rollup.js 781 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145
  1. /*
  2. @license
  3. Rollup.js v2.56.3
  4. Mon, 23 Aug 2021 05:06:39 GMT - commit c41d17ceedfa6c1d7430da70c6c80d86a91e9434
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. import { relative as relative$1, resolve, extname, basename, dirname } from 'path';
  9. import { createHash as createHash$1 } from 'crypto';
  10. import fs, { lstatSync, realpathSync, readdirSync } from 'fs';
  11. import { EventEmitter } from 'events';
  12. var version$1 = "2.56.3";
  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$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$1.original, loc, this$1$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$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$1.separator);
  999. }
  1000. var sourceIndex = source.filename ? this$1$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$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$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$1 = this;
  1095. var body = this.sources
  1096. .map(function (source, i) {
  1097. var separator = source.separator !== undefined ? source.separator : this$1$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. var MagicString$1 = MagicString;
  1149. function relative(from, to) {
  1150. const fromParts = from.split(/[/\\]/).filter(Boolean);
  1151. const toParts = to.split(/[/\\]/).filter(Boolean);
  1152. if (fromParts[0] === '.')
  1153. fromParts.shift();
  1154. if (toParts[0] === '.')
  1155. toParts.shift();
  1156. while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
  1157. fromParts.shift();
  1158. toParts.shift();
  1159. }
  1160. while (toParts[0] === '..' && fromParts.length > 0) {
  1161. toParts.shift();
  1162. fromParts.pop();
  1163. }
  1164. while (fromParts.pop()) {
  1165. toParts.unshift('..');
  1166. }
  1167. return toParts.join('/');
  1168. }
  1169. const RESERVED_NAMES = {
  1170. __proto__: null,
  1171. await: true,
  1172. break: true,
  1173. case: true,
  1174. catch: true,
  1175. class: true,
  1176. const: true,
  1177. continue: true,
  1178. debugger: true,
  1179. default: true,
  1180. delete: true,
  1181. do: true,
  1182. else: true,
  1183. enum: true,
  1184. eval: true,
  1185. export: true,
  1186. extends: true,
  1187. false: true,
  1188. finally: true,
  1189. for: true,
  1190. function: true,
  1191. if: true,
  1192. implements: true,
  1193. import: true,
  1194. in: true,
  1195. instanceof: true,
  1196. interface: true,
  1197. let: true,
  1198. new: true,
  1199. null: true,
  1200. package: true,
  1201. private: true,
  1202. protected: true,
  1203. public: true,
  1204. return: true,
  1205. static: true,
  1206. super: true,
  1207. switch: true,
  1208. this: true,
  1209. throw: true,
  1210. true: true,
  1211. try: true,
  1212. typeof: true,
  1213. undefined: true,
  1214. var: true,
  1215. void: true,
  1216. while: true,
  1217. with: true,
  1218. yield: true
  1219. };
  1220. function getOrCreate(map, key, init) {
  1221. const existing = map.get(key);
  1222. if (existing) {
  1223. return existing;
  1224. }
  1225. const value = init();
  1226. map.set(key, value);
  1227. return value;
  1228. }
  1229. const UnknownKey = Symbol('Unknown Key');
  1230. const UnknownInteger = Symbol('Unknown Integer');
  1231. const EMPTY_PATH = [];
  1232. const UNKNOWN_PATH = [UnknownKey];
  1233. const UNKNOWN_INTEGER_PATH = [UnknownInteger];
  1234. const EntitiesKey = Symbol('Entities');
  1235. class PathTracker {
  1236. constructor() {
  1237. this.entityPaths = Object.create(null, {
  1238. [EntitiesKey]: { value: new Set() }
  1239. });
  1240. }
  1241. trackEntityAtPathAndGetIfTracked(path, entity) {
  1242. const trackedEntities = this.getEntities(path);
  1243. if (trackedEntities.has(entity))
  1244. return true;
  1245. trackedEntities.add(entity);
  1246. return false;
  1247. }
  1248. withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
  1249. const trackedEntities = this.getEntities(path);
  1250. if (trackedEntities.has(entity))
  1251. return returnIfTracked;
  1252. trackedEntities.add(entity);
  1253. const result = onUntracked();
  1254. trackedEntities.delete(entity);
  1255. return result;
  1256. }
  1257. getEntities(path) {
  1258. let currentPaths = this.entityPaths;
  1259. for (const pathSegment of path) {
  1260. currentPaths = currentPaths[pathSegment] =
  1261. currentPaths[pathSegment] ||
  1262. Object.create(null, { [EntitiesKey]: { value: new Set() } });
  1263. }
  1264. return currentPaths[EntitiesKey];
  1265. }
  1266. }
  1267. const SHARED_RECURSION_TRACKER = new PathTracker();
  1268. class DiscriminatedPathTracker {
  1269. constructor() {
  1270. this.entityPaths = Object.create(null, {
  1271. [EntitiesKey]: { value: new Map() }
  1272. });
  1273. }
  1274. trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
  1275. let currentPaths = this.entityPaths;
  1276. for (const pathSegment of path) {
  1277. currentPaths = currentPaths[pathSegment] =
  1278. currentPaths[pathSegment] ||
  1279. Object.create(null, { [EntitiesKey]: { value: new Map() } });
  1280. }
  1281. const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, () => new Set());
  1282. if (trackedEntities.has(entity))
  1283. return true;
  1284. trackedEntities.add(entity);
  1285. return false;
  1286. }
  1287. }
  1288. const UnknownValue = Symbol('Unknown Value');
  1289. class ExpressionEntity {
  1290. constructor() {
  1291. this.included = false;
  1292. }
  1293. deoptimizePath(_path) { }
  1294. deoptimizeThisOnEventAtPath(_event, _path, thisParameter, _recursionTracker) {
  1295. thisParameter.deoptimizePath(UNKNOWN_PATH);
  1296. }
  1297. /**
  1298. * If possible it returns a stringifyable literal value for this node that can be used
  1299. * for inlining or comparing values.
  1300. * Otherwise it should return UnknownValue.
  1301. */
  1302. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  1303. return UnknownValue;
  1304. }
  1305. getReturnExpressionWhenCalledAtPath(_path, _callOptions, _recursionTracker, _origin) {
  1306. return UNKNOWN_EXPRESSION;
  1307. }
  1308. hasEffectsWhenAccessedAtPath(_path, _context) {
  1309. return true;
  1310. }
  1311. hasEffectsWhenAssignedAtPath(_path, _context) {
  1312. return true;
  1313. }
  1314. hasEffectsWhenCalledAtPath(_path, _callOptions, _context) {
  1315. return true;
  1316. }
  1317. include(_context, _includeChildrenRecursively) {
  1318. this.included = true;
  1319. }
  1320. includeCallArguments(context, args) {
  1321. for (const arg of args) {
  1322. arg.include(context, false);
  1323. }
  1324. }
  1325. }
  1326. const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
  1327. })();
  1328. class Variable extends ExpressionEntity {
  1329. constructor(name) {
  1330. super();
  1331. this.name = name;
  1332. this.alwaysRendered = false;
  1333. this.initReached = false;
  1334. this.isId = false;
  1335. this.isReassigned = false;
  1336. this.kind = null;
  1337. this.renderBaseName = null;
  1338. this.renderName = null;
  1339. }
  1340. /**
  1341. * Binds identifiers that reference this variable to this variable.
  1342. * Necessary to be able to change variable names.
  1343. */
  1344. addReference(_identifier) { }
  1345. getBaseVariableName() {
  1346. return this.renderBaseName || this.renderName || this.name;
  1347. }
  1348. getName() {
  1349. const name = this.renderName || this.name;
  1350. return this.renderBaseName
  1351. ? `${this.renderBaseName}${RESERVED_NAMES[name] ? `['${name}']` : `.${name}`}`
  1352. : name;
  1353. }
  1354. hasEffectsWhenAccessedAtPath(path, _context) {
  1355. return path.length > 0;
  1356. }
  1357. /**
  1358. * Marks this variable as being part of the bundle, which is usually the case when one of
  1359. * its identifiers becomes part of the bundle. Returns true if it has not been included
  1360. * previously.
  1361. * Once a variable is included, it should take care all its declarations are included.
  1362. */
  1363. include() {
  1364. this.included = true;
  1365. }
  1366. markCalledFromTryStatement() { }
  1367. setRenderNames(baseName, name) {
  1368. this.renderBaseName = baseName;
  1369. this.renderName = name;
  1370. }
  1371. }
  1372. class ExternalVariable extends Variable {
  1373. constructor(module, name) {
  1374. super(name);
  1375. this.module = module;
  1376. this.isNamespace = name === '*';
  1377. this.referenced = false;
  1378. }
  1379. addReference(identifier) {
  1380. this.referenced = true;
  1381. if (this.name === 'default' || this.name === '*') {
  1382. this.module.suggestName(identifier.name);
  1383. }
  1384. }
  1385. hasEffectsWhenAccessedAtPath(path) {
  1386. return path.length > (this.isNamespace ? 1 : 0);
  1387. }
  1388. include() {
  1389. if (!this.included) {
  1390. this.included = true;
  1391. this.module.used = true;
  1392. }
  1393. }
  1394. }
  1395. const BLANK = Object.freeze(Object.create(null));
  1396. const EMPTY_OBJECT = Object.freeze({});
  1397. const EMPTY_ARRAY = Object.freeze([]);
  1398. 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(' ');
  1399. 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(' ');
  1400. const blacklisted = new Set(reservedWords$1.concat(builtins$1));
  1401. const illegalCharacters = /[^$_a-zA-Z0-9]/g;
  1402. const startsWithDigit = (str) => /\d/.test(str[0]);
  1403. function isLegal(str) {
  1404. if (startsWithDigit(str) || blacklisted.has(str)) {
  1405. return false;
  1406. }
  1407. return !illegalCharacters.test(str);
  1408. }
  1409. function makeLegal(str) {
  1410. str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_');
  1411. if (startsWithDigit(str) || blacklisted.has(str))
  1412. str = `_${str}`;
  1413. return str || '_';
  1414. }
  1415. const absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
  1416. const relativePath = /^\.?\.\//;
  1417. function isAbsolute(path) {
  1418. return absolutePath.test(path);
  1419. }
  1420. function isRelative(path) {
  1421. return relativePath.test(path);
  1422. }
  1423. function normalize(path) {
  1424. if (path.indexOf('\\') == -1)
  1425. return path;
  1426. return path.replace(/\\/g, '/');
  1427. }
  1428. function printQuotedStringList(list, verbs) {
  1429. const isSingleItem = list.length <= 1;
  1430. const quotedList = list.map(item => `"${item}"`);
  1431. let output = isSingleItem
  1432. ? quotedList[0]
  1433. : `${quotedList.slice(0, -1).join(', ')} and ${quotedList.slice(-1)[0]}`;
  1434. if (verbs) {
  1435. output += ` ${isSingleItem ? verbs[0] : verbs[1]}`;
  1436. }
  1437. return output;
  1438. }
  1439. function getAliasName(id) {
  1440. const base = basename(id);
  1441. return base.substr(0, base.length - extname(id).length);
  1442. }
  1443. function relativeId(id) {
  1444. if (!isAbsolute(id))
  1445. return id;
  1446. return relative$1(resolve(), id);
  1447. }
  1448. function isPathFragment(name) {
  1449. // starting with "/", "./", "../", "C:/"
  1450. return (name[0] === '/' || (name[0] === '.' && (name[1] === '/' || name[1] === '.')) || isAbsolute(name));
  1451. }
  1452. class ExternalModule {
  1453. constructor(options, id, hasModuleSideEffects, meta, renormalizeRenderPath) {
  1454. this.options = options;
  1455. this.id = id;
  1456. this.renormalizeRenderPath = renormalizeRenderPath;
  1457. this.defaultVariableName = '';
  1458. this.dynamicImporters = [];
  1459. this.importers = [];
  1460. this.mostCommonSuggestion = 0;
  1461. this.namespaceVariableName = '';
  1462. this.reexported = false;
  1463. this.renderPath = undefined;
  1464. this.used = false;
  1465. this.variableName = '';
  1466. this.execIndex = Infinity;
  1467. this.suggestedVariableName = makeLegal(id.split(/[\\/]/).pop());
  1468. this.nameSuggestions = Object.create(null);
  1469. this.declarations = Object.create(null);
  1470. this.exportedVariables = new Map();
  1471. const { importers, dynamicImporters } = this;
  1472. this.info = {
  1473. ast: null,
  1474. code: null,
  1475. dynamicallyImportedIds: EMPTY_ARRAY,
  1476. get dynamicImporters() {
  1477. return dynamicImporters.sort();
  1478. },
  1479. hasModuleSideEffects,
  1480. id,
  1481. implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
  1482. implicitlyLoadedBefore: EMPTY_ARRAY,
  1483. importedIds: EMPTY_ARRAY,
  1484. get importers() {
  1485. return importers.sort();
  1486. },
  1487. isEntry: false,
  1488. isExternal: true,
  1489. meta,
  1490. syntheticNamedExports: false
  1491. };
  1492. }
  1493. getVariableForExportName(name) {
  1494. let declaration = this.declarations[name];
  1495. if (declaration)
  1496. return declaration;
  1497. this.declarations[name] = declaration = new ExternalVariable(this, name);
  1498. this.exportedVariables.set(declaration, name);
  1499. return declaration;
  1500. }
  1501. setRenderPath(options, inputBase) {
  1502. this.renderPath =
  1503. typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
  1504. if (!this.renderPath) {
  1505. this.renderPath = this.renormalizeRenderPath
  1506. ? normalize(relative$1(inputBase, this.id))
  1507. : this.id;
  1508. }
  1509. return this.renderPath;
  1510. }
  1511. suggestName(name) {
  1512. if (!this.nameSuggestions[name])
  1513. this.nameSuggestions[name] = 0;
  1514. this.nameSuggestions[name] += 1;
  1515. if (this.nameSuggestions[name] > this.mostCommonSuggestion) {
  1516. this.mostCommonSuggestion = this.nameSuggestions[name];
  1517. this.suggestedVariableName = name;
  1518. }
  1519. }
  1520. warnUnusedImports() {
  1521. const unused = Object.keys(this.declarations).filter(name => {
  1522. if (name === '*')
  1523. return false;
  1524. const declaration = this.declarations[name];
  1525. return !declaration.included && !this.reexported && !declaration.referenced;
  1526. });
  1527. if (unused.length === 0)
  1528. return;
  1529. const importersSet = new Set();
  1530. for (const name of unused) {
  1531. const { importers } = this.declarations[name].module;
  1532. for (const importer of importers) {
  1533. importersSet.add(importer);
  1534. }
  1535. }
  1536. const importersArray = [...importersSet];
  1537. this.options.onwarn({
  1538. code: 'UNUSED_EXTERNAL_IMPORT',
  1539. message: `${printQuotedStringList(unused, ['is', 'are'])} imported from external module "${this.id}" but never used in ${printQuotedStringList(importersArray.map(importer => relativeId(importer)))}.`,
  1540. names: unused,
  1541. source: this.id,
  1542. sources: importersArray
  1543. });
  1544. }
  1545. }
  1546. function getLocator(source, options) {
  1547. if (options === void 0) { options = {}; }
  1548. var offsetLine = options.offsetLine || 0;
  1549. var offsetColumn = options.offsetColumn || 0;
  1550. var originalLines = source.split('\n');
  1551. var start = 0;
  1552. var lineRanges = originalLines.map(function (line, i) {
  1553. var end = start + line.length + 1;
  1554. var range = { start: start, end: end, line: i };
  1555. start = end;
  1556. return range;
  1557. });
  1558. var i = 0;
  1559. function rangeContains(range, index) {
  1560. return range.start <= index && index < range.end;
  1561. }
  1562. function getLocation(range, index) {
  1563. return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
  1564. }
  1565. function locate(search, startIndex) {
  1566. if (typeof search === 'string') {
  1567. search = source.indexOf(search, startIndex || 0);
  1568. }
  1569. var range = lineRanges[i];
  1570. var d = search >= range.end ? 1 : -1;
  1571. while (range) {
  1572. if (rangeContains(range, search))
  1573. return getLocation(range, search);
  1574. i += d;
  1575. range = lineRanges[i];
  1576. }
  1577. }
  1578. return locate;
  1579. }
  1580. function locate(source, search, options) {
  1581. if (typeof options === 'number') {
  1582. throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
  1583. }
  1584. return getLocator(source, options)(search, options && options.startIndex);
  1585. }
  1586. const extractors = {
  1587. ArrayPattern(names, param) {
  1588. for (const element of param.elements) {
  1589. if (element)
  1590. extractors[element.type](names, element);
  1591. }
  1592. },
  1593. AssignmentPattern(names, param) {
  1594. extractors[param.left.type](names, param.left);
  1595. },
  1596. Identifier(names, param) {
  1597. names.push(param.name);
  1598. },
  1599. MemberExpression() { },
  1600. ObjectPattern(names, param) {
  1601. for (const prop of param.properties) {
  1602. if (prop.type === 'RestElement') {
  1603. extractors.RestElement(names, prop);
  1604. }
  1605. else {
  1606. extractors[prop.value.type](names, prop.value);
  1607. }
  1608. }
  1609. },
  1610. RestElement(names, param) {
  1611. extractors[param.argument.type](names, param.argument);
  1612. }
  1613. };
  1614. const extractAssignedNames = function extractAssignedNames(param) {
  1615. const names = [];
  1616. extractors[param.type](names, param);
  1617. return names;
  1618. };
  1619. const BROKEN_FLOW_NONE = 0;
  1620. const BROKEN_FLOW_BREAK_CONTINUE = 1;
  1621. const BROKEN_FLOW_ERROR_RETURN_LABEL = 2;
  1622. function createInclusionContext() {
  1623. return {
  1624. brokenFlow: BROKEN_FLOW_NONE,
  1625. includedCallArguments: new Set(),
  1626. includedLabels: new Set()
  1627. };
  1628. }
  1629. function createHasEffectsContext() {
  1630. return {
  1631. accessed: new PathTracker(),
  1632. assigned: new PathTracker(),
  1633. brokenFlow: BROKEN_FLOW_NONE,
  1634. called: new DiscriminatedPathTracker(),
  1635. ignore: {
  1636. breaks: false,
  1637. continues: false,
  1638. labels: new Set(),
  1639. returnYield: false
  1640. },
  1641. includedLabels: new Set(),
  1642. instantiated: new DiscriminatedPathTracker(),
  1643. replacedVariableInits: new Map()
  1644. };
  1645. }
  1646. // AST walker module for Mozilla Parser API compatible trees
  1647. function skipThrough(node, st, c) { c(node, st); }
  1648. function ignore(_node, _st, _c) {}
  1649. // Node walkers.
  1650. var base$1 = {};
  1651. base$1.Program = base$1.BlockStatement = function (node, st, c) {
  1652. for (var i = 0, list = node.body; i < list.length; i += 1)
  1653. {
  1654. var stmt = list[i];
  1655. c(stmt, st, "Statement");
  1656. }
  1657. };
  1658. base$1.Statement = skipThrough;
  1659. base$1.EmptyStatement = ignore;
  1660. base$1.ExpressionStatement = base$1.ParenthesizedExpression = base$1.ChainExpression =
  1661. function (node, st, c) { return c(node.expression, st, "Expression"); };
  1662. base$1.IfStatement = function (node, st, c) {
  1663. c(node.test, st, "Expression");
  1664. c(node.consequent, st, "Statement");
  1665. if (node.alternate) { c(node.alternate, st, "Statement"); }
  1666. };
  1667. base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
  1668. base$1.BreakStatement = base$1.ContinueStatement = ignore;
  1669. base$1.WithStatement = function (node, st, c) {
  1670. c(node.object, st, "Expression");
  1671. c(node.body, st, "Statement");
  1672. };
  1673. base$1.SwitchStatement = function (node, st, c) {
  1674. c(node.discriminant, st, "Expression");
  1675. for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
  1676. var cs = list$1[i$1];
  1677. if (cs.test) { c(cs.test, st, "Expression"); }
  1678. for (var i = 0, list = cs.consequent; i < list.length; i += 1)
  1679. {
  1680. var cons = list[i];
  1681. c(cons, st, "Statement");
  1682. }
  1683. }
  1684. };
  1685. base$1.SwitchCase = function (node, st, c) {
  1686. if (node.test) { c(node.test, st, "Expression"); }
  1687. for (var i = 0, list = node.consequent; i < list.length; i += 1)
  1688. {
  1689. var cons = list[i];
  1690. c(cons, st, "Statement");
  1691. }
  1692. };
  1693. base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
  1694. if (node.argument) { c(node.argument, st, "Expression"); }
  1695. };
  1696. base$1.ThrowStatement = base$1.SpreadElement =
  1697. function (node, st, c) { return c(node.argument, st, "Expression"); };
  1698. base$1.TryStatement = function (node, st, c) {
  1699. c(node.block, st, "Statement");
  1700. if (node.handler) { c(node.handler, st); }
  1701. if (node.finalizer) { c(node.finalizer, st, "Statement"); }
  1702. };
  1703. base$1.CatchClause = function (node, st, c) {
  1704. if (node.param) { c(node.param, st, "Pattern"); }
  1705. c(node.body, st, "Statement");
  1706. };
  1707. base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
  1708. c(node.test, st, "Expression");
  1709. c(node.body, st, "Statement");
  1710. };
  1711. base$1.ForStatement = function (node, st, c) {
  1712. if (node.init) { c(node.init, st, "ForInit"); }
  1713. if (node.test) { c(node.test, st, "Expression"); }
  1714. if (node.update) { c(node.update, st, "Expression"); }
  1715. c(node.body, st, "Statement");
  1716. };
  1717. base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
  1718. c(node.left, st, "ForInit");
  1719. c(node.right, st, "Expression");
  1720. c(node.body, st, "Statement");
  1721. };
  1722. base$1.ForInit = function (node, st, c) {
  1723. if (node.type === "VariableDeclaration") { c(node, st); }
  1724. else { c(node, st, "Expression"); }
  1725. };
  1726. base$1.DebuggerStatement = ignore;
  1727. base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
  1728. base$1.VariableDeclaration = function (node, st, c) {
  1729. for (var i = 0, list = node.declarations; i < list.length; i += 1)
  1730. {
  1731. var decl = list[i];
  1732. c(decl, st);
  1733. }
  1734. };
  1735. base$1.VariableDeclarator = function (node, st, c) {
  1736. c(node.id, st, "Pattern");
  1737. if (node.init) { c(node.init, st, "Expression"); }
  1738. };
  1739. base$1.Function = function (node, st, c) {
  1740. if (node.id) { c(node.id, st, "Pattern"); }
  1741. for (var i = 0, list = node.params; i < list.length; i += 1)
  1742. {
  1743. var param = list[i];
  1744. c(param, st, "Pattern");
  1745. }
  1746. c(node.body, st, node.expression ? "Expression" : "Statement");
  1747. };
  1748. base$1.Pattern = function (node, st, c) {
  1749. if (node.type === "Identifier")
  1750. { c(node, st, "VariablePattern"); }
  1751. else if (node.type === "MemberExpression")
  1752. { c(node, st, "MemberPattern"); }
  1753. else
  1754. { c(node, st); }
  1755. };
  1756. base$1.VariablePattern = ignore;
  1757. base$1.MemberPattern = skipThrough;
  1758. base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
  1759. base$1.ArrayPattern = function (node, st, c) {
  1760. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  1761. var elt = list[i];
  1762. if (elt) { c(elt, st, "Pattern"); }
  1763. }
  1764. };
  1765. base$1.ObjectPattern = function (node, st, c) {
  1766. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  1767. var prop = list[i];
  1768. if (prop.type === "Property") {
  1769. if (prop.computed) { c(prop.key, st, "Expression"); }
  1770. c(prop.value, st, "Pattern");
  1771. } else if (prop.type === "RestElement") {
  1772. c(prop.argument, st, "Pattern");
  1773. }
  1774. }
  1775. };
  1776. base$1.Expression = skipThrough;
  1777. base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
  1778. base$1.ArrayExpression = function (node, st, c) {
  1779. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  1780. var elt = list[i];
  1781. if (elt) { c(elt, st, "Expression"); }
  1782. }
  1783. };
  1784. base$1.ObjectExpression = function (node, st, c) {
  1785. for (var i = 0, list = node.properties; i < list.length; i += 1)
  1786. {
  1787. var prop = list[i];
  1788. c(prop, st);
  1789. }
  1790. };
  1791. base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
  1792. base$1.SequenceExpression = function (node, st, c) {
  1793. for (var i = 0, list = node.expressions; i < list.length; i += 1)
  1794. {
  1795. var expr = list[i];
  1796. c(expr, st, "Expression");
  1797. }
  1798. };
  1799. base$1.TemplateLiteral = function (node, st, c) {
  1800. for (var i = 0, list = node.quasis; i < list.length; i += 1)
  1801. {
  1802. var quasi = list[i];
  1803. c(quasi, st);
  1804. }
  1805. for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
  1806. {
  1807. var expr = list$1[i$1];
  1808. c(expr, st, "Expression");
  1809. }
  1810. };
  1811. base$1.TemplateElement = ignore;
  1812. base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
  1813. c(node.argument, st, "Expression");
  1814. };
  1815. base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
  1816. c(node.left, st, "Expression");
  1817. c(node.right, st, "Expression");
  1818. };
  1819. base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
  1820. c(node.left, st, "Pattern");
  1821. c(node.right, st, "Expression");
  1822. };
  1823. base$1.ConditionalExpression = function (node, st, c) {
  1824. c(node.test, st, "Expression");
  1825. c(node.consequent, st, "Expression");
  1826. c(node.alternate, st, "Expression");
  1827. };
  1828. base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
  1829. c(node.callee, st, "Expression");
  1830. if (node.arguments)
  1831. { for (var i = 0, list = node.arguments; i < list.length; i += 1)
  1832. {
  1833. var arg = list[i];
  1834. c(arg, st, "Expression");
  1835. } }
  1836. };
  1837. base$1.MemberExpression = function (node, st, c) {
  1838. c(node.object, st, "Expression");
  1839. if (node.computed) { c(node.property, st, "Expression"); }
  1840. };
  1841. base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
  1842. if (node.declaration)
  1843. { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
  1844. if (node.source) { c(node.source, st, "Expression"); }
  1845. };
  1846. base$1.ExportAllDeclaration = function (node, st, c) {
  1847. if (node.exported)
  1848. { c(node.exported, st); }
  1849. c(node.source, st, "Expression");
  1850. };
  1851. base$1.ImportDeclaration = function (node, st, c) {
  1852. for (var i = 0, list = node.specifiers; i < list.length; i += 1)
  1853. {
  1854. var spec = list[i];
  1855. c(spec, st);
  1856. }
  1857. c(node.source, st, "Expression");
  1858. };
  1859. base$1.ImportExpression = function (node, st, c) {
  1860. c(node.source, st, "Expression");
  1861. };
  1862. base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.PrivateIdentifier = base$1.Literal = ignore;
  1863. base$1.TaggedTemplateExpression = function (node, st, c) {
  1864. c(node.tag, st, "Expression");
  1865. c(node.quasi, st, "Expression");
  1866. };
  1867. base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
  1868. base$1.Class = function (node, st, c) {
  1869. if (node.id) { c(node.id, st, "Pattern"); }
  1870. if (node.superClass) { c(node.superClass, st, "Expression"); }
  1871. c(node.body, st);
  1872. };
  1873. base$1.ClassBody = function (node, st, c) {
  1874. for (var i = 0, list = node.body; i < list.length; i += 1)
  1875. {
  1876. var elt = list[i];
  1877. c(elt, st);
  1878. }
  1879. };
  1880. base$1.MethodDefinition = base$1.PropertyDefinition = base$1.Property = function (node, st, c) {
  1881. if (node.computed) { c(node.key, st, "Expression"); }
  1882. if (node.value) { c(node.value, st, "Expression"); }
  1883. };
  1884. const ArrowFunctionExpression$1 = 'ArrowFunctionExpression';
  1885. const BinaryExpression$1 = 'BinaryExpression';
  1886. const BlockStatement$1 = 'BlockStatement';
  1887. const CallExpression$1 = 'CallExpression';
  1888. const ChainExpression$1 = 'ChainExpression';
  1889. const ConditionalExpression$1 = 'ConditionalExpression';
  1890. const ExpressionStatement$1 = 'ExpressionStatement';
  1891. const Identifier$1 = 'Identifier';
  1892. const ImportDefaultSpecifier$1 = 'ImportDefaultSpecifier';
  1893. const ImportNamespaceSpecifier$1 = 'ImportNamespaceSpecifier';
  1894. const LogicalExpression$1 = 'LogicalExpression';
  1895. const NewExpression$1 = 'NewExpression';
  1896. const Program$1 = 'Program';
  1897. const Property$1 = 'Property';
  1898. const ReturnStatement$1 = 'ReturnStatement';
  1899. const SequenceExpression$1 = 'SequenceExpression';
  1900. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  1901. // this for an actual sourceMappingURL
  1902. let SOURCEMAPPING_URL = 'sourceMa';
  1903. SOURCEMAPPING_URL += 'ppingURL';
  1904. const whiteSpaceNoNewline = '[ \\f\\r\\t\\v\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]';
  1905. const SOURCEMAPPING_URL_RE = new RegExp(`^#${whiteSpaceNoNewline}+${SOURCEMAPPING_URL}=.+`);
  1906. // patch up acorn-walk until class-fields are officially supported
  1907. base$1.PropertyDefinition = function (node, st, c) {
  1908. if (node.computed) {
  1909. c(node.key, st, 'Expression');
  1910. }
  1911. if (node.value) {
  1912. c(node.value, st, 'Expression');
  1913. }
  1914. };
  1915. const ANNOTATION_KEY = '_rollupAnnotations';
  1916. const INVALID_COMMENT_KEY = '_rollupRemoved';
  1917. function handlePureAnnotationsOfNode(node, state, type = node.type) {
  1918. const { annotations } = state;
  1919. let comment = annotations[state.annotationIndex];
  1920. while (comment && node.start >= comment.end) {
  1921. markPureNode(node, comment, state.code);
  1922. comment = annotations[++state.annotationIndex];
  1923. }
  1924. if (comment && comment.end <= node.end) {
  1925. base$1[type](node, state, handlePureAnnotationsOfNode);
  1926. while ((comment = annotations[state.annotationIndex]) && comment.end <= node.end) {
  1927. ++state.annotationIndex;
  1928. annotateNode(node, comment, false);
  1929. }
  1930. }
  1931. }
  1932. const neitherWithespaceNorBrackets = /[^\s(]/g;
  1933. const noWhitespace = /\S/g;
  1934. function markPureNode(node, comment, code) {
  1935. const annotatedNodes = [];
  1936. let invalidAnnotation;
  1937. const codeInBetween = code.slice(comment.end, node.start);
  1938. if (doesNotMatchOutsideComment(codeInBetween, neitherWithespaceNorBrackets)) {
  1939. const parentStart = node.start;
  1940. while (true) {
  1941. annotatedNodes.push(node);
  1942. switch (node.type) {
  1943. case ExpressionStatement$1:
  1944. case ChainExpression$1:
  1945. node = node.expression;
  1946. continue;
  1947. case SequenceExpression$1:
  1948. // if there are parentheses, the annotation would apply to the entire expression
  1949. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  1950. node = node.expressions[0];
  1951. continue;
  1952. }
  1953. invalidAnnotation = true;
  1954. break;
  1955. case ConditionalExpression$1:
  1956. // if there are parentheses, the annotation would apply to the entire expression
  1957. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  1958. node = node.test;
  1959. continue;
  1960. }
  1961. invalidAnnotation = true;
  1962. break;
  1963. case LogicalExpression$1:
  1964. case BinaryExpression$1:
  1965. // if there are parentheses, the annotation would apply to the entire expression
  1966. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  1967. node = node.left;
  1968. continue;
  1969. }
  1970. invalidAnnotation = true;
  1971. break;
  1972. case CallExpression$1:
  1973. case NewExpression$1:
  1974. break;
  1975. default:
  1976. invalidAnnotation = true;
  1977. }
  1978. break;
  1979. }
  1980. }
  1981. else {
  1982. invalidAnnotation = true;
  1983. }
  1984. if (invalidAnnotation) {
  1985. annotateNode(node, comment, false);
  1986. }
  1987. else {
  1988. for (const node of annotatedNodes) {
  1989. annotateNode(node, comment, true);
  1990. }
  1991. }
  1992. }
  1993. function doesNotMatchOutsideComment(code, forbiddenChars) {
  1994. let nextMatch;
  1995. while ((nextMatch = forbiddenChars.exec(code)) !== null) {
  1996. if (nextMatch[0] === '/') {
  1997. const charCodeAfterSlash = code.charCodeAt(forbiddenChars.lastIndex);
  1998. if (charCodeAfterSlash === 42 /*"*"*/) {
  1999. forbiddenChars.lastIndex = code.indexOf('*/', forbiddenChars.lastIndex + 1) + 2;
  2000. continue;
  2001. }
  2002. else if (charCodeAfterSlash === 47 /*"/"*/) {
  2003. forbiddenChars.lastIndex = code.indexOf('\n', forbiddenChars.lastIndex + 1) + 1;
  2004. continue;
  2005. }
  2006. }
  2007. forbiddenChars.lastIndex = 0;
  2008. return false;
  2009. }
  2010. return true;
  2011. }
  2012. const pureCommentRegex = /[@#]__PURE__/;
  2013. function addAnnotations(comments, esTreeAst, code) {
  2014. const annotations = [];
  2015. const sourceMappingComments = [];
  2016. for (const comment of comments) {
  2017. if (pureCommentRegex.test(comment.value)) {
  2018. annotations.push(comment);
  2019. }
  2020. else if (SOURCEMAPPING_URL_RE.test(comment.value)) {
  2021. sourceMappingComments.push(comment);
  2022. }
  2023. }
  2024. for (const comment of sourceMappingComments) {
  2025. annotateNode(esTreeAst, comment, false);
  2026. }
  2027. handlePureAnnotationsOfNode(esTreeAst, {
  2028. annotationIndex: 0,
  2029. annotations,
  2030. code
  2031. });
  2032. }
  2033. function annotateNode(node, comment, valid) {
  2034. const key = valid ? ANNOTATION_KEY : INVALID_COMMENT_KEY;
  2035. const property = node[key];
  2036. if (property) {
  2037. property.push(comment);
  2038. }
  2039. else {
  2040. node[key] = [comment];
  2041. }
  2042. }
  2043. const keys = {
  2044. Literal: [],
  2045. Program: ['body']
  2046. };
  2047. function getAndCreateKeys(esTreeNode) {
  2048. keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
  2049. return keys[esTreeNode.type];
  2050. }
  2051. const INCLUDE_PARAMETERS = 'variables';
  2052. class NodeBase extends ExpressionEntity {
  2053. constructor(esTreeNode, parent, parentScope) {
  2054. super();
  2055. this.esTreeNode = esTreeNode;
  2056. this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
  2057. this.parent = parent;
  2058. this.context = parent.context;
  2059. this.createScope(parentScope);
  2060. this.parseNode(esTreeNode);
  2061. this.initialise();
  2062. this.context.magicString.addSourcemapLocation(this.start);
  2063. this.context.magicString.addSourcemapLocation(this.end);
  2064. }
  2065. addExportedVariables(_variables, _exportNamesByVariable) { }
  2066. /**
  2067. * Override this to bind assignments to variables and do any initialisations that
  2068. * require the scopes to be populated with variables.
  2069. */
  2070. bind() {
  2071. for (const key of this.keys) {
  2072. const value = this[key];
  2073. if (value === null)
  2074. continue;
  2075. if (Array.isArray(value)) {
  2076. for (const child of value) {
  2077. if (child !== null)
  2078. child.bind();
  2079. }
  2080. }
  2081. else {
  2082. value.bind();
  2083. }
  2084. }
  2085. }
  2086. /**
  2087. * Override if this node should receive a different scope than the parent scope.
  2088. */
  2089. createScope(parentScope) {
  2090. this.scope = parentScope;
  2091. }
  2092. hasEffects(context) {
  2093. if (this.deoptimized === false)
  2094. this.applyDeoptimizations();
  2095. for (const key of this.keys) {
  2096. const value = this[key];
  2097. if (value === null)
  2098. continue;
  2099. if (Array.isArray(value)) {
  2100. for (const child of value) {
  2101. if (child !== null && child.hasEffects(context))
  2102. return true;
  2103. }
  2104. }
  2105. else if (value.hasEffects(context))
  2106. return true;
  2107. }
  2108. return false;
  2109. }
  2110. include(context, includeChildrenRecursively) {
  2111. if (this.deoptimized === false)
  2112. this.applyDeoptimizations();
  2113. this.included = true;
  2114. for (const key of this.keys) {
  2115. const value = this[key];
  2116. if (value === null)
  2117. continue;
  2118. if (Array.isArray(value)) {
  2119. for (const child of value) {
  2120. if (child !== null)
  2121. child.include(context, includeChildrenRecursively);
  2122. }
  2123. }
  2124. else {
  2125. value.include(context, includeChildrenRecursively);
  2126. }
  2127. }
  2128. }
  2129. includeAsSingleStatement(context, includeChildrenRecursively) {
  2130. this.include(context, includeChildrenRecursively);
  2131. }
  2132. /**
  2133. * Override to perform special initialisation steps after the scope is initialised
  2134. */
  2135. initialise() { }
  2136. insertSemicolon(code) {
  2137. if (code.original[this.end - 1] !== ';') {
  2138. code.appendLeft(this.end, ';');
  2139. }
  2140. }
  2141. parseNode(esTreeNode) {
  2142. for (const [key, value] of Object.entries(esTreeNode)) {
  2143. // That way, we can override this function to add custom initialisation and then call super.parseNode
  2144. if (this.hasOwnProperty(key))
  2145. continue;
  2146. if (key.charCodeAt(0) === 95 /* _ */) {
  2147. if (key === ANNOTATION_KEY) {
  2148. this.annotations = value;
  2149. }
  2150. else if (key === INVALID_COMMENT_KEY) {
  2151. for (const { start, end } of value)
  2152. this.context.magicString.remove(start, end);
  2153. }
  2154. }
  2155. else if (typeof value !== 'object' || value === null) {
  2156. this[key] = value;
  2157. }
  2158. else if (Array.isArray(value)) {
  2159. this[key] = [];
  2160. for (const child of value) {
  2161. this[key].push(child === null
  2162. ? null
  2163. : new (this.context.nodeConstructors[child.type] ||
  2164. this.context.nodeConstructors.UnknownNode)(child, this, this.scope));
  2165. }
  2166. }
  2167. else {
  2168. this[key] = new (this.context.nodeConstructors[value.type] ||
  2169. this.context.nodeConstructors.UnknownNode)(value, this, this.scope);
  2170. }
  2171. }
  2172. }
  2173. render(code, options) {
  2174. for (const key of this.keys) {
  2175. const value = this[key];
  2176. if (value === null)
  2177. continue;
  2178. if (Array.isArray(value)) {
  2179. for (const child of value) {
  2180. if (child !== null)
  2181. child.render(code, options);
  2182. }
  2183. }
  2184. else {
  2185. value.render(code, options);
  2186. }
  2187. }
  2188. }
  2189. shouldBeIncluded(context) {
  2190. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  2191. }
  2192. applyDeoptimizations() { }
  2193. }
  2194. class ExportAllDeclaration extends NodeBase {
  2195. hasEffects() {
  2196. return false;
  2197. }
  2198. initialise() {
  2199. this.context.addExport(this);
  2200. }
  2201. render(code, _options, nodeRenderOptions) {
  2202. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  2203. }
  2204. }
  2205. ExportAllDeclaration.prototype.needsBoundaries = true;
  2206. function treeshakeNode(node, code, start, end) {
  2207. code.remove(start, end);
  2208. if (node.annotations) {
  2209. for (const annotation of node.annotations) {
  2210. if (annotation.start < start) {
  2211. code.remove(annotation.start, annotation.end);
  2212. }
  2213. else {
  2214. return;
  2215. }
  2216. }
  2217. }
  2218. }
  2219. function removeAnnotations(node, code) {
  2220. if (!node.annotations && node.parent.type === ExpressionStatement$1) {
  2221. node = node.parent;
  2222. }
  2223. if (node.annotations) {
  2224. for (const annotation of node.annotations) {
  2225. code.remove(annotation.start, annotation.end);
  2226. }
  2227. }
  2228. }
  2229. const NO_SEMICOLON = { isNoStatement: true };
  2230. // This assumes there are only white-space and comments between start and the string we are looking for
  2231. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  2232. let searchPos, charCodeAfterSlash;
  2233. searchPos = code.indexOf(searchString, start);
  2234. while (true) {
  2235. start = code.indexOf('/', start);
  2236. if (start === -1 || start >= searchPos)
  2237. return searchPos;
  2238. charCodeAfterSlash = code.charCodeAt(++start);
  2239. ++start;
  2240. // With our assumption, '/' always starts a comment. Determine comment type:
  2241. start =
  2242. charCodeAfterSlash === 47 /*"/"*/
  2243. ? code.indexOf('\n', start) + 1
  2244. : code.indexOf('*/', start) + 2;
  2245. if (start > searchPos) {
  2246. searchPos = code.indexOf(searchString, start);
  2247. }
  2248. }
  2249. }
  2250. const NON_WHITESPACE = /\S/g;
  2251. function findNonWhiteSpace(code, index) {
  2252. NON_WHITESPACE.lastIndex = index;
  2253. const result = NON_WHITESPACE.exec(code);
  2254. return result.index;
  2255. }
  2256. // This assumes "code" only contains white-space and comments
  2257. // Returns position of line-comment if applicable
  2258. function findFirstLineBreakOutsideComment(code) {
  2259. let lineBreakPos, charCodeAfterSlash, start = 0;
  2260. lineBreakPos = code.indexOf('\n', start);
  2261. while (true) {
  2262. start = code.indexOf('/', start);
  2263. if (start === -1 || start > lineBreakPos)
  2264. return [lineBreakPos, lineBreakPos + 1];
  2265. // With our assumption, '/' always starts a comment. Determine comment type:
  2266. charCodeAfterSlash = code.charCodeAt(start + 1);
  2267. if (charCodeAfterSlash === 47 /*"/"*/)
  2268. return [start, lineBreakPos + 1];
  2269. start = code.indexOf('*/', start + 3) + 2;
  2270. if (start > lineBreakPos) {
  2271. lineBreakPos = code.indexOf('\n', start);
  2272. }
  2273. }
  2274. }
  2275. function renderStatementList(statements, code, start, end, options) {
  2276. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  2277. let nextNode = statements[0];
  2278. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  2279. if (nextNodeNeedsBoundaries) {
  2280. nextNodeStart =
  2281. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
  2282. }
  2283. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  2284. currentNode = nextNode;
  2285. currentNodeStart = nextNodeStart;
  2286. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  2287. nextNode = statements[nextIndex];
  2288. nextNodeNeedsBoundaries =
  2289. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  2290. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  2291. nextNodeStart =
  2292. currentNode.end +
  2293. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
  2294. if (currentNode.included) {
  2295. currentNodeNeedsBoundaries
  2296. ? currentNode.render(code, options, {
  2297. end: nextNodeStart,
  2298. start: currentNodeStart
  2299. })
  2300. : currentNode.render(code, options);
  2301. }
  2302. else {
  2303. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  2304. }
  2305. }
  2306. else {
  2307. currentNode.render(code, options);
  2308. }
  2309. }
  2310. }
  2311. // This assumes that the first character is not part of the first node
  2312. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  2313. const splitUpNodes = [];
  2314. let node, nextNode, nextNodeStart, contentEnd, char;
  2315. let separator = start - 1;
  2316. for (let nextIndex = 0; nextIndex < nodes.length; nextIndex++) {
  2317. nextNode = nodes[nextIndex];
  2318. if (node !== undefined) {
  2319. separator =
  2320. node.end +
  2321. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  2322. }
  2323. nextNodeStart = contentEnd =
  2324. separator +
  2325. 1 +
  2326. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
  2327. while (((char = code.original.charCodeAt(nextNodeStart)),
  2328. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  2329. nextNodeStart++;
  2330. if (node !== undefined) {
  2331. splitUpNodes.push({
  2332. contentEnd,
  2333. end: nextNodeStart,
  2334. node,
  2335. separator,
  2336. start
  2337. });
  2338. }
  2339. node = nextNode;
  2340. start = nextNodeStart;
  2341. }
  2342. splitUpNodes.push({
  2343. contentEnd: end,
  2344. end,
  2345. node: node,
  2346. separator: null,
  2347. start
  2348. });
  2349. return splitUpNodes;
  2350. }
  2351. // This assumes there are only white-space and comments between start and end
  2352. function removeLineBreaks(code, start, end) {
  2353. while (true) {
  2354. const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  2355. if (removeStart === -1) {
  2356. break;
  2357. }
  2358. code.remove(start + removeStart, (start += removeEnd));
  2359. }
  2360. }
  2361. function getSystemExportStatement(exportedVariables, { compact, exportNamesByVariable }, modifier = '') {
  2362. const _ = compact ? '' : ' ';
  2363. if (exportedVariables.length === 1 &&
  2364. exportNamesByVariable.get(exportedVariables[0]).length === 1) {
  2365. const variable = exportedVariables[0];
  2366. return `exports('${exportNamesByVariable.get(variable)}',${_}${variable.getName()}${modifier})`;
  2367. }
  2368. else {
  2369. return `exports({${_}${exportedVariables
  2370. .map(variable => {
  2371. return exportNamesByVariable
  2372. .get(variable)
  2373. .map(exportName => `${exportName}:${_}${variable.getName()}${modifier}`)
  2374. .join(`,${_}`);
  2375. })
  2376. .join(`,${_}`)}${_}})`;
  2377. }
  2378. }
  2379. function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { compact, exportNamesByVariable }) {
  2380. const _ = compact ? '' : ' ';
  2381. code.prependRight(expressionStart, `exports('${exportNamesByVariable.get(exportedVariable)}',${_}`);
  2382. code.appendLeft(expressionEnd, ')');
  2383. }
  2384. function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
  2385. const _ = options.compact ? '' : ' ';
  2386. const s = options.compact ? '' : ';';
  2387. code.prependRight(expressionStart, `function${_}(v)${_}{${_}return ${getSystemExportStatement(exportedVariables, options)},${_}v${s}${_}}(`);
  2388. code.appendLeft(expressionEnd, ')');
  2389. if (needsParens) {
  2390. code.prependRight(expressionStart, '(');
  2391. code.appendLeft(expressionEnd, ')');
  2392. }
  2393. }
  2394. function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
  2395. const _ = options.compact ? '' : ' ';
  2396. code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName()}`);
  2397. if (needsParens) {
  2398. code.prependRight(expressionStart, '(');
  2399. code.appendLeft(expressionEnd, ')');
  2400. }
  2401. }
  2402. function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
  2403. const _ = options.compact ? '' : ' ';
  2404. code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
  2405. if (needsParens) {
  2406. code.prependRight(expressionStart, '(');
  2407. code.appendLeft(expressionEnd, ')');
  2408. }
  2409. }
  2410. const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  2411. const base = 64;
  2412. function toBase64(num) {
  2413. let outStr = '';
  2414. do {
  2415. const curDigit = num % base;
  2416. num = Math.floor(num / base);
  2417. outStr = chars[curDigit] + outStr;
  2418. } while (num !== 0);
  2419. return outStr;
  2420. }
  2421. function getSafeName(baseName, usedNames) {
  2422. let safeName = baseName;
  2423. let count = 1;
  2424. while (usedNames.has(safeName) || RESERVED_NAMES[safeName]) {
  2425. safeName = `${baseName}$${toBase64(count++)}`;
  2426. }
  2427. usedNames.add(safeName);
  2428. return safeName;
  2429. }
  2430. const NO_ARGS = [];
  2431. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  2432. return Object.create(inheritedDescriptions, memberDescriptions);
  2433. }
  2434. const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
  2435. getLiteralValueAtPath() {
  2436. return undefined;
  2437. }
  2438. })();
  2439. const returnsUnknown = {
  2440. value: {
  2441. callsArgs: null,
  2442. returns: UNKNOWN_EXPRESSION
  2443. }
  2444. };
  2445. const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
  2446. getReturnExpressionWhenCalledAtPath(path) {
  2447. if (path.length === 1) {
  2448. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  2449. }
  2450. return UNKNOWN_EXPRESSION;
  2451. }
  2452. hasEffectsWhenAccessedAtPath(path) {
  2453. return path.length > 1;
  2454. }
  2455. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  2456. if (path.length === 1) {
  2457. return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], callOptions, context);
  2458. }
  2459. return true;
  2460. }
  2461. })();
  2462. const returnsBoolean = {
  2463. value: {
  2464. callsArgs: null,
  2465. returns: UNKNOWN_LITERAL_BOOLEAN
  2466. }
  2467. };
  2468. const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
  2469. getReturnExpressionWhenCalledAtPath(path) {
  2470. if (path.length === 1) {
  2471. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  2472. }
  2473. return UNKNOWN_EXPRESSION;
  2474. }
  2475. hasEffectsWhenAccessedAtPath(path) {
  2476. return path.length > 1;
  2477. }
  2478. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  2479. if (path.length === 1) {
  2480. return hasMemberEffectWhenCalled(literalNumberMembers, path[0], callOptions, context);
  2481. }
  2482. return true;
  2483. }
  2484. })();
  2485. const returnsNumber = {
  2486. value: {
  2487. callsArgs: null,
  2488. returns: UNKNOWN_LITERAL_NUMBER
  2489. }
  2490. };
  2491. const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
  2492. getReturnExpressionWhenCalledAtPath(path) {
  2493. if (path.length === 1) {
  2494. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  2495. }
  2496. return UNKNOWN_EXPRESSION;
  2497. }
  2498. hasEffectsWhenAccessedAtPath(path) {
  2499. return path.length > 1;
  2500. }
  2501. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  2502. if (path.length === 1) {
  2503. return hasMemberEffectWhenCalled(literalStringMembers, path[0], callOptions, context);
  2504. }
  2505. return true;
  2506. }
  2507. })();
  2508. const returnsString = {
  2509. value: {
  2510. callsArgs: null,
  2511. returns: UNKNOWN_LITERAL_STRING
  2512. }
  2513. };
  2514. const objectMembers = assembleMemberDescriptions({
  2515. hasOwnProperty: returnsBoolean,
  2516. isPrototypeOf: returnsBoolean,
  2517. propertyIsEnumerable: returnsBoolean,
  2518. toLocaleString: returnsString,
  2519. toString: returnsString,
  2520. valueOf: returnsUnknown
  2521. });
  2522. const literalBooleanMembers = assembleMemberDescriptions({
  2523. valueOf: returnsBoolean
  2524. }, objectMembers);
  2525. const literalNumberMembers = assembleMemberDescriptions({
  2526. toExponential: returnsString,
  2527. toFixed: returnsString,
  2528. toLocaleString: returnsString,
  2529. toPrecision: returnsString,
  2530. valueOf: returnsNumber
  2531. }, objectMembers);
  2532. const literalStringMembers = assembleMemberDescriptions({
  2533. charAt: returnsString,
  2534. charCodeAt: returnsNumber,
  2535. codePointAt: returnsNumber,
  2536. concat: returnsString,
  2537. endsWith: returnsBoolean,
  2538. includes: returnsBoolean,
  2539. indexOf: returnsNumber,
  2540. lastIndexOf: returnsNumber,
  2541. localeCompare: returnsNumber,
  2542. match: returnsBoolean,
  2543. normalize: returnsString,
  2544. padEnd: returnsString,
  2545. padStart: returnsString,
  2546. repeat: returnsString,
  2547. replace: {
  2548. value: {
  2549. callsArgs: [1],
  2550. returns: UNKNOWN_LITERAL_STRING
  2551. }
  2552. },
  2553. search: returnsNumber,
  2554. slice: returnsString,
  2555. split: returnsUnknown,
  2556. startsWith: returnsBoolean,
  2557. substr: returnsString,
  2558. substring: returnsString,
  2559. toLocaleLowerCase: returnsString,
  2560. toLocaleUpperCase: returnsString,
  2561. toLowerCase: returnsString,
  2562. toUpperCase: returnsString,
  2563. trim: returnsString,
  2564. valueOf: returnsString
  2565. }, objectMembers);
  2566. function getLiteralMembersForValue(value) {
  2567. switch (typeof value) {
  2568. case 'boolean':
  2569. return literalBooleanMembers;
  2570. case 'number':
  2571. return literalNumberMembers;
  2572. case 'string':
  2573. return literalStringMembers;
  2574. default:
  2575. return Object.create(null);
  2576. }
  2577. }
  2578. function hasMemberEffectWhenCalled(members, memberName, callOptions, context) {
  2579. if (typeof memberName !== 'string' || !members[memberName]) {
  2580. return true;
  2581. }
  2582. if (!members[memberName].callsArgs)
  2583. return false;
  2584. for (const argIndex of members[memberName].callsArgs) {
  2585. if (callOptions.args[argIndex] &&
  2586. callOptions.args[argIndex].hasEffectsWhenCalledAtPath(EMPTY_PATH, {
  2587. args: NO_ARGS,
  2588. thisParam: null,
  2589. withNew: false
  2590. }, context))
  2591. return true;
  2592. }
  2593. return false;
  2594. }
  2595. function getMemberReturnExpressionWhenCalled(members, memberName) {
  2596. if (typeof memberName !== 'string' || !members[memberName])
  2597. return UNKNOWN_EXPRESSION;
  2598. return members[memberName].returns;
  2599. }
  2600. class LocalVariable extends Variable {
  2601. constructor(name, declarator, init, context) {
  2602. super(name);
  2603. this.calledFromTryStatement = false;
  2604. this.additionalInitializers = null;
  2605. this.expressionsToBeDeoptimized = [];
  2606. this.declarations = declarator ? [declarator] : [];
  2607. this.init = init;
  2608. this.deoptimizationTracker = context.deoptimizationTracker;
  2609. this.module = context.module;
  2610. }
  2611. addDeclaration(identifier, init) {
  2612. this.declarations.push(identifier);
  2613. const additionalInitializers = this.markInitializersForDeoptimization();
  2614. if (init !== null) {
  2615. additionalInitializers.push(init);
  2616. }
  2617. }
  2618. consolidateInitializers() {
  2619. if (this.additionalInitializers !== null) {
  2620. for (const initializer of this.additionalInitializers) {
  2621. initializer.deoptimizePath(UNKNOWN_PATH);
  2622. }
  2623. this.additionalInitializers = null;
  2624. }
  2625. }
  2626. deoptimizePath(path) {
  2627. var _a, _b;
  2628. if (this.isReassigned ||
  2629. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  2630. return;
  2631. }
  2632. if (path.length === 0) {
  2633. if (!this.isReassigned) {
  2634. this.isReassigned = true;
  2635. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  2636. this.expressionsToBeDeoptimized = [];
  2637. for (const expression of expressionsToBeDeoptimized) {
  2638. expression.deoptimizeCache();
  2639. }
  2640. (_a = this.init) === null || _a === void 0 ? void 0 : _a.deoptimizePath(UNKNOWN_PATH);
  2641. }
  2642. }
  2643. else {
  2644. (_b = this.init) === null || _b === void 0 ? void 0 : _b.deoptimizePath(path);
  2645. }
  2646. }
  2647. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  2648. if (this.isReassigned || !this.init) {
  2649. return thisParameter.deoptimizePath(UNKNOWN_PATH);
  2650. }
  2651. recursionTracker.withTrackedEntityAtPath(path, this.init, () => this.init.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker), undefined);
  2652. }
  2653. getLiteralValueAtPath(path, recursionTracker, origin) {
  2654. if (this.isReassigned || !this.init) {
  2655. return UnknownValue;
  2656. }
  2657. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  2658. this.expressionsToBeDeoptimized.push(origin);
  2659. return this.init.getLiteralValueAtPath(path, recursionTracker, origin);
  2660. }, UnknownValue);
  2661. }
  2662. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  2663. if (this.isReassigned || !this.init) {
  2664. return UNKNOWN_EXPRESSION;
  2665. }
  2666. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  2667. this.expressionsToBeDeoptimized.push(origin);
  2668. return this.init.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
  2669. }, UNKNOWN_EXPRESSION);
  2670. }
  2671. hasEffectsWhenAccessedAtPath(path, context) {
  2672. if (this.isReassigned)
  2673. return true;
  2674. return (this.init &&
  2675. !context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  2676. this.init.hasEffectsWhenAccessedAtPath(path, context));
  2677. }
  2678. hasEffectsWhenAssignedAtPath(path, context) {
  2679. if (this.included)
  2680. return true;
  2681. if (path.length === 0)
  2682. return false;
  2683. if (this.isReassigned)
  2684. return true;
  2685. return (this.init &&
  2686. !context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  2687. this.init.hasEffectsWhenAssignedAtPath(path, context));
  2688. }
  2689. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  2690. if (this.isReassigned)
  2691. return true;
  2692. return (this.init &&
  2693. !(callOptions.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, callOptions, this) &&
  2694. this.init.hasEffectsWhenCalledAtPath(path, callOptions, context));
  2695. }
  2696. include() {
  2697. if (!this.included) {
  2698. this.included = true;
  2699. for (const declaration of this.declarations) {
  2700. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  2701. if (!declaration.included)
  2702. declaration.include(createInclusionContext(), false);
  2703. let node = declaration.parent;
  2704. while (!node.included) {
  2705. // We do not want to properly include parents in case they are part of a dead branch
  2706. // in which case .include() might pull in more dead code
  2707. node.included = true;
  2708. if (node.type === Program$1)
  2709. break;
  2710. node = node.parent;
  2711. }
  2712. }
  2713. }
  2714. }
  2715. includeCallArguments(context, args) {
  2716. if (this.isReassigned || (this.init && context.includedCallArguments.has(this.init))) {
  2717. for (const arg of args) {
  2718. arg.include(context, false);
  2719. }
  2720. }
  2721. else if (this.init) {
  2722. context.includedCallArguments.add(this.init);
  2723. this.init.includeCallArguments(context, args);
  2724. context.includedCallArguments.delete(this.init);
  2725. }
  2726. }
  2727. markCalledFromTryStatement() {
  2728. this.calledFromTryStatement = true;
  2729. }
  2730. markInitializersForDeoptimization() {
  2731. if (this.additionalInitializers === null) {
  2732. this.additionalInitializers = this.init === null ? [] : [this.init];
  2733. this.init = UNKNOWN_EXPRESSION;
  2734. this.isReassigned = true;
  2735. }
  2736. return this.additionalInitializers;
  2737. }
  2738. }
  2739. class Scope$1 {
  2740. constructor() {
  2741. this.children = [];
  2742. this.variables = new Map();
  2743. }
  2744. addDeclaration(identifier, context, init, _isHoisted) {
  2745. const name = identifier.name;
  2746. let variable = this.variables.get(name);
  2747. if (variable) {
  2748. variable.addDeclaration(identifier, init);
  2749. }
  2750. else {
  2751. variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
  2752. this.variables.set(name, variable);
  2753. }
  2754. return variable;
  2755. }
  2756. contains(name) {
  2757. return this.variables.has(name);
  2758. }
  2759. findVariable(_name) {
  2760. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  2761. }
  2762. }
  2763. class ChildScope extends Scope$1 {
  2764. constructor(parent) {
  2765. super();
  2766. this.accessedOutsideVariables = new Map();
  2767. this.parent = parent;
  2768. parent.children.push(this);
  2769. }
  2770. addAccessedDynamicImport(importExpression) {
  2771. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  2772. if (this.parent instanceof ChildScope) {
  2773. this.parent.addAccessedDynamicImport(importExpression);
  2774. }
  2775. }
  2776. addAccessedGlobals(globals, accessedGlobalsByScope) {
  2777. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  2778. for (const name of globals) {
  2779. accessedGlobals.add(name);
  2780. }
  2781. accessedGlobalsByScope.set(this, accessedGlobals);
  2782. if (this.parent instanceof ChildScope) {
  2783. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  2784. }
  2785. }
  2786. addNamespaceMemberAccess(name, variable) {
  2787. this.accessedOutsideVariables.set(name, variable);
  2788. this.parent.addNamespaceMemberAccess(name, variable);
  2789. }
  2790. addReturnExpression(expression) {
  2791. this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
  2792. }
  2793. addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
  2794. for (const variable of this.accessedOutsideVariables.values()) {
  2795. if (variable.included) {
  2796. usedNames.add(variable.getBaseVariableName());
  2797. if (format === 'system' && exportNamesByVariable.has(variable)) {
  2798. usedNames.add('exports');
  2799. }
  2800. }
  2801. }
  2802. const accessedGlobals = accessedGlobalsByScope.get(this);
  2803. if (accessedGlobals) {
  2804. for (const name of accessedGlobals) {
  2805. usedNames.add(name);
  2806. }
  2807. }
  2808. }
  2809. contains(name) {
  2810. return this.variables.has(name) || this.parent.contains(name);
  2811. }
  2812. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  2813. const usedNames = new Set();
  2814. this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  2815. if (this.accessedDynamicImports) {
  2816. for (const importExpression of this.accessedDynamicImports) {
  2817. if (importExpression.inlineNamespace) {
  2818. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  2819. }
  2820. }
  2821. }
  2822. for (const [name, variable] of this.variables) {
  2823. if (variable.included || variable.alwaysRendered) {
  2824. variable.setRenderNames(null, getSafeName(name, usedNames));
  2825. }
  2826. }
  2827. for (const scope of this.children) {
  2828. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  2829. }
  2830. }
  2831. findLexicalBoundary() {
  2832. return this.parent.findLexicalBoundary();
  2833. }
  2834. findVariable(name) {
  2835. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  2836. if (knownVariable) {
  2837. return knownVariable;
  2838. }
  2839. const variable = this.parent.findVariable(name);
  2840. this.accessedOutsideVariables.set(name, variable);
  2841. return variable;
  2842. }
  2843. }
  2844. //@ts-check
  2845. /** @typedef { import('estree').Node} Node */
  2846. /** @typedef {Node | {
  2847. * type: 'PropertyDefinition';
  2848. * computed: boolean;
  2849. * value: Node
  2850. * }} NodeWithPropertyDefinition */
  2851. /**
  2852. *
  2853. * @param {NodeWithPropertyDefinition} node
  2854. * @param {NodeWithPropertyDefinition} parent
  2855. * @returns boolean
  2856. */
  2857. function is_reference (node, parent) {
  2858. if (node.type === 'MemberExpression') {
  2859. return !node.computed && is_reference(node.object, node);
  2860. }
  2861. if (node.type === 'Identifier') {
  2862. if (!parent) return true;
  2863. switch (parent.type) {
  2864. // disregard `bar` in `foo.bar`
  2865. case 'MemberExpression': return parent.computed || node === parent.object;
  2866. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  2867. case 'MethodDefinition': return parent.computed;
  2868. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  2869. case 'PropertyDefinition': return parent.computed || node === parent.value;
  2870. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  2871. case 'Property': return parent.computed || node === parent.value;
  2872. // disregard the `bar` in `export { foo as bar }` or
  2873. // the foo in `import { foo as bar }`
  2874. case 'ExportSpecifier':
  2875. case 'ImportSpecifier': return node === parent.local;
  2876. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  2877. case 'LabeledStatement':
  2878. case 'BreakStatement':
  2879. case 'ContinueStatement': return false;
  2880. default: return true;
  2881. }
  2882. }
  2883. return false;
  2884. }
  2885. /* eslint sort-keys: "off" */
  2886. const ValueProperties = Symbol('Value Properties');
  2887. const PURE = { pure: true };
  2888. const IMPURE = { pure: false };
  2889. // We use shortened variables to reduce file size here
  2890. /* OBJECT */
  2891. const O = {
  2892. __proto__: null,
  2893. [ValueProperties]: IMPURE
  2894. };
  2895. /* PURE FUNCTION */
  2896. const PF = {
  2897. __proto__: null,
  2898. [ValueProperties]: PURE
  2899. };
  2900. /* CONSTRUCTOR */
  2901. const C = {
  2902. __proto__: null,
  2903. [ValueProperties]: IMPURE,
  2904. prototype: O
  2905. };
  2906. /* PURE CONSTRUCTOR */
  2907. const PC = {
  2908. __proto__: null,
  2909. [ValueProperties]: PURE,
  2910. prototype: O
  2911. };
  2912. const ARRAY_TYPE = {
  2913. __proto__: null,
  2914. [ValueProperties]: PURE,
  2915. from: PF,
  2916. of: PF,
  2917. prototype: O
  2918. };
  2919. const INTL_MEMBER = {
  2920. __proto__: null,
  2921. [ValueProperties]: PURE,
  2922. supportedLocalesOf: PC
  2923. };
  2924. const knownGlobals = {
  2925. // Placeholders for global objects to avoid shape mutations
  2926. global: O,
  2927. globalThis: O,
  2928. self: O,
  2929. window: O,
  2930. // Common globals
  2931. __proto__: null,
  2932. [ValueProperties]: IMPURE,
  2933. Array: {
  2934. __proto__: null,
  2935. [ValueProperties]: IMPURE,
  2936. from: O,
  2937. isArray: PF,
  2938. of: PF,
  2939. prototype: O
  2940. },
  2941. ArrayBuffer: {
  2942. __proto__: null,
  2943. [ValueProperties]: PURE,
  2944. isView: PF,
  2945. prototype: O
  2946. },
  2947. Atomics: O,
  2948. BigInt: C,
  2949. BigInt64Array: C,
  2950. BigUint64Array: C,
  2951. Boolean: PC,
  2952. constructor: C,
  2953. DataView: PC,
  2954. Date: {
  2955. __proto__: null,
  2956. [ValueProperties]: PURE,
  2957. now: PF,
  2958. parse: PF,
  2959. prototype: O,
  2960. UTC: PF
  2961. },
  2962. decodeURI: PF,
  2963. decodeURIComponent: PF,
  2964. encodeURI: PF,
  2965. encodeURIComponent: PF,
  2966. Error: PC,
  2967. escape: PF,
  2968. eval: O,
  2969. EvalError: PC,
  2970. Float32Array: ARRAY_TYPE,
  2971. Float64Array: ARRAY_TYPE,
  2972. Function: C,
  2973. hasOwnProperty: O,
  2974. Infinity: O,
  2975. Int16Array: ARRAY_TYPE,
  2976. Int32Array: ARRAY_TYPE,
  2977. Int8Array: ARRAY_TYPE,
  2978. isFinite: PF,
  2979. isNaN: PF,
  2980. isPrototypeOf: O,
  2981. JSON: O,
  2982. Map: PC,
  2983. Math: {
  2984. __proto__: null,
  2985. [ValueProperties]: IMPURE,
  2986. abs: PF,
  2987. acos: PF,
  2988. acosh: PF,
  2989. asin: PF,
  2990. asinh: PF,
  2991. atan: PF,
  2992. atan2: PF,
  2993. atanh: PF,
  2994. cbrt: PF,
  2995. ceil: PF,
  2996. clz32: PF,
  2997. cos: PF,
  2998. cosh: PF,
  2999. exp: PF,
  3000. expm1: PF,
  3001. floor: PF,
  3002. fround: PF,
  3003. hypot: PF,
  3004. imul: PF,
  3005. log: PF,
  3006. log10: PF,
  3007. log1p: PF,
  3008. log2: PF,
  3009. max: PF,
  3010. min: PF,
  3011. pow: PF,
  3012. random: PF,
  3013. round: PF,
  3014. sign: PF,
  3015. sin: PF,
  3016. sinh: PF,
  3017. sqrt: PF,
  3018. tan: PF,
  3019. tanh: PF,
  3020. trunc: PF
  3021. },
  3022. NaN: O,
  3023. Number: {
  3024. __proto__: null,
  3025. [ValueProperties]: PURE,
  3026. isFinite: PF,
  3027. isInteger: PF,
  3028. isNaN: PF,
  3029. isSafeInteger: PF,
  3030. parseFloat: PF,
  3031. parseInt: PF,
  3032. prototype: O
  3033. },
  3034. Object: {
  3035. __proto__: null,
  3036. [ValueProperties]: PURE,
  3037. create: PF,
  3038. getNotifier: PF,
  3039. getOwn: PF,
  3040. getOwnPropertyDescriptor: PF,
  3041. getOwnPropertyNames: PF,
  3042. getOwnPropertySymbols: PF,
  3043. getPrototypeOf: PF,
  3044. is: PF,
  3045. isExtensible: PF,
  3046. isFrozen: PF,
  3047. isSealed: PF,
  3048. keys: PF,
  3049. prototype: O
  3050. },
  3051. parseFloat: PF,
  3052. parseInt: PF,
  3053. Promise: {
  3054. __proto__: null,
  3055. [ValueProperties]: IMPURE,
  3056. all: O,
  3057. prototype: O,
  3058. race: O,
  3059. reject: O,
  3060. resolve: O
  3061. },
  3062. propertyIsEnumerable: O,
  3063. Proxy: O,
  3064. RangeError: PC,
  3065. ReferenceError: PC,
  3066. Reflect: O,
  3067. RegExp: PC,
  3068. Set: PC,
  3069. SharedArrayBuffer: C,
  3070. String: {
  3071. __proto__: null,
  3072. [ValueProperties]: PURE,
  3073. fromCharCode: PF,
  3074. fromCodePoint: PF,
  3075. prototype: O,
  3076. raw: PF
  3077. },
  3078. Symbol: {
  3079. __proto__: null,
  3080. [ValueProperties]: PURE,
  3081. for: PF,
  3082. keyFor: PF,
  3083. prototype: O
  3084. },
  3085. SyntaxError: PC,
  3086. toLocaleString: O,
  3087. toString: O,
  3088. TypeError: PC,
  3089. Uint16Array: ARRAY_TYPE,
  3090. Uint32Array: ARRAY_TYPE,
  3091. Uint8Array: ARRAY_TYPE,
  3092. Uint8ClampedArray: ARRAY_TYPE,
  3093. // Technically, this is a global, but it needs special handling
  3094. // undefined: ?,
  3095. unescape: PF,
  3096. URIError: PC,
  3097. valueOf: O,
  3098. WeakMap: PC,
  3099. WeakSet: PC,
  3100. // Additional globals shared by Node and Browser that are not strictly part of the language
  3101. clearInterval: C,
  3102. clearTimeout: C,
  3103. console: O,
  3104. Intl: {
  3105. __proto__: null,
  3106. [ValueProperties]: IMPURE,
  3107. Collator: INTL_MEMBER,
  3108. DateTimeFormat: INTL_MEMBER,
  3109. ListFormat: INTL_MEMBER,
  3110. NumberFormat: INTL_MEMBER,
  3111. PluralRules: INTL_MEMBER,
  3112. RelativeTimeFormat: INTL_MEMBER
  3113. },
  3114. setInterval: C,
  3115. setTimeout: C,
  3116. TextDecoder: C,
  3117. TextEncoder: C,
  3118. URL: C,
  3119. URLSearchParams: C,
  3120. // Browser specific globals
  3121. AbortController: C,
  3122. AbortSignal: C,
  3123. addEventListener: O,
  3124. alert: O,
  3125. AnalyserNode: C,
  3126. Animation: C,
  3127. AnimationEvent: C,
  3128. applicationCache: O,
  3129. ApplicationCache: C,
  3130. ApplicationCacheErrorEvent: C,
  3131. atob: O,
  3132. Attr: C,
  3133. Audio: C,
  3134. AudioBuffer: C,
  3135. AudioBufferSourceNode: C,
  3136. AudioContext: C,
  3137. AudioDestinationNode: C,
  3138. AudioListener: C,
  3139. AudioNode: C,
  3140. AudioParam: C,
  3141. AudioProcessingEvent: C,
  3142. AudioScheduledSourceNode: C,
  3143. AudioWorkletNode: C,
  3144. BarProp: C,
  3145. BaseAudioContext: C,
  3146. BatteryManager: C,
  3147. BeforeUnloadEvent: C,
  3148. BiquadFilterNode: C,
  3149. Blob: C,
  3150. BlobEvent: C,
  3151. blur: O,
  3152. BroadcastChannel: C,
  3153. btoa: O,
  3154. ByteLengthQueuingStrategy: C,
  3155. Cache: C,
  3156. caches: O,
  3157. CacheStorage: C,
  3158. cancelAnimationFrame: O,
  3159. cancelIdleCallback: O,
  3160. CanvasCaptureMediaStreamTrack: C,
  3161. CanvasGradient: C,
  3162. CanvasPattern: C,
  3163. CanvasRenderingContext2D: C,
  3164. ChannelMergerNode: C,
  3165. ChannelSplitterNode: C,
  3166. CharacterData: C,
  3167. clientInformation: O,
  3168. ClipboardEvent: C,
  3169. close: O,
  3170. closed: O,
  3171. CloseEvent: C,
  3172. Comment: C,
  3173. CompositionEvent: C,
  3174. confirm: O,
  3175. ConstantSourceNode: C,
  3176. ConvolverNode: C,
  3177. CountQueuingStrategy: C,
  3178. createImageBitmap: O,
  3179. Credential: C,
  3180. CredentialsContainer: C,
  3181. crypto: O,
  3182. Crypto: C,
  3183. CryptoKey: C,
  3184. CSS: C,
  3185. CSSConditionRule: C,
  3186. CSSFontFaceRule: C,
  3187. CSSGroupingRule: C,
  3188. CSSImportRule: C,
  3189. CSSKeyframeRule: C,
  3190. CSSKeyframesRule: C,
  3191. CSSMediaRule: C,
  3192. CSSNamespaceRule: C,
  3193. CSSPageRule: C,
  3194. CSSRule: C,
  3195. CSSRuleList: C,
  3196. CSSStyleDeclaration: C,
  3197. CSSStyleRule: C,
  3198. CSSStyleSheet: C,
  3199. CSSSupportsRule: C,
  3200. CustomElementRegistry: C,
  3201. customElements: O,
  3202. CustomEvent: C,
  3203. DataTransfer: C,
  3204. DataTransferItem: C,
  3205. DataTransferItemList: C,
  3206. defaultstatus: O,
  3207. defaultStatus: O,
  3208. DelayNode: C,
  3209. DeviceMotionEvent: C,
  3210. DeviceOrientationEvent: C,
  3211. devicePixelRatio: O,
  3212. dispatchEvent: O,
  3213. document: O,
  3214. Document: C,
  3215. DocumentFragment: C,
  3216. DocumentType: C,
  3217. DOMError: C,
  3218. DOMException: C,
  3219. DOMImplementation: C,
  3220. DOMMatrix: C,
  3221. DOMMatrixReadOnly: C,
  3222. DOMParser: C,
  3223. DOMPoint: C,
  3224. DOMPointReadOnly: C,
  3225. DOMQuad: C,
  3226. DOMRect: C,
  3227. DOMRectReadOnly: C,
  3228. DOMStringList: C,
  3229. DOMStringMap: C,
  3230. DOMTokenList: C,
  3231. DragEvent: C,
  3232. DynamicsCompressorNode: C,
  3233. Element: C,
  3234. ErrorEvent: C,
  3235. Event: C,
  3236. EventSource: C,
  3237. EventTarget: C,
  3238. external: O,
  3239. fetch: O,
  3240. File: C,
  3241. FileList: C,
  3242. FileReader: C,
  3243. find: O,
  3244. focus: O,
  3245. FocusEvent: C,
  3246. FontFace: C,
  3247. FontFaceSetLoadEvent: C,
  3248. FormData: C,
  3249. frames: O,
  3250. GainNode: C,
  3251. Gamepad: C,
  3252. GamepadButton: C,
  3253. GamepadEvent: C,
  3254. getComputedStyle: O,
  3255. getSelection: O,
  3256. HashChangeEvent: C,
  3257. Headers: C,
  3258. history: O,
  3259. History: C,
  3260. HTMLAllCollection: C,
  3261. HTMLAnchorElement: C,
  3262. HTMLAreaElement: C,
  3263. HTMLAudioElement: C,
  3264. HTMLBaseElement: C,
  3265. HTMLBodyElement: C,
  3266. HTMLBRElement: C,
  3267. HTMLButtonElement: C,
  3268. HTMLCanvasElement: C,
  3269. HTMLCollection: C,
  3270. HTMLContentElement: C,
  3271. HTMLDataElement: C,
  3272. HTMLDataListElement: C,
  3273. HTMLDetailsElement: C,
  3274. HTMLDialogElement: C,
  3275. HTMLDirectoryElement: C,
  3276. HTMLDivElement: C,
  3277. HTMLDListElement: C,
  3278. HTMLDocument: C,
  3279. HTMLElement: C,
  3280. HTMLEmbedElement: C,
  3281. HTMLFieldSetElement: C,
  3282. HTMLFontElement: C,
  3283. HTMLFormControlsCollection: C,
  3284. HTMLFormElement: C,
  3285. HTMLFrameElement: C,
  3286. HTMLFrameSetElement: C,
  3287. HTMLHeadElement: C,
  3288. HTMLHeadingElement: C,
  3289. HTMLHRElement: C,
  3290. HTMLHtmlElement: C,
  3291. HTMLIFrameElement: C,
  3292. HTMLImageElement: C,
  3293. HTMLInputElement: C,
  3294. HTMLLabelElement: C,
  3295. HTMLLegendElement: C,
  3296. HTMLLIElement: C,
  3297. HTMLLinkElement: C,
  3298. HTMLMapElement: C,
  3299. HTMLMarqueeElement: C,
  3300. HTMLMediaElement: C,
  3301. HTMLMenuElement: C,
  3302. HTMLMetaElement: C,
  3303. HTMLMeterElement: C,
  3304. HTMLModElement: C,
  3305. HTMLObjectElement: C,
  3306. HTMLOListElement: C,
  3307. HTMLOptGroupElement: C,
  3308. HTMLOptionElement: C,
  3309. HTMLOptionsCollection: C,
  3310. HTMLOutputElement: C,
  3311. HTMLParagraphElement: C,
  3312. HTMLParamElement: C,
  3313. HTMLPictureElement: C,
  3314. HTMLPreElement: C,
  3315. HTMLProgressElement: C,
  3316. HTMLQuoteElement: C,
  3317. HTMLScriptElement: C,
  3318. HTMLSelectElement: C,
  3319. HTMLShadowElement: C,
  3320. HTMLSlotElement: C,
  3321. HTMLSourceElement: C,
  3322. HTMLSpanElement: C,
  3323. HTMLStyleElement: C,
  3324. HTMLTableCaptionElement: C,
  3325. HTMLTableCellElement: C,
  3326. HTMLTableColElement: C,
  3327. HTMLTableElement: C,
  3328. HTMLTableRowElement: C,
  3329. HTMLTableSectionElement: C,
  3330. HTMLTemplateElement: C,
  3331. HTMLTextAreaElement: C,
  3332. HTMLTimeElement: C,
  3333. HTMLTitleElement: C,
  3334. HTMLTrackElement: C,
  3335. HTMLUListElement: C,
  3336. HTMLUnknownElement: C,
  3337. HTMLVideoElement: C,
  3338. IDBCursor: C,
  3339. IDBCursorWithValue: C,
  3340. IDBDatabase: C,
  3341. IDBFactory: C,
  3342. IDBIndex: C,
  3343. IDBKeyRange: C,
  3344. IDBObjectStore: C,
  3345. IDBOpenDBRequest: C,
  3346. IDBRequest: C,
  3347. IDBTransaction: C,
  3348. IDBVersionChangeEvent: C,
  3349. IdleDeadline: C,
  3350. IIRFilterNode: C,
  3351. Image: C,
  3352. ImageBitmap: C,
  3353. ImageBitmapRenderingContext: C,
  3354. ImageCapture: C,
  3355. ImageData: C,
  3356. indexedDB: O,
  3357. innerHeight: O,
  3358. innerWidth: O,
  3359. InputEvent: C,
  3360. IntersectionObserver: C,
  3361. IntersectionObserverEntry: C,
  3362. isSecureContext: O,
  3363. KeyboardEvent: C,
  3364. KeyframeEffect: C,
  3365. length: O,
  3366. localStorage: O,
  3367. location: O,
  3368. Location: C,
  3369. locationbar: O,
  3370. matchMedia: O,
  3371. MediaDeviceInfo: C,
  3372. MediaDevices: C,
  3373. MediaElementAudioSourceNode: C,
  3374. MediaEncryptedEvent: C,
  3375. MediaError: C,
  3376. MediaKeyMessageEvent: C,
  3377. MediaKeySession: C,
  3378. MediaKeyStatusMap: C,
  3379. MediaKeySystemAccess: C,
  3380. MediaList: C,
  3381. MediaQueryList: C,
  3382. MediaQueryListEvent: C,
  3383. MediaRecorder: C,
  3384. MediaSettingsRange: C,
  3385. MediaSource: C,
  3386. MediaStream: C,
  3387. MediaStreamAudioDestinationNode: C,
  3388. MediaStreamAudioSourceNode: C,
  3389. MediaStreamEvent: C,
  3390. MediaStreamTrack: C,
  3391. MediaStreamTrackEvent: C,
  3392. menubar: O,
  3393. MessageChannel: C,
  3394. MessageEvent: C,
  3395. MessagePort: C,
  3396. MIDIAccess: C,
  3397. MIDIConnectionEvent: C,
  3398. MIDIInput: C,
  3399. MIDIInputMap: C,
  3400. MIDIMessageEvent: C,
  3401. MIDIOutput: C,
  3402. MIDIOutputMap: C,
  3403. MIDIPort: C,
  3404. MimeType: C,
  3405. MimeTypeArray: C,
  3406. MouseEvent: C,
  3407. moveBy: O,
  3408. moveTo: O,
  3409. MutationEvent: C,
  3410. MutationObserver: C,
  3411. MutationRecord: C,
  3412. name: O,
  3413. NamedNodeMap: C,
  3414. NavigationPreloadManager: C,
  3415. navigator: O,
  3416. Navigator: C,
  3417. NetworkInformation: C,
  3418. Node: C,
  3419. NodeFilter: O,
  3420. NodeIterator: C,
  3421. NodeList: C,
  3422. Notification: C,
  3423. OfflineAudioCompletionEvent: C,
  3424. OfflineAudioContext: C,
  3425. offscreenBuffering: O,
  3426. OffscreenCanvas: C,
  3427. open: O,
  3428. openDatabase: O,
  3429. Option: C,
  3430. origin: O,
  3431. OscillatorNode: C,
  3432. outerHeight: O,
  3433. outerWidth: O,
  3434. PageTransitionEvent: C,
  3435. pageXOffset: O,
  3436. pageYOffset: O,
  3437. PannerNode: C,
  3438. parent: O,
  3439. Path2D: C,
  3440. PaymentAddress: C,
  3441. PaymentRequest: C,
  3442. PaymentRequestUpdateEvent: C,
  3443. PaymentResponse: C,
  3444. performance: O,
  3445. Performance: C,
  3446. PerformanceEntry: C,
  3447. PerformanceLongTaskTiming: C,
  3448. PerformanceMark: C,
  3449. PerformanceMeasure: C,
  3450. PerformanceNavigation: C,
  3451. PerformanceNavigationTiming: C,
  3452. PerformanceObserver: C,
  3453. PerformanceObserverEntryList: C,
  3454. PerformancePaintTiming: C,
  3455. PerformanceResourceTiming: C,
  3456. PerformanceTiming: C,
  3457. PeriodicWave: C,
  3458. Permissions: C,
  3459. PermissionStatus: C,
  3460. personalbar: O,
  3461. PhotoCapabilities: C,
  3462. Plugin: C,
  3463. PluginArray: C,
  3464. PointerEvent: C,
  3465. PopStateEvent: C,
  3466. postMessage: O,
  3467. Presentation: C,
  3468. PresentationAvailability: C,
  3469. PresentationConnection: C,
  3470. PresentationConnectionAvailableEvent: C,
  3471. PresentationConnectionCloseEvent: C,
  3472. PresentationConnectionList: C,
  3473. PresentationReceiver: C,
  3474. PresentationRequest: C,
  3475. print: O,
  3476. ProcessingInstruction: C,
  3477. ProgressEvent: C,
  3478. PromiseRejectionEvent: C,
  3479. prompt: O,
  3480. PushManager: C,
  3481. PushSubscription: C,
  3482. PushSubscriptionOptions: C,
  3483. queueMicrotask: O,
  3484. RadioNodeList: C,
  3485. Range: C,
  3486. ReadableStream: C,
  3487. RemotePlayback: C,
  3488. removeEventListener: O,
  3489. Request: C,
  3490. requestAnimationFrame: O,
  3491. requestIdleCallback: O,
  3492. resizeBy: O,
  3493. ResizeObserver: C,
  3494. ResizeObserverEntry: C,
  3495. resizeTo: O,
  3496. Response: C,
  3497. RTCCertificate: C,
  3498. RTCDataChannel: C,
  3499. RTCDataChannelEvent: C,
  3500. RTCDtlsTransport: C,
  3501. RTCIceCandidate: C,
  3502. RTCIceTransport: C,
  3503. RTCPeerConnection: C,
  3504. RTCPeerConnectionIceEvent: C,
  3505. RTCRtpReceiver: C,
  3506. RTCRtpSender: C,
  3507. RTCSctpTransport: C,
  3508. RTCSessionDescription: C,
  3509. RTCStatsReport: C,
  3510. RTCTrackEvent: C,
  3511. screen: O,
  3512. Screen: C,
  3513. screenLeft: O,
  3514. ScreenOrientation: C,
  3515. screenTop: O,
  3516. screenX: O,
  3517. screenY: O,
  3518. ScriptProcessorNode: C,
  3519. scroll: O,
  3520. scrollbars: O,
  3521. scrollBy: O,
  3522. scrollTo: O,
  3523. scrollX: O,
  3524. scrollY: O,
  3525. SecurityPolicyViolationEvent: C,
  3526. Selection: C,
  3527. ServiceWorker: C,
  3528. ServiceWorkerContainer: C,
  3529. ServiceWorkerRegistration: C,
  3530. sessionStorage: O,
  3531. ShadowRoot: C,
  3532. SharedWorker: C,
  3533. SourceBuffer: C,
  3534. SourceBufferList: C,
  3535. speechSynthesis: O,
  3536. SpeechSynthesisEvent: C,
  3537. SpeechSynthesisUtterance: C,
  3538. StaticRange: C,
  3539. status: O,
  3540. statusbar: O,
  3541. StereoPannerNode: C,
  3542. stop: O,
  3543. Storage: C,
  3544. StorageEvent: C,
  3545. StorageManager: C,
  3546. styleMedia: O,
  3547. StyleSheet: C,
  3548. StyleSheetList: C,
  3549. SubtleCrypto: C,
  3550. SVGAElement: C,
  3551. SVGAngle: C,
  3552. SVGAnimatedAngle: C,
  3553. SVGAnimatedBoolean: C,
  3554. SVGAnimatedEnumeration: C,
  3555. SVGAnimatedInteger: C,
  3556. SVGAnimatedLength: C,
  3557. SVGAnimatedLengthList: C,
  3558. SVGAnimatedNumber: C,
  3559. SVGAnimatedNumberList: C,
  3560. SVGAnimatedPreserveAspectRatio: C,
  3561. SVGAnimatedRect: C,
  3562. SVGAnimatedString: C,
  3563. SVGAnimatedTransformList: C,
  3564. SVGAnimateElement: C,
  3565. SVGAnimateMotionElement: C,
  3566. SVGAnimateTransformElement: C,
  3567. SVGAnimationElement: C,
  3568. SVGCircleElement: C,
  3569. SVGClipPathElement: C,
  3570. SVGComponentTransferFunctionElement: C,
  3571. SVGDefsElement: C,
  3572. SVGDescElement: C,
  3573. SVGDiscardElement: C,
  3574. SVGElement: C,
  3575. SVGEllipseElement: C,
  3576. SVGFEBlendElement: C,
  3577. SVGFEColorMatrixElement: C,
  3578. SVGFEComponentTransferElement: C,
  3579. SVGFECompositeElement: C,
  3580. SVGFEConvolveMatrixElement: C,
  3581. SVGFEDiffuseLightingElement: C,
  3582. SVGFEDisplacementMapElement: C,
  3583. SVGFEDistantLightElement: C,
  3584. SVGFEDropShadowElement: C,
  3585. SVGFEFloodElement: C,
  3586. SVGFEFuncAElement: C,
  3587. SVGFEFuncBElement: C,
  3588. SVGFEFuncGElement: C,
  3589. SVGFEFuncRElement: C,
  3590. SVGFEGaussianBlurElement: C,
  3591. SVGFEImageElement: C,
  3592. SVGFEMergeElement: C,
  3593. SVGFEMergeNodeElement: C,
  3594. SVGFEMorphologyElement: C,
  3595. SVGFEOffsetElement: C,
  3596. SVGFEPointLightElement: C,
  3597. SVGFESpecularLightingElement: C,
  3598. SVGFESpotLightElement: C,
  3599. SVGFETileElement: C,
  3600. SVGFETurbulenceElement: C,
  3601. SVGFilterElement: C,
  3602. SVGForeignObjectElement: C,
  3603. SVGGElement: C,
  3604. SVGGeometryElement: C,
  3605. SVGGradientElement: C,
  3606. SVGGraphicsElement: C,
  3607. SVGImageElement: C,
  3608. SVGLength: C,
  3609. SVGLengthList: C,
  3610. SVGLinearGradientElement: C,
  3611. SVGLineElement: C,
  3612. SVGMarkerElement: C,
  3613. SVGMaskElement: C,
  3614. SVGMatrix: C,
  3615. SVGMetadataElement: C,
  3616. SVGMPathElement: C,
  3617. SVGNumber: C,
  3618. SVGNumberList: C,
  3619. SVGPathElement: C,
  3620. SVGPatternElement: C,
  3621. SVGPoint: C,
  3622. SVGPointList: C,
  3623. SVGPolygonElement: C,
  3624. SVGPolylineElement: C,
  3625. SVGPreserveAspectRatio: C,
  3626. SVGRadialGradientElement: C,
  3627. SVGRect: C,
  3628. SVGRectElement: C,
  3629. SVGScriptElement: C,
  3630. SVGSetElement: C,
  3631. SVGStopElement: C,
  3632. SVGStringList: C,
  3633. SVGStyleElement: C,
  3634. SVGSVGElement: C,
  3635. SVGSwitchElement: C,
  3636. SVGSymbolElement: C,
  3637. SVGTextContentElement: C,
  3638. SVGTextElement: C,
  3639. SVGTextPathElement: C,
  3640. SVGTextPositioningElement: C,
  3641. SVGTitleElement: C,
  3642. SVGTransform: C,
  3643. SVGTransformList: C,
  3644. SVGTSpanElement: C,
  3645. SVGUnitTypes: C,
  3646. SVGUseElement: C,
  3647. SVGViewElement: C,
  3648. TaskAttributionTiming: C,
  3649. Text: C,
  3650. TextEvent: C,
  3651. TextMetrics: C,
  3652. TextTrack: C,
  3653. TextTrackCue: C,
  3654. TextTrackCueList: C,
  3655. TextTrackList: C,
  3656. TimeRanges: C,
  3657. toolbar: O,
  3658. top: O,
  3659. Touch: C,
  3660. TouchEvent: C,
  3661. TouchList: C,
  3662. TrackEvent: C,
  3663. TransitionEvent: C,
  3664. TreeWalker: C,
  3665. UIEvent: C,
  3666. ValidityState: C,
  3667. visualViewport: O,
  3668. VisualViewport: C,
  3669. VTTCue: C,
  3670. WaveShaperNode: C,
  3671. WebAssembly: O,
  3672. WebGL2RenderingContext: C,
  3673. WebGLActiveInfo: C,
  3674. WebGLBuffer: C,
  3675. WebGLContextEvent: C,
  3676. WebGLFramebuffer: C,
  3677. WebGLProgram: C,
  3678. WebGLQuery: C,
  3679. WebGLRenderbuffer: C,
  3680. WebGLRenderingContext: C,
  3681. WebGLSampler: C,
  3682. WebGLShader: C,
  3683. WebGLShaderPrecisionFormat: C,
  3684. WebGLSync: C,
  3685. WebGLTexture: C,
  3686. WebGLTransformFeedback: C,
  3687. WebGLUniformLocation: C,
  3688. WebGLVertexArrayObject: C,
  3689. WebSocket: C,
  3690. WheelEvent: C,
  3691. Window: C,
  3692. Worker: C,
  3693. WritableStream: C,
  3694. XMLDocument: C,
  3695. XMLHttpRequest: C,
  3696. XMLHttpRequestEventTarget: C,
  3697. XMLHttpRequestUpload: C,
  3698. XMLSerializer: C,
  3699. XPathEvaluator: C,
  3700. XPathExpression: C,
  3701. XPathResult: C,
  3702. XSLTProcessor: C
  3703. };
  3704. for (const global of ['window', 'global', 'self', 'globalThis']) {
  3705. knownGlobals[global] = knownGlobals;
  3706. }
  3707. function getGlobalAtPath(path) {
  3708. let currentGlobal = knownGlobals;
  3709. for (const pathSegment of path) {
  3710. if (typeof pathSegment !== 'string') {
  3711. return null;
  3712. }
  3713. currentGlobal = currentGlobal[pathSegment];
  3714. if (!currentGlobal) {
  3715. return null;
  3716. }
  3717. }
  3718. return currentGlobal[ValueProperties];
  3719. }
  3720. function isPureGlobal(path) {
  3721. const globalAtPath = getGlobalAtPath(path);
  3722. return globalAtPath !== null && globalAtPath.pure;
  3723. }
  3724. function isGlobalMember(path) {
  3725. if (path.length === 1) {
  3726. return path[0] === 'undefined' || getGlobalAtPath(path) !== null;
  3727. }
  3728. return getGlobalAtPath(path.slice(0, -1)) !== null;
  3729. }
  3730. class GlobalVariable extends Variable {
  3731. constructor() {
  3732. super(...arguments);
  3733. this.isReassigned = true;
  3734. }
  3735. hasEffectsWhenAccessedAtPath(path) {
  3736. return !isGlobalMember([this.name, ...path]);
  3737. }
  3738. hasEffectsWhenCalledAtPath(path) {
  3739. return !isPureGlobal([this.name, ...path]);
  3740. }
  3741. }
  3742. const tdzVariableKinds = {
  3743. __proto__: null,
  3744. class: true,
  3745. const: true,
  3746. let: true,
  3747. var: true
  3748. };
  3749. class Identifier extends NodeBase {
  3750. constructor() {
  3751. super(...arguments);
  3752. this.variable = null;
  3753. this.deoptimized = false;
  3754. this.isTDZAccess = null;
  3755. }
  3756. addExportedVariables(variables, exportNamesByVariable) {
  3757. if (this.variable !== null && exportNamesByVariable.has(this.variable)) {
  3758. variables.push(this.variable);
  3759. }
  3760. }
  3761. bind() {
  3762. if (this.variable === null && is_reference(this, this.parent)) {
  3763. this.variable = this.scope.findVariable(this.name);
  3764. this.variable.addReference(this);
  3765. }
  3766. }
  3767. declare(kind, init) {
  3768. let variable;
  3769. const { treeshake } = this.context.options;
  3770. switch (kind) {
  3771. case 'var':
  3772. variable = this.scope.addDeclaration(this, this.context, init, true);
  3773. if (treeshake && treeshake.correctVarValueBeforeDeclaration) {
  3774. // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
  3775. variable.markInitializersForDeoptimization();
  3776. }
  3777. break;
  3778. case 'function':
  3779. // in strict mode, functions are only hoisted within a scope but not across block scopes
  3780. variable = this.scope.addDeclaration(this, this.context, init, false);
  3781. break;
  3782. case 'let':
  3783. case 'const':
  3784. case 'class':
  3785. variable = this.scope.addDeclaration(this, this.context, init, false);
  3786. break;
  3787. case 'parameter':
  3788. variable = this.scope.addParameterDeclaration(this);
  3789. break;
  3790. /* istanbul ignore next */
  3791. default:
  3792. /* istanbul ignore next */
  3793. throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
  3794. }
  3795. variable.kind = kind;
  3796. return [(this.variable = variable)];
  3797. }
  3798. deoptimizePath(path) {
  3799. if (path.length === 0 && !this.scope.contains(this.name)) {
  3800. this.disallowImportReassignment();
  3801. }
  3802. this.variable.deoptimizePath(path);
  3803. }
  3804. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  3805. this.variable.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  3806. }
  3807. getLiteralValueAtPath(path, recursionTracker, origin) {
  3808. return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
  3809. }
  3810. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  3811. return this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
  3812. }
  3813. hasEffects() {
  3814. if (!this.deoptimized)
  3815. this.applyDeoptimizations();
  3816. if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
  3817. return true;
  3818. }
  3819. return (this.context.options.treeshake.unknownGlobalSideEffects &&
  3820. this.variable instanceof GlobalVariable &&
  3821. this.variable.hasEffectsWhenAccessedAtPath(EMPTY_PATH));
  3822. }
  3823. hasEffectsWhenAccessedAtPath(path, context) {
  3824. return (this.variable !== null &&
  3825. this.getVariableRespectingTDZ().hasEffectsWhenAccessedAtPath(path, context));
  3826. }
  3827. hasEffectsWhenAssignedAtPath(path, context) {
  3828. return (!this.variable ||
  3829. (path.length > 0
  3830. ? this.getVariableRespectingTDZ()
  3831. : this.variable).hasEffectsWhenAssignedAtPath(path, context));
  3832. }
  3833. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  3834. return (!this.variable ||
  3835. this.getVariableRespectingTDZ().hasEffectsWhenCalledAtPath(path, callOptions, context));
  3836. }
  3837. include() {
  3838. if (!this.deoptimized)
  3839. this.applyDeoptimizations();
  3840. if (!this.included) {
  3841. this.included = true;
  3842. if (this.variable !== null) {
  3843. this.context.includeVariableInModule(this.variable);
  3844. }
  3845. }
  3846. }
  3847. includeCallArguments(context, args) {
  3848. this.getVariableRespectingTDZ().includeCallArguments(context, args);
  3849. }
  3850. isPossibleTDZ() {
  3851. // return cached value to avoid issues with the next tree-shaking pass
  3852. if (this.isTDZAccess !== null)
  3853. return this.isTDZAccess;
  3854. if (!(this.variable instanceof LocalVariable) ||
  3855. !this.variable.kind ||
  3856. !(this.variable.kind in tdzVariableKinds)) {
  3857. return (this.isTDZAccess = false);
  3858. }
  3859. let decl_id;
  3860. if (this.variable.declarations &&
  3861. this.variable.declarations.length === 1 &&
  3862. (decl_id = this.variable.declarations[0]) &&
  3863. this.start < decl_id.start &&
  3864. closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
  3865. // a variable accessed before its declaration
  3866. // in the same function or at top level of module
  3867. return (this.isTDZAccess = true);
  3868. }
  3869. if (!this.variable.initReached) {
  3870. // Either a const/let TDZ violation or
  3871. // var use before declaration was encountered.
  3872. return (this.isTDZAccess = true);
  3873. }
  3874. return (this.isTDZAccess = false);
  3875. }
  3876. markDeclarationReached() {
  3877. this.variable.initReached = true;
  3878. }
  3879. render(code, _options, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
  3880. if (this.variable) {
  3881. const name = this.variable.getName();
  3882. if (name !== this.name) {
  3883. code.overwrite(this.start, this.end, name, {
  3884. contentOnly: true,
  3885. storeName: true
  3886. });
  3887. if (isShorthandProperty) {
  3888. code.prependRight(this.start, `${this.name}: `);
  3889. }
  3890. }
  3891. // In strict mode, any variable named "eval" must be the actual "eval" function
  3892. if (name === 'eval' &&
  3893. renderedParentType === CallExpression$1 &&
  3894. isCalleeOfRenderedParent) {
  3895. code.appendRight(this.start, '0, ');
  3896. }
  3897. }
  3898. }
  3899. applyDeoptimizations() {
  3900. this.deoptimized = true;
  3901. if (this.variable !== null && this.variable instanceof LocalVariable) {
  3902. this.variable.consolidateInitializers();
  3903. this.context.requestTreeshakingPass();
  3904. }
  3905. }
  3906. disallowImportReassignment() {
  3907. return this.context.error({
  3908. code: 'ILLEGAL_REASSIGNMENT',
  3909. message: `Illegal reassignment to import '${this.name}'`
  3910. }, this.start);
  3911. }
  3912. getVariableRespectingTDZ() {
  3913. if (this.isPossibleTDZ()) {
  3914. return UNKNOWN_EXPRESSION;
  3915. }
  3916. return this.variable;
  3917. }
  3918. }
  3919. function closestParentFunctionOrProgram(node) {
  3920. while (node && !/^Program|Function/.test(node.type)) {
  3921. node = node.parent;
  3922. }
  3923. // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
  3924. return node;
  3925. }
  3926. const EVENT_ACCESSED = 0;
  3927. const EVENT_ASSIGNED = 1;
  3928. const EVENT_CALLED = 2;
  3929. class MethodBase extends NodeBase {
  3930. constructor() {
  3931. super(...arguments);
  3932. this.accessedValue = null;
  3933. this.accessorCallOptions = {
  3934. args: NO_ARGS,
  3935. thisParam: null,
  3936. withNew: false
  3937. };
  3938. }
  3939. // As getter properties directly receive their values from fixed function
  3940. // expressions, there is no known situation where a getter is deoptimized.
  3941. deoptimizeCache() { }
  3942. deoptimizePath(path) {
  3943. this.getAccessedValue().deoptimizePath(path);
  3944. }
  3945. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  3946. if (event === EVENT_ACCESSED && this.kind === 'get' && path.length === 0) {
  3947. return this.value.deoptimizeThisOnEventAtPath(EVENT_CALLED, EMPTY_PATH, thisParameter, recursionTracker);
  3948. }
  3949. if (event === EVENT_ASSIGNED && this.kind === 'set' && path.length === 0) {
  3950. return this.value.deoptimizeThisOnEventAtPath(EVENT_CALLED, EMPTY_PATH, thisParameter, recursionTracker);
  3951. }
  3952. this.getAccessedValue().deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  3953. }
  3954. getLiteralValueAtPath(path, recursionTracker, origin) {
  3955. return this.getAccessedValue().getLiteralValueAtPath(path, recursionTracker, origin);
  3956. }
  3957. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  3958. return this.getAccessedValue().getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
  3959. }
  3960. hasEffects(context) {
  3961. return this.key.hasEffects(context);
  3962. }
  3963. hasEffectsWhenAccessedAtPath(path, context) {
  3964. if (this.kind === 'get' && path.length === 0) {
  3965. return this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context);
  3966. }
  3967. return this.getAccessedValue().hasEffectsWhenAccessedAtPath(path, context);
  3968. }
  3969. hasEffectsWhenAssignedAtPath(path, context) {
  3970. if (this.kind === 'set') {
  3971. return this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context);
  3972. }
  3973. return this.getAccessedValue().hasEffectsWhenAssignedAtPath(path, context);
  3974. }
  3975. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  3976. return this.getAccessedValue().hasEffectsWhenCalledAtPath(path, callOptions, context);
  3977. }
  3978. getAccessedValue() {
  3979. if (this.accessedValue === null) {
  3980. if (this.kind === 'get') {
  3981. this.accessedValue = UNKNOWN_EXPRESSION;
  3982. return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, SHARED_RECURSION_TRACKER, this));
  3983. }
  3984. else {
  3985. return (this.accessedValue = this.value);
  3986. }
  3987. }
  3988. return this.accessedValue;
  3989. }
  3990. }
  3991. class MethodDefinition extends MethodBase {
  3992. }
  3993. const INTEGER_REG_EXP = /^\d+$/;
  3994. class ObjectEntity extends ExpressionEntity {
  3995. // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
  3996. // and we assume there are no setters or getters
  3997. constructor(properties, prototypeExpression, immutable = false) {
  3998. super();
  3999. this.prototypeExpression = prototypeExpression;
  4000. this.immutable = immutable;
  4001. this.allProperties = [];
  4002. this.deoptimizedPaths = Object.create(null);
  4003. this.expressionsToBeDeoptimizedByKey = Object.create(null);
  4004. this.gettersByKey = Object.create(null);
  4005. this.hasUnknownDeoptimizedInteger = false;
  4006. this.hasUnknownDeoptimizedProperty = false;
  4007. this.propertiesAndGettersByKey = Object.create(null);
  4008. this.propertiesAndSettersByKey = Object.create(null);
  4009. this.settersByKey = Object.create(null);
  4010. this.thisParametersToBeDeoptimized = new Set();
  4011. this.unknownIntegerProps = [];
  4012. this.unmatchableGetters = [];
  4013. this.unmatchablePropertiesAndGetters = [];
  4014. this.unmatchableSetters = [];
  4015. if (Array.isArray(properties)) {
  4016. this.buildPropertyMaps(properties);
  4017. }
  4018. else {
  4019. this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
  4020. for (const propertiesForKey of Object.values(properties)) {
  4021. this.allProperties.push(...propertiesForKey);
  4022. }
  4023. }
  4024. }
  4025. deoptimizeAllProperties() {
  4026. var _a;
  4027. if (this.hasUnknownDeoptimizedProperty) {
  4028. return;
  4029. }
  4030. this.hasUnknownDeoptimizedProperty = true;
  4031. for (const properties of Object.values(this.propertiesAndGettersByKey).concat(Object.values(this.settersByKey))) {
  4032. for (const property of properties) {
  4033. property.deoptimizePath(UNKNOWN_PATH);
  4034. }
  4035. }
  4036. // While the prototype itself cannot be mutated, each property can
  4037. (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizePath([UnknownKey, UnknownKey]);
  4038. this.deoptimizeCachedEntities();
  4039. }
  4040. deoptimizeIntegerProperties() {
  4041. if (this.hasUnknownDeoptimizedProperty || this.hasUnknownDeoptimizedInteger) {
  4042. return;
  4043. }
  4044. this.hasUnknownDeoptimizedInteger = true;
  4045. for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
  4046. if (INTEGER_REG_EXP.test(key)) {
  4047. for (const property of propertiesAndGetters) {
  4048. property.deoptimizePath(UNKNOWN_PATH);
  4049. }
  4050. }
  4051. }
  4052. this.deoptimizeCachedIntegerEntities();
  4053. }
  4054. deoptimizePath(path) {
  4055. var _a;
  4056. if (this.hasUnknownDeoptimizedProperty || this.immutable)
  4057. return;
  4058. const key = path[0];
  4059. if (path.length === 1) {
  4060. if (typeof key !== 'string') {
  4061. if (key === UnknownInteger) {
  4062. return this.deoptimizeIntegerProperties();
  4063. }
  4064. return this.deoptimizeAllProperties();
  4065. }
  4066. if (!this.deoptimizedPaths[key]) {
  4067. this.deoptimizedPaths[key] = true;
  4068. // we only deoptimizeCache exact matches as in all other cases,
  4069. // we do not return a literal value or return expression
  4070. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
  4071. if (expressionsToBeDeoptimized) {
  4072. for (const expression of expressionsToBeDeoptimized) {
  4073. expression.deoptimizeCache();
  4074. }
  4075. }
  4076. }
  4077. }
  4078. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  4079. for (const property of typeof key === 'string'
  4080. ? (this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters).concat(this.settersByKey[key] || this.unmatchableSetters)
  4081. : this.allProperties) {
  4082. property.deoptimizePath(subPath);
  4083. }
  4084. (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path.length === 1 ? [UnknownKey, UnknownKey] : path);
  4085. }
  4086. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  4087. var _a;
  4088. const [key, ...subPath] = path;
  4089. if (this.hasUnknownDeoptimizedProperty ||
  4090. // single paths that are deoptimized will not become getters or setters
  4091. ((event === EVENT_CALLED || path.length > 1) &&
  4092. typeof key === 'string' &&
  4093. this.deoptimizedPaths[key])) {
  4094. thisParameter.deoptimizePath(UNKNOWN_PATH);
  4095. return;
  4096. }
  4097. const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = event === EVENT_CALLED || path.length > 1
  4098. ? [
  4099. this.propertiesAndGettersByKey,
  4100. this.propertiesAndGettersByKey,
  4101. this.unmatchablePropertiesAndGetters
  4102. ]
  4103. : event === EVENT_ACCESSED
  4104. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  4105. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  4106. if (typeof key === 'string') {
  4107. if (propertiesForExactMatchByKey[key]) {
  4108. const properties = relevantPropertiesByKey[key];
  4109. if (properties) {
  4110. for (const property of properties) {
  4111. property.deoptimizeThisOnEventAtPath(event, subPath, thisParameter, recursionTracker);
  4112. }
  4113. }
  4114. if (!this.immutable) {
  4115. this.thisParametersToBeDeoptimized.add(thisParameter);
  4116. }
  4117. return;
  4118. }
  4119. for (const property of relevantUnmatchableProperties) {
  4120. property.deoptimizeThisOnEventAtPath(event, subPath, thisParameter, recursionTracker);
  4121. }
  4122. if (INTEGER_REG_EXP.test(key)) {
  4123. for (const property of this.unknownIntegerProps) {
  4124. property.deoptimizeThisOnEventAtPath(event, subPath, thisParameter, recursionTracker);
  4125. }
  4126. }
  4127. }
  4128. else {
  4129. for (const properties of Object.values(relevantPropertiesByKey).concat([
  4130. relevantUnmatchableProperties
  4131. ])) {
  4132. for (const property of properties) {
  4133. property.deoptimizeThisOnEventAtPath(event, subPath, thisParameter, recursionTracker);
  4134. }
  4135. }
  4136. for (const property of this.unknownIntegerProps) {
  4137. property.deoptimizeThisOnEventAtPath(event, subPath, thisParameter, recursionTracker);
  4138. }
  4139. }
  4140. if (!this.immutable) {
  4141. this.thisParametersToBeDeoptimized.add(thisParameter);
  4142. }
  4143. (_a = this.prototypeExpression) === null || _a === void 0 ? void 0 : _a.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  4144. }
  4145. getLiteralValueAtPath(path, recursionTracker, origin) {
  4146. if (path.length === 0) {
  4147. return UnknownValue;
  4148. }
  4149. const key = path[0];
  4150. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  4151. if (expressionAtPath) {
  4152. return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  4153. }
  4154. if (this.prototypeExpression) {
  4155. return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  4156. }
  4157. if (path.length === 1) {
  4158. return undefined;
  4159. }
  4160. return UnknownValue;
  4161. }
  4162. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  4163. if (path.length === 0) {
  4164. return UNKNOWN_EXPRESSION;
  4165. }
  4166. const key = path[0];
  4167. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  4168. if (expressionAtPath) {
  4169. return expressionAtPath.getReturnExpressionWhenCalledAtPath(path.slice(1), callOptions, recursionTracker, origin);
  4170. }
  4171. if (this.prototypeExpression) {
  4172. return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
  4173. }
  4174. return UNKNOWN_EXPRESSION;
  4175. }
  4176. hasEffectsWhenAccessedAtPath(path, context) {
  4177. const [key, ...subPath] = path;
  4178. if (path.length > 1) {
  4179. if (typeof key !== 'string') {
  4180. return true;
  4181. }
  4182. const expressionAtPath = this.getMemberExpression(key);
  4183. if (expressionAtPath) {
  4184. return expressionAtPath.hasEffectsWhenAccessedAtPath(subPath, context);
  4185. }
  4186. if (this.prototypeExpression) {
  4187. return this.prototypeExpression.hasEffectsWhenAccessedAtPath(path, context);
  4188. }
  4189. return true;
  4190. }
  4191. if (this.hasUnknownDeoptimizedProperty)
  4192. return true;
  4193. if (typeof key === 'string') {
  4194. if (this.propertiesAndGettersByKey[key]) {
  4195. const getters = this.gettersByKey[key];
  4196. if (getters) {
  4197. for (const getter of getters) {
  4198. if (getter.hasEffectsWhenAccessedAtPath(subPath, context))
  4199. return true;
  4200. }
  4201. }
  4202. return false;
  4203. }
  4204. for (const getter of this.unmatchableGetters) {
  4205. if (getter.hasEffectsWhenAccessedAtPath(subPath, context)) {
  4206. return true;
  4207. }
  4208. }
  4209. }
  4210. else {
  4211. for (const getters of Object.values(this.gettersByKey).concat([this.unmatchableGetters])) {
  4212. for (const getter of getters) {
  4213. if (getter.hasEffectsWhenAccessedAtPath(subPath, context))
  4214. return true;
  4215. }
  4216. }
  4217. }
  4218. if (this.prototypeExpression) {
  4219. return this.prototypeExpression.hasEffectsWhenAccessedAtPath(path, context);
  4220. }
  4221. return false;
  4222. }
  4223. hasEffectsWhenAssignedAtPath(path, context) {
  4224. const [key, ...subPath] = path;
  4225. if (path.length > 1) {
  4226. if (typeof key !== 'string') {
  4227. return true;
  4228. }
  4229. const expressionAtPath = this.getMemberExpression(key);
  4230. if (expressionAtPath) {
  4231. return expressionAtPath.hasEffectsWhenAssignedAtPath(subPath, context);
  4232. }
  4233. if (this.prototypeExpression) {
  4234. return this.prototypeExpression.hasEffectsWhenAssignedAtPath(path, context);
  4235. }
  4236. return true;
  4237. }
  4238. if (this.hasUnknownDeoptimizedProperty)
  4239. return true;
  4240. // We do not need to test for unknown properties as in that case, hasUnknownDeoptimizedProperty is true
  4241. if (typeof key === 'string') {
  4242. if (this.propertiesAndSettersByKey[key]) {
  4243. const setters = this.settersByKey[key];
  4244. if (setters) {
  4245. for (const setter of setters) {
  4246. if (setter.hasEffectsWhenAssignedAtPath(subPath, context))
  4247. return true;
  4248. }
  4249. }
  4250. return false;
  4251. }
  4252. for (const property of this.unmatchableSetters) {
  4253. if (property.hasEffectsWhenAssignedAtPath(subPath, context)) {
  4254. return true;
  4255. }
  4256. }
  4257. }
  4258. if (this.prototypeExpression) {
  4259. return this.prototypeExpression.hasEffectsWhenAssignedAtPath(path, context);
  4260. }
  4261. return false;
  4262. }
  4263. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  4264. const key = path[0];
  4265. const expressionAtPath = this.getMemberExpression(key);
  4266. if (expressionAtPath) {
  4267. return expressionAtPath.hasEffectsWhenCalledAtPath(path.slice(1), callOptions, context);
  4268. }
  4269. if (this.prototypeExpression) {
  4270. return this.prototypeExpression.hasEffectsWhenCalledAtPath(path, callOptions, context);
  4271. }
  4272. return true;
  4273. }
  4274. buildPropertyMaps(properties) {
  4275. const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchableGetters, unmatchableSetters } = this;
  4276. const unmatchablePropertiesAndSetters = [];
  4277. for (let index = properties.length - 1; index >= 0; index--) {
  4278. const { key, kind, property } = properties[index];
  4279. allProperties.push(property);
  4280. if (typeof key !== 'string') {
  4281. if (key === UnknownInteger) {
  4282. unknownIntegerProps.push(property);
  4283. continue;
  4284. }
  4285. if (kind === 'set')
  4286. unmatchableSetters.push(property);
  4287. if (kind === 'get')
  4288. unmatchableGetters.push(property);
  4289. if (kind !== 'get')
  4290. unmatchablePropertiesAndSetters.push(property);
  4291. if (kind !== 'set')
  4292. unmatchablePropertiesAndGetters.push(property);
  4293. }
  4294. else {
  4295. if (kind === 'set') {
  4296. if (!propertiesAndSettersByKey[key]) {
  4297. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  4298. settersByKey[key] = [property, ...unmatchableSetters];
  4299. }
  4300. }
  4301. else if (kind === 'get') {
  4302. if (!propertiesAndGettersByKey[key]) {
  4303. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  4304. gettersByKey[key] = [property, ...unmatchableGetters];
  4305. }
  4306. }
  4307. else {
  4308. if (!propertiesAndSettersByKey[key]) {
  4309. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  4310. }
  4311. if (!propertiesAndGettersByKey[key]) {
  4312. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  4313. }
  4314. }
  4315. }
  4316. }
  4317. }
  4318. deoptimizeCachedEntities() {
  4319. for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
  4320. for (const expression of expressionsToBeDeoptimized) {
  4321. expression.deoptimizeCache();
  4322. }
  4323. }
  4324. for (const expression of this.thisParametersToBeDeoptimized) {
  4325. expression.deoptimizePath(UNKNOWN_PATH);
  4326. }
  4327. }
  4328. deoptimizeCachedIntegerEntities() {
  4329. for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
  4330. if (INTEGER_REG_EXP.test(key)) {
  4331. for (const expression of expressionsToBeDeoptimized) {
  4332. expression.deoptimizeCache();
  4333. }
  4334. }
  4335. }
  4336. for (const expression of this.thisParametersToBeDeoptimized) {
  4337. expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
  4338. }
  4339. }
  4340. getMemberExpression(key) {
  4341. if (this.hasUnknownDeoptimizedProperty ||
  4342. typeof key !== 'string' ||
  4343. (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
  4344. this.deoptimizedPaths[key]) {
  4345. return UNKNOWN_EXPRESSION;
  4346. }
  4347. const properties = this.propertiesAndGettersByKey[key];
  4348. if ((properties === null || properties === void 0 ? void 0 : properties.length) === 1) {
  4349. return properties[0];
  4350. }
  4351. if (properties ||
  4352. this.unmatchablePropertiesAndGetters.length > 0 ||
  4353. (this.unknownIntegerProps.length && INTEGER_REG_EXP.test(key))) {
  4354. return UNKNOWN_EXPRESSION;
  4355. }
  4356. return null;
  4357. }
  4358. getMemberExpressionAndTrackDeopt(key, origin) {
  4359. if (typeof key !== 'string') {
  4360. return UNKNOWN_EXPRESSION;
  4361. }
  4362. const expression = this.getMemberExpression(key);
  4363. if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
  4364. const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
  4365. this.expressionsToBeDeoptimizedByKey[key] || []);
  4366. expressionsToBeDeoptimized.push(origin);
  4367. }
  4368. return expression;
  4369. }
  4370. }
  4371. class ObjectMember extends ExpressionEntity {
  4372. constructor(object, key) {
  4373. super();
  4374. this.object = object;
  4375. this.key = key;
  4376. }
  4377. deoptimizePath(path) {
  4378. this.object.deoptimizePath([this.key, ...path]);
  4379. }
  4380. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  4381. this.object.deoptimizeThisOnEventAtPath(event, [this.key, ...path], thisParameter, recursionTracker);
  4382. }
  4383. getLiteralValueAtPath(path, recursionTracker, origin) {
  4384. return this.object.getLiteralValueAtPath([this.key, ...path], recursionTracker, origin);
  4385. }
  4386. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  4387. return this.object.getReturnExpressionWhenCalledAtPath([this.key, ...path], callOptions, recursionTracker, origin);
  4388. }
  4389. hasEffectsWhenAccessedAtPath(path, context) {
  4390. if (path.length === 0)
  4391. return false;
  4392. return this.object.hasEffectsWhenAccessedAtPath([this.key, ...path], context);
  4393. }
  4394. hasEffectsWhenAssignedAtPath(path, context) {
  4395. return this.object.hasEffectsWhenAssignedAtPath([this.key, ...path], context);
  4396. }
  4397. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  4398. return this.object.hasEffectsWhenCalledAtPath([this.key, ...path], callOptions, context);
  4399. }
  4400. }
  4401. class Method extends ExpressionEntity {
  4402. constructor(description) {
  4403. super();
  4404. this.description = description;
  4405. }
  4406. deoptimizeThisOnEventAtPath(event, path, thisParameter) {
  4407. if (event === EVENT_CALLED && path.length === 0 && this.description.mutatesSelfAsArray) {
  4408. thisParameter.deoptimizePath(UNKNOWN_INTEGER_PATH);
  4409. }
  4410. }
  4411. getReturnExpressionWhenCalledAtPath(path, callOptions) {
  4412. if (path.length > 0) {
  4413. return UNKNOWN_EXPRESSION;
  4414. }
  4415. return (this.description.returnsPrimitive ||
  4416. (this.description.returns === 'self'
  4417. ? callOptions.thisParam || UNKNOWN_EXPRESSION
  4418. : this.description.returns()));
  4419. }
  4420. hasEffectsWhenAccessedAtPath(path) {
  4421. return path.length > 1;
  4422. }
  4423. hasEffectsWhenAssignedAtPath(path) {
  4424. return path.length > 0;
  4425. }
  4426. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  4427. var _a, _b;
  4428. if (path.length > 0 ||
  4429. (this.description.mutatesSelfAsArray === true &&
  4430. ((_a = callOptions.thisParam) === null || _a === void 0 ? void 0 : _a.hasEffectsWhenAssignedAtPath(UNKNOWN_INTEGER_PATH, context)))) {
  4431. return true;
  4432. }
  4433. if (!this.description.callsArgs) {
  4434. return false;
  4435. }
  4436. for (const argIndex of this.description.callsArgs) {
  4437. if ((_b = callOptions.args[argIndex]) === null || _b === void 0 ? void 0 : _b.hasEffectsWhenCalledAtPath(EMPTY_PATH, {
  4438. args: NO_ARGS,
  4439. thisParam: null,
  4440. withNew: false
  4441. }, context)) {
  4442. return true;
  4443. }
  4444. }
  4445. return false;
  4446. }
  4447. includeCallArguments(context, args) {
  4448. for (const arg of args) {
  4449. arg.include(context, false);
  4450. }
  4451. }
  4452. }
  4453. const METHOD_RETURNS_BOOLEAN = [
  4454. new Method({
  4455. callsArgs: null,
  4456. mutatesSelfAsArray: false,
  4457. returns: null,
  4458. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  4459. })
  4460. ];
  4461. const METHOD_RETURNS_STRING = [
  4462. new Method({
  4463. callsArgs: null,
  4464. mutatesSelfAsArray: false,
  4465. returns: null,
  4466. returnsPrimitive: UNKNOWN_LITERAL_STRING
  4467. })
  4468. ];
  4469. const METHOD_RETURNS_NUMBER = [
  4470. new Method({
  4471. callsArgs: null,
  4472. mutatesSelfAsArray: false,
  4473. returns: null,
  4474. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  4475. })
  4476. ];
  4477. const METHOD_RETURNS_UNKNOWN = [
  4478. new Method({
  4479. callsArgs: null,
  4480. mutatesSelfAsArray: false,
  4481. returns: null,
  4482. returnsPrimitive: UNKNOWN_EXPRESSION
  4483. })
  4484. ];
  4485. const OBJECT_PROTOTYPE = new ObjectEntity({
  4486. __proto__: null,
  4487. hasOwnProperty: METHOD_RETURNS_BOOLEAN,
  4488. isPrototypeOf: METHOD_RETURNS_BOOLEAN,
  4489. propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
  4490. toLocaleString: METHOD_RETURNS_STRING,
  4491. toString: METHOD_RETURNS_STRING,
  4492. valueOf: METHOD_RETURNS_UNKNOWN
  4493. }, null, true);
  4494. class ClassNode extends NodeBase {
  4495. constructor() {
  4496. super(...arguments);
  4497. this.objectEntity = null;
  4498. }
  4499. createScope(parentScope) {
  4500. this.scope = new ChildScope(parentScope);
  4501. }
  4502. deoptimizeCache() {
  4503. this.getObjectEntity().deoptimizeAllProperties();
  4504. }
  4505. deoptimizePath(path) {
  4506. this.getObjectEntity().deoptimizePath(path);
  4507. }
  4508. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  4509. this.getObjectEntity().deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  4510. }
  4511. getLiteralValueAtPath(path, recursionTracker, origin) {
  4512. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  4513. }
  4514. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  4515. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
  4516. }
  4517. hasEffects(context) {
  4518. var _a, _b;
  4519. const initEffect = ((_a = this.superClass) === null || _a === void 0 ? void 0 : _a.hasEffects(context)) || this.body.hasEffects(context);
  4520. (_b = this.id) === null || _b === void 0 ? void 0 : _b.markDeclarationReached();
  4521. return initEffect || super.hasEffects(context);
  4522. }
  4523. hasEffectsWhenAccessedAtPath(path, context) {
  4524. return this.getObjectEntity().hasEffectsWhenAccessedAtPath(path, context);
  4525. }
  4526. hasEffectsWhenAssignedAtPath(path, context) {
  4527. return this.getObjectEntity().hasEffectsWhenAssignedAtPath(path, context);
  4528. }
  4529. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  4530. if (path.length === 0) {
  4531. return (!callOptions.withNew ||
  4532. (this.classConstructor !== null
  4533. ? this.classConstructor.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, context)
  4534. : this.superClass !== null &&
  4535. this.superClass.hasEffectsWhenCalledAtPath(path, callOptions, context)));
  4536. }
  4537. else {
  4538. return this.getObjectEntity().hasEffectsWhenCalledAtPath(path, callOptions, context);
  4539. }
  4540. }
  4541. include(context, includeChildrenRecursively) {
  4542. var _a;
  4543. this.included = true;
  4544. (_a = this.superClass) === null || _a === void 0 ? void 0 : _a.include(context, includeChildrenRecursively);
  4545. this.body.include(context, includeChildrenRecursively);
  4546. if (this.id) {
  4547. this.id.markDeclarationReached();
  4548. this.id.include();
  4549. }
  4550. }
  4551. initialise() {
  4552. var _a;
  4553. (_a = this.id) === null || _a === void 0 ? void 0 : _a.declare('class', this);
  4554. for (const method of this.body.body) {
  4555. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  4556. this.classConstructor = method;
  4557. return;
  4558. }
  4559. }
  4560. this.classConstructor = null;
  4561. }
  4562. getObjectEntity() {
  4563. if (this.objectEntity !== null) {
  4564. return this.objectEntity;
  4565. }
  4566. const staticProperties = [];
  4567. const dynamicMethods = [];
  4568. for (const definition of this.body.body) {
  4569. const properties = definition.static ? staticProperties : dynamicMethods;
  4570. const definitionKind = definition.kind;
  4571. // Note that class fields do not end up on the prototype
  4572. if (properties === dynamicMethods && !definitionKind)
  4573. continue;
  4574. const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
  4575. let key;
  4576. if (definition.computed) {
  4577. const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  4578. if (keyValue === UnknownValue) {
  4579. properties.push({ key: UnknownKey, kind, property: definition });
  4580. continue;
  4581. }
  4582. else {
  4583. key = String(keyValue);
  4584. }
  4585. }
  4586. else {
  4587. key =
  4588. definition.key instanceof Identifier
  4589. ? definition.key.name
  4590. : String(definition.key.value);
  4591. }
  4592. properties.push({ key, kind, property: definition });
  4593. }
  4594. staticProperties.unshift({
  4595. key: 'prototype',
  4596. kind: 'init',
  4597. property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, 'prototype') : OBJECT_PROTOTYPE)
  4598. });
  4599. return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
  4600. }
  4601. }
  4602. class ClassDeclaration extends ClassNode {
  4603. initialise() {
  4604. super.initialise();
  4605. if (this.id !== null) {
  4606. this.id.variable.isId = true;
  4607. }
  4608. }
  4609. parseNode(esTreeNode) {
  4610. if (esTreeNode.id !== null) {
  4611. this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope.parent);
  4612. }
  4613. super.parseNode(esTreeNode);
  4614. }
  4615. render(code, options) {
  4616. if (options.format === 'system' &&
  4617. this.id &&
  4618. options.exportNamesByVariable.has(this.id.variable)) {
  4619. code.appendLeft(this.end, `${options.compact ? '' : ' '}${getSystemExportStatement([this.id.variable], options)};`);
  4620. }
  4621. super.render(code, options);
  4622. }
  4623. }
  4624. class ArgumentsVariable extends LocalVariable {
  4625. constructor(context) {
  4626. super('arguments', null, UNKNOWN_EXPRESSION, context);
  4627. }
  4628. hasEffectsWhenAccessedAtPath(path) {
  4629. return path.length > 1;
  4630. }
  4631. hasEffectsWhenAssignedAtPath() {
  4632. return true;
  4633. }
  4634. hasEffectsWhenCalledAtPath() {
  4635. return true;
  4636. }
  4637. }
  4638. class ThisVariable extends LocalVariable {
  4639. constructor(context) {
  4640. super('this', null, null, context);
  4641. this.deoptimizedPaths = [];
  4642. this.entitiesToBeDeoptimized = new Set();
  4643. this.thisDeoptimizationList = [];
  4644. this.thisDeoptimizations = new DiscriminatedPathTracker();
  4645. }
  4646. addEntityToBeDeoptimized(entity) {
  4647. for (const path of this.deoptimizedPaths) {
  4648. entity.deoptimizePath(path);
  4649. }
  4650. for (const thisDeoptimization of this.thisDeoptimizationList) {
  4651. this.applyThisDeoptimizationEvent(entity, thisDeoptimization);
  4652. }
  4653. this.entitiesToBeDeoptimized.add(entity);
  4654. }
  4655. deoptimizePath(path) {
  4656. if (path.length === 0 ||
  4657. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  4658. return;
  4659. }
  4660. this.deoptimizedPaths.push(path);
  4661. for (const entity of this.entitiesToBeDeoptimized) {
  4662. entity.deoptimizePath(path);
  4663. }
  4664. }
  4665. deoptimizeThisOnEventAtPath(event, path, thisParameter) {
  4666. const thisDeoptimization = {
  4667. event,
  4668. path,
  4669. thisParameter
  4670. };
  4671. if (!this.thisDeoptimizations.trackEntityAtPathAndGetIfTracked(path, event, thisParameter)) {
  4672. for (const entity of this.entitiesToBeDeoptimized) {
  4673. this.applyThisDeoptimizationEvent(entity, thisDeoptimization);
  4674. }
  4675. this.thisDeoptimizationList.push(thisDeoptimization);
  4676. }
  4677. }
  4678. hasEffectsWhenAccessedAtPath(path, context) {
  4679. return (this.getInit(context).hasEffectsWhenAccessedAtPath(path, context) ||
  4680. super.hasEffectsWhenAccessedAtPath(path, context));
  4681. }
  4682. hasEffectsWhenAssignedAtPath(path, context) {
  4683. return (this.getInit(context).hasEffectsWhenAssignedAtPath(path, context) ||
  4684. super.hasEffectsWhenAssignedAtPath(path, context));
  4685. }
  4686. applyThisDeoptimizationEvent(entity, { event, path, thisParameter }) {
  4687. entity.deoptimizeThisOnEventAtPath(event, path, thisParameter === this ? entity : thisParameter, SHARED_RECURSION_TRACKER);
  4688. }
  4689. getInit(context) {
  4690. return context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION;
  4691. }
  4692. }
  4693. class SpreadElement extends NodeBase {
  4694. constructor() {
  4695. super(...arguments);
  4696. this.deoptimized = false;
  4697. }
  4698. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  4699. if (path.length > 0) {
  4700. this.argument.deoptimizeThisOnEventAtPath(event, [UnknownKey, ...path], thisParameter, recursionTracker);
  4701. }
  4702. }
  4703. hasEffects(context) {
  4704. if (!this.deoptimized)
  4705. this.applyDeoptimizations();
  4706. const { propertyReadSideEffects } = this.context.options
  4707. .treeshake;
  4708. return (this.argument.hasEffects(context) ||
  4709. (propertyReadSideEffects &&
  4710. (propertyReadSideEffects === 'always' ||
  4711. this.argument.hasEffectsWhenAccessedAtPath(UNKNOWN_PATH, context))));
  4712. }
  4713. applyDeoptimizations() {
  4714. this.deoptimized = true;
  4715. // Only properties of properties of the argument could become subject to reassignment
  4716. // This will also reassign the return values of iterators
  4717. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  4718. this.context.requestTreeshakingPass();
  4719. }
  4720. }
  4721. class ParameterScope extends ChildScope {
  4722. constructor(parent, context) {
  4723. super(parent);
  4724. this.parameters = [];
  4725. this.hasRest = false;
  4726. this.context = context;
  4727. this.hoistedBodyVarScope = new ChildScope(this);
  4728. }
  4729. /**
  4730. * Adds a parameter to this scope. Parameters must be added in the correct
  4731. * order, e.g. from left to right.
  4732. */
  4733. addParameterDeclaration(identifier) {
  4734. const name = identifier.name;
  4735. let variable = this.hoistedBodyVarScope.variables.get(name);
  4736. if (variable) {
  4737. variable.addDeclaration(identifier, null);
  4738. }
  4739. else {
  4740. variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
  4741. }
  4742. this.variables.set(name, variable);
  4743. return variable;
  4744. }
  4745. addParameterVariables(parameters, hasRest) {
  4746. this.parameters = parameters;
  4747. for (const parameterList of parameters) {
  4748. for (const parameter of parameterList) {
  4749. parameter.alwaysRendered = true;
  4750. }
  4751. }
  4752. this.hasRest = hasRest;
  4753. }
  4754. includeCallArguments(context, args) {
  4755. let calledFromTryStatement = false;
  4756. let argIncluded = false;
  4757. const restParam = this.hasRest && this.parameters[this.parameters.length - 1];
  4758. for (const checkedArg of args) {
  4759. if (checkedArg instanceof SpreadElement) {
  4760. for (const arg of args) {
  4761. arg.include(context, false);
  4762. }
  4763. break;
  4764. }
  4765. }
  4766. for (let index = args.length - 1; index >= 0; index--) {
  4767. const paramVars = this.parameters[index] || restParam;
  4768. const arg = args[index];
  4769. if (paramVars) {
  4770. calledFromTryStatement = false;
  4771. if (paramVars.length === 0) {
  4772. // handle empty destructuring
  4773. argIncluded = true;
  4774. }
  4775. else {
  4776. for (const variable of paramVars) {
  4777. if (variable.included) {
  4778. argIncluded = true;
  4779. }
  4780. if (variable.calledFromTryStatement) {
  4781. calledFromTryStatement = true;
  4782. }
  4783. }
  4784. }
  4785. }
  4786. if (!argIncluded && arg.shouldBeIncluded(context)) {
  4787. argIncluded = true;
  4788. }
  4789. if (argIncluded) {
  4790. arg.include(context, calledFromTryStatement);
  4791. }
  4792. }
  4793. }
  4794. }
  4795. class ReturnValueScope extends ParameterScope {
  4796. constructor() {
  4797. super(...arguments);
  4798. this.returnExpression = null;
  4799. this.returnExpressions = [];
  4800. }
  4801. addReturnExpression(expression) {
  4802. this.returnExpressions.push(expression);
  4803. }
  4804. getReturnExpression() {
  4805. if (this.returnExpression === null)
  4806. this.updateReturnExpression();
  4807. return this.returnExpression;
  4808. }
  4809. updateReturnExpression() {
  4810. if (this.returnExpressions.length === 1) {
  4811. this.returnExpression = this.returnExpressions[0];
  4812. }
  4813. else {
  4814. this.returnExpression = UNKNOWN_EXPRESSION;
  4815. for (const expression of this.returnExpressions) {
  4816. expression.deoptimizePath(UNKNOWN_PATH);
  4817. }
  4818. }
  4819. }
  4820. }
  4821. class FunctionScope extends ReturnValueScope {
  4822. constructor(parent, context) {
  4823. super(parent, context);
  4824. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  4825. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  4826. }
  4827. findLexicalBoundary() {
  4828. return this;
  4829. }
  4830. includeCallArguments(context, args) {
  4831. super.includeCallArguments(context, args);
  4832. if (this.argumentsVariable.included) {
  4833. for (const arg of args) {
  4834. if (!arg.included) {
  4835. arg.include(context, false);
  4836. }
  4837. }
  4838. }
  4839. }
  4840. }
  4841. class RestElement extends NodeBase {
  4842. constructor() {
  4843. super(...arguments);
  4844. this.deoptimized = false;
  4845. this.declarationInit = null;
  4846. }
  4847. addExportedVariables(variables, exportNamesByVariable) {
  4848. this.argument.addExportedVariables(variables, exportNamesByVariable);
  4849. }
  4850. declare(kind, init) {
  4851. this.declarationInit = init;
  4852. return this.argument.declare(kind, UNKNOWN_EXPRESSION);
  4853. }
  4854. deoptimizePath(path) {
  4855. path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
  4856. }
  4857. hasEffectsWhenAssignedAtPath(path, context) {
  4858. return path.length > 0 || this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context);
  4859. }
  4860. markDeclarationReached() {
  4861. this.argument.markDeclarationReached();
  4862. }
  4863. applyDeoptimizations() {
  4864. this.deoptimized = true;
  4865. if (this.declarationInit !== null) {
  4866. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  4867. this.context.requestTreeshakingPass();
  4868. }
  4869. }
  4870. }
  4871. class FunctionNode extends NodeBase {
  4872. constructor() {
  4873. super(...arguments);
  4874. this.deoptimizedReturn = false;
  4875. this.isPrototypeDeoptimized = false;
  4876. }
  4877. createScope(parentScope) {
  4878. this.scope = new FunctionScope(parentScope, this.context);
  4879. }
  4880. deoptimizePath(path) {
  4881. if (path.length === 1) {
  4882. if (path[0] === 'prototype') {
  4883. this.isPrototypeDeoptimized = true;
  4884. }
  4885. else if (path[0] === UnknownKey) {
  4886. this.isPrototypeDeoptimized = true;
  4887. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  4888. // which means the return expression needs to be reassigned as well
  4889. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  4890. }
  4891. }
  4892. }
  4893. // TODO for completeness, we should also track other events here
  4894. deoptimizeThisOnEventAtPath(event, path, thisParameter) {
  4895. if (event === EVENT_CALLED) {
  4896. if (path.length > 0) {
  4897. thisParameter.deoptimizePath(UNKNOWN_PATH);
  4898. }
  4899. else {
  4900. this.scope.thisVariable.addEntityToBeDeoptimized(thisParameter);
  4901. }
  4902. }
  4903. }
  4904. getReturnExpressionWhenCalledAtPath(path) {
  4905. if (path.length !== 0) {
  4906. return UNKNOWN_EXPRESSION;
  4907. }
  4908. if (this.async) {
  4909. if (!this.deoptimizedReturn) {
  4910. this.deoptimizedReturn = true;
  4911. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  4912. this.context.requestTreeshakingPass();
  4913. }
  4914. return UNKNOWN_EXPRESSION;
  4915. }
  4916. return this.scope.getReturnExpression();
  4917. }
  4918. hasEffects() {
  4919. return this.id !== null && this.id.hasEffects();
  4920. }
  4921. hasEffectsWhenAccessedAtPath(path) {
  4922. if (path.length <= 1)
  4923. return false;
  4924. return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
  4925. }
  4926. hasEffectsWhenAssignedAtPath(path) {
  4927. if (path.length <= 1) {
  4928. return false;
  4929. }
  4930. return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
  4931. }
  4932. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  4933. if (path.length > 0)
  4934. return true;
  4935. if (this.async) {
  4936. const { propertyReadSideEffects } = this.context.options
  4937. .treeshake;
  4938. const returnExpression = this.scope.getReturnExpression();
  4939. if (returnExpression.hasEffectsWhenCalledAtPath(['then'], { args: NO_ARGS, thisParam: null, withNew: false }, context) ||
  4940. (propertyReadSideEffects &&
  4941. (propertyReadSideEffects === 'always' ||
  4942. returnExpression.hasEffectsWhenAccessedAtPath(['then'], context)))) {
  4943. return true;
  4944. }
  4945. }
  4946. for (const param of this.params) {
  4947. if (param.hasEffects(context))
  4948. return true;
  4949. }
  4950. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  4951. context.replacedVariableInits.set(this.scope.thisVariable, callOptions.withNew
  4952. ? new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE)
  4953. : UNKNOWN_EXPRESSION);
  4954. const { brokenFlow, ignore } = context;
  4955. context.ignore = {
  4956. breaks: false,
  4957. continues: false,
  4958. labels: new Set(),
  4959. returnYield: true
  4960. };
  4961. if (this.body.hasEffects(context))
  4962. return true;
  4963. context.brokenFlow = brokenFlow;
  4964. if (thisInit) {
  4965. context.replacedVariableInits.set(this.scope.thisVariable, thisInit);
  4966. }
  4967. else {
  4968. context.replacedVariableInits.delete(this.scope.thisVariable);
  4969. }
  4970. context.ignore = ignore;
  4971. return false;
  4972. }
  4973. include(context, includeChildrenRecursively) {
  4974. this.included = true;
  4975. if (this.id)
  4976. this.id.include();
  4977. const hasArguments = this.scope.argumentsVariable.included;
  4978. for (const param of this.params) {
  4979. if (!(param instanceof Identifier) || hasArguments) {
  4980. param.include(context, includeChildrenRecursively);
  4981. }
  4982. }
  4983. const { brokenFlow } = context;
  4984. context.brokenFlow = BROKEN_FLOW_NONE;
  4985. this.body.include(context, includeChildrenRecursively);
  4986. context.brokenFlow = brokenFlow;
  4987. }
  4988. includeCallArguments(context, args) {
  4989. this.scope.includeCallArguments(context, args);
  4990. }
  4991. initialise() {
  4992. if (this.id !== null) {
  4993. this.id.declare('function', this);
  4994. }
  4995. this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
  4996. this.body.addImplicitReturnExpressionToScope();
  4997. }
  4998. parseNode(esTreeNode) {
  4999. this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
  5000. super.parseNode(esTreeNode);
  5001. }
  5002. }
  5003. FunctionNode.prototype.preventChildBlockScope = true;
  5004. class FunctionDeclaration extends FunctionNode {
  5005. initialise() {
  5006. super.initialise();
  5007. if (this.id !== null) {
  5008. this.id.variable.isId = true;
  5009. }
  5010. }
  5011. parseNode(esTreeNode) {
  5012. if (esTreeNode.id !== null) {
  5013. this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope.parent);
  5014. }
  5015. super.parseNode(esTreeNode);
  5016. }
  5017. }
  5018. // The header ends at the first non-white-space after "default"
  5019. function getDeclarationStart(code, start) {
  5020. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  5021. }
  5022. function getIdInsertPosition(code, declarationKeyword, endMarker, start) {
  5023. const declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
  5024. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, endMarker, declarationEnd));
  5025. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  5026. if (generatorStarPos === -1) {
  5027. return declarationEnd;
  5028. }
  5029. return declarationEnd + generatorStarPos + 1;
  5030. }
  5031. class ExportDefaultDeclaration extends NodeBase {
  5032. include(context, includeChildrenRecursively) {
  5033. super.include(context, includeChildrenRecursively);
  5034. if (includeChildrenRecursively) {
  5035. this.context.includeVariableInModule(this.variable);
  5036. }
  5037. }
  5038. initialise() {
  5039. const declaration = this.declaration;
  5040. this.declarationName =
  5041. (declaration.id && declaration.id.name) || this.declaration.name;
  5042. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
  5043. this.context.addExport(this);
  5044. }
  5045. render(code, options, nodeRenderOptions) {
  5046. const { start, end } = nodeRenderOptions;
  5047. const declarationStart = getDeclarationStart(code.original, this.start);
  5048. if (this.declaration instanceof FunctionDeclaration) {
  5049. this.renderNamedDeclaration(code, declarationStart, 'function', '(', this.declaration.id === null, options);
  5050. }
  5051. else if (this.declaration instanceof ClassDeclaration) {
  5052. this.renderNamedDeclaration(code, declarationStart, 'class', '{', this.declaration.id === null, options);
  5053. }
  5054. else if (this.variable.getOriginalVariable() !== this.variable) {
  5055. // Remove altogether to prevent re-declaring the same variable
  5056. treeshakeNode(this, code, start, end);
  5057. return;
  5058. }
  5059. else if (this.variable.included) {
  5060. this.renderVariableDeclaration(code, declarationStart, options);
  5061. }
  5062. else {
  5063. code.remove(this.start, declarationStart);
  5064. this.declaration.render(code, options, {
  5065. renderedSurroundingElement: ExpressionStatement$1
  5066. });
  5067. if (code.original[this.end - 1] !== ';') {
  5068. code.appendLeft(this.end, ';');
  5069. }
  5070. return;
  5071. }
  5072. this.declaration.render(code, options);
  5073. }
  5074. renderNamedDeclaration(code, declarationStart, declarationKeyword, endMarker, needsId, options) {
  5075. const name = this.variable.getName();
  5076. // Remove `export default`
  5077. code.remove(this.start, declarationStart);
  5078. if (needsId) {
  5079. code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, endMarker, declarationStart), ` ${name}`);
  5080. }
  5081. if (options.format === 'system' &&
  5082. this.declaration instanceof ClassDeclaration &&
  5083. options.exportNamesByVariable.has(this.variable)) {
  5084. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  5085. }
  5086. }
  5087. renderVariableDeclaration(code, declarationStart, options) {
  5088. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  5089. const systemExportNames = options.format === 'system' && options.exportNamesByVariable.get(this.variable);
  5090. if (systemExportNames) {
  5091. code.overwrite(this.start, declarationStart, `${options.varOrConst} ${this.variable.getName()} = exports('${systemExportNames[0]}', `);
  5092. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  5093. }
  5094. else {
  5095. code.overwrite(this.start, declarationStart, `${options.varOrConst} ${this.variable.getName()} = `);
  5096. if (!hasTrailingSemicolon) {
  5097. code.appendLeft(this.end, ';');
  5098. }
  5099. }
  5100. }
  5101. }
  5102. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  5103. class Literal extends NodeBase {
  5104. deoptimizeThisOnEventAtPath() { }
  5105. getLiteralValueAtPath(path) {
  5106. if (path.length > 0 ||
  5107. // unknown literals can also be null but do not start with an "n"
  5108. (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
  5109. typeof this.value === 'bigint' ||
  5110. // to support shims for regular expressions
  5111. this.context.code.charCodeAt(this.start) === 47) {
  5112. return UnknownValue;
  5113. }
  5114. return this.value;
  5115. }
  5116. getReturnExpressionWhenCalledAtPath(path) {
  5117. if (path.length !== 1)
  5118. return UNKNOWN_EXPRESSION;
  5119. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  5120. }
  5121. hasEffectsWhenAccessedAtPath(path) {
  5122. if (this.value === null) {
  5123. return path.length > 0;
  5124. }
  5125. return path.length > 1;
  5126. }
  5127. hasEffectsWhenAssignedAtPath(path) {
  5128. return path.length > 0;
  5129. }
  5130. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  5131. if (path.length === 1) {
  5132. return hasMemberEffectWhenCalled(this.members, path[0], callOptions, context);
  5133. }
  5134. return true;
  5135. }
  5136. initialise() {
  5137. this.members = getLiteralMembersForValue(this.value);
  5138. }
  5139. parseNode(esTreeNode) {
  5140. this.value = esTreeNode.value;
  5141. this.regex = esTreeNode.regex;
  5142. super.parseNode(esTreeNode);
  5143. }
  5144. render(code) {
  5145. if (typeof this.value === 'string') {
  5146. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  5147. }
  5148. }
  5149. }
  5150. class Program extends NodeBase {
  5151. constructor() {
  5152. super(...arguments);
  5153. this.hasCachedEffect = false;
  5154. }
  5155. hasEffects(context) {
  5156. // We are caching here to later more efficiently identify side-effect-free modules
  5157. if (this.hasCachedEffect)
  5158. return true;
  5159. for (const node of this.body) {
  5160. if (node.hasEffects(context)) {
  5161. return (this.hasCachedEffect = true);
  5162. }
  5163. }
  5164. return false;
  5165. }
  5166. include(context, includeChildrenRecursively) {
  5167. this.included = true;
  5168. for (const node of this.body) {
  5169. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  5170. node.include(context, includeChildrenRecursively);
  5171. }
  5172. }
  5173. }
  5174. render(code, options) {
  5175. if (this.body.length) {
  5176. renderStatementList(this.body, code, this.start, this.end, options);
  5177. }
  5178. else {
  5179. super.render(code, options);
  5180. }
  5181. }
  5182. }
  5183. class TemplateLiteral extends NodeBase {
  5184. getLiteralValueAtPath(path) {
  5185. if (path.length > 0 || this.quasis.length !== 1) {
  5186. return UnknownValue;
  5187. }
  5188. return this.quasis[0].value.cooked;
  5189. }
  5190. render(code, options) {
  5191. code.indentExclusionRanges.push([this.start, this.end]);
  5192. super.render(code, options);
  5193. }
  5194. }
  5195. function isReassignedExportsMember(variable, exportNamesByVariable) {
  5196. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  5197. }
  5198. function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
  5199. for (const declarator of declarations) {
  5200. if (!declarator.id.included)
  5201. return false;
  5202. if (declarator.id.type === Identifier$1) {
  5203. if (exportNamesByVariable.has(declarator.id.variable))
  5204. return false;
  5205. }
  5206. else {
  5207. const exportedVariables = [];
  5208. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  5209. if (exportedVariables.length > 0)
  5210. return false;
  5211. }
  5212. }
  5213. return true;
  5214. }
  5215. class VariableDeclaration extends NodeBase {
  5216. deoptimizePath() {
  5217. for (const declarator of this.declarations) {
  5218. declarator.deoptimizePath(EMPTY_PATH);
  5219. }
  5220. }
  5221. hasEffectsWhenAssignedAtPath() {
  5222. return false;
  5223. }
  5224. include(context, includeChildrenRecursively) {
  5225. this.included = true;
  5226. for (const declarator of this.declarations) {
  5227. if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
  5228. declarator.include(context, includeChildrenRecursively);
  5229. }
  5230. }
  5231. includeAsSingleStatement(context, includeChildrenRecursively) {
  5232. this.included = true;
  5233. for (const declarator of this.declarations) {
  5234. if (includeChildrenRecursively || declarator.shouldBeIncluded(context)) {
  5235. declarator.include(context, includeChildrenRecursively);
  5236. declarator.id.include(context, includeChildrenRecursively);
  5237. }
  5238. }
  5239. }
  5240. initialise() {
  5241. for (const declarator of this.declarations) {
  5242. declarator.declareDeclarator(this.kind);
  5243. }
  5244. }
  5245. render(code, options, nodeRenderOptions = BLANK) {
  5246. if (areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
  5247. for (const declarator of this.declarations) {
  5248. declarator.render(code, options);
  5249. }
  5250. if (!nodeRenderOptions.isNoStatement &&
  5251. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  5252. code.appendLeft(this.end, ';');
  5253. }
  5254. }
  5255. else {
  5256. this.renderReplacedDeclarations(code, options, nodeRenderOptions);
  5257. }
  5258. }
  5259. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options, isNoStatement) {
  5260. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  5261. code.remove(this.end - 1, this.end);
  5262. }
  5263. if (!isNoStatement) {
  5264. separatorString += ';';
  5265. }
  5266. if (lastSeparatorPos !== null) {
  5267. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  5268. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  5269. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  5270. actualContentEnd--;
  5271. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  5272. actualContentEnd--;
  5273. }
  5274. }
  5275. if (actualContentEnd === lastSeparatorPos + 1) {
  5276. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  5277. }
  5278. else {
  5279. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  5280. code.remove(actualContentEnd, renderedContentEnd);
  5281. }
  5282. }
  5283. else {
  5284. code.appendLeft(renderedContentEnd, separatorString);
  5285. }
  5286. if (systemPatternExports.length > 0) {
  5287. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  5288. }
  5289. }
  5290. renderReplacedDeclarations(code, options, { isNoStatement }) {
  5291. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  5292. let actualContentEnd, renderedContentEnd;
  5293. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  5294. let lastSeparatorPos = renderedContentEnd - 1;
  5295. code.remove(this.start, lastSeparatorPos);
  5296. let isInDeclaration = false;
  5297. let hasRenderedContent = false;
  5298. let separatorString = '', leadingString, nextSeparatorString;
  5299. const aggregatedSystemExports = [];
  5300. const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
  5301. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  5302. if (!node.included) {
  5303. code.remove(start, end);
  5304. continue;
  5305. }
  5306. node.render(code, options);
  5307. leadingString = '';
  5308. nextSeparatorString = '';
  5309. if (!node.id.included ||
  5310. (node.id instanceof Identifier &&
  5311. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  5312. if (hasRenderedContent) {
  5313. separatorString += ';';
  5314. }
  5315. isInDeclaration = false;
  5316. }
  5317. else {
  5318. if (singleSystemExport && singleSystemExport === node.id.variable) {
  5319. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  5320. renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
  5321. }
  5322. if (isInDeclaration) {
  5323. separatorString += ',';
  5324. }
  5325. else {
  5326. if (hasRenderedContent) {
  5327. separatorString += ';';
  5328. }
  5329. leadingString += `${this.kind} `;
  5330. isInDeclaration = true;
  5331. }
  5332. }
  5333. if (renderedContentEnd === lastSeparatorPos + 1) {
  5334. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  5335. }
  5336. else {
  5337. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  5338. code.appendLeft(renderedContentEnd, leadingString);
  5339. }
  5340. actualContentEnd = contentEnd;
  5341. renderedContentEnd = end;
  5342. hasRenderedContent = true;
  5343. lastSeparatorPos = separator;
  5344. separatorString = nextSeparatorString;
  5345. }
  5346. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options, isNoStatement);
  5347. }
  5348. }
  5349. function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
  5350. var _a;
  5351. let singleSystemExport = null;
  5352. if (options.format === 'system') {
  5353. for (const { node } of separatedNodes) {
  5354. if (node.id instanceof Identifier &&
  5355. node.init &&
  5356. aggregatedSystemExports.length === 0 &&
  5357. ((_a = options.exportNamesByVariable.get(node.id.variable)) === null || _a === void 0 ? void 0 : _a.length) === 1) {
  5358. singleSystemExport = node.id.variable;
  5359. aggregatedSystemExports.push(singleSystemExport);
  5360. }
  5361. else {
  5362. node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
  5363. }
  5364. }
  5365. if (aggregatedSystemExports.length > 1) {
  5366. singleSystemExport = null;
  5367. }
  5368. else if (singleSystemExport) {
  5369. aggregatedSystemExports.length = 0;
  5370. }
  5371. }
  5372. return singleSystemExport;
  5373. }
  5374. const NEW_ARRAY_PROPERTIES = [
  5375. { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
  5376. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  5377. ];
  5378. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
  5379. new Method({
  5380. callsArgs: [0],
  5381. mutatesSelfAsArray: 'deopt-only',
  5382. returns: null,
  5383. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  5384. })
  5385. ];
  5386. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
  5387. new Method({
  5388. callsArgs: [0],
  5389. mutatesSelfAsArray: 'deopt-only',
  5390. returns: null,
  5391. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  5392. })
  5393. ];
  5394. const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
  5395. new Method({
  5396. callsArgs: null,
  5397. mutatesSelfAsArray: true,
  5398. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  5399. returnsPrimitive: null
  5400. })
  5401. ];
  5402. const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  5403. new Method({
  5404. callsArgs: null,
  5405. mutatesSelfAsArray: 'deopt-only',
  5406. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  5407. returnsPrimitive: null
  5408. })
  5409. ];
  5410. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  5411. new Method({
  5412. callsArgs: [0],
  5413. mutatesSelfAsArray: 'deopt-only',
  5414. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  5415. returnsPrimitive: null
  5416. })
  5417. ];
  5418. const METHOD_MUTATES_SELF_RETURNS_NUMBER = [
  5419. new Method({
  5420. callsArgs: null,
  5421. mutatesSelfAsArray: true,
  5422. returns: null,
  5423. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  5424. })
  5425. ];
  5426. const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
  5427. new Method({
  5428. callsArgs: null,
  5429. mutatesSelfAsArray: true,
  5430. returns: null,
  5431. returnsPrimitive: UNKNOWN_EXPRESSION
  5432. })
  5433. ];
  5434. const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
  5435. new Method({
  5436. callsArgs: null,
  5437. mutatesSelfAsArray: 'deopt-only',
  5438. returns: null,
  5439. returnsPrimitive: UNKNOWN_EXPRESSION
  5440. })
  5441. ];
  5442. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
  5443. new Method({
  5444. callsArgs: [0],
  5445. mutatesSelfAsArray: 'deopt-only',
  5446. returns: null,
  5447. returnsPrimitive: UNKNOWN_EXPRESSION
  5448. })
  5449. ];
  5450. const METHOD_MUTATES_SELF_RETURNS_SELF = [
  5451. new Method({
  5452. callsArgs: null,
  5453. mutatesSelfAsArray: true,
  5454. returns: 'self',
  5455. returnsPrimitive: null
  5456. })
  5457. ];
  5458. const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
  5459. new Method({
  5460. callsArgs: [0],
  5461. mutatesSelfAsArray: true,
  5462. returns: 'self',
  5463. returnsPrimitive: null
  5464. })
  5465. ];
  5466. const ARRAY_PROTOTYPE = new ObjectEntity({
  5467. __proto__: null,
  5468. // We assume that accessors have effects as we do not track the accessed value afterwards
  5469. at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
  5470. concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5471. copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
  5472. entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5473. every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  5474. fill: METHOD_MUTATES_SELF_RETURNS_SELF,
  5475. filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5476. find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5477. findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  5478. forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5479. includes: METHOD_RETURNS_BOOLEAN,
  5480. indexOf: METHOD_RETURNS_NUMBER,
  5481. join: METHOD_RETURNS_STRING,
  5482. keys: METHOD_RETURNS_UNKNOWN,
  5483. lastIndexOf: METHOD_RETURNS_NUMBER,
  5484. map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5485. pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  5486. push: METHOD_MUTATES_SELF_RETURNS_NUMBER,
  5487. reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5488. reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  5489. reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
  5490. shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  5491. slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  5492. some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  5493. sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
  5494. splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
  5495. unshift: METHOD_MUTATES_SELF_RETURNS_NUMBER,
  5496. values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
  5497. }, OBJECT_PROTOTYPE, true);
  5498. class ArrayExpression extends NodeBase {
  5499. constructor() {
  5500. super(...arguments);
  5501. this.objectEntity = null;
  5502. }
  5503. deoptimizePath(path) {
  5504. this.getObjectEntity().deoptimizePath(path);
  5505. }
  5506. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  5507. this.getObjectEntity().deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  5508. }
  5509. getLiteralValueAtPath(path, recursionTracker, origin) {
  5510. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  5511. }
  5512. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  5513. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
  5514. }
  5515. hasEffectsWhenAccessedAtPath(path, context) {
  5516. return this.getObjectEntity().hasEffectsWhenAccessedAtPath(path, context);
  5517. }
  5518. hasEffectsWhenAssignedAtPath(path, context) {
  5519. return this.getObjectEntity().hasEffectsWhenAssignedAtPath(path, context);
  5520. }
  5521. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  5522. return this.getObjectEntity().hasEffectsWhenCalledAtPath(path, callOptions, context);
  5523. }
  5524. getObjectEntity() {
  5525. if (this.objectEntity !== null) {
  5526. return this.objectEntity;
  5527. }
  5528. const properties = [
  5529. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  5530. ];
  5531. let hasSpread = false;
  5532. for (let index = 0; index < this.elements.length; index++) {
  5533. const element = this.elements[index];
  5534. if (element instanceof SpreadElement || hasSpread) {
  5535. if (element) {
  5536. hasSpread = true;
  5537. properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
  5538. }
  5539. }
  5540. else if (!element) {
  5541. properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
  5542. }
  5543. else {
  5544. properties.push({ key: String(index), kind: 'init', property: element });
  5545. }
  5546. }
  5547. return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
  5548. }
  5549. }
  5550. class ArrayPattern extends NodeBase {
  5551. addExportedVariables(variables, exportNamesByVariable) {
  5552. for (const element of this.elements) {
  5553. if (element !== null) {
  5554. element.addExportedVariables(variables, exportNamesByVariable);
  5555. }
  5556. }
  5557. }
  5558. declare(kind) {
  5559. const variables = [];
  5560. for (const element of this.elements) {
  5561. if (element !== null) {
  5562. variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
  5563. }
  5564. }
  5565. return variables;
  5566. }
  5567. deoptimizePath(path) {
  5568. if (path.length === 0) {
  5569. for (const element of this.elements) {
  5570. if (element !== null) {
  5571. element.deoptimizePath(path);
  5572. }
  5573. }
  5574. }
  5575. }
  5576. hasEffectsWhenAssignedAtPath(path, context) {
  5577. if (path.length > 0)
  5578. return true;
  5579. for (const element of this.elements) {
  5580. if (element !== null && element.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))
  5581. return true;
  5582. }
  5583. return false;
  5584. }
  5585. markDeclarationReached() {
  5586. for (const element of this.elements) {
  5587. if (element !== null) {
  5588. element.markDeclarationReached();
  5589. }
  5590. }
  5591. }
  5592. }
  5593. class BlockScope extends ChildScope {
  5594. addDeclaration(identifier, context, init, isHoisted) {
  5595. if (isHoisted) {
  5596. const variable = this.parent.addDeclaration(identifier, context, init, isHoisted);
  5597. // Necessary to make sure the init is deoptimized for conditional declarations.
  5598. // We cannot call deoptimizePath here.
  5599. variable.markInitializersForDeoptimization();
  5600. return variable;
  5601. }
  5602. else {
  5603. return super.addDeclaration(identifier, context, init, false);
  5604. }
  5605. }
  5606. }
  5607. class ExpressionStatement extends NodeBase {
  5608. initialise() {
  5609. if (this.directive &&
  5610. this.directive !== 'use strict' &&
  5611. this.parent.type === Program$1) {
  5612. this.context.warn(
  5613. // This is necessary, because either way (deleting or not) can lead to errors.
  5614. {
  5615. code: 'MODULE_LEVEL_DIRECTIVE',
  5616. message: `Module level directives cause errors when bundled, '${this.directive}' was ignored.`
  5617. }, this.start);
  5618. }
  5619. }
  5620. render(code, options) {
  5621. super.render(code, options);
  5622. if (this.included)
  5623. this.insertSemicolon(code);
  5624. }
  5625. shouldBeIncluded(context) {
  5626. if (this.directive && this.directive !== 'use strict')
  5627. return this.parent.type !== Program$1;
  5628. return super.shouldBeIncluded(context);
  5629. }
  5630. }
  5631. class BlockStatement extends NodeBase {
  5632. constructor() {
  5633. super(...arguments);
  5634. this.directlyIncluded = false;
  5635. }
  5636. addImplicitReturnExpressionToScope() {
  5637. const lastStatement = this.body[this.body.length - 1];
  5638. if (!lastStatement || lastStatement.type !== ReturnStatement$1) {
  5639. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  5640. }
  5641. }
  5642. createScope(parentScope) {
  5643. this.scope = this.parent.preventChildBlockScope
  5644. ? parentScope
  5645. : new BlockScope(parentScope);
  5646. }
  5647. hasEffects(context) {
  5648. if (this.deoptimizeBody)
  5649. return true;
  5650. for (const node of this.body) {
  5651. if (node.hasEffects(context))
  5652. return true;
  5653. if (context.brokenFlow)
  5654. break;
  5655. }
  5656. return false;
  5657. }
  5658. include(context, includeChildrenRecursively) {
  5659. if (!this.deoptimizeBody || !this.directlyIncluded) {
  5660. this.included = true;
  5661. this.directlyIncluded = true;
  5662. if (this.deoptimizeBody)
  5663. includeChildrenRecursively = true;
  5664. for (const node of this.body) {
  5665. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  5666. node.include(context, includeChildrenRecursively);
  5667. }
  5668. }
  5669. }
  5670. initialise() {
  5671. const firstBodyStatement = this.body[0];
  5672. this.deoptimizeBody =
  5673. firstBodyStatement instanceof ExpressionStatement &&
  5674. firstBodyStatement.directive === 'use asm';
  5675. }
  5676. render(code, options) {
  5677. if (this.body.length) {
  5678. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  5679. }
  5680. else {
  5681. super.render(code, options);
  5682. }
  5683. }
  5684. }
  5685. class ArrowFunctionExpression extends NodeBase {
  5686. constructor() {
  5687. super(...arguments);
  5688. this.deoptimizedReturn = false;
  5689. }
  5690. createScope(parentScope) {
  5691. this.scope = new ReturnValueScope(parentScope, this.context);
  5692. }
  5693. deoptimizePath(path) {
  5694. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  5695. // which means the return expression needs to be reassigned
  5696. if (path.length === 1 && path[0] === UnknownKey) {
  5697. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  5698. }
  5699. }
  5700. // Arrow functions do not mutate their context
  5701. deoptimizeThisOnEventAtPath() { }
  5702. getReturnExpressionWhenCalledAtPath(path) {
  5703. if (path.length !== 0) {
  5704. return UNKNOWN_EXPRESSION;
  5705. }
  5706. if (this.async) {
  5707. if (!this.deoptimizedReturn) {
  5708. this.deoptimizedReturn = true;
  5709. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  5710. this.context.requestTreeshakingPass();
  5711. }
  5712. return UNKNOWN_EXPRESSION;
  5713. }
  5714. return this.scope.getReturnExpression();
  5715. }
  5716. hasEffects() {
  5717. return false;
  5718. }
  5719. hasEffectsWhenAccessedAtPath(path) {
  5720. return path.length > 1;
  5721. }
  5722. hasEffectsWhenAssignedAtPath(path) {
  5723. return path.length > 1;
  5724. }
  5725. hasEffectsWhenCalledAtPath(path, _callOptions, context) {
  5726. if (path.length > 0)
  5727. return true;
  5728. if (this.async) {
  5729. const { propertyReadSideEffects } = this.context.options
  5730. .treeshake;
  5731. const returnExpression = this.scope.getReturnExpression();
  5732. if (returnExpression.hasEffectsWhenCalledAtPath(['then'], { args: NO_ARGS, thisParam: null, withNew: false }, context) ||
  5733. (propertyReadSideEffects &&
  5734. (propertyReadSideEffects === 'always' ||
  5735. returnExpression.hasEffectsWhenAccessedAtPath(['then'], context)))) {
  5736. return true;
  5737. }
  5738. }
  5739. for (const param of this.params) {
  5740. if (param.hasEffects(context))
  5741. return true;
  5742. }
  5743. const { ignore, brokenFlow } = context;
  5744. context.ignore = {
  5745. breaks: false,
  5746. continues: false,
  5747. labels: new Set(),
  5748. returnYield: true
  5749. };
  5750. if (this.body.hasEffects(context))
  5751. return true;
  5752. context.ignore = ignore;
  5753. context.brokenFlow = brokenFlow;
  5754. return false;
  5755. }
  5756. include(context, includeChildrenRecursively) {
  5757. this.included = true;
  5758. for (const param of this.params) {
  5759. if (!(param instanceof Identifier)) {
  5760. param.include(context, includeChildrenRecursively);
  5761. }
  5762. }
  5763. const { brokenFlow } = context;
  5764. context.brokenFlow = BROKEN_FLOW_NONE;
  5765. this.body.include(context, includeChildrenRecursively);
  5766. context.brokenFlow = brokenFlow;
  5767. }
  5768. includeCallArguments(context, args) {
  5769. this.scope.includeCallArguments(context, args);
  5770. }
  5771. initialise() {
  5772. this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
  5773. if (this.body instanceof BlockStatement) {
  5774. this.body.addImplicitReturnExpressionToScope();
  5775. }
  5776. else {
  5777. this.scope.addReturnExpression(this.body);
  5778. }
  5779. }
  5780. parseNode(esTreeNode) {
  5781. if (esTreeNode.body.type === BlockStatement$1) {
  5782. this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
  5783. }
  5784. super.parseNode(esTreeNode);
  5785. }
  5786. }
  5787. ArrowFunctionExpression.prototype.preventChildBlockScope = true;
  5788. class ObjectPattern extends NodeBase {
  5789. addExportedVariables(variables, exportNamesByVariable) {
  5790. for (const property of this.properties) {
  5791. if (property.type === Property$1) {
  5792. property.value.addExportedVariables(variables, exportNamesByVariable);
  5793. }
  5794. else {
  5795. property.argument.addExportedVariables(variables, exportNamesByVariable);
  5796. }
  5797. }
  5798. }
  5799. declare(kind, init) {
  5800. const variables = [];
  5801. for (const property of this.properties) {
  5802. variables.push(...property.declare(kind, init));
  5803. }
  5804. return variables;
  5805. }
  5806. deoptimizePath(path) {
  5807. if (path.length === 0) {
  5808. for (const property of this.properties) {
  5809. property.deoptimizePath(path);
  5810. }
  5811. }
  5812. }
  5813. hasEffectsWhenAssignedAtPath(path, context) {
  5814. if (path.length > 0)
  5815. return true;
  5816. for (const property of this.properties) {
  5817. if (property.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))
  5818. return true;
  5819. }
  5820. return false;
  5821. }
  5822. markDeclarationReached() {
  5823. for (const property of this.properties) {
  5824. property.markDeclarationReached();
  5825. }
  5826. }
  5827. }
  5828. class AssignmentExpression extends NodeBase {
  5829. constructor() {
  5830. super(...arguments);
  5831. this.deoptimized = false;
  5832. }
  5833. hasEffects(context) {
  5834. if (!this.deoptimized)
  5835. this.applyDeoptimizations();
  5836. return (this.right.hasEffects(context) ||
  5837. this.left.hasEffects(context) ||
  5838. this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context));
  5839. }
  5840. hasEffectsWhenAccessedAtPath(path, context) {
  5841. return path.length > 0 && this.right.hasEffectsWhenAccessedAtPath(path, context);
  5842. }
  5843. include(context, includeChildrenRecursively) {
  5844. if (!this.deoptimized)
  5845. this.applyDeoptimizations();
  5846. this.included = true;
  5847. let hasEffectsContext;
  5848. if (includeChildrenRecursively ||
  5849. this.operator !== '=' ||
  5850. this.left.included ||
  5851. ((hasEffectsContext = createHasEffectsContext()),
  5852. this.left.hasEffects(hasEffectsContext) ||
  5853. this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, hasEffectsContext))) {
  5854. this.left.include(context, includeChildrenRecursively);
  5855. }
  5856. this.right.include(context, includeChildrenRecursively);
  5857. }
  5858. render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  5859. if (this.left.included) {
  5860. this.left.render(code, options);
  5861. this.right.render(code, options);
  5862. }
  5863. else {
  5864. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', this.left.end) + 1);
  5865. code.remove(this.start, inclusionStart);
  5866. if (preventASI) {
  5867. removeLineBreaks(code, inclusionStart, this.right.start);
  5868. }
  5869. this.right.render(code, options, {
  5870. renderedParentType: renderedParentType || this.parent.type,
  5871. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  5872. });
  5873. }
  5874. if (options.format === 'system') {
  5875. if (this.left instanceof Identifier) {
  5876. const variable = this.left.variable;
  5877. const exportNames = options.exportNamesByVariable.get(variable);
  5878. if (exportNames) {
  5879. if (exportNames.length === 1) {
  5880. renderSystemExportExpression(variable, this.start, this.end, code, options);
  5881. }
  5882. else {
  5883. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options);
  5884. }
  5885. return;
  5886. }
  5887. }
  5888. else {
  5889. const systemPatternExports = [];
  5890. this.left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  5891. if (systemPatternExports.length > 0) {
  5892. renderSystemExportFunction(systemPatternExports, this.start, this.end, renderedSurroundingElement === ExpressionStatement$1, code, options);
  5893. return;
  5894. }
  5895. }
  5896. }
  5897. if (this.left.included &&
  5898. this.left instanceof ObjectPattern &&
  5899. (renderedSurroundingElement === ExpressionStatement$1 ||
  5900. renderedSurroundingElement === ArrowFunctionExpression$1)) {
  5901. code.appendRight(this.start, '(');
  5902. code.prependLeft(this.end, ')');
  5903. }
  5904. }
  5905. applyDeoptimizations() {
  5906. this.deoptimized = true;
  5907. this.left.deoptimizePath(EMPTY_PATH);
  5908. this.right.deoptimizePath(UNKNOWN_PATH);
  5909. this.context.requestTreeshakingPass();
  5910. }
  5911. }
  5912. class AssignmentPattern extends NodeBase {
  5913. constructor() {
  5914. super(...arguments);
  5915. this.deoptimized = false;
  5916. }
  5917. addExportedVariables(variables, exportNamesByVariable) {
  5918. this.left.addExportedVariables(variables, exportNamesByVariable);
  5919. }
  5920. declare(kind, init) {
  5921. return this.left.declare(kind, init);
  5922. }
  5923. deoptimizePath(path) {
  5924. path.length === 0 && this.left.deoptimizePath(path);
  5925. }
  5926. hasEffectsWhenAssignedAtPath(path, context) {
  5927. return path.length > 0 || this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context);
  5928. }
  5929. markDeclarationReached() {
  5930. this.left.markDeclarationReached();
  5931. }
  5932. render(code, options, { isShorthandProperty } = BLANK) {
  5933. this.left.render(code, options, { isShorthandProperty });
  5934. this.right.render(code, options);
  5935. }
  5936. applyDeoptimizations() {
  5937. this.deoptimized = true;
  5938. this.left.deoptimizePath(EMPTY_PATH);
  5939. this.right.deoptimizePath(UNKNOWN_PATH);
  5940. this.context.requestTreeshakingPass();
  5941. }
  5942. }
  5943. class AwaitExpression extends NodeBase {
  5944. constructor() {
  5945. super(...arguments);
  5946. this.deoptimized = false;
  5947. }
  5948. hasEffects() {
  5949. if (!this.deoptimized)
  5950. this.applyDeoptimizations();
  5951. return true;
  5952. }
  5953. include(context, includeChildrenRecursively) {
  5954. if (!this.deoptimized)
  5955. this.applyDeoptimizations();
  5956. if (!this.included) {
  5957. this.included = true;
  5958. checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
  5959. let parent = this.parent;
  5960. do {
  5961. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  5962. break checkTopLevelAwait;
  5963. } while ((parent = parent.parent));
  5964. this.context.usesTopLevelAwait = true;
  5965. }
  5966. }
  5967. this.argument.include(context, includeChildrenRecursively);
  5968. }
  5969. applyDeoptimizations() {
  5970. this.deoptimized = true;
  5971. this.argument.deoptimizePath(UNKNOWN_PATH);
  5972. this.context.requestTreeshakingPass();
  5973. }
  5974. }
  5975. const binaryOperators = {
  5976. '!=': (left, right) => left != right,
  5977. '!==': (left, right) => left !== right,
  5978. '%': (left, right) => left % right,
  5979. '&': (left, right) => left & right,
  5980. '*': (left, right) => left * right,
  5981. // At the moment, "**" will be transpiled to Math.pow
  5982. '**': (left, right) => left ** right,
  5983. '+': (left, right) => left + right,
  5984. '-': (left, right) => left - right,
  5985. '/': (left, right) => left / right,
  5986. '<': (left, right) => left < right,
  5987. '<<': (left, right) => left << right,
  5988. '<=': (left, right) => left <= right,
  5989. '==': (left, right) => left == right,
  5990. '===': (left, right) => left === right,
  5991. '>': (left, right) => left > right,
  5992. '>=': (left, right) => left >= right,
  5993. '>>': (left, right) => left >> right,
  5994. '>>>': (left, right) => left >>> right,
  5995. '^': (left, right) => left ^ right,
  5996. in: () => UnknownValue,
  5997. instanceof: () => UnknownValue,
  5998. '|': (left, right) => left | right
  5999. };
  6000. class BinaryExpression extends NodeBase {
  6001. deoptimizeCache() { }
  6002. getLiteralValueAtPath(path, recursionTracker, origin) {
  6003. if (path.length > 0)
  6004. return UnknownValue;
  6005. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  6006. if (leftValue === UnknownValue)
  6007. return UnknownValue;
  6008. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  6009. if (rightValue === UnknownValue)
  6010. return UnknownValue;
  6011. const operatorFn = binaryOperators[this.operator];
  6012. if (!operatorFn)
  6013. return UnknownValue;
  6014. return operatorFn(leftValue, rightValue);
  6015. }
  6016. hasEffects(context) {
  6017. // support some implicit type coercion runtime errors
  6018. if (this.operator === '+' &&
  6019. this.parent instanceof ExpressionStatement &&
  6020. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '')
  6021. return true;
  6022. return super.hasEffects(context);
  6023. }
  6024. hasEffectsWhenAccessedAtPath(path) {
  6025. return path.length > 1;
  6026. }
  6027. render(code, options, { renderedSurroundingElement } = BLANK) {
  6028. this.left.render(code, options, { renderedSurroundingElement });
  6029. this.right.render(code, options);
  6030. }
  6031. }
  6032. class BreakStatement extends NodeBase {
  6033. hasEffects(context) {
  6034. if (this.label) {
  6035. if (!context.ignore.labels.has(this.label.name))
  6036. return true;
  6037. context.includedLabels.add(this.label.name);
  6038. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  6039. }
  6040. else {
  6041. if (!context.ignore.breaks)
  6042. return true;
  6043. context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
  6044. }
  6045. return false;
  6046. }
  6047. include(context) {
  6048. this.included = true;
  6049. if (this.label) {
  6050. this.label.include();
  6051. context.includedLabels.add(this.label.name);
  6052. }
  6053. context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
  6054. }
  6055. }
  6056. // To avoid infinite recursions
  6057. const MAX_PATH_DEPTH = 7;
  6058. function getResolvablePropertyKey(memberExpression) {
  6059. return memberExpression.computed
  6060. ? getResolvableComputedPropertyKey(memberExpression.property)
  6061. : memberExpression.property.name;
  6062. }
  6063. function getResolvableComputedPropertyKey(propertyKey) {
  6064. if (propertyKey instanceof Literal) {
  6065. return String(propertyKey.value);
  6066. }
  6067. return null;
  6068. }
  6069. function getPathIfNotComputed(memberExpression) {
  6070. const nextPathKey = memberExpression.propertyKey;
  6071. const object = memberExpression.object;
  6072. if (typeof nextPathKey === 'string') {
  6073. if (object instanceof Identifier) {
  6074. return [
  6075. { key: object.name, pos: object.start },
  6076. { key: nextPathKey, pos: memberExpression.property.start }
  6077. ];
  6078. }
  6079. if (object instanceof MemberExpression) {
  6080. const parentPath = getPathIfNotComputed(object);
  6081. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  6082. }
  6083. }
  6084. return null;
  6085. }
  6086. function getStringFromPath(path) {
  6087. let pathString = path[0].key;
  6088. for (let index = 1; index < path.length; index++) {
  6089. pathString += '.' + path[index].key;
  6090. }
  6091. return pathString;
  6092. }
  6093. class MemberExpression extends NodeBase {
  6094. constructor() {
  6095. super(...arguments);
  6096. this.variable = null;
  6097. this.deoptimized = false;
  6098. this.bound = false;
  6099. this.expressionsToBeDeoptimized = [];
  6100. this.replacement = null;
  6101. }
  6102. bind() {
  6103. this.bound = true;
  6104. const path = getPathIfNotComputed(this);
  6105. const baseVariable = path && this.scope.findVariable(path[0].key);
  6106. if (baseVariable && baseVariable.isNamespace) {
  6107. const resolvedVariable = this.resolveNamespaceVariables(baseVariable, path.slice(1));
  6108. if (!resolvedVariable) {
  6109. super.bind();
  6110. }
  6111. else if (typeof resolvedVariable === 'string') {
  6112. this.replacement = resolvedVariable;
  6113. }
  6114. else {
  6115. this.variable = resolvedVariable;
  6116. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  6117. }
  6118. }
  6119. else {
  6120. super.bind();
  6121. }
  6122. }
  6123. deoptimizeCache() {
  6124. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  6125. this.expressionsToBeDeoptimized = [];
  6126. this.propertyKey = UnknownKey;
  6127. this.object.deoptimizePath(UNKNOWN_PATH);
  6128. for (const expression of expressionsToBeDeoptimized) {
  6129. expression.deoptimizeCache();
  6130. }
  6131. }
  6132. deoptimizePath(path) {
  6133. if (path.length === 0)
  6134. this.disallowNamespaceReassignment();
  6135. if (this.variable) {
  6136. this.variable.deoptimizePath(path);
  6137. }
  6138. else if (!this.replacement) {
  6139. if (path.length < MAX_PATH_DEPTH) {
  6140. this.object.deoptimizePath([this.getPropertyKey(), ...path]);
  6141. }
  6142. }
  6143. }
  6144. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  6145. if (this.variable) {
  6146. this.variable.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  6147. }
  6148. else if (!this.replacement) {
  6149. if (path.length < MAX_PATH_DEPTH) {
  6150. this.object.deoptimizeThisOnEventAtPath(event, [this.getPropertyKey(), ...path], thisParameter, recursionTracker);
  6151. }
  6152. else {
  6153. thisParameter.deoptimizePath(UNKNOWN_PATH);
  6154. }
  6155. }
  6156. }
  6157. getLiteralValueAtPath(path, recursionTracker, origin) {
  6158. if (this.variable !== null) {
  6159. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  6160. }
  6161. if (this.replacement) {
  6162. return UnknownValue;
  6163. }
  6164. this.expressionsToBeDeoptimized.push(origin);
  6165. if (path.length < MAX_PATH_DEPTH) {
  6166. return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
  6167. }
  6168. return UnknownValue;
  6169. }
  6170. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  6171. if (this.variable !== null) {
  6172. return this.variable.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
  6173. }
  6174. if (this.replacement) {
  6175. return UNKNOWN_EXPRESSION;
  6176. }
  6177. this.expressionsToBeDeoptimized.push(origin);
  6178. if (path.length < MAX_PATH_DEPTH) {
  6179. return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], callOptions, recursionTracker, origin);
  6180. }
  6181. return UNKNOWN_EXPRESSION;
  6182. }
  6183. hasEffects(context) {
  6184. if (!this.deoptimized)
  6185. this.applyDeoptimizations();
  6186. const { propertyReadSideEffects } = this.context.options
  6187. .treeshake;
  6188. return (this.property.hasEffects(context) ||
  6189. this.object.hasEffects(context) ||
  6190. // Assignments do not access the property before assigning
  6191. (!(this.variable ||
  6192. this.replacement ||
  6193. (this.parent instanceof AssignmentExpression && this.parent.operator === '=')) &&
  6194. propertyReadSideEffects &&
  6195. (propertyReadSideEffects === 'always' ||
  6196. this.object.hasEffectsWhenAccessedAtPath([this.getPropertyKey()], context))));
  6197. }
  6198. hasEffectsWhenAccessedAtPath(path, context) {
  6199. if (this.variable !== null) {
  6200. return this.variable.hasEffectsWhenAccessedAtPath(path, context);
  6201. }
  6202. if (this.replacement) {
  6203. return true;
  6204. }
  6205. if (path.length < MAX_PATH_DEPTH) {
  6206. return this.object.hasEffectsWhenAccessedAtPath([this.getPropertyKey(), ...path], context);
  6207. }
  6208. return true;
  6209. }
  6210. hasEffectsWhenAssignedAtPath(path, context) {
  6211. if (this.variable !== null) {
  6212. return this.variable.hasEffectsWhenAssignedAtPath(path, context);
  6213. }
  6214. if (this.replacement) {
  6215. return true;
  6216. }
  6217. if (path.length < MAX_PATH_DEPTH) {
  6218. return this.object.hasEffectsWhenAssignedAtPath([this.getPropertyKey(), ...path], context);
  6219. }
  6220. return true;
  6221. }
  6222. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6223. if (this.variable !== null) {
  6224. return this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context);
  6225. }
  6226. if (this.replacement) {
  6227. return true;
  6228. }
  6229. if (path.length < MAX_PATH_DEPTH) {
  6230. return this.object.hasEffectsWhenCalledAtPath([this.getPropertyKey(), ...path], callOptions, context);
  6231. }
  6232. return true;
  6233. }
  6234. include(context, includeChildrenRecursively) {
  6235. if (!this.deoptimized)
  6236. this.applyDeoptimizations();
  6237. if (!this.included) {
  6238. this.included = true;
  6239. if (this.variable !== null) {
  6240. this.context.includeVariableInModule(this.variable);
  6241. }
  6242. }
  6243. this.object.include(context, includeChildrenRecursively);
  6244. this.property.include(context, includeChildrenRecursively);
  6245. }
  6246. includeCallArguments(context, args) {
  6247. if (this.variable) {
  6248. this.variable.includeCallArguments(context, args);
  6249. }
  6250. else {
  6251. super.includeCallArguments(context, args);
  6252. }
  6253. }
  6254. initialise() {
  6255. this.propertyKey = getResolvablePropertyKey(this);
  6256. }
  6257. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) {
  6258. if (this.variable || this.replacement) {
  6259. let replacement = this.variable ? this.variable.getName() : this.replacement;
  6260. if (renderedParentType && isCalleeOfRenderedParent)
  6261. replacement = '0, ' + replacement;
  6262. code.overwrite(this.start, this.end, replacement, {
  6263. contentOnly: true,
  6264. storeName: true
  6265. });
  6266. }
  6267. else {
  6268. if (renderedParentType && isCalleeOfRenderedParent) {
  6269. code.appendRight(this.start, '0, ');
  6270. }
  6271. this.object.render(code, options, { renderedSurroundingElement });
  6272. this.property.render(code, options);
  6273. }
  6274. }
  6275. applyDeoptimizations() {
  6276. this.deoptimized = true;
  6277. const { propertyReadSideEffects } = this.context.options
  6278. .treeshake;
  6279. if (
  6280. // Namespaces are not bound and should not be deoptimized
  6281. this.bound &&
  6282. propertyReadSideEffects &&
  6283. !(this.variable || this.replacement)) {
  6284. // Regular Assignments do not access the property before assigning
  6285. if (!(this.parent instanceof AssignmentExpression && this.parent.operator === '=')) {
  6286. this.object.deoptimizeThisOnEventAtPath(EVENT_ACCESSED, [this.propertyKey], this.object, SHARED_RECURSION_TRACKER);
  6287. }
  6288. if (this.parent instanceof AssignmentExpression) {
  6289. this.object.deoptimizeThisOnEventAtPath(EVENT_ASSIGNED, [this.propertyKey], this.object, SHARED_RECURSION_TRACKER);
  6290. }
  6291. this.context.requestTreeshakingPass();
  6292. }
  6293. }
  6294. disallowNamespaceReassignment() {
  6295. if (this.object instanceof Identifier) {
  6296. const variable = this.scope.findVariable(this.object.name);
  6297. if (variable.isNamespace) {
  6298. if (this.variable) {
  6299. this.context.includeVariableInModule(this.variable);
  6300. }
  6301. this.context.warn({
  6302. code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
  6303. message: `Illegal reassignment to import '${this.object.name}'`
  6304. }, this.start);
  6305. }
  6306. }
  6307. }
  6308. getPropertyKey() {
  6309. if (this.propertyKey === null) {
  6310. this.propertyKey = UnknownKey;
  6311. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  6312. return (this.propertyKey = value === UnknownValue ? UnknownKey : String(value));
  6313. }
  6314. return this.propertyKey;
  6315. }
  6316. resolveNamespaceVariables(baseVariable, path) {
  6317. if (path.length === 0)
  6318. return baseVariable;
  6319. if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
  6320. return null;
  6321. const exportName = path[0].key;
  6322. const variable = baseVariable.context.traceExport(exportName);
  6323. if (!variable) {
  6324. const fileName = baseVariable.context.fileName;
  6325. this.context.warn({
  6326. code: 'MISSING_EXPORT',
  6327. exporter: relativeId(fileName),
  6328. importer: relativeId(this.context.fileName),
  6329. message: `'${exportName}' is not exported by '${relativeId(fileName)}'`,
  6330. missing: exportName,
  6331. url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
  6332. }, path[0].pos);
  6333. return 'undefined';
  6334. }
  6335. return this.resolveNamespaceVariables(variable, path.slice(1));
  6336. }
  6337. }
  6338. class CallExpression extends NodeBase {
  6339. constructor() {
  6340. super(...arguments);
  6341. this.deoptimized = false;
  6342. this.deoptimizableDependentExpressions = [];
  6343. this.expressionsToBeDeoptimized = new Set();
  6344. this.returnExpression = null;
  6345. }
  6346. bind() {
  6347. super.bind();
  6348. if (this.callee instanceof Identifier) {
  6349. const variable = this.scope.findVariable(this.callee.name);
  6350. if (variable.isNamespace) {
  6351. this.context.warn({
  6352. code: 'CANNOT_CALL_NAMESPACE',
  6353. message: `Cannot call a namespace ('${this.callee.name}')`
  6354. }, this.start);
  6355. }
  6356. if (this.callee.name === 'eval') {
  6357. this.context.warn({
  6358. code: 'EVAL',
  6359. message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
  6360. url: 'https://rollupjs.org/guide/en/#avoiding-eval'
  6361. }, this.start);
  6362. }
  6363. }
  6364. this.callOptions = {
  6365. args: this.arguments,
  6366. thisParam: this.callee instanceof MemberExpression && !this.callee.variable
  6367. ? this.callee.object
  6368. : null,
  6369. withNew: false
  6370. };
  6371. }
  6372. deoptimizeCache() {
  6373. if (this.returnExpression !== UNKNOWN_EXPRESSION) {
  6374. this.returnExpression = UNKNOWN_EXPRESSION;
  6375. for (const expression of this.deoptimizableDependentExpressions) {
  6376. expression.deoptimizeCache();
  6377. }
  6378. for (const expression of this.expressionsToBeDeoptimized) {
  6379. expression.deoptimizePath(UNKNOWN_PATH);
  6380. }
  6381. }
  6382. }
  6383. deoptimizePath(path) {
  6384. if (path.length === 0 ||
  6385. this.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  6386. return;
  6387. }
  6388. const returnExpression = this.getReturnExpression();
  6389. if (returnExpression !== UNKNOWN_EXPRESSION) {
  6390. returnExpression.deoptimizePath(path);
  6391. }
  6392. }
  6393. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  6394. const returnExpression = this.getReturnExpression(recursionTracker);
  6395. if (returnExpression === UNKNOWN_EXPRESSION) {
  6396. thisParameter.deoptimizePath(UNKNOWN_PATH);
  6397. }
  6398. else {
  6399. recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  6400. this.expressionsToBeDeoptimized.add(thisParameter);
  6401. returnExpression.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  6402. }, undefined);
  6403. }
  6404. }
  6405. getLiteralValueAtPath(path, recursionTracker, origin) {
  6406. const returnExpression = this.getReturnExpression(recursionTracker);
  6407. if (returnExpression === UNKNOWN_EXPRESSION) {
  6408. return UnknownValue;
  6409. }
  6410. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  6411. this.deoptimizableDependentExpressions.push(origin);
  6412. return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  6413. }, UnknownValue);
  6414. }
  6415. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  6416. const returnExpression = this.getReturnExpression(recursionTracker);
  6417. if (this.returnExpression === UNKNOWN_EXPRESSION) {
  6418. return UNKNOWN_EXPRESSION;
  6419. }
  6420. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  6421. this.deoptimizableDependentExpressions.push(origin);
  6422. return returnExpression.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
  6423. }, UNKNOWN_EXPRESSION);
  6424. }
  6425. hasEffects(context) {
  6426. try {
  6427. for (const argument of this.arguments) {
  6428. if (argument.hasEffects(context))
  6429. return true;
  6430. }
  6431. if (this.context.options.treeshake.annotations &&
  6432. this.annotations)
  6433. return false;
  6434. return (this.callee.hasEffects(context) ||
  6435. this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
  6436. }
  6437. finally {
  6438. if (!this.deoptimized)
  6439. this.applyDeoptimizations();
  6440. }
  6441. }
  6442. hasEffectsWhenAccessedAtPath(path, context) {
  6443. return (!context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  6444. this.getReturnExpression().hasEffectsWhenAccessedAtPath(path, context));
  6445. }
  6446. hasEffectsWhenAssignedAtPath(path, context) {
  6447. return (!context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
  6448. this.getReturnExpression().hasEffectsWhenAssignedAtPath(path, context));
  6449. }
  6450. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6451. return (!(callOptions.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, callOptions, this) &&
  6452. this.getReturnExpression().hasEffectsWhenCalledAtPath(path, callOptions, context));
  6453. }
  6454. include(context, includeChildrenRecursively) {
  6455. if (!this.deoptimized)
  6456. this.applyDeoptimizations();
  6457. if (includeChildrenRecursively) {
  6458. super.include(context, includeChildrenRecursively);
  6459. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  6460. this.callee instanceof Identifier &&
  6461. this.callee.variable) {
  6462. this.callee.variable.markCalledFromTryStatement();
  6463. }
  6464. }
  6465. else {
  6466. this.included = true;
  6467. this.callee.include(context, false);
  6468. }
  6469. this.callee.includeCallArguments(context, this.arguments);
  6470. const returnExpression = this.getReturnExpression();
  6471. if (!returnExpression.included) {
  6472. returnExpression.include(context, false);
  6473. }
  6474. }
  6475. render(code, options, { renderedSurroundingElement } = BLANK) {
  6476. this.callee.render(code, options, {
  6477. isCalleeOfRenderedParent: true,
  6478. renderedSurroundingElement
  6479. });
  6480. if (this.arguments.length > 0) {
  6481. if (this.arguments[this.arguments.length - 1].included) {
  6482. for (const arg of this.arguments) {
  6483. arg.render(code, options);
  6484. }
  6485. }
  6486. else {
  6487. let lastIncludedIndex = this.arguments.length - 2;
  6488. while (lastIncludedIndex >= 0 && !this.arguments[lastIncludedIndex].included) {
  6489. lastIncludedIndex--;
  6490. }
  6491. if (lastIncludedIndex >= 0) {
  6492. for (let index = 0; index <= lastIncludedIndex; index++) {
  6493. this.arguments[index].render(code, options);
  6494. }
  6495. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', this.arguments[lastIncludedIndex].end), this.end - 1);
  6496. }
  6497. else {
  6498. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', this.callee.end) + 1, this.end - 1);
  6499. }
  6500. }
  6501. }
  6502. }
  6503. applyDeoptimizations() {
  6504. this.deoptimized = true;
  6505. const { thisParam } = this.callOptions;
  6506. if (thisParam) {
  6507. this.callee.deoptimizeThisOnEventAtPath(EVENT_CALLED, EMPTY_PATH, thisParam, SHARED_RECURSION_TRACKER);
  6508. }
  6509. for (const argument of this.arguments) {
  6510. // This will make sure all properties of parameters behave as "unknown"
  6511. argument.deoptimizePath(UNKNOWN_PATH);
  6512. }
  6513. this.context.requestTreeshakingPass();
  6514. }
  6515. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  6516. if (this.returnExpression === null) {
  6517. this.returnExpression = UNKNOWN_EXPRESSION;
  6518. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.callOptions, recursionTracker, this));
  6519. }
  6520. return this.returnExpression;
  6521. }
  6522. }
  6523. class CatchScope extends ParameterScope {
  6524. addDeclaration(identifier, context, init, isHoisted) {
  6525. const existingParameter = this.variables.get(identifier.name);
  6526. if (existingParameter) {
  6527. // While we still create a hoisted declaration, the initializer goes to
  6528. // the parameter. Note that technically, the declaration now belongs to
  6529. // two variables, which is not correct but should not cause issues.
  6530. this.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, isHoisted);
  6531. existingParameter.addDeclaration(identifier, init);
  6532. return existingParameter;
  6533. }
  6534. return this.parent.addDeclaration(identifier, context, init, isHoisted);
  6535. }
  6536. }
  6537. class CatchClause extends NodeBase {
  6538. createScope(parentScope) {
  6539. this.scope = new CatchScope(parentScope, this.context);
  6540. }
  6541. parseNode(esTreeNode) {
  6542. // Parameters need to be declared first as the logic is that initializers
  6543. // of hoisted body variables are associated with parameters of the same
  6544. // name instead of the variable
  6545. const { param } = esTreeNode;
  6546. if (param) {
  6547. this.param = new (this.context.nodeConstructors[param.type] ||
  6548. this.context.nodeConstructors.UnknownNode)(param, this, this.scope);
  6549. this.param.declare('parameter', UNKNOWN_EXPRESSION);
  6550. }
  6551. super.parseNode(esTreeNode);
  6552. }
  6553. }
  6554. class ChainExpression extends NodeBase {
  6555. }
  6556. class ClassBodyScope extends ChildScope {
  6557. constructor(parent, classNode, context) {
  6558. super(parent);
  6559. this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, context)));
  6560. this.instanceScope = new ChildScope(this);
  6561. this.instanceScope.variables.set('this', new ThisVariable(context));
  6562. }
  6563. findLexicalBoundary() {
  6564. return this;
  6565. }
  6566. }
  6567. class ClassBody extends NodeBase {
  6568. createScope(parentScope) {
  6569. this.scope = new ClassBodyScope(parentScope, this.parent, this.context);
  6570. }
  6571. include(context, includeChildrenRecursively) {
  6572. this.included = true;
  6573. this.context.includeVariableInModule(this.scope.thisVariable);
  6574. for (const definition of this.body) {
  6575. definition.include(context, includeChildrenRecursively);
  6576. }
  6577. }
  6578. parseNode(esTreeNode) {
  6579. const body = (this.body = []);
  6580. for (const definition of esTreeNode.body) {
  6581. body.push(new this.context.nodeConstructors[definition.type](definition, this, definition.static ? this.scope : this.scope.instanceScope));
  6582. }
  6583. super.parseNode(esTreeNode);
  6584. }
  6585. }
  6586. class ClassExpression extends ClassNode {
  6587. render(code, options, { renderedSurroundingElement } = BLANK) {
  6588. super.render(code, options);
  6589. if (renderedSurroundingElement === ExpressionStatement$1) {
  6590. code.appendRight(this.start, '(');
  6591. code.prependLeft(this.end, ')');
  6592. }
  6593. }
  6594. }
  6595. class MultiExpression extends ExpressionEntity {
  6596. constructor(expressions) {
  6597. super();
  6598. this.expressions = expressions;
  6599. this.included = false;
  6600. }
  6601. deoptimizePath(path) {
  6602. for (const expression of this.expressions) {
  6603. expression.deoptimizePath(path);
  6604. }
  6605. }
  6606. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  6607. return new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin)));
  6608. }
  6609. hasEffectsWhenAccessedAtPath(path, context) {
  6610. for (const expression of this.expressions) {
  6611. if (expression.hasEffectsWhenAccessedAtPath(path, context))
  6612. return true;
  6613. }
  6614. return false;
  6615. }
  6616. hasEffectsWhenAssignedAtPath(path, context) {
  6617. for (const expression of this.expressions) {
  6618. if (expression.hasEffectsWhenAssignedAtPath(path, context))
  6619. return true;
  6620. }
  6621. return false;
  6622. }
  6623. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6624. for (const expression of this.expressions) {
  6625. if (expression.hasEffectsWhenCalledAtPath(path, callOptions, context))
  6626. return true;
  6627. }
  6628. return false;
  6629. }
  6630. include(context, includeChildrenRecursively) {
  6631. // This is only relevant to include values that do not have an AST representation,
  6632. // such as UnknownArrayExpression. Thus we only need to include them once.
  6633. for (const expression of this.expressions) {
  6634. if (!expression.included) {
  6635. expression.include(context, includeChildrenRecursively);
  6636. }
  6637. }
  6638. }
  6639. }
  6640. class ConditionalExpression extends NodeBase {
  6641. constructor() {
  6642. super(...arguments);
  6643. this.expressionsToBeDeoptimized = [];
  6644. this.isBranchResolutionAnalysed = false;
  6645. this.usedBranch = null;
  6646. }
  6647. deoptimizeCache() {
  6648. if (this.usedBranch !== null) {
  6649. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  6650. this.usedBranch = null;
  6651. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  6652. for (const expression of this.expressionsToBeDeoptimized) {
  6653. expression.deoptimizeCache();
  6654. }
  6655. }
  6656. }
  6657. deoptimizePath(path) {
  6658. const usedBranch = this.getUsedBranch();
  6659. if (usedBranch === null) {
  6660. this.consequent.deoptimizePath(path);
  6661. this.alternate.deoptimizePath(path);
  6662. }
  6663. else {
  6664. usedBranch.deoptimizePath(path);
  6665. }
  6666. }
  6667. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  6668. this.consequent.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  6669. this.alternate.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  6670. }
  6671. getLiteralValueAtPath(path, recursionTracker, origin) {
  6672. const usedBranch = this.getUsedBranch();
  6673. if (usedBranch === null)
  6674. return UnknownValue;
  6675. this.expressionsToBeDeoptimized.push(origin);
  6676. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  6677. }
  6678. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  6679. const usedBranch = this.getUsedBranch();
  6680. if (usedBranch === null)
  6681. return new MultiExpression([
  6682. this.consequent.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin),
  6683. this.alternate.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin)
  6684. ]);
  6685. this.expressionsToBeDeoptimized.push(origin);
  6686. return usedBranch.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
  6687. }
  6688. hasEffects(context) {
  6689. if (this.test.hasEffects(context))
  6690. return true;
  6691. const usedBranch = this.getUsedBranch();
  6692. if (usedBranch === null) {
  6693. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  6694. }
  6695. return usedBranch.hasEffects(context);
  6696. }
  6697. hasEffectsWhenAccessedAtPath(path, context) {
  6698. const usedBranch = this.getUsedBranch();
  6699. if (usedBranch === null) {
  6700. return (this.consequent.hasEffectsWhenAccessedAtPath(path, context) ||
  6701. this.alternate.hasEffectsWhenAccessedAtPath(path, context));
  6702. }
  6703. return usedBranch.hasEffectsWhenAccessedAtPath(path, context);
  6704. }
  6705. hasEffectsWhenAssignedAtPath(path, context) {
  6706. const usedBranch = this.getUsedBranch();
  6707. if (usedBranch === null) {
  6708. return (this.consequent.hasEffectsWhenAssignedAtPath(path, context) ||
  6709. this.alternate.hasEffectsWhenAssignedAtPath(path, context));
  6710. }
  6711. return usedBranch.hasEffectsWhenAssignedAtPath(path, context);
  6712. }
  6713. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  6714. const usedBranch = this.getUsedBranch();
  6715. if (usedBranch === null) {
  6716. return (this.consequent.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
  6717. this.alternate.hasEffectsWhenCalledAtPath(path, callOptions, context));
  6718. }
  6719. return usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context);
  6720. }
  6721. include(context, includeChildrenRecursively) {
  6722. this.included = true;
  6723. const usedBranch = this.getUsedBranch();
  6724. if (includeChildrenRecursively || this.test.shouldBeIncluded(context) || usedBranch === null) {
  6725. this.test.include(context, includeChildrenRecursively);
  6726. this.consequent.include(context, includeChildrenRecursively);
  6727. this.alternate.include(context, includeChildrenRecursively);
  6728. }
  6729. else {
  6730. usedBranch.include(context, includeChildrenRecursively);
  6731. }
  6732. }
  6733. includeCallArguments(context, args) {
  6734. const usedBranch = this.getUsedBranch();
  6735. if (usedBranch === null) {
  6736. this.consequent.includeCallArguments(context, args);
  6737. this.alternate.includeCallArguments(context, args);
  6738. }
  6739. else {
  6740. usedBranch.includeCallArguments(context, args);
  6741. }
  6742. }
  6743. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  6744. const usedBranch = this.getUsedBranch();
  6745. if (!this.test.included) {
  6746. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  6747. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  6748. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  6749. : colonPos) + 1);
  6750. if (preventASI) {
  6751. removeLineBreaks(code, inclusionStart, usedBranch.start);
  6752. }
  6753. code.remove(this.start, inclusionStart);
  6754. if (this.consequent.included) {
  6755. code.remove(colonPos, this.end);
  6756. }
  6757. removeAnnotations(this, code);
  6758. usedBranch.render(code, options, {
  6759. isCalleeOfRenderedParent,
  6760. preventASI: true,
  6761. renderedParentType: renderedParentType || this.parent.type,
  6762. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  6763. });
  6764. }
  6765. else {
  6766. this.test.render(code, options, { renderedSurroundingElement });
  6767. this.consequent.render(code, options);
  6768. this.alternate.render(code, options);
  6769. }
  6770. }
  6771. getUsedBranch() {
  6772. if (this.isBranchResolutionAnalysed) {
  6773. return this.usedBranch;
  6774. }
  6775. this.isBranchResolutionAnalysed = true;
  6776. const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  6777. return testValue === UnknownValue
  6778. ? null
  6779. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  6780. }
  6781. }
  6782. class ContinueStatement extends NodeBase {
  6783. hasEffects(context) {
  6784. if (this.label) {
  6785. if (!context.ignore.labels.has(this.label.name))
  6786. return true;
  6787. context.includedLabels.add(this.label.name);
  6788. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  6789. }
  6790. else {
  6791. if (!context.ignore.continues)
  6792. return true;
  6793. context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
  6794. }
  6795. return false;
  6796. }
  6797. include(context) {
  6798. this.included = true;
  6799. if (this.label) {
  6800. this.label.include();
  6801. context.includedLabels.add(this.label.name);
  6802. }
  6803. context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
  6804. }
  6805. }
  6806. class DoWhileStatement extends NodeBase {
  6807. hasEffects(context) {
  6808. if (this.test.hasEffects(context))
  6809. return true;
  6810. const { brokenFlow, ignore: { breaks, continues } } = context;
  6811. context.ignore.breaks = true;
  6812. context.ignore.continues = true;
  6813. if (this.body.hasEffects(context))
  6814. return true;
  6815. context.ignore.breaks = breaks;
  6816. context.ignore.continues = continues;
  6817. context.brokenFlow = brokenFlow;
  6818. return false;
  6819. }
  6820. include(context, includeChildrenRecursively) {
  6821. this.included = true;
  6822. this.test.include(context, includeChildrenRecursively);
  6823. const { brokenFlow } = context;
  6824. this.body.includeAsSingleStatement(context, includeChildrenRecursively);
  6825. context.brokenFlow = brokenFlow;
  6826. }
  6827. }
  6828. class EmptyStatement extends NodeBase {
  6829. hasEffects() {
  6830. return false;
  6831. }
  6832. }
  6833. class ExportNamedDeclaration extends NodeBase {
  6834. bind() {
  6835. // Do not bind specifiers
  6836. if (this.declaration !== null)
  6837. this.declaration.bind();
  6838. }
  6839. hasEffects(context) {
  6840. return this.declaration !== null && this.declaration.hasEffects(context);
  6841. }
  6842. initialise() {
  6843. this.context.addExport(this);
  6844. }
  6845. render(code, options, nodeRenderOptions) {
  6846. const { start, end } = nodeRenderOptions;
  6847. if (this.declaration === null) {
  6848. code.remove(start, end);
  6849. }
  6850. else {
  6851. code.remove(this.start, this.declaration.start);
  6852. this.declaration.render(code, options, { end, start });
  6853. }
  6854. }
  6855. }
  6856. ExportNamedDeclaration.prototype.needsBoundaries = true;
  6857. class ExportSpecifier extends NodeBase {
  6858. }
  6859. class ForInStatement extends NodeBase {
  6860. constructor() {
  6861. super(...arguments);
  6862. this.deoptimized = false;
  6863. }
  6864. createScope(parentScope) {
  6865. this.scope = new BlockScope(parentScope);
  6866. }
  6867. hasEffects(context) {
  6868. if (!this.deoptimized)
  6869. this.applyDeoptimizations();
  6870. if ((this.left &&
  6871. (this.left.hasEffects(context) ||
  6872. this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))) ||
  6873. (this.right && this.right.hasEffects(context)))
  6874. return true;
  6875. const { brokenFlow, ignore: { breaks, continues } } = context;
  6876. context.ignore.breaks = true;
  6877. context.ignore.continues = true;
  6878. if (this.body.hasEffects(context))
  6879. return true;
  6880. context.ignore.breaks = breaks;
  6881. context.ignore.continues = continues;
  6882. context.brokenFlow = brokenFlow;
  6883. return false;
  6884. }
  6885. include(context, includeChildrenRecursively) {
  6886. if (!this.deoptimized)
  6887. this.applyDeoptimizations();
  6888. this.included = true;
  6889. this.left.include(context, includeChildrenRecursively || true);
  6890. this.right.include(context, includeChildrenRecursively);
  6891. const { brokenFlow } = context;
  6892. this.body.includeAsSingleStatement(context, includeChildrenRecursively);
  6893. context.brokenFlow = brokenFlow;
  6894. }
  6895. render(code, options) {
  6896. this.left.render(code, options, NO_SEMICOLON);
  6897. this.right.render(code, options, NO_SEMICOLON);
  6898. // handle no space between "in" and the right side
  6899. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  6900. code.prependLeft(this.right.start, ' ');
  6901. }
  6902. this.body.render(code, options);
  6903. }
  6904. applyDeoptimizations() {
  6905. this.deoptimized = true;
  6906. this.left.deoptimizePath(EMPTY_PATH);
  6907. this.context.requestTreeshakingPass();
  6908. }
  6909. }
  6910. class ForOfStatement extends NodeBase {
  6911. constructor() {
  6912. super(...arguments);
  6913. this.deoptimized = false;
  6914. }
  6915. createScope(parentScope) {
  6916. this.scope = new BlockScope(parentScope);
  6917. }
  6918. hasEffects() {
  6919. if (!this.deoptimized)
  6920. this.applyDeoptimizations();
  6921. // Placeholder until proper Symbol.Iterator support
  6922. return true;
  6923. }
  6924. include(context, includeChildrenRecursively) {
  6925. if (!this.deoptimized)
  6926. this.applyDeoptimizations();
  6927. this.included = true;
  6928. this.left.include(context, includeChildrenRecursively || true);
  6929. this.right.include(context, includeChildrenRecursively);
  6930. const { brokenFlow } = context;
  6931. this.body.includeAsSingleStatement(context, includeChildrenRecursively);
  6932. context.brokenFlow = brokenFlow;
  6933. }
  6934. render(code, options) {
  6935. this.left.render(code, options, NO_SEMICOLON);
  6936. this.right.render(code, options, NO_SEMICOLON);
  6937. // handle no space between "of" and the right side
  6938. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  6939. code.prependLeft(this.right.start, ' ');
  6940. }
  6941. this.body.render(code, options);
  6942. }
  6943. applyDeoptimizations() {
  6944. this.deoptimized = true;
  6945. this.left.deoptimizePath(EMPTY_PATH);
  6946. this.context.requestTreeshakingPass();
  6947. }
  6948. }
  6949. class ForStatement extends NodeBase {
  6950. createScope(parentScope) {
  6951. this.scope = new BlockScope(parentScope);
  6952. }
  6953. hasEffects(context) {
  6954. if ((this.init && this.init.hasEffects(context)) ||
  6955. (this.test && this.test.hasEffects(context)) ||
  6956. (this.update && this.update.hasEffects(context)))
  6957. return true;
  6958. const { brokenFlow, ignore: { breaks, continues } } = context;
  6959. context.ignore.breaks = true;
  6960. context.ignore.continues = true;
  6961. if (this.body.hasEffects(context))
  6962. return true;
  6963. context.ignore.breaks = breaks;
  6964. context.ignore.continues = continues;
  6965. context.brokenFlow = brokenFlow;
  6966. return false;
  6967. }
  6968. include(context, includeChildrenRecursively) {
  6969. this.included = true;
  6970. if (this.init)
  6971. this.init.includeAsSingleStatement(context, includeChildrenRecursively);
  6972. if (this.test)
  6973. this.test.include(context, includeChildrenRecursively);
  6974. const { brokenFlow } = context;
  6975. if (this.update)
  6976. this.update.include(context, includeChildrenRecursively);
  6977. this.body.includeAsSingleStatement(context, includeChildrenRecursively);
  6978. context.brokenFlow = brokenFlow;
  6979. }
  6980. render(code, options) {
  6981. if (this.init)
  6982. this.init.render(code, options, NO_SEMICOLON);
  6983. if (this.test)
  6984. this.test.render(code, options, NO_SEMICOLON);
  6985. if (this.update)
  6986. this.update.render(code, options, NO_SEMICOLON);
  6987. this.body.render(code, options);
  6988. }
  6989. }
  6990. class FunctionExpression extends FunctionNode {
  6991. render(code, options, { renderedSurroundingElement } = BLANK) {
  6992. super.render(code, options);
  6993. if (renderedSurroundingElement === ExpressionStatement$1) {
  6994. code.appendRight(this.start, '(');
  6995. code.prependLeft(this.end, ')');
  6996. }
  6997. }
  6998. }
  6999. class TrackingScope extends BlockScope {
  7000. constructor() {
  7001. super(...arguments);
  7002. this.hoistedDeclarations = [];
  7003. }
  7004. addDeclaration(identifier, context, init, isHoisted) {
  7005. this.hoistedDeclarations.push(identifier);
  7006. return super.addDeclaration(identifier, context, init, isHoisted);
  7007. }
  7008. }
  7009. const unset = Symbol('unset');
  7010. class IfStatement extends NodeBase {
  7011. constructor() {
  7012. super(...arguments);
  7013. this.testValue = unset;
  7014. }
  7015. deoptimizeCache() {
  7016. this.testValue = UnknownValue;
  7017. }
  7018. hasEffects(context) {
  7019. if (this.test.hasEffects(context)) {
  7020. return true;
  7021. }
  7022. const testValue = this.getTestValue();
  7023. if (testValue === UnknownValue) {
  7024. const { brokenFlow } = context;
  7025. if (this.consequent.hasEffects(context))
  7026. return true;
  7027. const consequentBrokenFlow = context.brokenFlow;
  7028. context.brokenFlow = brokenFlow;
  7029. if (this.alternate === null)
  7030. return false;
  7031. if (this.alternate.hasEffects(context))
  7032. return true;
  7033. context.brokenFlow =
  7034. context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
  7035. return false;
  7036. }
  7037. return testValue
  7038. ? this.consequent.hasEffects(context)
  7039. : this.alternate !== null && this.alternate.hasEffects(context);
  7040. }
  7041. include(context, includeChildrenRecursively) {
  7042. this.included = true;
  7043. if (includeChildrenRecursively) {
  7044. this.includeRecursively(includeChildrenRecursively, context);
  7045. }
  7046. else {
  7047. const testValue = this.getTestValue();
  7048. if (testValue === UnknownValue) {
  7049. this.includeUnknownTest(context);
  7050. }
  7051. else {
  7052. this.includeKnownTest(context, testValue);
  7053. }
  7054. }
  7055. }
  7056. parseNode(esTreeNode) {
  7057. this.consequentScope = new TrackingScope(this.scope);
  7058. this.consequent = new (this.context.nodeConstructors[esTreeNode.consequent.type] ||
  7059. this.context.nodeConstructors.UnknownNode)(esTreeNode.consequent, this, this.consequentScope);
  7060. if (esTreeNode.alternate) {
  7061. this.alternateScope = new TrackingScope(this.scope);
  7062. this.alternate = new (this.context.nodeConstructors[esTreeNode.alternate.type] ||
  7063. this.context.nodeConstructors.UnknownNode)(esTreeNode.alternate, this, this.alternateScope);
  7064. }
  7065. super.parseNode(esTreeNode);
  7066. }
  7067. render(code, options) {
  7068. // Note that unknown test values are always included
  7069. const testValue = this.getTestValue();
  7070. const hoistedDeclarations = [];
  7071. const includesIfElse = this.test.included;
  7072. const noTreeshake = !this.context.options.treeshake;
  7073. if (includesIfElse) {
  7074. this.test.render(code, options);
  7075. }
  7076. else {
  7077. code.remove(this.start, this.consequent.start);
  7078. }
  7079. if (this.consequent.included && (noTreeshake || testValue === UnknownValue || testValue)) {
  7080. this.consequent.render(code, options);
  7081. }
  7082. else {
  7083. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  7084. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  7085. }
  7086. if (this.alternate) {
  7087. if (this.alternate.included && (noTreeshake || testValue === UnknownValue || !testValue)) {
  7088. if (includesIfElse) {
  7089. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  7090. code.prependLeft(this.alternate.start, ' ');
  7091. }
  7092. }
  7093. else {
  7094. code.remove(this.consequent.end, this.alternate.start);
  7095. }
  7096. this.alternate.render(code, options);
  7097. }
  7098. else {
  7099. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  7100. code.overwrite(this.alternate.start, this.end, ';');
  7101. }
  7102. else {
  7103. code.remove(this.consequent.end, this.end);
  7104. }
  7105. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  7106. }
  7107. }
  7108. this.renderHoistedDeclarations(hoistedDeclarations, code);
  7109. }
  7110. getTestValue() {
  7111. if (this.testValue === unset) {
  7112. return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  7113. }
  7114. return this.testValue;
  7115. }
  7116. includeKnownTest(context, testValue) {
  7117. if (this.test.shouldBeIncluded(context)) {
  7118. this.test.include(context, false);
  7119. }
  7120. if (testValue && this.consequent.shouldBeIncluded(context)) {
  7121. this.consequent.includeAsSingleStatement(context, false);
  7122. }
  7123. if (this.alternate !== null && !testValue && this.alternate.shouldBeIncluded(context)) {
  7124. this.alternate.includeAsSingleStatement(context, false);
  7125. }
  7126. }
  7127. includeRecursively(includeChildrenRecursively, context) {
  7128. this.test.include(context, includeChildrenRecursively);
  7129. this.consequent.include(context, includeChildrenRecursively);
  7130. if (this.alternate !== null) {
  7131. this.alternate.include(context, includeChildrenRecursively);
  7132. }
  7133. }
  7134. includeUnknownTest(context) {
  7135. this.test.include(context, false);
  7136. const { brokenFlow } = context;
  7137. let consequentBrokenFlow = BROKEN_FLOW_NONE;
  7138. if (this.consequent.shouldBeIncluded(context)) {
  7139. this.consequent.includeAsSingleStatement(context, false);
  7140. consequentBrokenFlow = context.brokenFlow;
  7141. context.brokenFlow = brokenFlow;
  7142. }
  7143. if (this.alternate !== null && this.alternate.shouldBeIncluded(context)) {
  7144. this.alternate.includeAsSingleStatement(context, false);
  7145. context.brokenFlow =
  7146. context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
  7147. }
  7148. }
  7149. renderHoistedDeclarations(hoistedDeclarations, code) {
  7150. const hoistedVars = [
  7151. ...new Set(hoistedDeclarations.map(identifier => {
  7152. const variable = identifier.variable;
  7153. return variable.included ? variable.getName() : '';
  7154. }))
  7155. ]
  7156. .filter(Boolean)
  7157. .join(', ');
  7158. if (hoistedVars) {
  7159. const parentType = this.parent.type;
  7160. const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
  7161. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVars}; `);
  7162. if (needsBraces) {
  7163. code.appendLeft(this.end, ` }`);
  7164. }
  7165. }
  7166. }
  7167. shouldKeepAlternateBranch() {
  7168. let currentParent = this.parent;
  7169. do {
  7170. if (currentParent instanceof IfStatement && currentParent.alternate) {
  7171. return true;
  7172. }
  7173. if (currentParent instanceof BlockStatement) {
  7174. return false;
  7175. }
  7176. currentParent = currentParent.parent;
  7177. } while (currentParent);
  7178. return false;
  7179. }
  7180. }
  7181. class ImportDeclaration extends NodeBase {
  7182. // Do not bind specifiers
  7183. bind() { }
  7184. hasEffects() {
  7185. return false;
  7186. }
  7187. initialise() {
  7188. this.context.addImport(this);
  7189. }
  7190. render(code, _options, nodeRenderOptions) {
  7191. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  7192. }
  7193. }
  7194. ImportDeclaration.prototype.needsBoundaries = true;
  7195. class ImportDefaultSpecifier extends NodeBase {
  7196. }
  7197. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  7198. const INTEROP_DEFAULT_LEGACY_VARIABLE = '_interopDefaultLegacy';
  7199. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  7200. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  7201. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  7202. const defaultInteropHelpersByInteropType = {
  7203. auto: INTEROP_DEFAULT_VARIABLE,
  7204. default: null,
  7205. defaultOnly: null,
  7206. esModule: null,
  7207. false: null,
  7208. true: INTEROP_DEFAULT_LEGACY_VARIABLE
  7209. };
  7210. function isDefaultAProperty(interopType, externalLiveBindings) {
  7211. return (interopType === 'esModule' ||
  7212. (externalLiveBindings && (interopType === 'auto' || interopType === 'true')));
  7213. }
  7214. const namespaceInteropHelpersByInteropType = {
  7215. auto: INTEROP_NAMESPACE_VARIABLE,
  7216. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  7217. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  7218. esModule: null,
  7219. false: null,
  7220. true: INTEROP_NAMESPACE_VARIABLE
  7221. };
  7222. function canDefaultBeTakenFromNamespace(interopType, externalLiveBindings) {
  7223. return (isDefaultAProperty(interopType, externalLiveBindings) &&
  7224. defaultInteropHelpersByInteropType[interopType] === INTEROP_DEFAULT_VARIABLE);
  7225. }
  7226. function getDefaultOnlyHelper() {
  7227. return INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE;
  7228. }
  7229. function getHelpersBlock(usedHelpers, accessedGlobals, _, n, s, t, liveBindings, freeze, namespaceToStringTag) {
  7230. return HELPER_NAMES.map(variable => usedHelpers.has(variable) || accessedGlobals.has(variable)
  7231. ? HELPER_GENERATORS[variable](_, n, s, t, liveBindings, freeze, namespaceToStringTag, usedHelpers)
  7232. : '').join('');
  7233. }
  7234. const HELPER_GENERATORS = {
  7235. [INTEROP_DEFAULT_LEGACY_VARIABLE]: (_, n, s, _t, liveBindings) => `function ${INTEROP_DEFAULT_LEGACY_VARIABLE}${_}(e)${_}{${_}return ` +
  7236. `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e${_}?${_}` +
  7237. `${liveBindings ? getDefaultLiveBinding(_) : getDefaultStatic(_)}${s}${_}}${n}${n}`,
  7238. [INTEROP_DEFAULT_VARIABLE]: (_, n, s, _t, liveBindings) => `function ${INTEROP_DEFAULT_VARIABLE}${_}(e)${_}{${_}return ` +
  7239. `e${_}&&${_}e.__esModule${_}?${_}` +
  7240. `${liveBindings ? getDefaultLiveBinding(_) : getDefaultStatic(_)}${s}${_}}${n}${n}`,
  7241. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE]: (_, n, _s, t, _liveBindings, freeze, namespaceToStringTag) => `function ${INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE}(e)${_}{${n}` +
  7242. `${t}return ${getFrozen(`{__proto__: null,${namespaceToStringTag ? `${_}[Symbol.toStringTag]:${_}'Module',` : ''}${_}'default':${_}e}`, freeze)};${n}` +
  7243. `}${n}${n}`,
  7244. [INTEROP_NAMESPACE_DEFAULT_VARIABLE]: (_, n, _s, t, liveBindings, freeze, namespaceToStringTag) => `function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  7245. createNamespaceObject(_, n, t, t, liveBindings, freeze, namespaceToStringTag) +
  7246. `}${n}${n}`,
  7247. [INTEROP_NAMESPACE_VARIABLE]: (_, n, s, t, liveBindings, freeze, namespaceToStringTag, usedHelpers) => `function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  7248. (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)
  7249. ? `${t}return e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${s}${n}`
  7250. : `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  7251. createNamespaceObject(_, n, t, t, liveBindings, freeze, namespaceToStringTag)) +
  7252. `}${n}${n}`
  7253. };
  7254. function getDefaultLiveBinding(_) {
  7255. return `e${_}:${_}{${_}'default':${_}e${_}}`;
  7256. }
  7257. function getDefaultStatic(_) {
  7258. return `e['default']${_}:${_}e`;
  7259. }
  7260. function createNamespaceObject(_, n, t, i, liveBindings, freeze, namespaceToStringTag) {
  7261. return (`${i}var n${_}=${_}${namespaceToStringTag
  7262. ? `{__proto__:${_}null,${_}[Symbol.toStringTag]:${_}'Module'}`
  7263. : 'Object.create(null)'};${n}` +
  7264. `${i}if${_}(e)${_}{${n}` +
  7265. `${i}${t}Object.keys(e).forEach(function${_}(k)${_}{${n}` +
  7266. (liveBindings ? copyPropertyLiveBinding : copyPropertyStatic)(_, n, t, i + t + t) +
  7267. `${i}${t}});${n}` +
  7268. `${i}}${n}` +
  7269. `${i}n['default']${_}=${_}e;${n}` +
  7270. `${i}return ${getFrozen('n', freeze)};${n}`);
  7271. }
  7272. function copyPropertyLiveBinding(_, n, t, i) {
  7273. return (`${i}if${_}(k${_}!==${_}'default')${_}{${n}` +
  7274. `${i}${t}var d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  7275. `${i}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  7276. `${i}${t}${t}enumerable:${_}true,${n}` +
  7277. `${i}${t}${t}get:${_}function${_}()${_}{${n}` +
  7278. `${i}${t}${t}${t}return e[k];${n}` +
  7279. `${i}${t}${t}}${n}` +
  7280. `${i}${t}});${n}` +
  7281. `${i}}${n}`);
  7282. }
  7283. function copyPropertyStatic(_, n, _t, i) {
  7284. return `${i}n[k]${_}=${_}e[k];${n}`;
  7285. }
  7286. function getFrozen(fragment, freeze) {
  7287. return freeze ? `Object.freeze(${fragment})` : fragment;
  7288. }
  7289. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  7290. class ImportExpression extends NodeBase {
  7291. constructor() {
  7292. super(...arguments);
  7293. this.inlineNamespace = null;
  7294. this.mechanism = null;
  7295. this.resolution = null;
  7296. }
  7297. hasEffects() {
  7298. return true;
  7299. }
  7300. include(context, includeChildrenRecursively) {
  7301. if (!this.included) {
  7302. this.included = true;
  7303. this.context.includeDynamicImport(this);
  7304. this.scope.addAccessedDynamicImport(this);
  7305. }
  7306. this.source.include(context, includeChildrenRecursively);
  7307. }
  7308. initialise() {
  7309. this.context.addDynamicImport(this);
  7310. }
  7311. render(code, options) {
  7312. if (this.inlineNamespace) {
  7313. const _ = options.compact ? '' : ' ';
  7314. const s = options.compact ? '' : ';';
  7315. code.overwrite(this.start, this.end, `Promise.resolve().then(function${_}()${_}{${_}return ${this.inlineNamespace.getName()}${s}${_}})`, { contentOnly: true });
  7316. return;
  7317. }
  7318. if (this.mechanism) {
  7319. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left, { contentOnly: true });
  7320. code.overwrite(this.end - 1, this.end, this.mechanism.right, { contentOnly: true });
  7321. }
  7322. this.source.render(code, options);
  7323. }
  7324. renderFinalResolution(code, resolution, namespaceExportName, options) {
  7325. code.overwrite(this.source.start, this.source.end, resolution);
  7326. if (namespaceExportName) {
  7327. const _ = options.compact ? '' : ' ';
  7328. const s = options.compact ? '' : ';';
  7329. code.prependLeft(this.end, `.then(function${_}(n)${_}{${_}return n.${namespaceExportName}${s}${_}})`);
  7330. }
  7331. }
  7332. setExternalResolution(exportMode, resolution, options, pluginDriver, accessedGlobalsByScope) {
  7333. this.resolution = resolution;
  7334. const accessedGlobals = [...(accessedImportGlobals[options.format] || [])];
  7335. let helper;
  7336. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, pluginDriver));
  7337. if (helper) {
  7338. accessedGlobals.push(helper);
  7339. }
  7340. if (accessedGlobals.length > 0) {
  7341. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  7342. }
  7343. }
  7344. setInternalResolution(inlineNamespace) {
  7345. this.inlineNamespace = inlineNamespace;
  7346. }
  7347. getDynamicImportMechanismAndHelper(resolution, exportMode, options, pluginDriver) {
  7348. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  7349. {
  7350. customResolution: typeof this.resolution === 'string' ? this.resolution : null,
  7351. format: options.format,
  7352. moduleId: this.context.module.id,
  7353. targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
  7354. }
  7355. ]);
  7356. if (mechanism) {
  7357. return { helper: null, mechanism };
  7358. }
  7359. switch (options.format) {
  7360. case 'cjs': {
  7361. const _ = options.compact ? '' : ' ';
  7362. const s = options.compact ? '' : ';';
  7363. const leftStart = `Promise.resolve().then(function${_}()${_}{${_}return`;
  7364. const helper = getInteropHelper(resolution, exportMode, options.interop);
  7365. return {
  7366. helper,
  7367. mechanism: helper
  7368. ? {
  7369. left: `${leftStart} /*#__PURE__*/${helper}(require(`,
  7370. right: `))${s}${_}})`
  7371. }
  7372. : {
  7373. left: `${leftStart} require(`,
  7374. right: `)${s}${_}})`
  7375. }
  7376. };
  7377. }
  7378. case 'amd': {
  7379. const _ = options.compact ? '' : ' ';
  7380. const resolve = options.compact ? 'c' : 'resolve';
  7381. const reject = options.compact ? 'e' : 'reject';
  7382. const helper = getInteropHelper(resolution, exportMode, options.interop);
  7383. const resolveNamespace = helper
  7384. ? `function${_}(m)${_}{${_}${resolve}(/*#__PURE__*/${helper}(m));${_}}`
  7385. : resolve;
  7386. return {
  7387. helper,
  7388. mechanism: {
  7389. left: `new Promise(function${_}(${resolve},${_}${reject})${_}{${_}require([`,
  7390. right: `],${_}${resolveNamespace},${_}${reject})${_}})`
  7391. }
  7392. };
  7393. }
  7394. case 'system':
  7395. return {
  7396. helper: null,
  7397. mechanism: {
  7398. left: 'module.import(',
  7399. right: ')'
  7400. }
  7401. };
  7402. case 'es':
  7403. if (options.dynamicImportFunction) {
  7404. return {
  7405. helper: null,
  7406. mechanism: {
  7407. left: `${options.dynamicImportFunction}(`,
  7408. right: ')'
  7409. }
  7410. };
  7411. }
  7412. }
  7413. return { helper: null, mechanism: null };
  7414. }
  7415. }
  7416. function getInteropHelper(resolution, exportMode, interop) {
  7417. return exportMode === 'external'
  7418. ? namespaceInteropHelpersByInteropType[String(interop(resolution instanceof ExternalModule ? resolution.id : null))]
  7419. : exportMode === 'default'
  7420. ? getDefaultOnlyHelper()
  7421. : null;
  7422. }
  7423. const accessedImportGlobals = {
  7424. amd: ['require'],
  7425. cjs: ['require'],
  7426. system: ['module']
  7427. };
  7428. class ImportNamespaceSpecifier extends NodeBase {
  7429. }
  7430. class ImportSpecifier extends NodeBase {
  7431. }
  7432. class LabeledStatement extends NodeBase {
  7433. hasEffects(context) {
  7434. const brokenFlow = context.brokenFlow;
  7435. context.ignore.labels.add(this.label.name);
  7436. if (this.body.hasEffects(context))
  7437. return true;
  7438. context.ignore.labels.delete(this.label.name);
  7439. if (context.includedLabels.has(this.label.name)) {
  7440. context.includedLabels.delete(this.label.name);
  7441. context.brokenFlow = brokenFlow;
  7442. }
  7443. return false;
  7444. }
  7445. include(context, includeChildrenRecursively) {
  7446. this.included = true;
  7447. const brokenFlow = context.brokenFlow;
  7448. this.body.include(context, includeChildrenRecursively);
  7449. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  7450. this.label.include();
  7451. context.includedLabels.delete(this.label.name);
  7452. context.brokenFlow = brokenFlow;
  7453. }
  7454. }
  7455. render(code, options) {
  7456. if (this.label.included) {
  7457. this.label.render(code, options);
  7458. }
  7459. else {
  7460. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  7461. }
  7462. this.body.render(code, options);
  7463. }
  7464. }
  7465. class LogicalExpression extends NodeBase {
  7466. constructor() {
  7467. super(...arguments);
  7468. // We collect deoptimization information if usedBranch !== null
  7469. this.expressionsToBeDeoptimized = [];
  7470. this.isBranchResolutionAnalysed = false;
  7471. this.usedBranch = null;
  7472. }
  7473. deoptimizeCache() {
  7474. if (this.usedBranch !== null) {
  7475. const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
  7476. this.usedBranch = null;
  7477. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  7478. for (const expression of this.expressionsToBeDeoptimized) {
  7479. expression.deoptimizeCache();
  7480. }
  7481. }
  7482. }
  7483. deoptimizePath(path) {
  7484. const usedBranch = this.getUsedBranch();
  7485. if (usedBranch === null) {
  7486. this.left.deoptimizePath(path);
  7487. this.right.deoptimizePath(path);
  7488. }
  7489. else {
  7490. usedBranch.deoptimizePath(path);
  7491. }
  7492. }
  7493. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  7494. this.left.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  7495. this.right.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  7496. }
  7497. getLiteralValueAtPath(path, recursionTracker, origin) {
  7498. const usedBranch = this.getUsedBranch();
  7499. if (usedBranch === null)
  7500. return UnknownValue;
  7501. this.expressionsToBeDeoptimized.push(origin);
  7502. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  7503. }
  7504. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  7505. const usedBranch = this.getUsedBranch();
  7506. if (usedBranch === null)
  7507. return new MultiExpression([
  7508. this.left.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin),
  7509. this.right.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin)
  7510. ]);
  7511. this.expressionsToBeDeoptimized.push(origin);
  7512. return usedBranch.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
  7513. }
  7514. hasEffects(context) {
  7515. if (this.left.hasEffects(context)) {
  7516. return true;
  7517. }
  7518. if (this.getUsedBranch() !== this.left) {
  7519. return this.right.hasEffects(context);
  7520. }
  7521. return false;
  7522. }
  7523. hasEffectsWhenAccessedAtPath(path, context) {
  7524. const usedBranch = this.getUsedBranch();
  7525. if (usedBranch === null) {
  7526. return (this.left.hasEffectsWhenAccessedAtPath(path, context) ||
  7527. this.right.hasEffectsWhenAccessedAtPath(path, context));
  7528. }
  7529. return usedBranch.hasEffectsWhenAccessedAtPath(path, context);
  7530. }
  7531. hasEffectsWhenAssignedAtPath(path, context) {
  7532. const usedBranch = this.getUsedBranch();
  7533. if (usedBranch === null) {
  7534. return (this.left.hasEffectsWhenAssignedAtPath(path, context) ||
  7535. this.right.hasEffectsWhenAssignedAtPath(path, context));
  7536. }
  7537. return usedBranch.hasEffectsWhenAssignedAtPath(path, context);
  7538. }
  7539. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  7540. const usedBranch = this.getUsedBranch();
  7541. if (usedBranch === null) {
  7542. return (this.left.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
  7543. this.right.hasEffectsWhenCalledAtPath(path, callOptions, context));
  7544. }
  7545. return usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context);
  7546. }
  7547. include(context, includeChildrenRecursively) {
  7548. this.included = true;
  7549. const usedBranch = this.getUsedBranch();
  7550. if (includeChildrenRecursively ||
  7551. (usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
  7552. usedBranch === null) {
  7553. this.left.include(context, includeChildrenRecursively);
  7554. this.right.include(context, includeChildrenRecursively);
  7555. }
  7556. else {
  7557. usedBranch.include(context, includeChildrenRecursively);
  7558. }
  7559. }
  7560. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  7561. if (!this.left.included || !this.right.included) {
  7562. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  7563. if (this.right.included) {
  7564. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  7565. code.remove(this.start, removePos);
  7566. if (preventASI) {
  7567. removeLineBreaks(code, removePos, this.right.start);
  7568. }
  7569. }
  7570. else {
  7571. code.remove(operatorPos, this.end);
  7572. }
  7573. removeAnnotations(this, code);
  7574. this.getUsedBranch().render(code, options, {
  7575. isCalleeOfRenderedParent,
  7576. preventASI,
  7577. renderedParentType: renderedParentType || this.parent.type,
  7578. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  7579. });
  7580. }
  7581. else {
  7582. this.left.render(code, options, {
  7583. preventASI,
  7584. renderedSurroundingElement
  7585. });
  7586. this.right.render(code, options);
  7587. }
  7588. }
  7589. getUsedBranch() {
  7590. if (!this.isBranchResolutionAnalysed) {
  7591. this.isBranchResolutionAnalysed = true;
  7592. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  7593. if (leftValue === UnknownValue) {
  7594. return null;
  7595. }
  7596. else {
  7597. this.usedBranch =
  7598. (this.operator === '||' && leftValue) ||
  7599. (this.operator === '&&' && !leftValue) ||
  7600. (this.operator === '??' && leftValue != null)
  7601. ? this.left
  7602. : this.right;
  7603. }
  7604. }
  7605. return this.usedBranch;
  7606. }
  7607. }
  7608. function spaces(i) {
  7609. let result = '';
  7610. while (i--)
  7611. result += ' ';
  7612. return result;
  7613. }
  7614. function tabsToSpaces(str) {
  7615. return str.replace(/^\t+/, match => match.split('\t').join(' '));
  7616. }
  7617. function getCodeFrame(source, line, column) {
  7618. let lines = source.split('\n');
  7619. const frameStart = Math.max(0, line - 3);
  7620. let frameEnd = Math.min(line + 2, lines.length);
  7621. lines = lines.slice(frameStart, frameEnd);
  7622. while (!/\S/.test(lines[lines.length - 1])) {
  7623. lines.pop();
  7624. frameEnd -= 1;
  7625. }
  7626. const digits = String(frameEnd).length;
  7627. return lines
  7628. .map((str, i) => {
  7629. const isErrorLine = frameStart + i + 1 === line;
  7630. let lineNum = String(i + frameStart + 1);
  7631. while (lineNum.length < digits)
  7632. lineNum = ` ${lineNum}`;
  7633. if (isErrorLine) {
  7634. const indicator = spaces(digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
  7635. return `${lineNum}: ${tabsToSpaces(str)}\n${indicator}`;
  7636. }
  7637. return `${lineNum}: ${tabsToSpaces(str)}`;
  7638. })
  7639. .join('\n');
  7640. }
  7641. function error(base) {
  7642. if (!(base instanceof Error))
  7643. base = Object.assign(new Error(base.message), base);
  7644. throw base;
  7645. }
  7646. function augmentCodeLocation(props, pos, source, id) {
  7647. if (typeof pos === 'object') {
  7648. const { line, column } = pos;
  7649. props.loc = { column, file: id, line };
  7650. }
  7651. else {
  7652. props.pos = pos;
  7653. const { line, column } = locate(source, pos, { offsetLine: 1 });
  7654. props.loc = { column, file: id, line };
  7655. }
  7656. if (props.frame === undefined) {
  7657. const { line, column } = props.loc;
  7658. props.frame = getCodeFrame(source, line, column);
  7659. }
  7660. }
  7661. var Errors;
  7662. (function (Errors) {
  7663. Errors["ALREADY_CLOSED"] = "ALREADY_CLOSED";
  7664. Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
  7665. Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
  7666. Errors["ASSET_SOURCE_ALREADY_SET"] = "ASSET_SOURCE_ALREADY_SET";
  7667. Errors["ASSET_SOURCE_MISSING"] = "ASSET_SOURCE_MISSING";
  7668. Errors["BAD_LOADER"] = "BAD_LOADER";
  7669. Errors["CANNOT_EMIT_FROM_OPTIONS_HOOK"] = "CANNOT_EMIT_FROM_OPTIONS_HOOK";
  7670. Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED";
  7671. Errors["CHUNK_INVALID"] = "CHUNK_INVALID";
  7672. Errors["CIRCULAR_REEXPORT"] = "CIRCULAR_REEXPORT";
  7673. Errors["CYCLIC_CROSS_CHUNK_REEXPORT"] = "CYCLIC_CROSS_CHUNK_REEXPORT";
  7674. Errors["DEPRECATED_FEATURE"] = "DEPRECATED_FEATURE";
  7675. Errors["EXTERNAL_SYNTHETIC_EXPORTS"] = "EXTERNAL_SYNTHETIC_EXPORTS";
  7676. Errors["FILE_NAME_CONFLICT"] = "FILE_NAME_CONFLICT";
  7677. Errors["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
  7678. Errors["INPUT_HOOK_IN_OUTPUT_PLUGIN"] = "INPUT_HOOK_IN_OUTPUT_PLUGIN";
  7679. Errors["INVALID_CHUNK"] = "INVALID_CHUNK";
  7680. Errors["INVALID_EXPORT_OPTION"] = "INVALID_EXPORT_OPTION";
  7681. Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID";
  7682. Errors["INVALID_OPTION"] = "INVALID_OPTION";
  7683. Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
  7684. Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
  7685. Errors["MISSING_EXPORT"] = "MISSING_EXPORT";
  7686. Errors["MISSING_IMPLICIT_DEPENDANT"] = "MISSING_IMPLICIT_DEPENDANT";
  7687. Errors["MIXED_EXPORTS"] = "MIXED_EXPORTS";
  7688. Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT";
  7689. Errors["AMBIGUOUS_EXTERNAL_NAMESPACES"] = "AMBIGUOUS_EXTERNAL_NAMESPACES";
  7690. Errors["NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE"] = "NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE";
  7691. Errors["PLUGIN_ERROR"] = "PLUGIN_ERROR";
  7692. Errors["PREFER_NAMED_EXPORTS"] = "PREFER_NAMED_EXPORTS";
  7693. Errors["SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT"] = "SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT";
  7694. Errors["UNEXPECTED_NAMED_IMPORT"] = "UNEXPECTED_NAMED_IMPORT";
  7695. Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY";
  7696. Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
  7697. Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR";
  7698. })(Errors || (Errors = {}));
  7699. function errAssetNotFinalisedForFileName(name) {
  7700. return {
  7701. code: Errors.ASSET_NOT_FINALISED,
  7702. message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.`
  7703. };
  7704. }
  7705. function errCannotEmitFromOptionsHook() {
  7706. return {
  7707. code: Errors.CANNOT_EMIT_FROM_OPTIONS_HOOK,
  7708. message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
  7709. };
  7710. }
  7711. function errChunkNotGeneratedForFileName(name) {
  7712. return {
  7713. code: Errors.CHUNK_NOT_GENERATED,
  7714. message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.`
  7715. };
  7716. }
  7717. function errChunkInvalid({ fileName, code }, exception) {
  7718. const errorProps = {
  7719. code: Errors.CHUNK_INVALID,
  7720. message: `Chunk "${fileName}" is not valid JavaScript: ${exception.message}.`
  7721. };
  7722. augmentCodeLocation(errorProps, exception.loc, code, fileName);
  7723. return errorProps;
  7724. }
  7725. function errCircularReexport(exportName, importedModule) {
  7726. return {
  7727. code: Errors.CIRCULAR_REEXPORT,
  7728. id: importedModule,
  7729. message: `"${exportName}" cannot be exported from ${relativeId(importedModule)} as it is a reexport that references itself.`
  7730. };
  7731. }
  7732. function errCyclicCrossChunkReexport(exportName, exporter, reexporter, importer) {
  7733. return {
  7734. code: Errors.CYCLIC_CROSS_CHUNK_REEXPORT,
  7735. exporter,
  7736. importer,
  7737. 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.`,
  7738. reexporter
  7739. };
  7740. }
  7741. function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
  7742. return {
  7743. code: Errors.ASSET_NOT_FOUND,
  7744. message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
  7745. };
  7746. }
  7747. function errAssetSourceAlreadySet(name) {
  7748. return {
  7749. code: Errors.ASSET_SOURCE_ALREADY_SET,
  7750. message: `Unable to set the source for asset "${name}", source already set.`
  7751. };
  7752. }
  7753. function errNoAssetSourceSet(assetName) {
  7754. return {
  7755. code: Errors.ASSET_SOURCE_MISSING,
  7756. message: `Plugin error creating asset "${assetName}" - no asset source set.`
  7757. };
  7758. }
  7759. function errBadLoader(id) {
  7760. return {
  7761. code: Errors.BAD_LOADER,
  7762. message: `Error loading ${relativeId(id)}: plugin load hook should return a string, a { code, map } object, or nothing/null`
  7763. };
  7764. }
  7765. function errDeprecation(deprecation) {
  7766. return {
  7767. code: Errors.DEPRECATED_FEATURE,
  7768. ...(typeof deprecation === 'string' ? { message: deprecation } : deprecation)
  7769. };
  7770. }
  7771. function errFileReferenceIdNotFoundForFilename(assetReferenceId) {
  7772. return {
  7773. code: Errors.FILE_NOT_FOUND,
  7774. message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
  7775. };
  7776. }
  7777. function errFileNameConflict(fileName) {
  7778. return {
  7779. code: Errors.FILE_NAME_CONFLICT,
  7780. message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.`
  7781. };
  7782. }
  7783. function errInputHookInOutputPlugin(pluginName, hookName) {
  7784. return {
  7785. code: Errors.INPUT_HOOK_IN_OUTPUT_PLUGIN,
  7786. 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.`
  7787. };
  7788. }
  7789. function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
  7790. return {
  7791. code: Errors.INVALID_CHUNK,
  7792. message: `Cannot assign ${relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
  7793. };
  7794. }
  7795. function errInvalidExportOptionValue(optionValue) {
  7796. return {
  7797. code: Errors.INVALID_EXPORT_OPTION,
  7798. message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}"`,
  7799. url: `https://rollupjs.org/guide/en/#outputexports`
  7800. };
  7801. }
  7802. function errIncompatibleExportOptionValue(optionValue, keys, entryModule) {
  7803. return {
  7804. code: 'INVALID_EXPORT_OPTION',
  7805. message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${keys.join(', ')}`
  7806. };
  7807. }
  7808. function errInternalIdCannotBeExternal(source, importer) {
  7809. return {
  7810. code: Errors.INVALID_EXTERNAL_ID,
  7811. message: `'${source}' is imported as an external by ${relativeId(importer)}, but is already an existing non-external module id.`
  7812. };
  7813. }
  7814. function errInvalidOption(option, explanation) {
  7815. return {
  7816. code: Errors.INVALID_OPTION,
  7817. message: `Invalid value for option "${option}" - ${explanation}.`
  7818. };
  7819. }
  7820. function errInvalidRollupPhaseForAddWatchFile() {
  7821. return {
  7822. code: Errors.INVALID_ROLLUP_PHASE,
  7823. message: `Cannot call addWatchFile after the build has finished.`
  7824. };
  7825. }
  7826. function errInvalidRollupPhaseForChunkEmission() {
  7827. return {
  7828. code: Errors.INVALID_ROLLUP_PHASE,
  7829. message: `Cannot emit chunks after module loading has finished.`
  7830. };
  7831. }
  7832. function errMissingExport(exportName, importingModule, importedModule) {
  7833. return {
  7834. code: Errors.MISSING_EXPORT,
  7835. message: `'${exportName}' is not exported by ${relativeId(importedModule)}, imported by ${relativeId(importingModule)}`,
  7836. url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
  7837. };
  7838. }
  7839. function errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) {
  7840. return {
  7841. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  7842. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" cannot be external.`
  7843. };
  7844. }
  7845. function errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) {
  7846. return {
  7847. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  7848. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" could not be resolved.`
  7849. };
  7850. }
  7851. function errImplicitDependantIsNotIncluded(module) {
  7852. const implicitDependencies = Array.from(module.implicitlyLoadedBefore, dependency => relativeId(dependency.id)).sort();
  7853. return {
  7854. code: Errors.MISSING_IMPLICIT_DEPENDANT,
  7855. message: `Module "${relativeId(module.id)}" that should be implicitly loaded before ${printQuotedStringList(implicitDependencies)} is not included in the module graph. Either it was not imported by an included module or only via a tree-shaken dynamic import, or no imported bindings were used and it had otherwise no side-effects.`
  7856. };
  7857. }
  7858. function errMixedExport(facadeModuleId, name) {
  7859. return {
  7860. code: Errors.MIXED_EXPORTS,
  7861. id: facadeModuleId,
  7862. 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`,
  7863. url: `https://rollupjs.org/guide/en/#outputexports`
  7864. };
  7865. }
  7866. function errNamespaceConflict(name, reexportingModule, additionalExportAllModule) {
  7867. return {
  7868. code: Errors.NAMESPACE_CONFLICT,
  7869. message: `Conflicting namespaces: "${relativeId(reexportingModule.id)}" re-exports "${name}" from both "${relativeId(reexportingModule.exportsAll[name])}" and "${relativeId(additionalExportAllModule.exportsAll[name])}" (will be ignored)`,
  7870. name,
  7871. reexporter: reexportingModule.id,
  7872. sources: [reexportingModule.exportsAll[name], additionalExportAllModule.exportsAll[name]]
  7873. };
  7874. }
  7875. function errAmbiguousExternalNamespaces(name, reexportingModule, usedExternalModule, externalModules) {
  7876. return {
  7877. code: Errors.AMBIGUOUS_EXTERNAL_NAMESPACES,
  7878. message: `Ambiguous external namespace resolution: "${relativeId(reexportingModule)}" re-exports "${name}" from one of the external modules ${printQuotedStringList(externalModules.map(module => relativeId(module)))}, guessing "${relativeId(usedExternalModule)}".`,
  7879. name,
  7880. reexporter: reexportingModule,
  7881. sources: externalModules
  7882. };
  7883. }
  7884. function errNoTransformMapOrAstWithoutCode(pluginName) {
  7885. return {
  7886. code: Errors.NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE,
  7887. message: `The plugin "${pluginName}" returned a "map" or "ast" without returning ` +
  7888. 'a "code". This will be ignored.'
  7889. };
  7890. }
  7891. function errPreferNamedExports(facadeModuleId) {
  7892. const file = relativeId(facadeModuleId);
  7893. return {
  7894. code: Errors.PREFER_NAMED_EXPORTS,
  7895. id: facadeModuleId,
  7896. 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.`,
  7897. url: `https://rollupjs.org/guide/en/#outputexports`
  7898. };
  7899. }
  7900. function errSyntheticNamedExportsNeedNamespaceExport(id, syntheticNamedExportsOption) {
  7901. return {
  7902. code: Errors.SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT,
  7903. id,
  7904. message: `Module "${relativeId(id)}" that is marked with 'syntheticNamedExports: ${JSON.stringify(syntheticNamedExportsOption)}' needs ${typeof syntheticNamedExportsOption === 'string' && syntheticNamedExportsOption !== 'default'
  7905. ? `an export named "${syntheticNamedExportsOption}"`
  7906. : 'a default export'} that does not reexport an unresolved named export of the same module.`
  7907. };
  7908. }
  7909. function errUnexpectedNamedImport(id, imported, isReexport) {
  7910. const importType = isReexport ? 'reexport' : 'import';
  7911. return {
  7912. code: Errors.UNEXPECTED_NAMED_IMPORT,
  7913. id,
  7914. 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.`,
  7915. url: 'https://rollupjs.org/guide/en/#outputinterop'
  7916. };
  7917. }
  7918. function errUnexpectedNamespaceReexport(id) {
  7919. return {
  7920. code: Errors.UNEXPECTED_NAMED_IMPORT,
  7921. id,
  7922. 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.`,
  7923. url: 'https://rollupjs.org/guide/en/#outputinterop'
  7924. };
  7925. }
  7926. function errEntryCannotBeExternal(unresolvedId) {
  7927. return {
  7928. code: Errors.UNRESOLVED_ENTRY,
  7929. message: `Entry module cannot be external (${relativeId(unresolvedId)}).`
  7930. };
  7931. }
  7932. function errUnresolvedEntry(unresolvedId) {
  7933. return {
  7934. code: Errors.UNRESOLVED_ENTRY,
  7935. message: `Could not resolve entry module (${relativeId(unresolvedId)}).`
  7936. };
  7937. }
  7938. function errUnresolvedImport(source, importer) {
  7939. return {
  7940. code: Errors.UNRESOLVED_IMPORT,
  7941. message: `Could not resolve '${source}' from ${relativeId(importer)}`
  7942. };
  7943. }
  7944. function errUnresolvedImportTreatedAsExternal(source, importer) {
  7945. return {
  7946. code: Errors.UNRESOLVED_IMPORT,
  7947. importer: relativeId(importer),
  7948. message: `'${source}' is imported by ${relativeId(importer)}, but could not be resolved – treating it as an external dependency`,
  7949. source,
  7950. url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency'
  7951. };
  7952. }
  7953. function errExternalSyntheticExports(source, importer) {
  7954. return {
  7955. code: Errors.EXTERNAL_SYNTHETIC_EXPORTS,
  7956. importer: relativeId(importer),
  7957. message: `External '${source}' can not have 'syntheticNamedExports' enabled.`,
  7958. source
  7959. };
  7960. }
  7961. function errFailedValidation(message) {
  7962. return {
  7963. code: Errors.VALIDATION_ERROR,
  7964. message
  7965. };
  7966. }
  7967. function errAlreadyClosed() {
  7968. return {
  7969. code: Errors.ALREADY_CLOSED,
  7970. message: 'Bundle is already closed, no more calls to "generate" or "write" are allowed.'
  7971. };
  7972. }
  7973. function warnDeprecation(deprecation, activeDeprecation, options) {
  7974. warnDeprecationWithOptions(deprecation, activeDeprecation, options.onwarn, options.strictDeprecations);
  7975. }
  7976. function warnDeprecationWithOptions(deprecation, activeDeprecation, warn, strictDeprecations) {
  7977. if (activeDeprecation || strictDeprecations) {
  7978. const warning = errDeprecation(deprecation);
  7979. if (strictDeprecations) {
  7980. return error(warning);
  7981. }
  7982. warn(warning);
  7983. }
  7984. }
  7985. const ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
  7986. const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
  7987. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  7988. class MetaProperty extends NodeBase {
  7989. addAccessedGlobals(format, accessedGlobalsByScope) {
  7990. const metaProperty = this.metaProperty;
  7991. const accessedGlobals = (metaProperty &&
  7992. (metaProperty.startsWith(FILE_PREFIX) ||
  7993. metaProperty.startsWith(ASSET_PREFIX) ||
  7994. metaProperty.startsWith(CHUNK_PREFIX))
  7995. ? accessedFileUrlGlobals
  7996. : accessedMetaUrlGlobals)[format];
  7997. if (accessedGlobals.length > 0) {
  7998. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  7999. }
  8000. }
  8001. getReferencedFileName(outputPluginDriver) {
  8002. const metaProperty = this.metaProperty;
  8003. if (metaProperty && metaProperty.startsWith(FILE_PREFIX)) {
  8004. return outputPluginDriver.getFileName(metaProperty.substr(FILE_PREFIX.length));
  8005. }
  8006. return null;
  8007. }
  8008. hasEffects() {
  8009. return false;
  8010. }
  8011. hasEffectsWhenAccessedAtPath(path) {
  8012. return path.length > 1;
  8013. }
  8014. include() {
  8015. if (!this.included) {
  8016. this.included = true;
  8017. if (this.meta.name === 'import') {
  8018. this.context.addImportMeta(this);
  8019. const parent = this.parent;
  8020. this.metaProperty =
  8021. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  8022. ? parent.propertyKey
  8023. : null;
  8024. }
  8025. }
  8026. }
  8027. renderFinalMechanism(code, chunkId, format, outputPluginDriver) {
  8028. var _a;
  8029. const parent = this.parent;
  8030. const metaProperty = this.metaProperty;
  8031. if (metaProperty &&
  8032. (metaProperty.startsWith(FILE_PREFIX) ||
  8033. metaProperty.startsWith(ASSET_PREFIX) ||
  8034. metaProperty.startsWith(CHUNK_PREFIX))) {
  8035. let referenceId = null;
  8036. let assetReferenceId = null;
  8037. let chunkReferenceId = null;
  8038. let fileName;
  8039. if (metaProperty.startsWith(FILE_PREFIX)) {
  8040. referenceId = metaProperty.substr(FILE_PREFIX.length);
  8041. fileName = outputPluginDriver.getFileName(referenceId);
  8042. }
  8043. else if (metaProperty.startsWith(ASSET_PREFIX)) {
  8044. warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
  8045. assetReferenceId = metaProperty.substr(ASSET_PREFIX.length);
  8046. fileName = outputPluginDriver.getFileName(assetReferenceId);
  8047. }
  8048. else {
  8049. warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
  8050. chunkReferenceId = metaProperty.substr(CHUNK_PREFIX.length);
  8051. fileName = outputPluginDriver.getFileName(chunkReferenceId);
  8052. }
  8053. const relativePath = normalize(relative$1(dirname(chunkId), fileName));
  8054. let replacement;
  8055. if (assetReferenceId !== null) {
  8056. replacement = outputPluginDriver.hookFirstSync('resolveAssetUrl', [
  8057. {
  8058. assetFileName: fileName,
  8059. chunkId,
  8060. format,
  8061. moduleId: this.context.module.id,
  8062. relativeAssetPath: relativePath
  8063. }
  8064. ]);
  8065. }
  8066. if (!replacement) {
  8067. replacement =
  8068. outputPluginDriver.hookFirstSync('resolveFileUrl', [
  8069. {
  8070. assetReferenceId,
  8071. chunkId,
  8072. chunkReferenceId,
  8073. fileName,
  8074. format,
  8075. moduleId: this.context.module.id,
  8076. referenceId: referenceId || assetReferenceId || chunkReferenceId,
  8077. relativePath
  8078. }
  8079. ]) || relativeUrlMechanisms[format](relativePath);
  8080. }
  8081. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  8082. return;
  8083. }
  8084. const replacement = outputPluginDriver.hookFirstSync('resolveImportMeta', [
  8085. metaProperty,
  8086. {
  8087. chunkId,
  8088. format,
  8089. moduleId: this.context.module.id
  8090. }
  8091. ]) || ((_a = importMetaMechanisms[format]) === null || _a === void 0 ? void 0 : _a.call(importMetaMechanisms, metaProperty, chunkId));
  8092. if (typeof replacement === 'string') {
  8093. if (parent instanceof MemberExpression) {
  8094. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  8095. }
  8096. else {
  8097. code.overwrite(this.start, this.end, replacement, { contentOnly: true });
  8098. }
  8099. }
  8100. }
  8101. }
  8102. const accessedMetaUrlGlobals = {
  8103. amd: ['document', 'module', 'URL'],
  8104. cjs: ['document', 'require', 'URL'],
  8105. es: [],
  8106. iife: ['document', 'URL'],
  8107. system: ['module'],
  8108. umd: ['document', 'require', 'URL']
  8109. };
  8110. const accessedFileUrlGlobals = {
  8111. amd: ['document', 'require', 'URL'],
  8112. cjs: ['document', 'require', 'URL'],
  8113. es: [],
  8114. iife: ['document', 'URL'],
  8115. system: ['module', 'URL'],
  8116. umd: ['document', 'require', 'URL']
  8117. };
  8118. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  8119. const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${relativePath}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.src || document.baseURI`);
  8120. const getGenericImportMetaMechanism = (getUrl) => (prop, chunkId) => {
  8121. const urlMechanism = getUrl(chunkId);
  8122. return prop === null
  8123. ? `({ url: ${urlMechanism} })`
  8124. : prop === 'url'
  8125. ? urlMechanism
  8126. : 'undefined';
  8127. };
  8128. const getUrlFromDocument = (chunkId, umd = false) => `${umd ? `typeof document === 'undefined' ? location.href : ` : ''}(document.currentScript && document.currentScript.src || new URL('${chunkId}', document.baseURI).href)`;
  8129. const relativeUrlMechanisms = {
  8130. amd: relativePath => {
  8131. if (relativePath[0] !== '.')
  8132. relativePath = './' + relativePath;
  8133. return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
  8134. },
  8135. cjs: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`,
  8136. es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
  8137. iife: relativePath => getRelativeUrlFromDocument(relativePath),
  8138. system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
  8139. umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath, true)})`
  8140. };
  8141. const importMetaMechanisms = {
  8142. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
  8143. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`),
  8144. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  8145. system: prop => (prop === null ? `module.meta` : `module.meta.${prop}`),
  8146. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId, true)})`)
  8147. };
  8148. class NewExpression extends NodeBase {
  8149. constructor() {
  8150. super(...arguments);
  8151. this.deoptimized = false;
  8152. }
  8153. hasEffects(context) {
  8154. if (!this.deoptimized)
  8155. this.applyDeoptimizations();
  8156. for (const argument of this.arguments) {
  8157. if (argument.hasEffects(context))
  8158. return true;
  8159. }
  8160. if (this.context.options.treeshake.annotations &&
  8161. this.annotations)
  8162. return false;
  8163. return (this.callee.hasEffects(context) ||
  8164. this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
  8165. }
  8166. hasEffectsWhenAccessedAtPath(path) {
  8167. return path.length > 0;
  8168. }
  8169. initialise() {
  8170. this.callOptions = {
  8171. args: this.arguments,
  8172. thisParam: null,
  8173. withNew: true
  8174. };
  8175. }
  8176. applyDeoptimizations() {
  8177. this.deoptimized = true;
  8178. for (const argument of this.arguments) {
  8179. // This will make sure all properties of parameters behave as "unknown"
  8180. argument.deoptimizePath(UNKNOWN_PATH);
  8181. }
  8182. this.context.requestTreeshakingPass();
  8183. }
  8184. }
  8185. class ObjectExpression extends NodeBase {
  8186. constructor() {
  8187. super(...arguments);
  8188. this.objectEntity = null;
  8189. }
  8190. deoptimizeCache() {
  8191. this.getObjectEntity().deoptimizeAllProperties();
  8192. }
  8193. deoptimizePath(path) {
  8194. this.getObjectEntity().deoptimizePath(path);
  8195. }
  8196. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  8197. this.getObjectEntity().deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  8198. }
  8199. getLiteralValueAtPath(path, recursionTracker, origin) {
  8200. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  8201. }
  8202. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  8203. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin);
  8204. }
  8205. hasEffectsWhenAccessedAtPath(path, context) {
  8206. return this.getObjectEntity().hasEffectsWhenAccessedAtPath(path, context);
  8207. }
  8208. hasEffectsWhenAssignedAtPath(path, context) {
  8209. return this.getObjectEntity().hasEffectsWhenAssignedAtPath(path, context);
  8210. }
  8211. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  8212. return this.getObjectEntity().hasEffectsWhenCalledAtPath(path, callOptions, context);
  8213. }
  8214. render(code, options, { renderedSurroundingElement } = BLANK) {
  8215. super.render(code, options);
  8216. if (renderedSurroundingElement === ExpressionStatement$1 ||
  8217. renderedSurroundingElement === ArrowFunctionExpression$1) {
  8218. code.appendRight(this.start, '(');
  8219. code.prependLeft(this.end, ')');
  8220. }
  8221. }
  8222. getObjectEntity() {
  8223. if (this.objectEntity !== null) {
  8224. return this.objectEntity;
  8225. }
  8226. let prototype = OBJECT_PROTOTYPE;
  8227. const properties = [];
  8228. for (const property of this.properties) {
  8229. if (property instanceof SpreadElement) {
  8230. properties.push({ key: UnknownKey, kind: 'init', property });
  8231. continue;
  8232. }
  8233. let key;
  8234. if (property.computed) {
  8235. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  8236. if (keyValue === UnknownValue) {
  8237. properties.push({ key: UnknownKey, kind: property.kind, property });
  8238. continue;
  8239. }
  8240. else {
  8241. key = String(keyValue);
  8242. }
  8243. }
  8244. else {
  8245. key =
  8246. property.key instanceof Identifier
  8247. ? property.key.name
  8248. : String(property.key.value);
  8249. if (key === '__proto__' && property.kind === 'init') {
  8250. prototype =
  8251. property.value instanceof Literal && property.value.value === null
  8252. ? null
  8253. : property.value;
  8254. continue;
  8255. }
  8256. }
  8257. properties.push({ key, kind: property.kind, property });
  8258. }
  8259. return (this.objectEntity = new ObjectEntity(properties, prototype));
  8260. }
  8261. }
  8262. class PrivateIdentifier extends NodeBase {
  8263. }
  8264. class Property extends MethodBase {
  8265. constructor() {
  8266. super(...arguments);
  8267. this.deoptimized = false;
  8268. this.declarationInit = null;
  8269. }
  8270. declare(kind, init) {
  8271. this.declarationInit = init;
  8272. return this.value.declare(kind, UNKNOWN_EXPRESSION);
  8273. }
  8274. hasEffects(context) {
  8275. if (!this.deoptimized)
  8276. this.applyDeoptimizations();
  8277. const propertyReadSideEffects = this.context.options.treeshake
  8278. .propertyReadSideEffects;
  8279. return ((this.parent.type === 'ObjectPattern' && propertyReadSideEffects === 'always') ||
  8280. this.key.hasEffects(context) ||
  8281. this.value.hasEffects(context));
  8282. }
  8283. markDeclarationReached() {
  8284. this.value.markDeclarationReached();
  8285. }
  8286. render(code, options) {
  8287. if (!this.shorthand) {
  8288. this.key.render(code, options);
  8289. }
  8290. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  8291. }
  8292. applyDeoptimizations() {
  8293. this.deoptimized = true;
  8294. if (this.declarationInit !== null) {
  8295. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  8296. this.context.requestTreeshakingPass();
  8297. }
  8298. }
  8299. }
  8300. class PropertyDefinition extends NodeBase {
  8301. deoptimizePath(path) {
  8302. var _a;
  8303. (_a = this.value) === null || _a === void 0 ? void 0 : _a.deoptimizePath(path);
  8304. }
  8305. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  8306. var _a;
  8307. (_a = this.value) === null || _a === void 0 ? void 0 : _a.deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  8308. }
  8309. getLiteralValueAtPath(path, recursionTracker, origin) {
  8310. return this.value
  8311. ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
  8312. : UnknownValue;
  8313. }
  8314. getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin) {
  8315. return this.value
  8316. ? this.value.getReturnExpressionWhenCalledAtPath(path, callOptions, recursionTracker, origin)
  8317. : UNKNOWN_EXPRESSION;
  8318. }
  8319. hasEffects(context) {
  8320. return (this.key.hasEffects(context) ||
  8321. (this.static && this.value !== null && this.value.hasEffects(context)));
  8322. }
  8323. hasEffectsWhenAccessedAtPath(path, context) {
  8324. return !this.value || this.value.hasEffectsWhenAccessedAtPath(path, context);
  8325. }
  8326. hasEffectsWhenAssignedAtPath(path, context) {
  8327. return !this.value || this.value.hasEffectsWhenAssignedAtPath(path, context);
  8328. }
  8329. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  8330. return !this.value || this.value.hasEffectsWhenCalledAtPath(path, callOptions, context);
  8331. }
  8332. }
  8333. class ReturnStatement extends NodeBase {
  8334. hasEffects(context) {
  8335. if (!context.ignore.returnYield ||
  8336. (this.argument !== null && this.argument.hasEffects(context)))
  8337. return true;
  8338. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  8339. return false;
  8340. }
  8341. include(context, includeChildrenRecursively) {
  8342. this.included = true;
  8343. if (this.argument) {
  8344. this.argument.include(context, includeChildrenRecursively);
  8345. }
  8346. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  8347. }
  8348. initialise() {
  8349. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  8350. }
  8351. render(code, options) {
  8352. if (this.argument) {
  8353. this.argument.render(code, options, { preventASI: true });
  8354. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  8355. code.prependLeft(this.start + 6, ' ');
  8356. }
  8357. }
  8358. }
  8359. }
  8360. class SequenceExpression extends NodeBase {
  8361. deoptimizePath(path) {
  8362. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  8363. }
  8364. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  8365. this.expressions[this.expressions.length - 1].deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker);
  8366. }
  8367. getLiteralValueAtPath(path, recursionTracker, origin) {
  8368. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  8369. }
  8370. hasEffects(context) {
  8371. for (const expression of this.expressions) {
  8372. if (expression.hasEffects(context))
  8373. return true;
  8374. }
  8375. return false;
  8376. }
  8377. hasEffectsWhenAccessedAtPath(path, context) {
  8378. return (path.length > 0 &&
  8379. this.expressions[this.expressions.length - 1].hasEffectsWhenAccessedAtPath(path, context));
  8380. }
  8381. hasEffectsWhenAssignedAtPath(path, context) {
  8382. return this.expressions[this.expressions.length - 1].hasEffectsWhenAssignedAtPath(path, context);
  8383. }
  8384. hasEffectsWhenCalledAtPath(path, callOptions, context) {
  8385. return this.expressions[this.expressions.length - 1].hasEffectsWhenCalledAtPath(path, callOptions, context);
  8386. }
  8387. include(context, includeChildrenRecursively) {
  8388. this.included = true;
  8389. const lastExpression = this.expressions[this.expressions.length - 1];
  8390. for (const expression of this.expressions) {
  8391. if (includeChildrenRecursively ||
  8392. (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
  8393. expression.shouldBeIncluded(context))
  8394. expression.include(context, includeChildrenRecursively);
  8395. }
  8396. }
  8397. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  8398. let includedNodes = 0;
  8399. let lastSeparatorPos = null;
  8400. const lastNode = this.expressions[this.expressions.length - 1];
  8401. for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  8402. if (!node.included) {
  8403. treeshakeNode(node, code, start, end);
  8404. continue;
  8405. }
  8406. includedNodes++;
  8407. lastSeparatorPos = separator;
  8408. if (includedNodes === 1 && preventASI) {
  8409. removeLineBreaks(code, start, node.start);
  8410. }
  8411. if (includedNodes === 1) {
  8412. const parentType = renderedParentType || this.parent.type;
  8413. node.render(code, options, {
  8414. isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
  8415. renderedParentType: parentType,
  8416. renderedSurroundingElement: parentType
  8417. });
  8418. }
  8419. else {
  8420. node.render(code, options);
  8421. }
  8422. }
  8423. if (lastSeparatorPos) {
  8424. code.remove(lastSeparatorPos, this.end);
  8425. }
  8426. }
  8427. }
  8428. class Super extends NodeBase {
  8429. bind() {
  8430. this.variable = this.scope.findVariable('this');
  8431. }
  8432. deoptimizePath(path) {
  8433. this.variable.deoptimizePath(path);
  8434. }
  8435. include() {
  8436. if (!this.included) {
  8437. this.included = true;
  8438. this.context.includeVariableInModule(this.variable);
  8439. }
  8440. }
  8441. }
  8442. class SwitchCase extends NodeBase {
  8443. hasEffects(context) {
  8444. if (this.test && this.test.hasEffects(context))
  8445. return true;
  8446. for (const node of this.consequent) {
  8447. if (context.brokenFlow)
  8448. break;
  8449. if (node.hasEffects(context))
  8450. return true;
  8451. }
  8452. return false;
  8453. }
  8454. include(context, includeChildrenRecursively) {
  8455. this.included = true;
  8456. if (this.test)
  8457. this.test.include(context, includeChildrenRecursively);
  8458. for (const node of this.consequent) {
  8459. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  8460. node.include(context, includeChildrenRecursively);
  8461. }
  8462. }
  8463. render(code, options, nodeRenderOptions) {
  8464. if (this.consequent.length) {
  8465. this.test && this.test.render(code, options);
  8466. const testEnd = this.test
  8467. ? this.test.end
  8468. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  8469. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  8470. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  8471. }
  8472. else {
  8473. super.render(code, options);
  8474. }
  8475. }
  8476. }
  8477. SwitchCase.prototype.needsBoundaries = true;
  8478. class SwitchStatement extends NodeBase {
  8479. createScope(parentScope) {
  8480. this.scope = new BlockScope(parentScope);
  8481. }
  8482. hasEffects(context) {
  8483. if (this.discriminant.hasEffects(context))
  8484. return true;
  8485. const { brokenFlow, ignore: { breaks } } = context;
  8486. let minBrokenFlow = Infinity;
  8487. context.ignore.breaks = true;
  8488. for (const switchCase of this.cases) {
  8489. if (switchCase.hasEffects(context))
  8490. return true;
  8491. minBrokenFlow = context.brokenFlow < minBrokenFlow ? context.brokenFlow : minBrokenFlow;
  8492. context.brokenFlow = brokenFlow;
  8493. }
  8494. if (this.defaultCase !== null && !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
  8495. context.brokenFlow = minBrokenFlow;
  8496. }
  8497. context.ignore.breaks = breaks;
  8498. return false;
  8499. }
  8500. include(context, includeChildrenRecursively) {
  8501. this.included = true;
  8502. this.discriminant.include(context, includeChildrenRecursively);
  8503. const { brokenFlow } = context;
  8504. let minBrokenFlow = Infinity;
  8505. let isCaseIncluded = includeChildrenRecursively ||
  8506. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  8507. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  8508. const switchCase = this.cases[caseIndex];
  8509. if (switchCase.included) {
  8510. isCaseIncluded = true;
  8511. }
  8512. if (!isCaseIncluded) {
  8513. const hasEffectsContext = createHasEffectsContext();
  8514. hasEffectsContext.ignore.breaks = true;
  8515. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  8516. }
  8517. if (isCaseIncluded) {
  8518. switchCase.include(context, includeChildrenRecursively);
  8519. minBrokenFlow = minBrokenFlow < context.brokenFlow ? minBrokenFlow : context.brokenFlow;
  8520. context.brokenFlow = brokenFlow;
  8521. }
  8522. else {
  8523. minBrokenFlow = brokenFlow;
  8524. }
  8525. }
  8526. if (isCaseIncluded &&
  8527. this.defaultCase !== null &&
  8528. !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
  8529. context.brokenFlow = minBrokenFlow;
  8530. }
  8531. }
  8532. initialise() {
  8533. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  8534. if (this.cases[caseIndex].test === null) {
  8535. this.defaultCase = caseIndex;
  8536. return;
  8537. }
  8538. }
  8539. this.defaultCase = null;
  8540. }
  8541. render(code, options) {
  8542. this.discriminant.render(code, options);
  8543. if (this.cases.length > 0) {
  8544. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  8545. }
  8546. }
  8547. }
  8548. class TaggedTemplateExpression extends NodeBase {
  8549. bind() {
  8550. super.bind();
  8551. if (this.tag.type === Identifier$1) {
  8552. const name = this.tag.name;
  8553. const variable = this.scope.findVariable(name);
  8554. if (variable.isNamespace) {
  8555. this.context.warn({
  8556. code: 'CANNOT_CALL_NAMESPACE',
  8557. message: `Cannot call a namespace ('${name}')`
  8558. }, this.start);
  8559. }
  8560. }
  8561. }
  8562. hasEffects(context) {
  8563. return (super.hasEffects(context) ||
  8564. this.tag.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
  8565. }
  8566. initialise() {
  8567. this.callOptions = {
  8568. args: NO_ARGS,
  8569. thisParam: null,
  8570. withNew: false
  8571. };
  8572. }
  8573. render(code, options) {
  8574. this.tag.render(code, options, { isCalleeOfRenderedParent: true });
  8575. this.quasi.render(code, options);
  8576. }
  8577. }
  8578. class TemplateElement extends NodeBase {
  8579. // Do not try to bind value
  8580. bind() { }
  8581. hasEffects() {
  8582. return false;
  8583. }
  8584. include() {
  8585. this.included = true;
  8586. }
  8587. parseNode(esTreeNode) {
  8588. this.value = esTreeNode.value;
  8589. super.parseNode(esTreeNode);
  8590. }
  8591. render() { }
  8592. }
  8593. class UndefinedVariable extends Variable {
  8594. constructor() {
  8595. super('undefined');
  8596. }
  8597. getLiteralValueAtPath() {
  8598. return undefined;
  8599. }
  8600. }
  8601. class ExportDefaultVariable extends LocalVariable {
  8602. constructor(name, exportDefaultDeclaration, context) {
  8603. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
  8604. this.hasId = false;
  8605. this.originalId = null;
  8606. this.originalVariable = null;
  8607. const declaration = exportDefaultDeclaration.declaration;
  8608. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  8609. declaration.id) {
  8610. this.hasId = true;
  8611. this.originalId = declaration.id;
  8612. }
  8613. else if (declaration instanceof Identifier) {
  8614. this.originalId = declaration;
  8615. }
  8616. }
  8617. addReference(identifier) {
  8618. if (!this.hasId) {
  8619. this.name = identifier.name;
  8620. }
  8621. }
  8622. getAssignedVariableName() {
  8623. return (this.originalId && this.originalId.name) || null;
  8624. }
  8625. getBaseVariableName() {
  8626. const original = this.getOriginalVariable();
  8627. if (original === this) {
  8628. return super.getBaseVariableName();
  8629. }
  8630. else {
  8631. return original.getBaseVariableName();
  8632. }
  8633. }
  8634. getDirectOriginalVariable() {
  8635. return this.originalId &&
  8636. (this.hasId ||
  8637. !(this.originalId.isPossibleTDZ() ||
  8638. this.originalId.variable.isReassigned ||
  8639. this.originalId.variable instanceof UndefinedVariable ||
  8640. // this avoids a circular dependency
  8641. 'syntheticNamespace' in this.originalId.variable))
  8642. ? this.originalId.variable
  8643. : null;
  8644. }
  8645. getName() {
  8646. const original = this.getOriginalVariable();
  8647. if (original === this) {
  8648. return super.getName();
  8649. }
  8650. else {
  8651. return original.getName();
  8652. }
  8653. }
  8654. getOriginalVariable() {
  8655. if (this.originalVariable)
  8656. return this.originalVariable;
  8657. // eslint-disable-next-line @typescript-eslint/no-this-alias
  8658. let original = this;
  8659. let currentVariable;
  8660. const checkedVariables = new Set();
  8661. do {
  8662. checkedVariables.add(original);
  8663. currentVariable = original;
  8664. original = currentVariable.getDirectOriginalVariable();
  8665. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  8666. return (this.originalVariable = original || currentVariable);
  8667. }
  8668. }
  8669. class ModuleScope extends ChildScope {
  8670. constructor(parent, context) {
  8671. super(parent);
  8672. this.context = context;
  8673. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
  8674. }
  8675. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  8676. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  8677. this.variables.set('default', variable);
  8678. return variable;
  8679. }
  8680. addNamespaceMemberAccess() { }
  8681. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  8682. // all module level variables are already deconflicted when deconflicting the chunk
  8683. for (const scope of this.children)
  8684. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  8685. }
  8686. findLexicalBoundary() {
  8687. return this;
  8688. }
  8689. findVariable(name) {
  8690. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  8691. if (knownVariable) {
  8692. return knownVariable;
  8693. }
  8694. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  8695. if (variable instanceof GlobalVariable) {
  8696. this.accessedOutsideVariables.set(name, variable);
  8697. }
  8698. return variable;
  8699. }
  8700. }
  8701. class ThisExpression extends NodeBase {
  8702. bind() {
  8703. this.variable = this.scope.findVariable('this');
  8704. }
  8705. deoptimizePath(path) {
  8706. this.variable.deoptimizePath(path);
  8707. }
  8708. deoptimizeThisOnEventAtPath(event, path, thisParameter, recursionTracker) {
  8709. this.variable.deoptimizeThisOnEventAtPath(event, path,
  8710. // We rewrite the parameter so that a ThisVariable can detect self-mutations
  8711. thisParameter === this ? this.variable : thisParameter, recursionTracker);
  8712. }
  8713. hasEffectsWhenAccessedAtPath(path, context) {
  8714. return path.length > 0 && this.variable.hasEffectsWhenAccessedAtPath(path, context);
  8715. }
  8716. hasEffectsWhenAssignedAtPath(path, context) {
  8717. return this.variable.hasEffectsWhenAssignedAtPath(path, context);
  8718. }
  8719. include() {
  8720. if (!this.included) {
  8721. this.included = true;
  8722. this.context.includeVariableInModule(this.variable);
  8723. }
  8724. }
  8725. initialise() {
  8726. this.alias =
  8727. this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
  8728. if (this.alias === 'undefined') {
  8729. this.context.warn({
  8730. code: 'THIS_IS_UNDEFINED',
  8731. message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
  8732. url: `https://rollupjs.org/guide/en/#error-this-is-undefined`
  8733. }, this.start);
  8734. }
  8735. }
  8736. render(code) {
  8737. if (this.alias !== null) {
  8738. code.overwrite(this.start, this.end, this.alias, {
  8739. contentOnly: false,
  8740. storeName: true
  8741. });
  8742. }
  8743. }
  8744. }
  8745. class ThrowStatement extends NodeBase {
  8746. hasEffects() {
  8747. return true;
  8748. }
  8749. include(context, includeChildrenRecursively) {
  8750. this.included = true;
  8751. this.argument.include(context, includeChildrenRecursively);
  8752. context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
  8753. }
  8754. render(code, options) {
  8755. this.argument.render(code, options, { preventASI: true });
  8756. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  8757. code.prependLeft(this.start + 5, ' ');
  8758. }
  8759. }
  8760. }
  8761. class TryStatement extends NodeBase {
  8762. constructor() {
  8763. super(...arguments);
  8764. this.directlyIncluded = false;
  8765. this.includedLabelsAfterBlock = null;
  8766. }
  8767. hasEffects(context) {
  8768. return ((this.context.options.treeshake.tryCatchDeoptimization
  8769. ? this.block.body.length > 0
  8770. : this.block.hasEffects(context)) ||
  8771. (this.finalizer !== null && this.finalizer.hasEffects(context)));
  8772. }
  8773. include(context, includeChildrenRecursively) {
  8774. var _a;
  8775. const tryCatchDeoptimization = (_a = this.context.options.treeshake) === null || _a === void 0 ? void 0 : _a.tryCatchDeoptimization;
  8776. const { brokenFlow } = context;
  8777. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  8778. this.included = true;
  8779. this.directlyIncluded = true;
  8780. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  8781. if (context.includedLabels.size > 0) {
  8782. this.includedLabelsAfterBlock = [...context.includedLabels];
  8783. }
  8784. context.brokenFlow = brokenFlow;
  8785. }
  8786. else if (this.includedLabelsAfterBlock) {
  8787. for (const label of this.includedLabelsAfterBlock) {
  8788. context.includedLabels.add(label);
  8789. }
  8790. }
  8791. if (this.handler !== null) {
  8792. this.handler.include(context, includeChildrenRecursively);
  8793. context.brokenFlow = brokenFlow;
  8794. }
  8795. if (this.finalizer !== null) {
  8796. this.finalizer.include(context, includeChildrenRecursively);
  8797. }
  8798. }
  8799. }
  8800. const unaryOperators = {
  8801. '!': value => !value,
  8802. '+': value => +value,
  8803. '-': value => -value,
  8804. delete: () => UnknownValue,
  8805. typeof: value => typeof value,
  8806. void: () => undefined,
  8807. '~': value => ~value
  8808. };
  8809. class UnaryExpression extends NodeBase {
  8810. constructor() {
  8811. super(...arguments);
  8812. this.deoptimized = false;
  8813. }
  8814. getLiteralValueAtPath(path, recursionTracker, origin) {
  8815. if (path.length > 0)
  8816. return UnknownValue;
  8817. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  8818. if (argumentValue === UnknownValue)
  8819. return UnknownValue;
  8820. return unaryOperators[this.operator](argumentValue);
  8821. }
  8822. hasEffects(context) {
  8823. if (!this.deoptimized)
  8824. this.applyDeoptimizations();
  8825. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  8826. return false;
  8827. return (this.argument.hasEffects(context) ||
  8828. (this.operator === 'delete' &&
  8829. this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context)));
  8830. }
  8831. hasEffectsWhenAccessedAtPath(path) {
  8832. if (this.operator === 'void') {
  8833. return path.length > 0;
  8834. }
  8835. return path.length > 1;
  8836. }
  8837. applyDeoptimizations() {
  8838. this.deoptimized = true;
  8839. if (this.operator === 'delete') {
  8840. this.argument.deoptimizePath(EMPTY_PATH);
  8841. this.context.requestTreeshakingPass();
  8842. }
  8843. }
  8844. }
  8845. class UnknownNode extends NodeBase {
  8846. hasEffects() {
  8847. return true;
  8848. }
  8849. include(context) {
  8850. super.include(context, true);
  8851. }
  8852. }
  8853. class UpdateExpression extends NodeBase {
  8854. constructor() {
  8855. super(...arguments);
  8856. this.deoptimized = false;
  8857. }
  8858. hasEffects(context) {
  8859. if (!this.deoptimized)
  8860. this.applyDeoptimizations();
  8861. return (this.argument.hasEffects(context) ||
  8862. this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context));
  8863. }
  8864. hasEffectsWhenAccessedAtPath(path) {
  8865. return path.length > 1;
  8866. }
  8867. render(code, options) {
  8868. this.argument.render(code, options);
  8869. if (options.format === 'system') {
  8870. const variable = this.argument.variable;
  8871. const exportNames = options.exportNamesByVariable.get(variable);
  8872. if (exportNames) {
  8873. const _ = options.compact ? '' : ' ';
  8874. if (this.prefix) {
  8875. if (exportNames.length === 1) {
  8876. renderSystemExportExpression(variable, this.start, this.end, code, options);
  8877. }
  8878. else {
  8879. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options);
  8880. }
  8881. }
  8882. else {
  8883. const operator = this.operator[0];
  8884. renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options, `${_}${operator}${_}1`);
  8885. }
  8886. }
  8887. }
  8888. }
  8889. applyDeoptimizations() {
  8890. this.deoptimized = true;
  8891. this.argument.deoptimizePath(EMPTY_PATH);
  8892. if (this.argument instanceof Identifier) {
  8893. const variable = this.scope.findVariable(this.argument.name);
  8894. variable.isReassigned = true;
  8895. }
  8896. this.context.requestTreeshakingPass();
  8897. }
  8898. }
  8899. class VariableDeclarator extends NodeBase {
  8900. declareDeclarator(kind) {
  8901. this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
  8902. }
  8903. deoptimizePath(path) {
  8904. this.id.deoptimizePath(path);
  8905. }
  8906. hasEffects(context) {
  8907. const initEffect = this.init !== null && this.init.hasEffects(context);
  8908. this.id.markDeclarationReached();
  8909. return initEffect || this.id.hasEffects(context);
  8910. }
  8911. include(context, includeChildrenRecursively) {
  8912. this.included = true;
  8913. if (this.init) {
  8914. this.init.include(context, includeChildrenRecursively);
  8915. }
  8916. this.id.markDeclarationReached();
  8917. if (includeChildrenRecursively || this.id.shouldBeIncluded(context)) {
  8918. this.id.include(context, includeChildrenRecursively);
  8919. }
  8920. }
  8921. render(code, options) {
  8922. const renderId = this.id.included;
  8923. if (renderId) {
  8924. this.id.render(code, options);
  8925. }
  8926. else {
  8927. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', this.id.end);
  8928. code.remove(this.start, findNonWhiteSpace(code.original, operatorPos + 1));
  8929. }
  8930. if (this.init) {
  8931. this.init.render(code, options, renderId ? BLANK : { renderedSurroundingElement: ExpressionStatement$1 });
  8932. }
  8933. else if (this.id instanceof Identifier &&
  8934. isReassignedExportsMember(this.id.variable, options.exportNamesByVariable)) {
  8935. const _ = options.compact ? '' : ' ';
  8936. code.appendLeft(this.end, `${_}=${_}void 0`);
  8937. }
  8938. }
  8939. }
  8940. class WhileStatement extends NodeBase {
  8941. hasEffects(context) {
  8942. if (this.test.hasEffects(context))
  8943. return true;
  8944. const { brokenFlow, ignore: { breaks, continues } } = context;
  8945. context.ignore.breaks = true;
  8946. context.ignore.continues = true;
  8947. if (this.body.hasEffects(context))
  8948. return true;
  8949. context.ignore.breaks = breaks;
  8950. context.ignore.continues = continues;
  8951. context.brokenFlow = brokenFlow;
  8952. return false;
  8953. }
  8954. include(context, includeChildrenRecursively) {
  8955. this.included = true;
  8956. this.test.include(context, includeChildrenRecursively);
  8957. const { brokenFlow } = context;
  8958. this.body.includeAsSingleStatement(context, includeChildrenRecursively);
  8959. context.brokenFlow = brokenFlow;
  8960. }
  8961. }
  8962. class YieldExpression extends NodeBase {
  8963. constructor() {
  8964. super(...arguments);
  8965. this.deoptimized = false;
  8966. }
  8967. hasEffects(context) {
  8968. if (!this.deoptimized)
  8969. this.applyDeoptimizations();
  8970. return (!context.ignore.returnYield || (this.argument !== null && this.argument.hasEffects(context)));
  8971. }
  8972. render(code, options) {
  8973. if (this.argument) {
  8974. this.argument.render(code, options, { preventASI: true });
  8975. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  8976. code.prependLeft(this.start + 5, ' ');
  8977. }
  8978. }
  8979. }
  8980. applyDeoptimizations() {
  8981. this.deoptimized = true;
  8982. const { argument } = this;
  8983. if (argument) {
  8984. argument.deoptimizePath(UNKNOWN_PATH);
  8985. this.context.requestTreeshakingPass();
  8986. }
  8987. }
  8988. }
  8989. const nodeConstructors = {
  8990. ArrayExpression,
  8991. ArrayPattern,
  8992. ArrowFunctionExpression,
  8993. AssignmentExpression,
  8994. AssignmentPattern,
  8995. AwaitExpression,
  8996. BinaryExpression,
  8997. BlockStatement,
  8998. BreakStatement,
  8999. CallExpression,
  9000. CatchClause,
  9001. ChainExpression,
  9002. ClassBody,
  9003. ClassDeclaration,
  9004. ClassExpression,
  9005. ConditionalExpression,
  9006. ContinueStatement,
  9007. DoWhileStatement,
  9008. EmptyStatement,
  9009. ExportAllDeclaration,
  9010. ExportDefaultDeclaration,
  9011. ExportNamedDeclaration,
  9012. ExportSpecifier,
  9013. ExpressionStatement,
  9014. ForInStatement,
  9015. ForOfStatement,
  9016. ForStatement,
  9017. FunctionDeclaration,
  9018. FunctionExpression,
  9019. Identifier,
  9020. IfStatement,
  9021. ImportDeclaration,
  9022. ImportDefaultSpecifier,
  9023. ImportExpression,
  9024. ImportNamespaceSpecifier,
  9025. ImportSpecifier,
  9026. LabeledStatement,
  9027. Literal,
  9028. LogicalExpression,
  9029. MemberExpression,
  9030. MetaProperty,
  9031. MethodDefinition,
  9032. NewExpression,
  9033. ObjectExpression,
  9034. ObjectPattern,
  9035. PrivateIdentifier,
  9036. Program,
  9037. Property,
  9038. PropertyDefinition,
  9039. RestElement,
  9040. ReturnStatement,
  9041. SequenceExpression,
  9042. SpreadElement,
  9043. Super,
  9044. SwitchCase,
  9045. SwitchStatement,
  9046. TaggedTemplateExpression,
  9047. TemplateElement,
  9048. TemplateLiteral,
  9049. ThisExpression,
  9050. ThrowStatement,
  9051. TryStatement,
  9052. UnaryExpression,
  9053. UnknownNode,
  9054. UpdateExpression,
  9055. VariableDeclaration,
  9056. VariableDeclarator,
  9057. WhileStatement,
  9058. YieldExpression
  9059. };
  9060. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  9061. class ExportShimVariable extends Variable {
  9062. constructor(module) {
  9063. super(MISSING_EXPORT_SHIM_VARIABLE);
  9064. this.module = module;
  9065. }
  9066. }
  9067. class NamespaceVariable extends Variable {
  9068. constructor(context, syntheticNamedExports) {
  9069. super(context.getModuleName());
  9070. this.memberVariables = null;
  9071. this.mergedNamespaces = [];
  9072. this.referencedEarly = false;
  9073. this.references = [];
  9074. this.context = context;
  9075. this.module = context.module;
  9076. this.syntheticNamedExports = syntheticNamedExports;
  9077. }
  9078. addReference(identifier) {
  9079. this.references.push(identifier);
  9080. this.name = identifier.name;
  9081. }
  9082. getMemberVariables() {
  9083. if (this.memberVariables) {
  9084. return this.memberVariables;
  9085. }
  9086. const memberVariables = Object.create(null);
  9087. for (const name of this.context.getExports().concat(this.context.getReexports())) {
  9088. if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
  9089. const exportedVariable = this.context.traceExport(name);
  9090. if (exportedVariable) {
  9091. memberVariables[name] = exportedVariable;
  9092. }
  9093. }
  9094. }
  9095. return (this.memberVariables = memberVariables);
  9096. }
  9097. include() {
  9098. this.included = true;
  9099. this.context.includeAllExports();
  9100. }
  9101. prepareNamespace(mergedNamespaces) {
  9102. this.mergedNamespaces = mergedNamespaces;
  9103. const moduleExecIndex = this.context.getModuleExecIndex();
  9104. for (const identifier of this.references) {
  9105. if (identifier.context.getModuleExecIndex() <= moduleExecIndex) {
  9106. this.referencedEarly = true;
  9107. break;
  9108. }
  9109. }
  9110. }
  9111. renderBlock(options) {
  9112. const _ = options.compact ? '' : ' ';
  9113. const n = options.compact ? '' : '\n';
  9114. const t = options.indent;
  9115. const memberVariables = this.getMemberVariables();
  9116. const members = Object.entries(memberVariables).map(([name, original]) => {
  9117. if (this.referencedEarly || original.isReassigned) {
  9118. return `${t}get ${name}${_}()${_}{${_}return ${original.getName()}${options.compact ? '' : ';'}${_}}`;
  9119. }
  9120. const safeName = RESERVED_NAMES[name] ? `'${name}'` : name;
  9121. return `${t}${safeName}: ${original.getName()}`;
  9122. });
  9123. if (options.namespaceToStringTag) {
  9124. members.unshift(`${t}[Symbol.toStringTag]:${_}'Module'`);
  9125. }
  9126. const needsObjectAssign = this.mergedNamespaces.length > 0 || this.syntheticNamedExports;
  9127. if (!needsObjectAssign)
  9128. members.unshift(`${t}__proto__:${_}null`);
  9129. let output = `{${n}${members.join(`,${n}`)}${n}}`;
  9130. if (needsObjectAssign) {
  9131. const assignmentArgs = ['/*#__PURE__*/Object.create(null)'];
  9132. if (this.mergedNamespaces.length > 0) {
  9133. assignmentArgs.push(...this.mergedNamespaces.map(variable => variable.getName()));
  9134. }
  9135. if (this.syntheticNamedExports) {
  9136. assignmentArgs.push(this.module.getSyntheticNamespace().getName());
  9137. }
  9138. if (members.length > 0) {
  9139. assignmentArgs.push(output);
  9140. }
  9141. output = `/*#__PURE__*/Object.assign(${assignmentArgs.join(`,${_}`)})`;
  9142. }
  9143. if (options.freeze) {
  9144. output = `/*#__PURE__*/Object.freeze(${output})`;
  9145. }
  9146. const name = this.getName();
  9147. output = `${options.varOrConst} ${name}${_}=${_}${output};`;
  9148. if (options.format === 'system' && options.exportNamesByVariable.has(this)) {
  9149. output += `${n}${getSystemExportStatement([this], options)};`;
  9150. }
  9151. return output;
  9152. }
  9153. renderFirst() {
  9154. return this.referencedEarly;
  9155. }
  9156. }
  9157. NamespaceVariable.prototype.isNamespace = true;
  9158. class SyntheticNamedExportVariable extends Variable {
  9159. constructor(context, name, syntheticNamespace) {
  9160. super(name);
  9161. this.baseVariable = null;
  9162. this.context = context;
  9163. this.module = context.module;
  9164. this.syntheticNamespace = syntheticNamespace;
  9165. }
  9166. getBaseVariable() {
  9167. if (this.baseVariable)
  9168. return this.baseVariable;
  9169. let baseVariable = this.syntheticNamespace;
  9170. while (baseVariable instanceof ExportDefaultVariable ||
  9171. baseVariable instanceof SyntheticNamedExportVariable) {
  9172. if (baseVariable instanceof ExportDefaultVariable) {
  9173. const original = baseVariable.getOriginalVariable();
  9174. if (original === baseVariable)
  9175. break;
  9176. baseVariable = original;
  9177. }
  9178. if (baseVariable instanceof SyntheticNamedExportVariable) {
  9179. baseVariable = baseVariable.syntheticNamespace;
  9180. }
  9181. }
  9182. return (this.baseVariable = baseVariable);
  9183. }
  9184. getBaseVariableName() {
  9185. return this.syntheticNamespace.getBaseVariableName();
  9186. }
  9187. getName() {
  9188. const name = this.name;
  9189. return `${this.syntheticNamespace.getName()}${getPropertyAccess(name)}`;
  9190. }
  9191. include() {
  9192. if (!this.included) {
  9193. this.included = true;
  9194. this.context.includeVariableInModule(this.syntheticNamespace);
  9195. }
  9196. }
  9197. setRenderNames(baseName, name) {
  9198. super.setRenderNames(baseName, name);
  9199. }
  9200. }
  9201. const getPropertyAccess = (name) => {
  9202. return !RESERVED_NAMES[name] && /^(?!\d)[\w$]+$/.test(name)
  9203. ? `.${name}`
  9204. : `[${JSON.stringify(name)}]`;
  9205. };
  9206. function getId(m) {
  9207. return m.id;
  9208. }
  9209. function getOriginalLocation(sourcemapChain, location) {
  9210. // This cast is guaranteed. If it were a missing Map, it wouldn't have a mappings.
  9211. const filteredSourcemapChain = sourcemapChain.filter(sourcemap => sourcemap.mappings);
  9212. while (filteredSourcemapChain.length > 0) {
  9213. const sourcemap = filteredSourcemapChain.pop();
  9214. const line = sourcemap.mappings[location.line - 1];
  9215. let locationFound = false;
  9216. if (line !== undefined) {
  9217. for (const segment of line) {
  9218. if (segment[0] >= location.column) {
  9219. if (segment.length === 1)
  9220. break;
  9221. location = {
  9222. column: segment[3],
  9223. line: segment[2] + 1,
  9224. name: segment.length === 5 ? sourcemap.names[segment[4]] : undefined,
  9225. source: sourcemap.sources[segment[1]]
  9226. };
  9227. locationFound = true;
  9228. break;
  9229. }
  9230. }
  9231. }
  9232. if (!locationFound) {
  9233. throw new Error("Can't resolve original location of error.");
  9234. }
  9235. }
  9236. return location;
  9237. }
  9238. const NOOP = () => { };
  9239. let getStartTime = () => [0, 0];
  9240. let getElapsedTime = () => 0;
  9241. let getMemory = () => 0;
  9242. let timers = {};
  9243. const normalizeHrTime = (time) => time[0] * 1e3 + time[1] / 1e6;
  9244. function setTimeHelpers() {
  9245. if (typeof process !== 'undefined' && typeof process.hrtime === 'function') {
  9246. getStartTime = process.hrtime.bind(process);
  9247. getElapsedTime = previous => normalizeHrTime(process.hrtime(previous));
  9248. }
  9249. else if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
  9250. getStartTime = () => [performance.now(), 0];
  9251. getElapsedTime = previous => performance.now() - previous[0];
  9252. }
  9253. if (typeof process !== 'undefined' && typeof process.memoryUsage === 'function') {
  9254. getMemory = () => process.memoryUsage().heapUsed;
  9255. }
  9256. }
  9257. function getPersistedLabel(label, level) {
  9258. switch (level) {
  9259. case 1:
  9260. return `# ${label}`;
  9261. case 2:
  9262. return `## ${label}`;
  9263. case 3:
  9264. return label;
  9265. default:
  9266. return `${' '.repeat(level - 4)}- ${label}`;
  9267. }
  9268. }
  9269. function timeStartImpl(label, level = 3) {
  9270. label = getPersistedLabel(label, level);
  9271. if (!timers.hasOwnProperty(label)) {
  9272. timers[label] = {
  9273. memory: 0,
  9274. startMemory: undefined,
  9275. startTime: undefined,
  9276. time: 0,
  9277. totalMemory: 0
  9278. };
  9279. }
  9280. const currentMemory = getMemory();
  9281. timers[label].startTime = getStartTime();
  9282. timers[label].startMemory = currentMemory;
  9283. }
  9284. function timeEndImpl(label, level = 3) {
  9285. label = getPersistedLabel(label, level);
  9286. if (timers.hasOwnProperty(label)) {
  9287. const currentMemory = getMemory();
  9288. timers[label].time += getElapsedTime(timers[label].startTime);
  9289. timers[label].totalMemory = Math.max(timers[label].totalMemory, currentMemory);
  9290. timers[label].memory += currentMemory - timers[label].startMemory;
  9291. }
  9292. }
  9293. function getTimings() {
  9294. const newTimings = {};
  9295. for (const [label, { time, memory, totalMemory }] of Object.entries(timers)) {
  9296. newTimings[label] = [time, memory, totalMemory];
  9297. }
  9298. return newTimings;
  9299. }
  9300. let timeStart = NOOP, timeEnd = NOOP;
  9301. const TIMED_PLUGIN_HOOKS = {
  9302. load: true,
  9303. resolveDynamicImport: true,
  9304. resolveId: true,
  9305. transform: true
  9306. };
  9307. function getPluginWithTimers(plugin, index) {
  9308. const timedPlugin = {};
  9309. for (const hook of Object.keys(plugin)) {
  9310. if (TIMED_PLUGIN_HOOKS[hook] === true) {
  9311. let timerLabel = `plugin ${index}`;
  9312. if (plugin.name) {
  9313. timerLabel += ` (${plugin.name})`;
  9314. }
  9315. timerLabel += ` - ${hook}`;
  9316. timedPlugin[hook] = function (...args) {
  9317. timeStart(timerLabel, 4);
  9318. let result = plugin[hook].apply(this === timedPlugin ? plugin : this, args);
  9319. timeEnd(timerLabel, 4);
  9320. if (result && typeof result.then === 'function') {
  9321. timeStart(`${timerLabel} (async)`, 4);
  9322. result = result.then((hookResult) => {
  9323. timeEnd(`${timerLabel} (async)`, 4);
  9324. return hookResult;
  9325. });
  9326. }
  9327. return result;
  9328. };
  9329. }
  9330. else {
  9331. timedPlugin[hook] = plugin[hook];
  9332. }
  9333. }
  9334. return timedPlugin;
  9335. }
  9336. function initialiseTimers(inputOptions) {
  9337. if (inputOptions.perf) {
  9338. timers = {};
  9339. setTimeHelpers();
  9340. timeStart = timeStartImpl;
  9341. timeEnd = timeEndImpl;
  9342. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  9343. }
  9344. else {
  9345. timeStart = NOOP;
  9346. timeEnd = NOOP;
  9347. }
  9348. }
  9349. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  9350. baseModule.isExecuted = true;
  9351. const modules = [baseModule];
  9352. const visitedModules = new Set();
  9353. for (const module of modules) {
  9354. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  9355. if (!(dependency instanceof ExternalModule) &&
  9356. !dependency.isExecuted &&
  9357. (dependency.info.hasModuleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  9358. !visitedModules.has(dependency.id)) {
  9359. dependency.isExecuted = true;
  9360. visitedModules.add(dependency.id);
  9361. modules.push(dependency);
  9362. }
  9363. }
  9364. }
  9365. }
  9366. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  9367. identifier: null,
  9368. localName: MISSING_EXPORT_SHIM_VARIABLE
  9369. };
  9370. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map(), skipExternalNamespaceReexports) {
  9371. const searchedModules = searchedNamesAndModules.get(name);
  9372. if (searchedModules) {
  9373. if (searchedModules.has(target)) {
  9374. return isExportAllSearch ? null : error(errCircularReexport(name, target.id));
  9375. }
  9376. searchedModules.add(target);
  9377. }
  9378. else {
  9379. searchedNamesAndModules.set(name, new Set([target]));
  9380. }
  9381. return target.getVariableForExportName(name, {
  9382. importerForSideEffects,
  9383. isExportAllSearch,
  9384. searchedNamesAndModules,
  9385. skipExternalNamespaceReexports
  9386. });
  9387. }
  9388. function getAndExtendSideEffectModules(variable, module) {
  9389. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, () => new Set());
  9390. let currentVariable = variable;
  9391. const referencedVariables = new Set([currentVariable]);
  9392. while (true) {
  9393. const importingModule = currentVariable.module;
  9394. currentVariable =
  9395. currentVariable instanceof ExportDefaultVariable
  9396. ? currentVariable.getDirectOriginalVariable()
  9397. : currentVariable instanceof SyntheticNamedExportVariable
  9398. ? currentVariable.syntheticNamespace
  9399. : null;
  9400. if (!currentVariable || referencedVariables.has(currentVariable)) {
  9401. break;
  9402. }
  9403. referencedVariables.add(currentVariable);
  9404. sideEffectModules.add(importingModule);
  9405. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  9406. if (originalSideEffects) {
  9407. for (const module of originalSideEffects) {
  9408. sideEffectModules.add(module);
  9409. }
  9410. }
  9411. }
  9412. return sideEffectModules;
  9413. }
  9414. class Module {
  9415. constructor(graph, id, options, isEntry, hasModuleSideEffects, syntheticNamedExports, meta) {
  9416. this.graph = graph;
  9417. this.id = id;
  9418. this.options = options;
  9419. this.alternativeReexportModules = new Map();
  9420. this.ast = null;
  9421. this.chunkFileNames = new Set();
  9422. this.chunkName = null;
  9423. this.cycles = new Set();
  9424. this.dependencies = new Set();
  9425. this.dynamicDependencies = new Set();
  9426. this.dynamicImporters = [];
  9427. this.dynamicImports = [];
  9428. this.execIndex = Infinity;
  9429. this.exportAllSources = new Set();
  9430. this.exports = Object.create(null);
  9431. this.exportsAll = Object.create(null);
  9432. this.implicitlyLoadedAfter = new Set();
  9433. this.implicitlyLoadedBefore = new Set();
  9434. this.importDescriptions = Object.create(null);
  9435. this.importMetas = [];
  9436. this.importedFromNotTreeshaken = false;
  9437. this.importers = [];
  9438. this.imports = new Set();
  9439. this.includedDynamicImporters = [];
  9440. this.isExecuted = false;
  9441. this.isUserDefinedEntryPoint = false;
  9442. this.preserveSignature = this.options.preserveEntrySignatures;
  9443. this.reexportDescriptions = Object.create(null);
  9444. this.sideEffectDependenciesByVariable = new Map();
  9445. this.sources = new Set();
  9446. this.userChunkNames = new Set();
  9447. this.usesTopLevelAwait = false;
  9448. this.allExportNames = null;
  9449. this.exportAllModules = [];
  9450. this.exportNamesByVariable = null;
  9451. this.exportShimVariable = new ExportShimVariable(this);
  9452. this.namespaceReexportsByName = Object.create(null);
  9453. this.relevantDependencies = null;
  9454. this.syntheticExports = new Map();
  9455. this.syntheticNamespace = null;
  9456. this.transformDependencies = [];
  9457. this.transitiveReexports = null;
  9458. this.excludeFromSourcemap = /\0/.test(id);
  9459. this.context = options.moduleContext(id);
  9460. // eslint-disable-next-line @typescript-eslint/no-this-alias
  9461. const module = this;
  9462. this.info = {
  9463. ast: null,
  9464. code: null,
  9465. get dynamicallyImportedIds() {
  9466. const dynamicallyImportedIds = [];
  9467. for (const { id } of module.dynamicImports) {
  9468. if (id) {
  9469. dynamicallyImportedIds.push(id);
  9470. }
  9471. }
  9472. return dynamicallyImportedIds;
  9473. },
  9474. get dynamicImporters() {
  9475. return module.dynamicImporters.sort();
  9476. },
  9477. hasModuleSideEffects,
  9478. id,
  9479. get implicitlyLoadedAfterOneOf() {
  9480. return Array.from(module.implicitlyLoadedAfter, getId);
  9481. },
  9482. get implicitlyLoadedBefore() {
  9483. return Array.from(module.implicitlyLoadedBefore, getId);
  9484. },
  9485. get importedIds() {
  9486. return Array.from(module.sources, source => module.resolvedIds[source].id);
  9487. },
  9488. get importers() {
  9489. return module.importers.sort();
  9490. },
  9491. isEntry,
  9492. isExternal: false,
  9493. meta,
  9494. syntheticNamedExports
  9495. };
  9496. }
  9497. basename() {
  9498. const base = basename(this.id);
  9499. const ext = extname(this.id);
  9500. return makeLegal(ext ? base.slice(0, -ext.length) : base);
  9501. }
  9502. bindReferences() {
  9503. this.ast.bind();
  9504. }
  9505. error(props, pos) {
  9506. this.addLocationToLogProps(props, pos);
  9507. return error(props);
  9508. }
  9509. getAllExportNames() {
  9510. if (this.allExportNames) {
  9511. return this.allExportNames;
  9512. }
  9513. const allExportNames = (this.allExportNames = new Set());
  9514. for (const name of Object.keys(this.exports)) {
  9515. allExportNames.add(name);
  9516. }
  9517. for (const name of Object.keys(this.reexportDescriptions)) {
  9518. allExportNames.add(name);
  9519. }
  9520. for (const module of this.exportAllModules) {
  9521. if (module instanceof ExternalModule) {
  9522. allExportNames.add(`*${module.id}`);
  9523. continue;
  9524. }
  9525. for (const name of module.getAllExportNames()) {
  9526. if (name !== 'default')
  9527. allExportNames.add(name);
  9528. }
  9529. }
  9530. return allExportNames;
  9531. }
  9532. getDependenciesToBeIncluded() {
  9533. if (this.relevantDependencies)
  9534. return this.relevantDependencies;
  9535. const relevantDependencies = new Set();
  9536. const necessaryDependencies = new Set();
  9537. const alwaysCheckedDependencies = new Set();
  9538. let dependencyVariables = this.imports.keys();
  9539. if (this.info.isEntry ||
  9540. this.includedDynamicImporters.length > 0 ||
  9541. this.namespace.included ||
  9542. this.implicitlyLoadedAfter.size > 0) {
  9543. dependencyVariables = new Set(dependencyVariables);
  9544. for (const exportName of [...this.getReexports(), ...this.getExports()]) {
  9545. const exportedVariable = this.getVariableForExportName(exportName);
  9546. if (exportedVariable) {
  9547. dependencyVariables.add(exportedVariable);
  9548. }
  9549. }
  9550. }
  9551. for (let variable of dependencyVariables) {
  9552. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  9553. if (sideEffectDependencies) {
  9554. for (const module of sideEffectDependencies) {
  9555. alwaysCheckedDependencies.add(module);
  9556. }
  9557. }
  9558. if (variable instanceof SyntheticNamedExportVariable) {
  9559. variable = variable.getBaseVariable();
  9560. }
  9561. else if (variable instanceof ExportDefaultVariable) {
  9562. variable = variable.getOriginalVariable();
  9563. }
  9564. necessaryDependencies.add(variable.module);
  9565. }
  9566. if (!this.options.treeshake || this.info.hasModuleSideEffects === 'no-treeshake') {
  9567. for (const dependency of this.dependencies) {
  9568. relevantDependencies.add(dependency);
  9569. }
  9570. }
  9571. else {
  9572. this.addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  9573. }
  9574. for (const dependency of necessaryDependencies) {
  9575. relevantDependencies.add(dependency);
  9576. }
  9577. return (this.relevantDependencies = relevantDependencies);
  9578. }
  9579. getExportNamesByVariable() {
  9580. if (this.exportNamesByVariable) {
  9581. return this.exportNamesByVariable;
  9582. }
  9583. const exportNamesByVariable = new Map();
  9584. for (const exportName of this.getAllExportNames()) {
  9585. if (exportName === this.info.syntheticNamedExports)
  9586. continue;
  9587. let tracedVariable = this.getVariableForExportName(exportName);
  9588. if (tracedVariable instanceof ExportDefaultVariable) {
  9589. tracedVariable = tracedVariable.getOriginalVariable();
  9590. }
  9591. if (!tracedVariable ||
  9592. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  9593. continue;
  9594. }
  9595. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  9596. if (existingExportNames) {
  9597. existingExportNames.push(exportName);
  9598. }
  9599. else {
  9600. exportNamesByVariable.set(tracedVariable, [exportName]);
  9601. }
  9602. }
  9603. return (this.exportNamesByVariable = exportNamesByVariable);
  9604. }
  9605. getExports() {
  9606. return Object.keys(this.exports);
  9607. }
  9608. getReexports() {
  9609. if (this.transitiveReexports) {
  9610. return this.transitiveReexports;
  9611. }
  9612. // to avoid infinite recursion when using circular `export * from X`
  9613. this.transitiveReexports = [];
  9614. const reexports = new Set();
  9615. for (const name in this.reexportDescriptions) {
  9616. reexports.add(name);
  9617. }
  9618. for (const module of this.exportAllModules) {
  9619. if (module instanceof ExternalModule) {
  9620. reexports.add(`*${module.id}`);
  9621. }
  9622. else {
  9623. for (const name of [...module.getReexports(), ...module.getExports()]) {
  9624. if (name !== 'default')
  9625. reexports.add(name);
  9626. }
  9627. }
  9628. }
  9629. return (this.transitiveReexports = [...reexports]);
  9630. }
  9631. getRenderedExports() {
  9632. // only direct exports are counted here, not reexports at all
  9633. const renderedExports = [];
  9634. const removedExports = [];
  9635. for (const exportName in this.exports) {
  9636. const variable = this.getVariableForExportName(exportName);
  9637. (variable && variable.included ? renderedExports : removedExports).push(exportName);
  9638. }
  9639. return { removedExports, renderedExports };
  9640. }
  9641. getSyntheticNamespace() {
  9642. if (this.syntheticNamespace === null) {
  9643. this.syntheticNamespace = undefined;
  9644. this.syntheticNamespace = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  9645. ? this.info.syntheticNamedExports
  9646. : 'default');
  9647. }
  9648. if (!this.syntheticNamespace) {
  9649. return error(errSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  9650. }
  9651. return this.syntheticNamespace;
  9652. }
  9653. getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules, skipExternalNamespaceReexports } = EMPTY_OBJECT) {
  9654. if (name[0] === '*') {
  9655. if (name.length === 1) {
  9656. // export * from './other'
  9657. return this.namespace;
  9658. }
  9659. else {
  9660. // export * from 'external'
  9661. const module = this.graph.modulesById.get(name.slice(1));
  9662. return module.getVariableForExportName('*');
  9663. }
  9664. }
  9665. // export { foo } from './other'
  9666. const reexportDeclaration = this.reexportDescriptions[name];
  9667. if (reexportDeclaration) {
  9668. const variable = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules, false);
  9669. if (!variable) {
  9670. return this.error(errMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
  9671. }
  9672. if (importerForSideEffects) {
  9673. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  9674. }
  9675. return variable;
  9676. }
  9677. const exportDeclaration = this.exports[name];
  9678. if (exportDeclaration) {
  9679. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  9680. return this.exportShimVariable;
  9681. }
  9682. const name = exportDeclaration.localName;
  9683. const variable = this.traceVariable(name, importerForSideEffects);
  9684. if (importerForSideEffects) {
  9685. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, () => new Set()).add(this);
  9686. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  9687. }
  9688. return variable;
  9689. }
  9690. if (name !== 'default') {
  9691. const foundNamespaceReexport = name in this.namespaceReexportsByName
  9692. ? this.namespaceReexportsByName[name]
  9693. : this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules, skipExternalNamespaceReexports);
  9694. if (!skipExternalNamespaceReexports) {
  9695. this.namespaceReexportsByName[name] = foundNamespaceReexport;
  9696. }
  9697. if (foundNamespaceReexport) {
  9698. return foundNamespaceReexport;
  9699. }
  9700. }
  9701. if (this.info.syntheticNamedExports) {
  9702. let syntheticExport = this.syntheticExports.get(name);
  9703. if (!syntheticExport) {
  9704. const syntheticNamespace = this.getSyntheticNamespace();
  9705. syntheticExport = new SyntheticNamedExportVariable(this.astContext, name, syntheticNamespace);
  9706. this.syntheticExports.set(name, syntheticExport);
  9707. return syntheticExport;
  9708. }
  9709. return syntheticExport;
  9710. }
  9711. // we don't want to create shims when we are just
  9712. // probing export * modules for exports
  9713. if (!isExportAllSearch) {
  9714. if (this.options.shimMissingExports) {
  9715. this.shimMissingExport(name);
  9716. return this.exportShimVariable;
  9717. }
  9718. }
  9719. return null;
  9720. }
  9721. hasEffects() {
  9722. return (this.info.hasModuleSideEffects === 'no-treeshake' ||
  9723. (this.ast.included && this.ast.hasEffects(createHasEffectsContext())));
  9724. }
  9725. include() {
  9726. const context = createInclusionContext();
  9727. if (this.ast.shouldBeIncluded(context))
  9728. this.ast.include(context, false);
  9729. }
  9730. includeAllExports(includeNamespaceMembers) {
  9731. if (!this.isExecuted) {
  9732. markModuleAndImpureDependenciesAsExecuted(this);
  9733. this.graph.needsTreeshakingPass = true;
  9734. }
  9735. for (const exportName of this.getExports()) {
  9736. if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
  9737. const variable = this.getVariableForExportName(exportName);
  9738. variable.deoptimizePath(UNKNOWN_PATH);
  9739. if (!variable.included) {
  9740. this.includeVariable(variable);
  9741. }
  9742. }
  9743. }
  9744. for (const name of this.getReexports()) {
  9745. const variable = this.getVariableForExportName(name);
  9746. if (variable) {
  9747. variable.deoptimizePath(UNKNOWN_PATH);
  9748. if (!variable.included) {
  9749. this.includeVariable(variable);
  9750. }
  9751. if (variable instanceof ExternalVariable) {
  9752. variable.module.reexported = true;
  9753. }
  9754. }
  9755. }
  9756. if (includeNamespaceMembers) {
  9757. this.namespace.prepareNamespace(this.includeAndGetAdditionalMergedNamespaces());
  9758. }
  9759. }
  9760. includeAllInBundle() {
  9761. this.ast.include(createInclusionContext(), true);
  9762. this.includeAllExports(false);
  9763. }
  9764. isIncluded() {
  9765. return this.ast.included || this.namespace.included || this.importedFromNotTreeshaken;
  9766. }
  9767. linkImports() {
  9768. this.addModulesToImportDescriptions(this.importDescriptions);
  9769. this.addModulesToImportDescriptions(this.reexportDescriptions);
  9770. for (const name in this.exports) {
  9771. if (name !== 'default' && name !== this.info.syntheticNamedExports) {
  9772. this.exportsAll[name] = this.id;
  9773. }
  9774. }
  9775. const externalExportAllModules = [];
  9776. for (const source of this.exportAllSources) {
  9777. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  9778. if (module instanceof ExternalModule) {
  9779. externalExportAllModules.push(module);
  9780. continue;
  9781. }
  9782. this.exportAllModules.push(module);
  9783. for (const name in module.exportsAll) {
  9784. if (name in this.exportsAll) {
  9785. this.options.onwarn(errNamespaceConflict(name, this, module));
  9786. }
  9787. else {
  9788. this.exportsAll[name] = module.exportsAll[name];
  9789. }
  9790. }
  9791. }
  9792. this.exportAllModules.push(...externalExportAllModules);
  9793. }
  9794. render(options) {
  9795. const magicString = this.magicString.clone();
  9796. this.ast.render(magicString, options);
  9797. this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
  9798. return magicString;
  9799. }
  9800. setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
  9801. this.info.code = code;
  9802. this.originalCode = originalCode;
  9803. this.originalSourcemap = originalSourcemap;
  9804. this.sourcemapChain = sourcemapChain;
  9805. if (transformFiles) {
  9806. this.transformFiles = transformFiles;
  9807. }
  9808. this.transformDependencies = transformDependencies;
  9809. this.customTransformCache = customTransformCache;
  9810. this.updateOptions(moduleOptions);
  9811. timeStart('generate ast', 3);
  9812. if (!ast) {
  9813. ast = this.tryParse();
  9814. }
  9815. timeEnd('generate ast', 3);
  9816. this.resolvedIds = resolvedIds || Object.create(null);
  9817. // By default, `id` is the file name. Custom resolvers and loaders
  9818. // can change that, but it makes sense to use it for the source file name
  9819. const fileName = this.id;
  9820. this.magicString = new MagicString$1(code, {
  9821. filename: (this.excludeFromSourcemap ? null : fileName),
  9822. indentExclusionRanges: []
  9823. });
  9824. timeStart('analyse ast', 3);
  9825. this.astContext = {
  9826. addDynamicImport: this.addDynamicImport.bind(this),
  9827. addExport: this.addExport.bind(this),
  9828. addImport: this.addImport.bind(this),
  9829. addImportMeta: this.addImportMeta.bind(this),
  9830. code,
  9831. deoptimizationTracker: this.graph.deoptimizationTracker,
  9832. error: this.error.bind(this),
  9833. fileName,
  9834. getExports: this.getExports.bind(this),
  9835. getModuleExecIndex: () => this.execIndex,
  9836. getModuleName: this.basename.bind(this),
  9837. getReexports: this.getReexports.bind(this),
  9838. importDescriptions: this.importDescriptions,
  9839. includeAllExports: () => this.includeAllExports(true),
  9840. includeDynamicImport: this.includeDynamicImport.bind(this),
  9841. includeVariableInModule: this.includeVariableInModule.bind(this),
  9842. magicString: this.magicString,
  9843. module: this,
  9844. moduleContext: this.context,
  9845. nodeConstructors,
  9846. options: this.options,
  9847. requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
  9848. traceExport: this.getVariableForExportName.bind(this),
  9849. traceVariable: this.traceVariable.bind(this),
  9850. usesTopLevelAwait: false,
  9851. warn: this.warn.bind(this)
  9852. };
  9853. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  9854. this.namespace = new NamespaceVariable(this.astContext, this.info.syntheticNamedExports);
  9855. this.ast = new Program(ast, { context: this.astContext, type: 'Module' }, this.scope);
  9856. this.info.ast = ast;
  9857. timeEnd('analyse ast', 3);
  9858. }
  9859. toJSON() {
  9860. return {
  9861. ast: this.ast.esTreeNode,
  9862. code: this.info.code,
  9863. customTransformCache: this.customTransformCache,
  9864. dependencies: Array.from(this.dependencies, getId),
  9865. id: this.id,
  9866. meta: this.info.meta,
  9867. moduleSideEffects: this.info.hasModuleSideEffects,
  9868. originalCode: this.originalCode,
  9869. originalSourcemap: this.originalSourcemap,
  9870. resolvedIds: this.resolvedIds,
  9871. sourcemapChain: this.sourcemapChain,
  9872. syntheticNamedExports: this.info.syntheticNamedExports,
  9873. transformDependencies: this.transformDependencies,
  9874. transformFiles: this.transformFiles
  9875. };
  9876. }
  9877. traceVariable(name, importerForSideEffects) {
  9878. const localVariable = this.scope.variables.get(name);
  9879. if (localVariable) {
  9880. return localVariable;
  9881. }
  9882. if (name in this.importDescriptions) {
  9883. const importDeclaration = this.importDescriptions[name];
  9884. const otherModule = importDeclaration.module;
  9885. if (otherModule instanceof Module && importDeclaration.name === '*') {
  9886. return otherModule.namespace;
  9887. }
  9888. const declaration = otherModule.getVariableForExportName(importDeclaration.name, {
  9889. importerForSideEffects: importerForSideEffects || this
  9890. });
  9891. if (!declaration) {
  9892. return this.error(errMissingExport(importDeclaration.name, this.id, otherModule.id), importDeclaration.start);
  9893. }
  9894. return declaration;
  9895. }
  9896. return null;
  9897. }
  9898. tryParse() {
  9899. try {
  9900. return this.graph.contextParse(this.info.code);
  9901. }
  9902. catch (err) {
  9903. let message = err.message.replace(/ \(\d+:\d+\)$/, '');
  9904. if (this.id.endsWith('.json')) {
  9905. message += ' (Note that you need @rollup/plugin-json to import JSON files)';
  9906. }
  9907. else if (!this.id.endsWith('.js')) {
  9908. message += ' (Note that you need plugins to import files that are not JavaScript)';
  9909. }
  9910. return this.error({
  9911. code: 'PARSE_ERROR',
  9912. message,
  9913. parserError: err
  9914. }, err.pos);
  9915. }
  9916. }
  9917. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  9918. if (moduleSideEffects != null) {
  9919. this.info.hasModuleSideEffects = moduleSideEffects;
  9920. }
  9921. if (syntheticNamedExports != null) {
  9922. this.info.syntheticNamedExports = syntheticNamedExports;
  9923. }
  9924. if (meta != null) {
  9925. this.info.meta = { ...this.info.meta, ...meta };
  9926. }
  9927. }
  9928. warn(props, pos) {
  9929. this.addLocationToLogProps(props, pos);
  9930. this.options.onwarn(props);
  9931. }
  9932. addDynamicImport(node) {
  9933. let argument = node.source;
  9934. if (argument instanceof TemplateLiteral) {
  9935. if (argument.quasis.length === 1 && argument.quasis[0].value.cooked) {
  9936. argument = argument.quasis[0].value.cooked;
  9937. }
  9938. }
  9939. else if (argument instanceof Literal && typeof argument.value === 'string') {
  9940. argument = argument.value;
  9941. }
  9942. this.dynamicImports.push({ argument, id: null, node, resolution: null });
  9943. }
  9944. addExport(node) {
  9945. if (node instanceof ExportDefaultDeclaration) {
  9946. // export default foo;
  9947. this.exports.default = {
  9948. identifier: node.variable.getAssignedVariableName(),
  9949. localName: 'default'
  9950. };
  9951. }
  9952. else if (node instanceof ExportAllDeclaration) {
  9953. const source = node.source.value;
  9954. this.sources.add(source);
  9955. if (node.exported) {
  9956. // export * as name from './other'
  9957. const name = node.exported.name;
  9958. this.reexportDescriptions[name] = {
  9959. localName: '*',
  9960. module: null,
  9961. source,
  9962. start: node.start
  9963. };
  9964. }
  9965. else {
  9966. // export * from './other'
  9967. this.exportAllSources.add(source);
  9968. }
  9969. }
  9970. else if (node.source instanceof Literal) {
  9971. // export { name } from './other'
  9972. const source = node.source.value;
  9973. this.sources.add(source);
  9974. for (const specifier of node.specifiers) {
  9975. const name = specifier.exported.name;
  9976. this.reexportDescriptions[name] = {
  9977. localName: specifier.local.name,
  9978. module: null,
  9979. source,
  9980. start: specifier.start
  9981. };
  9982. }
  9983. }
  9984. else if (node.declaration) {
  9985. const declaration = node.declaration;
  9986. if (declaration instanceof VariableDeclaration) {
  9987. // export var { foo, bar } = ...
  9988. // export var foo = 1, bar = 2;
  9989. for (const declarator of declaration.declarations) {
  9990. for (const localName of extractAssignedNames(declarator.id)) {
  9991. this.exports[localName] = { identifier: null, localName };
  9992. }
  9993. }
  9994. }
  9995. else {
  9996. // export function foo () {}
  9997. const localName = declaration.id.name;
  9998. this.exports[localName] = { identifier: null, localName };
  9999. }
  10000. }
  10001. else {
  10002. // export { foo, bar, baz }
  10003. for (const specifier of node.specifiers) {
  10004. const localName = specifier.local.name;
  10005. const exportedName = specifier.exported.name;
  10006. this.exports[exportedName] = { identifier: null, localName };
  10007. }
  10008. }
  10009. }
  10010. addImport(node) {
  10011. const source = node.source.value;
  10012. this.sources.add(source);
  10013. for (const specifier of node.specifiers) {
  10014. const isDefault = specifier.type === ImportDefaultSpecifier$1;
  10015. const isNamespace = specifier.type === ImportNamespaceSpecifier$1;
  10016. const name = isDefault
  10017. ? 'default'
  10018. : isNamespace
  10019. ? '*'
  10020. : specifier.imported.name;
  10021. this.importDescriptions[specifier.local.name] = {
  10022. module: null,
  10023. name,
  10024. source,
  10025. start: specifier.start
  10026. };
  10027. }
  10028. }
  10029. addImportMeta(node) {
  10030. this.importMetas.push(node);
  10031. }
  10032. addLocationToLogProps(props, pos) {
  10033. props.id = this.id;
  10034. props.pos = pos;
  10035. let code = this.info.code;
  10036. const location = locate(code, pos, { offsetLine: 1 });
  10037. if (location) {
  10038. let { column, line } = location;
  10039. try {
  10040. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  10041. code = this.originalCode;
  10042. }
  10043. catch (e) {
  10044. this.options.onwarn({
  10045. code: 'SOURCEMAP_ERROR',
  10046. id: this.id,
  10047. loc: {
  10048. column,
  10049. file: this.id,
  10050. line
  10051. },
  10052. message: `Error when using sourcemap for reporting an error: ${e.message}`,
  10053. pos
  10054. });
  10055. }
  10056. augmentCodeLocation(props, { column, line }, code, this.id);
  10057. }
  10058. }
  10059. addModulesToImportDescriptions(importDescription) {
  10060. for (const specifier of Object.values(importDescription)) {
  10061. const id = this.resolvedIds[specifier.source].id;
  10062. specifier.module = this.graph.modulesById.get(id);
  10063. }
  10064. }
  10065. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  10066. const handledDependencies = new Set();
  10067. const addSideEffectDependencies = (possibleDependencies) => {
  10068. for (const dependency of possibleDependencies) {
  10069. if (handledDependencies.has(dependency)) {
  10070. continue;
  10071. }
  10072. handledDependencies.add(dependency);
  10073. if (necessaryDependencies.has(dependency)) {
  10074. relevantDependencies.add(dependency);
  10075. continue;
  10076. }
  10077. if (!(dependency.info.hasModuleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  10078. continue;
  10079. }
  10080. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  10081. relevantDependencies.add(dependency);
  10082. continue;
  10083. }
  10084. addSideEffectDependencies(dependency.dependencies);
  10085. }
  10086. };
  10087. addSideEffectDependencies(this.dependencies);
  10088. addSideEffectDependencies(alwaysCheckedDependencies);
  10089. }
  10090. getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules, skipExternalNamespaceReexports = false) {
  10091. let foundSyntheticDeclaration = null;
  10092. const skipExternalNamespaceValues = [{ searchedNamesAndModules, skipExternalNamespaces: true }];
  10093. if (!skipExternalNamespaceReexports) {
  10094. const clonedSearchedNamesAndModules = new Map();
  10095. for (const [name, modules] of searchedNamesAndModules || []) {
  10096. clonedSearchedNamesAndModules.set(name, new Set(modules));
  10097. }
  10098. skipExternalNamespaceValues.push({
  10099. searchedNamesAndModules: clonedSearchedNamesAndModules,
  10100. skipExternalNamespaces: false
  10101. });
  10102. }
  10103. for (const { skipExternalNamespaces, searchedNamesAndModules } of skipExternalNamespaceValues) {
  10104. const foundDeclarations = new Set();
  10105. for (const module of this.exportAllModules) {
  10106. if (module instanceof Module || !skipExternalNamespaces) {
  10107. const declaration = getVariableForExportNameRecursive(module, name, importerForSideEffects, true, searchedNamesAndModules, skipExternalNamespaces);
  10108. if (declaration) {
  10109. if (!(declaration instanceof SyntheticNamedExportVariable)) {
  10110. foundDeclarations.add(declaration);
  10111. }
  10112. else if (!foundSyntheticDeclaration) {
  10113. foundSyntheticDeclaration = declaration;
  10114. }
  10115. }
  10116. }
  10117. }
  10118. if (foundDeclarations.size === 1) {
  10119. return [...foundDeclarations][0];
  10120. }
  10121. if (foundDeclarations.size > 1) {
  10122. if (skipExternalNamespaces) {
  10123. return null;
  10124. }
  10125. const foundDeclarationList = [...foundDeclarations];
  10126. const usedDeclaration = foundDeclarationList[0];
  10127. this.options.onwarn(errAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
  10128. return usedDeclaration;
  10129. }
  10130. }
  10131. if (foundSyntheticDeclaration) {
  10132. return foundSyntheticDeclaration;
  10133. }
  10134. return null;
  10135. }
  10136. includeAndGetAdditionalMergedNamespaces() {
  10137. const mergedNamespaces = [];
  10138. for (const module of this.exportAllModules) {
  10139. if (module instanceof ExternalModule) {
  10140. const externalVariable = module.getVariableForExportName('*');
  10141. externalVariable.include();
  10142. this.imports.add(externalVariable);
  10143. mergedNamespaces.push(externalVariable);
  10144. }
  10145. else if (module.info.syntheticNamedExports) {
  10146. const syntheticNamespace = module.getSyntheticNamespace();
  10147. syntheticNamespace.include();
  10148. this.imports.add(syntheticNamespace);
  10149. mergedNamespaces.push(syntheticNamespace);
  10150. }
  10151. }
  10152. return mergedNamespaces;
  10153. }
  10154. includeDynamicImport(node) {
  10155. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  10156. if (resolution instanceof Module) {
  10157. resolution.includedDynamicImporters.push(this);
  10158. resolution.includeAllExports(true);
  10159. }
  10160. }
  10161. includeVariable(variable) {
  10162. if (!variable.included) {
  10163. variable.include();
  10164. this.graph.needsTreeshakingPass = true;
  10165. const variableModule = variable.module;
  10166. if (variableModule && variableModule instanceof Module) {
  10167. if (!variableModule.isExecuted) {
  10168. markModuleAndImpureDependenciesAsExecuted(variableModule);
  10169. }
  10170. if (variableModule !== this) {
  10171. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  10172. for (const module of sideEffectModules) {
  10173. if (!module.isExecuted) {
  10174. markModuleAndImpureDependenciesAsExecuted(module);
  10175. }
  10176. }
  10177. }
  10178. }
  10179. }
  10180. }
  10181. includeVariableInModule(variable) {
  10182. this.includeVariable(variable);
  10183. const variableModule = variable.module;
  10184. if (variableModule && variableModule !== this) {
  10185. this.imports.add(variable);
  10186. }
  10187. }
  10188. shimMissingExport(name) {
  10189. this.options.onwarn({
  10190. code: 'SHIMMED_EXPORT',
  10191. exporter: relativeId(this.id),
  10192. exportName: name,
  10193. message: `Missing export "${name}" has been shimmed in module ${relativeId(this.id)}.`
  10194. });
  10195. this.exports[name] = MISSING_EXPORT_SHIM_DESCRIPTION;
  10196. }
  10197. }
  10198. // if there is a cyclic import in the reexport chain, we should not
  10199. // import from the original module but from the cyclic module to not
  10200. // mess up execution order.
  10201. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  10202. if (variable.module instanceof Module && variable.module !== reexporter) {
  10203. const exporterCycles = variable.module.cycles;
  10204. if (exporterCycles.size > 0) {
  10205. const importerCycles = reexporter.cycles;
  10206. for (const cycleSymbol of importerCycles) {
  10207. if (exporterCycles.has(cycleSymbol)) {
  10208. importer.alternativeReexportModules.set(variable, reexporter);
  10209. break;
  10210. }
  10211. }
  10212. }
  10213. }
  10214. }
  10215. function removeJsExtension(name) {
  10216. return name.endsWith('.js') ? name.slice(0, -3) : name;
  10217. }
  10218. function getCompleteAmdId(options, chunkId) {
  10219. if (!options.autoId) {
  10220. return options.id || '';
  10221. }
  10222. else {
  10223. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  10224. }
  10225. }
  10226. function getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings, mechanism = 'return ') {
  10227. const _ = compact ? '' : ' ';
  10228. const n = compact ? '' : '\n';
  10229. if (!namedExportsMode) {
  10230. return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings)};`;
  10231. }
  10232. let exportBlock = '';
  10233. for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  10234. if (reexports && namedExportsMode) {
  10235. for (const specifier of reexports) {
  10236. if (specifier.reexported !== '*') {
  10237. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings);
  10238. if (exportBlock)
  10239. exportBlock += n;
  10240. exportBlock +=
  10241. specifier.imported !== '*' && specifier.needsLiveBinding
  10242. ? `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
  10243. `${t}enumerable:${_}true,${n}` +
  10244. `${t}get:${_}function${_}()${_}{${n}` +
  10245. `${t}${t}return ${importName};${n}${t}}${n}});`
  10246. : `exports.${specifier.reexported}${_}=${_}${importName};`;
  10247. }
  10248. }
  10249. }
  10250. }
  10251. for (const { exported, local } of exports) {
  10252. const lhs = `exports${RESERVED_NAMES[exported] ? `['${exported}']` : `.${exported}`}`;
  10253. const rhs = local;
  10254. if (lhs !== rhs) {
  10255. if (exportBlock)
  10256. exportBlock += n;
  10257. exportBlock += `${lhs}${_}=${_}${rhs};`;
  10258. }
  10259. }
  10260. for (const { name, reexports } of dependencies) {
  10261. if (reexports && namedExportsMode) {
  10262. for (const specifier of reexports) {
  10263. if (specifier.reexported === '*') {
  10264. if (exportBlock)
  10265. exportBlock += n;
  10266. if (specifier.needsLiveBinding) {
  10267. exportBlock +=
  10268. `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
  10269. `${t}if${_}(k${_}!==${_}'default'${_}&&${_}!exports.hasOwnProperty(k))${_}Object.defineProperty(exports,${_}k,${_}{${n}` +
  10270. `${t}${t}enumerable:${_}true,${n}` +
  10271. `${t}${t}get:${_}function${_}()${_}{${n}` +
  10272. `${t}${t}${t}return ${name}[k];${n}` +
  10273. `${t}${t}}${n}${t}});${n}});`;
  10274. }
  10275. else {
  10276. exportBlock +=
  10277. `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
  10278. `${t}if${_}(k${_}!==${_}'default'${_}&&${_}!exports.hasOwnProperty(k))${_}exports[k]${_}=${_}${name}[k];${n}});`;
  10279. }
  10280. }
  10281. }
  10282. }
  10283. }
  10284. if (exportBlock) {
  10285. return `${n}${n}${exportBlock}`;
  10286. }
  10287. return '';
  10288. }
  10289. function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings) {
  10290. if (exports.length > 0) {
  10291. return exports[0].local;
  10292. }
  10293. else {
  10294. for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  10295. if (reexports) {
  10296. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings);
  10297. }
  10298. }
  10299. }
  10300. }
  10301. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings) {
  10302. if (imported === 'default') {
  10303. if (!isChunk) {
  10304. const moduleInterop = String(interop(moduleId));
  10305. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  10306. ? defaultVariableName
  10307. : moduleVariableName;
  10308. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  10309. ? `${variableName}['default']`
  10310. : variableName;
  10311. }
  10312. return depNamedExportsMode ? `${moduleVariableName}['default']` : moduleVariableName;
  10313. }
  10314. if (imported === '*') {
  10315. return (isChunk
  10316. ? !depNamedExportsMode
  10317. : namespaceInteropHelpersByInteropType[String(interop(moduleId))])
  10318. ? namespaceVariableName
  10319. : moduleVariableName;
  10320. }
  10321. return `${moduleVariableName}.${imported}`;
  10322. }
  10323. function getEsModuleExport(_) {
  10324. return `Object.defineProperty(exports,${_}'__esModule',${_}{${_}value:${_}true${_}});`;
  10325. }
  10326. function getNamespaceToStringExport(_) {
  10327. return `exports[Symbol.toStringTag]${_}=${_}'Module';`;
  10328. }
  10329. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, _, n) {
  10330. let namespaceMarkers = '';
  10331. if (hasNamedExports) {
  10332. if (addEsModule) {
  10333. namespaceMarkers += getEsModuleExport(_);
  10334. }
  10335. if (addNamespaceToStringTag) {
  10336. if (namespaceMarkers) {
  10337. namespaceMarkers += n;
  10338. }
  10339. namespaceMarkers += getNamespaceToStringExport(_);
  10340. }
  10341. }
  10342. return namespaceMarkers;
  10343. }
  10344. function getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t) {
  10345. const neededInteropHelpers = new Set();
  10346. const interopStatements = [];
  10347. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  10348. neededInteropHelpers.add(helper);
  10349. interopStatements.push(`${varOrConst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  10350. };
  10351. for (const { defaultVariableName, imports, id, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  10352. if (isChunk) {
  10353. for (const { imported, reexported } of [
  10354. ...(imports || []),
  10355. ...(reexports || [])
  10356. ]) {
  10357. if (imported === '*' && reexported !== '*') {
  10358. if (!namedExportsMode) {
  10359. addInteropStatement(namespaceVariableName, getDefaultOnlyHelper(), name);
  10360. }
  10361. break;
  10362. }
  10363. }
  10364. }
  10365. else {
  10366. const moduleInterop = String(interop(id));
  10367. let hasDefault = false;
  10368. let hasNamespace = false;
  10369. for (const { imported, reexported } of [
  10370. ...(imports || []),
  10371. ...(reexports || [])
  10372. ]) {
  10373. let helper;
  10374. let variableName;
  10375. if (imported === 'default') {
  10376. if (!hasDefault) {
  10377. hasDefault = true;
  10378. if (defaultVariableName !== namespaceVariableName) {
  10379. variableName = defaultVariableName;
  10380. helper = defaultInteropHelpersByInteropType[moduleInterop];
  10381. }
  10382. }
  10383. }
  10384. else if (imported === '*' && reexported !== '*') {
  10385. if (!hasNamespace) {
  10386. hasNamespace = true;
  10387. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  10388. variableName = namespaceVariableName;
  10389. }
  10390. }
  10391. if (helper) {
  10392. addInteropStatement(variableName, helper, name);
  10393. }
  10394. }
  10395. }
  10396. }
  10397. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, _, n, s, t, externalLiveBindings, freeze, namespaceToStringTag)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  10398. }
  10399. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  10400. // The assumption is that this makes sense for all relative ids:
  10401. // https://requirejs.org/docs/api.html#jsfiles
  10402. function removeExtensionFromRelativeAmdId(id) {
  10403. return id[0] === '.' ? removeJsExtension(id) : id;
  10404. }
  10405. const builtins = {
  10406. assert: true,
  10407. buffer: true,
  10408. console: true,
  10409. constants: true,
  10410. domain: true,
  10411. events: true,
  10412. http: true,
  10413. https: true,
  10414. os: true,
  10415. path: true,
  10416. process: true,
  10417. punycode: true,
  10418. querystring: true,
  10419. stream: true,
  10420. string_decoder: true,
  10421. timers: true,
  10422. tty: true,
  10423. url: true,
  10424. util: true,
  10425. vm: true,
  10426. zlib: true
  10427. };
  10428. function warnOnBuiltins(warn, dependencies) {
  10429. const externalBuiltins = dependencies.map(({ id }) => id).filter(id => id in builtins);
  10430. if (!externalBuiltins.length)
  10431. return;
  10432. warn({
  10433. code: 'MISSING_NODE_BUILTINS',
  10434. message: `Creating a browser bundle that depends on Node.js built-in modules (${printQuotedStringList(externalBuiltins)}). You might need to include https://github.com/snowpackjs/rollup-plugin-polyfill-node`,
  10435. modules: externalBuiltins
  10436. });
  10437. }
  10438. 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 }) {
  10439. warnOnBuiltins(warn, dependencies);
  10440. const deps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
  10441. const args = dependencies.map(m => m.name);
  10442. const n = compact ? '' : '\n';
  10443. const s = compact ? '' : ';';
  10444. const _ = compact ? '' : ' ';
  10445. if (namedExportsMode && hasExports) {
  10446. args.unshift(`exports`);
  10447. deps.unshift(`'exports'`);
  10448. }
  10449. if (accessedGlobals.has('require')) {
  10450. args.unshift('require');
  10451. deps.unshift(`'require'`);
  10452. }
  10453. if (accessedGlobals.has('module')) {
  10454. args.unshift('module');
  10455. deps.unshift(`'module'`);
  10456. }
  10457. const completeAmdId = getCompleteAmdId(amd, id);
  10458. const params = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  10459. (deps.length ? `[${deps.join(`,${_}`)}],${_}` : ``);
  10460. const useStrict = strict ? `${_}'use strict';` : '';
  10461. magicString.prepend(`${intro}${getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t)}`);
  10462. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
  10463. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, _, n);
  10464. if (namespaceMarkers) {
  10465. namespaceMarkers = n + n + namespaceMarkers;
  10466. }
  10467. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  10468. return magicString
  10469. .indent(t)
  10470. .prepend(`${amd.define}(${params}function${_}(${args.join(`,${_}`)})${_}{${useStrict}${n}${n}`)
  10471. .append(`${n}${n}});`);
  10472. }
  10473. function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, varOrConst }, { compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  10474. const n = compact ? '' : '\n';
  10475. const s = compact ? '' : ';';
  10476. const _ = compact ? '' : ' ';
  10477. const useStrict = strict ? `'use strict';${n}${n}` : '';
  10478. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, _, n);
  10479. if (namespaceMarkers) {
  10480. namespaceMarkers += n + n;
  10481. }
  10482. const importBlock = getImportBlock$1(dependencies, compact, varOrConst, n, _);
  10483. const interopBlock = getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t);
  10484. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  10485. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings, `module.exports${_}=${_}`);
  10486. return magicString.append(`${exportBlock}${outro}`);
  10487. }
  10488. function getImportBlock$1(dependencies, compact, varOrConst, n, _) {
  10489. let importBlock = '';
  10490. let definingVariable = false;
  10491. for (const { id, name, reexports, imports } of dependencies) {
  10492. if (!reexports && !imports) {
  10493. if (importBlock) {
  10494. importBlock += !compact || definingVariable ? `;${n}` : ',';
  10495. }
  10496. definingVariable = false;
  10497. importBlock += `require('${id}')`;
  10498. }
  10499. else {
  10500. importBlock +=
  10501. compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${varOrConst} `;
  10502. definingVariable = true;
  10503. importBlock += `${name}${_}=${_}require('${id}')`;
  10504. }
  10505. }
  10506. if (importBlock) {
  10507. return `${importBlock};${n}${n}`;
  10508. }
  10509. return '';
  10510. }
  10511. function es(magicString, { intro, outro, dependencies, exports, varOrConst }, { compact }) {
  10512. const _ = compact ? '' : ' ';
  10513. const n = compact ? '' : '\n';
  10514. const importBlock = getImportBlock(dependencies, _);
  10515. if (importBlock.length > 0)
  10516. intro += importBlock.join(n) + n + n;
  10517. if (intro)
  10518. magicString.prepend(intro);
  10519. const exportBlock = getExportBlock(exports, _, varOrConst);
  10520. if (exportBlock.length)
  10521. magicString.append(n + n + exportBlock.join(n).trim());
  10522. if (outro)
  10523. magicString.append(outro);
  10524. return magicString.trim();
  10525. }
  10526. function getImportBlock(dependencies, _) {
  10527. const importBlock = [];
  10528. for (const { id, reexports, imports, name } of dependencies) {
  10529. if (!reexports && !imports) {
  10530. importBlock.push(`import${_}'${id}';`);
  10531. continue;
  10532. }
  10533. if (imports) {
  10534. let defaultImport = null;
  10535. let starImport = null;
  10536. const importedNames = [];
  10537. for (const specifier of imports) {
  10538. if (specifier.imported === 'default') {
  10539. defaultImport = specifier;
  10540. }
  10541. else if (specifier.imported === '*') {
  10542. starImport = specifier;
  10543. }
  10544. else {
  10545. importedNames.push(specifier);
  10546. }
  10547. }
  10548. if (starImport) {
  10549. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}'${id}';`);
  10550. }
  10551. if (defaultImport && importedNames.length === 0) {
  10552. importBlock.push(`import ${defaultImport.local} from${_}'${id}';`);
  10553. }
  10554. else if (importedNames.length > 0) {
  10555. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  10556. .map(specifier => {
  10557. if (specifier.imported === specifier.local) {
  10558. return specifier.imported;
  10559. }
  10560. else {
  10561. return `${specifier.imported} as ${specifier.local}`;
  10562. }
  10563. })
  10564. .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
  10565. }
  10566. }
  10567. if (reexports) {
  10568. let starExport = null;
  10569. const namespaceReexports = [];
  10570. const namedReexports = [];
  10571. for (const specifier of reexports) {
  10572. if (specifier.reexported === '*') {
  10573. starExport = specifier;
  10574. }
  10575. else if (specifier.imported === '*') {
  10576. namespaceReexports.push(specifier);
  10577. }
  10578. else {
  10579. namedReexports.push(specifier);
  10580. }
  10581. }
  10582. if (starExport) {
  10583. importBlock.push(`export${_}*${_}from${_}'${id}';`);
  10584. }
  10585. if (namespaceReexports.length > 0) {
  10586. if (!imports ||
  10587. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  10588. importBlock.push(`import${_}*${_}as ${name} from${_}'${id}';`);
  10589. }
  10590. for (const specifier of namespaceReexports) {
  10591. importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
  10592. }
  10593. }
  10594. if (namedReexports.length > 0) {
  10595. importBlock.push(`export${_}{${_}${namedReexports
  10596. .map(specifier => {
  10597. if (specifier.imported === specifier.reexported) {
  10598. return specifier.imported;
  10599. }
  10600. else {
  10601. return `${specifier.imported} as ${specifier.reexported}`;
  10602. }
  10603. })
  10604. .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
  10605. }
  10606. }
  10607. }
  10608. return importBlock;
  10609. }
  10610. function getExportBlock(exports, _, varOrConst) {
  10611. const exportBlock = [];
  10612. const exportDeclaration = [];
  10613. for (const specifier of exports) {
  10614. if (specifier.expression) {
  10615. exportBlock.push(`${varOrConst} ${specifier.local}${_}=${_}${specifier.expression};`);
  10616. }
  10617. exportDeclaration.push(specifier.exported === specifier.local
  10618. ? specifier.local
  10619. : `${specifier.local} as ${specifier.exported}`);
  10620. }
  10621. if (exportDeclaration.length) {
  10622. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  10623. }
  10624. return exportBlock;
  10625. }
  10626. // Generate strings which dereference dotted properties, but use array notation `['prop-deref']`
  10627. // if the property name isn't trivial
  10628. const shouldUseDot = /^[a-zA-Z$_][a-zA-Z0-9$_]*$/;
  10629. function property(prop) {
  10630. return shouldUseDot.test(prop) ? `.${prop}` : `['${prop}']`;
  10631. }
  10632. function keypath(keypath) {
  10633. return keypath.split('.').map(property).join('');
  10634. }
  10635. function setupNamespace(name, root, globals, compact) {
  10636. const _ = compact ? '' : ' ';
  10637. const parts = name.split('.');
  10638. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  10639. parts.pop();
  10640. let acc = root;
  10641. return (parts
  10642. .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}${compact ? '' : ';'}`))
  10643. .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
  10644. }
  10645. function assignToDeepVariable(deepName, root, globals, compact, assignment) {
  10646. const _ = compact ? '' : ' ';
  10647. const parts = deepName.split('.');
  10648. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  10649. const last = parts.pop();
  10650. let acc = root;
  10651. let deepAssignment = parts
  10652. .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}`))
  10653. .concat(`${acc}${property(last)}`)
  10654. .join(`,${_}`)
  10655. .concat(`${_}=${_}${assignment}`);
  10656. if (parts.length > 0) {
  10657. deepAssignment = `(${deepAssignment})`;
  10658. }
  10659. return deepAssignment;
  10660. }
  10661. function trimEmptyImports(dependencies) {
  10662. let i = dependencies.length;
  10663. while (i--) {
  10664. const { imports, reexports } = dependencies[i];
  10665. if (imports || reexports) {
  10666. return dependencies.slice(0, i + 1);
  10667. }
  10668. }
  10669. return [];
  10670. }
  10671. const thisProp = (name) => `this${keypath(name)}`;
  10672. function iife(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, namedExportsMode, outro, varOrConst, warn }, { compact, esModule, extend, freeze, externalLiveBindings, globals, interop, name, namespaceToStringTag, strict }) {
  10673. const _ = compact ? '' : ' ';
  10674. const s = compact ? '' : ';';
  10675. const n = compact ? '' : '\n';
  10676. const isNamespaced = name && name.indexOf('.') !== -1;
  10677. const useVariableAssignment = !extend && !isNamespaced;
  10678. if (name && useVariableAssignment && !isLegal(name)) {
  10679. return error({
  10680. code: 'ILLEGAL_IDENTIFIER_AS_NAME',
  10681. message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`
  10682. });
  10683. }
  10684. warnOnBuiltins(warn, dependencies);
  10685. const external = trimEmptyImports(dependencies);
  10686. const deps = external.map(dep => dep.globalName || 'null');
  10687. const args = external.map(m => m.name);
  10688. if (hasExports && !name) {
  10689. warn({
  10690. code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
  10691. message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`
  10692. });
  10693. }
  10694. if (namedExportsMode && hasExports) {
  10695. if (extend) {
  10696. deps.unshift(`${thisProp(name)}${_}=${_}${thisProp(name)}${_}||${_}{}`);
  10697. args.unshift('exports');
  10698. }
  10699. else {
  10700. deps.unshift('{}');
  10701. args.unshift('exports');
  10702. }
  10703. }
  10704. const useStrict = strict ? `${t}'use strict';${n}` : '';
  10705. const interopBlock = getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t);
  10706. magicString.prepend(`${intro}${interopBlock}`);
  10707. let wrapperIntro = `(function${_}(${args.join(`,${_}`)})${_}{${n}${useStrict}${n}`;
  10708. if (hasExports) {
  10709. if (name && !(extend && namedExportsMode)) {
  10710. wrapperIntro =
  10711. (useVariableAssignment ? `${varOrConst} ${name}` : thisProp(name)) +
  10712. `${_}=${_}${wrapperIntro}`;
  10713. }
  10714. if (isNamespaced) {
  10715. wrapperIntro = setupNamespace(name, 'this', globals, compact) + wrapperIntro;
  10716. }
  10717. }
  10718. let wrapperOutro = `${n}${n}}(${deps.join(`,${_}`)}));`;
  10719. if (hasExports && !extend && namedExportsMode) {
  10720. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  10721. }
  10722. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
  10723. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, _, n);
  10724. if (namespaceMarkers) {
  10725. namespaceMarkers = n + n + namespaceMarkers;
  10726. }
  10727. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  10728. return magicString.indent(t).prepend(wrapperIntro).append(wrapperOutro);
  10729. }
  10730. function getStarExcludes({ dependencies, exports }) {
  10731. const starExcludes = new Set(exports.map(expt => expt.exported));
  10732. starExcludes.add('default');
  10733. for (const { reexports } of dependencies) {
  10734. if (reexports) {
  10735. for (const reexport of reexports) {
  10736. if (reexport.imported !== '*')
  10737. starExcludes.add(reexport.reexported);
  10738. }
  10739. }
  10740. }
  10741. return starExcludes;
  10742. }
  10743. const getStarExcludesBlock = (starExcludes, varOrConst, _, t, n) => starExcludes
  10744. ? `${n}${t}${varOrConst} _starExcludes${_}=${_}{${_}${[...starExcludes]
  10745. .map(prop => `${prop}:${_}1`)
  10746. .join(`,${_}`)}${_}};`
  10747. : '';
  10748. const getImportBindingsBlock = (importBindings, _, t, n) => (importBindings.length ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  10749. function getExportsBlock(exports, _, t, n) {
  10750. if (exports.length === 0) {
  10751. return '';
  10752. }
  10753. if (exports.length === 1) {
  10754. return `${t}${t}${t}exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
  10755. }
  10756. return (`${t}${t}${t}exports({${n}` +
  10757. exports.map(({ name, value }) => `${t}${t}${t}${t}${name}:${_}${value}`).join(`,${n}`) +
  10758. `${n}${t}${t}${t}});${n}${n}`);
  10759. }
  10760. const getHoistedExportsBlock = (exports, _, t, n) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), _, t, n);
  10761. const getMissingExportsBlock = (exports, _, t, n) => getExportsBlock(exports
  10762. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  10763. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), _, t, n);
  10764. const getSyntheticExportsBlock = (exports, _, t, n) => getExportsBlock(exports
  10765. .filter(expt => expt.expression)
  10766. .map(expt => ({ name: expt.exported, value: expt.local })), _, t, n);
  10767. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, outro, usesTopLevelAwait, varOrConst }, options) {
  10768. const n = options.compact ? '' : '\n';
  10769. const _ = options.compact ? '' : ' ';
  10770. const dependencyIds = dependencies.map(m => `'${m.id}'`);
  10771. const importBindings = [];
  10772. let starExcludes;
  10773. const setters = [];
  10774. for (const { imports, reexports } of dependencies) {
  10775. const setter = [];
  10776. if (imports) {
  10777. for (const specifier of imports) {
  10778. importBindings.push(specifier.local);
  10779. if (specifier.imported === '*') {
  10780. setter.push(`${specifier.local}${_}=${_}module;`);
  10781. }
  10782. else {
  10783. setter.push(`${specifier.local}${_}=${_}module.${specifier.imported};`);
  10784. }
  10785. }
  10786. }
  10787. if (reexports) {
  10788. let createdSetter = false;
  10789. // bulk-reexport form
  10790. if (reexports.length > 1 ||
  10791. (reexports.length === 1 &&
  10792. (reexports[0].reexported === '*' || reexports[0].imported === '*'))) {
  10793. // star reexports
  10794. for (const specifier of reexports) {
  10795. if (specifier.reexported !== '*')
  10796. continue;
  10797. // need own exports list for deduping in star export case
  10798. if (!starExcludes) {
  10799. starExcludes = getStarExcludes({ dependencies, exports });
  10800. }
  10801. createdSetter = true;
  10802. setter.push(`${varOrConst} _setter${_}=${_}{};`);
  10803. setter.push(`for${_}(var _$p${_}in${_}module)${_}{`);
  10804. setter.push(`${t}if${_}(!_starExcludes[_$p])${_}_setter[_$p]${_}=${_}module[_$p];`);
  10805. setter.push('}');
  10806. }
  10807. // star import reexport
  10808. for (const specifier of reexports) {
  10809. if (specifier.imported !== '*' || specifier.reexported === '*')
  10810. continue;
  10811. setter.push(`exports('${specifier.reexported}',${_}module);`);
  10812. }
  10813. // reexports
  10814. for (const specifier of reexports) {
  10815. if (specifier.reexported === '*' || specifier.imported === '*')
  10816. continue;
  10817. if (!createdSetter) {
  10818. setter.push(`${varOrConst} _setter${_}=${_}{};`);
  10819. createdSetter = true;
  10820. }
  10821. setter.push(`_setter.${specifier.reexported}${_}=${_}module.${specifier.imported};`);
  10822. }
  10823. if (createdSetter) {
  10824. setter.push('exports(_setter);');
  10825. }
  10826. }
  10827. else {
  10828. // single reexport
  10829. for (const specifier of reexports) {
  10830. setter.push(`exports('${specifier.reexported}',${_}module.${specifier.imported});`);
  10831. }
  10832. }
  10833. }
  10834. setters.push(setter.join(`${n}${t}${t}${t}`));
  10835. }
  10836. const registeredName = options.name ? `'${options.name}',${_}` : '';
  10837. const wrapperParams = accessedGlobals.has('module')
  10838. ? `exports,${_}module`
  10839. : hasExports
  10840. ? 'exports'
  10841. : '';
  10842. let wrapperStart = `System.register(${registeredName}[` +
  10843. dependencyIds.join(`,${_}`) +
  10844. `],${_}function${_}(${wrapperParams})${_}{${n}${t}${options.strict ? "'use strict';" : ''}` +
  10845. getStarExcludesBlock(starExcludes, varOrConst, _, t, n) +
  10846. getImportBindingsBlock(importBindings, _, t, n) +
  10847. `${n}${t}return${_}{${setters.length
  10848. ? `${n}${t}${t}setters:${_}[${setters
  10849. .map(s => s
  10850. ? `function${_}(module)${_}{${n}${t}${t}${t}${s}${n}${t}${t}}`
  10851. : options.systemNullSetters
  10852. ? `null`
  10853. : `function${_}()${_}{}`)
  10854. .join(`,${_}`)}],`
  10855. : ''}${n}`;
  10856. wrapperStart +=
  10857. `${t}${t}execute:${_}${usesTopLevelAwait ? `async${_}` : ''}function${_}()${_}{${n}${n}` +
  10858. getHoistedExportsBlock(exports, _, t, n);
  10859. const wrapperEnd = `${n}${n}` +
  10860. getSyntheticExportsBlock(exports, _, t, n) +
  10861. getMissingExportsBlock(exports, _, t, n) +
  10862. `${t}${t}}${n}${t}}${options.compact ? '' : ';'}${n}});`;
  10863. if (intro)
  10864. magicString.prepend(intro);
  10865. if (outro)
  10866. magicString.append(outro);
  10867. return magicString.indent(`${t}${t}${t}`).append(wrapperEnd).prepend(wrapperStart);
  10868. }
  10869. function globalProp(name, globalVar) {
  10870. if (!name)
  10871. return 'null';
  10872. return `${globalVar}${keypath(name)}`;
  10873. }
  10874. function safeAccess(name, globalVar, _) {
  10875. const parts = name.split('.');
  10876. let acc = globalVar;
  10877. return parts.map(part => (acc += property(part))).join(`${_}&&${_}`);
  10878. }
  10879. 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 }) {
  10880. const _ = compact ? '' : ' ';
  10881. const n = compact ? '' : '\n';
  10882. const s = compact ? '' : ';';
  10883. const factoryVar = compact ? 'f' : 'factory';
  10884. const globalVar = compact ? 'g' : 'global';
  10885. if (hasExports && !name) {
  10886. return error({
  10887. code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
  10888. message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.'
  10889. });
  10890. }
  10891. warnOnBuiltins(warn, dependencies);
  10892. const amdDeps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
  10893. const cjsDeps = dependencies.map(m => `require('${m.id}')`);
  10894. const trimmedImports = trimEmptyImports(dependencies);
  10895. const globalDeps = trimmedImports.map(module => globalProp(module.globalName, globalVar));
  10896. const factoryArgs = trimmedImports.map(m => m.name);
  10897. if (namedExportsMode && (hasExports || noConflict)) {
  10898. amdDeps.unshift(`'exports'`);
  10899. cjsDeps.unshift(`exports`);
  10900. globalDeps.unshift(assignToDeepVariable(name, globalVar, globals, compact, `${extend ? `${globalProp(name, globalVar)}${_}||${_}` : ''}{}`));
  10901. factoryArgs.unshift('exports');
  10902. }
  10903. const completeAmdId = getCompleteAmdId(amd, id);
  10904. const amdParams = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  10905. (amdDeps.length ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  10906. const define = amd.define;
  10907. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  10908. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  10909. let iifeExport;
  10910. if (noConflict) {
  10911. const noConflictExportsVar = compact ? 'e' : 'exports';
  10912. let factory;
  10913. if (!namedExportsMode && hasExports) {
  10914. factory = `var ${noConflictExportsVar}${_}=${_}${assignToDeepVariable(name, globalVar, globals, compact, `${factoryVar}(${globalDeps.join(`,${_}`)})`)};`;
  10915. }
  10916. else {
  10917. const module = globalDeps.shift();
  10918. factory =
  10919. `var ${noConflictExportsVar}${_}=${_}${module};${n}` +
  10920. `${t}${t}${factoryVar}(${[noConflictExportsVar].concat(globalDeps).join(`,${_}`)});`;
  10921. }
  10922. iifeExport =
  10923. `(function${_}()${_}{${n}` +
  10924. `${t}${t}var current${_}=${_}${safeAccess(name, globalVar, _)};${n}` +
  10925. `${t}${t}${factory}${n}` +
  10926. `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}function${_}()${_}{${_}` +
  10927. `${globalProp(name, globalVar)}${_}=${_}current;${_}return ${noConflictExportsVar}${compact ? '' : '; '}};${n}` +
  10928. `${t}}())`;
  10929. }
  10930. else {
  10931. iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`;
  10932. if (!namedExportsMode && hasExports) {
  10933. iifeExport = assignToDeepVariable(name, globalVar, globals, compact, iifeExport);
  10934. }
  10935. }
  10936. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  10937. const globalParam = iifeNeedsGlobal ? `${globalVar},${_}` : '';
  10938. const globalArg = iifeNeedsGlobal ? `this,${_}` : '';
  10939. const iifeStart = iifeNeedsGlobal
  10940. ? `(${globalVar}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVar}${_}||${_}self,${_}`
  10941. : '';
  10942. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  10943. const cjsIntro = iifeNeedsGlobal
  10944. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  10945. `${_}${cjsExport}${factoryVar}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  10946. : '';
  10947. // factory function should be wrapped by parentheses to avoid lazy parsing
  10948. const wrapperIntro = `(function${_}(${globalParam}${factoryVar})${_}{${n}` +
  10949. cjsIntro +
  10950. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}${factoryVar})${_}:${n}` +
  10951. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  10952. `}(${globalArg}(function${_}(${factoryArgs.join(', ')})${_}{${useStrict}${n}`;
  10953. const wrapperOutro = n + n + '})));';
  10954. magicString.prepend(`${intro}${getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t)}`);
  10955. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
  10956. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, _, n);
  10957. if (namespaceMarkers) {
  10958. namespaceMarkers = n + n + namespaceMarkers;
  10959. }
  10960. magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
  10961. return magicString.trim().indent(t).append(wrapperOutro).prepend(wrapperIntro);
  10962. }
  10963. var finalisers = { amd, cjs, es, iife, system, umd };
  10964. class Source {
  10965. constructor(filename, content) {
  10966. this.isOriginal = true;
  10967. this.filename = filename;
  10968. this.content = content;
  10969. }
  10970. traceSegment(line, column, name) {
  10971. return { column, line, name, source: this };
  10972. }
  10973. }
  10974. class Link {
  10975. constructor(map, sources) {
  10976. this.sources = sources;
  10977. this.names = map.names;
  10978. this.mappings = map.mappings;
  10979. }
  10980. traceMappings() {
  10981. const sources = [];
  10982. const sourcesContent = [];
  10983. const names = [];
  10984. const nameIndexMap = new Map();
  10985. const mappings = [];
  10986. for (const line of this.mappings) {
  10987. const tracedLine = [];
  10988. for (const segment of line) {
  10989. if (segment.length == 1)
  10990. continue;
  10991. const source = this.sources[segment[1]];
  10992. if (!source)
  10993. continue;
  10994. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  10995. if (traced) {
  10996. // newer sources are more likely to be used, so search backwards.
  10997. let sourceIndex = sources.lastIndexOf(traced.source.filename);
  10998. if (sourceIndex === -1) {
  10999. sourceIndex = sources.length;
  11000. sources.push(traced.source.filename);
  11001. sourcesContent[sourceIndex] = traced.source.content;
  11002. }
  11003. else if (sourcesContent[sourceIndex] == null) {
  11004. sourcesContent[sourceIndex] = traced.source.content;
  11005. }
  11006. else if (traced.source.content != null &&
  11007. sourcesContent[sourceIndex] !== traced.source.content) {
  11008. return error({
  11009. message: `Multiple conflicting contents for sourcemap source ${traced.source.filename}`
  11010. });
  11011. }
  11012. const tracedSegment = [
  11013. segment[0],
  11014. sourceIndex,
  11015. traced.line,
  11016. traced.column
  11017. ];
  11018. if (traced.name) {
  11019. let nameIndex = nameIndexMap.get(traced.name);
  11020. if (nameIndex === undefined) {
  11021. nameIndex = names.length;
  11022. names.push(traced.name);
  11023. nameIndexMap.set(traced.name, nameIndex);
  11024. }
  11025. tracedSegment[4] = nameIndex;
  11026. }
  11027. tracedLine.push(tracedSegment);
  11028. }
  11029. }
  11030. mappings.push(tracedLine);
  11031. }
  11032. return { mappings, names, sources, sourcesContent };
  11033. }
  11034. traceSegment(line, column, name) {
  11035. const segments = this.mappings[line];
  11036. if (!segments)
  11037. return null;
  11038. // binary search through segments for the given column
  11039. let i = 0;
  11040. let j = segments.length - 1;
  11041. while (i <= j) {
  11042. const m = (i + j) >> 1;
  11043. const segment = segments[m];
  11044. if (segment[0] === column) {
  11045. if (segment.length == 1)
  11046. return null;
  11047. const source = this.sources[segment[1]];
  11048. if (!source)
  11049. return null;
  11050. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  11051. }
  11052. if (segment[0] > column) {
  11053. j = m - 1;
  11054. }
  11055. else {
  11056. i = m + 1;
  11057. }
  11058. }
  11059. return null;
  11060. }
  11061. }
  11062. function getLinkMap(warn) {
  11063. return function linkMap(source, map) {
  11064. if (map.mappings) {
  11065. return new Link(map, [source]);
  11066. }
  11067. warn({
  11068. code: 'SOURCEMAP_BROKEN',
  11069. message: `Sourcemap is likely to be incorrect: a plugin (${map.plugin}) was used to transform ` +
  11070. "files, but didn't generate a sourcemap for the transformation. Consult the plugin " +
  11071. 'documentation for help',
  11072. plugin: map.plugin,
  11073. url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
  11074. });
  11075. return new Link({
  11076. mappings: [],
  11077. names: []
  11078. }, [source]);
  11079. };
  11080. }
  11081. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  11082. let source;
  11083. if (!originalSourcemap) {
  11084. source = new Source(id, originalCode);
  11085. }
  11086. else {
  11087. const sources = originalSourcemap.sources;
  11088. const sourcesContent = originalSourcemap.sourcesContent || [];
  11089. const directory = dirname(id) || '.';
  11090. const sourceRoot = originalSourcemap.sourceRoot || '.';
  11091. const baseSources = sources.map((source, i) => new Source(resolve(directory, sourceRoot, source), sourcesContent[i]));
  11092. source = new Link(originalSourcemap, baseSources);
  11093. }
  11094. return sourcemapChain.reduce(linkMap, source);
  11095. }
  11096. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, warn) {
  11097. const linkMap = getLinkMap(warn);
  11098. const moduleSources = modules
  11099. .filter(module => !module.excludeFromSourcemap)
  11100. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  11101. // DecodedSourceMap (from magic-string) uses a number[] instead of the more
  11102. // correct SourceMapSegment tuples. Cast it here to gain type safety.
  11103. let source = new Link(map, moduleSources);
  11104. source = bundleSourcemapChain.reduce(linkMap, source);
  11105. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  11106. if (file) {
  11107. const directory = dirname(file);
  11108. sources = sources.map((source) => relative$1(directory, source));
  11109. file = basename(file);
  11110. }
  11111. sourcesContent = (excludeContent ? null : sourcesContent);
  11112. return new SourceMap({ file, mappings, names, sources, sourcesContent });
  11113. }
  11114. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn) {
  11115. if (!sourcemapChain.length) {
  11116. return originalSourcemap;
  11117. }
  11118. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(warn));
  11119. const map = source.traceMappings();
  11120. return { version: 3, ...map };
  11121. }
  11122. const createHash = () => createHash$1('sha256');
  11123. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  11124. amd: deconflictImportsOther,
  11125. cjs: deconflictImportsOther,
  11126. es: deconflictImportsEsmOrSystem,
  11127. iife: deconflictImportsOther,
  11128. system: deconflictImportsEsmOrSystem,
  11129. umd: deconflictImportsOther
  11130. };
  11131. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  11132. const reversedModules = modules.slice().reverse();
  11133. for (const module of reversedModules) {
  11134. module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  11135. }
  11136. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  11137. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports);
  11138. for (const module of reversedModules) {
  11139. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  11140. }
  11141. }
  11142. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, syntheticExports) {
  11143. // This is needed for namespace reexports
  11144. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  11145. if (preserveModules || dependency instanceof ExternalModule) {
  11146. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames);
  11147. }
  11148. }
  11149. for (const variable of imports) {
  11150. const module = variable.module;
  11151. const name = variable.name;
  11152. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  11153. variable.setRenderNames(null, (module instanceof ExternalModule ? module : chunkByModule.get(module)).variableName);
  11154. }
  11155. else if (module instanceof ExternalModule && name === 'default') {
  11156. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  11157. ? module.suggestedVariableName + '__default'
  11158. : module.suggestedVariableName, usedNames));
  11159. }
  11160. else {
  11161. variable.setRenderNames(null, getSafeName(name, usedNames));
  11162. }
  11163. }
  11164. for (const variable of syntheticExports) {
  11165. variable.setRenderNames(null, getSafeName(variable.name, usedNames));
  11166. }
  11167. }
  11168. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule) {
  11169. for (const chunkOrExternalModule of dependencies) {
  11170. chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.suggestedVariableName, usedNames);
  11171. }
  11172. for (const externalModuleOrChunk of deconflictedNamespace) {
  11173. externalModuleOrChunk.namespaceVariableName = getSafeName(`${externalModuleOrChunk.suggestedVariableName}__namespace`, usedNames);
  11174. }
  11175. for (const externalModule of deconflictedDefault) {
  11176. if (deconflictedNamespace.has(externalModule) &&
  11177. canDefaultBeTakenFromNamespace(String(interop(externalModule.id)), externalLiveBindings)) {
  11178. externalModule.defaultVariableName = externalModule.namespaceVariableName;
  11179. }
  11180. else {
  11181. externalModule.defaultVariableName = getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames);
  11182. }
  11183. }
  11184. for (const variable of imports) {
  11185. const module = variable.module;
  11186. if (module instanceof ExternalModule) {
  11187. const name = variable.name;
  11188. if (name === 'default') {
  11189. const moduleInterop = String(interop(module.id));
  11190. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  11191. ? module.defaultVariableName
  11192. : module.variableName;
  11193. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  11194. variable.setRenderNames(variableName, 'default');
  11195. }
  11196. else {
  11197. variable.setRenderNames(null, variableName);
  11198. }
  11199. }
  11200. else if (name === '*') {
  11201. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[String(interop(module.id))]
  11202. ? module.namespaceVariableName
  11203. : module.variableName);
  11204. }
  11205. else {
  11206. // if the second parameter is `null`, it uses its "name" for the property name
  11207. variable.setRenderNames(module.variableName, null);
  11208. }
  11209. }
  11210. else {
  11211. const chunk = chunkByModule.get(module);
  11212. if (preserveModules && variable.isNamespace) {
  11213. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  11214. }
  11215. else if (chunk.exportMode === 'default') {
  11216. variable.setRenderNames(null, chunk.variableName);
  11217. }
  11218. else {
  11219. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  11220. }
  11221. }
  11222. }
  11223. }
  11224. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  11225. for (const module of modules) {
  11226. for (const variable of module.scope.variables.values()) {
  11227. if (variable.included &&
  11228. // this will only happen for exports in some formats
  11229. !(variable.renderBaseName ||
  11230. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  11231. variable.setRenderNames(null, getSafeName(variable.name, usedNames));
  11232. }
  11233. }
  11234. if (includedNamespaces.has(module)) {
  11235. const namespace = module.namespace;
  11236. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames));
  11237. }
  11238. }
  11239. }
  11240. const needsEscapeRegEx = /[\\'\r\n\u2028\u2029]/;
  11241. const quoteNewlineRegEx = /(['\r\n\u2028\u2029])/g;
  11242. const backSlashRegEx = /\\/g;
  11243. function escapeId(id) {
  11244. if (!id.match(needsEscapeRegEx))
  11245. return id;
  11246. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  11247. }
  11248. function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
  11249. let nameIndex = 0;
  11250. for (const variable of exports) {
  11251. let exportName = variable.name[0];
  11252. if (exportsByName[exportName]) {
  11253. do {
  11254. exportName = toBase64(++nameIndex);
  11255. // skip past leading number identifiers
  11256. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  11257. nameIndex += 9 * 64 ** (exportName.length - 1);
  11258. exportName = toBase64(nameIndex);
  11259. }
  11260. } while (RESERVED_NAMES[exportName] || exportsByName[exportName]);
  11261. }
  11262. exportsByName[exportName] = variable;
  11263. exportNamesByVariable.set(variable, [exportName]);
  11264. }
  11265. }
  11266. function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
  11267. for (const variable of exports) {
  11268. let nameIndex = 0;
  11269. let exportName = variable.name;
  11270. while (exportsByName[exportName]) {
  11271. exportName = variable.name + '$' + ++nameIndex;
  11272. }
  11273. exportsByName[exportName] = variable;
  11274. exportNamesByVariable.set(variable, [exportName]);
  11275. }
  11276. }
  11277. function getExportMode(chunk, { exports: exportMode, name, format }, unsetOptions, facadeModuleId, warn) {
  11278. const exportKeys = chunk.getExportNames();
  11279. if (exportMode === 'default') {
  11280. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  11281. return error(errIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  11282. }
  11283. }
  11284. else if (exportMode === 'none' && exportKeys.length) {
  11285. return error(errIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  11286. }
  11287. if (exportMode === 'auto') {
  11288. if (exportKeys.length === 0) {
  11289. exportMode = 'none';
  11290. }
  11291. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  11292. if (format === 'cjs' && unsetOptions.has('exports')) {
  11293. warn(errPreferNamedExports(facadeModuleId));
  11294. }
  11295. exportMode = 'default';
  11296. }
  11297. else {
  11298. if (format !== 'es' && exportKeys.indexOf('default') !== -1) {
  11299. warn(errMixedExport(facadeModuleId, name));
  11300. }
  11301. exportMode = 'named';
  11302. }
  11303. }
  11304. return exportMode;
  11305. }
  11306. function guessIndentString(code) {
  11307. const lines = code.split('\n');
  11308. const tabbed = lines.filter(line => /^\t+/.test(line));
  11309. const spaced = lines.filter(line => /^ {2,}/.test(line));
  11310. if (tabbed.length === 0 && spaced.length === 0) {
  11311. return null;
  11312. }
  11313. // More lines tabbed than spaced? Assume tabs, and
  11314. // default to tabs in the case of a tie (or nothing
  11315. // to go on)
  11316. if (tabbed.length >= spaced.length) {
  11317. return '\t';
  11318. }
  11319. // Otherwise, we need to guess the multiple
  11320. const min = spaced.reduce((previous, current) => {
  11321. const numSpaces = /^ +/.exec(current)[0].length;
  11322. return Math.min(numSpaces, previous);
  11323. }, Infinity);
  11324. return new Array(min + 1).join(' ');
  11325. }
  11326. function getIndentString(modules, options) {
  11327. if (options.indent !== true)
  11328. return options.indent;
  11329. for (let i = 0; i < modules.length; i++) {
  11330. const indent = guessIndentString(modules[i].originalCode);
  11331. if (indent !== null)
  11332. return indent;
  11333. }
  11334. return '\t';
  11335. }
  11336. function getStaticDependencies(chunk, orderedModules, chunkByModule) {
  11337. const staticDependencyBlocks = [];
  11338. const handledDependencies = new Set();
  11339. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  11340. const module = orderedModules[modulePos];
  11341. if (!handledDependencies.has(module)) {
  11342. const staticDependencies = [];
  11343. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule);
  11344. staticDependencyBlocks.unshift(staticDependencies);
  11345. }
  11346. }
  11347. const dependencies = new Set();
  11348. for (const block of staticDependencyBlocks) {
  11349. for (const dependency of block) {
  11350. dependencies.add(dependency);
  11351. }
  11352. }
  11353. return dependencies;
  11354. }
  11355. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule) {
  11356. const dependencies = module.getDependenciesToBeIncluded();
  11357. for (const dependency of dependencies) {
  11358. if (dependency instanceof ExternalModule) {
  11359. staticDependencies.push(dependency);
  11360. continue;
  11361. }
  11362. const dependencyChunk = chunkByModule.get(dependency);
  11363. if (dependencyChunk !== chunk) {
  11364. staticDependencies.push(dependencyChunk);
  11365. continue;
  11366. }
  11367. if (!handledModules.has(dependency)) {
  11368. handledModules.add(dependency);
  11369. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule);
  11370. }
  11371. }
  11372. }
  11373. function decodedSourcemap(map) {
  11374. if (!map)
  11375. return null;
  11376. if (typeof map === 'string') {
  11377. map = JSON.parse(map);
  11378. }
  11379. if (map.mappings === '') {
  11380. return {
  11381. mappings: [],
  11382. names: [],
  11383. sources: [],
  11384. version: 3
  11385. };
  11386. }
  11387. let mappings;
  11388. if (typeof map.mappings === 'string') {
  11389. mappings = decode(map.mappings);
  11390. }
  11391. else {
  11392. mappings = map.mappings;
  11393. }
  11394. return { ...map, mappings };
  11395. }
  11396. function renderChunk({ code, options, outputPluginDriver, renderChunk, sourcemapChain }) {
  11397. const renderChunkReducer = (code, result, plugin) => {
  11398. if (result == null)
  11399. return code;
  11400. if (typeof result === 'string')
  11401. result = {
  11402. code: result,
  11403. map: undefined
  11404. };
  11405. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  11406. if (result.map !== null) {
  11407. const map = decodedSourcemap(result.map);
  11408. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  11409. }
  11410. return result.code;
  11411. };
  11412. return outputPluginDriver.hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer);
  11413. }
  11414. function renderNamePattern(pattern, patternName, replacements) {
  11415. if (isPathFragment(pattern))
  11416. return error(errFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths.`));
  11417. return pattern.replace(/\[(\w+)\]/g, (_match, type) => {
  11418. if (!replacements.hasOwnProperty(type)) {
  11419. return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`));
  11420. }
  11421. const replacement = replacements[type]();
  11422. if (isPathFragment(replacement))
  11423. return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  11424. return replacement;
  11425. });
  11426. }
  11427. function makeUnique(name, existingNames) {
  11428. const existingNamesLowercase = new Set(Object.keys(existingNames).map(key => key.toLowerCase()));
  11429. if (!existingNamesLowercase.has(name.toLocaleLowerCase()))
  11430. return name;
  11431. const ext = extname(name);
  11432. name = name.substr(0, name.length - ext.length);
  11433. let uniqueName, uniqueIndex = 1;
  11434. while (existingNamesLowercase.has((uniqueName = name + ++uniqueIndex + ext).toLowerCase()))
  11435. ;
  11436. return uniqueName;
  11437. }
  11438. const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];
  11439. function getGlobalName(module, globals, hasExports, warn) {
  11440. const globalName = typeof globals === 'function' ? globals(module.id) : globals[module.id];
  11441. if (globalName) {
  11442. return globalName;
  11443. }
  11444. if (hasExports) {
  11445. warn({
  11446. code: 'MISSING_GLOBAL_NAME',
  11447. guess: module.variableName,
  11448. message: `No name was provided for external module '${module.id}' in output.globals – guessing '${module.variableName}'`,
  11449. source: module.id
  11450. });
  11451. return module.variableName;
  11452. }
  11453. }
  11454. class Chunk {
  11455. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias) {
  11456. this.orderedModules = orderedModules;
  11457. this.inputOptions = inputOptions;
  11458. this.outputOptions = outputOptions;
  11459. this.unsetOptions = unsetOptions;
  11460. this.pluginDriver = pluginDriver;
  11461. this.modulesById = modulesById;
  11462. this.chunkByModule = chunkByModule;
  11463. this.facadeChunkByModule = facadeChunkByModule;
  11464. this.includedNamespaces = includedNamespaces;
  11465. this.manualChunkAlias = manualChunkAlias;
  11466. this.entryModules = [];
  11467. this.exportMode = 'named';
  11468. this.facadeModule = null;
  11469. this.id = null;
  11470. this.namespaceVariableName = '';
  11471. this.variableName = '';
  11472. this.accessedGlobalsByScope = new Map();
  11473. this.dependencies = new Set();
  11474. this.dynamicDependencies = new Set();
  11475. this.dynamicEntryModules = [];
  11476. this.dynamicName = null;
  11477. this.exportNamesByVariable = new Map();
  11478. this.exports = new Set();
  11479. this.exportsByName = Object.create(null);
  11480. this.fileName = null;
  11481. this.implicitEntryModules = [];
  11482. this.implicitlyLoadedBefore = new Set();
  11483. this.imports = new Set();
  11484. this.indentString = undefined;
  11485. this.isEmpty = true;
  11486. this.name = null;
  11487. this.needsExportsShim = false;
  11488. this.renderedDependencies = null;
  11489. this.renderedExports = null;
  11490. this.renderedHash = undefined;
  11491. this.renderedModuleSources = new Map();
  11492. this.renderedModules = Object.create(null);
  11493. this.renderedSource = null;
  11494. this.sortedExportNames = null;
  11495. this.strictFacade = false;
  11496. this.usedModules = undefined;
  11497. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  11498. const chunkModules = new Set(orderedModules);
  11499. for (const module of orderedModules) {
  11500. if (module.namespace.included) {
  11501. includedNamespaces.add(module);
  11502. }
  11503. if (this.isEmpty && module.isIncluded()) {
  11504. this.isEmpty = false;
  11505. }
  11506. if (module.info.isEntry || outputOptions.preserveModules) {
  11507. this.entryModules.push(module);
  11508. }
  11509. for (const importer of module.includedDynamicImporters) {
  11510. if (!chunkModules.has(importer)) {
  11511. this.dynamicEntryModules.push(module);
  11512. // Modules with synthetic exports need an artificial namespace for dynamic imports
  11513. if (module.info.syntheticNamedExports && !outputOptions.preserveModules) {
  11514. includedNamespaces.add(module);
  11515. this.exports.add(module.namespace);
  11516. }
  11517. }
  11518. }
  11519. if (module.implicitlyLoadedAfter.size > 0) {
  11520. this.implicitEntryModules.push(module);
  11521. }
  11522. }
  11523. this.suggestedVariableName = makeLegal(this.generateVariableName());
  11524. }
  11525. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName) {
  11526. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, null);
  11527. chunk.assignFacadeName(facadeName, facadedModule);
  11528. if (!facadeChunkByModule.has(facadedModule)) {
  11529. facadeChunkByModule.set(facadedModule, chunk);
  11530. }
  11531. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  11532. chunk.dependencies.add(dependency instanceof Module ? chunkByModule.get(dependency) : dependency);
  11533. }
  11534. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  11535. facadedModule.info.hasModuleSideEffects &&
  11536. facadedModule.hasEffects()) {
  11537. chunk.dependencies.add(chunkByModule.get(facadedModule));
  11538. }
  11539. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  11540. chunk.facadeModule = facadedModule;
  11541. chunk.strictFacade = true;
  11542. return chunk;
  11543. }
  11544. canModuleBeFacade(module, exposedVariables) {
  11545. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  11546. for (const exposedVariable of this.exports) {
  11547. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  11548. if (moduleExportNamesByVariable.size === 0 &&
  11549. module.isUserDefinedEntryPoint &&
  11550. module.preserveSignature === 'strict' &&
  11551. this.unsetOptions.has('preserveEntrySignatures')) {
  11552. this.inputOptions.onwarn({
  11553. code: 'EMPTY_FACADE',
  11554. id: module.id,
  11555. 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.`,
  11556. url: 'https://rollupjs.org/guide/en/#preserveentrysignatures'
  11557. });
  11558. }
  11559. return false;
  11560. }
  11561. }
  11562. for (const exposedVariable of exposedVariables) {
  11563. if (!(moduleExportNamesByVariable.has(exposedVariable) || exposedVariable.module === module)) {
  11564. return false;
  11565. }
  11566. }
  11567. return true;
  11568. }
  11569. generateExports() {
  11570. this.sortedExportNames = null;
  11571. const remainingExports = new Set(this.exports);
  11572. if (this.facadeModule !== null &&
  11573. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  11574. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  11575. for (const [variable, exportNames] of exportNamesByVariable) {
  11576. this.exportNamesByVariable.set(variable, [...exportNames]);
  11577. for (const exportName of exportNames) {
  11578. this.exportsByName[exportName] = variable;
  11579. }
  11580. remainingExports.delete(variable);
  11581. }
  11582. }
  11583. if (this.outputOptions.minifyInternalExports) {
  11584. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  11585. }
  11586. else {
  11587. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  11588. }
  11589. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  11590. this.exportMode = getExportMode(this, this.outputOptions, this.unsetOptions, this.facadeModule.id, this.inputOptions.onwarn);
  11591. }
  11592. generateFacades() {
  11593. var _a;
  11594. const facades = [];
  11595. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  11596. const exposedVariables = new Set(this.dynamicEntryModules.map(module => module.namespace));
  11597. for (const module of entryModules) {
  11598. if (module.preserveSignature) {
  11599. for (const exportedVariable of module.getExportNamesByVariable().keys()) {
  11600. exposedVariables.add(exportedVariable);
  11601. }
  11602. }
  11603. }
  11604. for (const module of entryModules) {
  11605. const requiredFacades = Array.from(module.userChunkNames, name => ({
  11606. name
  11607. }));
  11608. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  11609. requiredFacades.push({});
  11610. }
  11611. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  11612. if (requiredFacades.length === 0) {
  11613. requiredFacades.push({});
  11614. }
  11615. if (!this.facadeModule) {
  11616. const needsStrictFacade = module.preserveSignature === 'strict' ||
  11617. (module.preserveSignature === 'exports-only' &&
  11618. module.getExportNamesByVariable().size !== 0);
  11619. if (!needsStrictFacade ||
  11620. this.outputOptions.preserveModules ||
  11621. this.canModuleBeFacade(module, exposedVariables)) {
  11622. this.facadeModule = module;
  11623. this.facadeChunkByModule.set(module, this);
  11624. if (module.preserveSignature) {
  11625. this.strictFacade = needsStrictFacade;
  11626. }
  11627. this.assignFacadeName(requiredFacades.shift(), module);
  11628. }
  11629. }
  11630. for (const facadeName of requiredFacades) {
  11631. facades.push(Chunk.generateFacade(this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.modulesById, this.chunkByModule, this.facadeChunkByModule, this.includedNamespaces, module, facadeName));
  11632. }
  11633. }
  11634. for (const module of this.dynamicEntryModules) {
  11635. if (module.info.syntheticNamedExports)
  11636. continue;
  11637. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  11638. this.facadeModule = module;
  11639. this.facadeChunkByModule.set(module, this);
  11640. this.strictFacade = true;
  11641. this.dynamicName = getChunkNameFromModule(module);
  11642. }
  11643. else if (this.facadeModule === module &&
  11644. !this.strictFacade &&
  11645. this.canModuleBeFacade(module, exposedVariables)) {
  11646. this.strictFacade = true;
  11647. }
  11648. else if (!((_a = this.facadeChunkByModule.get(module)) === null || _a === void 0 ? void 0 : _a.strictFacade)) {
  11649. this.includedNamespaces.add(module);
  11650. this.exports.add(module.namespace);
  11651. }
  11652. }
  11653. return facades;
  11654. }
  11655. generateId(addons, options, existingNames, includeHash) {
  11656. if (this.fileName !== null) {
  11657. return this.fileName;
  11658. }
  11659. const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint
  11660. ? [options.entryFileNames, 'output.entryFileNames']
  11661. : [options.chunkFileNames, 'output.chunkFileNames'];
  11662. return makeUnique(renderNamePattern(typeof pattern === 'function' ? pattern(this.getChunkInfo()) : pattern, patternName, {
  11663. format: () => options.format,
  11664. hash: () => includeHash
  11665. ? this.computeContentHashWithDependencies(addons, options, existingNames)
  11666. : '[hash]',
  11667. name: () => this.getChunkName()
  11668. }), existingNames);
  11669. }
  11670. generateIdPreserveModules(preserveModulesRelativeDir, options, existingNames, unsetOptions) {
  11671. const id = this.orderedModules[0].id;
  11672. const sanitizedId = this.outputOptions.sanitizeFileName(id);
  11673. let path;
  11674. if (isAbsolute(id)) {
  11675. const extension = extname(id);
  11676. const pattern = unsetOptions.has('entryFileNames')
  11677. ? '[name][assetExtname].js'
  11678. : options.entryFileNames;
  11679. const currentDir = dirname(sanitizedId);
  11680. const fileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getChunkInfo()) : pattern, 'output.entryFileNames', {
  11681. assetExtname: () => (NON_ASSET_EXTENSIONS.includes(extension) ? '' : extension),
  11682. ext: () => extension.substr(1),
  11683. extname: () => extension,
  11684. format: () => options.format,
  11685. name: () => this.getChunkName()
  11686. });
  11687. const currentPath = `${currentDir}/${fileName}`;
  11688. const { preserveModulesRoot } = options;
  11689. if (preserveModulesRoot && currentPath.startsWith(preserveModulesRoot)) {
  11690. path = currentPath.slice(preserveModulesRoot.length).replace(/^[\\/]/, '');
  11691. }
  11692. else {
  11693. path = relative(preserveModulesRelativeDir, currentPath);
  11694. }
  11695. }
  11696. else {
  11697. path = `_virtual/${basename(sanitizedId)}`;
  11698. }
  11699. return makeUnique(normalize(path), existingNames);
  11700. }
  11701. getChunkInfo() {
  11702. const facadeModule = this.facadeModule;
  11703. const getChunkName = this.getChunkName.bind(this);
  11704. return {
  11705. exports: this.getExportNames(),
  11706. facadeModuleId: facadeModule && facadeModule.id,
  11707. isDynamicEntry: this.dynamicEntryModules.length > 0,
  11708. isEntry: facadeModule !== null && facadeModule.info.isEntry,
  11709. isImplicitEntry: this.implicitEntryModules.length > 0,
  11710. modules: this.renderedModules,
  11711. get name() {
  11712. return getChunkName();
  11713. },
  11714. type: 'chunk'
  11715. };
  11716. }
  11717. getChunkInfoWithFileNames() {
  11718. return Object.assign(this.getChunkInfo(), {
  11719. code: undefined,
  11720. dynamicImports: Array.from(this.dynamicDependencies, getId),
  11721. fileName: this.id,
  11722. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, getId),
  11723. importedBindings: this.getImportedBindingsPerDependency(),
  11724. imports: Array.from(this.dependencies, getId),
  11725. map: undefined,
  11726. referencedFiles: this.getReferencedFiles()
  11727. });
  11728. }
  11729. getChunkName() {
  11730. return (this.name || (this.name = this.outputOptions.sanitizeFileName(this.getFallbackChunkName())));
  11731. }
  11732. getExportNames() {
  11733. return (this.sortedExportNames || (this.sortedExportNames = Object.keys(this.exportsByName).sort()));
  11734. }
  11735. getRenderedHash() {
  11736. if (this.renderedHash)
  11737. return this.renderedHash;
  11738. const hash = createHash();
  11739. const hashAugmentation = this.pluginDriver.hookReduceValueSync('augmentChunkHash', '', [this.getChunkInfo()], (augmentation, pluginHash) => {
  11740. if (pluginHash) {
  11741. augmentation += pluginHash;
  11742. }
  11743. return augmentation;
  11744. });
  11745. hash.update(hashAugmentation);
  11746. hash.update(this.renderedSource.toString());
  11747. hash.update(this.getExportNames()
  11748. .map(exportName => {
  11749. const variable = this.exportsByName[exportName];
  11750. return `${relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
  11751. })
  11752. .join(','));
  11753. return (this.renderedHash = hash.digest('hex'));
  11754. }
  11755. getVariableExportName(variable) {
  11756. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  11757. return '*';
  11758. }
  11759. return this.exportNamesByVariable.get(variable)[0];
  11760. }
  11761. link() {
  11762. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule);
  11763. for (const module of this.orderedModules) {
  11764. this.addDependenciesToChunk(module.dynamicDependencies, this.dynamicDependencies);
  11765. this.addDependenciesToChunk(module.implicitlyLoadedBefore, this.implicitlyLoadedBefore);
  11766. this.setUpChunkImportsAndExportsForModule(module);
  11767. }
  11768. }
  11769. // prerender allows chunk hashes and names to be generated before finalizing
  11770. preRender(options, inputBase) {
  11771. const magicString = new Bundle$1({ separator: options.compact ? '' : '\n\n' });
  11772. this.usedModules = [];
  11773. this.indentString = getIndentString(this.orderedModules, options);
  11774. const n = options.compact ? '' : '\n';
  11775. const _ = options.compact ? '' : ' ';
  11776. const renderOptions = {
  11777. compact: options.compact,
  11778. dynamicImportFunction: options.dynamicImportFunction,
  11779. exportNamesByVariable: this.exportNamesByVariable,
  11780. format: options.format,
  11781. freeze: options.freeze,
  11782. indent: this.indentString,
  11783. namespaceToStringTag: options.namespaceToStringTag,
  11784. outputPluginDriver: this.pluginDriver,
  11785. varOrConst: options.preferConst ? 'const' : 'var'
  11786. };
  11787. // for static and dynamic entry points, inline the execution list to avoid loading latency
  11788. if (options.hoistTransitiveImports &&
  11789. !this.outputOptions.preserveModules &&
  11790. this.facadeModule !== null) {
  11791. for (const dep of this.dependencies) {
  11792. if (dep instanceof Chunk)
  11793. this.inlineChunkDependencies(dep);
  11794. }
  11795. }
  11796. this.prepareDynamicImportsAndImportMetas();
  11797. this.setIdentifierRenderResolutions(options);
  11798. let hoistedSource = '';
  11799. const renderedModules = this.renderedModules;
  11800. for (const module of this.orderedModules) {
  11801. let renderedLength = 0;
  11802. if (module.isIncluded() || this.includedNamespaces.has(module)) {
  11803. const source = module.render(renderOptions).trim();
  11804. renderedLength = source.length();
  11805. if (renderedLength) {
  11806. if (options.compact && source.lastLine().indexOf('//') !== -1)
  11807. source.append('\n');
  11808. this.renderedModuleSources.set(module, source);
  11809. magicString.addSource(source);
  11810. this.usedModules.push(module);
  11811. }
  11812. const namespace = module.namespace;
  11813. if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
  11814. const rendered = namespace.renderBlock(renderOptions);
  11815. if (namespace.renderFirst())
  11816. hoistedSource += n + rendered;
  11817. else
  11818. magicString.addSource(new MagicString$1(rendered));
  11819. }
  11820. }
  11821. const { renderedExports, removedExports } = module.getRenderedExports();
  11822. const { renderedModuleSources } = this;
  11823. renderedModules[module.id] = {
  11824. get code() {
  11825. var _a, _b;
  11826. return (_b = (_a = renderedModuleSources.get(module)) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : null;
  11827. },
  11828. originalLength: module.originalCode.length,
  11829. removedExports,
  11830. renderedExports,
  11831. renderedLength
  11832. };
  11833. }
  11834. if (hoistedSource)
  11835. magicString.prepend(hoistedSource + n + n);
  11836. if (this.needsExportsShim) {
  11837. magicString.prepend(`${n}${renderOptions.varOrConst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  11838. }
  11839. if (options.compact) {
  11840. this.renderedSource = magicString;
  11841. }
  11842. else {
  11843. this.renderedSource = magicString.trim();
  11844. }
  11845. this.renderedHash = undefined;
  11846. if (this.isEmpty && this.getExportNames().length === 0 && this.dependencies.size === 0) {
  11847. const chunkName = this.getChunkName();
  11848. this.inputOptions.onwarn({
  11849. chunkName,
  11850. code: 'EMPTY_BUNDLE',
  11851. message: `Generated an empty chunk: "${chunkName}"`
  11852. });
  11853. }
  11854. this.setExternalRenderPaths(options, inputBase);
  11855. this.renderedDependencies = this.getChunkDependencyDeclarations(options);
  11856. this.renderedExports =
  11857. this.exportMode === 'none' ? [] : this.getChunkExportDeclarations(options.format);
  11858. }
  11859. async render(options, addons, outputChunk) {
  11860. timeStart('render format', 2);
  11861. const format = options.format;
  11862. const finalise = finalisers[format];
  11863. if (options.dynamicImportFunction && format !== 'es') {
  11864. this.inputOptions.onwarn({
  11865. code: 'INVALID_OPTION',
  11866. message: '"output.dynamicImportFunction" is ignored for formats other than "es".'
  11867. });
  11868. }
  11869. // populate ids in the rendered declarations only here
  11870. // as chunk ids known only after prerender
  11871. for (const dependency of this.dependencies) {
  11872. const renderedDependency = this.renderedDependencies.get(dependency);
  11873. if (dependency instanceof ExternalModule) {
  11874. const originalId = dependency.renderPath;
  11875. renderedDependency.id = escapeId(dependency.renormalizeRenderPath ? this.getRelativePath(originalId, false) : originalId);
  11876. }
  11877. else {
  11878. renderedDependency.namedExportsMode = dependency.exportMode !== 'default';
  11879. renderedDependency.id = escapeId(this.getRelativePath(dependency.id, false));
  11880. }
  11881. }
  11882. this.finaliseDynamicImports(options);
  11883. this.finaliseImportMetas(format);
  11884. const hasExports = this.renderedExports.length !== 0 ||
  11885. [...this.renderedDependencies.values()].some(dep => (dep.reexports && dep.reexports.length !== 0));
  11886. let usesTopLevelAwait = false;
  11887. const accessedGlobals = new Set();
  11888. for (const module of this.orderedModules) {
  11889. if (module.usesTopLevelAwait) {
  11890. usesTopLevelAwait = true;
  11891. }
  11892. const accessedGlobalVariables = this.accessedGlobalsByScope.get(module.scope);
  11893. if (accessedGlobalVariables) {
  11894. for (const name of accessedGlobalVariables) {
  11895. accessedGlobals.add(name);
  11896. }
  11897. }
  11898. }
  11899. if (usesTopLevelAwait && format !== 'es' && format !== 'system') {
  11900. return error({
  11901. code: 'INVALID_TLA_FORMAT',
  11902. message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
  11903. });
  11904. }
  11905. /* istanbul ignore next */
  11906. if (!this.id) {
  11907. throw new Error('Internal Error: expecting chunk id');
  11908. }
  11909. const magicString = finalise(this.renderedSource, {
  11910. accessedGlobals,
  11911. dependencies: [...this.renderedDependencies.values()],
  11912. exports: this.renderedExports,
  11913. hasExports,
  11914. id: this.id,
  11915. indentString: this.indentString,
  11916. intro: addons.intro,
  11917. isEntryFacade: this.outputOptions.preserveModules ||
  11918. (this.facadeModule !== null && this.facadeModule.info.isEntry),
  11919. isModuleFacade: this.facadeModule !== null,
  11920. namedExportsMode: this.exportMode !== 'default',
  11921. outro: addons.outro,
  11922. usesTopLevelAwait,
  11923. varOrConst: options.preferConst ? 'const' : 'var',
  11924. warn: this.inputOptions.onwarn
  11925. }, options);
  11926. if (addons.banner)
  11927. magicString.prepend(addons.banner);
  11928. if (addons.footer)
  11929. magicString.append(addons.footer);
  11930. const prevCode = magicString.toString();
  11931. timeEnd('render format', 2);
  11932. let map = null;
  11933. const chunkSourcemapChain = [];
  11934. let code = await renderChunk({
  11935. code: prevCode,
  11936. options,
  11937. outputPluginDriver: this.pluginDriver,
  11938. renderChunk: outputChunk,
  11939. sourcemapChain: chunkSourcemapChain
  11940. });
  11941. if (options.sourcemap) {
  11942. timeStart('sourcemap', 2);
  11943. let file;
  11944. if (options.file)
  11945. file = resolve(options.sourcemapFile || options.file);
  11946. else if (options.dir)
  11947. file = resolve(options.dir, this.id);
  11948. else
  11949. file = resolve(this.id);
  11950. const decodedMap = magicString.generateDecodedMap({});
  11951. map = collapseSourcemaps(file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources, this.inputOptions.onwarn);
  11952. map.sources = map.sources
  11953. .map(sourcePath => {
  11954. const { sourcemapPathTransform } = options;
  11955. if (sourcemapPathTransform) {
  11956. const newSourcePath = sourcemapPathTransform(sourcePath, `${file}.map`);
  11957. if (typeof newSourcePath !== 'string') {
  11958. error(errFailedValidation(`sourcemapPathTransform function must return a string.`));
  11959. }
  11960. return newSourcePath;
  11961. }
  11962. return sourcePath;
  11963. })
  11964. .map(normalize);
  11965. timeEnd('sourcemap', 2);
  11966. }
  11967. if (!options.compact && code[code.length - 1] !== '\n')
  11968. code += '\n';
  11969. return { code, map };
  11970. }
  11971. addDependenciesToChunk(moduleDependencies, chunkDependencies) {
  11972. for (const module of moduleDependencies) {
  11973. if (module instanceof Module) {
  11974. const chunk = this.chunkByModule.get(module);
  11975. if (chunk && chunk !== this) {
  11976. chunkDependencies.add(chunk);
  11977. }
  11978. }
  11979. else {
  11980. chunkDependencies.add(module);
  11981. }
  11982. }
  11983. }
  11984. assignFacadeName({ fileName, name }, facadedModule) {
  11985. if (fileName) {
  11986. this.fileName = fileName;
  11987. }
  11988. else {
  11989. this.name = this.outputOptions.sanitizeFileName(name || getChunkNameFromModule(facadedModule));
  11990. }
  11991. }
  11992. checkCircularDependencyImport(variable, importingModule) {
  11993. const variableModule = variable.module;
  11994. if (variableModule instanceof Module) {
  11995. const exportChunk = this.chunkByModule.get(variableModule);
  11996. let alternativeReexportModule;
  11997. do {
  11998. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  11999. if (alternativeReexportModule) {
  12000. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  12001. if (exportingChunk && exportingChunk !== exportChunk) {
  12002. this.inputOptions.onwarn(errCyclicCrossChunkReexport(variableModule.getExportNamesByVariable().get(variable)[0], variableModule.id, alternativeReexportModule.id, importingModule.id));
  12003. }
  12004. importingModule = alternativeReexportModule;
  12005. }
  12006. } while (alternativeReexportModule);
  12007. }
  12008. }
  12009. computeContentHashWithDependencies(addons, options, existingNames) {
  12010. const hash = createHash();
  12011. hash.update([addons.intro, addons.outro, addons.banner, addons.footer].map(addon => addon || '').join(':'));
  12012. hash.update(options.format);
  12013. const dependenciesForHashing = new Set([this]);
  12014. for (const current of dependenciesForHashing) {
  12015. if (current instanceof ExternalModule) {
  12016. hash.update(':' + current.renderPath);
  12017. }
  12018. else {
  12019. hash.update(current.getRenderedHash());
  12020. hash.update(current.generateId(addons, options, existingNames, false));
  12021. }
  12022. if (current instanceof ExternalModule)
  12023. continue;
  12024. for (const dependency of [...current.dependencies, ...current.dynamicDependencies]) {
  12025. dependenciesForHashing.add(dependency);
  12026. }
  12027. }
  12028. return hash.digest('hex').substr(0, 8);
  12029. }
  12030. ensureReexportsAreAvailableForModule(module) {
  12031. const map = module.getExportNamesByVariable();
  12032. for (const exportedVariable of map.keys()) {
  12033. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  12034. const importedVariable = isSynthetic
  12035. ? exportedVariable.getBaseVariable()
  12036. : exportedVariable;
  12037. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  12038. this.checkCircularDependencyImport(importedVariable, module);
  12039. const exportingModule = importedVariable.module;
  12040. if (exportingModule instanceof Module) {
  12041. const chunk = this.chunkByModule.get(exportingModule);
  12042. if (chunk && chunk !== this) {
  12043. chunk.exports.add(importedVariable);
  12044. if (isSynthetic) {
  12045. this.imports.add(importedVariable);
  12046. }
  12047. }
  12048. }
  12049. }
  12050. }
  12051. }
  12052. finaliseDynamicImports(options) {
  12053. const stripKnownJsExtensions = options.format === 'amd';
  12054. for (const [module, code] of this.renderedModuleSources) {
  12055. for (const { node, resolution } of module.dynamicImports) {
  12056. const chunk = this.chunkByModule.get(resolution);
  12057. const facadeChunk = this.facadeChunkByModule.get(resolution);
  12058. if (!resolution || !node.included || chunk === this) {
  12059. continue;
  12060. }
  12061. const renderedResolution = resolution instanceof Module
  12062. ? `'${this.getRelativePath((facadeChunk || chunk).id, stripKnownJsExtensions)}'`
  12063. : resolution instanceof ExternalModule
  12064. ? `'${resolution.renormalizeRenderPath
  12065. ? this.getRelativePath(resolution.renderPath, stripKnownJsExtensions)
  12066. : resolution.renderPath}'`
  12067. : resolution;
  12068. node.renderFinalResolution(code, renderedResolution, resolution instanceof Module &&
  12069. !(facadeChunk === null || facadeChunk === void 0 ? void 0 : facadeChunk.strictFacade) &&
  12070. chunk.exportNamesByVariable.get(resolution.namespace)[0], options);
  12071. }
  12072. }
  12073. }
  12074. finaliseImportMetas(format) {
  12075. for (const [module, code] of this.renderedModuleSources) {
  12076. for (const importMeta of module.importMetas) {
  12077. importMeta.renderFinalMechanism(code, this.id, format, this.pluginDriver);
  12078. }
  12079. }
  12080. }
  12081. generateVariableName() {
  12082. if (this.manualChunkAlias) {
  12083. return this.manualChunkAlias;
  12084. }
  12085. const moduleForNaming = this.entryModules[0] ||
  12086. this.implicitEntryModules[0] ||
  12087. this.dynamicEntryModules[0] ||
  12088. this.orderedModules[this.orderedModules.length - 1];
  12089. if (moduleForNaming) {
  12090. return moduleForNaming.chunkName || getAliasName(moduleForNaming.id);
  12091. }
  12092. return 'chunk';
  12093. }
  12094. getChunkDependencyDeclarations(options) {
  12095. const importSpecifiers = this.getImportSpecifiers();
  12096. const reexportSpecifiers = this.getReexportSpecifiers();
  12097. const dependencyDeclaration = new Map();
  12098. for (const dep of this.dependencies) {
  12099. const imports = importSpecifiers.get(dep) || null;
  12100. const reexports = reexportSpecifiers.get(dep) || null;
  12101. const namedExportsMode = dep instanceof ExternalModule || dep.exportMode !== 'default';
  12102. dependencyDeclaration.set(dep, {
  12103. defaultVariableName: dep.defaultVariableName,
  12104. globalName: (dep instanceof ExternalModule &&
  12105. (options.format === 'umd' || options.format === 'iife') &&
  12106. getGlobalName(dep, options.globals, (imports || reexports) !== null, this.inputOptions.onwarn)),
  12107. id: undefined,
  12108. imports,
  12109. isChunk: dep instanceof Chunk,
  12110. name: dep.variableName,
  12111. namedExportsMode,
  12112. namespaceVariableName: dep.namespaceVariableName,
  12113. reexports
  12114. });
  12115. }
  12116. return dependencyDeclaration;
  12117. }
  12118. getChunkExportDeclarations(format) {
  12119. const exports = [];
  12120. for (const exportName of this.getExportNames()) {
  12121. if (exportName[0] === '*')
  12122. continue;
  12123. const variable = this.exportsByName[exportName];
  12124. if (!(variable instanceof SyntheticNamedExportVariable)) {
  12125. const module = variable.module;
  12126. if (module && this.chunkByModule.get(module) !== this)
  12127. continue;
  12128. }
  12129. let expression = null;
  12130. let hoisted = false;
  12131. let local = variable.getName();
  12132. if (variable instanceof LocalVariable) {
  12133. for (const declaration of variable.declarations) {
  12134. if (declaration.parent instanceof FunctionDeclaration ||
  12135. (declaration instanceof ExportDefaultDeclaration &&
  12136. declaration.declaration instanceof FunctionDeclaration)) {
  12137. hoisted = true;
  12138. break;
  12139. }
  12140. }
  12141. }
  12142. else if (variable instanceof SyntheticNamedExportVariable) {
  12143. expression = local;
  12144. if (format === 'es') {
  12145. local = variable.renderName;
  12146. }
  12147. }
  12148. exports.push({
  12149. exported: exportName,
  12150. expression,
  12151. hoisted,
  12152. local
  12153. });
  12154. }
  12155. return exports;
  12156. }
  12157. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  12158. const dependencies = new Set();
  12159. const deconflictedDefault = new Set();
  12160. const deconflictedNamespace = new Set();
  12161. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  12162. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  12163. const module = variable.module;
  12164. if (module instanceof ExternalModule) {
  12165. dependencies.add(module);
  12166. if (addNonNamespacesAndInteropHelpers) {
  12167. if (variable.name === 'default') {
  12168. if (defaultInteropHelpersByInteropType[String(interop(module.id))]) {
  12169. deconflictedDefault.add(module);
  12170. }
  12171. }
  12172. else if (variable.name === '*') {
  12173. if (namespaceInteropHelpersByInteropType[String(interop(module.id))]) {
  12174. deconflictedNamespace.add(module);
  12175. }
  12176. }
  12177. }
  12178. }
  12179. else {
  12180. const chunk = this.chunkByModule.get(module);
  12181. if (chunk !== this) {
  12182. dependencies.add(chunk);
  12183. if (addNonNamespacesAndInteropHelpers &&
  12184. chunk.exportMode === 'default' &&
  12185. variable.isNamespace) {
  12186. deconflictedNamespace.add(chunk);
  12187. }
  12188. }
  12189. }
  12190. }
  12191. }
  12192. if (addDependenciesWithoutBindings) {
  12193. for (const dependency of this.dependencies) {
  12194. dependencies.add(dependency);
  12195. }
  12196. }
  12197. return { deconflictedDefault, deconflictedNamespace, dependencies };
  12198. }
  12199. getFallbackChunkName() {
  12200. if (this.manualChunkAlias) {
  12201. return this.manualChunkAlias;
  12202. }
  12203. if (this.dynamicName) {
  12204. return this.dynamicName;
  12205. }
  12206. if (this.fileName) {
  12207. return getAliasName(this.fileName);
  12208. }
  12209. return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  12210. }
  12211. getImportSpecifiers() {
  12212. const { interop } = this.outputOptions;
  12213. const importsByDependency = new Map();
  12214. for (const variable of this.imports) {
  12215. const module = variable.module;
  12216. let dependency;
  12217. let imported;
  12218. if (module instanceof ExternalModule) {
  12219. dependency = module;
  12220. imported = variable.name;
  12221. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  12222. return error(errUnexpectedNamedImport(module.id, imported, false));
  12223. }
  12224. }
  12225. else {
  12226. dependency = this.chunkByModule.get(module);
  12227. imported = dependency.getVariableExportName(variable);
  12228. }
  12229. getOrCreate(importsByDependency, dependency, () => []).push({
  12230. imported,
  12231. local: variable.getName()
  12232. });
  12233. }
  12234. return importsByDependency;
  12235. }
  12236. getImportedBindingsPerDependency() {
  12237. const importSpecifiers = {};
  12238. for (const [dependency, declaration] of this.renderedDependencies) {
  12239. const specifiers = new Set();
  12240. if (declaration.imports) {
  12241. for (const { imported } of declaration.imports) {
  12242. specifiers.add(imported);
  12243. }
  12244. }
  12245. if (declaration.reexports) {
  12246. for (const { imported } of declaration.reexports) {
  12247. specifiers.add(imported);
  12248. }
  12249. }
  12250. importSpecifiers[dependency.id] = [...specifiers];
  12251. }
  12252. return importSpecifiers;
  12253. }
  12254. getReexportSpecifiers() {
  12255. const { externalLiveBindings, interop } = this.outputOptions;
  12256. const reexportSpecifiers = new Map();
  12257. for (let exportName of this.getExportNames()) {
  12258. let dependency;
  12259. let imported;
  12260. let needsLiveBinding = false;
  12261. if (exportName[0] === '*') {
  12262. const id = exportName.substr(1);
  12263. if (interop(id) === 'defaultOnly') {
  12264. this.inputOptions.onwarn(errUnexpectedNamespaceReexport(id));
  12265. }
  12266. needsLiveBinding = externalLiveBindings;
  12267. dependency = this.modulesById.get(id);
  12268. imported = exportName = '*';
  12269. }
  12270. else {
  12271. const variable = this.exportsByName[exportName];
  12272. if (variable instanceof SyntheticNamedExportVariable)
  12273. continue;
  12274. const module = variable.module;
  12275. if (module instanceof Module) {
  12276. dependency = this.chunkByModule.get(module);
  12277. if (dependency === this)
  12278. continue;
  12279. imported = dependency.getVariableExportName(variable);
  12280. needsLiveBinding = variable.isReassigned;
  12281. }
  12282. else {
  12283. dependency = module;
  12284. imported = variable.name;
  12285. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  12286. return error(errUnexpectedNamedImport(module.id, imported, true));
  12287. }
  12288. needsLiveBinding =
  12289. externalLiveBindings &&
  12290. (imported !== 'default' || isDefaultAProperty(String(interop(module.id)), true));
  12291. }
  12292. }
  12293. getOrCreate(reexportSpecifiers, dependency, () => []).push({
  12294. imported,
  12295. needsLiveBinding,
  12296. reexported: exportName
  12297. });
  12298. }
  12299. return reexportSpecifiers;
  12300. }
  12301. getReferencedFiles() {
  12302. const referencedFiles = [];
  12303. for (const module of this.orderedModules) {
  12304. for (const meta of module.importMetas) {
  12305. const fileName = meta.getReferencedFileName(this.pluginDriver);
  12306. if (fileName) {
  12307. referencedFiles.push(fileName);
  12308. }
  12309. }
  12310. }
  12311. return referencedFiles;
  12312. }
  12313. getRelativePath(targetPath, stripJsExtension) {
  12314. let relativePath = normalize(relative(dirname(this.id), targetPath));
  12315. if (stripJsExtension && relativePath.endsWith('.js')) {
  12316. relativePath = relativePath.slice(0, -3);
  12317. }
  12318. if (relativePath === '..')
  12319. return '../../' + basename(targetPath);
  12320. if (relativePath === '')
  12321. return '../' + basename(targetPath);
  12322. return relativePath.startsWith('../') ? relativePath : './' + relativePath;
  12323. }
  12324. inlineChunkDependencies(chunk) {
  12325. for (const dep of chunk.dependencies) {
  12326. if (this.dependencies.has(dep))
  12327. continue;
  12328. this.dependencies.add(dep);
  12329. if (dep instanceof Chunk) {
  12330. this.inlineChunkDependencies(dep);
  12331. }
  12332. }
  12333. }
  12334. prepareDynamicImportsAndImportMetas() {
  12335. var _a;
  12336. const accessedGlobalsByScope = this.accessedGlobalsByScope;
  12337. for (const module of this.orderedModules) {
  12338. for (const { node, resolution } of module.dynamicImports) {
  12339. if (node.included) {
  12340. if (resolution instanceof Module) {
  12341. const chunk = this.chunkByModule.get(resolution);
  12342. if (chunk === this) {
  12343. node.setInternalResolution(resolution.namespace);
  12344. }
  12345. else {
  12346. node.setExternalResolution(((_a = this.facadeChunkByModule.get(resolution)) === null || _a === void 0 ? void 0 : _a.exportMode) || chunk.exportMode, resolution, this.outputOptions, this.pluginDriver, accessedGlobalsByScope);
  12347. }
  12348. }
  12349. else {
  12350. node.setExternalResolution('external', resolution, this.outputOptions, this.pluginDriver, accessedGlobalsByScope);
  12351. }
  12352. }
  12353. }
  12354. for (const importMeta of module.importMetas) {
  12355. importMeta.addAccessedGlobals(this.outputOptions.format, accessedGlobalsByScope);
  12356. }
  12357. }
  12358. }
  12359. setExternalRenderPaths(options, inputBase) {
  12360. for (const dependency of [...this.dependencies, ...this.dynamicDependencies]) {
  12361. if (dependency instanceof ExternalModule) {
  12362. dependency.setRenderPath(options, inputBase);
  12363. }
  12364. }
  12365. }
  12366. setIdentifierRenderResolutions({ format, interop, namespaceToStringTag }) {
  12367. const syntheticExports = new Set();
  12368. for (const exportName of this.getExportNames()) {
  12369. const exportVariable = this.exportsByName[exportName];
  12370. if (exportVariable instanceof ExportShimVariable) {
  12371. this.needsExportsShim = true;
  12372. }
  12373. if (format !== 'es' &&
  12374. format !== 'system' &&
  12375. exportVariable.isReassigned &&
  12376. !exportVariable.isId) {
  12377. exportVariable.setRenderNames('exports', exportName);
  12378. }
  12379. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  12380. syntheticExports.add(exportVariable);
  12381. }
  12382. else {
  12383. exportVariable.setRenderNames(null, null);
  12384. }
  12385. }
  12386. const usedNames = new Set(['Object', 'Promise']);
  12387. if (this.needsExportsShim) {
  12388. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  12389. }
  12390. if (namespaceToStringTag) {
  12391. usedNames.add('Symbol');
  12392. }
  12393. switch (format) {
  12394. case 'system':
  12395. usedNames.add('module').add('exports');
  12396. break;
  12397. case 'es':
  12398. break;
  12399. case 'cjs':
  12400. usedNames.add('module').add('require').add('__filename').add('__dirname');
  12401. // fallthrough
  12402. default:
  12403. usedNames.add('exports');
  12404. for (const helper of HELPER_NAMES) {
  12405. usedNames.add(helper);
  12406. }
  12407. }
  12408. 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);
  12409. }
  12410. setUpChunkImportsAndExportsForModule(module) {
  12411. const moduleImports = new Set(module.imports);
  12412. // when we are not preserving modules, we need to make all namespace variables available for
  12413. // rendering the namespace object
  12414. if (!this.outputOptions.preserveModules) {
  12415. if (this.includedNamespaces.has(module)) {
  12416. const memberVariables = module.namespace.getMemberVariables();
  12417. for (const variable of Object.values(memberVariables)) {
  12418. moduleImports.add(variable);
  12419. }
  12420. }
  12421. }
  12422. for (let variable of moduleImports) {
  12423. if (variable instanceof ExportDefaultVariable) {
  12424. variable = variable.getOriginalVariable();
  12425. }
  12426. if (variable instanceof SyntheticNamedExportVariable) {
  12427. variable = variable.getBaseVariable();
  12428. }
  12429. const chunk = this.chunkByModule.get(variable.module);
  12430. if (chunk !== this) {
  12431. this.imports.add(variable);
  12432. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules) &&
  12433. variable.module instanceof Module) {
  12434. chunk.exports.add(variable);
  12435. this.checkCircularDependencyImport(variable, module);
  12436. }
  12437. }
  12438. }
  12439. if (this.includedNamespaces.has(module) ||
  12440. (module.info.isEntry && module.preserveSignature !== false) ||
  12441. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  12442. this.ensureReexportsAreAvailableForModule(module);
  12443. }
  12444. for (const { node, resolution } of module.dynamicImports) {
  12445. if (node.included &&
  12446. resolution instanceof Module &&
  12447. this.chunkByModule.get(resolution) === this &&
  12448. !this.includedNamespaces.has(resolution)) {
  12449. this.includedNamespaces.add(resolution);
  12450. this.ensureReexportsAreAvailableForModule(resolution);
  12451. }
  12452. }
  12453. }
  12454. }
  12455. function getChunkNameFromModule(module) {
  12456. return module.chunkName || getAliasName(module.id);
  12457. }
  12458. var BuildPhase;
  12459. (function (BuildPhase) {
  12460. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  12461. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  12462. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  12463. })(BuildPhase || (BuildPhase = {}));
  12464. function generateAssetFileName(name, source, outputOptions, bundle) {
  12465. const emittedName = outputOptions.sanitizeFileName(name || 'asset');
  12466. return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
  12467. ? outputOptions.assetFileNames({ name, source, type: 'asset' })
  12468. : outputOptions.assetFileNames, 'output.assetFileNames', {
  12469. ext: () => extname(emittedName).substr(1),
  12470. extname: () => extname(emittedName),
  12471. hash() {
  12472. const hash = createHash();
  12473. hash.update(emittedName);
  12474. hash.update(':');
  12475. hash.update(source);
  12476. return hash.digest('hex').substr(0, 8);
  12477. },
  12478. name: () => emittedName.substr(0, emittedName.length - extname(emittedName).length)
  12479. }), bundle);
  12480. }
  12481. function reserveFileNameInBundle(fileName, bundle, warn) {
  12482. if (fileName in bundle) {
  12483. warn(errFileNameConflict(fileName));
  12484. }
  12485. bundle[fileName] = FILE_PLACEHOLDER;
  12486. }
  12487. const FILE_PLACEHOLDER = {
  12488. type: 'placeholder'
  12489. };
  12490. function hasValidType(emittedFile) {
  12491. return Boolean(emittedFile &&
  12492. (emittedFile.type === 'asset' ||
  12493. emittedFile.type === 'chunk'));
  12494. }
  12495. function hasValidName(emittedFile) {
  12496. const validatedName = emittedFile.fileName || emittedFile.name;
  12497. return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
  12498. }
  12499. function getValidSource(source, emittedFile, fileReferenceId) {
  12500. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  12501. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  12502. 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.`));
  12503. }
  12504. return source;
  12505. }
  12506. function getAssetFileName(file, referenceId) {
  12507. if (typeof file.fileName !== 'string') {
  12508. return error(errAssetNotFinalisedForFileName(file.name || referenceId));
  12509. }
  12510. return file.fileName;
  12511. }
  12512. function getChunkFileName(file, facadeChunkByModule) {
  12513. var _a;
  12514. 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));
  12515. if (!fileName)
  12516. return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
  12517. return fileName;
  12518. }
  12519. class FileEmitter {
  12520. constructor(graph, options, baseFileEmitter) {
  12521. this.graph = graph;
  12522. this.options = options;
  12523. this.bundle = null;
  12524. this.facadeChunkByModule = null;
  12525. this.outputOptions = null;
  12526. this.assertAssetsFinalized = () => {
  12527. for (const [referenceId, emittedFile] of this.filesByReferenceId.entries()) {
  12528. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  12529. return error(errNoAssetSourceSet(emittedFile.name || referenceId));
  12530. }
  12531. };
  12532. this.emitFile = (emittedFile) => {
  12533. if (!hasValidType(emittedFile)) {
  12534. return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && emittedFile.type}".`));
  12535. }
  12536. if (!hasValidName(emittedFile)) {
  12537. return error(errFailedValidation(`The "fileName" or "name" properties of emitted files must be strings that are neither absolute nor relative paths, received "${emittedFile.fileName || emittedFile.name}".`));
  12538. }
  12539. if (emittedFile.type === 'chunk') {
  12540. return this.emitChunk(emittedFile);
  12541. }
  12542. else {
  12543. return this.emitAsset(emittedFile);
  12544. }
  12545. };
  12546. this.getFileName = (fileReferenceId) => {
  12547. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  12548. if (!emittedFile)
  12549. return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
  12550. if (emittedFile.type === 'chunk') {
  12551. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  12552. }
  12553. else {
  12554. return getAssetFileName(emittedFile, fileReferenceId);
  12555. }
  12556. };
  12557. this.setAssetSource = (referenceId, requestedSource) => {
  12558. const consumedFile = this.filesByReferenceId.get(referenceId);
  12559. if (!consumedFile)
  12560. return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
  12561. if (consumedFile.type !== 'asset') {
  12562. return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  12563. }
  12564. if (consumedFile.source !== undefined) {
  12565. return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
  12566. }
  12567. const source = getValidSource(requestedSource, consumedFile, referenceId);
  12568. if (this.bundle) {
  12569. this.finalizeAsset(consumedFile, source, referenceId, this.bundle);
  12570. }
  12571. else {
  12572. consumedFile.source = source;
  12573. }
  12574. };
  12575. this.setOutputBundle = (outputBundle, outputOptions, facadeChunkByModule) => {
  12576. this.outputOptions = outputOptions;
  12577. this.bundle = outputBundle;
  12578. this.facadeChunkByModule = facadeChunkByModule;
  12579. for (const emittedFile of this.filesByReferenceId.values()) {
  12580. if (emittedFile.fileName) {
  12581. reserveFileNameInBundle(emittedFile.fileName, this.bundle, this.options.onwarn);
  12582. }
  12583. }
  12584. for (const [referenceId, consumedFile] of this.filesByReferenceId.entries()) {
  12585. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  12586. this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.bundle);
  12587. }
  12588. }
  12589. };
  12590. this.filesByReferenceId = baseFileEmitter
  12591. ? new Map(baseFileEmitter.filesByReferenceId)
  12592. : new Map();
  12593. }
  12594. assignReferenceId(file, idBase) {
  12595. let referenceId;
  12596. do {
  12597. const hash = createHash();
  12598. if (referenceId) {
  12599. hash.update(referenceId);
  12600. }
  12601. else {
  12602. hash.update(idBase);
  12603. }
  12604. referenceId = hash.digest('hex').substr(0, 8);
  12605. } while (this.filesByReferenceId.has(referenceId));
  12606. this.filesByReferenceId.set(referenceId, file);
  12607. return referenceId;
  12608. }
  12609. emitAsset(emittedAsset) {
  12610. const source = typeof emittedAsset.source !== 'undefined'
  12611. ? getValidSource(emittedAsset.source, emittedAsset, null)
  12612. : undefined;
  12613. const consumedAsset = {
  12614. fileName: emittedAsset.fileName,
  12615. name: emittedAsset.name,
  12616. source,
  12617. type: 'asset'
  12618. };
  12619. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
  12620. if (this.bundle) {
  12621. if (emittedAsset.fileName) {
  12622. reserveFileNameInBundle(emittedAsset.fileName, this.bundle, this.options.onwarn);
  12623. }
  12624. if (source !== undefined) {
  12625. this.finalizeAsset(consumedAsset, source, referenceId, this.bundle);
  12626. }
  12627. }
  12628. return referenceId;
  12629. }
  12630. emitChunk(emittedChunk) {
  12631. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  12632. return error(errInvalidRollupPhaseForChunkEmission());
  12633. }
  12634. if (typeof emittedChunk.id !== 'string') {
  12635. return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  12636. }
  12637. const consumedChunk = {
  12638. fileName: emittedChunk.fileName,
  12639. module: null,
  12640. name: emittedChunk.name || emittedChunk.id,
  12641. type: 'chunk'
  12642. };
  12643. this.graph.moduleLoader
  12644. .emitChunk(emittedChunk)
  12645. .then(module => (consumedChunk.module = module))
  12646. .catch(() => {
  12647. // Avoid unhandled Promise rejection as the error will be thrown later
  12648. // once module loading has finished
  12649. });
  12650. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  12651. }
  12652. finalizeAsset(consumedFile, source, referenceId, bundle) {
  12653. const fileName = consumedFile.fileName ||
  12654. findExistingAssetFileNameWithSource(bundle, source) ||
  12655. generateAssetFileName(consumedFile.name, source, this.outputOptions, bundle);
  12656. // We must not modify the original assets to avoid interaction between outputs
  12657. const assetWithFileName = { ...consumedFile, fileName, source };
  12658. this.filesByReferenceId.set(referenceId, assetWithFileName);
  12659. const { options } = this;
  12660. bundle[fileName] = {
  12661. fileName,
  12662. get isAsset() {
  12663. warnDeprecation('Accessing "isAsset" on files in the bundle is deprecated, please use "type === \'asset\'" instead', true, options);
  12664. return true;
  12665. },
  12666. name: consumedFile.name,
  12667. source,
  12668. type: 'asset'
  12669. };
  12670. }
  12671. }
  12672. function findExistingAssetFileNameWithSource(bundle, source) {
  12673. for (const [fileName, outputFile] of Object.entries(bundle)) {
  12674. if (outputFile.type === 'asset' && areSourcesEqual(source, outputFile.source))
  12675. return fileName;
  12676. }
  12677. return null;
  12678. }
  12679. function areSourcesEqual(sourceA, sourceB) {
  12680. if (typeof sourceA === 'string') {
  12681. return sourceA === sourceB;
  12682. }
  12683. if (typeof sourceB === 'string') {
  12684. return false;
  12685. }
  12686. if ('equals' in sourceA) {
  12687. return sourceA.equals(sourceB);
  12688. }
  12689. if (sourceA.length !== sourceB.length) {
  12690. return false;
  12691. }
  12692. for (let index = 0; index < sourceA.length; index++) {
  12693. if (sourceA[index] !== sourceB[index]) {
  12694. return false;
  12695. }
  12696. }
  12697. return true;
  12698. }
  12699. const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
  12700. const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
  12701. async function createAddons(options, outputPluginDriver) {
  12702. try {
  12703. let [banner, footer, intro, outro] = await Promise.all([
  12704. outputPluginDriver.hookReduceValue('banner', options.banner(), [], concatSep),
  12705. outputPluginDriver.hookReduceValue('footer', options.footer(), [], concatSep),
  12706. outputPluginDriver.hookReduceValue('intro', options.intro(), [], concatDblSep),
  12707. outputPluginDriver.hookReduceValue('outro', options.outro(), [], concatDblSep)
  12708. ]);
  12709. if (intro)
  12710. intro += '\n\n';
  12711. if (outro)
  12712. outro = `\n\n${outro}`;
  12713. if (banner.length)
  12714. banner += '\n';
  12715. if (footer.length)
  12716. footer = '\n' + footer;
  12717. return { banner, footer, intro, outro };
  12718. }
  12719. catch (err) {
  12720. return error({
  12721. code: 'ADDON_ERROR',
  12722. message: `Could not retrieve ${err.hook}. Check configuration of plugin ${err.plugin}.
  12723. \tError Message: ${err.message}`
  12724. });
  12725. }
  12726. }
  12727. function getChunkAssignments(entryModules, manualChunkAliasByEntry) {
  12728. const chunkDefinitions = [];
  12729. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  12730. const manualChunkModulesByAlias = Object.create(null);
  12731. for (const [entry, alias] of manualChunkAliasByEntry) {
  12732. const chunkModules = (manualChunkModulesByAlias[alias] =
  12733. manualChunkModulesByAlias[alias] || []);
  12734. addStaticDependenciesToManualChunk(entry, chunkModules, modulesInManualChunks);
  12735. }
  12736. for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
  12737. chunkDefinitions.push({ alias, modules });
  12738. }
  12739. const assignedEntryPointsByModule = new Map();
  12740. const { dependentEntryPointsByModule, dynamicEntryModules } = analyzeModuleGraph(entryModules);
  12741. const dynamicallyDependentEntryPointsByDynamicEntry = getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules);
  12742. const staticEntries = new Set(entryModules);
  12743. function assignEntryToStaticDependencies(entry, dynamicDependentEntryPoints) {
  12744. const modulesToHandle = new Set([entry]);
  12745. for (const module of modulesToHandle) {
  12746. const assignedEntryPoints = getOrCreate(assignedEntryPointsByModule, module, () => new Set());
  12747. if (dynamicDependentEntryPoints &&
  12748. areEntryPointsContainedOrDynamicallyDependent(dynamicDependentEntryPoints, dependentEntryPointsByModule.get(module))) {
  12749. continue;
  12750. }
  12751. else {
  12752. assignedEntryPoints.add(entry);
  12753. }
  12754. for (const dependency of module.getDependenciesToBeIncluded()) {
  12755. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  12756. modulesToHandle.add(dependency);
  12757. }
  12758. }
  12759. }
  12760. }
  12761. function areEntryPointsContainedOrDynamicallyDependent(entryPoints, containedIn) {
  12762. const entriesToCheck = new Set(entryPoints);
  12763. for (const entry of entriesToCheck) {
  12764. if (!containedIn.has(entry)) {
  12765. if (staticEntries.has(entry))
  12766. return false;
  12767. const dynamicallyDependentEntryPoints = dynamicallyDependentEntryPointsByDynamicEntry.get(entry);
  12768. for (const dependentEntry of dynamicallyDependentEntryPoints) {
  12769. entriesToCheck.add(dependentEntry);
  12770. }
  12771. }
  12772. }
  12773. return true;
  12774. }
  12775. for (const entry of entryModules) {
  12776. if (!modulesInManualChunks.has(entry)) {
  12777. assignEntryToStaticDependencies(entry, null);
  12778. }
  12779. }
  12780. for (const entry of dynamicEntryModules) {
  12781. if (!modulesInManualChunks.has(entry)) {
  12782. assignEntryToStaticDependencies(entry, dynamicallyDependentEntryPointsByDynamicEntry.get(entry));
  12783. }
  12784. }
  12785. chunkDefinitions.push(...createChunks([...entryModules, ...dynamicEntryModules], assignedEntryPointsByModule));
  12786. return chunkDefinitions;
  12787. }
  12788. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  12789. const modulesToHandle = new Set([entry]);
  12790. for (const module of modulesToHandle) {
  12791. modulesInManualChunks.add(module);
  12792. manualChunkModules.push(module);
  12793. for (const dependency of module.dependencies) {
  12794. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  12795. modulesToHandle.add(dependency);
  12796. }
  12797. }
  12798. }
  12799. }
  12800. function analyzeModuleGraph(entryModules) {
  12801. const dynamicEntryModules = new Set();
  12802. const dependentEntryPointsByModule = new Map();
  12803. const entriesToHandle = new Set(entryModules);
  12804. for (const currentEntry of entriesToHandle) {
  12805. const modulesToHandle = new Set([currentEntry]);
  12806. for (const module of modulesToHandle) {
  12807. getOrCreate(dependentEntryPointsByModule, module, () => new Set()).add(currentEntry);
  12808. for (const dependency of module.getDependenciesToBeIncluded()) {
  12809. if (!(dependency instanceof ExternalModule)) {
  12810. modulesToHandle.add(dependency);
  12811. }
  12812. }
  12813. for (const { resolution } of module.dynamicImports) {
  12814. if (resolution instanceof Module && resolution.includedDynamicImporters.length > 0) {
  12815. dynamicEntryModules.add(resolution);
  12816. entriesToHandle.add(resolution);
  12817. }
  12818. }
  12819. for (const dependency of module.implicitlyLoadedBefore) {
  12820. dynamicEntryModules.add(dependency);
  12821. entriesToHandle.add(dependency);
  12822. }
  12823. }
  12824. }
  12825. return { dependentEntryPointsByModule, dynamicEntryModules };
  12826. }
  12827. function getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules) {
  12828. const dynamicallyDependentEntryPointsByDynamicEntry = new Map();
  12829. for (const dynamicEntry of dynamicEntryModules) {
  12830. const dynamicDependentEntryPoints = getOrCreate(dynamicallyDependentEntryPointsByDynamicEntry, dynamicEntry, () => new Set());
  12831. for (const importer of [
  12832. ...dynamicEntry.includedDynamicImporters,
  12833. ...dynamicEntry.implicitlyLoadedAfter
  12834. ]) {
  12835. for (const entryPoint of dependentEntryPointsByModule.get(importer)) {
  12836. dynamicDependentEntryPoints.add(entryPoint);
  12837. }
  12838. }
  12839. }
  12840. return dynamicallyDependentEntryPointsByDynamicEntry;
  12841. }
  12842. function createChunks(allEntryPoints, assignedEntryPointsByModule) {
  12843. const chunkModules = Object.create(null);
  12844. for (const [module, assignedEntryPoints] of assignedEntryPointsByModule) {
  12845. let chunkSignature = '';
  12846. for (const entry of allEntryPoints) {
  12847. chunkSignature += assignedEntryPoints.has(entry) ? 'X' : '_';
  12848. }
  12849. const chunk = chunkModules[chunkSignature];
  12850. if (chunk) {
  12851. chunk.push(module);
  12852. }
  12853. else {
  12854. chunkModules[chunkSignature] = [module];
  12855. }
  12856. }
  12857. return Object.values(chunkModules).map(modules => ({
  12858. alias: null,
  12859. modules
  12860. }));
  12861. }
  12862. // ported from https://github.com/substack/node-commondir
  12863. function commondir(files) {
  12864. if (files.length === 0)
  12865. return '/';
  12866. if (files.length === 1)
  12867. return dirname(files[0]);
  12868. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  12869. const pathSegements = file.split(/\/+|\\+/);
  12870. let i;
  12871. for (i = 0; commonSegments[i] === pathSegements[i] &&
  12872. i < Math.min(commonSegments.length, pathSegements.length); i++)
  12873. ;
  12874. return commonSegments.slice(0, i);
  12875. }, files[0].split(/\/+|\\+/));
  12876. // Windows correctly handles paths with forward-slashes
  12877. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  12878. }
  12879. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  12880. function sortByExecutionOrder(units) {
  12881. units.sort(compareExecIndex);
  12882. }
  12883. function analyseModuleExecution(entryModules) {
  12884. let nextExecIndex = 0;
  12885. const cyclePaths = [];
  12886. const analysedModules = new Set();
  12887. const dynamicImports = new Set();
  12888. const parents = new Map();
  12889. const orderedModules = [];
  12890. const analyseModule = (module) => {
  12891. if (module instanceof Module) {
  12892. for (const dependency of module.dependencies) {
  12893. if (parents.has(dependency)) {
  12894. if (!analysedModules.has(dependency)) {
  12895. cyclePaths.push(getCyclePath(dependency, module, parents));
  12896. }
  12897. continue;
  12898. }
  12899. parents.set(dependency, module);
  12900. analyseModule(dependency);
  12901. }
  12902. for (const dependency of module.implicitlyLoadedBefore) {
  12903. dynamicImports.add(dependency);
  12904. }
  12905. for (const { resolution } of module.dynamicImports) {
  12906. if (resolution instanceof Module) {
  12907. dynamicImports.add(resolution);
  12908. }
  12909. }
  12910. orderedModules.push(module);
  12911. }
  12912. module.execIndex = nextExecIndex++;
  12913. analysedModules.add(module);
  12914. };
  12915. for (const curEntry of entryModules) {
  12916. if (!parents.has(curEntry)) {
  12917. parents.set(curEntry, null);
  12918. analyseModule(curEntry);
  12919. }
  12920. }
  12921. for (const curEntry of dynamicImports) {
  12922. if (!parents.has(curEntry)) {
  12923. parents.set(curEntry, null);
  12924. analyseModule(curEntry);
  12925. }
  12926. }
  12927. return { cyclePaths, orderedModules };
  12928. }
  12929. function getCyclePath(module, parent, parents) {
  12930. const cycleSymbol = Symbol(module.id);
  12931. const path = [relativeId(module.id)];
  12932. let nextModule = parent;
  12933. module.cycles.add(cycleSymbol);
  12934. while (nextModule !== module) {
  12935. nextModule.cycles.add(cycleSymbol);
  12936. path.push(relativeId(nextModule.id));
  12937. nextModule = parents.get(nextModule);
  12938. }
  12939. path.push(path[0]);
  12940. path.reverse();
  12941. return path;
  12942. }
  12943. class Bundle {
  12944. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  12945. this.outputOptions = outputOptions;
  12946. this.unsetOptions = unsetOptions;
  12947. this.inputOptions = inputOptions;
  12948. this.pluginDriver = pluginDriver;
  12949. this.graph = graph;
  12950. this.facadeChunkByModule = new Map();
  12951. this.includedNamespaces = new Set();
  12952. }
  12953. async generate(isWrite) {
  12954. timeStart('GENERATE', 1);
  12955. const outputBundle = Object.create(null);
  12956. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions, this.facadeChunkByModule);
  12957. try {
  12958. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  12959. timeStart('generate chunks', 2);
  12960. const chunks = await this.generateChunks();
  12961. if (chunks.length > 1) {
  12962. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onwarn);
  12963. }
  12964. const inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
  12965. timeEnd('generate chunks', 2);
  12966. timeStart('render modules', 2);
  12967. // We need to create addons before prerender because at the moment, there
  12968. // can be no async code between prerender and render due to internal state
  12969. const addons = await createAddons(this.outputOptions, this.pluginDriver);
  12970. this.prerenderChunks(chunks, inputBase);
  12971. timeEnd('render modules', 2);
  12972. await this.addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle);
  12973. }
  12974. catch (error) {
  12975. await this.pluginDriver.hookParallel('renderError', [error]);
  12976. throw error;
  12977. }
  12978. await this.pluginDriver.hookSeq('generateBundle', [
  12979. this.outputOptions,
  12980. outputBundle,
  12981. isWrite
  12982. ]);
  12983. this.finaliseAssets(outputBundle);
  12984. timeEnd('GENERATE', 1);
  12985. return outputBundle;
  12986. }
  12987. async addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle) {
  12988. this.assignChunkIds(chunks, inputBase, addons, outputBundle);
  12989. for (const chunk of chunks) {
  12990. outputBundle[chunk.id] = chunk.getChunkInfoWithFileNames();
  12991. }
  12992. await Promise.all(chunks.map(async (chunk) => {
  12993. const outputChunk = outputBundle[chunk.id];
  12994. Object.assign(outputChunk, await chunk.render(this.outputOptions, addons, outputChunk));
  12995. }));
  12996. }
  12997. async addManualChunks(manualChunks) {
  12998. const manualChunkAliasByEntry = new Map();
  12999. const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
  13000. alias,
  13001. entries: await this.graph.moduleLoader.addAdditionalModules(files)
  13002. })));
  13003. for (const { alias, entries } of chunkEntries) {
  13004. for (const entry of entries) {
  13005. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  13006. }
  13007. }
  13008. return manualChunkAliasByEntry;
  13009. }
  13010. assignChunkIds(chunks, inputBase, addons, bundle) {
  13011. const entryChunks = [];
  13012. const otherChunks = [];
  13013. for (const chunk of chunks) {
  13014. (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
  13015. ? entryChunks
  13016. : otherChunks).push(chunk);
  13017. }
  13018. // make sure entry chunk names take precedence with regard to deconflicting
  13019. const chunksForNaming = entryChunks.concat(otherChunks);
  13020. for (const chunk of chunksForNaming) {
  13021. if (this.outputOptions.file) {
  13022. chunk.id = basename(this.outputOptions.file);
  13023. }
  13024. else if (this.outputOptions.preserveModules) {
  13025. chunk.id = chunk.generateIdPreserveModules(inputBase, this.outputOptions, bundle, this.unsetOptions);
  13026. }
  13027. else {
  13028. chunk.id = chunk.generateId(addons, this.outputOptions, bundle, true);
  13029. }
  13030. bundle[chunk.id] = FILE_PLACEHOLDER;
  13031. }
  13032. }
  13033. assignManualChunks(getManualChunk) {
  13034. const manualChunkAliasByEntry = new Map();
  13035. const manualChunksApi = {
  13036. getModuleIds: () => this.graph.modulesById.keys(),
  13037. getModuleInfo: this.graph.getModuleInfo
  13038. };
  13039. for (const module of this.graph.modulesById.values()) {
  13040. if (module instanceof Module) {
  13041. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  13042. if (typeof manualChunkAlias === 'string') {
  13043. addModuleToManualChunk(manualChunkAlias, module, manualChunkAliasByEntry);
  13044. }
  13045. }
  13046. }
  13047. return manualChunkAliasByEntry;
  13048. }
  13049. finaliseAssets(outputBundle) {
  13050. for (const file of Object.values(outputBundle)) {
  13051. if (!file.type) {
  13052. 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);
  13053. file.type = 'asset';
  13054. }
  13055. if (this.outputOptions.validate && typeof file.code == 'string') {
  13056. try {
  13057. this.graph.contextParse(file.code, {
  13058. allowHashBang: true,
  13059. ecmaVersion: 'latest'
  13060. });
  13061. }
  13062. catch (exception) {
  13063. this.inputOptions.onwarn(errChunkInvalid(file, exception));
  13064. }
  13065. }
  13066. }
  13067. this.pluginDriver.finaliseAssets();
  13068. }
  13069. async generateChunks() {
  13070. const { manualChunks } = this.outputOptions;
  13071. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  13072. ? await this.addManualChunks(manualChunks)
  13073. : this.assignManualChunks(manualChunks);
  13074. const chunks = [];
  13075. const chunkByModule = new Map();
  13076. for (const { alias, modules } of this.outputOptions.inlineDynamicImports
  13077. ? [{ alias: null, modules: getIncludedModules(this.graph.modulesById) }]
  13078. : this.outputOptions.preserveModules
  13079. ? getIncludedModules(this.graph.modulesById).map(module => ({
  13080. alias: null,
  13081. modules: [module]
  13082. }))
  13083. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry)) {
  13084. sortByExecutionOrder(modules);
  13085. const chunk = new Chunk(modules, this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.graph.modulesById, chunkByModule, this.facadeChunkByModule, this.includedNamespaces, alias);
  13086. chunks.push(chunk);
  13087. for (const module of modules) {
  13088. chunkByModule.set(module, chunk);
  13089. }
  13090. }
  13091. for (const chunk of chunks) {
  13092. chunk.link();
  13093. }
  13094. const facades = [];
  13095. for (const chunk of chunks) {
  13096. facades.push(...chunk.generateFacades());
  13097. }
  13098. return [...chunks, ...facades];
  13099. }
  13100. prerenderChunks(chunks, inputBase) {
  13101. for (const chunk of chunks) {
  13102. chunk.generateExports();
  13103. }
  13104. for (const chunk of chunks) {
  13105. chunk.preRender(this.outputOptions, inputBase);
  13106. }
  13107. }
  13108. }
  13109. function getAbsoluteEntryModulePaths(chunks) {
  13110. const absoluteEntryModulePaths = [];
  13111. for (const chunk of chunks) {
  13112. for (const entryModule of chunk.entryModules) {
  13113. if (isAbsolute(entryModule.id)) {
  13114. absoluteEntryModulePaths.push(entryModule.id);
  13115. }
  13116. }
  13117. }
  13118. return absoluteEntryModulePaths;
  13119. }
  13120. function validateOptionsForMultiChunkOutput(outputOptions, onWarn) {
  13121. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  13122. return error({
  13123. code: 'INVALID_OPTION',
  13124. message: 'UMD and IIFE output formats are not supported for code-splitting builds.'
  13125. });
  13126. if (typeof outputOptions.file === 'string')
  13127. return error({
  13128. code: 'INVALID_OPTION',
  13129. message: 'When building multiple chunks, the "output.dir" option must be used, not "output.file". ' +
  13130. 'To inline dynamic imports, set the "inlineDynamicImports" option.'
  13131. });
  13132. if (outputOptions.sourcemapFile)
  13133. return error({
  13134. code: 'INVALID_OPTION',
  13135. message: '"output.sourcemapFile" is only supported for single-file builds.'
  13136. });
  13137. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  13138. onWarn({
  13139. code: 'INVALID_OPTION',
  13140. message: '"output.amd.id" is only properly supported for single-file builds. Use "output.amd.autoId" and "output.amd.basePath".'
  13141. });
  13142. }
  13143. function getIncludedModules(modulesById) {
  13144. return [...modulesById.values()].filter(module => module instanceof Module &&
  13145. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0));
  13146. }
  13147. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  13148. const existingAlias = manualChunkAliasByEntry.get(module);
  13149. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  13150. return error(errCannotAssignModuleToChunk(module.id, alias, existingAlias));
  13151. }
  13152. manualChunkAliasByEntry.set(module, alias);
  13153. }
  13154. // Reserved word lists for various dialects of the language
  13155. var reservedWords = {
  13156. 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",
  13157. 5: "class enum extends super const export import",
  13158. 6: "enum",
  13159. strict: "implements interface let package private protected public static yield",
  13160. strictBind: "eval arguments"
  13161. };
  13162. // And the keywords
  13163. 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";
  13164. var keywords = {
  13165. 5: ecma5AndLessKeywords,
  13166. "5module": ecma5AndLessKeywords + " export import",
  13167. 6: ecma5AndLessKeywords + " const class extends export import super"
  13168. };
  13169. var keywordRelationalOperator = /^in(stanceof)?$/;
  13170. // ## Character categories
  13171. // Big ugly regular expressions that match characters in the
  13172. // whitespace, identifier, and identifier-start categories. These
  13173. // are only applied when a character is found to actually have a
  13174. // code point above 128.
  13175. // Generated by `bin/generate-identifier-regex.js`.
  13176. 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";
  13177. 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";
  13178. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  13179. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  13180. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  13181. // These are a run-length and offset encoded representation of the
  13182. // >0xffff code points that are a valid part of identifiers. The
  13183. // offset starts at 0x10000, and each pair of numbers represents an
  13184. // offset to the next range, and then a size of the range. They were
  13185. // generated by bin/generate-identifier-regex.js
  13186. // eslint-disable-next-line comma-spacing
  13187. 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];
  13188. // eslint-disable-next-line comma-spacing
  13189. 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];
  13190. // This has a complexity linear to the value of the code. The
  13191. // assumption is that looking up astral identifier characters is
  13192. // rare.
  13193. function isInAstralSet(code, set) {
  13194. var pos = 0x10000;
  13195. for (var i = 0; i < set.length; i += 2) {
  13196. pos += set[i];
  13197. if (pos > code) { return false }
  13198. pos += set[i + 1];
  13199. if (pos >= code) { return true }
  13200. }
  13201. }
  13202. // Test whether a given character code starts an identifier.
  13203. function isIdentifierStart(code, astral) {
  13204. if (code < 65) { return code === 36 }
  13205. if (code < 91) { return true }
  13206. if (code < 97) { return code === 95 }
  13207. if (code < 123) { return true }
  13208. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  13209. if (astral === false) { return false }
  13210. return isInAstralSet(code, astralIdentifierStartCodes)
  13211. }
  13212. // Test whether a given character is part of an identifier.
  13213. function isIdentifierChar(code, astral) {
  13214. if (code < 48) { return code === 36 }
  13215. if (code < 58) { return true }
  13216. if (code < 65) { return false }
  13217. if (code < 91) { return true }
  13218. if (code < 97) { return code === 95 }
  13219. if (code < 123) { return true }
  13220. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
  13221. if (astral === false) { return false }
  13222. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
  13223. }
  13224. // ## Token types
  13225. // The assignment of fine-grained, information-carrying type objects
  13226. // allows the tokenizer to store the information it has about a
  13227. // token in a way that is very cheap for the parser to look up.
  13228. // All token type variables start with an underscore, to make them
  13229. // easy to recognize.
  13230. // The `beforeExpr` property is used to disambiguate between regular
  13231. // expressions and divisions. It is set on all token types that can
  13232. // be followed by an expression (thus, a slash after them would be a
  13233. // regular expression).
  13234. //
  13235. // The `startsExpr` property is used to check if the token ends a
  13236. // `yield` expression. It is set on all token types that either can
  13237. // directly start an expression (like a quotation mark) or can
  13238. // continue an expression (like the body of a string).
  13239. //
  13240. // `isLoop` marks a keyword as starting a loop, which is important
  13241. // to know when parsing a label, in order to allow or disallow
  13242. // continue jumps to that label.
  13243. var TokenType = function TokenType(label, conf) {
  13244. if ( conf === void 0 ) conf = {};
  13245. this.label = label;
  13246. this.keyword = conf.keyword;
  13247. this.beforeExpr = !!conf.beforeExpr;
  13248. this.startsExpr = !!conf.startsExpr;
  13249. this.isLoop = !!conf.isLoop;
  13250. this.isAssign = !!conf.isAssign;
  13251. this.prefix = !!conf.prefix;
  13252. this.postfix = !!conf.postfix;
  13253. this.binop = conf.binop || null;
  13254. this.updateContext = null;
  13255. };
  13256. function binop(name, prec) {
  13257. return new TokenType(name, {beforeExpr: true, binop: prec})
  13258. }
  13259. var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
  13260. // Map keyword names to token types.
  13261. var keywords$1 = {};
  13262. // Succinct definitions of keyword token types
  13263. function kw(name, options) {
  13264. if ( options === void 0 ) options = {};
  13265. options.keyword = name;
  13266. return keywords$1[name] = new TokenType(name, options)
  13267. }
  13268. var types = {
  13269. num: new TokenType("num", startsExpr),
  13270. regexp: new TokenType("regexp", startsExpr),
  13271. string: new TokenType("string", startsExpr),
  13272. name: new TokenType("name", startsExpr),
  13273. privateId: new TokenType("privateId", startsExpr),
  13274. eof: new TokenType("eof"),
  13275. // Punctuation token types.
  13276. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
  13277. bracketR: new TokenType("]"),
  13278. braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
  13279. braceR: new TokenType("}"),
  13280. parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
  13281. parenR: new TokenType(")"),
  13282. comma: new TokenType(",", beforeExpr),
  13283. semi: new TokenType(";", beforeExpr),
  13284. colon: new TokenType(":", beforeExpr),
  13285. dot: new TokenType("."),
  13286. question: new TokenType("?", beforeExpr),
  13287. questionDot: new TokenType("?."),
  13288. arrow: new TokenType("=>", beforeExpr),
  13289. template: new TokenType("template"),
  13290. invalidTemplate: new TokenType("invalidTemplate"),
  13291. ellipsis: new TokenType("...", beforeExpr),
  13292. backQuote: new TokenType("`", startsExpr),
  13293. dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
  13294. // Operators. These carry several kinds of properties to help the
  13295. // parser use them properly (the presence of these properties is
  13296. // what categorizes them as operators).
  13297. //
  13298. // `binop`, when present, specifies that this operator is a binary
  13299. // operator, and will refer to its precedence.
  13300. //
  13301. // `prefix` and `postfix` mark the operator as a prefix or postfix
  13302. // unary operator.
  13303. //
  13304. // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  13305. // binary operators with a very low precedence, that should result
  13306. // in AssignmentExpression nodes.
  13307. eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
  13308. assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
  13309. incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  13310. prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  13311. logicalOR: binop("||", 1),
  13312. logicalAND: binop("&&", 2),
  13313. bitwiseOR: binop("|", 3),
  13314. bitwiseXOR: binop("^", 4),
  13315. bitwiseAND: binop("&", 5),
  13316. equality: binop("==/!=/===/!==", 6),
  13317. relational: binop("</>/<=/>=", 7),
  13318. bitShift: binop("<</>>/>>>", 8),
  13319. plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  13320. modulo: binop("%", 10),
  13321. star: binop("*", 10),
  13322. slash: binop("/", 10),
  13323. starstar: new TokenType("**", {beforeExpr: true}),
  13324. coalesce: binop("??", 1),
  13325. // Keyword token types.
  13326. _break: kw("break"),
  13327. _case: kw("case", beforeExpr),
  13328. _catch: kw("catch"),
  13329. _continue: kw("continue"),
  13330. _debugger: kw("debugger"),
  13331. _default: kw("default", beforeExpr),
  13332. _do: kw("do", {isLoop: true, beforeExpr: true}),
  13333. _else: kw("else", beforeExpr),
  13334. _finally: kw("finally"),
  13335. _for: kw("for", {isLoop: true}),
  13336. _function: kw("function", startsExpr),
  13337. _if: kw("if"),
  13338. _return: kw("return", beforeExpr),
  13339. _switch: kw("switch"),
  13340. _throw: kw("throw", beforeExpr),
  13341. _try: kw("try"),
  13342. _var: kw("var"),
  13343. _const: kw("const"),
  13344. _while: kw("while", {isLoop: true}),
  13345. _with: kw("with"),
  13346. _new: kw("new", {beforeExpr: true, startsExpr: true}),
  13347. _this: kw("this", startsExpr),
  13348. _super: kw("super", startsExpr),
  13349. _class: kw("class", startsExpr),
  13350. _extends: kw("extends", beforeExpr),
  13351. _export: kw("export"),
  13352. _import: kw("import", startsExpr),
  13353. _null: kw("null", startsExpr),
  13354. _true: kw("true", startsExpr),
  13355. _false: kw("false", startsExpr),
  13356. _in: kw("in", {beforeExpr: true, binop: 7}),
  13357. _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
  13358. _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  13359. _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  13360. _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
  13361. };
  13362. // Matches a whole line break (where CRLF is considered a single
  13363. // line break). Used to count lines.
  13364. var lineBreak = /\r\n?|\n|\u2028|\u2029/;
  13365. var lineBreakG = new RegExp(lineBreak.source, "g");
  13366. function isNewLine(code, ecma2019String) {
  13367. return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029))
  13368. }
  13369. var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  13370. var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  13371. var ref = Object.prototype;
  13372. var hasOwnProperty = ref.hasOwnProperty;
  13373. var toString = ref.toString;
  13374. // Checks if an object has a property.
  13375. function has(obj, propName) {
  13376. return hasOwnProperty.call(obj, propName)
  13377. }
  13378. var isArray = Array.isArray || (function (obj) { return (
  13379. toString.call(obj) === "[object Array]"
  13380. ); });
  13381. function wordsRegexp(words) {
  13382. return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
  13383. }
  13384. // These are used when `options.locations` is on, for the
  13385. // `startLoc` and `endLoc` properties.
  13386. var Position = function Position(line, col) {
  13387. this.line = line;
  13388. this.column = col;
  13389. };
  13390. Position.prototype.offset = function offset (n) {
  13391. return new Position(this.line, this.column + n)
  13392. };
  13393. var SourceLocation = function SourceLocation(p, start, end) {
  13394. this.start = start;
  13395. this.end = end;
  13396. if (p.sourceFile !== null) { this.source = p.sourceFile; }
  13397. };
  13398. // The `getLineInfo` function is mostly useful when the
  13399. // `locations` option is off (for performance reasons) and you
  13400. // want to find the line/column position for a given character
  13401. // offset. `input` should be the code string that the offset refers
  13402. // into.
  13403. function getLineInfo(input, offset) {
  13404. for (var line = 1, cur = 0;;) {
  13405. lineBreakG.lastIndex = cur;
  13406. var match = lineBreakG.exec(input);
  13407. if (match && match.index < offset) {
  13408. ++line;
  13409. cur = match.index + match[0].length;
  13410. } else {
  13411. return new Position(line, offset - cur)
  13412. }
  13413. }
  13414. }
  13415. // A second argument must be given to configure the parser process.
  13416. // These options are recognized (only `ecmaVersion` is required):
  13417. var defaultOptions = {
  13418. // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  13419. // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
  13420. // (2019), 11 (2020), 12 (2021), 13 (2022), or `"latest"` (the
  13421. // latest version the library supports). This influences support
  13422. // for strict mode, the set of reserved words, and support for
  13423. // new syntax features.
  13424. ecmaVersion: null,
  13425. // `sourceType` indicates the mode the code should be parsed in.
  13426. // Can be either `"script"` or `"module"`. This influences global
  13427. // strict mode and parsing of `import` and `export` declarations.
  13428. sourceType: "script",
  13429. // `onInsertedSemicolon` can be a callback that will be called
  13430. // when a semicolon is automatically inserted. It will be passed
  13431. // the position of the comma as an offset, and if `locations` is
  13432. // enabled, it is given the location as a `{line, column}` object
  13433. // as second argument.
  13434. onInsertedSemicolon: null,
  13435. // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  13436. // trailing commas.
  13437. onTrailingComma: null,
  13438. // By default, reserved words are only enforced if ecmaVersion >= 5.
  13439. // Set `allowReserved` to a boolean value to explicitly turn this on
  13440. // an off. When this option has the value "never", reserved words
  13441. // and keywords can also not be used as property names.
  13442. allowReserved: null,
  13443. // When enabled, a return at the top level is not considered an
  13444. // error.
  13445. allowReturnOutsideFunction: false,
  13446. // When enabled, import/export statements are not constrained to
  13447. // appearing at the top of the program, and an import.meta expression
  13448. // in a script isn't considered an error.
  13449. allowImportExportEverywhere: false,
  13450. // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
  13451. // When enabled, await identifiers are allowed to appear at the top-level scope,
  13452. // but they are still not allowed in non-async functions.
  13453. allowAwaitOutsideFunction: null,
  13454. // When enabled, super identifiers are not constrained to
  13455. // appearing in methods and do not raise an error when they appear elsewhere.
  13456. allowSuperOutsideMethod: null,
  13457. // When enabled, hashbang directive in the beginning of file
  13458. // is allowed and treated as a line comment.
  13459. allowHashBang: false,
  13460. // When `locations` is on, `loc` properties holding objects with
  13461. // `start` and `end` properties in `{line, column}` form (with
  13462. // line being 1-based and column 0-based) will be attached to the
  13463. // nodes.
  13464. locations: false,
  13465. // A function can be passed as `onToken` option, which will
  13466. // cause Acorn to call that function with object in the same
  13467. // format as tokens returned from `tokenizer().getToken()`. Note
  13468. // that you are not allowed to call the parser from the
  13469. // callback—that will corrupt its internal state.
  13470. onToken: null,
  13471. // A function can be passed as `onComment` option, which will
  13472. // cause Acorn to call that function with `(block, text, start,
  13473. // end)` parameters whenever a comment is skipped. `block` is a
  13474. // boolean indicating whether this is a block (`/* */`) comment,
  13475. // `text` is the content of the comment, and `start` and `end` are
  13476. // character offsets that denote the start and end of the comment.
  13477. // When the `locations` option is on, two more parameters are
  13478. // passed, the full `{line, column}` locations of the start and
  13479. // end of the comments. Note that you are not allowed to call the
  13480. // parser from the callback—that will corrupt its internal state.
  13481. onComment: null,
  13482. // Nodes have their start and end characters offsets recorded in
  13483. // `start` and `end` properties (directly on the node, rather than
  13484. // the `loc` object, which holds line/column data. To also add a
  13485. // [semi-standardized][range] `range` property holding a `[start,
  13486. // end]` array with the same numbers, set the `ranges` option to
  13487. // `true`.
  13488. //
  13489. // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  13490. ranges: false,
  13491. // It is possible to parse multiple files into a single AST by
  13492. // passing the tree produced by parsing the first file as
  13493. // `program` option in subsequent parses. This will add the
  13494. // toplevel forms of the parsed file to the `Program` (top) node
  13495. // of an existing parse tree.
  13496. program: null,
  13497. // When `locations` is on, you can pass this to record the source
  13498. // file in every node's `loc` object.
  13499. sourceFile: null,
  13500. // This value, if given, is stored in every node, whether
  13501. // `locations` is on or off.
  13502. directSourceFile: null,
  13503. // When enabled, parenthesized expressions are represented by
  13504. // (non-standard) ParenthesizedExpression nodes
  13505. preserveParens: false
  13506. };
  13507. // Interpret and default an options object
  13508. var warnedAboutEcmaVersion = false;
  13509. function getOptions(opts) {
  13510. var options = {};
  13511. for (var opt in defaultOptions)
  13512. { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }
  13513. if (options.ecmaVersion === "latest") {
  13514. options.ecmaVersion = 1e8;
  13515. } else if (options.ecmaVersion == null) {
  13516. if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
  13517. warnedAboutEcmaVersion = true;
  13518. console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
  13519. }
  13520. options.ecmaVersion = 11;
  13521. } else if (options.ecmaVersion >= 2015) {
  13522. options.ecmaVersion -= 2009;
  13523. }
  13524. if (options.allowReserved == null)
  13525. { options.allowReserved = options.ecmaVersion < 5; }
  13526. if (options.allowAwaitOutsideFunction == null)
  13527. { options.allowAwaitOutsideFunction = options.ecmaVersion >= 13; }
  13528. if (isArray(options.onToken)) {
  13529. var tokens = options.onToken;
  13530. options.onToken = function (token) { return tokens.push(token); };
  13531. }
  13532. if (isArray(options.onComment))
  13533. { options.onComment = pushComment(options, options.onComment); }
  13534. return options
  13535. }
  13536. function pushComment(options, array) {
  13537. return function(block, text, start, end, startLoc, endLoc) {
  13538. var comment = {
  13539. type: block ? "Block" : "Line",
  13540. value: text,
  13541. start: start,
  13542. end: end
  13543. };
  13544. if (options.locations)
  13545. { comment.loc = new SourceLocation(this, startLoc, endLoc); }
  13546. if (options.ranges)
  13547. { comment.range = [start, end]; }
  13548. array.push(comment);
  13549. }
  13550. }
  13551. // Each scope gets a bitset that may contain these flags
  13552. var
  13553. SCOPE_TOP = 1,
  13554. SCOPE_FUNCTION = 2,
  13555. SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION,
  13556. SCOPE_ASYNC = 4,
  13557. SCOPE_GENERATOR = 8,
  13558. SCOPE_ARROW = 16,
  13559. SCOPE_SIMPLE_CATCH = 32,
  13560. SCOPE_SUPER = 64,
  13561. SCOPE_DIRECT_SUPER = 128;
  13562. function functionFlags(async, generator) {
  13563. return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
  13564. }
  13565. // Used in checkLVal* and declareName to determine the type of a binding
  13566. var
  13567. BIND_NONE = 0, // Not a binding
  13568. BIND_VAR = 1, // Var-style binding
  13569. BIND_LEXICAL = 2, // Let- or const-style binding
  13570. BIND_FUNCTION = 3, // Function declaration
  13571. BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
  13572. BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
  13573. var Parser = function Parser(options, input, startPos) {
  13574. this.options = options = getOptions(options);
  13575. this.sourceFile = options.sourceFile;
  13576. this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  13577. var reserved = "";
  13578. if (options.allowReserved !== true) {
  13579. reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
  13580. if (options.sourceType === "module") { reserved += " await"; }
  13581. }
  13582. this.reservedWords = wordsRegexp(reserved);
  13583. var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  13584. this.reservedWordsStrict = wordsRegexp(reservedStrict);
  13585. this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
  13586. this.input = String(input);
  13587. // Used to signal to callers of `readWord1` whether the word
  13588. // contained any escape sequences. This is needed because words with
  13589. // escape sequences must not be interpreted as keywords.
  13590. this.containsEsc = false;
  13591. // Set up token state
  13592. // The current position of the tokenizer in the input.
  13593. if (startPos) {
  13594. this.pos = startPos;
  13595. this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
  13596. this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  13597. } else {
  13598. this.pos = this.lineStart = 0;
  13599. this.curLine = 1;
  13600. }
  13601. // Properties of the current token:
  13602. // Its type
  13603. this.type = types.eof;
  13604. // For tokens that include more information than their type, the value
  13605. this.value = null;
  13606. // Its start and end offset
  13607. this.start = this.end = this.pos;
  13608. // And, if locations are used, the {line, column} object
  13609. // corresponding to those offsets
  13610. this.startLoc = this.endLoc = this.curPosition();
  13611. // Position information for the previous token
  13612. this.lastTokEndLoc = this.lastTokStartLoc = null;
  13613. this.lastTokStart = this.lastTokEnd = this.pos;
  13614. // The context stack is used to superficially track syntactic
  13615. // context to predict whether a regular expression is allowed in a
  13616. // given position.
  13617. this.context = this.initialContext();
  13618. this.exprAllowed = true;
  13619. // Figure out if it's a module code.
  13620. this.inModule = options.sourceType === "module";
  13621. this.strict = this.inModule || this.strictDirective(this.pos);
  13622. // Used to signify the start of a potential arrow function
  13623. this.potentialArrowAt = -1;
  13624. this.potentialArrowInForAwait = false;
  13625. // Positions to delayed-check that yield/await does not exist in default parameters.
  13626. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  13627. // Labels in scope.
  13628. this.labels = [];
  13629. // Thus-far undefined exports.
  13630. this.undefinedExports = Object.create(null);
  13631. // If enabled, skip leading hashbang line.
  13632. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
  13633. { this.skipLineComment(2); }
  13634. // Scope tracking for duplicate variable names (see scope.js)
  13635. this.scopeStack = [];
  13636. this.enterScope(SCOPE_TOP);
  13637. // For RegExp validation
  13638. this.regexpState = null;
  13639. // The stack of private names.
  13640. // Each element has two properties: 'declared' and 'used'.
  13641. // When it exited from the outermost class definition, all used private names must be declared.
  13642. this.privateNameStack = [];
  13643. };
  13644. var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },inNonArrowFunction: { configurable: true } };
  13645. Parser.prototype.parse = function parse () {
  13646. var node = this.options.program || this.startNode();
  13647. this.nextToken();
  13648. return this.parseTopLevel(node)
  13649. };
  13650. prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
  13651. prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
  13652. prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
  13653. prototypeAccessors.allowSuper.get = function () {
  13654. var ref = this.currentThisScope();
  13655. var flags = ref.flags;
  13656. var inClassFieldInit = ref.inClassFieldInit;
  13657. return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
  13658. };
  13659. prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
  13660. prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
  13661. prototypeAccessors.inNonArrowFunction.get = function () {
  13662. var ref = this.currentThisScope();
  13663. var flags = ref.flags;
  13664. var inClassFieldInit = ref.inClassFieldInit;
  13665. return (flags & SCOPE_FUNCTION) > 0 || inClassFieldInit
  13666. };
  13667. Parser.extend = function extend () {
  13668. var plugins = [], len = arguments.length;
  13669. while ( len-- ) plugins[ len ] = arguments[ len ];
  13670. var cls = this;
  13671. for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
  13672. return cls
  13673. };
  13674. Parser.parse = function parse (input, options) {
  13675. return new this(options, input).parse()
  13676. };
  13677. Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
  13678. var parser = new this(options, input, pos);
  13679. parser.nextToken();
  13680. return parser.parseExpression()
  13681. };
  13682. Parser.tokenizer = function tokenizer (input, options) {
  13683. return new this(options, input)
  13684. };
  13685. Object.defineProperties( Parser.prototype, prototypeAccessors );
  13686. var pp = Parser.prototype;
  13687. // ## Parser utilities
  13688. var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
  13689. pp.strictDirective = function(start) {
  13690. for (;;) {
  13691. // Try to find string literal.
  13692. skipWhiteSpace.lastIndex = start;
  13693. start += skipWhiteSpace.exec(this.input)[0].length;
  13694. var match = literal.exec(this.input.slice(start));
  13695. if (!match) { return false }
  13696. if ((match[1] || match[2]) === "use strict") {
  13697. skipWhiteSpace.lastIndex = start + match[0].length;
  13698. var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
  13699. var next = this.input.charAt(end);
  13700. return next === ";" || next === "}" ||
  13701. (lineBreak.test(spaceAfter[0]) &&
  13702. !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
  13703. }
  13704. start += match[0].length;
  13705. // Skip semicolon, if any.
  13706. skipWhiteSpace.lastIndex = start;
  13707. start += skipWhiteSpace.exec(this.input)[0].length;
  13708. if (this.input[start] === ";")
  13709. { start++; }
  13710. }
  13711. };
  13712. // Predicate that tests whether the next token is of the given
  13713. // type, and if yes, consumes it as a side effect.
  13714. pp.eat = function(type) {
  13715. if (this.type === type) {
  13716. this.next();
  13717. return true
  13718. } else {
  13719. return false
  13720. }
  13721. };
  13722. // Tests whether parsed token is a contextual keyword.
  13723. pp.isContextual = function(name) {
  13724. return this.type === types.name && this.value === name && !this.containsEsc
  13725. };
  13726. // Consumes contextual keyword if possible.
  13727. pp.eatContextual = function(name) {
  13728. if (!this.isContextual(name)) { return false }
  13729. this.next();
  13730. return true
  13731. };
  13732. // Asserts that following token is given contextual keyword.
  13733. pp.expectContextual = function(name) {
  13734. if (!this.eatContextual(name)) { this.unexpected(); }
  13735. };
  13736. // Test whether a semicolon can be inserted at the current position.
  13737. pp.canInsertSemicolon = function() {
  13738. return this.type === types.eof ||
  13739. this.type === types.braceR ||
  13740. lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  13741. };
  13742. pp.insertSemicolon = function() {
  13743. if (this.canInsertSemicolon()) {
  13744. if (this.options.onInsertedSemicolon)
  13745. { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
  13746. return true
  13747. }
  13748. };
  13749. // Consume a semicolon, or, failing that, see if we are allowed to
  13750. // pretend that there is a semicolon at this position.
  13751. pp.semicolon = function() {
  13752. if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); }
  13753. };
  13754. pp.afterTrailingComma = function(tokType, notNext) {
  13755. if (this.type === tokType) {
  13756. if (this.options.onTrailingComma)
  13757. { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
  13758. if (!notNext)
  13759. { this.next(); }
  13760. return true
  13761. }
  13762. };
  13763. // Expect a token of a given type. If found, consume it, otherwise,
  13764. // raise an unexpected token error.
  13765. pp.expect = function(type) {
  13766. this.eat(type) || this.unexpected();
  13767. };
  13768. // Raise an unexpected token error.
  13769. pp.unexpected = function(pos) {
  13770. this.raise(pos != null ? pos : this.start, "Unexpected token");
  13771. };
  13772. function DestructuringErrors() {
  13773. this.shorthandAssign =
  13774. this.trailingComma =
  13775. this.parenthesizedAssign =
  13776. this.parenthesizedBind =
  13777. this.doubleProto =
  13778. -1;
  13779. }
  13780. pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  13781. if (!refDestructuringErrors) { return }
  13782. if (refDestructuringErrors.trailingComma > -1)
  13783. { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
  13784. var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  13785. if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
  13786. };
  13787. pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  13788. if (!refDestructuringErrors) { return false }
  13789. var shorthandAssign = refDestructuringErrors.shorthandAssign;
  13790. var doubleProto = refDestructuringErrors.doubleProto;
  13791. if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
  13792. if (shorthandAssign >= 0)
  13793. { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
  13794. if (doubleProto >= 0)
  13795. { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
  13796. };
  13797. pp.checkYieldAwaitInDefaultParams = function() {
  13798. if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
  13799. { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
  13800. if (this.awaitPos)
  13801. { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
  13802. };
  13803. pp.isSimpleAssignTarget = function(expr) {
  13804. if (expr.type === "ParenthesizedExpression")
  13805. { return this.isSimpleAssignTarget(expr.expression) }
  13806. return expr.type === "Identifier" || expr.type === "MemberExpression"
  13807. };
  13808. var pp$1 = Parser.prototype;
  13809. // ### Statement parsing
  13810. // Parse a program. Initializes the parser, reads any number of
  13811. // statements, and wraps them in a Program node. Optionally takes a
  13812. // `program` argument. If present, the statements will be appended
  13813. // to its body instead of creating a new node.
  13814. pp$1.parseTopLevel = function(node) {
  13815. var exports = Object.create(null);
  13816. if (!node.body) { node.body = []; }
  13817. while (this.type !== types.eof) {
  13818. var stmt = this.parseStatement(null, true, exports);
  13819. node.body.push(stmt);
  13820. }
  13821. if (this.inModule)
  13822. { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
  13823. {
  13824. var name = list[i];
  13825. this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
  13826. } }
  13827. this.adaptDirectivePrologue(node.body);
  13828. this.next();
  13829. node.sourceType = this.options.sourceType;
  13830. return this.finishNode(node, "Program")
  13831. };
  13832. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  13833. pp$1.isLet = function(context) {
  13834. if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
  13835. skipWhiteSpace.lastIndex = this.pos;
  13836. var skip = skipWhiteSpace.exec(this.input);
  13837. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  13838. // For ambiguous cases, determine if a LexicalDeclaration (or only a
  13839. // Statement) is allowed here. If context is not empty then only a Statement
  13840. // is allowed. However, `let [` is an explicit negative lookahead for
  13841. // ExpressionStatement, so special-case it first.
  13842. if (nextCh === 91 || nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral
  13843. if (context) { return false }
  13844. if (nextCh === 123) { return true } // '{'
  13845. if (isIdentifierStart(nextCh, true)) {
  13846. var pos = next + 1;
  13847. while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
  13848. if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
  13849. var ident = this.input.slice(next, pos);
  13850. if (!keywordRelationalOperator.test(ident)) { return true }
  13851. }
  13852. return false
  13853. };
  13854. // check 'async [no LineTerminator here] function'
  13855. // - 'async /*foo*/ function' is OK.
  13856. // - 'async /*\n*/ function' is invalid.
  13857. pp$1.isAsyncFunction = function() {
  13858. if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
  13859. { return false }
  13860. skipWhiteSpace.lastIndex = this.pos;
  13861. var skip = skipWhiteSpace.exec(this.input);
  13862. var next = this.pos + skip[0].length, after;
  13863. return !lineBreak.test(this.input.slice(this.pos, next)) &&
  13864. this.input.slice(next, next + 8) === "function" &&
  13865. (next + 8 === this.input.length ||
  13866. !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
  13867. };
  13868. // Parse a single statement.
  13869. //
  13870. // If expecting a statement and finding a slash operator, parse a
  13871. // regular expression literal. This is to handle cases like
  13872. // `if (foo) /blah/.exec(foo)`, where looking at the previous token
  13873. // does not help.
  13874. pp$1.parseStatement = function(context, topLevel, exports) {
  13875. var starttype = this.type, node = this.startNode(), kind;
  13876. if (this.isLet(context)) {
  13877. starttype = types._var;
  13878. kind = "let";
  13879. }
  13880. // Most types of statements are recognized by the keyword they
  13881. // start with. Many are trivial to parse, some require a bit of
  13882. // complexity.
  13883. switch (starttype) {
  13884. case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  13885. case types._debugger: return this.parseDebuggerStatement(node)
  13886. case types._do: return this.parseDoStatement(node)
  13887. case types._for: return this.parseForStatement(node)
  13888. case types._function:
  13889. // Function as sole body of either an if statement or a labeled statement
  13890. // works, but not when it is part of a labeled statement that is the sole
  13891. // body of an if statement.
  13892. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
  13893. return this.parseFunctionStatement(node, false, !context)
  13894. case types._class:
  13895. if (context) { this.unexpected(); }
  13896. return this.parseClass(node, true)
  13897. case types._if: return this.parseIfStatement(node)
  13898. case types._return: return this.parseReturnStatement(node)
  13899. case types._switch: return this.parseSwitchStatement(node)
  13900. case types._throw: return this.parseThrowStatement(node)
  13901. case types._try: return this.parseTryStatement(node)
  13902. case types._const: case types._var:
  13903. kind = kind || this.value;
  13904. if (context && kind !== "var") { this.unexpected(); }
  13905. return this.parseVarStatement(node, kind)
  13906. case types._while: return this.parseWhileStatement(node)
  13907. case types._with: return this.parseWithStatement(node)
  13908. case types.braceL: return this.parseBlock(true, node)
  13909. case types.semi: return this.parseEmptyStatement(node)
  13910. case types._export:
  13911. case types._import:
  13912. if (this.options.ecmaVersion > 10 && starttype === types._import) {
  13913. skipWhiteSpace.lastIndex = this.pos;
  13914. var skip = skipWhiteSpace.exec(this.input);
  13915. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  13916. if (nextCh === 40 || nextCh === 46) // '(' or '.'
  13917. { return this.parseExpressionStatement(node, this.parseExpression()) }
  13918. }
  13919. if (!this.options.allowImportExportEverywhere) {
  13920. if (!topLevel)
  13921. { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
  13922. if (!this.inModule)
  13923. { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
  13924. }
  13925. return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports)
  13926. // If the statement does not start with a statement keyword or a
  13927. // brace, it's an ExpressionStatement or LabeledStatement. We
  13928. // simply start parsing an expression, and afterwards, if the
  13929. // next token is a colon and the expression was a simple
  13930. // Identifier node, we switch to interpreting it as a label.
  13931. default:
  13932. if (this.isAsyncFunction()) {
  13933. if (context) { this.unexpected(); }
  13934. this.next();
  13935. return this.parseFunctionStatement(node, true, !context)
  13936. }
  13937. var maybeName = this.value, expr = this.parseExpression();
  13938. if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon))
  13939. { return this.parseLabeledStatement(node, maybeName, expr, context) }
  13940. else { return this.parseExpressionStatement(node, expr) }
  13941. }
  13942. };
  13943. pp$1.parseBreakContinueStatement = function(node, keyword) {
  13944. var isBreak = keyword === "break";
  13945. this.next();
  13946. if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; }
  13947. else if (this.type !== types.name) { this.unexpected(); }
  13948. else {
  13949. node.label = this.parseIdent();
  13950. this.semicolon();
  13951. }
  13952. // Verify that there is an actual destination to break or
  13953. // continue to.
  13954. var i = 0;
  13955. for (; i < this.labels.length; ++i) {
  13956. var lab = this.labels[i];
  13957. if (node.label == null || lab.name === node.label.name) {
  13958. if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
  13959. if (node.label && isBreak) { break }
  13960. }
  13961. }
  13962. if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
  13963. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
  13964. };
  13965. pp$1.parseDebuggerStatement = function(node) {
  13966. this.next();
  13967. this.semicolon();
  13968. return this.finishNode(node, "DebuggerStatement")
  13969. };
  13970. pp$1.parseDoStatement = function(node) {
  13971. this.next();
  13972. this.labels.push(loopLabel);
  13973. node.body = this.parseStatement("do");
  13974. this.labels.pop();
  13975. this.expect(types._while);
  13976. node.test = this.parseParenExpression();
  13977. if (this.options.ecmaVersion >= 6)
  13978. { this.eat(types.semi); }
  13979. else
  13980. { this.semicolon(); }
  13981. return this.finishNode(node, "DoWhileStatement")
  13982. };
  13983. // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
  13984. // loop is non-trivial. Basically, we have to parse the init `var`
  13985. // statement or expression, disallowing the `in` operator (see
  13986. // the second parameter to `parseExpression`), and then check
  13987. // whether the next token is `in` or `of`. When there is no init
  13988. // part (semicolon immediately after the opening parenthesis), it
  13989. // is a regular `for` loop.
  13990. pp$1.parseForStatement = function(node) {
  13991. this.next();
  13992. var awaitAt = (this.options.ecmaVersion >= 9 && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction)) && this.eatContextual("await")) ? this.lastTokStart : -1;
  13993. this.labels.push(loopLabel);
  13994. this.enterScope(0);
  13995. this.expect(types.parenL);
  13996. if (this.type === types.semi) {
  13997. if (awaitAt > -1) { this.unexpected(awaitAt); }
  13998. return this.parseFor(node, null)
  13999. }
  14000. var isLet = this.isLet();
  14001. if (this.type === types._var || this.type === types._const || isLet) {
  14002. var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
  14003. this.next();
  14004. this.parseVar(init$1, true, kind);
  14005. this.finishNode(init$1, "VariableDeclaration");
  14006. if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
  14007. if (this.options.ecmaVersion >= 9) {
  14008. if (this.type === types._in) {
  14009. if (awaitAt > -1) { this.unexpected(awaitAt); }
  14010. } else { node.await = awaitAt > -1; }
  14011. }
  14012. return this.parseForIn(node, init$1)
  14013. }
  14014. if (awaitAt > -1) { this.unexpected(awaitAt); }
  14015. return this.parseFor(node, init$1)
  14016. }
  14017. var refDestructuringErrors = new DestructuringErrors;
  14018. var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
  14019. if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
  14020. if (this.options.ecmaVersion >= 9) {
  14021. if (this.type === types._in) {
  14022. if (awaitAt > -1) { this.unexpected(awaitAt); }
  14023. } else { node.await = awaitAt > -1; }
  14024. }
  14025. this.toAssignable(init, false, refDestructuringErrors);
  14026. this.checkLValPattern(init);
  14027. return this.parseForIn(node, init)
  14028. } else {
  14029. this.checkExpressionErrors(refDestructuringErrors, true);
  14030. }
  14031. if (awaitAt > -1) { this.unexpected(awaitAt); }
  14032. return this.parseFor(node, init)
  14033. };
  14034. pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) {
  14035. this.next();
  14036. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
  14037. };
  14038. pp$1.parseIfStatement = function(node) {
  14039. this.next();
  14040. node.test = this.parseParenExpression();
  14041. // allow function declarations in branches, but only in non-strict mode
  14042. node.consequent = this.parseStatement("if");
  14043. node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
  14044. return this.finishNode(node, "IfStatement")
  14045. };
  14046. pp$1.parseReturnStatement = function(node) {
  14047. if (!this.inFunction && !this.options.allowReturnOutsideFunction)
  14048. { this.raise(this.start, "'return' outside of function"); }
  14049. this.next();
  14050. // In `return` (and `break`/`continue`), the keywords with
  14051. // optional arguments, we eagerly look for a semicolon or the
  14052. // possibility to insert one.
  14053. if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; }
  14054. else { node.argument = this.parseExpression(); this.semicolon(); }
  14055. return this.finishNode(node, "ReturnStatement")
  14056. };
  14057. pp$1.parseSwitchStatement = function(node) {
  14058. this.next();
  14059. node.discriminant = this.parseParenExpression();
  14060. node.cases = [];
  14061. this.expect(types.braceL);
  14062. this.labels.push(switchLabel);
  14063. this.enterScope(0);
  14064. // Statements under must be grouped (by label) in SwitchCase
  14065. // nodes. `cur` is used to keep the node that we are currently
  14066. // adding statements to.
  14067. var cur;
  14068. for (var sawDefault = false; this.type !== types.braceR;) {
  14069. if (this.type === types._case || this.type === types._default) {
  14070. var isCase = this.type === types._case;
  14071. if (cur) { this.finishNode(cur, "SwitchCase"); }
  14072. node.cases.push(cur = this.startNode());
  14073. cur.consequent = [];
  14074. this.next();
  14075. if (isCase) {
  14076. cur.test = this.parseExpression();
  14077. } else {
  14078. if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
  14079. sawDefault = true;
  14080. cur.test = null;
  14081. }
  14082. this.expect(types.colon);
  14083. } else {
  14084. if (!cur) { this.unexpected(); }
  14085. cur.consequent.push(this.parseStatement(null));
  14086. }
  14087. }
  14088. this.exitScope();
  14089. if (cur) { this.finishNode(cur, "SwitchCase"); }
  14090. this.next(); // Closing brace
  14091. this.labels.pop();
  14092. return this.finishNode(node, "SwitchStatement")
  14093. };
  14094. pp$1.parseThrowStatement = function(node) {
  14095. this.next();
  14096. if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
  14097. { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
  14098. node.argument = this.parseExpression();
  14099. this.semicolon();
  14100. return this.finishNode(node, "ThrowStatement")
  14101. };
  14102. // Reused empty array added for node fields that are always empty.
  14103. var empty = [];
  14104. pp$1.parseTryStatement = function(node) {
  14105. this.next();
  14106. node.block = this.parseBlock();
  14107. node.handler = null;
  14108. if (this.type === types._catch) {
  14109. var clause = this.startNode();
  14110. this.next();
  14111. if (this.eat(types.parenL)) {
  14112. clause.param = this.parseBindingAtom();
  14113. var simple = clause.param.type === "Identifier";
  14114. this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
  14115. this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
  14116. this.expect(types.parenR);
  14117. } else {
  14118. if (this.options.ecmaVersion < 10) { this.unexpected(); }
  14119. clause.param = null;
  14120. this.enterScope(0);
  14121. }
  14122. clause.body = this.parseBlock(false);
  14123. this.exitScope();
  14124. node.handler = this.finishNode(clause, "CatchClause");
  14125. }
  14126. node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
  14127. if (!node.handler && !node.finalizer)
  14128. { this.raise(node.start, "Missing catch or finally clause"); }
  14129. return this.finishNode(node, "TryStatement")
  14130. };
  14131. pp$1.parseVarStatement = function(node, kind) {
  14132. this.next();
  14133. this.parseVar(node, false, kind);
  14134. this.semicolon();
  14135. return this.finishNode(node, "VariableDeclaration")
  14136. };
  14137. pp$1.parseWhileStatement = function(node) {
  14138. this.next();
  14139. node.test = this.parseParenExpression();
  14140. this.labels.push(loopLabel);
  14141. node.body = this.parseStatement("while");
  14142. this.labels.pop();
  14143. return this.finishNode(node, "WhileStatement")
  14144. };
  14145. pp$1.parseWithStatement = function(node) {
  14146. if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
  14147. this.next();
  14148. node.object = this.parseParenExpression();
  14149. node.body = this.parseStatement("with");
  14150. return this.finishNode(node, "WithStatement")
  14151. };
  14152. pp$1.parseEmptyStatement = function(node) {
  14153. this.next();
  14154. return this.finishNode(node, "EmptyStatement")
  14155. };
  14156. pp$1.parseLabeledStatement = function(node, maybeName, expr, context) {
  14157. for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
  14158. {
  14159. var label = list[i$1];
  14160. if (label.name === maybeName)
  14161. { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
  14162. } }
  14163. var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null;
  14164. for (var i = this.labels.length - 1; i >= 0; i--) {
  14165. var label$1 = this.labels[i];
  14166. if (label$1.statementStart === node.start) {
  14167. // Update information about previous labels on this node
  14168. label$1.statementStart = this.start;
  14169. label$1.kind = kind;
  14170. } else { break }
  14171. }
  14172. this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
  14173. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  14174. this.labels.pop();
  14175. node.label = expr;
  14176. return this.finishNode(node, "LabeledStatement")
  14177. };
  14178. pp$1.parseExpressionStatement = function(node, expr) {
  14179. node.expression = expr;
  14180. this.semicolon();
  14181. return this.finishNode(node, "ExpressionStatement")
  14182. };
  14183. // Parse a semicolon-enclosed block of statements, handling `"use
  14184. // strict"` declarations when `allowStrict` is true (used for
  14185. // function bodies).
  14186. pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  14187. if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  14188. if ( node === void 0 ) node = this.startNode();
  14189. node.body = [];
  14190. this.expect(types.braceL);
  14191. if (createNewLexicalScope) { this.enterScope(0); }
  14192. while (this.type !== types.braceR) {
  14193. var stmt = this.parseStatement(null);
  14194. node.body.push(stmt);
  14195. }
  14196. if (exitStrict) { this.strict = false; }
  14197. this.next();
  14198. if (createNewLexicalScope) { this.exitScope(); }
  14199. return this.finishNode(node, "BlockStatement")
  14200. };
  14201. // Parse a regular `for` loop. The disambiguation code in
  14202. // `parseStatement` will already have parsed the init statement or
  14203. // expression.
  14204. pp$1.parseFor = function(node, init) {
  14205. node.init = init;
  14206. this.expect(types.semi);
  14207. node.test = this.type === types.semi ? null : this.parseExpression();
  14208. this.expect(types.semi);
  14209. node.update = this.type === types.parenR ? null : this.parseExpression();
  14210. this.expect(types.parenR);
  14211. node.body = this.parseStatement("for");
  14212. this.exitScope();
  14213. this.labels.pop();
  14214. return this.finishNode(node, "ForStatement")
  14215. };
  14216. // Parse a `for`/`in` and `for`/`of` loop, which are almost
  14217. // same from parser's perspective.
  14218. pp$1.parseForIn = function(node, init) {
  14219. var isForIn = this.type === types._in;
  14220. this.next();
  14221. if (
  14222. init.type === "VariableDeclaration" &&
  14223. init.declarations[0].init != null &&
  14224. (
  14225. !isForIn ||
  14226. this.options.ecmaVersion < 8 ||
  14227. this.strict ||
  14228. init.kind !== "var" ||
  14229. init.declarations[0].id.type !== "Identifier"
  14230. )
  14231. ) {
  14232. this.raise(
  14233. init.start,
  14234. ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
  14235. );
  14236. }
  14237. node.left = init;
  14238. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  14239. this.expect(types.parenR);
  14240. node.body = this.parseStatement("for");
  14241. this.exitScope();
  14242. this.labels.pop();
  14243. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
  14244. };
  14245. // Parse a list of variable declarations.
  14246. pp$1.parseVar = function(node, isFor, kind) {
  14247. node.declarations = [];
  14248. node.kind = kind;
  14249. for (;;) {
  14250. var decl = this.startNode();
  14251. this.parseVarId(decl, kind);
  14252. if (this.eat(types.eq)) {
  14253. decl.init = this.parseMaybeAssign(isFor);
  14254. } else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
  14255. this.unexpected();
  14256. } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) {
  14257. this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
  14258. } else {
  14259. decl.init = null;
  14260. }
  14261. node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
  14262. if (!this.eat(types.comma)) { break }
  14263. }
  14264. return node
  14265. };
  14266. pp$1.parseVarId = function(decl, kind) {
  14267. decl.id = this.parseBindingAtom();
  14268. this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
  14269. };
  14270. var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
  14271. // Parse a function declaration or literal (depending on the
  14272. // `statement & FUNC_STATEMENT`).
  14273. // Remove `allowExpressionBody` for 7.0.0, as it is only called with false
  14274. pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) {
  14275. this.initFunction(node);
  14276. if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
  14277. if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT))
  14278. { this.unexpected(); }
  14279. node.generator = this.eat(types.star);
  14280. }
  14281. if (this.options.ecmaVersion >= 8)
  14282. { node.async = !!isAsync; }
  14283. if (statement & FUNC_STATEMENT) {
  14284. node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent();
  14285. if (node.id && !(statement & FUNC_HANGING_STATEMENT))
  14286. // If it is a regular function declaration in sloppy mode, then it is
  14287. // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
  14288. // mode depends on properties of the current scope (see
  14289. // treatFunctionsAsVar).
  14290. { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
  14291. }
  14292. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  14293. this.yieldPos = 0;
  14294. this.awaitPos = 0;
  14295. this.awaitIdentPos = 0;
  14296. this.enterScope(functionFlags(node.async, node.generator));
  14297. if (!(statement & FUNC_STATEMENT))
  14298. { node.id = this.type === types.name ? this.parseIdent() : null; }
  14299. this.parseFunctionParams(node);
  14300. this.parseFunctionBody(node, allowExpressionBody, false);
  14301. this.yieldPos = oldYieldPos;
  14302. this.awaitPos = oldAwaitPos;
  14303. this.awaitIdentPos = oldAwaitIdentPos;
  14304. return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
  14305. };
  14306. pp$1.parseFunctionParams = function(node) {
  14307. this.expect(types.parenL);
  14308. node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
  14309. this.checkYieldAwaitInDefaultParams();
  14310. };
  14311. // Parse a class declaration or literal (depending on the
  14312. // `isStatement` parameter).
  14313. pp$1.parseClass = function(node, isStatement) {
  14314. this.next();
  14315. // ecma-262 14.6 Class Definitions
  14316. // A class definition is always strict mode code.
  14317. var oldStrict = this.strict;
  14318. this.strict = true;
  14319. this.parseClassId(node, isStatement);
  14320. this.parseClassSuper(node);
  14321. var privateNameMap = this.enterClassBody();
  14322. var classBody = this.startNode();
  14323. var hadConstructor = false;
  14324. classBody.body = [];
  14325. this.expect(types.braceL);
  14326. while (this.type !== types.braceR) {
  14327. var element = this.parseClassElement(node.superClass !== null);
  14328. if (element) {
  14329. classBody.body.push(element);
  14330. if (element.type === "MethodDefinition" && element.kind === "constructor") {
  14331. if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
  14332. hadConstructor = true;
  14333. } else if (element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
  14334. this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
  14335. }
  14336. }
  14337. }
  14338. this.strict = oldStrict;
  14339. this.next();
  14340. node.body = this.finishNode(classBody, "ClassBody");
  14341. this.exitClassBody();
  14342. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
  14343. };
  14344. pp$1.parseClassElement = function(constructorAllowsSuper) {
  14345. if (this.eat(types.semi)) { return null }
  14346. var ecmaVersion = this.options.ecmaVersion;
  14347. var node = this.startNode();
  14348. var keyName = "";
  14349. var isGenerator = false;
  14350. var isAsync = false;
  14351. var kind = "method";
  14352. // Parse modifiers
  14353. node.static = false;
  14354. if (this.eatContextual("static")) {
  14355. if (this.isClassElementNameStart() || this.type === types.star) {
  14356. node.static = true;
  14357. } else {
  14358. keyName = "static";
  14359. }
  14360. }
  14361. if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
  14362. if ((this.isClassElementNameStart() || this.type === types.star) && !this.canInsertSemicolon()) {
  14363. isAsync = true;
  14364. } else {
  14365. keyName = "async";
  14366. }
  14367. }
  14368. if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types.star)) {
  14369. isGenerator = true;
  14370. }
  14371. if (!keyName && !isAsync && !isGenerator) {
  14372. var lastValue = this.value;
  14373. if (this.eatContextual("get") || this.eatContextual("set")) {
  14374. if (this.isClassElementNameStart()) {
  14375. kind = lastValue;
  14376. } else {
  14377. keyName = lastValue;
  14378. }
  14379. }
  14380. }
  14381. // Parse element name
  14382. if (keyName) {
  14383. // 'async', 'get', 'set', or 'static' were not a keyword contextually.
  14384. // The last token is any of those. Make it the element name.
  14385. node.computed = false;
  14386. node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
  14387. node.key.name = keyName;
  14388. this.finishNode(node.key, "Identifier");
  14389. } else {
  14390. this.parseClassElementName(node);
  14391. }
  14392. // Parse element value
  14393. if (ecmaVersion < 13 || this.type === types.parenL || kind !== "method" || isGenerator || isAsync) {
  14394. var isConstructor = !node.static && checkKeyName(node, "constructor");
  14395. var allowsDirectSuper = isConstructor && constructorAllowsSuper;
  14396. // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
  14397. if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
  14398. node.kind = isConstructor ? "constructor" : kind;
  14399. this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
  14400. } else {
  14401. this.parseClassField(node);
  14402. }
  14403. return node
  14404. };
  14405. pp$1.isClassElementNameStart = function() {
  14406. return (
  14407. this.type === types.name ||
  14408. this.type === types.privateId ||
  14409. this.type === types.num ||
  14410. this.type === types.string ||
  14411. this.type === types.bracketL ||
  14412. this.type.keyword
  14413. )
  14414. };
  14415. pp$1.parseClassElementName = function(element) {
  14416. if (this.type === types.privateId) {
  14417. if (this.value === "constructor") {
  14418. this.raise(this.start, "Classes can't have an element named '#constructor'");
  14419. }
  14420. element.computed = false;
  14421. element.key = this.parsePrivateIdent();
  14422. } else {
  14423. this.parsePropertyName(element);
  14424. }
  14425. };
  14426. pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
  14427. // Check key and flags
  14428. var key = method.key;
  14429. if (method.kind === "constructor") {
  14430. if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
  14431. if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
  14432. } else if (method.static && checkKeyName(method, "prototype")) {
  14433. this.raise(key.start, "Classes may not have a static property named prototype");
  14434. }
  14435. // Parse value
  14436. var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
  14437. // Check value
  14438. if (method.kind === "get" && value.params.length !== 0)
  14439. { this.raiseRecoverable(value.start, "getter should have no params"); }
  14440. if (method.kind === "set" && value.params.length !== 1)
  14441. { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
  14442. if (method.kind === "set" && value.params[0].type === "RestElement")
  14443. { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
  14444. return this.finishNode(method, "MethodDefinition")
  14445. };
  14446. pp$1.parseClassField = function(field) {
  14447. if (checkKeyName(field, "constructor")) {
  14448. this.raise(field.key.start, "Classes can't have a field named 'constructor'");
  14449. } else if (field.static && checkKeyName(field, "prototype")) {
  14450. this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
  14451. }
  14452. if (this.eat(types.eq)) {
  14453. // To raise SyntaxError if 'arguments' exists in the initializer.
  14454. var scope = this.currentThisScope();
  14455. var inClassFieldInit = scope.inClassFieldInit;
  14456. scope.inClassFieldInit = true;
  14457. field.value = this.parseMaybeAssign();
  14458. scope.inClassFieldInit = inClassFieldInit;
  14459. } else {
  14460. field.value = null;
  14461. }
  14462. this.semicolon();
  14463. return this.finishNode(field, "PropertyDefinition")
  14464. };
  14465. pp$1.parseClassId = function(node, isStatement) {
  14466. if (this.type === types.name) {
  14467. node.id = this.parseIdent();
  14468. if (isStatement)
  14469. { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
  14470. } else {
  14471. if (isStatement === true)
  14472. { this.unexpected(); }
  14473. node.id = null;
  14474. }
  14475. };
  14476. pp$1.parseClassSuper = function(node) {
  14477. node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
  14478. };
  14479. pp$1.enterClassBody = function() {
  14480. var element = {declared: Object.create(null), used: []};
  14481. this.privateNameStack.push(element);
  14482. return element.declared
  14483. };
  14484. pp$1.exitClassBody = function() {
  14485. var ref = this.privateNameStack.pop();
  14486. var declared = ref.declared;
  14487. var used = ref.used;
  14488. var len = this.privateNameStack.length;
  14489. var parent = len === 0 ? null : this.privateNameStack[len - 1];
  14490. for (var i = 0; i < used.length; ++i) {
  14491. var id = used[i];
  14492. if (!has(declared, id.name)) {
  14493. if (parent) {
  14494. parent.used.push(id);
  14495. } else {
  14496. this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
  14497. }
  14498. }
  14499. }
  14500. };
  14501. function isPrivateNameConflicted(privateNameMap, element) {
  14502. var name = element.key.name;
  14503. var curr = privateNameMap[name];
  14504. var next = "true";
  14505. if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
  14506. next = (element.static ? "s" : "i") + element.kind;
  14507. }
  14508. // `class { get #a(){}; static set #a(_){} }` is also conflict.
  14509. if (
  14510. curr === "iget" && next === "iset" ||
  14511. curr === "iset" && next === "iget" ||
  14512. curr === "sget" && next === "sset" ||
  14513. curr === "sset" && next === "sget"
  14514. ) {
  14515. privateNameMap[name] = "true";
  14516. return false
  14517. } else if (!curr) {
  14518. privateNameMap[name] = next;
  14519. return false
  14520. } else {
  14521. return true
  14522. }
  14523. }
  14524. function checkKeyName(node, name) {
  14525. var computed = node.computed;
  14526. var key = node.key;
  14527. return !computed && (
  14528. key.type === "Identifier" && key.name === name ||
  14529. key.type === "Literal" && key.value === name
  14530. )
  14531. }
  14532. // Parses module export declaration.
  14533. pp$1.parseExport = function(node, exports) {
  14534. this.next();
  14535. // export * from '...'
  14536. if (this.eat(types.star)) {
  14537. if (this.options.ecmaVersion >= 11) {
  14538. if (this.eatContextual("as")) {
  14539. node.exported = this.parseIdent(true);
  14540. this.checkExport(exports, node.exported.name, this.lastTokStart);
  14541. } else {
  14542. node.exported = null;
  14543. }
  14544. }
  14545. this.expectContextual("from");
  14546. if (this.type !== types.string) { this.unexpected(); }
  14547. node.source = this.parseExprAtom();
  14548. this.semicolon();
  14549. return this.finishNode(node, "ExportAllDeclaration")
  14550. }
  14551. if (this.eat(types._default)) { // export default ...
  14552. this.checkExport(exports, "default", this.lastTokStart);
  14553. var isAsync;
  14554. if (this.type === types._function || (isAsync = this.isAsyncFunction())) {
  14555. var fNode = this.startNode();
  14556. this.next();
  14557. if (isAsync) { this.next(); }
  14558. node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
  14559. } else if (this.type === types._class) {
  14560. var cNode = this.startNode();
  14561. node.declaration = this.parseClass(cNode, "nullableID");
  14562. } else {
  14563. node.declaration = this.parseMaybeAssign();
  14564. this.semicolon();
  14565. }
  14566. return this.finishNode(node, "ExportDefaultDeclaration")
  14567. }
  14568. // export var|const|let|function|class ...
  14569. if (this.shouldParseExportStatement()) {
  14570. node.declaration = this.parseStatement(null);
  14571. if (node.declaration.type === "VariableDeclaration")
  14572. { this.checkVariableExport(exports, node.declaration.declarations); }
  14573. else
  14574. { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
  14575. node.specifiers = [];
  14576. node.source = null;
  14577. } else { // export { x, y as z } [from '...']
  14578. node.declaration = null;
  14579. node.specifiers = this.parseExportSpecifiers(exports);
  14580. if (this.eatContextual("from")) {
  14581. if (this.type !== types.string) { this.unexpected(); }
  14582. node.source = this.parseExprAtom();
  14583. } else {
  14584. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  14585. // check for keywords used as local names
  14586. var spec = list[i];
  14587. this.checkUnreserved(spec.local);
  14588. // check if export is defined
  14589. this.checkLocalExport(spec.local);
  14590. }
  14591. node.source = null;
  14592. }
  14593. this.semicolon();
  14594. }
  14595. return this.finishNode(node, "ExportNamedDeclaration")
  14596. };
  14597. pp$1.checkExport = function(exports, name, pos) {
  14598. if (!exports) { return }
  14599. if (has(exports, name))
  14600. { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  14601. exports[name] = true;
  14602. };
  14603. pp$1.checkPatternExport = function(exports, pat) {
  14604. var type = pat.type;
  14605. if (type === "Identifier")
  14606. { this.checkExport(exports, pat.name, pat.start); }
  14607. else if (type === "ObjectPattern")
  14608. { for (var i = 0, list = pat.properties; i < list.length; i += 1)
  14609. {
  14610. var prop = list[i];
  14611. this.checkPatternExport(exports, prop);
  14612. } }
  14613. else if (type === "ArrayPattern")
  14614. { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
  14615. var elt = list$1[i$1];
  14616. if (elt) { this.checkPatternExport(exports, elt); }
  14617. } }
  14618. else if (type === "Property")
  14619. { this.checkPatternExport(exports, pat.value); }
  14620. else if (type === "AssignmentPattern")
  14621. { this.checkPatternExport(exports, pat.left); }
  14622. else if (type === "RestElement")
  14623. { this.checkPatternExport(exports, pat.argument); }
  14624. else if (type === "ParenthesizedExpression")
  14625. { this.checkPatternExport(exports, pat.expression); }
  14626. };
  14627. pp$1.checkVariableExport = function(exports, decls) {
  14628. if (!exports) { return }
  14629. for (var i = 0, list = decls; i < list.length; i += 1)
  14630. {
  14631. var decl = list[i];
  14632. this.checkPatternExport(exports, decl.id);
  14633. }
  14634. };
  14635. pp$1.shouldParseExportStatement = function() {
  14636. return this.type.keyword === "var" ||
  14637. this.type.keyword === "const" ||
  14638. this.type.keyword === "class" ||
  14639. this.type.keyword === "function" ||
  14640. this.isLet() ||
  14641. this.isAsyncFunction()
  14642. };
  14643. // Parses a comma-separated list of module exports.
  14644. pp$1.parseExportSpecifiers = function(exports) {
  14645. var nodes = [], first = true;
  14646. // export { x, y as z } [from '...']
  14647. this.expect(types.braceL);
  14648. while (!this.eat(types.braceR)) {
  14649. if (!first) {
  14650. this.expect(types.comma);
  14651. if (this.afterTrailingComma(types.braceR)) { break }
  14652. } else { first = false; }
  14653. var node = this.startNode();
  14654. node.local = this.parseIdent(true);
  14655. node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
  14656. this.checkExport(exports, node.exported.name, node.exported.start);
  14657. nodes.push(this.finishNode(node, "ExportSpecifier"));
  14658. }
  14659. return nodes
  14660. };
  14661. // Parses import declaration.
  14662. pp$1.parseImport = function(node) {
  14663. this.next();
  14664. // import '...'
  14665. if (this.type === types.string) {
  14666. node.specifiers = empty;
  14667. node.source = this.parseExprAtom();
  14668. } else {
  14669. node.specifiers = this.parseImportSpecifiers();
  14670. this.expectContextual("from");
  14671. node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
  14672. }
  14673. this.semicolon();
  14674. return this.finishNode(node, "ImportDeclaration")
  14675. };
  14676. // Parses a comma-separated list of module imports.
  14677. pp$1.parseImportSpecifiers = function() {
  14678. var nodes = [], first = true;
  14679. if (this.type === types.name) {
  14680. // import defaultObj, { x, y as z } from '...'
  14681. var node = this.startNode();
  14682. node.local = this.parseIdent();
  14683. this.checkLValSimple(node.local, BIND_LEXICAL);
  14684. nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
  14685. if (!this.eat(types.comma)) { return nodes }
  14686. }
  14687. if (this.type === types.star) {
  14688. var node$1 = this.startNode();
  14689. this.next();
  14690. this.expectContextual("as");
  14691. node$1.local = this.parseIdent();
  14692. this.checkLValSimple(node$1.local, BIND_LEXICAL);
  14693. nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
  14694. return nodes
  14695. }
  14696. this.expect(types.braceL);
  14697. while (!this.eat(types.braceR)) {
  14698. if (!first) {
  14699. this.expect(types.comma);
  14700. if (this.afterTrailingComma(types.braceR)) { break }
  14701. } else { first = false; }
  14702. var node$2 = this.startNode();
  14703. node$2.imported = this.parseIdent(true);
  14704. if (this.eatContextual("as")) {
  14705. node$2.local = this.parseIdent();
  14706. } else {
  14707. this.checkUnreserved(node$2.imported);
  14708. node$2.local = node$2.imported;
  14709. }
  14710. this.checkLValSimple(node$2.local, BIND_LEXICAL);
  14711. nodes.push(this.finishNode(node$2, "ImportSpecifier"));
  14712. }
  14713. return nodes
  14714. };
  14715. // Set `ExpressionStatement#directive` property for directive prologues.
  14716. pp$1.adaptDirectivePrologue = function(statements) {
  14717. for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
  14718. statements[i].directive = statements[i].expression.raw.slice(1, -1);
  14719. }
  14720. };
  14721. pp$1.isDirectiveCandidate = function(statement) {
  14722. return (
  14723. statement.type === "ExpressionStatement" &&
  14724. statement.expression.type === "Literal" &&
  14725. typeof statement.expression.value === "string" &&
  14726. // Reject parenthesized strings.
  14727. (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
  14728. )
  14729. };
  14730. var pp$2 = Parser.prototype;
  14731. // Convert existing expression atom to assignable pattern
  14732. // if possible.
  14733. pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) {
  14734. if (this.options.ecmaVersion >= 6 && node) {
  14735. switch (node.type) {
  14736. case "Identifier":
  14737. if (this.inAsync && node.name === "await")
  14738. { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
  14739. break
  14740. case "ObjectPattern":
  14741. case "ArrayPattern":
  14742. case "AssignmentPattern":
  14743. case "RestElement":
  14744. break
  14745. case "ObjectExpression":
  14746. node.type = "ObjectPattern";
  14747. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  14748. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  14749. var prop = list[i];
  14750. this.toAssignable(prop, isBinding);
  14751. // Early error:
  14752. // AssignmentRestProperty[Yield, Await] :
  14753. // `...` DestructuringAssignmentTarget[Yield, Await]
  14754. //
  14755. // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
  14756. if (
  14757. prop.type === "RestElement" &&
  14758. (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
  14759. ) {
  14760. this.raise(prop.argument.start, "Unexpected token");
  14761. }
  14762. }
  14763. break
  14764. case "Property":
  14765. // AssignmentProperty has type === "Property"
  14766. if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
  14767. this.toAssignable(node.value, isBinding);
  14768. break
  14769. case "ArrayExpression":
  14770. node.type = "ArrayPattern";
  14771. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  14772. this.toAssignableList(node.elements, isBinding);
  14773. break
  14774. case "SpreadElement":
  14775. node.type = "RestElement";
  14776. this.toAssignable(node.argument, isBinding);
  14777. if (node.argument.type === "AssignmentPattern")
  14778. { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
  14779. break
  14780. case "AssignmentExpression":
  14781. if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
  14782. node.type = "AssignmentPattern";
  14783. delete node.operator;
  14784. this.toAssignable(node.left, isBinding);
  14785. break
  14786. case "ParenthesizedExpression":
  14787. this.toAssignable(node.expression, isBinding, refDestructuringErrors);
  14788. break
  14789. case "ChainExpression":
  14790. this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
  14791. break
  14792. case "MemberExpression":
  14793. if (!isBinding) { break }
  14794. default:
  14795. this.raise(node.start, "Assigning to rvalue");
  14796. }
  14797. } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  14798. return node
  14799. };
  14800. // Convert list of expression atoms to binding list.
  14801. pp$2.toAssignableList = function(exprList, isBinding) {
  14802. var end = exprList.length;
  14803. for (var i = 0; i < end; i++) {
  14804. var elt = exprList[i];
  14805. if (elt) { this.toAssignable(elt, isBinding); }
  14806. }
  14807. if (end) {
  14808. var last = exprList[end - 1];
  14809. if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
  14810. { this.unexpected(last.argument.start); }
  14811. }
  14812. return exprList
  14813. };
  14814. // Parses spread element.
  14815. pp$2.parseSpread = function(refDestructuringErrors) {
  14816. var node = this.startNode();
  14817. this.next();
  14818. node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  14819. return this.finishNode(node, "SpreadElement")
  14820. };
  14821. pp$2.parseRestBinding = function() {
  14822. var node = this.startNode();
  14823. this.next();
  14824. // RestElement inside of a function parameter must be an identifier
  14825. if (this.options.ecmaVersion === 6 && this.type !== types.name)
  14826. { this.unexpected(); }
  14827. node.argument = this.parseBindingAtom();
  14828. return this.finishNode(node, "RestElement")
  14829. };
  14830. // Parses lvalue (assignable) atom.
  14831. pp$2.parseBindingAtom = function() {
  14832. if (this.options.ecmaVersion >= 6) {
  14833. switch (this.type) {
  14834. case types.bracketL:
  14835. var node = this.startNode();
  14836. this.next();
  14837. node.elements = this.parseBindingList(types.bracketR, true, true);
  14838. return this.finishNode(node, "ArrayPattern")
  14839. case types.braceL:
  14840. return this.parseObj(true)
  14841. }
  14842. }
  14843. return this.parseIdent()
  14844. };
  14845. pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
  14846. var elts = [], first = true;
  14847. while (!this.eat(close)) {
  14848. if (first) { first = false; }
  14849. else { this.expect(types.comma); }
  14850. if (allowEmpty && this.type === types.comma) {
  14851. elts.push(null);
  14852. } else if (allowTrailingComma && this.afterTrailingComma(close)) {
  14853. break
  14854. } else if (this.type === types.ellipsis) {
  14855. var rest = this.parseRestBinding();
  14856. this.parseBindingListItem(rest);
  14857. elts.push(rest);
  14858. if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  14859. this.expect(close);
  14860. break
  14861. } else {
  14862. var elem = this.parseMaybeDefault(this.start, this.startLoc);
  14863. this.parseBindingListItem(elem);
  14864. elts.push(elem);
  14865. }
  14866. }
  14867. return elts
  14868. };
  14869. pp$2.parseBindingListItem = function(param) {
  14870. return param
  14871. };
  14872. // Parses assignment pattern around given atom if possible.
  14873. pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
  14874. left = left || this.parseBindingAtom();
  14875. if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left }
  14876. var node = this.startNodeAt(startPos, startLoc);
  14877. node.left = left;
  14878. node.right = this.parseMaybeAssign();
  14879. return this.finishNode(node, "AssignmentPattern")
  14880. };
  14881. // The following three functions all verify that a node is an lvalue —
  14882. // something that can be bound, or assigned to. In order to do so, they perform
  14883. // a variety of checks:
  14884. //
  14885. // - Check that none of the bound/assigned-to identifiers are reserved words.
  14886. // - Record name declarations for bindings in the appropriate scope.
  14887. // - Check duplicate argument names, if checkClashes is set.
  14888. //
  14889. // If a complex binding pattern is encountered (e.g., object and array
  14890. // destructuring), the entire pattern is recursively checked.
  14891. //
  14892. // There are three versions of checkLVal*() appropriate for different
  14893. // circumstances:
  14894. //
  14895. // - checkLValSimple() shall be used if the syntactic construct supports
  14896. // nothing other than identifiers and member expressions. Parenthesized
  14897. // expressions are also correctly handled. This is generally appropriate for
  14898. // constructs for which the spec says
  14899. //
  14900. // > It is a Syntax Error if AssignmentTargetType of [the production] is not
  14901. // > simple.
  14902. //
  14903. // It is also appropriate for checking if an identifier is valid and not
  14904. // defined elsewhere, like import declarations or function/class identifiers.
  14905. //
  14906. // Examples where this is used include:
  14907. // a += …;
  14908. // import a from '…';
  14909. // where a is the node to be checked.
  14910. //
  14911. // - checkLValPattern() shall be used if the syntactic construct supports
  14912. // anything checkLValSimple() supports, as well as object and array
  14913. // destructuring patterns. This is generally appropriate for constructs for
  14914. // which the spec says
  14915. //
  14916. // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
  14917. // > an ArrayLiteral and AssignmentTargetType of [the production] is not
  14918. // > simple.
  14919. //
  14920. // Examples where this is used include:
  14921. // (a = …);
  14922. // const a = …;
  14923. // try { … } catch (a) { … }
  14924. // where a is the node to be checked.
  14925. //
  14926. // - checkLValInnerPattern() shall be used if the syntactic construct supports
  14927. // anything checkLValPattern() supports, as well as default assignment
  14928. // patterns, rest elements, and other constructs that may appear within an
  14929. // object or array destructuring pattern.
  14930. //
  14931. // As a special case, function parameters also use checkLValInnerPattern(),
  14932. // as they also support defaults and rest constructs.
  14933. //
  14934. // These functions deliberately support both assignment and binding constructs,
  14935. // as the logic for both is exceedingly similar. If the node is the target of
  14936. // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
  14937. // should be set to the appropriate BIND_* constant, like BIND_VAR or
  14938. // BIND_LEXICAL.
  14939. //
  14940. // If the function is called with a non-BIND_NONE bindingType, then
  14941. // additionally a checkClashes object may be specified to allow checking for
  14942. // duplicate argument names. checkClashes is ignored if the provided construct
  14943. // is an assignment (i.e., bindingType is BIND_NONE).
  14944. pp$2.checkLValSimple = function(expr, bindingType, checkClashes) {
  14945. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  14946. var isBind = bindingType !== BIND_NONE;
  14947. switch (expr.type) {
  14948. case "Identifier":
  14949. if (this.strict && this.reservedWordsStrictBind.test(expr.name))
  14950. { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
  14951. if (isBind) {
  14952. if (bindingType === BIND_LEXICAL && expr.name === "let")
  14953. { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
  14954. if (checkClashes) {
  14955. if (has(checkClashes, expr.name))
  14956. { this.raiseRecoverable(expr.start, "Argument name clash"); }
  14957. checkClashes[expr.name] = true;
  14958. }
  14959. if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
  14960. }
  14961. break
  14962. case "ChainExpression":
  14963. this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
  14964. break
  14965. case "MemberExpression":
  14966. if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
  14967. break
  14968. case "ParenthesizedExpression":
  14969. if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
  14970. return this.checkLValSimple(expr.expression, bindingType, checkClashes)
  14971. default:
  14972. this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  14973. }
  14974. };
  14975. pp$2.checkLValPattern = function(expr, bindingType, checkClashes) {
  14976. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  14977. switch (expr.type) {
  14978. case "ObjectPattern":
  14979. for (var i = 0, list = expr.properties; i < list.length; i += 1) {
  14980. var prop = list[i];
  14981. this.checkLValInnerPattern(prop, bindingType, checkClashes);
  14982. }
  14983. break
  14984. case "ArrayPattern":
  14985. for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
  14986. var elem = list$1[i$1];
  14987. if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
  14988. }
  14989. break
  14990. default:
  14991. this.checkLValSimple(expr, bindingType, checkClashes);
  14992. }
  14993. };
  14994. pp$2.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  14995. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  14996. switch (expr.type) {
  14997. case "Property":
  14998. // AssignmentProperty has type === "Property"
  14999. this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
  15000. break
  15001. case "AssignmentPattern":
  15002. this.checkLValPattern(expr.left, bindingType, checkClashes);
  15003. break
  15004. case "RestElement":
  15005. this.checkLValPattern(expr.argument, bindingType, checkClashes);
  15006. break
  15007. default:
  15008. this.checkLValPattern(expr, bindingType, checkClashes);
  15009. }
  15010. };
  15011. // A recursive descent parser operates by defining functions for all
  15012. var pp$3 = Parser.prototype;
  15013. // Check if property name clashes with already added.
  15014. // Object/class getters and setters are not allowed to clash —
  15015. // either with each other or with an init property — and in
  15016. // strict mode, init properties are also not allowed to be repeated.
  15017. pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  15018. if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
  15019. { return }
  15020. if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
  15021. { return }
  15022. var key = prop.key;
  15023. var name;
  15024. switch (key.type) {
  15025. case "Identifier": name = key.name; break
  15026. case "Literal": name = String(key.value); break
  15027. default: return
  15028. }
  15029. var kind = prop.kind;
  15030. if (this.options.ecmaVersion >= 6) {
  15031. if (name === "__proto__" && kind === "init") {
  15032. if (propHash.proto) {
  15033. if (refDestructuringErrors) {
  15034. if (refDestructuringErrors.doubleProto < 0)
  15035. { refDestructuringErrors.doubleProto = key.start; }
  15036. // Backwards-compat kludge. Can be removed in version 6.0
  15037. } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); }
  15038. }
  15039. propHash.proto = true;
  15040. }
  15041. return
  15042. }
  15043. name = "$" + name;
  15044. var other = propHash[name];
  15045. if (other) {
  15046. var redefinition;
  15047. if (kind === "init") {
  15048. redefinition = this.strict && other.init || other.get || other.set;
  15049. } else {
  15050. redefinition = other.init || other[kind];
  15051. }
  15052. if (redefinition)
  15053. { this.raiseRecoverable(key.start, "Redefinition of property"); }
  15054. } else {
  15055. other = propHash[name] = {
  15056. init: false,
  15057. get: false,
  15058. set: false
  15059. };
  15060. }
  15061. other[kind] = true;
  15062. };
  15063. // ### Expression parsing
  15064. // These nest, from the most general expression type at the top to
  15065. // 'atomic', nondivisible expression types at the bottom. Most of
  15066. // the functions will simply let the function(s) below them parse,
  15067. // and, *if* the syntactic construct they handle is present, wrap
  15068. // the AST node that the inner parser gave them in another node.
  15069. // Parse a full expression. The optional arguments are used to
  15070. // forbid the `in` operator (in for loops initalization expressions)
  15071. // and provide reference for storing '=' operator inside shorthand
  15072. // property assignment in contexts where both object expression
  15073. // and object pattern might appear (so it's possible to raise
  15074. // delayed syntax error at correct position).
  15075. pp$3.parseExpression = function(forInit, refDestructuringErrors) {
  15076. var startPos = this.start, startLoc = this.startLoc;
  15077. var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
  15078. if (this.type === types.comma) {
  15079. var node = this.startNodeAt(startPos, startLoc);
  15080. node.expressions = [expr];
  15081. while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
  15082. return this.finishNode(node, "SequenceExpression")
  15083. }
  15084. return expr
  15085. };
  15086. // Parse an assignment expression. This includes applications of
  15087. // operators like `+=`.
  15088. pp$3.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
  15089. if (this.isContextual("yield")) {
  15090. if (this.inGenerator) { return this.parseYield(forInit) }
  15091. // The tokenizer will assume an expression is allowed after
  15092. // `yield`, but this isn't that kind of yield
  15093. else { this.exprAllowed = false; }
  15094. }
  15095. var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1;
  15096. if (refDestructuringErrors) {
  15097. oldParenAssign = refDestructuringErrors.parenthesizedAssign;
  15098. oldTrailingComma = refDestructuringErrors.trailingComma;
  15099. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  15100. } else {
  15101. refDestructuringErrors = new DestructuringErrors;
  15102. ownDestructuringErrors = true;
  15103. }
  15104. var startPos = this.start, startLoc = this.startLoc;
  15105. if (this.type === types.parenL || this.type === types.name) {
  15106. this.potentialArrowAt = this.start;
  15107. this.potentialArrowInForAwait = forInit === "await";
  15108. }
  15109. var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
  15110. if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
  15111. if (this.type.isAssign) {
  15112. var node = this.startNodeAt(startPos, startLoc);
  15113. node.operator = this.value;
  15114. if (this.type === types.eq)
  15115. { left = this.toAssignable(left, false, refDestructuringErrors); }
  15116. if (!ownDestructuringErrors) {
  15117. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
  15118. }
  15119. if (refDestructuringErrors.shorthandAssign >= left.start)
  15120. { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
  15121. if (this.type === types.eq)
  15122. { this.checkLValPattern(left); }
  15123. else
  15124. { this.checkLValSimple(left); }
  15125. node.left = left;
  15126. this.next();
  15127. node.right = this.parseMaybeAssign(forInit);
  15128. return this.finishNode(node, "AssignmentExpression")
  15129. } else {
  15130. if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
  15131. }
  15132. if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
  15133. if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
  15134. return left
  15135. };
  15136. // Parse a ternary conditional (`?:`) operator.
  15137. pp$3.parseMaybeConditional = function(forInit, refDestructuringErrors) {
  15138. var startPos = this.start, startLoc = this.startLoc;
  15139. var expr = this.parseExprOps(forInit, refDestructuringErrors);
  15140. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  15141. if (this.eat(types.question)) {
  15142. var node = this.startNodeAt(startPos, startLoc);
  15143. node.test = expr;
  15144. node.consequent = this.parseMaybeAssign();
  15145. this.expect(types.colon);
  15146. node.alternate = this.parseMaybeAssign(forInit);
  15147. return this.finishNode(node, "ConditionalExpression")
  15148. }
  15149. return expr
  15150. };
  15151. // Start the precedence parser.
  15152. pp$3.parseExprOps = function(forInit, refDestructuringErrors) {
  15153. var startPos = this.start, startLoc = this.startLoc;
  15154. var expr = this.parseMaybeUnary(refDestructuringErrors, false);
  15155. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  15156. return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
  15157. };
  15158. // Parse binary operators with the operator precedence parsing
  15159. // algorithm. `left` is the left-hand side of the operator.
  15160. // `minPrec` provides context that allows the function to stop and
  15161. // defer further parser to one of its callers when it encounters an
  15162. // operator that has a lower precedence than the set it is parsing.
  15163. pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
  15164. var prec = this.type.binop;
  15165. if (prec != null && (!forInit || this.type !== types._in)) {
  15166. if (prec > minPrec) {
  15167. var logical = this.type === types.logicalOR || this.type === types.logicalAND;
  15168. var coalesce = this.type === types.coalesce;
  15169. if (coalesce) {
  15170. // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
  15171. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
  15172. prec = types.logicalAND.binop;
  15173. }
  15174. var op = this.value;
  15175. this.next();
  15176. var startPos = this.start, startLoc = this.startLoc;
  15177. var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, forInit);
  15178. var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
  15179. if ((logical && this.type === types.coalesce) || (coalesce && (this.type === types.logicalOR || this.type === types.logicalAND))) {
  15180. this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
  15181. }
  15182. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
  15183. }
  15184. }
  15185. return left
  15186. };
  15187. pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  15188. var node = this.startNodeAt(startPos, startLoc);
  15189. node.left = left;
  15190. node.operator = op;
  15191. node.right = right;
  15192. return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
  15193. };
  15194. // Parse unary operators, both prefix and postfix.
  15195. pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec) {
  15196. var startPos = this.start, startLoc = this.startLoc, expr;
  15197. if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) {
  15198. expr = this.parseAwait();
  15199. sawUnary = true;
  15200. } else if (this.type.prefix) {
  15201. var node = this.startNode(), update = this.type === types.incDec;
  15202. node.operator = this.value;
  15203. node.prefix = true;
  15204. this.next();
  15205. node.argument = this.parseMaybeUnary(null, true, update);
  15206. this.checkExpressionErrors(refDestructuringErrors, true);
  15207. if (update) { this.checkLValSimple(node.argument); }
  15208. else if (this.strict && node.operator === "delete" &&
  15209. node.argument.type === "Identifier")
  15210. { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
  15211. else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
  15212. { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
  15213. else { sawUnary = true; }
  15214. expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  15215. } else {
  15216. expr = this.parseExprSubscripts(refDestructuringErrors);
  15217. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  15218. while (this.type.postfix && !this.canInsertSemicolon()) {
  15219. var node$1 = this.startNodeAt(startPos, startLoc);
  15220. node$1.operator = this.value;
  15221. node$1.prefix = false;
  15222. node$1.argument = expr;
  15223. this.checkLValSimple(expr);
  15224. this.next();
  15225. expr = this.finishNode(node$1, "UpdateExpression");
  15226. }
  15227. }
  15228. if (!incDec && this.eat(types.starstar)) {
  15229. if (sawUnary)
  15230. { this.unexpected(this.lastTokStart); }
  15231. else
  15232. { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) }
  15233. } else {
  15234. return expr
  15235. }
  15236. };
  15237. function isPrivateFieldAccess(node) {
  15238. return (
  15239. node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
  15240. node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
  15241. )
  15242. }
  15243. // Parse call, dot, and `[]`-subscript expressions.
  15244. pp$3.parseExprSubscripts = function(refDestructuringErrors) {
  15245. var startPos = this.start, startLoc = this.startLoc;
  15246. var expr = this.parseExprAtom(refDestructuringErrors);
  15247. if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
  15248. { return expr }
  15249. var result = this.parseSubscripts(expr, startPos, startLoc);
  15250. if (refDestructuringErrors && result.type === "MemberExpression") {
  15251. if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
  15252. if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
  15253. if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
  15254. }
  15255. return result
  15256. };
  15257. pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
  15258. var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
  15259. this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
  15260. this.potentialArrowAt === base.start;
  15261. var optionalChained = false;
  15262. while (true) {
  15263. var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained);
  15264. if (element.optional) { optionalChained = true; }
  15265. if (element === base || element.type === "ArrowFunctionExpression") {
  15266. if (optionalChained) {
  15267. var chainNode = this.startNodeAt(startPos, startLoc);
  15268. chainNode.expression = element;
  15269. element = this.finishNode(chainNode, "ChainExpression");
  15270. }
  15271. return element
  15272. }
  15273. base = element;
  15274. }
  15275. };
  15276. pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) {
  15277. var optionalSupported = this.options.ecmaVersion >= 11;
  15278. var optional = optionalSupported && this.eat(types.questionDot);
  15279. if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
  15280. var computed = this.eat(types.bracketL);
  15281. if (computed || (optional && this.type !== types.parenL && this.type !== types.backQuote) || this.eat(types.dot)) {
  15282. var node = this.startNodeAt(startPos, startLoc);
  15283. node.object = base;
  15284. if (computed) {
  15285. node.property = this.parseExpression();
  15286. this.expect(types.bracketR);
  15287. } else if (this.type === types.privateId && base.type !== "Super") {
  15288. node.property = this.parsePrivateIdent();
  15289. } else {
  15290. node.property = this.parseIdent(this.options.allowReserved !== "never");
  15291. }
  15292. node.computed = !!computed;
  15293. if (optionalSupported) {
  15294. node.optional = optional;
  15295. }
  15296. base = this.finishNode(node, "MemberExpression");
  15297. } else if (!noCalls && this.eat(types.parenL)) {
  15298. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  15299. this.yieldPos = 0;
  15300. this.awaitPos = 0;
  15301. this.awaitIdentPos = 0;
  15302. var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
  15303. if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types.arrow)) {
  15304. this.checkPatternErrors(refDestructuringErrors, false);
  15305. this.checkYieldAwaitInDefaultParams();
  15306. if (this.awaitIdentPos > 0)
  15307. { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
  15308. this.yieldPos = oldYieldPos;
  15309. this.awaitPos = oldAwaitPos;
  15310. this.awaitIdentPos = oldAwaitIdentPos;
  15311. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true)
  15312. }
  15313. this.checkExpressionErrors(refDestructuringErrors, true);
  15314. this.yieldPos = oldYieldPos || this.yieldPos;
  15315. this.awaitPos = oldAwaitPos || this.awaitPos;
  15316. this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
  15317. var node$1 = this.startNodeAt(startPos, startLoc);
  15318. node$1.callee = base;
  15319. node$1.arguments = exprList;
  15320. if (optionalSupported) {
  15321. node$1.optional = optional;
  15322. }
  15323. base = this.finishNode(node$1, "CallExpression");
  15324. } else if (this.type === types.backQuote) {
  15325. if (optional || optionalChained) {
  15326. this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
  15327. }
  15328. var node$2 = this.startNodeAt(startPos, startLoc);
  15329. node$2.tag = base;
  15330. node$2.quasi = this.parseTemplate({isTagged: true});
  15331. base = this.finishNode(node$2, "TaggedTemplateExpression");
  15332. }
  15333. return base
  15334. };
  15335. // Parse an atomic expression — either a single token that is an
  15336. // expression, an expression started by a keyword like `function` or
  15337. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  15338. // or `{}`.
  15339. pp$3.parseExprAtom = function(refDestructuringErrors) {
  15340. // If a division operator appears in an expression position, the
  15341. // tokenizer got confused, and we force it to read a regexp instead.
  15342. if (this.type === types.slash) { this.readRegexp(); }
  15343. var node, canBeArrow = this.potentialArrowAt === this.start;
  15344. switch (this.type) {
  15345. case types._super:
  15346. if (!this.allowSuper)
  15347. { this.raise(this.start, "'super' keyword outside a method"); }
  15348. node = this.startNode();
  15349. this.next();
  15350. if (this.type === types.parenL && !this.allowDirectSuper)
  15351. { this.raise(node.start, "super() call outside constructor of a subclass"); }
  15352. // The `super` keyword can appear at below:
  15353. // SuperProperty:
  15354. // super [ Expression ]
  15355. // super . IdentifierName
  15356. // SuperCall:
  15357. // super ( Arguments )
  15358. if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL)
  15359. { this.unexpected(); }
  15360. return this.finishNode(node, "Super")
  15361. case types._this:
  15362. node = this.startNode();
  15363. this.next();
  15364. return this.finishNode(node, "ThisExpression")
  15365. case types.name:
  15366. var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
  15367. var id = this.parseIdent(false);
  15368. if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function))
  15369. { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) }
  15370. if (canBeArrow && !this.canInsertSemicolon()) {
  15371. if (this.eat(types.arrow))
  15372. { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) }
  15373. if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc &&
  15374. (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
  15375. id = this.parseIdent(false);
  15376. if (this.canInsertSemicolon() || !this.eat(types.arrow))
  15377. { this.unexpected(); }
  15378. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
  15379. }
  15380. }
  15381. return id
  15382. case types.regexp:
  15383. var value = this.value;
  15384. node = this.parseLiteral(value.value);
  15385. node.regex = {pattern: value.pattern, flags: value.flags};
  15386. return node
  15387. case types.num: case types.string:
  15388. return this.parseLiteral(this.value)
  15389. case types._null: case types._true: case types._false:
  15390. node = this.startNode();
  15391. node.value = this.type === types._null ? null : this.type === types._true;
  15392. node.raw = this.type.keyword;
  15393. this.next();
  15394. return this.finishNode(node, "Literal")
  15395. case types.parenL:
  15396. var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);
  15397. if (refDestructuringErrors) {
  15398. if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
  15399. { refDestructuringErrors.parenthesizedAssign = start; }
  15400. if (refDestructuringErrors.parenthesizedBind < 0)
  15401. { refDestructuringErrors.parenthesizedBind = start; }
  15402. }
  15403. return expr
  15404. case types.bracketL:
  15405. node = this.startNode();
  15406. this.next();
  15407. node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors);
  15408. return this.finishNode(node, "ArrayExpression")
  15409. case types.braceL:
  15410. return this.parseObj(false, refDestructuringErrors)
  15411. case types._function:
  15412. node = this.startNode();
  15413. this.next();
  15414. return this.parseFunction(node, 0)
  15415. case types._class:
  15416. return this.parseClass(this.startNode(), false)
  15417. case types._new:
  15418. return this.parseNew()
  15419. case types.backQuote:
  15420. return this.parseTemplate()
  15421. case types._import:
  15422. if (this.options.ecmaVersion >= 11) {
  15423. return this.parseExprImport()
  15424. } else {
  15425. return this.unexpected()
  15426. }
  15427. default:
  15428. this.unexpected();
  15429. }
  15430. };
  15431. pp$3.parseExprImport = function() {
  15432. var node = this.startNode();
  15433. // Consume `import` as an identifier for `import.meta`.
  15434. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
  15435. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
  15436. var meta = this.parseIdent(true);
  15437. switch (this.type) {
  15438. case types.parenL:
  15439. return this.parseDynamicImport(node)
  15440. case types.dot:
  15441. node.meta = meta;
  15442. return this.parseImportMeta(node)
  15443. default:
  15444. this.unexpected();
  15445. }
  15446. };
  15447. pp$3.parseDynamicImport = function(node) {
  15448. this.next(); // skip `(`
  15449. // Parse node.source.
  15450. node.source = this.parseMaybeAssign();
  15451. // Verify ending.
  15452. if (!this.eat(types.parenR)) {
  15453. var errorPos = this.start;
  15454. if (this.eat(types.comma) && this.eat(types.parenR)) {
  15455. this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
  15456. } else {
  15457. this.unexpected(errorPos);
  15458. }
  15459. }
  15460. return this.finishNode(node, "ImportExpression")
  15461. };
  15462. pp$3.parseImportMeta = function(node) {
  15463. this.next(); // skip `.`
  15464. var containsEsc = this.containsEsc;
  15465. node.property = this.parseIdent(true);
  15466. if (node.property.name !== "meta")
  15467. { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
  15468. if (containsEsc)
  15469. { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
  15470. if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
  15471. { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
  15472. return this.finishNode(node, "MetaProperty")
  15473. };
  15474. pp$3.parseLiteral = function(value) {
  15475. var node = this.startNode();
  15476. node.value = value;
  15477. node.raw = this.input.slice(this.start, this.end);
  15478. if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
  15479. this.next();
  15480. return this.finishNode(node, "Literal")
  15481. };
  15482. pp$3.parseParenExpression = function() {
  15483. this.expect(types.parenL);
  15484. var val = this.parseExpression();
  15485. this.expect(types.parenR);
  15486. return val
  15487. };
  15488. pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
  15489. var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  15490. if (this.options.ecmaVersion >= 6) {
  15491. this.next();
  15492. var innerStartPos = this.start, innerStartLoc = this.startLoc;
  15493. var exprList = [], first = true, lastIsComma = false;
  15494. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
  15495. this.yieldPos = 0;
  15496. this.awaitPos = 0;
  15497. // Do not save awaitIdentPos to allow checking awaits nested in parameters
  15498. while (this.type !== types.parenR) {
  15499. first ? first = false : this.expect(types.comma);
  15500. if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) {
  15501. lastIsComma = true;
  15502. break
  15503. } else if (this.type === types.ellipsis) {
  15504. spreadStart = this.start;
  15505. exprList.push(this.parseParenItem(this.parseRestBinding()));
  15506. if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
  15507. break
  15508. } else {
  15509. exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
  15510. }
  15511. }
  15512. var innerEndPos = this.start, innerEndLoc = this.startLoc;
  15513. this.expect(types.parenR);
  15514. if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
  15515. this.checkPatternErrors(refDestructuringErrors, false);
  15516. this.checkYieldAwaitInDefaultParams();
  15517. this.yieldPos = oldYieldPos;
  15518. this.awaitPos = oldAwaitPos;
  15519. return this.parseParenArrowList(startPos, startLoc, exprList)
  15520. }
  15521. if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
  15522. if (spreadStart) { this.unexpected(spreadStart); }
  15523. this.checkExpressionErrors(refDestructuringErrors, true);
  15524. this.yieldPos = oldYieldPos || this.yieldPos;
  15525. this.awaitPos = oldAwaitPos || this.awaitPos;
  15526. if (exprList.length > 1) {
  15527. val = this.startNodeAt(innerStartPos, innerStartLoc);
  15528. val.expressions = exprList;
  15529. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  15530. } else {
  15531. val = exprList[0];
  15532. }
  15533. } else {
  15534. val = this.parseParenExpression();
  15535. }
  15536. if (this.options.preserveParens) {
  15537. var par = this.startNodeAt(startPos, startLoc);
  15538. par.expression = val;
  15539. return this.finishNode(par, "ParenthesizedExpression")
  15540. } else {
  15541. return val
  15542. }
  15543. };
  15544. pp$3.parseParenItem = function(item) {
  15545. return item
  15546. };
  15547. pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
  15548. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
  15549. };
  15550. // New's precedence is slightly tricky. It must allow its argument to
  15551. // be a `[]` or dot subscript expression, but not a call — at least,
  15552. // not without wrapping it in parentheses. Thus, it uses the noCalls
  15553. // argument to parseSubscripts to prevent it from consuming the
  15554. // argument list.
  15555. var empty$1 = [];
  15556. pp$3.parseNew = function() {
  15557. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
  15558. var node = this.startNode();
  15559. var meta = this.parseIdent(true);
  15560. if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) {
  15561. node.meta = meta;
  15562. var containsEsc = this.containsEsc;
  15563. node.property = this.parseIdent(true);
  15564. if (node.property.name !== "target")
  15565. { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
  15566. if (containsEsc)
  15567. { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
  15568. if (!this.inNonArrowFunction)
  15569. { this.raiseRecoverable(node.start, "'new.target' can only be used in functions"); }
  15570. return this.finishNode(node, "MetaProperty")
  15571. }
  15572. var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import;
  15573. node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  15574. if (isImport && node.callee.type === "ImportExpression") {
  15575. this.raise(startPos, "Cannot use new with import()");
  15576. }
  15577. if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); }
  15578. else { node.arguments = empty$1; }
  15579. return this.finishNode(node, "NewExpression")
  15580. };
  15581. // Parse template expression.
  15582. pp$3.parseTemplateElement = function(ref) {
  15583. var isTagged = ref.isTagged;
  15584. var elem = this.startNode();
  15585. if (this.type === types.invalidTemplate) {
  15586. if (!isTagged) {
  15587. this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
  15588. }
  15589. elem.value = {
  15590. raw: this.value,
  15591. cooked: null
  15592. };
  15593. } else {
  15594. elem.value = {
  15595. raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
  15596. cooked: this.value
  15597. };
  15598. }
  15599. this.next();
  15600. elem.tail = this.type === types.backQuote;
  15601. return this.finishNode(elem, "TemplateElement")
  15602. };
  15603. pp$3.parseTemplate = function(ref) {
  15604. if ( ref === void 0 ) ref = {};
  15605. var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
  15606. var node = this.startNode();
  15607. this.next();
  15608. node.expressions = [];
  15609. var curElt = this.parseTemplateElement({isTagged: isTagged});
  15610. node.quasis = [curElt];
  15611. while (!curElt.tail) {
  15612. if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); }
  15613. this.expect(types.dollarBraceL);
  15614. node.expressions.push(this.parseExpression());
  15615. this.expect(types.braceR);
  15616. node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
  15617. }
  15618. this.next();
  15619. return this.finishNode(node, "TemplateLiteral")
  15620. };
  15621. pp$3.isAsyncProp = function(prop) {
  15622. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
  15623. (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)) &&
  15624. !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  15625. };
  15626. // Parse an object literal or binding pattern.
  15627. pp$3.parseObj = function(isPattern, refDestructuringErrors) {
  15628. var node = this.startNode(), first = true, propHash = {};
  15629. node.properties = [];
  15630. this.next();
  15631. while (!this.eat(types.braceR)) {
  15632. if (!first) {
  15633. this.expect(types.comma);
  15634. if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) { break }
  15635. } else { first = false; }
  15636. var prop = this.parseProperty(isPattern, refDestructuringErrors);
  15637. if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
  15638. node.properties.push(prop);
  15639. }
  15640. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
  15641. };
  15642. pp$3.parseProperty = function(isPattern, refDestructuringErrors) {
  15643. var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  15644. if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) {
  15645. if (isPattern) {
  15646. prop.argument = this.parseIdent(false);
  15647. if (this.type === types.comma) {
  15648. this.raise(this.start, "Comma is not permitted after the rest element");
  15649. }
  15650. return this.finishNode(prop, "RestElement")
  15651. }
  15652. // To disallow parenthesized identifier via `this.toAssignable()`.
  15653. if (this.type === types.parenL && refDestructuringErrors) {
  15654. if (refDestructuringErrors.parenthesizedAssign < 0) {
  15655. refDestructuringErrors.parenthesizedAssign = this.start;
  15656. }
  15657. if (refDestructuringErrors.parenthesizedBind < 0) {
  15658. refDestructuringErrors.parenthesizedBind = this.start;
  15659. }
  15660. }
  15661. // Parse argument.
  15662. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  15663. // To disallow trailing comma via `this.toAssignable()`.
  15664. if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
  15665. refDestructuringErrors.trailingComma = this.start;
  15666. }
  15667. // Finish
  15668. return this.finishNode(prop, "SpreadElement")
  15669. }
  15670. if (this.options.ecmaVersion >= 6) {
  15671. prop.method = false;
  15672. prop.shorthand = false;
  15673. if (isPattern || refDestructuringErrors) {
  15674. startPos = this.start;
  15675. startLoc = this.startLoc;
  15676. }
  15677. if (!isPattern)
  15678. { isGenerator = this.eat(types.star); }
  15679. }
  15680. var containsEsc = this.containsEsc;
  15681. this.parsePropertyName(prop);
  15682. if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
  15683. isAsync = true;
  15684. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
  15685. this.parsePropertyName(prop, refDestructuringErrors);
  15686. } else {
  15687. isAsync = false;
  15688. }
  15689. this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  15690. return this.finishNode(prop, "Property")
  15691. };
  15692. pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  15693. if ((isGenerator || isAsync) && this.type === types.colon)
  15694. { this.unexpected(); }
  15695. if (this.eat(types.colon)) {
  15696. prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
  15697. prop.kind = "init";
  15698. } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) {
  15699. if (isPattern) { this.unexpected(); }
  15700. prop.kind = "init";
  15701. prop.method = true;
  15702. prop.value = this.parseMethod(isGenerator, isAsync);
  15703. } else if (!isPattern && !containsEsc &&
  15704. this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
  15705. (prop.key.name === "get" || prop.key.name === "set") &&
  15706. (this.type !== types.comma && this.type !== types.braceR && this.type !== types.eq)) {
  15707. if (isGenerator || isAsync) { this.unexpected(); }
  15708. prop.kind = prop.key.name;
  15709. this.parsePropertyName(prop);
  15710. prop.value = this.parseMethod(false);
  15711. var paramCount = prop.kind === "get" ? 0 : 1;
  15712. if (prop.value.params.length !== paramCount) {
  15713. var start = prop.value.start;
  15714. if (prop.kind === "get")
  15715. { this.raiseRecoverable(start, "getter should have no params"); }
  15716. else
  15717. { this.raiseRecoverable(start, "setter should have exactly one param"); }
  15718. } else {
  15719. if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
  15720. { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
  15721. }
  15722. } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
  15723. if (isGenerator || isAsync) { this.unexpected(); }
  15724. this.checkUnreserved(prop.key);
  15725. if (prop.key.name === "await" && !this.awaitIdentPos)
  15726. { this.awaitIdentPos = startPos; }
  15727. prop.kind = "init";
  15728. if (isPattern) {
  15729. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  15730. } else if (this.type === types.eq && refDestructuringErrors) {
  15731. if (refDestructuringErrors.shorthandAssign < 0)
  15732. { refDestructuringErrors.shorthandAssign = this.start; }
  15733. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  15734. } else {
  15735. prop.value = this.copyNode(prop.key);
  15736. }
  15737. prop.shorthand = true;
  15738. } else { this.unexpected(); }
  15739. };
  15740. pp$3.parsePropertyName = function(prop) {
  15741. if (this.options.ecmaVersion >= 6) {
  15742. if (this.eat(types.bracketL)) {
  15743. prop.computed = true;
  15744. prop.key = this.parseMaybeAssign();
  15745. this.expect(types.bracketR);
  15746. return prop.key
  15747. } else {
  15748. prop.computed = false;
  15749. }
  15750. }
  15751. return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
  15752. };
  15753. // Initialize empty function node.
  15754. pp$3.initFunction = function(node) {
  15755. node.id = null;
  15756. if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
  15757. if (this.options.ecmaVersion >= 8) { node.async = false; }
  15758. };
  15759. // Parse object or class method.
  15760. pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
  15761. var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  15762. this.initFunction(node);
  15763. if (this.options.ecmaVersion >= 6)
  15764. { node.generator = isGenerator; }
  15765. if (this.options.ecmaVersion >= 8)
  15766. { node.async = !!isAsync; }
  15767. this.yieldPos = 0;
  15768. this.awaitPos = 0;
  15769. this.awaitIdentPos = 0;
  15770. this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  15771. this.expect(types.parenL);
  15772. node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
  15773. this.checkYieldAwaitInDefaultParams();
  15774. this.parseFunctionBody(node, false, true);
  15775. this.yieldPos = oldYieldPos;
  15776. this.awaitPos = oldAwaitPos;
  15777. this.awaitIdentPos = oldAwaitIdentPos;
  15778. return this.finishNode(node, "FunctionExpression")
  15779. };
  15780. // Parse arrow function expression with given parameters.
  15781. pp$3.parseArrowExpression = function(node, params, isAsync) {
  15782. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  15783. this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
  15784. this.initFunction(node);
  15785. if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
  15786. this.yieldPos = 0;
  15787. this.awaitPos = 0;
  15788. this.awaitIdentPos = 0;
  15789. node.params = this.toAssignableList(params, true);
  15790. this.parseFunctionBody(node, true, false);
  15791. this.yieldPos = oldYieldPos;
  15792. this.awaitPos = oldAwaitPos;
  15793. this.awaitIdentPos = oldAwaitIdentPos;
  15794. return this.finishNode(node, "ArrowFunctionExpression")
  15795. };
  15796. // Parse function body and check parameters.
  15797. pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) {
  15798. var isExpression = isArrowFunction && this.type !== types.braceL;
  15799. var oldStrict = this.strict, useStrict = false;
  15800. if (isExpression) {
  15801. node.body = this.parseMaybeAssign();
  15802. node.expression = true;
  15803. this.checkParams(node, false);
  15804. } else {
  15805. var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
  15806. if (!oldStrict || nonSimple) {
  15807. useStrict = this.strictDirective(this.end);
  15808. // If this is a strict mode function, verify that argument names
  15809. // are not repeated, and it does not try to bind the words `eval`
  15810. // or `arguments`.
  15811. if (useStrict && nonSimple)
  15812. { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
  15813. }
  15814. // Start a new scope with regard to labels and the `inFunction`
  15815. // flag (restore them to their old value afterwards).
  15816. var oldLabels = this.labels;
  15817. this.labels = [];
  15818. if (useStrict) { this.strict = true; }
  15819. // Add the params to varDeclaredNames to ensure that an error is thrown
  15820. // if a let/const declaration in the function clashes with one of the params.
  15821. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
  15822. // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
  15823. if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
  15824. node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
  15825. node.expression = false;
  15826. this.adaptDirectivePrologue(node.body.body);
  15827. this.labels = oldLabels;
  15828. }
  15829. this.exitScope();
  15830. };
  15831. pp$3.isSimpleParamList = function(params) {
  15832. for (var i = 0, list = params; i < list.length; i += 1)
  15833. {
  15834. var param = list[i];
  15835. if (param.type !== "Identifier") { return false
  15836. } }
  15837. return true
  15838. };
  15839. // Checks function params for various disallowed patterns such as using "eval"
  15840. // or "arguments" and duplicate parameters.
  15841. pp$3.checkParams = function(node, allowDuplicates) {
  15842. var nameHash = Object.create(null);
  15843. for (var i = 0, list = node.params; i < list.length; i += 1)
  15844. {
  15845. var param = list[i];
  15846. this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
  15847. }
  15848. };
  15849. // Parses a comma-separated list of expressions, and returns them as
  15850. // an array. `close` is the token type that ends the list, and
  15851. // `allowEmpty` can be turned on to allow subsequent commas with
  15852. // nothing in between them to be parsed as `null` (which is needed
  15853. // for array literals).
  15854. pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  15855. var elts = [], first = true;
  15856. while (!this.eat(close)) {
  15857. if (!first) {
  15858. this.expect(types.comma);
  15859. if (allowTrailingComma && this.afterTrailingComma(close)) { break }
  15860. } else { first = false; }
  15861. var elt = (void 0);
  15862. if (allowEmpty && this.type === types.comma)
  15863. { elt = null; }
  15864. else if (this.type === types.ellipsis) {
  15865. elt = this.parseSpread(refDestructuringErrors);
  15866. if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0)
  15867. { refDestructuringErrors.trailingComma = this.start; }
  15868. } else {
  15869. elt = this.parseMaybeAssign(false, refDestructuringErrors);
  15870. }
  15871. elts.push(elt);
  15872. }
  15873. return elts
  15874. };
  15875. pp$3.checkUnreserved = function(ref) {
  15876. var start = ref.start;
  15877. var end = ref.end;
  15878. var name = ref.name;
  15879. if (this.inGenerator && name === "yield")
  15880. { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
  15881. if (this.inAsync && name === "await")
  15882. { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
  15883. if (this.currentThisScope().inClassFieldInit && name === "arguments")
  15884. { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
  15885. if (this.keywords.test(name))
  15886. { this.raise(start, ("Unexpected keyword '" + name + "'")); }
  15887. if (this.options.ecmaVersion < 6 &&
  15888. this.input.slice(start, end).indexOf("\\") !== -1) { return }
  15889. var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  15890. if (re.test(name)) {
  15891. if (!this.inAsync && name === "await")
  15892. { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
  15893. this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
  15894. }
  15895. };
  15896. // Parse the next token as an identifier. If `liberal` is true (used
  15897. // when parsing properties), it will also convert keywords into
  15898. // identifiers.
  15899. pp$3.parseIdent = function(liberal, isBinding) {
  15900. var node = this.startNode();
  15901. if (this.type === types.name) {
  15902. node.name = this.value;
  15903. } else if (this.type.keyword) {
  15904. node.name = this.type.keyword;
  15905. // To fix https://github.com/acornjs/acorn/issues/575
  15906. // `class` and `function` keywords push new context into this.context.
  15907. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
  15908. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
  15909. if ((node.name === "class" || node.name === "function") &&
  15910. (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
  15911. this.context.pop();
  15912. }
  15913. } else {
  15914. this.unexpected();
  15915. }
  15916. this.next(!!liberal);
  15917. this.finishNode(node, "Identifier");
  15918. if (!liberal) {
  15919. this.checkUnreserved(node);
  15920. if (node.name === "await" && !this.awaitIdentPos)
  15921. { this.awaitIdentPos = node.start; }
  15922. }
  15923. return node
  15924. };
  15925. pp$3.parsePrivateIdent = function() {
  15926. var node = this.startNode();
  15927. if (this.type === types.privateId) {
  15928. node.name = this.value;
  15929. } else {
  15930. this.unexpected();
  15931. }
  15932. this.next();
  15933. this.finishNode(node, "PrivateIdentifier");
  15934. // For validating existence
  15935. if (this.privateNameStack.length === 0) {
  15936. this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
  15937. } else {
  15938. this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
  15939. }
  15940. return node
  15941. };
  15942. // Parses yield expression inside generator.
  15943. pp$3.parseYield = function(forInit) {
  15944. if (!this.yieldPos) { this.yieldPos = this.start; }
  15945. var node = this.startNode();
  15946. this.next();
  15947. if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) {
  15948. node.delegate = false;
  15949. node.argument = null;
  15950. } else {
  15951. node.delegate = this.eat(types.star);
  15952. node.argument = this.parseMaybeAssign(forInit);
  15953. }
  15954. return this.finishNode(node, "YieldExpression")
  15955. };
  15956. pp$3.parseAwait = function() {
  15957. if (!this.awaitPos) { this.awaitPos = this.start; }
  15958. var node = this.startNode();
  15959. this.next();
  15960. node.argument = this.parseMaybeUnary(null, true);
  15961. return this.finishNode(node, "AwaitExpression")
  15962. };
  15963. var pp$4 = Parser.prototype;
  15964. // This function is used to raise exceptions on parse errors. It
  15965. // takes an offset integer (into the current `input`) to indicate
  15966. // the location of the error, attaches the position to the end
  15967. // of the error message, and then raises a `SyntaxError` with that
  15968. // message.
  15969. pp$4.raise = function(pos, message) {
  15970. var loc = getLineInfo(this.input, pos);
  15971. message += " (" + loc.line + ":" + loc.column + ")";
  15972. var err = new SyntaxError(message);
  15973. err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
  15974. throw err
  15975. };
  15976. pp$4.raiseRecoverable = pp$4.raise;
  15977. pp$4.curPosition = function() {
  15978. if (this.options.locations) {
  15979. return new Position(this.curLine, this.pos - this.lineStart)
  15980. }
  15981. };
  15982. var pp$5 = Parser.prototype;
  15983. var Scope = function Scope(flags) {
  15984. this.flags = flags;
  15985. // A list of var-declared names in the current lexical scope
  15986. this.var = [];
  15987. // A list of lexically-declared names in the current lexical scope
  15988. this.lexical = [];
  15989. // A list of lexically-declared FunctionDeclaration names in the current lexical scope
  15990. this.functions = [];
  15991. // A switch to disallow the identifier reference 'arguments'
  15992. this.inClassFieldInit = false;
  15993. };
  15994. // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
  15995. pp$5.enterScope = function(flags) {
  15996. this.scopeStack.push(new Scope(flags));
  15997. };
  15998. pp$5.exitScope = function() {
  15999. this.scopeStack.pop();
  16000. };
  16001. // The spec says:
  16002. // > At the top level of a function, or script, function declarations are
  16003. // > treated like var declarations rather than like lexical declarations.
  16004. pp$5.treatFunctionsAsVarInScope = function(scope) {
  16005. return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
  16006. };
  16007. pp$5.declareName = function(name, bindingType, pos) {
  16008. var redeclared = false;
  16009. if (bindingType === BIND_LEXICAL) {
  16010. var scope = this.currentScope();
  16011. redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  16012. scope.lexical.push(name);
  16013. if (this.inModule && (scope.flags & SCOPE_TOP))
  16014. { delete this.undefinedExports[name]; }
  16015. } else if (bindingType === BIND_SIMPLE_CATCH) {
  16016. var scope$1 = this.currentScope();
  16017. scope$1.lexical.push(name);
  16018. } else if (bindingType === BIND_FUNCTION) {
  16019. var scope$2 = this.currentScope();
  16020. if (this.treatFunctionsAsVar)
  16021. { redeclared = scope$2.lexical.indexOf(name) > -1; }
  16022. else
  16023. { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
  16024. scope$2.functions.push(name);
  16025. } else {
  16026. for (var i = this.scopeStack.length - 1; i >= 0; --i) {
  16027. var scope$3 = this.scopeStack[i];
  16028. if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
  16029. !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
  16030. redeclared = true;
  16031. break
  16032. }
  16033. scope$3.var.push(name);
  16034. if (this.inModule && (scope$3.flags & SCOPE_TOP))
  16035. { delete this.undefinedExports[name]; }
  16036. if (scope$3.flags & SCOPE_VAR) { break }
  16037. }
  16038. }
  16039. if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
  16040. };
  16041. pp$5.checkLocalExport = function(id) {
  16042. // scope.functions must be empty as Module code is always strict.
  16043. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
  16044. this.scopeStack[0].var.indexOf(id.name) === -1) {
  16045. this.undefinedExports[id.name] = id;
  16046. }
  16047. };
  16048. pp$5.currentScope = function() {
  16049. return this.scopeStack[this.scopeStack.length - 1]
  16050. };
  16051. pp$5.currentVarScope = function() {
  16052. for (var i = this.scopeStack.length - 1;; i--) {
  16053. var scope = this.scopeStack[i];
  16054. if (scope.flags & SCOPE_VAR) { return scope }
  16055. }
  16056. };
  16057. // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
  16058. pp$5.currentThisScope = function() {
  16059. for (var i = this.scopeStack.length - 1;; i--) {
  16060. var scope = this.scopeStack[i];
  16061. if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
  16062. }
  16063. };
  16064. var Node = function Node(parser, pos, loc) {
  16065. this.type = "";
  16066. this.start = pos;
  16067. this.end = 0;
  16068. if (parser.options.locations)
  16069. { this.loc = new SourceLocation(parser, loc); }
  16070. if (parser.options.directSourceFile)
  16071. { this.sourceFile = parser.options.directSourceFile; }
  16072. if (parser.options.ranges)
  16073. { this.range = [pos, 0]; }
  16074. };
  16075. // Start an AST node, attaching a start offset.
  16076. var pp$6 = Parser.prototype;
  16077. pp$6.startNode = function() {
  16078. return new Node(this, this.start, this.startLoc)
  16079. };
  16080. pp$6.startNodeAt = function(pos, loc) {
  16081. return new Node(this, pos, loc)
  16082. };
  16083. // Finish an AST node, adding `type` and `end` properties.
  16084. function finishNodeAt(node, type, pos, loc) {
  16085. node.type = type;
  16086. node.end = pos;
  16087. if (this.options.locations)
  16088. { node.loc.end = loc; }
  16089. if (this.options.ranges)
  16090. { node.range[1] = pos; }
  16091. return node
  16092. }
  16093. pp$6.finishNode = function(node, type) {
  16094. return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
  16095. };
  16096. // Finish node at given position
  16097. pp$6.finishNodeAt = function(node, type, pos, loc) {
  16098. return finishNodeAt.call(this, node, type, pos, loc)
  16099. };
  16100. pp$6.copyNode = function(node) {
  16101. var newNode = new Node(this, node.start, this.startLoc);
  16102. for (var prop in node) { newNode[prop] = node[prop]; }
  16103. return newNode
  16104. };
  16105. // The algorithm used to determine whether a regexp can appear at a
  16106. var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  16107. this.token = token;
  16108. this.isExpr = !!isExpr;
  16109. this.preserveSpace = !!preserveSpace;
  16110. this.override = override;
  16111. this.generator = !!generator;
  16112. };
  16113. var types$1 = {
  16114. b_stat: new TokContext("{", false),
  16115. b_expr: new TokContext("{", true),
  16116. b_tmpl: new TokContext("${", false),
  16117. p_stat: new TokContext("(", false),
  16118. p_expr: new TokContext("(", true),
  16119. q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  16120. f_stat: new TokContext("function", false),
  16121. f_expr: new TokContext("function", true),
  16122. f_expr_gen: new TokContext("function", true, false, null, true),
  16123. f_gen: new TokContext("function", false, false, null, true)
  16124. };
  16125. var pp$7 = Parser.prototype;
  16126. pp$7.initialContext = function() {
  16127. return [types$1.b_stat]
  16128. };
  16129. pp$7.braceIsBlock = function(prevType) {
  16130. var parent = this.curContext();
  16131. if (parent === types$1.f_expr || parent === types$1.f_stat)
  16132. { return true }
  16133. if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr))
  16134. { return !parent.isExpr }
  16135. // The check for `tt.name && exprAllowed` detects whether we are
  16136. // after a `yield` or `of` construct. See the `updateContext` for
  16137. // `tt.name`.
  16138. if (prevType === types._return || prevType === types.name && this.exprAllowed)
  16139. { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  16140. if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow)
  16141. { return true }
  16142. if (prevType === types.braceL)
  16143. { return parent === types$1.b_stat }
  16144. if (prevType === types._var || prevType === types._const || prevType === types.name)
  16145. { return false }
  16146. return !this.exprAllowed
  16147. };
  16148. pp$7.inGeneratorContext = function() {
  16149. for (var i = this.context.length - 1; i >= 1; i--) {
  16150. var context = this.context[i];
  16151. if (context.token === "function")
  16152. { return context.generator }
  16153. }
  16154. return false
  16155. };
  16156. pp$7.updateContext = function(prevType) {
  16157. var update, type = this.type;
  16158. if (type.keyword && prevType === types.dot)
  16159. { this.exprAllowed = false; }
  16160. else if (update = type.updateContext)
  16161. { update.call(this, prevType); }
  16162. else
  16163. { this.exprAllowed = type.beforeExpr; }
  16164. };
  16165. // Token-specific context update code
  16166. types.parenR.updateContext = types.braceR.updateContext = function() {
  16167. if (this.context.length === 1) {
  16168. this.exprAllowed = true;
  16169. return
  16170. }
  16171. var out = this.context.pop();
  16172. if (out === types$1.b_stat && this.curContext().token === "function") {
  16173. out = this.context.pop();
  16174. }
  16175. this.exprAllowed = !out.isExpr;
  16176. };
  16177. types.braceL.updateContext = function(prevType) {
  16178. this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);
  16179. this.exprAllowed = true;
  16180. };
  16181. types.dollarBraceL.updateContext = function() {
  16182. this.context.push(types$1.b_tmpl);
  16183. this.exprAllowed = true;
  16184. };
  16185. types.parenL.updateContext = function(prevType) {
  16186. var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
  16187. this.context.push(statementParens ? types$1.p_stat : types$1.p_expr);
  16188. this.exprAllowed = true;
  16189. };
  16190. types.incDec.updateContext = function() {
  16191. // tokExprAllowed stays unchanged
  16192. };
  16193. types._function.updateContext = types._class.updateContext = function(prevType) {
  16194. if (prevType.beforeExpr && prevType !== types._else &&
  16195. !(prevType === types.semi && this.curContext() !== types$1.p_stat) &&
  16196. !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
  16197. !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat))
  16198. { this.context.push(types$1.f_expr); }
  16199. else
  16200. { this.context.push(types$1.f_stat); }
  16201. this.exprAllowed = false;
  16202. };
  16203. types.backQuote.updateContext = function() {
  16204. if (this.curContext() === types$1.q_tmpl)
  16205. { this.context.pop(); }
  16206. else
  16207. { this.context.push(types$1.q_tmpl); }
  16208. this.exprAllowed = false;
  16209. };
  16210. types.star.updateContext = function(prevType) {
  16211. if (prevType === types._function) {
  16212. var index = this.context.length - 1;
  16213. if (this.context[index] === types$1.f_expr)
  16214. { this.context[index] = types$1.f_expr_gen; }
  16215. else
  16216. { this.context[index] = types$1.f_gen; }
  16217. }
  16218. this.exprAllowed = true;
  16219. };
  16220. types.name.updateContext = function(prevType) {
  16221. var allowed = false;
  16222. if (this.options.ecmaVersion >= 6 && prevType !== types.dot) {
  16223. if (this.value === "of" && !this.exprAllowed ||
  16224. this.value === "yield" && this.inGeneratorContext())
  16225. { allowed = true; }
  16226. }
  16227. this.exprAllowed = allowed;
  16228. };
  16229. // This file contains Unicode properties extracted from the ECMAScript
  16230. // specification. The lists are extracted like so:
  16231. // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
  16232. // #table-binary-unicode-properties
  16233. 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";
  16234. var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
  16235. var ecma11BinaryProperties = ecma10BinaryProperties;
  16236. var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
  16237. var unicodeBinaryProperties = {
  16238. 9: ecma9BinaryProperties,
  16239. 10: ecma10BinaryProperties,
  16240. 11: ecma11BinaryProperties,
  16241. 12: ecma12BinaryProperties
  16242. };
  16243. // #table-unicode-general-category-values
  16244. 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";
  16245. // #table-unicode-script-values
  16246. 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";
  16247. var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
  16248. var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
  16249. var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
  16250. var unicodeScriptValues = {
  16251. 9: ecma9ScriptValues,
  16252. 10: ecma10ScriptValues,
  16253. 11: ecma11ScriptValues,
  16254. 12: ecma12ScriptValues
  16255. };
  16256. var data = {};
  16257. function buildUnicodeData(ecmaVersion) {
  16258. var d = data[ecmaVersion] = {
  16259. binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
  16260. nonBinary: {
  16261. General_Category: wordsRegexp(unicodeGeneralCategoryValues),
  16262. Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
  16263. }
  16264. };
  16265. d.nonBinary.Script_Extensions = d.nonBinary.Script;
  16266. d.nonBinary.gc = d.nonBinary.General_Category;
  16267. d.nonBinary.sc = d.nonBinary.Script;
  16268. d.nonBinary.scx = d.nonBinary.Script_Extensions;
  16269. }
  16270. buildUnicodeData(9);
  16271. buildUnicodeData(10);
  16272. buildUnicodeData(11);
  16273. buildUnicodeData(12);
  16274. var pp$8 = Parser.prototype;
  16275. var RegExpValidationState = function RegExpValidationState(parser) {
  16276. this.parser = parser;
  16277. this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "");
  16278. this.unicodeProperties = data[parser.options.ecmaVersion >= 12 ? 12 : parser.options.ecmaVersion];
  16279. this.source = "";
  16280. this.flags = "";
  16281. this.start = 0;
  16282. this.switchU = false;
  16283. this.switchN = false;
  16284. this.pos = 0;
  16285. this.lastIntValue = 0;
  16286. this.lastStringValue = "";
  16287. this.lastAssertionIsQuantifiable = false;
  16288. this.numCapturingParens = 0;
  16289. this.maxBackReference = 0;
  16290. this.groupNames = [];
  16291. this.backReferenceNames = [];
  16292. };
  16293. RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
  16294. var unicode = flags.indexOf("u") !== -1;
  16295. this.start = start | 0;
  16296. this.source = pattern + "";
  16297. this.flags = flags;
  16298. this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
  16299. this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
  16300. };
  16301. RegExpValidationState.prototype.raise = function raise (message) {
  16302. this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
  16303. };
  16304. // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
  16305. // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
  16306. RegExpValidationState.prototype.at = function at (i, forceU) {
  16307. if ( forceU === void 0 ) forceU = false;
  16308. var s = this.source;
  16309. var l = s.length;
  16310. if (i >= l) {
  16311. return -1
  16312. }
  16313. var c = s.charCodeAt(i);
  16314. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
  16315. return c
  16316. }
  16317. var next = s.charCodeAt(i + 1);
  16318. return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
  16319. };
  16320. RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
  16321. if ( forceU === void 0 ) forceU = false;
  16322. var s = this.source;
  16323. var l = s.length;
  16324. if (i >= l) {
  16325. return l
  16326. }
  16327. var c = s.charCodeAt(i), next;
  16328. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
  16329. (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
  16330. return i + 1
  16331. }
  16332. return i + 2
  16333. };
  16334. RegExpValidationState.prototype.current = function current (forceU) {
  16335. if ( forceU === void 0 ) forceU = false;
  16336. return this.at(this.pos, forceU)
  16337. };
  16338. RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
  16339. if ( forceU === void 0 ) forceU = false;
  16340. return this.at(this.nextIndex(this.pos, forceU), forceU)
  16341. };
  16342. RegExpValidationState.prototype.advance = function advance (forceU) {
  16343. if ( forceU === void 0 ) forceU = false;
  16344. this.pos = this.nextIndex(this.pos, forceU);
  16345. };
  16346. RegExpValidationState.prototype.eat = function eat (ch, forceU) {
  16347. if ( forceU === void 0 ) forceU = false;
  16348. if (this.current(forceU) === ch) {
  16349. this.advance(forceU);
  16350. return true
  16351. }
  16352. return false
  16353. };
  16354. function codePointToString(ch) {
  16355. if (ch <= 0xFFFF) { return String.fromCharCode(ch) }
  16356. ch -= 0x10000;
  16357. return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00)
  16358. }
  16359. /**
  16360. * Validate the flags part of a given RegExpLiteral.
  16361. *
  16362. * @param {RegExpValidationState} state The state to validate RegExp.
  16363. * @returns {void}
  16364. */
  16365. pp$8.validateRegExpFlags = function(state) {
  16366. var validFlags = state.validFlags;
  16367. var flags = state.flags;
  16368. for (var i = 0; i < flags.length; i++) {
  16369. var flag = flags.charAt(i);
  16370. if (validFlags.indexOf(flag) === -1) {
  16371. this.raise(state.start, "Invalid regular expression flag");
  16372. }
  16373. if (flags.indexOf(flag, i + 1) > -1) {
  16374. this.raise(state.start, "Duplicate regular expression flag");
  16375. }
  16376. }
  16377. };
  16378. /**
  16379. * Validate the pattern part of a given RegExpLiteral.
  16380. *
  16381. * @param {RegExpValidationState} state The state to validate RegExp.
  16382. * @returns {void}
  16383. */
  16384. pp$8.validateRegExpPattern = function(state) {
  16385. this.regexp_pattern(state);
  16386. // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
  16387. // parsing contains a |GroupName|, reparse with the goal symbol
  16388. // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
  16389. // exception if _P_ did not conform to the grammar, if any elements of _P_
  16390. // were not matched by the parse, or if any Early Error conditions exist.
  16391. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
  16392. state.switchN = true;
  16393. this.regexp_pattern(state);
  16394. }
  16395. };
  16396. // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
  16397. pp$8.regexp_pattern = function(state) {
  16398. state.pos = 0;
  16399. state.lastIntValue = 0;
  16400. state.lastStringValue = "";
  16401. state.lastAssertionIsQuantifiable = false;
  16402. state.numCapturingParens = 0;
  16403. state.maxBackReference = 0;
  16404. state.groupNames.length = 0;
  16405. state.backReferenceNames.length = 0;
  16406. this.regexp_disjunction(state);
  16407. if (state.pos !== state.source.length) {
  16408. // Make the same messages as V8.
  16409. if (state.eat(0x29 /* ) */)) {
  16410. state.raise("Unmatched ')'");
  16411. }
  16412. if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
  16413. state.raise("Lone quantifier brackets");
  16414. }
  16415. }
  16416. if (state.maxBackReference > state.numCapturingParens) {
  16417. state.raise("Invalid escape");
  16418. }
  16419. for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
  16420. var name = list[i];
  16421. if (state.groupNames.indexOf(name) === -1) {
  16422. state.raise("Invalid named capture referenced");
  16423. }
  16424. }
  16425. };
  16426. // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
  16427. pp$8.regexp_disjunction = function(state) {
  16428. this.regexp_alternative(state);
  16429. while (state.eat(0x7C /* | */)) {
  16430. this.regexp_alternative(state);
  16431. }
  16432. // Make the same message as V8.
  16433. if (this.regexp_eatQuantifier(state, true)) {
  16434. state.raise("Nothing to repeat");
  16435. }
  16436. if (state.eat(0x7B /* { */)) {
  16437. state.raise("Lone quantifier brackets");
  16438. }
  16439. };
  16440. // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
  16441. pp$8.regexp_alternative = function(state) {
  16442. while (state.pos < state.source.length && this.regexp_eatTerm(state))
  16443. { }
  16444. };
  16445. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
  16446. pp$8.regexp_eatTerm = function(state) {
  16447. if (this.regexp_eatAssertion(state)) {
  16448. // Handle `QuantifiableAssertion Quantifier` alternative.
  16449. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
  16450. // is a QuantifiableAssertion.
  16451. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
  16452. // Make the same message as V8.
  16453. if (state.switchU) {
  16454. state.raise("Invalid quantifier");
  16455. }
  16456. }
  16457. return true
  16458. }
  16459. if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
  16460. this.regexp_eatQuantifier(state);
  16461. return true
  16462. }
  16463. return false
  16464. };
  16465. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
  16466. pp$8.regexp_eatAssertion = function(state) {
  16467. var start = state.pos;
  16468. state.lastAssertionIsQuantifiable = false;
  16469. // ^, $
  16470. if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
  16471. return true
  16472. }
  16473. // \b \B
  16474. if (state.eat(0x5C /* \ */)) {
  16475. if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
  16476. return true
  16477. }
  16478. state.pos = start;
  16479. }
  16480. // Lookahead / Lookbehind
  16481. if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
  16482. var lookbehind = false;
  16483. if (this.options.ecmaVersion >= 9) {
  16484. lookbehind = state.eat(0x3C /* < */);
  16485. }
  16486. if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
  16487. this.regexp_disjunction(state);
  16488. if (!state.eat(0x29 /* ) */)) {
  16489. state.raise("Unterminated group");
  16490. }
  16491. state.lastAssertionIsQuantifiable = !lookbehind;
  16492. return true
  16493. }
  16494. }
  16495. state.pos = start;
  16496. return false
  16497. };
  16498. // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
  16499. pp$8.regexp_eatQuantifier = function(state, noError) {
  16500. if ( noError === void 0 ) noError = false;
  16501. if (this.regexp_eatQuantifierPrefix(state, noError)) {
  16502. state.eat(0x3F /* ? */);
  16503. return true
  16504. }
  16505. return false
  16506. };
  16507. // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
  16508. pp$8.regexp_eatQuantifierPrefix = function(state, noError) {
  16509. return (
  16510. state.eat(0x2A /* * */) ||
  16511. state.eat(0x2B /* + */) ||
  16512. state.eat(0x3F /* ? */) ||
  16513. this.regexp_eatBracedQuantifier(state, noError)
  16514. )
  16515. };
  16516. pp$8.regexp_eatBracedQuantifier = function(state, noError) {
  16517. var start = state.pos;
  16518. if (state.eat(0x7B /* { */)) {
  16519. var min = 0, max = -1;
  16520. if (this.regexp_eatDecimalDigits(state)) {
  16521. min = state.lastIntValue;
  16522. if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
  16523. max = state.lastIntValue;
  16524. }
  16525. if (state.eat(0x7D /* } */)) {
  16526. // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
  16527. if (max !== -1 && max < min && !noError) {
  16528. state.raise("numbers out of order in {} quantifier");
  16529. }
  16530. return true
  16531. }
  16532. }
  16533. if (state.switchU && !noError) {
  16534. state.raise("Incomplete quantifier");
  16535. }
  16536. state.pos = start;
  16537. }
  16538. return false
  16539. };
  16540. // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
  16541. pp$8.regexp_eatAtom = function(state) {
  16542. return (
  16543. this.regexp_eatPatternCharacters(state) ||
  16544. state.eat(0x2E /* . */) ||
  16545. this.regexp_eatReverseSolidusAtomEscape(state) ||
  16546. this.regexp_eatCharacterClass(state) ||
  16547. this.regexp_eatUncapturingGroup(state) ||
  16548. this.regexp_eatCapturingGroup(state)
  16549. )
  16550. };
  16551. pp$8.regexp_eatReverseSolidusAtomEscape = function(state) {
  16552. var start = state.pos;
  16553. if (state.eat(0x5C /* \ */)) {
  16554. if (this.regexp_eatAtomEscape(state)) {
  16555. return true
  16556. }
  16557. state.pos = start;
  16558. }
  16559. return false
  16560. };
  16561. pp$8.regexp_eatUncapturingGroup = function(state) {
  16562. var start = state.pos;
  16563. if (state.eat(0x28 /* ( */)) {
  16564. if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
  16565. this.regexp_disjunction(state);
  16566. if (state.eat(0x29 /* ) */)) {
  16567. return true
  16568. }
  16569. state.raise("Unterminated group");
  16570. }
  16571. state.pos = start;
  16572. }
  16573. return false
  16574. };
  16575. pp$8.regexp_eatCapturingGroup = function(state) {
  16576. if (state.eat(0x28 /* ( */)) {
  16577. if (this.options.ecmaVersion >= 9) {
  16578. this.regexp_groupSpecifier(state);
  16579. } else if (state.current() === 0x3F /* ? */) {
  16580. state.raise("Invalid group");
  16581. }
  16582. this.regexp_disjunction(state);
  16583. if (state.eat(0x29 /* ) */)) {
  16584. state.numCapturingParens += 1;
  16585. return true
  16586. }
  16587. state.raise("Unterminated group");
  16588. }
  16589. return false
  16590. };
  16591. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
  16592. pp$8.regexp_eatExtendedAtom = function(state) {
  16593. return (
  16594. state.eat(0x2E /* . */) ||
  16595. this.regexp_eatReverseSolidusAtomEscape(state) ||
  16596. this.regexp_eatCharacterClass(state) ||
  16597. this.regexp_eatUncapturingGroup(state) ||
  16598. this.regexp_eatCapturingGroup(state) ||
  16599. this.regexp_eatInvalidBracedQuantifier(state) ||
  16600. this.regexp_eatExtendedPatternCharacter(state)
  16601. )
  16602. };
  16603. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
  16604. pp$8.regexp_eatInvalidBracedQuantifier = function(state) {
  16605. if (this.regexp_eatBracedQuantifier(state, true)) {
  16606. state.raise("Nothing to repeat");
  16607. }
  16608. return false
  16609. };
  16610. // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
  16611. pp$8.regexp_eatSyntaxCharacter = function(state) {
  16612. var ch = state.current();
  16613. if (isSyntaxCharacter(ch)) {
  16614. state.lastIntValue = ch;
  16615. state.advance();
  16616. return true
  16617. }
  16618. return false
  16619. };
  16620. function isSyntaxCharacter(ch) {
  16621. return (
  16622. ch === 0x24 /* $ */ ||
  16623. ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
  16624. ch === 0x2E /* . */ ||
  16625. ch === 0x3F /* ? */ ||
  16626. ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
  16627. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  16628. )
  16629. }
  16630. // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
  16631. // But eat eager.
  16632. pp$8.regexp_eatPatternCharacters = function(state) {
  16633. var start = state.pos;
  16634. var ch = 0;
  16635. while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
  16636. state.advance();
  16637. }
  16638. return state.pos !== start
  16639. };
  16640. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
  16641. pp$8.regexp_eatExtendedPatternCharacter = function(state) {
  16642. var ch = state.current();
  16643. if (
  16644. ch !== -1 &&
  16645. ch !== 0x24 /* $ */ &&
  16646. !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
  16647. ch !== 0x2E /* . */ &&
  16648. ch !== 0x3F /* ? */ &&
  16649. ch !== 0x5B /* [ */ &&
  16650. ch !== 0x5E /* ^ */ &&
  16651. ch !== 0x7C /* | */
  16652. ) {
  16653. state.advance();
  16654. return true
  16655. }
  16656. return false
  16657. };
  16658. // GroupSpecifier ::
  16659. // [empty]
  16660. // `?` GroupName
  16661. pp$8.regexp_groupSpecifier = function(state) {
  16662. if (state.eat(0x3F /* ? */)) {
  16663. if (this.regexp_eatGroupName(state)) {
  16664. if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
  16665. state.raise("Duplicate capture group name");
  16666. }
  16667. state.groupNames.push(state.lastStringValue);
  16668. return
  16669. }
  16670. state.raise("Invalid group");
  16671. }
  16672. };
  16673. // GroupName ::
  16674. // `<` RegExpIdentifierName `>`
  16675. // Note: this updates `state.lastStringValue` property with the eaten name.
  16676. pp$8.regexp_eatGroupName = function(state) {
  16677. state.lastStringValue = "";
  16678. if (state.eat(0x3C /* < */)) {
  16679. if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
  16680. return true
  16681. }
  16682. state.raise("Invalid capture group name");
  16683. }
  16684. return false
  16685. };
  16686. // RegExpIdentifierName ::
  16687. // RegExpIdentifierStart
  16688. // RegExpIdentifierName RegExpIdentifierPart
  16689. // Note: this updates `state.lastStringValue` property with the eaten name.
  16690. pp$8.regexp_eatRegExpIdentifierName = function(state) {
  16691. state.lastStringValue = "";
  16692. if (this.regexp_eatRegExpIdentifierStart(state)) {
  16693. state.lastStringValue += codePointToString(state.lastIntValue);
  16694. while (this.regexp_eatRegExpIdentifierPart(state)) {
  16695. state.lastStringValue += codePointToString(state.lastIntValue);
  16696. }
  16697. return true
  16698. }
  16699. return false
  16700. };
  16701. // RegExpIdentifierStart ::
  16702. // UnicodeIDStart
  16703. // `$`
  16704. // `_`
  16705. // `\` RegExpUnicodeEscapeSequence[+U]
  16706. pp$8.regexp_eatRegExpIdentifierStart = function(state) {
  16707. var start = state.pos;
  16708. var forceU = this.options.ecmaVersion >= 11;
  16709. var ch = state.current(forceU);
  16710. state.advance(forceU);
  16711. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  16712. ch = state.lastIntValue;
  16713. }
  16714. if (isRegExpIdentifierStart(ch)) {
  16715. state.lastIntValue = ch;
  16716. return true
  16717. }
  16718. state.pos = start;
  16719. return false
  16720. };
  16721. function isRegExpIdentifierStart(ch) {
  16722. return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
  16723. }
  16724. // RegExpIdentifierPart ::
  16725. // UnicodeIDContinue
  16726. // `$`
  16727. // `_`
  16728. // `\` RegExpUnicodeEscapeSequence[+U]
  16729. // <ZWNJ>
  16730. // <ZWJ>
  16731. pp$8.regexp_eatRegExpIdentifierPart = function(state) {
  16732. var start = state.pos;
  16733. var forceU = this.options.ecmaVersion >= 11;
  16734. var ch = state.current(forceU);
  16735. state.advance(forceU);
  16736. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  16737. ch = state.lastIntValue;
  16738. }
  16739. if (isRegExpIdentifierPart(ch)) {
  16740. state.lastIntValue = ch;
  16741. return true
  16742. }
  16743. state.pos = start;
  16744. return false
  16745. };
  16746. function isRegExpIdentifierPart(ch) {
  16747. return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
  16748. }
  16749. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
  16750. pp$8.regexp_eatAtomEscape = function(state) {
  16751. if (
  16752. this.regexp_eatBackReference(state) ||
  16753. this.regexp_eatCharacterClassEscape(state) ||
  16754. this.regexp_eatCharacterEscape(state) ||
  16755. (state.switchN && this.regexp_eatKGroupName(state))
  16756. ) {
  16757. return true
  16758. }
  16759. if (state.switchU) {
  16760. // Make the same message as V8.
  16761. if (state.current() === 0x63 /* c */) {
  16762. state.raise("Invalid unicode escape");
  16763. }
  16764. state.raise("Invalid escape");
  16765. }
  16766. return false
  16767. };
  16768. pp$8.regexp_eatBackReference = function(state) {
  16769. var start = state.pos;
  16770. if (this.regexp_eatDecimalEscape(state)) {
  16771. var n = state.lastIntValue;
  16772. if (state.switchU) {
  16773. // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
  16774. if (n > state.maxBackReference) {
  16775. state.maxBackReference = n;
  16776. }
  16777. return true
  16778. }
  16779. if (n <= state.numCapturingParens) {
  16780. return true
  16781. }
  16782. state.pos = start;
  16783. }
  16784. return false
  16785. };
  16786. pp$8.regexp_eatKGroupName = function(state) {
  16787. if (state.eat(0x6B /* k */)) {
  16788. if (this.regexp_eatGroupName(state)) {
  16789. state.backReferenceNames.push(state.lastStringValue);
  16790. return true
  16791. }
  16792. state.raise("Invalid named reference");
  16793. }
  16794. return false
  16795. };
  16796. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
  16797. pp$8.regexp_eatCharacterEscape = function(state) {
  16798. return (
  16799. this.regexp_eatControlEscape(state) ||
  16800. this.regexp_eatCControlLetter(state) ||
  16801. this.regexp_eatZero(state) ||
  16802. this.regexp_eatHexEscapeSequence(state) ||
  16803. this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
  16804. (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
  16805. this.regexp_eatIdentityEscape(state)
  16806. )
  16807. };
  16808. pp$8.regexp_eatCControlLetter = function(state) {
  16809. var start = state.pos;
  16810. if (state.eat(0x63 /* c */)) {
  16811. if (this.regexp_eatControlLetter(state)) {
  16812. return true
  16813. }
  16814. state.pos = start;
  16815. }
  16816. return false
  16817. };
  16818. pp$8.regexp_eatZero = function(state) {
  16819. if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
  16820. state.lastIntValue = 0;
  16821. state.advance();
  16822. return true
  16823. }
  16824. return false
  16825. };
  16826. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
  16827. pp$8.regexp_eatControlEscape = function(state) {
  16828. var ch = state.current();
  16829. if (ch === 0x74 /* t */) {
  16830. state.lastIntValue = 0x09; /* \t */
  16831. state.advance();
  16832. return true
  16833. }
  16834. if (ch === 0x6E /* n */) {
  16835. state.lastIntValue = 0x0A; /* \n */
  16836. state.advance();
  16837. return true
  16838. }
  16839. if (ch === 0x76 /* v */) {
  16840. state.lastIntValue = 0x0B; /* \v */
  16841. state.advance();
  16842. return true
  16843. }
  16844. if (ch === 0x66 /* f */) {
  16845. state.lastIntValue = 0x0C; /* \f */
  16846. state.advance();
  16847. return true
  16848. }
  16849. if (ch === 0x72 /* r */) {
  16850. state.lastIntValue = 0x0D; /* \r */
  16851. state.advance();
  16852. return true
  16853. }
  16854. return false
  16855. };
  16856. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
  16857. pp$8.regexp_eatControlLetter = function(state) {
  16858. var ch = state.current();
  16859. if (isControlLetter(ch)) {
  16860. state.lastIntValue = ch % 0x20;
  16861. state.advance();
  16862. return true
  16863. }
  16864. return false
  16865. };
  16866. function isControlLetter(ch) {
  16867. return (
  16868. (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
  16869. (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
  16870. )
  16871. }
  16872. // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
  16873. pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
  16874. if ( forceU === void 0 ) forceU = false;
  16875. var start = state.pos;
  16876. var switchU = forceU || state.switchU;
  16877. if (state.eat(0x75 /* u */)) {
  16878. if (this.regexp_eatFixedHexDigits(state, 4)) {
  16879. var lead = state.lastIntValue;
  16880. if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
  16881. var leadSurrogateEnd = state.pos;
  16882. if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
  16883. var trail = state.lastIntValue;
  16884. if (trail >= 0xDC00 && trail <= 0xDFFF) {
  16885. state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
  16886. return true
  16887. }
  16888. }
  16889. state.pos = leadSurrogateEnd;
  16890. state.lastIntValue = lead;
  16891. }
  16892. return true
  16893. }
  16894. if (
  16895. switchU &&
  16896. state.eat(0x7B /* { */) &&
  16897. this.regexp_eatHexDigits(state) &&
  16898. state.eat(0x7D /* } */) &&
  16899. isValidUnicode(state.lastIntValue)
  16900. ) {
  16901. return true
  16902. }
  16903. if (switchU) {
  16904. state.raise("Invalid unicode escape");
  16905. }
  16906. state.pos = start;
  16907. }
  16908. return false
  16909. };
  16910. function isValidUnicode(ch) {
  16911. return ch >= 0 && ch <= 0x10FFFF
  16912. }
  16913. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
  16914. pp$8.regexp_eatIdentityEscape = function(state) {
  16915. if (state.switchU) {
  16916. if (this.regexp_eatSyntaxCharacter(state)) {
  16917. return true
  16918. }
  16919. if (state.eat(0x2F /* / */)) {
  16920. state.lastIntValue = 0x2F; /* / */
  16921. return true
  16922. }
  16923. return false
  16924. }
  16925. var ch = state.current();
  16926. if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
  16927. state.lastIntValue = ch;
  16928. state.advance();
  16929. return true
  16930. }
  16931. return false
  16932. };
  16933. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
  16934. pp$8.regexp_eatDecimalEscape = function(state) {
  16935. state.lastIntValue = 0;
  16936. var ch = state.current();
  16937. if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
  16938. do {
  16939. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  16940. state.advance();
  16941. } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
  16942. return true
  16943. }
  16944. return false
  16945. };
  16946. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
  16947. pp$8.regexp_eatCharacterClassEscape = function(state) {
  16948. var ch = state.current();
  16949. if (isCharacterClassEscape(ch)) {
  16950. state.lastIntValue = -1;
  16951. state.advance();
  16952. return true
  16953. }
  16954. if (
  16955. state.switchU &&
  16956. this.options.ecmaVersion >= 9 &&
  16957. (ch === 0x50 /* P */ || ch === 0x70 /* p */)
  16958. ) {
  16959. state.lastIntValue = -1;
  16960. state.advance();
  16961. if (
  16962. state.eat(0x7B /* { */) &&
  16963. this.regexp_eatUnicodePropertyValueExpression(state) &&
  16964. state.eat(0x7D /* } */)
  16965. ) {
  16966. return true
  16967. }
  16968. state.raise("Invalid property name");
  16969. }
  16970. return false
  16971. };
  16972. function isCharacterClassEscape(ch) {
  16973. return (
  16974. ch === 0x64 /* d */ ||
  16975. ch === 0x44 /* D */ ||
  16976. ch === 0x73 /* s */ ||
  16977. ch === 0x53 /* S */ ||
  16978. ch === 0x77 /* w */ ||
  16979. ch === 0x57 /* W */
  16980. )
  16981. }
  16982. // UnicodePropertyValueExpression ::
  16983. // UnicodePropertyName `=` UnicodePropertyValue
  16984. // LoneUnicodePropertyNameOrValue
  16985. pp$8.regexp_eatUnicodePropertyValueExpression = function(state) {
  16986. var start = state.pos;
  16987. // UnicodePropertyName `=` UnicodePropertyValue
  16988. if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
  16989. var name = state.lastStringValue;
  16990. if (this.regexp_eatUnicodePropertyValue(state)) {
  16991. var value = state.lastStringValue;
  16992. this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
  16993. return true
  16994. }
  16995. }
  16996. state.pos = start;
  16997. // LoneUnicodePropertyNameOrValue
  16998. if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
  16999. var nameOrValue = state.lastStringValue;
  17000. this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
  17001. return true
  17002. }
  17003. return false
  17004. };
  17005. pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  17006. if (!has(state.unicodeProperties.nonBinary, name))
  17007. { state.raise("Invalid property name"); }
  17008. if (!state.unicodeProperties.nonBinary[name].test(value))
  17009. { state.raise("Invalid property value"); }
  17010. };
  17011. pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  17012. if (!state.unicodeProperties.binary.test(nameOrValue))
  17013. { state.raise("Invalid property name"); }
  17014. };
  17015. // UnicodePropertyName ::
  17016. // UnicodePropertyNameCharacters
  17017. pp$8.regexp_eatUnicodePropertyName = function(state) {
  17018. var ch = 0;
  17019. state.lastStringValue = "";
  17020. while (isUnicodePropertyNameCharacter(ch = state.current())) {
  17021. state.lastStringValue += codePointToString(ch);
  17022. state.advance();
  17023. }
  17024. return state.lastStringValue !== ""
  17025. };
  17026. function isUnicodePropertyNameCharacter(ch) {
  17027. return isControlLetter(ch) || ch === 0x5F /* _ */
  17028. }
  17029. // UnicodePropertyValue ::
  17030. // UnicodePropertyValueCharacters
  17031. pp$8.regexp_eatUnicodePropertyValue = function(state) {
  17032. var ch = 0;
  17033. state.lastStringValue = "";
  17034. while (isUnicodePropertyValueCharacter(ch = state.current())) {
  17035. state.lastStringValue += codePointToString(ch);
  17036. state.advance();
  17037. }
  17038. return state.lastStringValue !== ""
  17039. };
  17040. function isUnicodePropertyValueCharacter(ch) {
  17041. return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
  17042. }
  17043. // LoneUnicodePropertyNameOrValue ::
  17044. // UnicodePropertyValueCharacters
  17045. pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  17046. return this.regexp_eatUnicodePropertyValue(state)
  17047. };
  17048. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
  17049. pp$8.regexp_eatCharacterClass = function(state) {
  17050. if (state.eat(0x5B /* [ */)) {
  17051. state.eat(0x5E /* ^ */);
  17052. this.regexp_classRanges(state);
  17053. if (state.eat(0x5D /* ] */)) {
  17054. return true
  17055. }
  17056. // Unreachable since it threw "unterminated regular expression" error before.
  17057. state.raise("Unterminated character class");
  17058. }
  17059. return false
  17060. };
  17061. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
  17062. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
  17063. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
  17064. pp$8.regexp_classRanges = function(state) {
  17065. while (this.regexp_eatClassAtom(state)) {
  17066. var left = state.lastIntValue;
  17067. if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
  17068. var right = state.lastIntValue;
  17069. if (state.switchU && (left === -1 || right === -1)) {
  17070. state.raise("Invalid character class");
  17071. }
  17072. if (left !== -1 && right !== -1 && left > right) {
  17073. state.raise("Range out of order in character class");
  17074. }
  17075. }
  17076. }
  17077. };
  17078. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
  17079. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
  17080. pp$8.regexp_eatClassAtom = function(state) {
  17081. var start = state.pos;
  17082. if (state.eat(0x5C /* \ */)) {
  17083. if (this.regexp_eatClassEscape(state)) {
  17084. return true
  17085. }
  17086. if (state.switchU) {
  17087. // Make the same message as V8.
  17088. var ch$1 = state.current();
  17089. if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
  17090. state.raise("Invalid class escape");
  17091. }
  17092. state.raise("Invalid escape");
  17093. }
  17094. state.pos = start;
  17095. }
  17096. var ch = state.current();
  17097. if (ch !== 0x5D /* ] */) {
  17098. state.lastIntValue = ch;
  17099. state.advance();
  17100. return true
  17101. }
  17102. return false
  17103. };
  17104. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
  17105. pp$8.regexp_eatClassEscape = function(state) {
  17106. var start = state.pos;
  17107. if (state.eat(0x62 /* b */)) {
  17108. state.lastIntValue = 0x08; /* <BS> */
  17109. return true
  17110. }
  17111. if (state.switchU && state.eat(0x2D /* - */)) {
  17112. state.lastIntValue = 0x2D; /* - */
  17113. return true
  17114. }
  17115. if (!state.switchU && state.eat(0x63 /* c */)) {
  17116. if (this.regexp_eatClassControlLetter(state)) {
  17117. return true
  17118. }
  17119. state.pos = start;
  17120. }
  17121. return (
  17122. this.regexp_eatCharacterClassEscape(state) ||
  17123. this.regexp_eatCharacterEscape(state)
  17124. )
  17125. };
  17126. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
  17127. pp$8.regexp_eatClassControlLetter = function(state) {
  17128. var ch = state.current();
  17129. if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
  17130. state.lastIntValue = ch % 0x20;
  17131. state.advance();
  17132. return true
  17133. }
  17134. return false
  17135. };
  17136. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  17137. pp$8.regexp_eatHexEscapeSequence = function(state) {
  17138. var start = state.pos;
  17139. if (state.eat(0x78 /* x */)) {
  17140. if (this.regexp_eatFixedHexDigits(state, 2)) {
  17141. return true
  17142. }
  17143. if (state.switchU) {
  17144. state.raise("Invalid escape");
  17145. }
  17146. state.pos = start;
  17147. }
  17148. return false
  17149. };
  17150. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
  17151. pp$8.regexp_eatDecimalDigits = function(state) {
  17152. var start = state.pos;
  17153. var ch = 0;
  17154. state.lastIntValue = 0;
  17155. while (isDecimalDigit(ch = state.current())) {
  17156. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  17157. state.advance();
  17158. }
  17159. return state.pos !== start
  17160. };
  17161. function isDecimalDigit(ch) {
  17162. return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
  17163. }
  17164. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
  17165. pp$8.regexp_eatHexDigits = function(state) {
  17166. var start = state.pos;
  17167. var ch = 0;
  17168. state.lastIntValue = 0;
  17169. while (isHexDigit(ch = state.current())) {
  17170. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  17171. state.advance();
  17172. }
  17173. return state.pos !== start
  17174. };
  17175. function isHexDigit(ch) {
  17176. return (
  17177. (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
  17178. (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
  17179. (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
  17180. )
  17181. }
  17182. function hexToInt(ch) {
  17183. if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
  17184. return 10 + (ch - 0x41 /* A */)
  17185. }
  17186. if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
  17187. return 10 + (ch - 0x61 /* a */)
  17188. }
  17189. return ch - 0x30 /* 0 */
  17190. }
  17191. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
  17192. // Allows only 0-377(octal) i.e. 0-255(decimal).
  17193. pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) {
  17194. if (this.regexp_eatOctalDigit(state)) {
  17195. var n1 = state.lastIntValue;
  17196. if (this.regexp_eatOctalDigit(state)) {
  17197. var n2 = state.lastIntValue;
  17198. if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
  17199. state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
  17200. } else {
  17201. state.lastIntValue = n1 * 8 + n2;
  17202. }
  17203. } else {
  17204. state.lastIntValue = n1;
  17205. }
  17206. return true
  17207. }
  17208. return false
  17209. };
  17210. // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
  17211. pp$8.regexp_eatOctalDigit = function(state) {
  17212. var ch = state.current();
  17213. if (isOctalDigit(ch)) {
  17214. state.lastIntValue = ch - 0x30; /* 0 */
  17215. state.advance();
  17216. return true
  17217. }
  17218. state.lastIntValue = 0;
  17219. return false
  17220. };
  17221. function isOctalDigit(ch) {
  17222. return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
  17223. }
  17224. // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
  17225. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
  17226. // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  17227. pp$8.regexp_eatFixedHexDigits = function(state, length) {
  17228. var start = state.pos;
  17229. state.lastIntValue = 0;
  17230. for (var i = 0; i < length; ++i) {
  17231. var ch = state.current();
  17232. if (!isHexDigit(ch)) {
  17233. state.pos = start;
  17234. return false
  17235. }
  17236. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  17237. state.advance();
  17238. }
  17239. return true
  17240. };
  17241. // Object type used to represent tokens. Note that normally, tokens
  17242. // simply exist as properties on the parser object. This is only
  17243. // used for the onToken callback and the external tokenizer.
  17244. var Token = function Token(p) {
  17245. this.type = p.type;
  17246. this.value = p.value;
  17247. this.start = p.start;
  17248. this.end = p.end;
  17249. if (p.options.locations)
  17250. { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
  17251. if (p.options.ranges)
  17252. { this.range = [p.start, p.end]; }
  17253. };
  17254. // ## Tokenizer
  17255. var pp$9 = Parser.prototype;
  17256. // Move to the next token
  17257. pp$9.next = function(ignoreEscapeSequenceInKeyword) {
  17258. if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
  17259. { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
  17260. if (this.options.onToken)
  17261. { this.options.onToken(new Token(this)); }
  17262. this.lastTokEnd = this.end;
  17263. this.lastTokStart = this.start;
  17264. this.lastTokEndLoc = this.endLoc;
  17265. this.lastTokStartLoc = this.startLoc;
  17266. this.nextToken();
  17267. };
  17268. pp$9.getToken = function() {
  17269. this.next();
  17270. return new Token(this)
  17271. };
  17272. // If we're in an ES6 environment, make parsers iterable
  17273. if (typeof Symbol !== "undefined")
  17274. { pp$9[Symbol.iterator] = function() {
  17275. var this$1$1 = this;
  17276. return {
  17277. next: function () {
  17278. var token = this$1$1.getToken();
  17279. return {
  17280. done: token.type === types.eof,
  17281. value: token
  17282. }
  17283. }
  17284. }
  17285. }; }
  17286. // Toggle strict mode. Re-reads the next number or string to please
  17287. // pedantic tests (`"use strict"; 010;` should fail).
  17288. pp$9.curContext = function() {
  17289. return this.context[this.context.length - 1]
  17290. };
  17291. // Read a single token, updating the parser object's token-related
  17292. // properties.
  17293. pp$9.nextToken = function() {
  17294. var curContext = this.curContext();
  17295. if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
  17296. this.start = this.pos;
  17297. if (this.options.locations) { this.startLoc = this.curPosition(); }
  17298. if (this.pos >= this.input.length) { return this.finishToken(types.eof) }
  17299. if (curContext.override) { return curContext.override(this) }
  17300. else { this.readToken(this.fullCharCodeAtPos()); }
  17301. };
  17302. pp$9.readToken = function(code) {
  17303. // Identifier or keyword. '\uXXXX' sequences are allowed in
  17304. // identifiers, so '\' also dispatches to that.
  17305. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
  17306. { return this.readWord() }
  17307. return this.getTokenFromCode(code)
  17308. };
  17309. pp$9.fullCharCodeAtPos = function() {
  17310. var code = this.input.charCodeAt(this.pos);
  17311. if (code <= 0xd7ff || code >= 0xdc00) { return code }
  17312. var next = this.input.charCodeAt(this.pos + 1);
  17313. return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
  17314. };
  17315. pp$9.skipBlockComment = function() {
  17316. var startLoc = this.options.onComment && this.curPosition();
  17317. var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  17318. if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
  17319. this.pos = end + 2;
  17320. if (this.options.locations) {
  17321. lineBreakG.lastIndex = start;
  17322. var match;
  17323. while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
  17324. ++this.curLine;
  17325. this.lineStart = match.index + match[0].length;
  17326. }
  17327. }
  17328. if (this.options.onComment)
  17329. { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
  17330. startLoc, this.curPosition()); }
  17331. };
  17332. pp$9.skipLineComment = function(startSkip) {
  17333. var start = this.pos;
  17334. var startLoc = this.options.onComment && this.curPosition();
  17335. var ch = this.input.charCodeAt(this.pos += startSkip);
  17336. while (this.pos < this.input.length && !isNewLine(ch)) {
  17337. ch = this.input.charCodeAt(++this.pos);
  17338. }
  17339. if (this.options.onComment)
  17340. { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
  17341. startLoc, this.curPosition()); }
  17342. };
  17343. // Called at the start of the parse and after every token. Skips
  17344. // whitespace and comments, and.
  17345. pp$9.skipSpace = function() {
  17346. loop: while (this.pos < this.input.length) {
  17347. var ch = this.input.charCodeAt(this.pos);
  17348. switch (ch) {
  17349. case 32: case 160: // ' '
  17350. ++this.pos;
  17351. break
  17352. case 13:
  17353. if (this.input.charCodeAt(this.pos + 1) === 10) {
  17354. ++this.pos;
  17355. }
  17356. case 10: case 8232: case 8233:
  17357. ++this.pos;
  17358. if (this.options.locations) {
  17359. ++this.curLine;
  17360. this.lineStart = this.pos;
  17361. }
  17362. break
  17363. case 47: // '/'
  17364. switch (this.input.charCodeAt(this.pos + 1)) {
  17365. case 42: // '*'
  17366. this.skipBlockComment();
  17367. break
  17368. case 47:
  17369. this.skipLineComment(2);
  17370. break
  17371. default:
  17372. break loop
  17373. }
  17374. break
  17375. default:
  17376. if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  17377. ++this.pos;
  17378. } else {
  17379. break loop
  17380. }
  17381. }
  17382. }
  17383. };
  17384. // Called at the end of every token. Sets `end`, `val`, and
  17385. // maintains `context` and `exprAllowed`, and skips the space after
  17386. // the token, so that the next one's `start` will point at the
  17387. // right position.
  17388. pp$9.finishToken = function(type, val) {
  17389. this.end = this.pos;
  17390. if (this.options.locations) { this.endLoc = this.curPosition(); }
  17391. var prevType = this.type;
  17392. this.type = type;
  17393. this.value = val;
  17394. this.updateContext(prevType);
  17395. };
  17396. // ### Token reading
  17397. // This is the function that is called to fetch the next token. It
  17398. // is somewhat obscure, because it works in character codes rather
  17399. // than characters, and because operator parsing has been inlined
  17400. // into it.
  17401. //
  17402. // All in the name of speed.
  17403. //
  17404. pp$9.readToken_dot = function() {
  17405. var next = this.input.charCodeAt(this.pos + 1);
  17406. if (next >= 48 && next <= 57) { return this.readNumber(true) }
  17407. var next2 = this.input.charCodeAt(this.pos + 2);
  17408. if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
  17409. this.pos += 3;
  17410. return this.finishToken(types.ellipsis)
  17411. } else {
  17412. ++this.pos;
  17413. return this.finishToken(types.dot)
  17414. }
  17415. };
  17416. pp$9.readToken_slash = function() { // '/'
  17417. var next = this.input.charCodeAt(this.pos + 1);
  17418. if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
  17419. if (next === 61) { return this.finishOp(types.assign, 2) }
  17420. return this.finishOp(types.slash, 1)
  17421. };
  17422. pp$9.readToken_mult_modulo_exp = function(code) { // '%*'
  17423. var next = this.input.charCodeAt(this.pos + 1);
  17424. var size = 1;
  17425. var tokentype = code === 42 ? types.star : types.modulo;
  17426. // exponentiation operator ** and **=
  17427. if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
  17428. ++size;
  17429. tokentype = types.starstar;
  17430. next = this.input.charCodeAt(this.pos + 2);
  17431. }
  17432. if (next === 61) { return this.finishOp(types.assign, size + 1) }
  17433. return this.finishOp(tokentype, size)
  17434. };
  17435. pp$9.readToken_pipe_amp = function(code) { // '|&'
  17436. var next = this.input.charCodeAt(this.pos + 1);
  17437. if (next === code) {
  17438. if (this.options.ecmaVersion >= 12) {
  17439. var next2 = this.input.charCodeAt(this.pos + 2);
  17440. if (next2 === 61) { return this.finishOp(types.assign, 3) }
  17441. }
  17442. return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2)
  17443. }
  17444. if (next === 61) { return this.finishOp(types.assign, 2) }
  17445. return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1)
  17446. };
  17447. pp$9.readToken_caret = function() { // '^'
  17448. var next = this.input.charCodeAt(this.pos + 1);
  17449. if (next === 61) { return this.finishOp(types.assign, 2) }
  17450. return this.finishOp(types.bitwiseXOR, 1)
  17451. };
  17452. pp$9.readToken_plus_min = function(code) { // '+-'
  17453. var next = this.input.charCodeAt(this.pos + 1);
  17454. if (next === code) {
  17455. if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
  17456. (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
  17457. // A `-->` line comment
  17458. this.skipLineComment(3);
  17459. this.skipSpace();
  17460. return this.nextToken()
  17461. }
  17462. return this.finishOp(types.incDec, 2)
  17463. }
  17464. if (next === 61) { return this.finishOp(types.assign, 2) }
  17465. return this.finishOp(types.plusMin, 1)
  17466. };
  17467. pp$9.readToken_lt_gt = function(code) { // '<>'
  17468. var next = this.input.charCodeAt(this.pos + 1);
  17469. var size = 1;
  17470. if (next === code) {
  17471. size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
  17472. if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) }
  17473. return this.finishOp(types.bitShift, size)
  17474. }
  17475. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
  17476. this.input.charCodeAt(this.pos + 3) === 45) {
  17477. // `<!--`, an XML-style comment that should be interpreted as a line comment
  17478. this.skipLineComment(4);
  17479. this.skipSpace();
  17480. return this.nextToken()
  17481. }
  17482. if (next === 61) { size = 2; }
  17483. return this.finishOp(types.relational, size)
  17484. };
  17485. pp$9.readToken_eq_excl = function(code) { // '=!'
  17486. var next = this.input.charCodeAt(this.pos + 1);
  17487. if (next === 61) { return this.finishOp(types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
  17488. if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
  17489. this.pos += 2;
  17490. return this.finishToken(types.arrow)
  17491. }
  17492. return this.finishOp(code === 61 ? types.eq : types.prefix, 1)
  17493. };
  17494. pp$9.readToken_question = function() { // '?'
  17495. var ecmaVersion = this.options.ecmaVersion;
  17496. if (ecmaVersion >= 11) {
  17497. var next = this.input.charCodeAt(this.pos + 1);
  17498. if (next === 46) {
  17499. var next2 = this.input.charCodeAt(this.pos + 2);
  17500. if (next2 < 48 || next2 > 57) { return this.finishOp(types.questionDot, 2) }
  17501. }
  17502. if (next === 63) {
  17503. if (ecmaVersion >= 12) {
  17504. var next2$1 = this.input.charCodeAt(this.pos + 2);
  17505. if (next2$1 === 61) { return this.finishOp(types.assign, 3) }
  17506. }
  17507. return this.finishOp(types.coalesce, 2)
  17508. }
  17509. }
  17510. return this.finishOp(types.question, 1)
  17511. };
  17512. pp$9.readToken_numberSign = function() { // '#'
  17513. var ecmaVersion = this.options.ecmaVersion;
  17514. var code = 35; // '#'
  17515. if (ecmaVersion >= 13) {
  17516. ++this.pos;
  17517. code = this.fullCharCodeAtPos();
  17518. if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
  17519. return this.finishToken(types.privateId, this.readWord1())
  17520. }
  17521. }
  17522. this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
  17523. };
  17524. pp$9.getTokenFromCode = function(code) {
  17525. switch (code) {
  17526. // The interpretation of a dot depends on whether it is followed
  17527. // by a digit or another two dots.
  17528. case 46: // '.'
  17529. return this.readToken_dot()
  17530. // Punctuation tokens.
  17531. case 40: ++this.pos; return this.finishToken(types.parenL)
  17532. case 41: ++this.pos; return this.finishToken(types.parenR)
  17533. case 59: ++this.pos; return this.finishToken(types.semi)
  17534. case 44: ++this.pos; return this.finishToken(types.comma)
  17535. case 91: ++this.pos; return this.finishToken(types.bracketL)
  17536. case 93: ++this.pos; return this.finishToken(types.bracketR)
  17537. case 123: ++this.pos; return this.finishToken(types.braceL)
  17538. case 125: ++this.pos; return this.finishToken(types.braceR)
  17539. case 58: ++this.pos; return this.finishToken(types.colon)
  17540. case 96: // '`'
  17541. if (this.options.ecmaVersion < 6) { break }
  17542. ++this.pos;
  17543. return this.finishToken(types.backQuote)
  17544. case 48: // '0'
  17545. var next = this.input.charCodeAt(this.pos + 1);
  17546. if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
  17547. if (this.options.ecmaVersion >= 6) {
  17548. if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
  17549. if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
  17550. }
  17551. // Anything else beginning with a digit is an integer, octal
  17552. // number, or float.
  17553. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
  17554. return this.readNumber(false)
  17555. // Quotes produce strings.
  17556. case 34: case 39: // '"', "'"
  17557. return this.readString(code)
  17558. // Operators are parsed inline in tiny state machines. '=' (61) is
  17559. // often referred to. `finishOp` simply skips the amount of
  17560. // characters it is given as second argument, and returns a token
  17561. // of the type given by its first argument.
  17562. case 47: // '/'
  17563. return this.readToken_slash()
  17564. case 37: case 42: // '%*'
  17565. return this.readToken_mult_modulo_exp(code)
  17566. case 124: case 38: // '|&'
  17567. return this.readToken_pipe_amp(code)
  17568. case 94: // '^'
  17569. return this.readToken_caret()
  17570. case 43: case 45: // '+-'
  17571. return this.readToken_plus_min(code)
  17572. case 60: case 62: // '<>'
  17573. return this.readToken_lt_gt(code)
  17574. case 61: case 33: // '=!'
  17575. return this.readToken_eq_excl(code)
  17576. case 63: // '?'
  17577. return this.readToken_question()
  17578. case 126: // '~'
  17579. return this.finishOp(types.prefix, 1)
  17580. case 35: // '#'
  17581. return this.readToken_numberSign()
  17582. }
  17583. this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
  17584. };
  17585. pp$9.finishOp = function(type, size) {
  17586. var str = this.input.slice(this.pos, this.pos + size);
  17587. this.pos += size;
  17588. return this.finishToken(type, str)
  17589. };
  17590. pp$9.readRegexp = function() {
  17591. var escaped, inClass, start = this.pos;
  17592. for (;;) {
  17593. if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
  17594. var ch = this.input.charAt(this.pos);
  17595. if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
  17596. if (!escaped) {
  17597. if (ch === "[") { inClass = true; }
  17598. else if (ch === "]" && inClass) { inClass = false; }
  17599. else if (ch === "/" && !inClass) { break }
  17600. escaped = ch === "\\";
  17601. } else { escaped = false; }
  17602. ++this.pos;
  17603. }
  17604. var pattern = this.input.slice(start, this.pos);
  17605. ++this.pos;
  17606. var flagsStart = this.pos;
  17607. var flags = this.readWord1();
  17608. if (this.containsEsc) { this.unexpected(flagsStart); }
  17609. // Validate pattern
  17610. var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  17611. state.reset(start, pattern, flags);
  17612. this.validateRegExpFlags(state);
  17613. this.validateRegExpPattern(state);
  17614. // Create Literal#value property value.
  17615. var value = null;
  17616. try {
  17617. value = new RegExp(pattern, flags);
  17618. } catch (e) {
  17619. // ESTree requires null if it failed to instantiate RegExp object.
  17620. // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
  17621. }
  17622. return this.finishToken(types.regexp, {pattern: pattern, flags: flags, value: value})
  17623. };
  17624. // Read an integer in the given radix. Return null if zero digits
  17625. // were read, the integer value otherwise. When `len` is given, this
  17626. // will return `null` unless the integer has exactly `len` digits.
  17627. pp$9.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  17628. // `len` is used for character escape sequences. In that case, disallow separators.
  17629. var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
  17630. // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
  17631. // and isn't fraction part nor exponent part. In that case, if the first digit
  17632. // is zero then disallow separators.
  17633. var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
  17634. var start = this.pos, total = 0, lastCode = 0;
  17635. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
  17636. var code = this.input.charCodeAt(this.pos), val = (void 0);
  17637. if (allowSeparators && code === 95) {
  17638. if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
  17639. if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
  17640. if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
  17641. lastCode = code;
  17642. continue
  17643. }
  17644. if (code >= 97) { val = code - 97 + 10; } // a
  17645. else if (code >= 65) { val = code - 65 + 10; } // A
  17646. else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
  17647. else { val = Infinity; }
  17648. if (val >= radix) { break }
  17649. lastCode = code;
  17650. total = total * radix + val;
  17651. }
  17652. if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
  17653. if (this.pos === start || len != null && this.pos - start !== len) { return null }
  17654. return total
  17655. };
  17656. function stringToNumber(str, isLegacyOctalNumericLiteral) {
  17657. if (isLegacyOctalNumericLiteral) {
  17658. return parseInt(str, 8)
  17659. }
  17660. // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
  17661. return parseFloat(str.replace(/_/g, ""))
  17662. }
  17663. function stringToBigInt(str) {
  17664. if (typeof BigInt !== "function") {
  17665. return null
  17666. }
  17667. // `BigInt(value)` throws syntax error if the string contains numeric separators.
  17668. return BigInt(str.replace(/_/g, ""))
  17669. }
  17670. pp$9.readRadixNumber = function(radix) {
  17671. var start = this.pos;
  17672. this.pos += 2; // 0x
  17673. var val = this.readInt(radix);
  17674. if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
  17675. if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
  17676. val = stringToBigInt(this.input.slice(start, this.pos));
  17677. ++this.pos;
  17678. } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  17679. return this.finishToken(types.num, val)
  17680. };
  17681. // Read an integer, octal integer, or floating-point number.
  17682. pp$9.readNumber = function(startsWithDot) {
  17683. var start = this.pos;
  17684. if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
  17685. var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  17686. if (octal && this.strict) { this.raise(start, "Invalid number"); }
  17687. var next = this.input.charCodeAt(this.pos);
  17688. if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
  17689. var val$1 = stringToBigInt(this.input.slice(start, this.pos));
  17690. ++this.pos;
  17691. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  17692. return this.finishToken(types.num, val$1)
  17693. }
  17694. if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
  17695. if (next === 46 && !octal) { // '.'
  17696. ++this.pos;
  17697. this.readInt(10);
  17698. next = this.input.charCodeAt(this.pos);
  17699. }
  17700. if ((next === 69 || next === 101) && !octal) { // 'eE'
  17701. next = this.input.charCodeAt(++this.pos);
  17702. if (next === 43 || next === 45) { ++this.pos; } // '+-'
  17703. if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  17704. }
  17705. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  17706. var val = stringToNumber(this.input.slice(start, this.pos), octal);
  17707. return this.finishToken(types.num, val)
  17708. };
  17709. // Read a string value, interpreting backslash-escapes.
  17710. pp$9.readCodePoint = function() {
  17711. var ch = this.input.charCodeAt(this.pos), code;
  17712. if (ch === 123) { // '{'
  17713. if (this.options.ecmaVersion < 6) { this.unexpected(); }
  17714. var codePos = ++this.pos;
  17715. code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
  17716. ++this.pos;
  17717. if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
  17718. } else {
  17719. code = this.readHexChar(4);
  17720. }
  17721. return code
  17722. };
  17723. function codePointToString$1(code) {
  17724. // UTF-16 Decoding
  17725. if (code <= 0xFFFF) { return String.fromCharCode(code) }
  17726. code -= 0x10000;
  17727. return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
  17728. }
  17729. pp$9.readString = function(quote) {
  17730. var out = "", chunkStart = ++this.pos;
  17731. for (;;) {
  17732. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
  17733. var ch = this.input.charCodeAt(this.pos);
  17734. if (ch === quote) { break }
  17735. if (ch === 92) { // '\'
  17736. out += this.input.slice(chunkStart, this.pos);
  17737. out += this.readEscapedChar(false);
  17738. chunkStart = this.pos;
  17739. } else {
  17740. if (isNewLine(ch, this.options.ecmaVersion >= 10)) { this.raise(this.start, "Unterminated string constant"); }
  17741. ++this.pos;
  17742. }
  17743. }
  17744. out += this.input.slice(chunkStart, this.pos++);
  17745. return this.finishToken(types.string, out)
  17746. };
  17747. // Reads template string tokens.
  17748. var INVALID_TEMPLATE_ESCAPE_ERROR = {};
  17749. pp$9.tryReadTemplateToken = function() {
  17750. this.inTemplateElement = true;
  17751. try {
  17752. this.readTmplToken();
  17753. } catch (err) {
  17754. if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
  17755. this.readInvalidTemplateToken();
  17756. } else {
  17757. throw err
  17758. }
  17759. }
  17760. this.inTemplateElement = false;
  17761. };
  17762. pp$9.invalidStringToken = function(position, message) {
  17763. if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
  17764. throw INVALID_TEMPLATE_ESCAPE_ERROR
  17765. } else {
  17766. this.raise(position, message);
  17767. }
  17768. };
  17769. pp$9.readTmplToken = function() {
  17770. var out = "", chunkStart = this.pos;
  17771. for (;;) {
  17772. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
  17773. var ch = this.input.charCodeAt(this.pos);
  17774. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
  17775. if (this.pos === this.start && (this.type === types.template || this.type === types.invalidTemplate)) {
  17776. if (ch === 36) {
  17777. this.pos += 2;
  17778. return this.finishToken(types.dollarBraceL)
  17779. } else {
  17780. ++this.pos;
  17781. return this.finishToken(types.backQuote)
  17782. }
  17783. }
  17784. out += this.input.slice(chunkStart, this.pos);
  17785. return this.finishToken(types.template, out)
  17786. }
  17787. if (ch === 92) { // '\'
  17788. out += this.input.slice(chunkStart, this.pos);
  17789. out += this.readEscapedChar(true);
  17790. chunkStart = this.pos;
  17791. } else if (isNewLine(ch)) {
  17792. out += this.input.slice(chunkStart, this.pos);
  17793. ++this.pos;
  17794. switch (ch) {
  17795. case 13:
  17796. if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
  17797. case 10:
  17798. out += "\n";
  17799. break
  17800. default:
  17801. out += String.fromCharCode(ch);
  17802. break
  17803. }
  17804. if (this.options.locations) {
  17805. ++this.curLine;
  17806. this.lineStart = this.pos;
  17807. }
  17808. chunkStart = this.pos;
  17809. } else {
  17810. ++this.pos;
  17811. }
  17812. }
  17813. };
  17814. // Reads a template token to search for the end, without validating any escape sequences
  17815. pp$9.readInvalidTemplateToken = function() {
  17816. for (; this.pos < this.input.length; this.pos++) {
  17817. switch (this.input[this.pos]) {
  17818. case "\\":
  17819. ++this.pos;
  17820. break
  17821. case "$":
  17822. if (this.input[this.pos + 1] !== "{") {
  17823. break
  17824. }
  17825. // falls through
  17826. case "`":
  17827. return this.finishToken(types.invalidTemplate, this.input.slice(this.start, this.pos))
  17828. // no default
  17829. }
  17830. }
  17831. this.raise(this.start, "Unterminated template");
  17832. };
  17833. // Used to read escaped characters
  17834. pp$9.readEscapedChar = function(inTemplate) {
  17835. var ch = this.input.charCodeAt(++this.pos);
  17836. ++this.pos;
  17837. switch (ch) {
  17838. case 110: return "\n" // 'n' -> '\n'
  17839. case 114: return "\r" // 'r' -> '\r'
  17840. case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
  17841. case 117: return codePointToString$1(this.readCodePoint()) // 'u'
  17842. case 116: return "\t" // 't' -> '\t'
  17843. case 98: return "\b" // 'b' -> '\b'
  17844. case 118: return "\u000b" // 'v' -> '\u000b'
  17845. case 102: return "\f" // 'f' -> '\f'
  17846. case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
  17847. case 10: // ' \n'
  17848. if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
  17849. return ""
  17850. case 56:
  17851. case 57:
  17852. if (this.strict) {
  17853. this.invalidStringToken(
  17854. this.pos - 1,
  17855. "Invalid escape sequence"
  17856. );
  17857. }
  17858. if (inTemplate) {
  17859. var codePos = this.pos - 1;
  17860. this.invalidStringToken(
  17861. codePos,
  17862. "Invalid escape sequence in template string"
  17863. );
  17864. return null
  17865. }
  17866. default:
  17867. if (ch >= 48 && ch <= 55) {
  17868. var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
  17869. var octal = parseInt(octalStr, 8);
  17870. if (octal > 255) {
  17871. octalStr = octalStr.slice(0, -1);
  17872. octal = parseInt(octalStr, 8);
  17873. }
  17874. this.pos += octalStr.length - 1;
  17875. ch = this.input.charCodeAt(this.pos);
  17876. if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
  17877. this.invalidStringToken(
  17878. this.pos - 1 - octalStr.length,
  17879. inTemplate
  17880. ? "Octal literal in template string"
  17881. : "Octal literal in strict mode"
  17882. );
  17883. }
  17884. return String.fromCharCode(octal)
  17885. }
  17886. if (isNewLine(ch)) {
  17887. // Unicode new line characters after \ get removed from output in both
  17888. // template literals and strings
  17889. return ""
  17890. }
  17891. return String.fromCharCode(ch)
  17892. }
  17893. };
  17894. // Used to read character escape sequences ('\x', '\u', '\U').
  17895. pp$9.readHexChar = function(len) {
  17896. var codePos = this.pos;
  17897. var n = this.readInt(16, len);
  17898. if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
  17899. return n
  17900. };
  17901. // Read an identifier, and return it as a string. Sets `this.containsEsc`
  17902. // to whether the word contained a '\u' escape.
  17903. //
  17904. // Incrementally adds only escaped chars, adding other chunks as-is
  17905. // as a micro-optimization.
  17906. pp$9.readWord1 = function() {
  17907. this.containsEsc = false;
  17908. var word = "", first = true, chunkStart = this.pos;
  17909. var astral = this.options.ecmaVersion >= 6;
  17910. while (this.pos < this.input.length) {
  17911. var ch = this.fullCharCodeAtPos();
  17912. if (isIdentifierChar(ch, astral)) {
  17913. this.pos += ch <= 0xffff ? 1 : 2;
  17914. } else if (ch === 92) { // "\"
  17915. this.containsEsc = true;
  17916. word += this.input.slice(chunkStart, this.pos);
  17917. var escStart = this.pos;
  17918. if (this.input.charCodeAt(++this.pos) !== 117) // "u"
  17919. { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
  17920. ++this.pos;
  17921. var esc = this.readCodePoint();
  17922. if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
  17923. { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
  17924. word += codePointToString$1(esc);
  17925. chunkStart = this.pos;
  17926. } else {
  17927. break
  17928. }
  17929. first = false;
  17930. }
  17931. return word + this.input.slice(chunkStart, this.pos)
  17932. };
  17933. // Read an identifier or keyword token. Will check for reserved
  17934. // words when necessary.
  17935. pp$9.readWord = function() {
  17936. var word = this.readWord1();
  17937. var type = types.name;
  17938. if (this.keywords.test(word)) {
  17939. type = keywords$1[word];
  17940. }
  17941. return this.finishToken(type, word)
  17942. };
  17943. // Acorn is a tiny, fast JavaScript parser written in JavaScript.
  17944. var version = "8.4.0";
  17945. Parser.acorn = {
  17946. Parser: Parser,
  17947. version: version,
  17948. defaultOptions: defaultOptions,
  17949. Position: Position,
  17950. SourceLocation: SourceLocation,
  17951. getLineInfo: getLineInfo,
  17952. Node: Node,
  17953. TokenType: TokenType,
  17954. tokTypes: types,
  17955. keywordTypes: keywords$1,
  17956. TokContext: TokContext,
  17957. tokContexts: types$1,
  17958. isIdentifierChar: isIdentifierChar,
  17959. isIdentifierStart: isIdentifierStart,
  17960. Token: Token,
  17961. isNewLine: isNewLine,
  17962. lineBreak: lineBreak,
  17963. lineBreakG: lineBreakG,
  17964. nonASCIIwhitespace: nonASCIIwhitespace
  17965. };
  17966. const readFile = (file) => new Promise((fulfil, reject) => fs.readFile(file, 'utf-8', (err, contents) => (err ? reject(err) : fulfil(contents))));
  17967. function mkdirpath(path) {
  17968. const dir = dirname(path);
  17969. try {
  17970. fs.readdirSync(dir);
  17971. }
  17972. catch (err) {
  17973. mkdirpath(dir);
  17974. try {
  17975. fs.mkdirSync(dir);
  17976. }
  17977. catch (err2) {
  17978. if (err2.code !== 'EEXIST') {
  17979. throw err2;
  17980. }
  17981. }
  17982. }
  17983. }
  17984. function writeFile(dest, data) {
  17985. return new Promise((fulfil, reject) => {
  17986. mkdirpath(dest);
  17987. fs.writeFile(dest, data, err => {
  17988. if (err) {
  17989. reject(err);
  17990. }
  17991. else {
  17992. fulfil();
  17993. }
  17994. });
  17995. });
  17996. }
  17997. class Queue {
  17998. constructor(maxParallel = 1) {
  17999. this.maxParallel = maxParallel;
  18000. this.queue = new Array();
  18001. this.workerCount = 0;
  18002. }
  18003. run(task) {
  18004. return new Promise((resolve, reject) => {
  18005. this.queue.push({ reject, resolve, task });
  18006. this.work();
  18007. });
  18008. }
  18009. async work() {
  18010. if (this.workerCount >= this.maxParallel)
  18011. return;
  18012. this.workerCount++;
  18013. let entry;
  18014. while ((entry = this.queue.shift())) {
  18015. const { reject, resolve, task } = entry;
  18016. try {
  18017. const result = await task();
  18018. resolve(result);
  18019. }
  18020. catch (err) {
  18021. reject(err);
  18022. }
  18023. }
  18024. this.workerCount--;
  18025. }
  18026. }
  18027. function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions) {
  18028. let skipped = null;
  18029. let replaceContext = null;
  18030. if (skip) {
  18031. skipped = new Set();
  18032. for (const skippedCall of skip) {
  18033. if (source === skippedCall.source && importer === skippedCall.importer) {
  18034. skipped.add(skippedCall.plugin);
  18035. }
  18036. }
  18037. replaceContext = (pluginContext, plugin) => ({
  18038. ...pluginContext,
  18039. resolve: (source, importer, { custom, skipSelf } = BLANK) => {
  18040. return moduleLoaderResolveId(source, importer, custom, skipSelf ? [...skip, { importer, plugin, source }] : skip);
  18041. }
  18042. });
  18043. }
  18044. return pluginDriver.hookFirst('resolveId', [source, importer, { custom: customOptions }], replaceContext, skipped);
  18045. }
  18046. async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions) {
  18047. const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions);
  18048. if (pluginResult != null)
  18049. return pluginResult;
  18050. // external modules (non-entry modules that start with neither '.' or '/')
  18051. // are skipped at this stage.
  18052. if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
  18053. return null;
  18054. // `resolve` processes paths from right to left, prepending them until an
  18055. // absolute path is created. Absolute importees therefore shortcircuit the
  18056. // resolve call and require no special handing on our part.
  18057. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  18058. return addJsExtensionIfNecessary(importer ? resolve(dirname(importer), source) : resolve(source), preserveSymlinks);
  18059. }
  18060. function addJsExtensionIfNecessary(file, preserveSymlinks) {
  18061. let found = findFile(file, preserveSymlinks);
  18062. if (found)
  18063. return found;
  18064. found = findFile(file + '.mjs', preserveSymlinks);
  18065. if (found)
  18066. return found;
  18067. found = findFile(file + '.js', preserveSymlinks);
  18068. return found;
  18069. }
  18070. function findFile(file, preserveSymlinks) {
  18071. try {
  18072. const stats = lstatSync(file);
  18073. if (!preserveSymlinks && stats.isSymbolicLink())
  18074. return findFile(realpathSync(file), preserveSymlinks);
  18075. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  18076. // check case
  18077. const name = basename(file);
  18078. const files = readdirSync(dirname(file));
  18079. if (files.indexOf(name) !== -1)
  18080. return file;
  18081. }
  18082. }
  18083. catch (_a) {
  18084. // suppress
  18085. }
  18086. }
  18087. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  18088. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  18089. function throwPluginError(err, plugin, { hook, id } = {}) {
  18090. if (typeof err === 'string')
  18091. err = { message: err };
  18092. if (err.code && err.code !== Errors.PLUGIN_ERROR) {
  18093. err.pluginCode = err.code;
  18094. }
  18095. err.code = Errors.PLUGIN_ERROR;
  18096. err.plugin = plugin;
  18097. if (hook) {
  18098. err.hook = hook;
  18099. }
  18100. if (id) {
  18101. err.id = id;
  18102. }
  18103. return error(err);
  18104. }
  18105. const deprecatedHooks = [
  18106. { active: true, deprecated: 'resolveAssetUrl', replacement: 'resolveFileUrl' }
  18107. ];
  18108. function warnDeprecatedHooks(plugins, options) {
  18109. for (const { active, deprecated, replacement } of deprecatedHooks) {
  18110. for (const plugin of plugins) {
  18111. if (deprecated in plugin) {
  18112. warnDeprecation({
  18113. message: `The "${deprecated}" hook used by plugin ${plugin.name} is deprecated. The "${replacement}" hook should be used instead.`,
  18114. plugin: plugin.name
  18115. }, active, options);
  18116. }
  18117. }
  18118. }
  18119. }
  18120. function createPluginCache(cache) {
  18121. return {
  18122. delete(id) {
  18123. return delete cache[id];
  18124. },
  18125. get(id) {
  18126. const item = cache[id];
  18127. if (!item)
  18128. return undefined;
  18129. item[0] = 0;
  18130. return item[1];
  18131. },
  18132. has(id) {
  18133. const item = cache[id];
  18134. if (!item)
  18135. return false;
  18136. item[0] = 0;
  18137. return true;
  18138. },
  18139. set(id, value) {
  18140. cache[id] = [0, value];
  18141. }
  18142. };
  18143. }
  18144. function getTrackedPluginCache(pluginCache, onUse) {
  18145. return {
  18146. delete(id) {
  18147. onUse();
  18148. return pluginCache.delete(id);
  18149. },
  18150. get(id) {
  18151. onUse();
  18152. return pluginCache.get(id);
  18153. },
  18154. has(id) {
  18155. onUse();
  18156. return pluginCache.has(id);
  18157. },
  18158. set(id, value) {
  18159. onUse();
  18160. return pluginCache.set(id, value);
  18161. }
  18162. };
  18163. }
  18164. const NO_CACHE = {
  18165. delete() {
  18166. return false;
  18167. },
  18168. get() {
  18169. return undefined;
  18170. },
  18171. has() {
  18172. return false;
  18173. },
  18174. set() { }
  18175. };
  18176. function uncacheablePluginError(pluginName) {
  18177. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  18178. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  18179. return error({
  18180. code: 'ANONYMOUS_PLUGIN_CACHE',
  18181. message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
  18182. });
  18183. }
  18184. return error({
  18185. code: 'DUPLICATE_PLUGIN_NAME',
  18186. 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).`
  18187. });
  18188. }
  18189. function getCacheForUncacheablePlugin(pluginName) {
  18190. return {
  18191. delete() {
  18192. return uncacheablePluginError(pluginName);
  18193. },
  18194. get() {
  18195. return uncacheablePluginError(pluginName);
  18196. },
  18197. has() {
  18198. return uncacheablePluginError(pluginName);
  18199. },
  18200. set() {
  18201. return uncacheablePluginError(pluginName);
  18202. }
  18203. };
  18204. }
  18205. function transform(source, module, pluginDriver, warn) {
  18206. const id = module.id;
  18207. const sourcemapChain = [];
  18208. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  18209. const originalCode = source.code;
  18210. let ast = source.ast;
  18211. const transformDependencies = [];
  18212. const emittedFiles = [];
  18213. let customTransformCache = false;
  18214. const useCustomTransformCache = () => (customTransformCache = true);
  18215. let curPlugin;
  18216. const curSource = source.code;
  18217. function transformReducer(previousCode, result, plugin) {
  18218. let code;
  18219. let map;
  18220. if (typeof result === 'string') {
  18221. code = result;
  18222. }
  18223. else if (result && typeof result === 'object') {
  18224. module.updateOptions(result);
  18225. if (result.code == null) {
  18226. if (result.map || result.ast) {
  18227. warn(errNoTransformMapOrAstWithoutCode(plugin.name));
  18228. }
  18229. return previousCode;
  18230. }
  18231. ({ code, map, ast } = result);
  18232. }
  18233. else {
  18234. return previousCode;
  18235. }
  18236. // strict null check allows 'null' maps to not be pushed to the chain,
  18237. // while 'undefined' gets the missing map warning
  18238. if (map !== null) {
  18239. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  18240. missing: true,
  18241. plugin: plugin.name
  18242. });
  18243. }
  18244. return code;
  18245. }
  18246. return pluginDriver
  18247. .hookReduceArg0('transform', [curSource, id], transformReducer, (pluginContext, plugin) => {
  18248. curPlugin = plugin;
  18249. return {
  18250. ...pluginContext,
  18251. addWatchFile(id) {
  18252. transformDependencies.push(id);
  18253. pluginContext.addWatchFile(id);
  18254. },
  18255. cache: customTransformCache
  18256. ? pluginContext.cache
  18257. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  18258. emitAsset(name, source) {
  18259. emittedFiles.push({ name, source, type: 'asset' });
  18260. return pluginContext.emitAsset(name, source);
  18261. },
  18262. emitChunk(id, options) {
  18263. emittedFiles.push({ id, name: options && options.name, type: 'chunk' });
  18264. return pluginContext.emitChunk(id, options);
  18265. },
  18266. emitFile(emittedFile) {
  18267. emittedFiles.push(emittedFile);
  18268. return pluginDriver.emitFile(emittedFile);
  18269. },
  18270. error(err, pos) {
  18271. if (typeof err === 'string')
  18272. err = { message: err };
  18273. if (pos)
  18274. augmentCodeLocation(err, pos, curSource, id);
  18275. err.id = id;
  18276. err.hook = 'transform';
  18277. return pluginContext.error(err);
  18278. },
  18279. getCombinedSourcemap() {
  18280. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn);
  18281. if (!combinedMap) {
  18282. const magicString = new MagicString$1(originalCode);
  18283. return magicString.generateMap({ hires: true, includeContent: true, source: id });
  18284. }
  18285. if (originalSourcemap !== combinedMap) {
  18286. originalSourcemap = combinedMap;
  18287. sourcemapChain.length = 0;
  18288. }
  18289. return new SourceMap({
  18290. ...combinedMap,
  18291. file: null,
  18292. sourcesContent: combinedMap.sourcesContent
  18293. });
  18294. },
  18295. setAssetSource() {
  18296. return this.error({
  18297. code: 'INVALID_SETASSETSOURCE',
  18298. message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
  18299. });
  18300. },
  18301. warn(warning, pos) {
  18302. if (typeof warning === 'string')
  18303. warning = { message: warning };
  18304. if (pos)
  18305. augmentCodeLocation(warning, pos, curSource, id);
  18306. warning.id = id;
  18307. warning.hook = 'transform';
  18308. pluginContext.warn(warning);
  18309. }
  18310. };
  18311. })
  18312. .catch(err => throwPluginError(err, curPlugin.name, { hook: 'transform', id }))
  18313. .then(code => {
  18314. if (!customTransformCache) {
  18315. // files emitted by a transform hook need to be emitted again if the hook is skipped
  18316. if (emittedFiles.length)
  18317. module.transformFiles = emittedFiles;
  18318. }
  18319. return {
  18320. ast,
  18321. code,
  18322. customTransformCache,
  18323. meta: module.info.meta,
  18324. originalCode,
  18325. originalSourcemap,
  18326. sourcemapChain,
  18327. transformDependencies
  18328. };
  18329. });
  18330. }
  18331. class ModuleLoader {
  18332. constructor(graph, modulesById, options, pluginDriver) {
  18333. this.graph = graph;
  18334. this.modulesById = modulesById;
  18335. this.options = options;
  18336. this.pluginDriver = pluginDriver;
  18337. this.implicitEntryModules = new Set();
  18338. this.indexedEntryModules = [];
  18339. this.latestLoadModulesPromise = Promise.resolve();
  18340. this.nextEntryModuleIndex = 0;
  18341. this.readQueue = new Queue();
  18342. this.resolveId = async (source, importer, customOptions, skip = null) => {
  18343. return this.addDefaultsToResolvedId(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  18344. ? false
  18345. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions), importer, source));
  18346. };
  18347. this.hasModuleSideEffects = options.treeshake
  18348. ? options.treeshake.moduleSideEffects
  18349. : () => true;
  18350. this.readQueue.maxParallel = options.maxParallelFileReads;
  18351. }
  18352. async addAdditionalModules(unresolvedModules) {
  18353. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null))));
  18354. await this.awaitLoadModulesPromise();
  18355. return result;
  18356. }
  18357. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  18358. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  18359. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  18360. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
  18361. let moduleIndex = firstEntryModuleIndex;
  18362. for (let index = 0; index < entryModules.length; index++) {
  18363. const entryModule = entryModules[index];
  18364. entryModule.isUserDefinedEntryPoint =
  18365. entryModule.isUserDefinedEntryPoint || isUserDefined;
  18366. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined);
  18367. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  18368. if (!existingIndexedModule) {
  18369. this.indexedEntryModules.push({ index: moduleIndex, module: entryModule });
  18370. }
  18371. else {
  18372. existingIndexedModule.index = Math.min(existingIndexedModule.index, moduleIndex);
  18373. }
  18374. moduleIndex++;
  18375. }
  18376. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  18377. return entryModules;
  18378. }));
  18379. await this.awaitLoadModulesPromise();
  18380. return {
  18381. entryModules: this.indexedEntryModules.map(({ module }) => module),
  18382. implicitEntryModules: [...this.implicitEntryModules],
  18383. newEntryModules
  18384. };
  18385. }
  18386. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  18387. const unresolvedModule = {
  18388. fileName: fileName || null,
  18389. id,
  18390. importer,
  18391. name: name || null
  18392. };
  18393. const module = implicitlyLoadedAfterOneOf
  18394. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  18395. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  18396. if (preserveSignature != null) {
  18397. module.preserveSignature = preserveSignature;
  18398. }
  18399. return module;
  18400. }
  18401. addDefaultsToResolvedId(resolvedId) {
  18402. var _a, _b;
  18403. if (!resolvedId) {
  18404. return null;
  18405. }
  18406. const external = resolvedId.external || false;
  18407. return {
  18408. external,
  18409. id: resolvedId.id,
  18410. meta: resolvedId.meta || EMPTY_OBJECT,
  18411. moduleSideEffects: (_a = resolvedId.moduleSideEffects) !== null && _a !== void 0 ? _a : this.hasModuleSideEffects(resolvedId.id, !!external),
  18412. syntheticNamedExports: (_b = resolvedId.syntheticNamedExports) !== null && _b !== void 0 ? _b : false
  18413. };
  18414. }
  18415. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  18416. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
  18417. addChunkNamesToModule(entryModule, unresolvedModule, false);
  18418. if (!entryModule.info.isEntry) {
  18419. this.implicitEntryModules.add(entryModule);
  18420. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
  18421. for (const module of implicitlyLoadedAfterModules) {
  18422. entryModule.implicitlyLoadedAfter.add(module);
  18423. }
  18424. for (const dependant of entryModule.implicitlyLoadedAfter) {
  18425. dependant.implicitlyLoadedBefore.add(entryModule);
  18426. }
  18427. }
  18428. return entryModule;
  18429. }));
  18430. }
  18431. async addModuleSource(id, importer, module) {
  18432. timeStart('load modules', 3);
  18433. let source;
  18434. try {
  18435. source = await this.readQueue.run(async () => { var _a; return (_a = (await this.pluginDriver.hookFirst('load', [id]))) !== null && _a !== void 0 ? _a : (await readFile(id)); });
  18436. }
  18437. catch (err) {
  18438. timeEnd('load modules', 3);
  18439. let msg = `Could not load ${id}`;
  18440. if (importer)
  18441. msg += ` (imported by ${relativeId(importer)})`;
  18442. msg += `: ${err.message}`;
  18443. err.message = msg;
  18444. throw err;
  18445. }
  18446. timeEnd('load modules', 3);
  18447. const sourceDescription = typeof source === 'string'
  18448. ? { code: source }
  18449. : typeof source === 'object' && typeof source.code === 'string'
  18450. ? source
  18451. : error(errBadLoader(id));
  18452. const cachedModule = this.graph.cachedModules.get(id);
  18453. if (cachedModule &&
  18454. !cachedModule.customTransformCache &&
  18455. cachedModule.originalCode === sourceDescription.code) {
  18456. if (cachedModule.transformFiles) {
  18457. for (const emittedFile of cachedModule.transformFiles)
  18458. this.pluginDriver.emitFile(emittedFile);
  18459. }
  18460. module.setSource(cachedModule);
  18461. }
  18462. else {
  18463. module.updateOptions(sourceDescription);
  18464. module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onwarn));
  18465. }
  18466. }
  18467. async awaitLoadModulesPromise() {
  18468. let startingPromise;
  18469. do {
  18470. startingPromise = this.latestLoadModulesPromise;
  18471. await startingPromise;
  18472. } while (startingPromise !== this.latestLoadModulesPromise);
  18473. }
  18474. extendLoadModulesPromise(loadNewModulesPromise) {
  18475. this.latestLoadModulesPromise = Promise.all([
  18476. loadNewModulesPromise,
  18477. this.latestLoadModulesPromise
  18478. ]);
  18479. this.latestLoadModulesPromise.catch(() => {
  18480. /* Avoid unhandled Promise rejections */
  18481. });
  18482. return loadNewModulesPromise;
  18483. }
  18484. async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
  18485. const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([dynamicImport, resolvedId]) => {
  18486. if (resolvedId === null)
  18487. return null;
  18488. if (typeof resolvedId === 'string') {
  18489. dynamicImport.resolution = resolvedId;
  18490. return null;
  18491. }
  18492. return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
  18493. })));
  18494. for (const dependency of dependencies) {
  18495. if (dependency) {
  18496. module.dynamicDependencies.add(dependency);
  18497. dependency.dynamicImporters.push(module.id);
  18498. }
  18499. }
  18500. }
  18501. async fetchModule({ id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry) {
  18502. const existingModule = this.modulesById.get(id);
  18503. if (existingModule instanceof Module) {
  18504. if (isEntry) {
  18505. existingModule.info.isEntry = true;
  18506. this.implicitEntryModules.delete(existingModule);
  18507. for (const dependant of existingModule.implicitlyLoadedAfter) {
  18508. dependant.implicitlyLoadedBefore.delete(existingModule);
  18509. }
  18510. existingModule.implicitlyLoadedAfter.clear();
  18511. }
  18512. return existingModule;
  18513. }
  18514. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta);
  18515. this.modulesById.set(id, module);
  18516. this.graph.watchFiles[id] = true;
  18517. await this.addModuleSource(id, importer, module);
  18518. const resolveStaticDependencyPromises = this.getResolveStaticDependencyPromises(module);
  18519. const resolveDynamicImportPromises = this.getResolveDynamicImportPromises(module);
  18520. Promise.all([
  18521. ...resolveStaticDependencyPromises,
  18522. ...resolveDynamicImportPromises
  18523. ]).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
  18524. await Promise.all([
  18525. this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
  18526. this.fetchDynamicDependencies(module, resolveDynamicImportPromises)
  18527. ]);
  18528. module.linkImports();
  18529. return module;
  18530. }
  18531. fetchResolvedDependency(source, importer, resolvedId) {
  18532. if (resolvedId.external) {
  18533. const { external, id, moduleSideEffects, meta } = resolvedId;
  18534. if (!this.modulesById.has(id)) {
  18535. this.modulesById.set(id, new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && isAbsolute(id)));
  18536. }
  18537. const externalModule = this.modulesById.get(id);
  18538. if (!(externalModule instanceof ExternalModule)) {
  18539. return error(errInternalIdCannotBeExternal(source, importer));
  18540. }
  18541. return Promise.resolve(externalModule);
  18542. }
  18543. else {
  18544. return this.fetchModule(resolvedId, importer, false);
  18545. }
  18546. }
  18547. async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
  18548. for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => this.fetchResolvedDependency(source, module.id, resolvedId))))) {
  18549. module.dependencies.add(dependency);
  18550. dependency.importers.push(module.id);
  18551. }
  18552. if (!this.options.treeshake || module.info.hasModuleSideEffects === 'no-treeshake') {
  18553. for (const dependency of module.dependencies) {
  18554. if (dependency instanceof Module) {
  18555. dependency.importedFromNotTreeshaken = true;
  18556. }
  18557. }
  18558. }
  18559. }
  18560. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  18561. const { makeAbsoluteExternalsRelative } = this.options;
  18562. if (resolveIdResult) {
  18563. if (typeof resolveIdResult === 'object') {
  18564. const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
  18565. return {
  18566. ...resolveIdResult,
  18567. external: external &&
  18568. (external === 'relative' ||
  18569. !isAbsolute(resolveIdResult.id) ||
  18570. (external === true &&
  18571. isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
  18572. 'absolute')
  18573. };
  18574. }
  18575. const external = this.options.external(resolveIdResult, importer, true);
  18576. return {
  18577. external: external &&
  18578. (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
  18579. 'absolute'),
  18580. id: external && makeAbsoluteExternalsRelative
  18581. ? normalizeRelativeExternalId(resolveIdResult, importer)
  18582. : resolveIdResult
  18583. };
  18584. }
  18585. const id = makeAbsoluteExternalsRelative
  18586. ? normalizeRelativeExternalId(source, importer)
  18587. : source;
  18588. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  18589. return null;
  18590. }
  18591. return {
  18592. external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
  18593. id
  18594. };
  18595. }
  18596. getResolveDynamicImportPromises(module) {
  18597. return module.dynamicImports.map(async (dynamicImport) => {
  18598. const resolvedId = await this.resolveDynamicImport(module, typeof dynamicImport.argument === 'string'
  18599. ? dynamicImport.argument
  18600. : dynamicImport.argument.esTreeNode, module.id);
  18601. if (resolvedId && typeof resolvedId === 'object') {
  18602. dynamicImport.id = resolvedId.id;
  18603. }
  18604. return [dynamicImport, resolvedId];
  18605. });
  18606. }
  18607. getResolveStaticDependencyPromises(module) {
  18608. return Array.from(module.sources, async (source) => [
  18609. source,
  18610. (module.resolvedIds[source] =
  18611. module.resolvedIds[source] ||
  18612. this.handleResolveId(await this.resolveId(source, module.id, EMPTY_OBJECT), source, module.id))
  18613. ]);
  18614. }
  18615. handleResolveId(resolvedId, source, importer) {
  18616. if (resolvedId === null) {
  18617. if (isRelative(source)) {
  18618. return error(errUnresolvedImport(source, importer));
  18619. }
  18620. this.options.onwarn(errUnresolvedImportTreatedAsExternal(source, importer));
  18621. return {
  18622. external: true,
  18623. id: source,
  18624. meta: EMPTY_OBJECT,
  18625. moduleSideEffects: this.hasModuleSideEffects(source, true),
  18626. syntheticNamedExports: false
  18627. };
  18628. }
  18629. else {
  18630. if (resolvedId.external && resolvedId.syntheticNamedExports) {
  18631. this.options.onwarn(errExternalSyntheticExports(source, importer));
  18632. }
  18633. }
  18634. return resolvedId;
  18635. }
  18636. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore) {
  18637. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, EMPTY_OBJECT);
  18638. if (resolveIdResult == null) {
  18639. return error(implicitlyLoadedBefore === null
  18640. ? errUnresolvedEntry(unresolvedId)
  18641. : errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  18642. }
  18643. if (resolveIdResult === false ||
  18644. (typeof resolveIdResult === 'object' && resolveIdResult.external)) {
  18645. return error(implicitlyLoadedBefore === null
  18646. ? errEntryCannotBeExternal(unresolvedId)
  18647. : errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  18648. }
  18649. return this.fetchModule(this.addDefaultsToResolvedId(typeof resolveIdResult === 'object'
  18650. ? resolveIdResult
  18651. : { id: resolveIdResult }), undefined, isEntry);
  18652. }
  18653. async resolveDynamicImport(module, specifier, importer) {
  18654. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  18655. specifier,
  18656. importer
  18657. ]);
  18658. if (typeof specifier !== 'string') {
  18659. if (typeof resolution === 'string') {
  18660. return resolution;
  18661. }
  18662. if (!resolution) {
  18663. return null;
  18664. }
  18665. return {
  18666. external: false,
  18667. moduleSideEffects: true,
  18668. ...resolution
  18669. };
  18670. }
  18671. if (resolution == null) {
  18672. return (module.resolvedIds[specifier] =
  18673. module.resolvedIds[specifier] ||
  18674. this.handleResolveId(await this.resolveId(specifier, module.id, EMPTY_OBJECT), specifier, module.id));
  18675. }
  18676. return this.handleResolveId(this.addDefaultsToResolvedId(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier)), specifier, importer);
  18677. }
  18678. }
  18679. function normalizeRelativeExternalId(source, importer) {
  18680. return isRelative(source)
  18681. ? importer
  18682. ? resolve(importer, '..', source)
  18683. : resolve(source)
  18684. : source;
  18685. }
  18686. function addChunkNamesToModule(module, { fileName, name }, isUserDefined) {
  18687. if (fileName !== null) {
  18688. module.chunkFileNames.add(fileName);
  18689. }
  18690. else if (name !== null) {
  18691. if (module.chunkName === null) {
  18692. module.chunkName = name;
  18693. }
  18694. if (isUserDefined) {
  18695. module.userChunkNames.add(name);
  18696. }
  18697. }
  18698. }
  18699. function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
  18700. return (makeAbsoluteExternalsRelative === true ||
  18701. (makeAbsoluteExternalsRelative === 'ifRelativeSource' && isRelative(source)) ||
  18702. !isAbsolute(id));
  18703. }
  18704. class GlobalScope extends Scope$1 {
  18705. constructor() {
  18706. super();
  18707. this.variables.set('undefined', new UndefinedVariable());
  18708. }
  18709. findVariable(name) {
  18710. let variable = this.variables.get(name);
  18711. if (!variable) {
  18712. variable = new GlobalVariable(name);
  18713. this.variables.set(name, variable);
  18714. }
  18715. return variable;
  18716. }
  18717. }
  18718. // eslint-disable-next-line @typescript-eslint/ban-types
  18719. function getDeprecatedContextHandler(handler, handlerName, newHandlerName, pluginName, activeDeprecation, options) {
  18720. let deprecationWarningShown = false;
  18721. return ((...args) => {
  18722. if (!deprecationWarningShown) {
  18723. deprecationWarningShown = true;
  18724. warnDeprecation({
  18725. message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`,
  18726. plugin: pluginName
  18727. }, activeDeprecation, options);
  18728. }
  18729. return handler(...args);
  18730. });
  18731. }
  18732. function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
  18733. let cacheable = true;
  18734. if (typeof plugin.cacheKey !== 'string') {
  18735. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  18736. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  18737. existingPluginNames.has(plugin.name)) {
  18738. cacheable = false;
  18739. }
  18740. else {
  18741. existingPluginNames.add(plugin.name);
  18742. }
  18743. }
  18744. let cacheInstance;
  18745. if (!pluginCache) {
  18746. cacheInstance = NO_CACHE;
  18747. }
  18748. else if (cacheable) {
  18749. const cacheKey = plugin.cacheKey || plugin.name;
  18750. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  18751. }
  18752. else {
  18753. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  18754. }
  18755. const context = {
  18756. addWatchFile(id) {
  18757. if (graph.phase >= BuildPhase.GENERATE) {
  18758. return this.error(errInvalidRollupPhaseForAddWatchFile());
  18759. }
  18760. graph.watchFiles[id] = true;
  18761. },
  18762. cache: cacheInstance,
  18763. emitAsset: getDeprecatedContextHandler((name, source) => fileEmitter.emitFile({ name, source, type: 'asset' }), 'emitAsset', 'emitFile', plugin.name, true, options),
  18764. emitChunk: getDeprecatedContextHandler((id, options) => fileEmitter.emitFile({ id, name: options && options.name, type: 'chunk' }), 'emitChunk', 'emitFile', plugin.name, true, options),
  18765. emitFile: fileEmitter.emitFile.bind(fileEmitter),
  18766. error(err) {
  18767. return throwPluginError(err, plugin.name);
  18768. },
  18769. getAssetFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, true, options),
  18770. getChunkFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, true, options),
  18771. getFileName: fileEmitter.getFileName,
  18772. getModuleIds: () => graph.modulesById.keys(),
  18773. getModuleInfo: graph.getModuleInfo,
  18774. getWatchFiles: () => Object.keys(graph.watchFiles),
  18775. isExternal: getDeprecatedContextHandler((id, parentId, isResolved = false) => options.external(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, true, options),
  18776. meta: {
  18777. rollupVersion: version$1,
  18778. watchMode: graph.watchMode
  18779. },
  18780. get moduleIds() {
  18781. function* wrappedModuleIds() {
  18782. warnDeprecation({
  18783. message: `Accessing "this.moduleIds" on the plugin context by plugin ${plugin.name} is deprecated. The "this.getModuleIds" plugin context function should be used instead.`,
  18784. plugin: plugin.name
  18785. }, false, options);
  18786. yield* moduleIds;
  18787. }
  18788. const moduleIds = graph.modulesById.keys();
  18789. return wrappedModuleIds();
  18790. },
  18791. parse: graph.contextParse.bind(graph),
  18792. resolve(source, importer, { custom, skipSelf } = BLANK) {
  18793. return graph.moduleLoader.resolveId(source, importer, custom, skipSelf ? [{ importer, plugin, source }] : null);
  18794. },
  18795. resolveId: getDeprecatedContextHandler((source, importer) => graph.moduleLoader
  18796. .resolveId(source, importer, BLANK)
  18797. .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, true, options),
  18798. setAssetSource: fileEmitter.setAssetSource,
  18799. warn(warning) {
  18800. if (typeof warning === 'string')
  18801. warning = { message: warning };
  18802. if (warning.code)
  18803. warning.pluginCode = warning.code;
  18804. warning.code = 'PLUGIN_WARNING';
  18805. warning.plugin = plugin.name;
  18806. options.onwarn(warning);
  18807. }
  18808. };
  18809. return context;
  18810. }
  18811. const inputHookNames = {
  18812. buildEnd: 1,
  18813. buildStart: 1,
  18814. closeBundle: 1,
  18815. closeWatcher: 1,
  18816. load: 1,
  18817. moduleParsed: 1,
  18818. options: 1,
  18819. resolveDynamicImport: 1,
  18820. resolveId: 1,
  18821. transform: 1,
  18822. watchChange: 1
  18823. };
  18824. const inputHooks = Object.keys(inputHookNames);
  18825. function throwInvalidHookError(hookName, pluginName) {
  18826. return error({
  18827. code: 'INVALID_PLUGIN_HOOK',
  18828. message: `Error running plugin hook ${hookName} for ${pluginName}, expected a function hook.`
  18829. });
  18830. }
  18831. class PluginDriver {
  18832. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  18833. this.graph = graph;
  18834. this.options = options;
  18835. this.pluginContexts = new Map();
  18836. warnDeprecatedHooks(userPlugins, options);
  18837. this.pluginCache = pluginCache;
  18838. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  18839. this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
  18840. this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
  18841. this.finaliseAssets = this.fileEmitter.assertAssetsFinalized.bind(this.fileEmitter);
  18842. this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
  18843. this.plugins = userPlugins.concat(basePluginDriver ? basePluginDriver.plugins : []);
  18844. const existingPluginNames = new Set();
  18845. for (const plugin of this.plugins) {
  18846. this.pluginContexts.set(plugin, getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames));
  18847. }
  18848. if (basePluginDriver) {
  18849. for (const plugin of userPlugins) {
  18850. for (const hook of inputHooks) {
  18851. if (hook in plugin) {
  18852. options.onwarn(errInputHookInOutputPlugin(plugin.name, hook));
  18853. }
  18854. }
  18855. }
  18856. }
  18857. }
  18858. createOutputPluginDriver(plugins) {
  18859. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  18860. }
  18861. // chains, first non-null result stops and returns
  18862. hookFirst(hookName, args, replaceContext, skipped) {
  18863. let promise = Promise.resolve(undefined);
  18864. for (const plugin of this.plugins) {
  18865. if (skipped && skipped.has(plugin))
  18866. continue;
  18867. promise = promise.then(result => {
  18868. if (result != null)
  18869. return result;
  18870. return this.runHook(hookName, args, plugin, false, replaceContext);
  18871. });
  18872. }
  18873. return promise;
  18874. }
  18875. // chains synchronously, first non-null result stops and returns
  18876. hookFirstSync(hookName, args, replaceContext) {
  18877. for (const plugin of this.plugins) {
  18878. const result = this.runHookSync(hookName, args, plugin, replaceContext);
  18879. if (result != null)
  18880. return result;
  18881. }
  18882. return null;
  18883. }
  18884. // parallel, ignores returns
  18885. hookParallel(hookName, args, replaceContext) {
  18886. const promises = [];
  18887. for (const plugin of this.plugins) {
  18888. const hookPromise = this.runHook(hookName, args, plugin, false, replaceContext);
  18889. if (!hookPromise)
  18890. continue;
  18891. promises.push(hookPromise);
  18892. }
  18893. return Promise.all(promises).then(() => { });
  18894. }
  18895. // chains, reduces returned value, handling the reduced value as the first hook argument
  18896. hookReduceArg0(hookName, [arg0, ...rest], reduce, replaceContext) {
  18897. let promise = Promise.resolve(arg0);
  18898. for (const plugin of this.plugins) {
  18899. promise = promise.then(arg0 => {
  18900. const args = [arg0, ...rest];
  18901. const hookPromise = this.runHook(hookName, args, plugin, false, replaceContext);
  18902. if (!hookPromise)
  18903. return arg0;
  18904. return hookPromise.then(result => reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin));
  18905. });
  18906. }
  18907. return promise;
  18908. }
  18909. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  18910. hookReduceArg0Sync(hookName, [arg0, ...rest], reduce, replaceContext) {
  18911. for (const plugin of this.plugins) {
  18912. const args = [arg0, ...rest];
  18913. const result = this.runHookSync(hookName, args, plugin, replaceContext);
  18914. arg0 = reduce.call(this.pluginContexts.get(plugin), arg0, result, plugin);
  18915. }
  18916. return arg0;
  18917. }
  18918. // chains, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  18919. hookReduceValue(hookName, initialValue, args, reduce, replaceContext) {
  18920. let promise = Promise.resolve(initialValue);
  18921. for (const plugin of this.plugins) {
  18922. promise = promise.then(value => {
  18923. const hookPromise = this.runHook(hookName, args, plugin, true, replaceContext);
  18924. if (!hookPromise)
  18925. return value;
  18926. return hookPromise.then(result => reduce.call(this.pluginContexts.get(plugin), value, result, plugin));
  18927. });
  18928. }
  18929. return promise;
  18930. }
  18931. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  18932. hookReduceValueSync(hookName, initialValue, args, reduce, replaceContext) {
  18933. let acc = initialValue;
  18934. for (const plugin of this.plugins) {
  18935. const result = this.runHookSync(hookName, args, plugin, replaceContext);
  18936. acc = reduce.call(this.pluginContexts.get(plugin), acc, result, plugin);
  18937. }
  18938. return acc;
  18939. }
  18940. // chains, ignores returns
  18941. hookSeq(hookName, args, replaceContext) {
  18942. let promise = Promise.resolve();
  18943. for (const plugin of this.plugins) {
  18944. promise = promise.then(() => this.runHook(hookName, args, plugin, false, replaceContext));
  18945. }
  18946. return promise;
  18947. }
  18948. // chains synchronously, ignores returns
  18949. hookSeqSync(hookName, args, replaceContext) {
  18950. for (const plugin of this.plugins) {
  18951. this.runHookSync(hookName, args, plugin, replaceContext);
  18952. }
  18953. }
  18954. runHook(hookName, args, plugin, permitValues, hookContext) {
  18955. const hook = plugin[hookName];
  18956. if (!hook)
  18957. return undefined;
  18958. let context = this.pluginContexts.get(plugin);
  18959. if (hookContext) {
  18960. context = hookContext(context, plugin);
  18961. }
  18962. return Promise.resolve()
  18963. .then(() => {
  18964. // permit values allows values to be returned instead of a functional hook
  18965. if (typeof hook !== 'function') {
  18966. if (permitValues)
  18967. return hook;
  18968. return throwInvalidHookError(hookName, plugin.name);
  18969. }
  18970. // eslint-disable-next-line @typescript-eslint/ban-types
  18971. return hook.apply(context, args);
  18972. })
  18973. .catch(err => throwPluginError(err, plugin.name, { hook: hookName }));
  18974. }
  18975. /**
  18976. * Run a sync plugin hook and return the result.
  18977. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  18978. * @param args Arguments passed to the plugin hook.
  18979. * @param plugin The acutal plugin
  18980. * @param hookContext When passed, the plugin context can be overridden.
  18981. */
  18982. runHookSync(hookName, args, plugin, hookContext) {
  18983. const hook = plugin[hookName];
  18984. if (!hook)
  18985. return undefined;
  18986. let context = this.pluginContexts.get(plugin);
  18987. if (hookContext) {
  18988. context = hookContext(context, plugin);
  18989. }
  18990. try {
  18991. // permit values allows values to be returned instead of a functional hook
  18992. if (typeof hook !== 'function') {
  18993. return throwInvalidHookError(hookName, plugin.name);
  18994. }
  18995. // eslint-disable-next-line @typescript-eslint/ban-types
  18996. return hook.apply(context, args);
  18997. }
  18998. catch (err) {
  18999. return throwPluginError(err, plugin.name, { hook: hookName });
  19000. }
  19001. }
  19002. }
  19003. function normalizeEntryModules(entryModules) {
  19004. if (Array.isArray(entryModules)) {
  19005. return entryModules.map(id => ({
  19006. fileName: null,
  19007. id,
  19008. implicitlyLoadedAfter: [],
  19009. importer: undefined,
  19010. name: null
  19011. }));
  19012. }
  19013. return Object.entries(entryModules).map(([name, id]) => ({
  19014. fileName: null,
  19015. id,
  19016. implicitlyLoadedAfter: [],
  19017. importer: undefined,
  19018. name
  19019. }));
  19020. }
  19021. class Graph {
  19022. constructor(options, watcher) {
  19023. var _a, _b;
  19024. this.options = options;
  19025. this.entryModules = [];
  19026. this.modulesById = new Map();
  19027. this.needsTreeshakingPass = false;
  19028. this.phase = BuildPhase.LOAD_AND_PARSE;
  19029. this.watchFiles = Object.create(null);
  19030. this.watchMode = false;
  19031. this.externalModules = [];
  19032. this.implicitEntryModules = [];
  19033. this.modules = [];
  19034. this.getModuleInfo = (moduleId) => {
  19035. const foundModule = this.modulesById.get(moduleId);
  19036. if (!foundModule)
  19037. return null;
  19038. return foundModule.info;
  19039. };
  19040. this.deoptimizationTracker = new PathTracker();
  19041. this.cachedModules = new Map();
  19042. if (options.cache !== false) {
  19043. if ((_a = options.cache) === null || _a === void 0 ? void 0 : _a.modules) {
  19044. for (const module of options.cache.modules)
  19045. this.cachedModules.set(module.id, module);
  19046. }
  19047. this.pluginCache = ((_b = options.cache) === null || _b === void 0 ? void 0 : _b.plugins) || Object.create(null);
  19048. // increment access counter
  19049. for (const name in this.pluginCache) {
  19050. const cache = this.pluginCache[name];
  19051. for (const value of Object.values(cache))
  19052. value[0]++;
  19053. }
  19054. }
  19055. if (watcher) {
  19056. this.watchMode = true;
  19057. const handleChange = (...args) => this.pluginDriver.hookSeqSync('watchChange', args);
  19058. const handleClose = () => this.pluginDriver.hookSeqSync('closeWatcher', []);
  19059. watcher.on('change', handleChange);
  19060. watcher.on('close', handleClose);
  19061. watcher.once('restart', () => {
  19062. watcher.removeListener('change', handleChange);
  19063. watcher.removeListener('close', handleClose);
  19064. });
  19065. }
  19066. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  19067. this.scope = new GlobalScope();
  19068. this.acornParser = Parser.extend(...options.acornInjectPlugins);
  19069. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  19070. }
  19071. async build() {
  19072. timeStart('generate module graph', 2);
  19073. await this.generateModuleGraph();
  19074. timeEnd('generate module graph', 2);
  19075. timeStart('sort modules', 2);
  19076. this.phase = BuildPhase.ANALYSE;
  19077. this.sortModules();
  19078. timeEnd('sort modules', 2);
  19079. timeStart('mark included statements', 2);
  19080. this.includeStatements();
  19081. timeEnd('mark included statements', 2);
  19082. this.phase = BuildPhase.GENERATE;
  19083. }
  19084. contextParse(code, options = {}) {
  19085. const onCommentOrig = options.onComment;
  19086. const comments = [];
  19087. if (onCommentOrig && typeof onCommentOrig == 'function') {
  19088. options.onComment = (block, text, start, end, ...args) => {
  19089. comments.push({ end, start, type: block ? 'Block' : 'Line', value: text });
  19090. return onCommentOrig.call(options, block, text, start, end, ...args);
  19091. };
  19092. }
  19093. else {
  19094. options.onComment = comments;
  19095. }
  19096. const ast = this.acornParser.parse(code, {
  19097. ...this.options.acorn,
  19098. ...options
  19099. });
  19100. if (typeof onCommentOrig == 'object') {
  19101. onCommentOrig.push(...comments);
  19102. }
  19103. options.onComment = onCommentOrig;
  19104. addAnnotations(comments, ast, code);
  19105. return ast;
  19106. }
  19107. getCache() {
  19108. // handle plugin cache eviction
  19109. for (const name in this.pluginCache) {
  19110. const cache = this.pluginCache[name];
  19111. let allDeleted = true;
  19112. for (const [key, value] of Object.entries(cache)) {
  19113. if (value[0] >= this.options.experimentalCacheExpiry)
  19114. delete cache[key];
  19115. else
  19116. allDeleted = false;
  19117. }
  19118. if (allDeleted)
  19119. delete this.pluginCache[name];
  19120. }
  19121. return {
  19122. modules: this.modules.map(module => module.toJSON()),
  19123. plugins: this.pluginCache
  19124. };
  19125. }
  19126. async generateModuleGraph() {
  19127. ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
  19128. await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  19129. if (this.entryModules.length === 0) {
  19130. throw new Error('You must supply options.input to rollup');
  19131. }
  19132. for (const module of this.modulesById.values()) {
  19133. if (module instanceof Module) {
  19134. this.modules.push(module);
  19135. }
  19136. else {
  19137. this.externalModules.push(module);
  19138. }
  19139. }
  19140. }
  19141. includeStatements() {
  19142. for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
  19143. markModuleAndImpureDependenciesAsExecuted(module);
  19144. }
  19145. if (this.options.treeshake) {
  19146. let treeshakingPass = 1;
  19147. do {
  19148. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  19149. this.needsTreeshakingPass = false;
  19150. for (const module of this.modules) {
  19151. if (module.isExecuted) {
  19152. if (module.info.hasModuleSideEffects === 'no-treeshake') {
  19153. module.includeAllInBundle();
  19154. }
  19155. else {
  19156. module.include();
  19157. }
  19158. }
  19159. }
  19160. if (treeshakingPass === 1) {
  19161. // We only include exports after the first pass to avoid issues with
  19162. // the TDZ detection logic
  19163. for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
  19164. if (module.preserveSignature !== false) {
  19165. module.includeAllExports(false);
  19166. this.needsTreeshakingPass = true;
  19167. }
  19168. }
  19169. }
  19170. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  19171. } while (this.needsTreeshakingPass);
  19172. }
  19173. else {
  19174. for (const module of this.modules)
  19175. module.includeAllInBundle();
  19176. }
  19177. for (const externalModule of this.externalModules)
  19178. externalModule.warnUnusedImports();
  19179. for (const module of this.implicitEntryModules) {
  19180. for (const dependant of module.implicitlyLoadedAfter) {
  19181. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  19182. error(errImplicitDependantIsNotIncluded(dependant));
  19183. }
  19184. }
  19185. }
  19186. }
  19187. sortModules() {
  19188. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  19189. for (const cyclePath of cyclePaths) {
  19190. this.options.onwarn({
  19191. code: 'CIRCULAR_DEPENDENCY',
  19192. cycle: cyclePath,
  19193. importer: cyclePath[0],
  19194. message: `Circular dependency: ${cyclePath.join(' -> ')}`
  19195. });
  19196. }
  19197. this.modules = orderedModules;
  19198. for (const module of this.modules) {
  19199. module.bindReferences();
  19200. }
  19201. this.warnForMissingExports();
  19202. }
  19203. warnForMissingExports() {
  19204. for (const module of this.modules) {
  19205. for (const importDescription of Object.values(module.importDescriptions)) {
  19206. if (importDescription.name !== '*' &&
  19207. !importDescription.module.getVariableForExportName(importDescription.name)) {
  19208. module.warn({
  19209. code: 'NON_EXISTENT_EXPORT',
  19210. message: `Non-existent export '${importDescription.name}' is imported from ${relativeId(importDescription.module.id)}`,
  19211. name: importDescription.name,
  19212. source: importDescription.module.id
  19213. }, importDescription.start);
  19214. }
  19215. }
  19216. }
  19217. }
  19218. }
  19219. function ensureArray(items) {
  19220. if (Array.isArray(items)) {
  19221. return items.filter(Boolean);
  19222. }
  19223. if (items) {
  19224. return [items];
  19225. }
  19226. return [];
  19227. }
  19228. const defaultOnWarn = warning => console.warn(warning.message || warning);
  19229. function warnUnknownOptions(passedOptions, validOptions, optionType, warn, ignoredKeys = /$./) {
  19230. const validOptionSet = new Set(validOptions);
  19231. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  19232. if (unknownOptions.length > 0) {
  19233. warn({
  19234. code: 'UNKNOWN_OPTION',
  19235. message: `Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${[
  19236. ...validOptionSet
  19237. ]
  19238. .sort()
  19239. .join(', ')}`
  19240. });
  19241. }
  19242. }
  19243. const treeshakePresets = {
  19244. recommended: {
  19245. annotations: true,
  19246. correctVarValueBeforeDeclaration: false,
  19247. moduleSideEffects: () => true,
  19248. propertyReadSideEffects: true,
  19249. tryCatchDeoptimization: true,
  19250. unknownGlobalSideEffects: false
  19251. },
  19252. safest: {
  19253. annotations: true,
  19254. correctVarValueBeforeDeclaration: true,
  19255. moduleSideEffects: () => true,
  19256. propertyReadSideEffects: true,
  19257. tryCatchDeoptimization: true,
  19258. unknownGlobalSideEffects: true
  19259. },
  19260. smallest: {
  19261. annotations: true,
  19262. correctVarValueBeforeDeclaration: false,
  19263. moduleSideEffects: () => false,
  19264. propertyReadSideEffects: false,
  19265. tryCatchDeoptimization: false,
  19266. unknownGlobalSideEffects: false
  19267. }
  19268. };
  19269. function normalizeInputOptions(config) {
  19270. var _a, _b, _c;
  19271. // These are options that may trigger special warnings or behaviour later
  19272. // if the user did not select an explicit value
  19273. const unsetOptions = new Set();
  19274. const context = (_a = config.context) !== null && _a !== void 0 ? _a : 'undefined';
  19275. const onwarn = getOnwarn(config);
  19276. const strictDeprecations = config.strictDeprecations || false;
  19277. const options = {
  19278. acorn: getAcorn(config),
  19279. acornInjectPlugins: getAcornInjectPlugins(config),
  19280. cache: getCache(config),
  19281. context,
  19282. experimentalCacheExpiry: (_b = config.experimentalCacheExpiry) !== null && _b !== void 0 ? _b : 10,
  19283. external: getIdMatcher(config.external),
  19284. inlineDynamicImports: getInlineDynamicImports$1(config, onwarn, strictDeprecations),
  19285. input: getInput(config),
  19286. makeAbsoluteExternalsRelative: (_c = config.makeAbsoluteExternalsRelative) !== null && _c !== void 0 ? _c : true,
  19287. manualChunks: getManualChunks$1(config, onwarn, strictDeprecations),
  19288. maxParallelFileReads: getMaxParallelFileReads(config),
  19289. moduleContext: getModuleContext(config, context),
  19290. onwarn,
  19291. perf: config.perf || false,
  19292. plugins: ensureArray(config.plugins),
  19293. preserveEntrySignatures: getPreserveEntrySignatures(config, unsetOptions),
  19294. preserveModules: getPreserveModules$1(config, onwarn, strictDeprecations),
  19295. preserveSymlinks: config.preserveSymlinks || false,
  19296. shimMissingExports: config.shimMissingExports || false,
  19297. strictDeprecations,
  19298. treeshake: getTreeshake(config, onwarn, strictDeprecations)
  19299. };
  19300. warnUnknownOptions(config, [...Object.keys(options), 'watch'], 'input options', options.onwarn, /^(output)$/);
  19301. return { options, unsetOptions };
  19302. }
  19303. const getOnwarn = (config) => {
  19304. const { onwarn } = config;
  19305. return onwarn
  19306. ? warning => {
  19307. warning.toString = () => {
  19308. let str = '';
  19309. if (warning.plugin)
  19310. str += `(${warning.plugin} plugin) `;
  19311. if (warning.loc)
  19312. str += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
  19313. str += warning.message;
  19314. return str;
  19315. };
  19316. onwarn(warning, defaultOnWarn);
  19317. }
  19318. : defaultOnWarn;
  19319. };
  19320. const getAcorn = (config) => ({
  19321. allowAwaitOutsideFunction: true,
  19322. ecmaVersion: 'latest',
  19323. preserveParens: false,
  19324. sourceType: 'module',
  19325. ...config.acorn
  19326. });
  19327. const getAcornInjectPlugins = (config) => ensureArray(config.acornInjectPlugins);
  19328. const getCache = (config) => { var _a; return ((_a = config.cache) === null || _a === void 0 ? void 0 : _a.cache) || config.cache; };
  19329. const getIdMatcher = (option) => {
  19330. if (option === true) {
  19331. return () => true;
  19332. }
  19333. if (typeof option === 'function') {
  19334. return (id, ...args) => (!id.startsWith('\0') && option(id, ...args)) || false;
  19335. }
  19336. if (option) {
  19337. const ids = new Set();
  19338. const matchers = [];
  19339. for (const value of ensureArray(option)) {
  19340. if (value instanceof RegExp) {
  19341. matchers.push(value);
  19342. }
  19343. else {
  19344. ids.add(value);
  19345. }
  19346. }
  19347. return (id, ..._args) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  19348. }
  19349. return () => false;
  19350. };
  19351. const getInlineDynamicImports$1 = (config, warn, strictDeprecations) => {
  19352. const configInlineDynamicImports = config.inlineDynamicImports;
  19353. if (configInlineDynamicImports) {
  19354. warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', false, warn, strictDeprecations);
  19355. }
  19356. return configInlineDynamicImports;
  19357. };
  19358. const getInput = (config) => {
  19359. const configInput = config.input;
  19360. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  19361. };
  19362. const getManualChunks$1 = (config, warn, strictDeprecations) => {
  19363. const configManualChunks = config.manualChunks;
  19364. if (configManualChunks) {
  19365. warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', false, warn, strictDeprecations);
  19366. }
  19367. return configManualChunks;
  19368. };
  19369. const getMaxParallelFileReads = (config) => {
  19370. const maxParallelFileReads = config.maxParallelFileReads;
  19371. if (typeof maxParallelFileReads === 'number') {
  19372. if (maxParallelFileReads <= 0)
  19373. return Infinity;
  19374. return maxParallelFileReads;
  19375. }
  19376. return 20;
  19377. };
  19378. const getModuleContext = (config, context) => {
  19379. const configModuleContext = config.moduleContext;
  19380. if (typeof configModuleContext === 'function') {
  19381. return id => { var _a; return (_a = configModuleContext(id)) !== null && _a !== void 0 ? _a : context; };
  19382. }
  19383. if (configModuleContext) {
  19384. const contextByModuleId = Object.create(null);
  19385. for (const [key, moduleContext] of Object.entries(configModuleContext)) {
  19386. contextByModuleId[resolve(key)] = moduleContext;
  19387. }
  19388. return id => contextByModuleId[id] || context;
  19389. }
  19390. return () => context;
  19391. };
  19392. const getPreserveEntrySignatures = (config, unsetOptions) => {
  19393. const configPreserveEntrySignatures = config.preserveEntrySignatures;
  19394. if (configPreserveEntrySignatures == null) {
  19395. unsetOptions.add('preserveEntrySignatures');
  19396. }
  19397. return configPreserveEntrySignatures !== null && configPreserveEntrySignatures !== void 0 ? configPreserveEntrySignatures : 'strict';
  19398. };
  19399. const getPreserveModules$1 = (config, warn, strictDeprecations) => {
  19400. const configPreserveModules = config.preserveModules;
  19401. if (configPreserveModules) {
  19402. warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', false, warn, strictDeprecations);
  19403. }
  19404. return configPreserveModules;
  19405. };
  19406. const getTreeshake = (config, warn, strictDeprecations) => {
  19407. const configTreeshake = config.treeshake;
  19408. if (configTreeshake === false) {
  19409. return false;
  19410. }
  19411. if (typeof configTreeshake === 'string') {
  19412. const preset = treeshakePresets[configTreeshake];
  19413. if (preset) {
  19414. return preset;
  19415. }
  19416. error(errInvalidOption('treeshake', `valid values are false, true, ${printQuotedStringList(Object.keys(treeshakePresets))}. You can also supply an object for more fine-grained control`));
  19417. }
  19418. let configWithPreset = {};
  19419. if (typeof configTreeshake === 'object') {
  19420. if (typeof configTreeshake.pureExternalModules !== 'undefined') {
  19421. 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);
  19422. }
  19423. configWithPreset = configTreeshake;
  19424. const presetName = configTreeshake.preset;
  19425. if (presetName) {
  19426. const preset = treeshakePresets[presetName];
  19427. if (preset) {
  19428. configWithPreset = { ...preset, ...configTreeshake };
  19429. }
  19430. else {
  19431. error(errInvalidOption('treeshake.preset', `valid values are ${printQuotedStringList(Object.keys(treeshakePresets))}`));
  19432. }
  19433. }
  19434. }
  19435. return {
  19436. annotations: configWithPreset.annotations !== false,
  19437. correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
  19438. moduleSideEffects: typeof configTreeshake === 'object' && configTreeshake.pureExternalModules
  19439. ? getHasModuleSideEffects(configTreeshake.moduleSideEffects, configTreeshake.pureExternalModules)
  19440. : getHasModuleSideEffects(configWithPreset.moduleSideEffects, undefined),
  19441. propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
  19442. ? 'always'
  19443. : configWithPreset.propertyReadSideEffects !== false,
  19444. tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
  19445. unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
  19446. };
  19447. };
  19448. const getHasModuleSideEffects = (moduleSideEffectsOption, pureExternalModules) => {
  19449. if (typeof moduleSideEffectsOption === 'boolean') {
  19450. return () => moduleSideEffectsOption;
  19451. }
  19452. if (moduleSideEffectsOption === 'no-external') {
  19453. return (_id, external) => !external;
  19454. }
  19455. if (typeof moduleSideEffectsOption === 'function') {
  19456. return (id, external) => !id.startsWith('\0') ? moduleSideEffectsOption(id, external) !== false : true;
  19457. }
  19458. if (Array.isArray(moduleSideEffectsOption)) {
  19459. const ids = new Set(moduleSideEffectsOption);
  19460. return id => ids.has(id);
  19461. }
  19462. if (moduleSideEffectsOption) {
  19463. error(errInvalidOption('treeshake.moduleSideEffects', 'please use one of false, "no-external", a function or an array'));
  19464. }
  19465. const isPureExternalModule = getIdMatcher(pureExternalModules);
  19466. return (id, external) => !(external && isPureExternalModule(id));
  19467. };
  19468. function sanitizeFileName(name) {
  19469. const match = /^[a-z]:/i.exec(name);
  19470. const driveLetter = match ? match[0] : '';
  19471. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  19472. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  19473. return driveLetter + name.substr(driveLetter.length).replace(/[\0?*:]/g, '_');
  19474. }
  19475. function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  19476. var _a, _b, _c, _d, _e, _f, _g;
  19477. // These are options that may trigger special warnings or behaviour later
  19478. // if the user did not select an explicit value
  19479. const unsetOptions = new Set(unsetInputOptions);
  19480. const compact = config.compact || false;
  19481. const format = getFormat(config);
  19482. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  19483. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  19484. const file = getFile(config, preserveModules, inputOptions);
  19485. const outputOptions = {
  19486. amd: getAmd(config),
  19487. assetFileNames: (_a = config.assetFileNames) !== null && _a !== void 0 ? _a : 'assets/[name]-[hash][extname]',
  19488. banner: getAddon(config, 'banner'),
  19489. chunkFileNames: (_b = config.chunkFileNames) !== null && _b !== void 0 ? _b : '[name]-[hash].js',
  19490. compact,
  19491. dir: getDir(config, file),
  19492. dynamicImportFunction: getDynamicImportFunction(config, inputOptions),
  19493. entryFileNames: getEntryFileNames(config, unsetOptions),
  19494. esModule: (_c = config.esModule) !== null && _c !== void 0 ? _c : true,
  19495. exports: getExports(config, unsetOptions),
  19496. extend: config.extend || false,
  19497. externalLiveBindings: (_d = config.externalLiveBindings) !== null && _d !== void 0 ? _d : true,
  19498. file,
  19499. footer: getAddon(config, 'footer'),
  19500. format,
  19501. freeze: (_e = config.freeze) !== null && _e !== void 0 ? _e : true,
  19502. globals: config.globals || {},
  19503. hoistTransitiveImports: (_f = config.hoistTransitiveImports) !== null && _f !== void 0 ? _f : true,
  19504. indent: getIndent(config, compact),
  19505. inlineDynamicImports,
  19506. interop: getInterop(config, inputOptions),
  19507. intro: getAddon(config, 'intro'),
  19508. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules, inputOptions),
  19509. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  19510. name: config.name,
  19511. namespaceToStringTag: config.namespaceToStringTag || false,
  19512. noConflict: config.noConflict || false,
  19513. outro: getAddon(config, 'outro'),
  19514. paths: config.paths || {},
  19515. plugins: ensureArray(config.plugins),
  19516. preferConst: config.preferConst || false,
  19517. preserveModules,
  19518. preserveModulesRoot: getPreserveModulesRoot(config),
  19519. sanitizeFileName: typeof config.sanitizeFileName === 'function'
  19520. ? config.sanitizeFileName
  19521. : config.sanitizeFileName === false
  19522. ? id => id
  19523. : sanitizeFileName,
  19524. sourcemap: config.sourcemap || false,
  19525. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  19526. sourcemapFile: config.sourcemapFile,
  19527. sourcemapPathTransform: config.sourcemapPathTransform,
  19528. strict: (_g = config.strict) !== null && _g !== void 0 ? _g : true,
  19529. systemNullSetters: config.systemNullSetters || false,
  19530. validate: config.validate || false
  19531. };
  19532. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onwarn);
  19533. return { options: outputOptions, unsetOptions };
  19534. }
  19535. const getFile = (config, preserveModules, inputOptions) => {
  19536. const { file } = config;
  19537. if (typeof file === 'string') {
  19538. if (preserveModules) {
  19539. return error({
  19540. code: 'INVALID_OPTION',
  19541. message: 'You must set "output.dir" instead of "output.file" when using the "output.preserveModules" option.'
  19542. });
  19543. }
  19544. if (!Array.isArray(inputOptions.input))
  19545. return error({
  19546. code: 'INVALID_OPTION',
  19547. message: 'You must set "output.dir" instead of "output.file" when providing named inputs.'
  19548. });
  19549. }
  19550. return file;
  19551. };
  19552. const getFormat = (config) => {
  19553. const configFormat = config.format;
  19554. switch (configFormat) {
  19555. case undefined:
  19556. case 'es':
  19557. case 'esm':
  19558. case 'module':
  19559. return 'es';
  19560. case 'cjs':
  19561. case 'commonjs':
  19562. return 'cjs';
  19563. case 'system':
  19564. case 'systemjs':
  19565. return 'system';
  19566. case 'amd':
  19567. case 'iife':
  19568. case 'umd':
  19569. return configFormat;
  19570. default:
  19571. return error({
  19572. message: `You must specify "output.format", which can be one of "amd", "cjs", "system", "es", "iife" or "umd".`,
  19573. url: `https://rollupjs.org/guide/en/#outputformat`
  19574. });
  19575. }
  19576. };
  19577. const getInlineDynamicImports = (config, inputOptions) => {
  19578. var _a;
  19579. const inlineDynamicImports = ((_a = config.inlineDynamicImports) !== null && _a !== void 0 ? _a : inputOptions.inlineDynamicImports) || false;
  19580. const { input } = inputOptions;
  19581. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  19582. return error({
  19583. code: 'INVALID_OPTION',
  19584. message: 'Multiple inputs are not supported for "output.inlineDynamicImports".'
  19585. });
  19586. }
  19587. return inlineDynamicImports;
  19588. };
  19589. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  19590. var _a;
  19591. const preserveModules = ((_a = config.preserveModules) !== null && _a !== void 0 ? _a : inputOptions.preserveModules) || false;
  19592. if (preserveModules) {
  19593. if (inlineDynamicImports) {
  19594. return error({
  19595. code: 'INVALID_OPTION',
  19596. message: `The "output.inlineDynamicImports" option is not supported for "output.preserveModules".`
  19597. });
  19598. }
  19599. if (inputOptions.preserveEntrySignatures === false) {
  19600. return error({
  19601. code: 'INVALID_OPTION',
  19602. message: 'Setting "preserveEntrySignatures" to "false" is not supported for "output.preserveModules".'
  19603. });
  19604. }
  19605. }
  19606. return preserveModules;
  19607. };
  19608. const getPreserveModulesRoot = (config) => {
  19609. const { preserveModulesRoot } = config;
  19610. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  19611. return undefined;
  19612. }
  19613. return resolve(preserveModulesRoot);
  19614. };
  19615. const getAmd = (config) => {
  19616. const collection = {
  19617. autoId: false,
  19618. basePath: '',
  19619. define: 'define',
  19620. ...config.amd
  19621. };
  19622. if ((collection.autoId || collection.basePath) && collection.id) {
  19623. return error({
  19624. code: 'INVALID_OPTION',
  19625. message: '"output.amd.autoId"/"output.amd.basePath" and "output.amd.id" cannot be used together.'
  19626. });
  19627. }
  19628. if (collection.basePath && !collection.autoId) {
  19629. return error({
  19630. code: 'INVALID_OPTION',
  19631. message: '"output.amd.basePath" only works with "output.amd.autoId".'
  19632. });
  19633. }
  19634. let normalized;
  19635. if (collection.autoId) {
  19636. normalized = {
  19637. autoId: true,
  19638. basePath: collection.basePath,
  19639. define: collection.define
  19640. };
  19641. }
  19642. else {
  19643. normalized = {
  19644. autoId: false,
  19645. define: collection.define,
  19646. id: collection.id
  19647. };
  19648. }
  19649. return normalized;
  19650. };
  19651. const getAddon = (config, name) => {
  19652. const configAddon = config[name];
  19653. if (typeof configAddon === 'function') {
  19654. return configAddon;
  19655. }
  19656. return () => configAddon || '';
  19657. };
  19658. const getDir = (config, file) => {
  19659. const { dir } = config;
  19660. if (typeof dir === 'string' && typeof file === 'string') {
  19661. return error({
  19662. code: 'INVALID_OPTION',
  19663. message: 'You must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks.'
  19664. });
  19665. }
  19666. return dir;
  19667. };
  19668. const getDynamicImportFunction = (config, inputOptions) => {
  19669. const configDynamicImportFunction = config.dynamicImportFunction;
  19670. if (configDynamicImportFunction) {
  19671. warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, false, inputOptions);
  19672. }
  19673. return configDynamicImportFunction;
  19674. };
  19675. const getEntryFileNames = (config, unsetOptions) => {
  19676. const configEntryFileNames = config.entryFileNames;
  19677. if (configEntryFileNames == null) {
  19678. unsetOptions.add('entryFileNames');
  19679. }
  19680. return configEntryFileNames !== null && configEntryFileNames !== void 0 ? configEntryFileNames : '[name].js';
  19681. };
  19682. function getExports(config, unsetOptions) {
  19683. const configExports = config.exports;
  19684. if (configExports == null) {
  19685. unsetOptions.add('exports');
  19686. }
  19687. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  19688. return error(errInvalidExportOptionValue(configExports));
  19689. }
  19690. return configExports || 'auto';
  19691. }
  19692. const getIndent = (config, compact) => {
  19693. if (compact) {
  19694. return '';
  19695. }
  19696. const configIndent = config.indent;
  19697. return configIndent === false ? '' : configIndent !== null && configIndent !== void 0 ? configIndent : true;
  19698. };
  19699. const ALLOWED_INTEROP_TYPES = new Set(['auto', 'esModule', 'default', 'defaultOnly', true, false]);
  19700. const getInterop = (config, inputOptions) => {
  19701. const configInterop = config.interop;
  19702. const validatedInteropTypes = new Set();
  19703. const validateInterop = (interop) => {
  19704. if (!validatedInteropTypes.has(interop)) {
  19705. validatedInteropTypes.add(interop);
  19706. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  19707. return error({
  19708. code: 'INVALID_OPTION',
  19709. 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.`,
  19710. url: 'https://rollupjs.org/guide/en/#outputinterop'
  19711. });
  19712. }
  19713. if (typeof interop === 'boolean') {
  19714. warnDeprecation({
  19715. message: `The boolean value "${interop}" for the "output.interop" option is deprecated. Use ${interop ? '"auto"' : '"esModule", "default" or "defaultOnly"'} instead.`,
  19716. url: 'https://rollupjs.org/guide/en/#outputinterop'
  19717. }, false, inputOptions);
  19718. }
  19719. }
  19720. return interop;
  19721. };
  19722. if (typeof configInterop === 'function') {
  19723. const interopPerId = Object.create(null);
  19724. let defaultInterop = null;
  19725. return id => id === null
  19726. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  19727. : id in interopPerId
  19728. ? interopPerId[id]
  19729. : validateInterop((interopPerId[id] = configInterop(id)));
  19730. }
  19731. return configInterop === undefined ? () => true : () => validateInterop(configInterop);
  19732. };
  19733. const getManualChunks = (config, inlineDynamicImports, preserveModules, inputOptions) => {
  19734. const configManualChunks = config.manualChunks || inputOptions.manualChunks;
  19735. if (configManualChunks) {
  19736. if (inlineDynamicImports) {
  19737. return error({
  19738. code: 'INVALID_OPTION',
  19739. message: 'The "output.manualChunks" option is not supported for "output.inlineDynamicImports".'
  19740. });
  19741. }
  19742. if (preserveModules) {
  19743. return error({
  19744. code: 'INVALID_OPTION',
  19745. message: 'The "output.manualChunks" option is not supported for "output.preserveModules".'
  19746. });
  19747. }
  19748. }
  19749. return configManualChunks || {};
  19750. };
  19751. const getMinifyInternalExports = (config, format, compact) => { var _a; return (_a = config.minifyInternalExports) !== null && _a !== void 0 ? _a : (compact || format === 'es' || format === 'system'); };
  19752. function rollup(rawInputOptions) {
  19753. return rollupInternal(rawInputOptions, null);
  19754. }
  19755. async function rollupInternal(rawInputOptions, watcher) {
  19756. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  19757. initialiseTimers(inputOptions);
  19758. const graph = new Graph(inputOptions, watcher);
  19759. // remove the cache option from the memory after graph creation (cache is not used anymore)
  19760. const useCache = rawInputOptions.cache !== false;
  19761. delete inputOptions.cache;
  19762. delete rawInputOptions.cache;
  19763. timeStart('BUILD', 1);
  19764. try {
  19765. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  19766. await graph.build();
  19767. }
  19768. catch (err) {
  19769. const watchFiles = Object.keys(graph.watchFiles);
  19770. if (watchFiles.length > 0) {
  19771. err.watchFiles = watchFiles;
  19772. }
  19773. await graph.pluginDriver.hookParallel('buildEnd', [err]);
  19774. await graph.pluginDriver.hookParallel('closeBundle', []);
  19775. throw err;
  19776. }
  19777. await graph.pluginDriver.hookParallel('buildEnd', []);
  19778. timeEnd('BUILD', 1);
  19779. const result = {
  19780. cache: useCache ? graph.getCache() : undefined,
  19781. async close() {
  19782. if (result.closed)
  19783. return;
  19784. result.closed = true;
  19785. await graph.pluginDriver.hookParallel('closeBundle', []);
  19786. },
  19787. closed: false,
  19788. async generate(rawOutputOptions) {
  19789. if (result.closed)
  19790. return error(errAlreadyClosed());
  19791. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  19792. },
  19793. watchFiles: Object.keys(graph.watchFiles),
  19794. async write(rawOutputOptions) {
  19795. if (result.closed)
  19796. return error(errAlreadyClosed());
  19797. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  19798. }
  19799. };
  19800. if (inputOptions.perf)
  19801. result.getTimings = getTimings;
  19802. return result;
  19803. }
  19804. async function getInputOptions(rawInputOptions, watchMode) {
  19805. if (!rawInputOptions) {
  19806. throw new Error('You must supply an options object to rollup');
  19807. }
  19808. const rawPlugins = ensureArray(rawInputOptions.plugins);
  19809. const { options, unsetOptions } = normalizeInputOptions(await rawPlugins.reduce(applyOptionHook(watchMode), Promise.resolve(rawInputOptions)));
  19810. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  19811. return { options, unsetOptions };
  19812. }
  19813. function applyOptionHook(watchMode) {
  19814. return async (inputOptions, plugin) => {
  19815. if (plugin.options) {
  19816. return ((await plugin.options.call({ meta: { rollupVersion: version$1, watchMode } }, await inputOptions)) || inputOptions);
  19817. }
  19818. return inputOptions;
  19819. };
  19820. }
  19821. function normalizePlugins(plugins, anonymousPrefix) {
  19822. for (let pluginIndex = 0; pluginIndex < plugins.length; pluginIndex++) {
  19823. const plugin = plugins[pluginIndex];
  19824. if (!plugin.name) {
  19825. plugin.name = `${anonymousPrefix}${pluginIndex + 1}`;
  19826. }
  19827. }
  19828. }
  19829. async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  19830. const { options: outputOptions, outputPluginDriver, unsetOptions } = getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  19831. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  19832. const generated = await bundle.generate(isWrite);
  19833. if (isWrite) {
  19834. if (!outputOptions.dir && !outputOptions.file) {
  19835. return error({
  19836. code: 'MISSING_OPTION',
  19837. message: 'You must specify "output.file" or "output.dir" for the build.'
  19838. });
  19839. }
  19840. await Promise.all(Object.values(generated).map(chunk => writeOutputFile(chunk, outputOptions)));
  19841. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  19842. }
  19843. return createOutput(generated);
  19844. }
  19845. function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  19846. if (!rawOutputOptions) {
  19847. throw new Error('You must supply an options object');
  19848. }
  19849. const rawPlugins = ensureArray(rawOutputOptions.plugins);
  19850. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  19851. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  19852. return {
  19853. ...getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver),
  19854. outputPluginDriver
  19855. };
  19856. }
  19857. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  19858. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions.output || rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  19859. const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook());
  19860. return {
  19861. ...pluginContext,
  19862. emitFile: emitError,
  19863. setAssetSource: emitError
  19864. };
  19865. }), inputOptions, unsetInputOptions);
  19866. }
  19867. function createOutput(outputBundle) {
  19868. return {
  19869. output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => {
  19870. const fileTypeA = getSortingFileType(outputFileA);
  19871. const fileTypeB = getSortingFileType(outputFileB);
  19872. if (fileTypeA === fileTypeB)
  19873. return 0;
  19874. return fileTypeA < fileTypeB ? -1 : 1;
  19875. })
  19876. };
  19877. }
  19878. var SortingFileType;
  19879. (function (SortingFileType) {
  19880. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  19881. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  19882. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  19883. })(SortingFileType || (SortingFileType = {}));
  19884. function getSortingFileType(file) {
  19885. if (file.type === 'asset') {
  19886. return SortingFileType.ASSET;
  19887. }
  19888. if (file.isEntry) {
  19889. return SortingFileType.ENTRY_CHUNK;
  19890. }
  19891. return SortingFileType.SECONDARY_CHUNK;
  19892. }
  19893. function writeOutputFile(outputFile, outputOptions) {
  19894. const fileName = resolve(outputOptions.dir || dirname(outputOptions.file), outputFile.fileName);
  19895. let writeSourceMapPromise;
  19896. let source;
  19897. if (outputFile.type === 'asset') {
  19898. source = outputFile.source;
  19899. }
  19900. else {
  19901. source = outputFile.code;
  19902. if (outputOptions.sourcemap && outputFile.map) {
  19903. let url;
  19904. if (outputOptions.sourcemap === 'inline') {
  19905. url = outputFile.map.toUrl();
  19906. }
  19907. else {
  19908. url = `${basename(outputFile.fileName)}.map`;
  19909. writeSourceMapPromise = writeFile(`${fileName}.map`, outputFile.map.toString());
  19910. }
  19911. if (outputOptions.sourcemap !== 'hidden') {
  19912. source += `//# ${SOURCEMAPPING_URL}=${url}\n`;
  19913. }
  19914. }
  19915. }
  19916. return Promise.all([writeFile(fileName, source), writeSourceMapPromise]);
  19917. }
  19918. /**
  19919. * Auxiliary function for defining rollup configuration
  19920. * Mainly to facilitate IDE code prompts, after all, export default does not prompt, even if you add @type annotations, it is not accurate
  19921. * @param options
  19922. */
  19923. function defineConfig(options) {
  19924. return options;
  19925. }
  19926. let fsEvents;
  19927. let fsEventsImportError;
  19928. function loadFsEvents() {
  19929. return import('fsevents')
  19930. .then(namespace => {
  19931. fsEvents = namespace.default;
  19932. })
  19933. .catch(err => {
  19934. fsEventsImportError = err;
  19935. });
  19936. }
  19937. // A call to this function will be injected into the chokidar code
  19938. function getFsEvents() {
  19939. if (fsEventsImportError)
  19940. throw fsEventsImportError;
  19941. return fsEvents;
  19942. }
  19943. var fseventsImporter = {
  19944. __proto__: null,
  19945. loadFsEvents: loadFsEvents,
  19946. getFsEvents: getFsEvents
  19947. };
  19948. class WatchEmitter extends EventEmitter {
  19949. constructor() {
  19950. super();
  19951. // Allows more than 10 bundles to be watched without
  19952. // showing the `MaxListenersExceededWarning` to the user.
  19953. this.setMaxListeners(Infinity);
  19954. }
  19955. close() { }
  19956. }
  19957. function watch(configs) {
  19958. const emitter = new WatchEmitter();
  19959. const configArray = ensureArray(configs);
  19960. const watchConfigs = configArray.filter(config => config.watch !== false);
  19961. if (watchConfigs.length === 0) {
  19962. throw error(errInvalidOption('watch', 'there must be at least one config where "watch" is not set to "false"'));
  19963. }
  19964. loadFsEvents()
  19965. .then(() => import('./watch.js'))
  19966. .then(({ Watcher }) => new Watcher(watchConfigs, emitter));
  19967. return emitter;
  19968. }
  19969. export { defaultOnWarn, defineConfig, ensureArray, errInvalidOption, error, fseventsImporter, printQuotedStringList, rollup, rollupInternal, treeshakePresets, version$1 as version, warnUnknownOptions, watch };