compiler-sfc.esm-browser.js 1.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088
  1. /**
  2. * @vue/compiler-sfc v3.5.35
  3. * (c) 2018-present Yuxi (Evan) You and Vue contributors
  4. * @license MIT
  5. **/
  6. // @__NO_SIDE_EFFECTS__
  7. function makeMap(str) {
  8. const map = /* @__PURE__ */ Object.create(null);
  9. for (const key of str.split(",")) map[key] = 1;
  10. return (val) => val in map;
  11. }
  12. const EMPTY_OBJ = Object.freeze({}) ;
  13. const NOOP = () => {
  14. };
  15. const NO = () => false;
  16. const isOn = (key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && // uppercase letter
  17. (key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97);
  18. const extend = Object.assign;
  19. const hasOwnProperty$3 = Object.prototype.hasOwnProperty;
  20. const hasOwn = (val, key) => hasOwnProperty$3.call(val, key);
  21. const isArray$3 = Array.isArray;
  22. const isMap = (val) => toTypeString(val) === "[object Map]";
  23. const isSet = (val) => toTypeString(val) === "[object Set]";
  24. const isFunction$1 = (val) => typeof val === "function";
  25. const isString$1 = (val) => typeof val === "string";
  26. const isSymbol$1 = (val) => typeof val === "symbol";
  27. const isObject$2 = (val) => val !== null && typeof val === "object";
  28. const objectToString$1 = Object.prototype.toString;
  29. const toTypeString = (value) => objectToString$1.call(value);
  30. const isPlainObject = (val) => toTypeString(val) === "[object Object]";
  31. const isReservedProp = /* @__PURE__ */ makeMap(
  32. // the leading comma is intentional so empty string "" is also included
  33. ",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"
  34. );
  35. const isBuiltInDirective = /* @__PURE__ */ makeMap(
  36. "bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo"
  37. );
  38. const cacheStringFunction = (fn) => {
  39. const cache = /* @__PURE__ */ Object.create(null);
  40. return ((str) => {
  41. const hit = cache[str];
  42. return hit || (cache[str] = fn(str));
  43. });
  44. };
  45. const camelizeRE = /-\w/g;
  46. const camelize = cacheStringFunction(
  47. (str) => {
  48. return str.replace(camelizeRE, (c) => c.slice(1).toUpperCase());
  49. }
  50. );
  51. const hyphenateRE = /\B([A-Z])/g;
  52. const hyphenate = cacheStringFunction(
  53. (str) => str.replace(hyphenateRE, "-$1").toLowerCase()
  54. );
  55. const capitalize = cacheStringFunction((str) => {
  56. return str.charAt(0).toUpperCase() + str.slice(1);
  57. });
  58. const toHandlerKey = cacheStringFunction(
  59. (str) => {
  60. const s = str ? `on${capitalize(str)}` : ``;
  61. return s;
  62. }
  63. );
  64. const identRE = /^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/;
  65. function genPropsAccessExp(name) {
  66. return identRE.test(name) ? `__props.${name}` : `__props[${JSON.stringify(name)}]`;
  67. }
  68. function genCacheKey(source, options) {
  69. return source + JSON.stringify(
  70. options,
  71. (_, val) => typeof val === "function" ? val.toString() : val
  72. );
  73. }
  74. const PatchFlagNames = {
  75. [1]: `TEXT`,
  76. [2]: `CLASS`,
  77. [4]: `STYLE`,
  78. [8]: `PROPS`,
  79. [16]: `FULL_PROPS`,
  80. [32]: `NEED_HYDRATION`,
  81. [64]: `STABLE_FRAGMENT`,
  82. [128]: `KEYED_FRAGMENT`,
  83. [256]: `UNKEYED_FRAGMENT`,
  84. [512]: `NEED_PATCH`,
  85. [1024]: `DYNAMIC_SLOTS`,
  86. [2048]: `DEV_ROOT_FRAGMENT`,
  87. [-1]: `CACHED`,
  88. [-2]: `BAIL`
  89. };
  90. const slotFlagsText = {
  91. [1]: "STABLE",
  92. [2]: "DYNAMIC",
  93. [3]: "FORWARDED"
  94. };
  95. const GLOBALS_ALLOWED = "Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error,Symbol";
  96. const isGloballyAllowed = /* @__PURE__ */ makeMap(GLOBALS_ALLOWED);
  97. const range = 2;
  98. function generateCodeFrame(source, start = 0, end = source.length) {
  99. start = Math.max(0, Math.min(start, source.length));
  100. end = Math.max(0, Math.min(end, source.length));
  101. if (start > end) return "";
  102. let lines = source.split(/(\r?\n)/);
  103. const newlineSequences = lines.filter((_, idx) => idx % 2 === 1);
  104. lines = lines.filter((_, idx) => idx % 2 === 0);
  105. let count = 0;
  106. const res = [];
  107. for (let i = 0; i < lines.length; i++) {
  108. count += lines[i].length + (newlineSequences[i] && newlineSequences[i].length || 0);
  109. if (count >= start) {
  110. for (let j = i - range; j <= i + range || end > count; j++) {
  111. if (j < 0 || j >= lines.length) continue;
  112. const line = j + 1;
  113. res.push(
  114. `${line}${" ".repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`
  115. );
  116. const lineLength = lines[j].length;
  117. const newLineSeqLength = newlineSequences[j] && newlineSequences[j].length || 0;
  118. if (j === i) {
  119. const pad = start - (count - (lineLength + newLineSeqLength));
  120. const length = Math.max(
  121. 1,
  122. end > count ? lineLength - pad : end - start
  123. );
  124. res.push(` | ` + " ".repeat(pad) + "^".repeat(length));
  125. } else if (j > i) {
  126. if (end > count) {
  127. const length = Math.max(Math.min(end - count, lineLength), 1);
  128. res.push(` | ` + "^".repeat(length));
  129. }
  130. count += lineLength + newLineSeqLength;
  131. }
  132. }
  133. break;
  134. }
  135. }
  136. return res.join("\n");
  137. }
  138. function normalizeStyle(value) {
  139. if (isArray$3(value)) {
  140. const res = {};
  141. for (let i = 0; i < value.length; i++) {
  142. const item = value[i];
  143. const normalized = isString$1(item) ? parseStringStyle(item) : normalizeStyle(item);
  144. if (normalized) {
  145. for (const key in normalized) {
  146. res[key] = normalized[key];
  147. }
  148. }
  149. }
  150. return res;
  151. } else if (isString$1(value) || isObject$2(value)) {
  152. return value;
  153. }
  154. }
  155. const listDelimiterRE = /;(?![^(]*\))/g;
  156. const propertyDelimiterRE = /:([^]+)/;
  157. const styleCommentRE = /\/\*[^]*?\*\//g;
  158. function parseStringStyle(cssText) {
  159. const ret = {};
  160. cssText.replace(styleCommentRE, "").split(listDelimiterRE).forEach((item) => {
  161. if (item) {
  162. const tmp = item.split(propertyDelimiterRE);
  163. tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
  164. }
  165. });
  166. return ret;
  167. }
  168. function stringifyStyle(styles) {
  169. if (!styles) return "";
  170. if (isString$1(styles)) return styles;
  171. let ret = "";
  172. for (const key in styles) {
  173. const value = styles[key];
  174. if (isString$1(value) || typeof value === "number") {
  175. const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key);
  176. ret += `${normalizedKey}:${value};`;
  177. }
  178. }
  179. return ret;
  180. }
  181. function normalizeClass(value) {
  182. let res = "";
  183. if (isString$1(value)) {
  184. res = value;
  185. } else if (isArray$3(value)) {
  186. for (let i = 0; i < value.length; i++) {
  187. const normalized = normalizeClass(value[i]);
  188. if (normalized) {
  189. res += normalized + " ";
  190. }
  191. }
  192. } else if (isObject$2(value)) {
  193. for (const name in value) {
  194. if (value[name]) {
  195. res += name + " ";
  196. }
  197. }
  198. }
  199. return res.trim();
  200. }
  201. const HTML_TAGS = "html,body,base,head,link,meta,style,title,address,article,aside,footer,header,hgroup,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,summary,template,blockquote,iframe,tfoot";
  202. const SVG_TAGS = "svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,feDistantLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,text,textPath,title,tspan,unknown,use,view";
  203. const MATH_TAGS = "annotation,annotation-xml,maction,maligngroup,malignmark,math,menclose,merror,mfenced,mfrac,mfraction,mglyph,mi,mlabeledtr,mlongdiv,mmultiscripts,mn,mo,mover,mpadded,mphantom,mprescripts,mroot,mrow,ms,mscarries,mscarry,msgroup,msline,mspace,msqrt,msrow,mstack,mstyle,msub,msubsup,msup,mtable,mtd,mtext,mtr,munder,munderover,none,semantics";
  204. const VOID_TAGS = "area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr";
  205. const isHTMLTag = /* @__PURE__ */ makeMap(HTML_TAGS);
  206. const isSVGTag = /* @__PURE__ */ makeMap(SVG_TAGS);
  207. const isMathMLTag = /* @__PURE__ */ makeMap(MATH_TAGS);
  208. const isVoidTag = /* @__PURE__ */ makeMap(VOID_TAGS);
  209. const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
  210. const isBooleanAttr = /* @__PURE__ */ makeMap(
  211. specialBooleanAttrs + `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,inert,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected`
  212. );
  213. const unsafeAttrCharRE = /[>/="'\u0009\u000a\u000c\u0020]/;
  214. const attrValidationCache = {};
  215. function isSSRSafeAttrName(name) {
  216. if (attrValidationCache.hasOwnProperty(name)) {
  217. return attrValidationCache[name];
  218. }
  219. const isUnsafe = unsafeAttrCharRE.test(name);
  220. if (isUnsafe) {
  221. console.error(`unsafe attribute name: ${name}`);
  222. }
  223. return attrValidationCache[name] = !isUnsafe;
  224. }
  225. const propsToAttrMap = {
  226. acceptCharset: "accept-charset",
  227. className: "class",
  228. htmlFor: "for",
  229. httpEquiv: "http-equiv"
  230. };
  231. const isKnownHtmlAttr = /* @__PURE__ */ makeMap(
  232. `accept,accept-charset,accesskey,action,align,allow,alt,async,autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,border,buffered,capture,challenge,charset,checked,cite,class,code,codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,formaction,formenctype,formmethod,formnovalidate,formtarget,headers,height,hidden,high,href,hreflang,http-equiv,icon,id,importance,inert,integrity,ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,target,title,translate,type,usemap,value,width,wrap`
  233. );
  234. const isKnownSvgAttr = /* @__PURE__ */ makeMap(
  235. `xmlns,accent-height,accumulate,additive,alignment-baseline,alphabetic,amplitude,arabic-form,ascent,attributeName,attributeType,azimuth,baseFrequency,baseline-shift,baseProfile,bbox,begin,bias,by,calcMode,cap-height,class,clip,clipPathUnits,clip-path,clip-rule,color,color-interpolation,color-interpolation-filters,color-profile,color-rendering,contentScriptType,contentStyleType,crossorigin,cursor,cx,cy,d,decelerate,descent,diffuseConstant,direction,display,divisor,dominant-baseline,dur,dx,dy,edgeMode,elevation,enable-background,end,exponent,fill,fill-opacity,fill-rule,filter,filterRes,filterUnits,flood-color,flood-opacity,font-family,font-size,font-size-adjust,font-stretch,font-style,font-variant,font-weight,format,from,fr,fx,fy,g1,g2,glyph-name,glyph-orientation-horizontal,glyph-orientation-vertical,glyphRef,gradientTransform,gradientUnits,hanging,height,href,hreflang,horiz-adv-x,horiz-origin-x,id,ideographic,image-rendering,in,in2,intercept,k,k1,k2,k3,k4,kernelMatrix,kernelUnitLength,kerning,keyPoints,keySplines,keyTimes,lang,lengthAdjust,letter-spacing,lighting-color,limitingConeAngle,local,marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mask,maskContentUnits,maskUnits,mathematical,max,media,method,min,mode,name,numOctaves,offset,opacity,operator,order,orient,orientation,origin,overflow,overline-position,overline-thickness,panose-1,paint-order,path,pathLength,patternContentUnits,patternTransform,patternUnits,ping,pointer-events,points,pointsAtX,pointsAtY,pointsAtZ,preserveAlpha,preserveAspectRatio,primitiveUnits,r,radius,referrerPolicy,refX,refY,rel,rendering-intent,repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,result,rotate,rx,ry,scale,seed,shape-rendering,slope,spacing,specularConstant,specularExponent,speed,spreadMethod,startOffset,stdDeviation,stemh,stemv,stitchTiles,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,string,stroke,stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,stroke-width,style,surfaceScale,systemLanguage,tabindex,tableValues,target,targetX,targetY,text-anchor,text-decoration,text-rendering,textLength,to,transform,transform-origin,type,u1,u2,underline-position,underline-thickness,unicode,unicode-bidi,unicode-range,units-per-em,v-alphabetic,v-hanging,v-ideographic,v-mathematical,values,vector-effect,version,vert-adv-y,vert-origin-x,vert-origin-y,viewBox,viewTarget,visibility,width,widths,word-spacing,writing-mode,x,x-height,x1,x2,xChannelSelector,xlink:actuate,xlink:arcrole,xlink:href,xlink:role,xlink:show,xlink:title,xlink:type,xmlns:xlink,xml:base,xml:lang,xml:space,y,y1,y2,yChannelSelector,z,zoomAndPan`
  236. );
  237. const isKnownMathMLAttr = /* @__PURE__ */ makeMap(
  238. `accent,accentunder,actiontype,align,alignmentscope,altimg,altimg-height,altimg-valign,altimg-width,alttext,bevelled,close,columnsalign,columnlines,columnspan,denomalign,depth,dir,display,displaystyle,encoding,equalcolumns,equalrows,fence,fontstyle,fontweight,form,frame,framespacing,groupalign,height,href,id,indentalign,indentalignfirst,indentalignlast,indentshift,indentshiftfirst,indentshiftlast,indextype,justify,largetop,largeop,lquote,lspace,mathbackground,mathcolor,mathsize,mathvariant,maxsize,minlabelspacing,mode,other,overflow,position,rowalign,rowlines,rowspan,rquote,rspace,scriptlevel,scriptminsize,scriptsizemultiplier,selection,separator,separators,shift,side,src,stackalign,stretchy,subscriptshift,superscriptshift,symmetric,voffset,width,widths,xlink:href,xlink:show,xlink:type,xmlns`
  239. );
  240. const escapeRE = /["'&<>]/;
  241. function escapeHtml(string) {
  242. const str = "" + string;
  243. const match = escapeRE.exec(str);
  244. if (!match) {
  245. return str;
  246. }
  247. let html = "";
  248. let escaped;
  249. let index;
  250. let lastIndex = 0;
  251. for (index = match.index; index < str.length; index++) {
  252. switch (str.charCodeAt(index)) {
  253. case 34:
  254. escaped = "&quot;";
  255. break;
  256. case 38:
  257. escaped = "&amp;";
  258. break;
  259. case 39:
  260. escaped = "&#39;";
  261. break;
  262. case 60:
  263. escaped = "&lt;";
  264. break;
  265. case 62:
  266. escaped = "&gt;";
  267. break;
  268. default:
  269. continue;
  270. }
  271. if (lastIndex !== index) {
  272. html += str.slice(lastIndex, index);
  273. }
  274. lastIndex = index + 1;
  275. html += escaped;
  276. }
  277. return lastIndex !== index ? html + str.slice(lastIndex, index) : html;
  278. }
  279. const cssVarNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/g;
  280. function getEscapedCssVarName(key, doubleEscape) {
  281. return key.replace(
  282. cssVarNameEscapeSymbolsRE,
  283. (s) => doubleEscape ? s === '"' ? '\\\\\\"' : `\\\\${s}` : `\\${s}`
  284. );
  285. }
  286. const isRef = (val) => {
  287. return !!(val && val["__v_isRef"] === true);
  288. };
  289. const toDisplayString = (val) => {
  290. return isString$1(val) ? val : val == null ? "" : isArray$3(val) || isObject$2(val) && (val.toString === objectToString$1 || !isFunction$1(val.toString)) ? isRef(val) ? toDisplayString(val.value) : JSON.stringify(val, replacer, 2) : String(val);
  291. };
  292. const replacer = (_key, val) => {
  293. if (isRef(val)) {
  294. return replacer(_key, val.value);
  295. } else if (isMap(val)) {
  296. return {
  297. [`Map(${val.size})`]: [...val.entries()].reduce(
  298. (entries, [key, val2], i) => {
  299. entries[stringifySymbol(key, i) + " =>"] = val2;
  300. return entries;
  301. },
  302. {}
  303. )
  304. };
  305. } else if (isSet(val)) {
  306. return {
  307. [`Set(${val.size})`]: [...val.values()].map((v) => stringifySymbol(v))
  308. };
  309. } else if (isSymbol$1(val)) {
  310. return stringifySymbol(val);
  311. } else if (isObject$2(val) && !isArray$3(val) && !isPlainObject(val)) {
  312. return String(val);
  313. }
  314. return val;
  315. };
  316. const stringifySymbol = (v, i = "") => {
  317. var _a;
  318. return (
  319. // Symbol.description in es2019+ so we need to cast here to pass
  320. // the lib: es2016 check
  321. isSymbol$1(v) ? `Symbol(${(_a = v.description) != null ? _a : i})` : v
  322. );
  323. };
  324. const FRAGMENT = /* @__PURE__ */ Symbol(`Fragment` );
  325. const TELEPORT = /* @__PURE__ */ Symbol(`Teleport` );
  326. const SUSPENSE = /* @__PURE__ */ Symbol(`Suspense` );
  327. const KEEP_ALIVE = /* @__PURE__ */ Symbol(`KeepAlive` );
  328. const BASE_TRANSITION = /* @__PURE__ */ Symbol(
  329. `BaseTransition`
  330. );
  331. const OPEN_BLOCK = /* @__PURE__ */ Symbol(`openBlock` );
  332. const CREATE_BLOCK = /* @__PURE__ */ Symbol(`createBlock` );
  333. const CREATE_ELEMENT_BLOCK = /* @__PURE__ */ Symbol(
  334. `createElementBlock`
  335. );
  336. const CREATE_VNODE = /* @__PURE__ */ Symbol(`createVNode` );
  337. const CREATE_ELEMENT_VNODE = /* @__PURE__ */ Symbol(
  338. `createElementVNode`
  339. );
  340. const CREATE_COMMENT = /* @__PURE__ */ Symbol(
  341. `createCommentVNode`
  342. );
  343. const CREATE_TEXT = /* @__PURE__ */ Symbol(
  344. `createTextVNode`
  345. );
  346. const CREATE_STATIC = /* @__PURE__ */ Symbol(
  347. `createStaticVNode`
  348. );
  349. const RESOLVE_COMPONENT = /* @__PURE__ */ Symbol(
  350. `resolveComponent`
  351. );
  352. const RESOLVE_DYNAMIC_COMPONENT = /* @__PURE__ */ Symbol(
  353. `resolveDynamicComponent`
  354. );
  355. const RESOLVE_DIRECTIVE = /* @__PURE__ */ Symbol(
  356. `resolveDirective`
  357. );
  358. const RESOLVE_FILTER = /* @__PURE__ */ Symbol(
  359. `resolveFilter`
  360. );
  361. const WITH_DIRECTIVES = /* @__PURE__ */ Symbol(
  362. `withDirectives`
  363. );
  364. const RENDER_LIST = /* @__PURE__ */ Symbol(`renderList` );
  365. const RENDER_SLOT = /* @__PURE__ */ Symbol(`renderSlot` );
  366. const CREATE_SLOTS = /* @__PURE__ */ Symbol(`createSlots` );
  367. const TO_DISPLAY_STRING = /* @__PURE__ */ Symbol(
  368. `toDisplayString`
  369. );
  370. const MERGE_PROPS = /* @__PURE__ */ Symbol(`mergeProps` );
  371. const NORMALIZE_CLASS = /* @__PURE__ */ Symbol(
  372. `normalizeClass`
  373. );
  374. const NORMALIZE_STYLE = /* @__PURE__ */ Symbol(
  375. `normalizeStyle`
  376. );
  377. const NORMALIZE_PROPS = /* @__PURE__ */ Symbol(
  378. `normalizeProps`
  379. );
  380. const GUARD_REACTIVE_PROPS = /* @__PURE__ */ Symbol(
  381. `guardReactiveProps`
  382. );
  383. const TO_HANDLERS = /* @__PURE__ */ Symbol(`toHandlers` );
  384. const CAMELIZE = /* @__PURE__ */ Symbol(`camelize` );
  385. const CAPITALIZE = /* @__PURE__ */ Symbol(`capitalize` );
  386. const TO_HANDLER_KEY = /* @__PURE__ */ Symbol(
  387. `toHandlerKey`
  388. );
  389. const SET_BLOCK_TRACKING = /* @__PURE__ */ Symbol(
  390. `setBlockTracking`
  391. );
  392. const PUSH_SCOPE_ID = /* @__PURE__ */ Symbol(`pushScopeId` );
  393. const POP_SCOPE_ID = /* @__PURE__ */ Symbol(`popScopeId` );
  394. const WITH_CTX = /* @__PURE__ */ Symbol(`withCtx` );
  395. const UNREF = /* @__PURE__ */ Symbol(`unref` );
  396. const IS_REF = /* @__PURE__ */ Symbol(`isRef` );
  397. const WITH_MEMO = /* @__PURE__ */ Symbol(`withMemo` );
  398. const IS_MEMO_SAME = /* @__PURE__ */ Symbol(`isMemoSame` );
  399. const helperNameMap = {
  400. [FRAGMENT]: `Fragment`,
  401. [TELEPORT]: `Teleport`,
  402. [SUSPENSE]: `Suspense`,
  403. [KEEP_ALIVE]: `KeepAlive`,
  404. [BASE_TRANSITION]: `BaseTransition`,
  405. [OPEN_BLOCK]: `openBlock`,
  406. [CREATE_BLOCK]: `createBlock`,
  407. [CREATE_ELEMENT_BLOCK]: `createElementBlock`,
  408. [CREATE_VNODE]: `createVNode`,
  409. [CREATE_ELEMENT_VNODE]: `createElementVNode`,
  410. [CREATE_COMMENT]: `createCommentVNode`,
  411. [CREATE_TEXT]: `createTextVNode`,
  412. [CREATE_STATIC]: `createStaticVNode`,
  413. [RESOLVE_COMPONENT]: `resolveComponent`,
  414. [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
  415. [RESOLVE_DIRECTIVE]: `resolveDirective`,
  416. [RESOLVE_FILTER]: `resolveFilter`,
  417. [WITH_DIRECTIVES]: `withDirectives`,
  418. [RENDER_LIST]: `renderList`,
  419. [RENDER_SLOT]: `renderSlot`,
  420. [CREATE_SLOTS]: `createSlots`,
  421. [TO_DISPLAY_STRING]: `toDisplayString`,
  422. [MERGE_PROPS]: `mergeProps`,
  423. [NORMALIZE_CLASS]: `normalizeClass`,
  424. [NORMALIZE_STYLE]: `normalizeStyle`,
  425. [NORMALIZE_PROPS]: `normalizeProps`,
  426. [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
  427. [TO_HANDLERS]: `toHandlers`,
  428. [CAMELIZE]: `camelize`,
  429. [CAPITALIZE]: `capitalize`,
  430. [TO_HANDLER_KEY]: `toHandlerKey`,
  431. [SET_BLOCK_TRACKING]: `setBlockTracking`,
  432. [PUSH_SCOPE_ID]: `pushScopeId`,
  433. [POP_SCOPE_ID]: `popScopeId`,
  434. [WITH_CTX]: `withCtx`,
  435. [UNREF]: `unref`,
  436. [IS_REF]: `isRef`,
  437. [WITH_MEMO]: `withMemo`,
  438. [IS_MEMO_SAME]: `isMemoSame`
  439. };
  440. function registerRuntimeHelpers(helpers) {
  441. Object.getOwnPropertySymbols(helpers).forEach((s) => {
  442. helperNameMap[s] = helpers[s];
  443. });
  444. }
  445. const Namespaces = {
  446. "HTML": 0,
  447. "0": "HTML",
  448. "SVG": 1,
  449. "1": "SVG",
  450. "MATH_ML": 2,
  451. "2": "MATH_ML"
  452. };
  453. const NodeTypes = {
  454. "ROOT": 0,
  455. "0": "ROOT",
  456. "ELEMENT": 1,
  457. "1": "ELEMENT",
  458. "TEXT": 2,
  459. "2": "TEXT",
  460. "COMMENT": 3,
  461. "3": "COMMENT",
  462. "SIMPLE_EXPRESSION": 4,
  463. "4": "SIMPLE_EXPRESSION",
  464. "INTERPOLATION": 5,
  465. "5": "INTERPOLATION",
  466. "ATTRIBUTE": 6,
  467. "6": "ATTRIBUTE",
  468. "DIRECTIVE": 7,
  469. "7": "DIRECTIVE",
  470. "COMPOUND_EXPRESSION": 8,
  471. "8": "COMPOUND_EXPRESSION",
  472. "IF": 9,
  473. "9": "IF",
  474. "IF_BRANCH": 10,
  475. "10": "IF_BRANCH",
  476. "FOR": 11,
  477. "11": "FOR",
  478. "TEXT_CALL": 12,
  479. "12": "TEXT_CALL",
  480. "VNODE_CALL": 13,
  481. "13": "VNODE_CALL",
  482. "JS_CALL_EXPRESSION": 14,
  483. "14": "JS_CALL_EXPRESSION",
  484. "JS_OBJECT_EXPRESSION": 15,
  485. "15": "JS_OBJECT_EXPRESSION",
  486. "JS_PROPERTY": 16,
  487. "16": "JS_PROPERTY",
  488. "JS_ARRAY_EXPRESSION": 17,
  489. "17": "JS_ARRAY_EXPRESSION",
  490. "JS_FUNCTION_EXPRESSION": 18,
  491. "18": "JS_FUNCTION_EXPRESSION",
  492. "JS_CONDITIONAL_EXPRESSION": 19,
  493. "19": "JS_CONDITIONAL_EXPRESSION",
  494. "JS_CACHE_EXPRESSION": 20,
  495. "20": "JS_CACHE_EXPRESSION",
  496. "JS_BLOCK_STATEMENT": 21,
  497. "21": "JS_BLOCK_STATEMENT",
  498. "JS_TEMPLATE_LITERAL": 22,
  499. "22": "JS_TEMPLATE_LITERAL",
  500. "JS_IF_STATEMENT": 23,
  501. "23": "JS_IF_STATEMENT",
  502. "JS_ASSIGNMENT_EXPRESSION": 24,
  503. "24": "JS_ASSIGNMENT_EXPRESSION",
  504. "JS_SEQUENCE_EXPRESSION": 25,
  505. "25": "JS_SEQUENCE_EXPRESSION",
  506. "JS_RETURN_STATEMENT": 26,
  507. "26": "JS_RETURN_STATEMENT"
  508. };
  509. const ElementTypes = {
  510. "ELEMENT": 0,
  511. "0": "ELEMENT",
  512. "COMPONENT": 1,
  513. "1": "COMPONENT",
  514. "SLOT": 2,
  515. "2": "SLOT",
  516. "TEMPLATE": 3,
  517. "3": "TEMPLATE"
  518. };
  519. const ConstantTypes = {
  520. "NOT_CONSTANT": 0,
  521. "0": "NOT_CONSTANT",
  522. "CAN_SKIP_PATCH": 1,
  523. "1": "CAN_SKIP_PATCH",
  524. "CAN_CACHE": 2,
  525. "2": "CAN_CACHE",
  526. "CAN_STRINGIFY": 3,
  527. "3": "CAN_STRINGIFY"
  528. };
  529. const locStub = {
  530. start: { line: 1, column: 1, offset: 0 },
  531. end: { line: 1, column: 1, offset: 0 },
  532. source: ""
  533. };
  534. function createRoot(children, source = "") {
  535. return {
  536. type: 0,
  537. source,
  538. children,
  539. helpers: /* @__PURE__ */ new Set(),
  540. components: [],
  541. directives: [],
  542. hoists: [],
  543. imports: [],
  544. cached: [],
  545. temps: 0,
  546. codegenNode: void 0,
  547. loc: locStub
  548. };
  549. }
  550. function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) {
  551. if (context) {
  552. if (isBlock) {
  553. context.helper(OPEN_BLOCK);
  554. context.helper(getVNodeBlockHelper(context.inSSR, isComponent));
  555. } else {
  556. context.helper(getVNodeHelper(context.inSSR, isComponent));
  557. }
  558. if (directives) {
  559. context.helper(WITH_DIRECTIVES);
  560. }
  561. }
  562. return {
  563. type: 13,
  564. tag,
  565. props,
  566. children,
  567. patchFlag,
  568. dynamicProps,
  569. directives,
  570. isBlock,
  571. disableTracking,
  572. isComponent,
  573. loc
  574. };
  575. }
  576. function createArrayExpression(elements, loc = locStub) {
  577. return {
  578. type: 17,
  579. loc,
  580. elements
  581. };
  582. }
  583. function createObjectExpression(properties, loc = locStub) {
  584. return {
  585. type: 15,
  586. loc,
  587. properties
  588. };
  589. }
  590. function createObjectProperty(key, value) {
  591. return {
  592. type: 16,
  593. loc: locStub,
  594. key: isString$1(key) ? createSimpleExpression(key, true) : key,
  595. value
  596. };
  597. }
  598. function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0) {
  599. return {
  600. type: 4,
  601. loc,
  602. content,
  603. isStatic,
  604. constType: isStatic ? 3 : constType
  605. };
  606. }
  607. function createInterpolation(content, loc) {
  608. return {
  609. type: 5,
  610. loc,
  611. content: isString$1(content) ? createSimpleExpression(content, false, loc) : content
  612. };
  613. }
  614. function createCompoundExpression(children, loc = locStub) {
  615. return {
  616. type: 8,
  617. loc,
  618. children
  619. };
  620. }
  621. function createCallExpression(callee, args = [], loc = locStub) {
  622. return {
  623. type: 14,
  624. loc,
  625. callee,
  626. arguments: args
  627. };
  628. }
  629. function createFunctionExpression(params, returns = void 0, newline = false, isSlot = false, loc = locStub) {
  630. return {
  631. type: 18,
  632. params,
  633. returns,
  634. newline,
  635. isSlot,
  636. loc
  637. };
  638. }
  639. function createConditionalExpression(test, consequent, alternate, newline = true) {
  640. return {
  641. type: 19,
  642. test,
  643. consequent,
  644. alternate,
  645. newline,
  646. loc: locStub
  647. };
  648. }
  649. function createCacheExpression(index, value, needPauseTracking = false, inVOnce = false) {
  650. return {
  651. type: 20,
  652. index,
  653. value,
  654. needPauseTracking,
  655. inVOnce,
  656. needArraySpread: false,
  657. loc: locStub
  658. };
  659. }
  660. function createBlockStatement(body) {
  661. return {
  662. type: 21,
  663. body,
  664. loc: locStub
  665. };
  666. }
  667. function createTemplateLiteral(elements) {
  668. return {
  669. type: 22,
  670. elements,
  671. loc: locStub
  672. };
  673. }
  674. function createIfStatement(test, consequent, alternate) {
  675. return {
  676. type: 23,
  677. test,
  678. consequent,
  679. alternate,
  680. loc: locStub
  681. };
  682. }
  683. function createAssignmentExpression(left, right) {
  684. return {
  685. type: 24,
  686. left,
  687. right,
  688. loc: locStub
  689. };
  690. }
  691. function createSequenceExpression(expressions) {
  692. return {
  693. type: 25,
  694. expressions,
  695. loc: locStub
  696. };
  697. }
  698. function createReturnStatement(returns) {
  699. return {
  700. type: 26,
  701. returns,
  702. loc: locStub
  703. };
  704. }
  705. function getVNodeHelper(ssr, isComponent) {
  706. return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
  707. }
  708. function getVNodeBlockHelper(ssr, isComponent) {
  709. return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
  710. }
  711. function convertToBlock(node, { helper, removeHelper, inSSR }) {
  712. if (!node.isBlock) {
  713. node.isBlock = true;
  714. removeHelper(getVNodeHelper(inSSR, node.isComponent));
  715. helper(OPEN_BLOCK);
  716. helper(getVNodeBlockHelper(inSSR, node.isComponent));
  717. }
  718. }
  719. // Adapted from https://github.com/mathiasbynens/he/blob/36afe179392226cf1b6ccdb16ebbb7a5a844d93a/src/he.js#L106-L134
  720. var _a$1;
  721. const decodeMap = new Map([
  722. [0, 65533],
  723. // C1 Unicode control character reference replacements
  724. [128, 8364],
  725. [130, 8218],
  726. [131, 402],
  727. [132, 8222],
  728. [133, 8230],
  729. [134, 8224],
  730. [135, 8225],
  731. [136, 710],
  732. [137, 8240],
  733. [138, 352],
  734. [139, 8249],
  735. [140, 338],
  736. [142, 381],
  737. [145, 8216],
  738. [146, 8217],
  739. [147, 8220],
  740. [148, 8221],
  741. [149, 8226],
  742. [150, 8211],
  743. [151, 8212],
  744. [152, 732],
  745. [153, 8482],
  746. [154, 353],
  747. [155, 8250],
  748. [156, 339],
  749. [158, 382],
  750. [159, 376],
  751. ]);
  752. /**
  753. * Polyfill for `String.fromCodePoint`. It is used to create a string from a Unicode code point.
  754. */
  755. const fromCodePoint =
  756. // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, n/no-unsupported-features/es-builtins
  757. (_a$1 = String.fromCodePoint) !== null && _a$1 !== void 0 ? _a$1 : ((codePoint) => {
  758. let output = "";
  759. if (codePoint > 65535) {
  760. codePoint -= 65536;
  761. output += String.fromCharCode(((codePoint >>> 10) & 1023) | 55296);
  762. codePoint = 56320 | (codePoint & 1023);
  763. }
  764. output += String.fromCharCode(codePoint);
  765. return output;
  766. });
  767. /**
  768. * Replace the given code point with a replacement character if it is a
  769. * surrogate or is outside the valid range. Otherwise return the code
  770. * point unchanged.
  771. */
  772. function replaceCodePoint(codePoint) {
  773. var _a;
  774. if ((codePoint >= 55296 && codePoint <= 57343) ||
  775. codePoint > 1114111) {
  776. return 65533;
  777. }
  778. return (_a = decodeMap.get(codePoint)) !== null && _a !== void 0 ? _a : codePoint;
  779. }
  780. var global$1 = (typeof global !== "undefined" ? global :
  781. typeof self !== "undefined" ? self :
  782. typeof window !== "undefined" ? window : {});
  783. var lookup = [];
  784. var revLookup = [];
  785. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
  786. var inited = false;
  787. function init () {
  788. inited = true;
  789. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  790. for (var i = 0, len = code.length; i < len; ++i) {
  791. lookup[i] = code[i];
  792. revLookup[code.charCodeAt(i)] = i;
  793. }
  794. revLookup['-'.charCodeAt(0)] = 62;
  795. revLookup['_'.charCodeAt(0)] = 63;
  796. }
  797. function toByteArray (b64) {
  798. if (!inited) {
  799. init();
  800. }
  801. var i, j, l, tmp, placeHolders, arr;
  802. var len = b64.length;
  803. if (len % 4 > 0) {
  804. throw new Error('Invalid string. Length must be a multiple of 4')
  805. }
  806. // the number of equal signs (place holders)
  807. // if there are two placeholders, than the two characters before it
  808. // represent one byte
  809. // if there is only one, then the three characters before it represent 2 bytes
  810. // this is just a cheap hack to not do indexOf twice
  811. placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
  812. // base64 is 4/3 + up to two characters of the original data
  813. arr = new Arr(len * 3 / 4 - placeHolders);
  814. // if there are placeholders, only get up to the last complete 4 chars
  815. l = placeHolders > 0 ? len - 4 : len;
  816. var L = 0;
  817. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  818. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];
  819. arr[L++] = (tmp >> 16) & 0xFF;
  820. arr[L++] = (tmp >> 8) & 0xFF;
  821. arr[L++] = tmp & 0xFF;
  822. }
  823. if (placeHolders === 2) {
  824. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
  825. arr[L++] = tmp & 0xFF;
  826. } else if (placeHolders === 1) {
  827. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);
  828. arr[L++] = (tmp >> 8) & 0xFF;
  829. arr[L++] = tmp & 0xFF;
  830. }
  831. return arr
  832. }
  833. function tripletToBase64 (num) {
  834. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  835. }
  836. function encodeChunk (uint8, start, end) {
  837. var tmp;
  838. var output = [];
  839. for (var i = start; i < end; i += 3) {
  840. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
  841. output.push(tripletToBase64(tmp));
  842. }
  843. return output.join('')
  844. }
  845. function fromByteArray (uint8) {
  846. if (!inited) {
  847. init();
  848. }
  849. var tmp;
  850. var len = uint8.length;
  851. var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
  852. var output = '';
  853. var parts = [];
  854. var maxChunkLength = 16383; // must be multiple of 3
  855. // go through the array every three bytes, we'll deal with trailing stuff later
  856. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  857. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));
  858. }
  859. // pad the end with zeros, but make sure to not forget the extra bytes
  860. if (extraBytes === 1) {
  861. tmp = uint8[len - 1];
  862. output += lookup[tmp >> 2];
  863. output += lookup[(tmp << 4) & 0x3F];
  864. output += '==';
  865. } else if (extraBytes === 2) {
  866. tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);
  867. output += lookup[tmp >> 10];
  868. output += lookup[(tmp >> 4) & 0x3F];
  869. output += lookup[(tmp << 2) & 0x3F];
  870. output += '=';
  871. }
  872. parts.push(output);
  873. return parts.join('')
  874. }
  875. function read (buffer, offset, isLE, mLen, nBytes) {
  876. var e, m;
  877. var eLen = nBytes * 8 - mLen - 1;
  878. var eMax = (1 << eLen) - 1;
  879. var eBias = eMax >> 1;
  880. var nBits = -7;
  881. var i = isLE ? (nBytes - 1) : 0;
  882. var d = isLE ? -1 : 1;
  883. var s = buffer[offset + i];
  884. i += d;
  885. e = s & ((1 << (-nBits)) - 1);
  886. s >>= (-nBits);
  887. nBits += eLen;
  888. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  889. m = e & ((1 << (-nBits)) - 1);
  890. e >>= (-nBits);
  891. nBits += mLen;
  892. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  893. if (e === 0) {
  894. e = 1 - eBias;
  895. } else if (e === eMax) {
  896. return m ? NaN : ((s ? -1 : 1) * Infinity)
  897. } else {
  898. m = m + Math.pow(2, mLen);
  899. e = e - eBias;
  900. }
  901. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  902. }
  903. function write (buffer, value, offset, isLE, mLen, nBytes) {
  904. var e, m, c;
  905. var eLen = nBytes * 8 - mLen - 1;
  906. var eMax = (1 << eLen) - 1;
  907. var eBias = eMax >> 1;
  908. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
  909. var i = isLE ? 0 : (nBytes - 1);
  910. var d = isLE ? 1 : -1;
  911. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
  912. value = Math.abs(value);
  913. if (isNaN(value) || value === Infinity) {
  914. m = isNaN(value) ? 1 : 0;
  915. e = eMax;
  916. } else {
  917. e = Math.floor(Math.log(value) / Math.LN2);
  918. if (value * (c = Math.pow(2, -e)) < 1) {
  919. e--;
  920. c *= 2;
  921. }
  922. if (e + eBias >= 1) {
  923. value += rt / c;
  924. } else {
  925. value += rt * Math.pow(2, 1 - eBias);
  926. }
  927. if (value * c >= 2) {
  928. e++;
  929. c /= 2;
  930. }
  931. if (e + eBias >= eMax) {
  932. m = 0;
  933. e = eMax;
  934. } else if (e + eBias >= 1) {
  935. m = (value * c - 1) * Math.pow(2, mLen);
  936. e = e + eBias;
  937. } else {
  938. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  939. e = 0;
  940. }
  941. }
  942. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  943. e = (e << mLen) | m;
  944. eLen += mLen;
  945. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  946. buffer[offset + i - d] |= s * 128;
  947. }
  948. var toString$1 = {}.toString;
  949. var isArray$2 = Array.isArray || function (arr) {
  950. return toString$1.call(arr) == '[object Array]';
  951. };
  952. /*!
  953. * The buffer module from node.js, for the browser.
  954. *
  955. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  956. * @license MIT
  957. */
  958. /* eslint-disable no-proto */
  959. var INSPECT_MAX_BYTES = 50;
  960. /**
  961. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  962. * === true Use Uint8Array implementation (fastest)
  963. * === false Use Object implementation (most compatible, even IE6)
  964. *
  965. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  966. * Opera 11.6+, iOS 4.2+.
  967. *
  968. * Due to various browser bugs, sometimes the Object implementation will be used even
  969. * when the browser supports typed arrays.
  970. *
  971. * Note:
  972. *
  973. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  974. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  975. *
  976. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  977. *
  978. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  979. * incorrect length in some situations.
  980. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  981. * get the Object implementation, which is slower but behaves correctly.
  982. */
  983. Buffer$1.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined
  984. ? global$1.TYPED_ARRAY_SUPPORT
  985. : true;
  986. /*
  987. * Export kMaxLength after typed array support is determined.
  988. */
  989. kMaxLength();
  990. function kMaxLength () {
  991. return Buffer$1.TYPED_ARRAY_SUPPORT
  992. ? 0x7fffffff
  993. : 0x3fffffff
  994. }
  995. function createBuffer (that, length) {
  996. if (kMaxLength() < length) {
  997. throw new RangeError('Invalid typed array length')
  998. }
  999. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  1000. // Return an augmented `Uint8Array` instance, for best performance
  1001. that = new Uint8Array(length);
  1002. that.__proto__ = Buffer$1.prototype;
  1003. } else {
  1004. // Fallback: Return an object instance of the Buffer class
  1005. if (that === null) {
  1006. that = new Buffer$1(length);
  1007. }
  1008. that.length = length;
  1009. }
  1010. return that
  1011. }
  1012. /**
  1013. * The Buffer constructor returns instances of `Uint8Array` that have their
  1014. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  1015. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  1016. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  1017. * returns a single octet.
  1018. *
  1019. * The `Uint8Array` prototype remains unmodified.
  1020. */
  1021. function Buffer$1 (arg, encodingOrOffset, length) {
  1022. if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) {
  1023. return new Buffer$1(arg, encodingOrOffset, length)
  1024. }
  1025. // Common case.
  1026. if (typeof arg === 'number') {
  1027. if (typeof encodingOrOffset === 'string') {
  1028. throw new Error(
  1029. 'If encoding is specified then the first argument must be a string'
  1030. )
  1031. }
  1032. return allocUnsafe(this, arg)
  1033. }
  1034. return from(this, arg, encodingOrOffset, length)
  1035. }
  1036. Buffer$1.poolSize = 8192; // not used by this implementation
  1037. // TODO: Legacy, not needed anymore. Remove in next major version.
  1038. Buffer$1._augment = function (arr) {
  1039. arr.__proto__ = Buffer$1.prototype;
  1040. return arr
  1041. };
  1042. function from (that, value, encodingOrOffset, length) {
  1043. if (typeof value === 'number') {
  1044. throw new TypeError('"value" argument must not be a number')
  1045. }
  1046. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  1047. return fromArrayBuffer(that, value, encodingOrOffset, length)
  1048. }
  1049. if (typeof value === 'string') {
  1050. return fromString(that, value, encodingOrOffset)
  1051. }
  1052. return fromObject(that, value)
  1053. }
  1054. /**
  1055. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  1056. * if value is a number.
  1057. * Buffer.from(str[, encoding])
  1058. * Buffer.from(array)
  1059. * Buffer.from(buffer)
  1060. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  1061. **/
  1062. Buffer$1.from = function (value, encodingOrOffset, length) {
  1063. return from(null, value, encodingOrOffset, length)
  1064. };
  1065. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  1066. Buffer$1.prototype.__proto__ = Uint8Array.prototype;
  1067. Buffer$1.__proto__ = Uint8Array;
  1068. if (typeof Symbol !== 'undefined' && Symbol.species &&
  1069. Buffer$1[Symbol.species] === Buffer$1) ;
  1070. }
  1071. function assertSize (size) {
  1072. if (typeof size !== 'number') {
  1073. throw new TypeError('"size" argument must be a number')
  1074. } else if (size < 0) {
  1075. throw new RangeError('"size" argument must not be negative')
  1076. }
  1077. }
  1078. function alloc (that, size, fill, encoding) {
  1079. assertSize(size);
  1080. if (size <= 0) {
  1081. return createBuffer(that, size)
  1082. }
  1083. if (fill !== undefined) {
  1084. // Only pay attention to encoding if it's a string. This
  1085. // prevents accidentally sending in a number that would
  1086. // be interpretted as a start offset.
  1087. return typeof encoding === 'string'
  1088. ? createBuffer(that, size).fill(fill, encoding)
  1089. : createBuffer(that, size).fill(fill)
  1090. }
  1091. return createBuffer(that, size)
  1092. }
  1093. /**
  1094. * Creates a new filled Buffer instance.
  1095. * alloc(size[, fill[, encoding]])
  1096. **/
  1097. Buffer$1.alloc = function (size, fill, encoding) {
  1098. return alloc(null, size, fill, encoding)
  1099. };
  1100. function allocUnsafe (that, size) {
  1101. assertSize(size);
  1102. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
  1103. if (!Buffer$1.TYPED_ARRAY_SUPPORT) {
  1104. for (var i = 0; i < size; ++i) {
  1105. that[i] = 0;
  1106. }
  1107. }
  1108. return that
  1109. }
  1110. /**
  1111. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  1112. * */
  1113. Buffer$1.allocUnsafe = function (size) {
  1114. return allocUnsafe(null, size)
  1115. };
  1116. /**
  1117. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  1118. */
  1119. Buffer$1.allocUnsafeSlow = function (size) {
  1120. return allocUnsafe(null, size)
  1121. };
  1122. function fromString (that, string, encoding) {
  1123. if (typeof encoding !== 'string' || encoding === '') {
  1124. encoding = 'utf8';
  1125. }
  1126. if (!Buffer$1.isEncoding(encoding)) {
  1127. throw new TypeError('"encoding" must be a valid string encoding')
  1128. }
  1129. var length = byteLength(string, encoding) | 0;
  1130. that = createBuffer(that, length);
  1131. var actual = that.write(string, encoding);
  1132. if (actual !== length) {
  1133. // Writing a hex string, for example, that contains invalid characters will
  1134. // cause everything after the first invalid character to be ignored. (e.g.
  1135. // 'abxxcd' will be treated as 'ab')
  1136. that = that.slice(0, actual);
  1137. }
  1138. return that
  1139. }
  1140. function fromArrayLike (that, array) {
  1141. var length = array.length < 0 ? 0 : checked(array.length) | 0;
  1142. that = createBuffer(that, length);
  1143. for (var i = 0; i < length; i += 1) {
  1144. that[i] = array[i] & 255;
  1145. }
  1146. return that
  1147. }
  1148. function fromArrayBuffer (that, array, byteOffset, length) {
  1149. array.byteLength; // this throws if `array` is not a valid ArrayBuffer
  1150. if (byteOffset < 0 || array.byteLength < byteOffset) {
  1151. throw new RangeError('\'offset\' is out of bounds')
  1152. }
  1153. if (array.byteLength < byteOffset + (length || 0)) {
  1154. throw new RangeError('\'length\' is out of bounds')
  1155. }
  1156. if (byteOffset === undefined && length === undefined) {
  1157. array = new Uint8Array(array);
  1158. } else if (length === undefined) {
  1159. array = new Uint8Array(array, byteOffset);
  1160. } else {
  1161. array = new Uint8Array(array, byteOffset, length);
  1162. }
  1163. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  1164. // Return an augmented `Uint8Array` instance, for best performance
  1165. that = array;
  1166. that.__proto__ = Buffer$1.prototype;
  1167. } else {
  1168. // Fallback: Return an object instance of the Buffer class
  1169. that = fromArrayLike(that, array);
  1170. }
  1171. return that
  1172. }
  1173. function fromObject (that, obj) {
  1174. if (internalIsBuffer(obj)) {
  1175. var len = checked(obj.length) | 0;
  1176. that = createBuffer(that, len);
  1177. if (that.length === 0) {
  1178. return that
  1179. }
  1180. obj.copy(that, 0, 0, len);
  1181. return that
  1182. }
  1183. if (obj) {
  1184. if ((typeof ArrayBuffer !== 'undefined' &&
  1185. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  1186. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  1187. return createBuffer(that, 0)
  1188. }
  1189. return fromArrayLike(that, obj)
  1190. }
  1191. if (obj.type === 'Buffer' && isArray$2(obj.data)) {
  1192. return fromArrayLike(that, obj.data)
  1193. }
  1194. }
  1195. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  1196. }
  1197. function checked (length) {
  1198. // Note: cannot use `length < kMaxLength()` here because that fails when
  1199. // length is NaN (which is otherwise coerced to zero.)
  1200. if (length >= kMaxLength()) {
  1201. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  1202. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  1203. }
  1204. return length | 0
  1205. }
  1206. Buffer$1.isBuffer = isBuffer$1;
  1207. function internalIsBuffer (b) {
  1208. return !!(b != null && b._isBuffer)
  1209. }
  1210. Buffer$1.compare = function compare (a, b) {
  1211. if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
  1212. throw new TypeError('Arguments must be Buffers')
  1213. }
  1214. if (a === b) return 0
  1215. var x = a.length;
  1216. var y = b.length;
  1217. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  1218. if (a[i] !== b[i]) {
  1219. x = a[i];
  1220. y = b[i];
  1221. break
  1222. }
  1223. }
  1224. if (x < y) return -1
  1225. if (y < x) return 1
  1226. return 0
  1227. };
  1228. Buffer$1.isEncoding = function isEncoding (encoding) {
  1229. switch (String(encoding).toLowerCase()) {
  1230. case 'hex':
  1231. case 'utf8':
  1232. case 'utf-8':
  1233. case 'ascii':
  1234. case 'latin1':
  1235. case 'binary':
  1236. case 'base64':
  1237. case 'ucs2':
  1238. case 'ucs-2':
  1239. case 'utf16le':
  1240. case 'utf-16le':
  1241. return true
  1242. default:
  1243. return false
  1244. }
  1245. };
  1246. Buffer$1.concat = function concat (list, length) {
  1247. if (!isArray$2(list)) {
  1248. throw new TypeError('"list" argument must be an Array of Buffers')
  1249. }
  1250. if (list.length === 0) {
  1251. return Buffer$1.alloc(0)
  1252. }
  1253. var i;
  1254. if (length === undefined) {
  1255. length = 0;
  1256. for (i = 0; i < list.length; ++i) {
  1257. length += list[i].length;
  1258. }
  1259. }
  1260. var buffer = Buffer$1.allocUnsafe(length);
  1261. var pos = 0;
  1262. for (i = 0; i < list.length; ++i) {
  1263. var buf = list[i];
  1264. if (!internalIsBuffer(buf)) {
  1265. throw new TypeError('"list" argument must be an Array of Buffers')
  1266. }
  1267. buf.copy(buffer, pos);
  1268. pos += buf.length;
  1269. }
  1270. return buffer
  1271. };
  1272. function byteLength (string, encoding) {
  1273. if (internalIsBuffer(string)) {
  1274. return string.length
  1275. }
  1276. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  1277. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  1278. return string.byteLength
  1279. }
  1280. if (typeof string !== 'string') {
  1281. string = '' + string;
  1282. }
  1283. var len = string.length;
  1284. if (len === 0) return 0
  1285. // Use a for loop to avoid recursion
  1286. var loweredCase = false;
  1287. for (;;) {
  1288. switch (encoding) {
  1289. case 'ascii':
  1290. case 'latin1':
  1291. case 'binary':
  1292. return len
  1293. case 'utf8':
  1294. case 'utf-8':
  1295. case undefined:
  1296. return utf8ToBytes(string).length
  1297. case 'ucs2':
  1298. case 'ucs-2':
  1299. case 'utf16le':
  1300. case 'utf-16le':
  1301. return len * 2
  1302. case 'hex':
  1303. return len >>> 1
  1304. case 'base64':
  1305. return base64ToBytes(string).length
  1306. default:
  1307. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  1308. encoding = ('' + encoding).toLowerCase();
  1309. loweredCase = true;
  1310. }
  1311. }
  1312. }
  1313. Buffer$1.byteLength = byteLength;
  1314. function slowToString (encoding, start, end) {
  1315. var loweredCase = false;
  1316. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  1317. // property of a typed array.
  1318. // This behaves neither like String nor Uint8Array in that we set start/end
  1319. // to their upper/lower bounds if the value passed is out of range.
  1320. // undefined is handled specially as per ECMA-262 6th Edition,
  1321. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  1322. if (start === undefined || start < 0) {
  1323. start = 0;
  1324. }
  1325. // Return early if start > this.length. Done here to prevent potential uint32
  1326. // coercion fail below.
  1327. if (start > this.length) {
  1328. return ''
  1329. }
  1330. if (end === undefined || end > this.length) {
  1331. end = this.length;
  1332. }
  1333. if (end <= 0) {
  1334. return ''
  1335. }
  1336. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  1337. end >>>= 0;
  1338. start >>>= 0;
  1339. if (end <= start) {
  1340. return ''
  1341. }
  1342. if (!encoding) encoding = 'utf8';
  1343. while (true) {
  1344. switch (encoding) {
  1345. case 'hex':
  1346. return hexSlice(this, start, end)
  1347. case 'utf8':
  1348. case 'utf-8':
  1349. return utf8Slice(this, start, end)
  1350. case 'ascii':
  1351. return asciiSlice(this, start, end)
  1352. case 'latin1':
  1353. case 'binary':
  1354. return latin1Slice(this, start, end)
  1355. case 'base64':
  1356. return base64Slice(this, start, end)
  1357. case 'ucs2':
  1358. case 'ucs-2':
  1359. case 'utf16le':
  1360. case 'utf-16le':
  1361. return utf16leSlice(this, start, end)
  1362. default:
  1363. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  1364. encoding = (encoding + '').toLowerCase();
  1365. loweredCase = true;
  1366. }
  1367. }
  1368. }
  1369. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  1370. // Buffer instances.
  1371. Buffer$1.prototype._isBuffer = true;
  1372. function swap (b, n, m) {
  1373. var i = b[n];
  1374. b[n] = b[m];
  1375. b[m] = i;
  1376. }
  1377. Buffer$1.prototype.swap16 = function swap16 () {
  1378. var len = this.length;
  1379. if (len % 2 !== 0) {
  1380. throw new RangeError('Buffer size must be a multiple of 16-bits')
  1381. }
  1382. for (var i = 0; i < len; i += 2) {
  1383. swap(this, i, i + 1);
  1384. }
  1385. return this
  1386. };
  1387. Buffer$1.prototype.swap32 = function swap32 () {
  1388. var len = this.length;
  1389. if (len % 4 !== 0) {
  1390. throw new RangeError('Buffer size must be a multiple of 32-bits')
  1391. }
  1392. for (var i = 0; i < len; i += 4) {
  1393. swap(this, i, i + 3);
  1394. swap(this, i + 1, i + 2);
  1395. }
  1396. return this
  1397. };
  1398. Buffer$1.prototype.swap64 = function swap64 () {
  1399. var len = this.length;
  1400. if (len % 8 !== 0) {
  1401. throw new RangeError('Buffer size must be a multiple of 64-bits')
  1402. }
  1403. for (var i = 0; i < len; i += 8) {
  1404. swap(this, i, i + 7);
  1405. swap(this, i + 1, i + 6);
  1406. swap(this, i + 2, i + 5);
  1407. swap(this, i + 3, i + 4);
  1408. }
  1409. return this
  1410. };
  1411. Buffer$1.prototype.toString = function toString () {
  1412. var length = this.length | 0;
  1413. if (length === 0) return ''
  1414. if (arguments.length === 0) return utf8Slice(this, 0, length)
  1415. return slowToString.apply(this, arguments)
  1416. };
  1417. Buffer$1.prototype.equals = function equals (b) {
  1418. if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')
  1419. if (this === b) return true
  1420. return Buffer$1.compare(this, b) === 0
  1421. };
  1422. Buffer$1.prototype.inspect = function inspect () {
  1423. var str = '';
  1424. var max = INSPECT_MAX_BYTES;
  1425. if (this.length > 0) {
  1426. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
  1427. if (this.length > max) str += ' ... ';
  1428. }
  1429. return '<Buffer ' + str + '>'
  1430. };
  1431. Buffer$1.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  1432. if (!internalIsBuffer(target)) {
  1433. throw new TypeError('Argument must be a Buffer')
  1434. }
  1435. if (start === undefined) {
  1436. start = 0;
  1437. }
  1438. if (end === undefined) {
  1439. end = target ? target.length : 0;
  1440. }
  1441. if (thisStart === undefined) {
  1442. thisStart = 0;
  1443. }
  1444. if (thisEnd === undefined) {
  1445. thisEnd = this.length;
  1446. }
  1447. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  1448. throw new RangeError('out of range index')
  1449. }
  1450. if (thisStart >= thisEnd && start >= end) {
  1451. return 0
  1452. }
  1453. if (thisStart >= thisEnd) {
  1454. return -1
  1455. }
  1456. if (start >= end) {
  1457. return 1
  1458. }
  1459. start >>>= 0;
  1460. end >>>= 0;
  1461. thisStart >>>= 0;
  1462. thisEnd >>>= 0;
  1463. if (this === target) return 0
  1464. var x = thisEnd - thisStart;
  1465. var y = end - start;
  1466. var len = Math.min(x, y);
  1467. var thisCopy = this.slice(thisStart, thisEnd);
  1468. var targetCopy = target.slice(start, end);
  1469. for (var i = 0; i < len; ++i) {
  1470. if (thisCopy[i] !== targetCopy[i]) {
  1471. x = thisCopy[i];
  1472. y = targetCopy[i];
  1473. break
  1474. }
  1475. }
  1476. if (x < y) return -1
  1477. if (y < x) return 1
  1478. return 0
  1479. };
  1480. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  1481. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  1482. //
  1483. // Arguments:
  1484. // - buffer - a Buffer to search
  1485. // - val - a string, Buffer, or number
  1486. // - byteOffset - an index into `buffer`; will be clamped to an int32
  1487. // - encoding - an optional encoding, relevant is val is a string
  1488. // - dir - true for indexOf, false for lastIndexOf
  1489. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  1490. // Empty buffer means no match
  1491. if (buffer.length === 0) return -1
  1492. // Normalize byteOffset
  1493. if (typeof byteOffset === 'string') {
  1494. encoding = byteOffset;
  1495. byteOffset = 0;
  1496. } else if (byteOffset > 0x7fffffff) {
  1497. byteOffset = 0x7fffffff;
  1498. } else if (byteOffset < -2147483648) {
  1499. byteOffset = -2147483648;
  1500. }
  1501. byteOffset = +byteOffset; // Coerce to Number.
  1502. if (isNaN(byteOffset)) {
  1503. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  1504. byteOffset = dir ? 0 : (buffer.length - 1);
  1505. }
  1506. // Normalize byteOffset: negative offsets start from the end of the buffer
  1507. if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
  1508. if (byteOffset >= buffer.length) {
  1509. if (dir) return -1
  1510. else byteOffset = buffer.length - 1;
  1511. } else if (byteOffset < 0) {
  1512. if (dir) byteOffset = 0;
  1513. else return -1
  1514. }
  1515. // Normalize val
  1516. if (typeof val === 'string') {
  1517. val = Buffer$1.from(val, encoding);
  1518. }
  1519. // Finally, search either indexOf (if dir is true) or lastIndexOf
  1520. if (internalIsBuffer(val)) {
  1521. // Special case: looking for empty string/buffer always fails
  1522. if (val.length === 0) {
  1523. return -1
  1524. }
  1525. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  1526. } else if (typeof val === 'number') {
  1527. val = val & 0xFF; // Search for a byte value [0-255]
  1528. if (Buffer$1.TYPED_ARRAY_SUPPORT &&
  1529. typeof Uint8Array.prototype.indexOf === 'function') {
  1530. if (dir) {
  1531. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  1532. } else {
  1533. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  1534. }
  1535. }
  1536. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  1537. }
  1538. throw new TypeError('val must be string, number or Buffer')
  1539. }
  1540. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  1541. var indexSize = 1;
  1542. var arrLength = arr.length;
  1543. var valLength = val.length;
  1544. if (encoding !== undefined) {
  1545. encoding = String(encoding).toLowerCase();
  1546. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  1547. encoding === 'utf16le' || encoding === 'utf-16le') {
  1548. if (arr.length < 2 || val.length < 2) {
  1549. return -1
  1550. }
  1551. indexSize = 2;
  1552. arrLength /= 2;
  1553. valLength /= 2;
  1554. byteOffset /= 2;
  1555. }
  1556. }
  1557. function read (buf, i) {
  1558. if (indexSize === 1) {
  1559. return buf[i]
  1560. } else {
  1561. return buf.readUInt16BE(i * indexSize)
  1562. }
  1563. }
  1564. var i;
  1565. if (dir) {
  1566. var foundIndex = -1;
  1567. for (i = byteOffset; i < arrLength; i++) {
  1568. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  1569. if (foundIndex === -1) foundIndex = i;
  1570. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  1571. } else {
  1572. if (foundIndex !== -1) i -= i - foundIndex;
  1573. foundIndex = -1;
  1574. }
  1575. }
  1576. } else {
  1577. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
  1578. for (i = byteOffset; i >= 0; i--) {
  1579. var found = true;
  1580. for (var j = 0; j < valLength; j++) {
  1581. if (read(arr, i + j) !== read(val, j)) {
  1582. found = false;
  1583. break
  1584. }
  1585. }
  1586. if (found) return i
  1587. }
  1588. }
  1589. return -1
  1590. }
  1591. Buffer$1.prototype.includes = function includes (val, byteOffset, encoding) {
  1592. return this.indexOf(val, byteOffset, encoding) !== -1
  1593. };
  1594. Buffer$1.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  1595. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  1596. };
  1597. Buffer$1.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  1598. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  1599. };
  1600. function hexWrite (buf, string, offset, length) {
  1601. offset = Number(offset) || 0;
  1602. var remaining = buf.length - offset;
  1603. if (!length) {
  1604. length = remaining;
  1605. } else {
  1606. length = Number(length);
  1607. if (length > remaining) {
  1608. length = remaining;
  1609. }
  1610. }
  1611. // must be an even number of digits
  1612. var strLen = string.length;
  1613. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  1614. if (length > strLen / 2) {
  1615. length = strLen / 2;
  1616. }
  1617. for (var i = 0; i < length; ++i) {
  1618. var parsed = parseInt(string.substr(i * 2, 2), 16);
  1619. if (isNaN(parsed)) return i
  1620. buf[offset + i] = parsed;
  1621. }
  1622. return i
  1623. }
  1624. function utf8Write (buf, string, offset, length) {
  1625. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  1626. }
  1627. function asciiWrite (buf, string, offset, length) {
  1628. return blitBuffer(asciiToBytes(string), buf, offset, length)
  1629. }
  1630. function latin1Write (buf, string, offset, length) {
  1631. return asciiWrite(buf, string, offset, length)
  1632. }
  1633. function base64Write (buf, string, offset, length) {
  1634. return blitBuffer(base64ToBytes(string), buf, offset, length)
  1635. }
  1636. function ucs2Write (buf, string, offset, length) {
  1637. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  1638. }
  1639. Buffer$1.prototype.write = function write (string, offset, length, encoding) {
  1640. // Buffer#write(string)
  1641. if (offset === undefined) {
  1642. encoding = 'utf8';
  1643. length = this.length;
  1644. offset = 0;
  1645. // Buffer#write(string, encoding)
  1646. } else if (length === undefined && typeof offset === 'string') {
  1647. encoding = offset;
  1648. length = this.length;
  1649. offset = 0;
  1650. // Buffer#write(string, offset[, length][, encoding])
  1651. } else if (isFinite(offset)) {
  1652. offset = offset | 0;
  1653. if (isFinite(length)) {
  1654. length = length | 0;
  1655. if (encoding === undefined) encoding = 'utf8';
  1656. } else {
  1657. encoding = length;
  1658. length = undefined;
  1659. }
  1660. // legacy write(string, encoding, offset, length) - remove in v0.13
  1661. } else {
  1662. throw new Error(
  1663. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  1664. )
  1665. }
  1666. var remaining = this.length - offset;
  1667. if (length === undefined || length > remaining) length = remaining;
  1668. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  1669. throw new RangeError('Attempt to write outside buffer bounds')
  1670. }
  1671. if (!encoding) encoding = 'utf8';
  1672. var loweredCase = false;
  1673. for (;;) {
  1674. switch (encoding) {
  1675. case 'hex':
  1676. return hexWrite(this, string, offset, length)
  1677. case 'utf8':
  1678. case 'utf-8':
  1679. return utf8Write(this, string, offset, length)
  1680. case 'ascii':
  1681. return asciiWrite(this, string, offset, length)
  1682. case 'latin1':
  1683. case 'binary':
  1684. return latin1Write(this, string, offset, length)
  1685. case 'base64':
  1686. // Warning: maxLength not taken into account in base64Write
  1687. return base64Write(this, string, offset, length)
  1688. case 'ucs2':
  1689. case 'ucs-2':
  1690. case 'utf16le':
  1691. case 'utf-16le':
  1692. return ucs2Write(this, string, offset, length)
  1693. default:
  1694. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  1695. encoding = ('' + encoding).toLowerCase();
  1696. loweredCase = true;
  1697. }
  1698. }
  1699. };
  1700. Buffer$1.prototype.toJSON = function toJSON () {
  1701. return {
  1702. type: 'Buffer',
  1703. data: Array.prototype.slice.call(this._arr || this, 0)
  1704. }
  1705. };
  1706. function base64Slice (buf, start, end) {
  1707. if (start === 0 && end === buf.length) {
  1708. return fromByteArray(buf)
  1709. } else {
  1710. return fromByteArray(buf.slice(start, end))
  1711. }
  1712. }
  1713. function utf8Slice (buf, start, end) {
  1714. end = Math.min(buf.length, end);
  1715. var res = [];
  1716. var i = start;
  1717. while (i < end) {
  1718. var firstByte = buf[i];
  1719. var codePoint = null;
  1720. var bytesPerSequence = (firstByte > 0xEF) ? 4
  1721. : (firstByte > 0xDF) ? 3
  1722. : (firstByte > 0xBF) ? 2
  1723. : 1;
  1724. if (i + bytesPerSequence <= end) {
  1725. var secondByte, thirdByte, fourthByte, tempCodePoint;
  1726. switch (bytesPerSequence) {
  1727. case 1:
  1728. if (firstByte < 0x80) {
  1729. codePoint = firstByte;
  1730. }
  1731. break
  1732. case 2:
  1733. secondByte = buf[i + 1];
  1734. if ((secondByte & 0xC0) === 0x80) {
  1735. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
  1736. if (tempCodePoint > 0x7F) {
  1737. codePoint = tempCodePoint;
  1738. }
  1739. }
  1740. break
  1741. case 3:
  1742. secondByte = buf[i + 1];
  1743. thirdByte = buf[i + 2];
  1744. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  1745. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
  1746. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  1747. codePoint = tempCodePoint;
  1748. }
  1749. }
  1750. break
  1751. case 4:
  1752. secondByte = buf[i + 1];
  1753. thirdByte = buf[i + 2];
  1754. fourthByte = buf[i + 3];
  1755. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  1756. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
  1757. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  1758. codePoint = tempCodePoint;
  1759. }
  1760. }
  1761. }
  1762. }
  1763. if (codePoint === null) {
  1764. // we did not generate a valid codePoint so insert a
  1765. // replacement char (U+FFFD) and advance only 1 byte
  1766. codePoint = 0xFFFD;
  1767. bytesPerSequence = 1;
  1768. } else if (codePoint > 0xFFFF) {
  1769. // encode to utf16 (surrogate pair dance)
  1770. codePoint -= 0x10000;
  1771. res.push(codePoint >>> 10 & 0x3FF | 0xD800);
  1772. codePoint = 0xDC00 | codePoint & 0x3FF;
  1773. }
  1774. res.push(codePoint);
  1775. i += bytesPerSequence;
  1776. }
  1777. return decodeCodePointsArray(res)
  1778. }
  1779. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  1780. // the lowest limit is Chrome, with 0x10000 args.
  1781. // We go 1 magnitude less, for safety
  1782. var MAX_ARGUMENTS_LENGTH = 0x1000;
  1783. function decodeCodePointsArray (codePoints) {
  1784. var len = codePoints.length;
  1785. if (len <= MAX_ARGUMENTS_LENGTH) {
  1786. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  1787. }
  1788. // Decode in chunks to avoid "call stack size exceeded".
  1789. var res = '';
  1790. var i = 0;
  1791. while (i < len) {
  1792. res += String.fromCharCode.apply(
  1793. String,
  1794. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  1795. );
  1796. }
  1797. return res
  1798. }
  1799. function asciiSlice (buf, start, end) {
  1800. var ret = '';
  1801. end = Math.min(buf.length, end);
  1802. for (var i = start; i < end; ++i) {
  1803. ret += String.fromCharCode(buf[i] & 0x7F);
  1804. }
  1805. return ret
  1806. }
  1807. function latin1Slice (buf, start, end) {
  1808. var ret = '';
  1809. end = Math.min(buf.length, end);
  1810. for (var i = start; i < end; ++i) {
  1811. ret += String.fromCharCode(buf[i]);
  1812. }
  1813. return ret
  1814. }
  1815. function hexSlice (buf, start, end) {
  1816. var len = buf.length;
  1817. if (!start || start < 0) start = 0;
  1818. if (!end || end < 0 || end > len) end = len;
  1819. var out = '';
  1820. for (var i = start; i < end; ++i) {
  1821. out += toHex(buf[i]);
  1822. }
  1823. return out
  1824. }
  1825. function utf16leSlice (buf, start, end) {
  1826. var bytes = buf.slice(start, end);
  1827. var res = '';
  1828. for (var i = 0; i < bytes.length; i += 2) {
  1829. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
  1830. }
  1831. return res
  1832. }
  1833. Buffer$1.prototype.slice = function slice (start, end) {
  1834. var len = this.length;
  1835. start = ~~start;
  1836. end = end === undefined ? len : ~~end;
  1837. if (start < 0) {
  1838. start += len;
  1839. if (start < 0) start = 0;
  1840. } else if (start > len) {
  1841. start = len;
  1842. }
  1843. if (end < 0) {
  1844. end += len;
  1845. if (end < 0) end = 0;
  1846. } else if (end > len) {
  1847. end = len;
  1848. }
  1849. if (end < start) end = start;
  1850. var newBuf;
  1851. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  1852. newBuf = this.subarray(start, end);
  1853. newBuf.__proto__ = Buffer$1.prototype;
  1854. } else {
  1855. var sliceLen = end - start;
  1856. newBuf = new Buffer$1(sliceLen, undefined);
  1857. for (var i = 0; i < sliceLen; ++i) {
  1858. newBuf[i] = this[i + start];
  1859. }
  1860. }
  1861. return newBuf
  1862. };
  1863. /*
  1864. * Need to make sure that buffer isn't trying to write out of bounds.
  1865. */
  1866. function checkOffset (offset, ext, length) {
  1867. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  1868. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  1869. }
  1870. Buffer$1.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  1871. offset = offset | 0;
  1872. byteLength = byteLength | 0;
  1873. if (!noAssert) checkOffset(offset, byteLength, this.length);
  1874. var val = this[offset];
  1875. var mul = 1;
  1876. var i = 0;
  1877. while (++i < byteLength && (mul *= 0x100)) {
  1878. val += this[offset + i] * mul;
  1879. }
  1880. return val
  1881. };
  1882. Buffer$1.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  1883. offset = offset | 0;
  1884. byteLength = byteLength | 0;
  1885. if (!noAssert) {
  1886. checkOffset(offset, byteLength, this.length);
  1887. }
  1888. var val = this[offset + --byteLength];
  1889. var mul = 1;
  1890. while (byteLength > 0 && (mul *= 0x100)) {
  1891. val += this[offset + --byteLength] * mul;
  1892. }
  1893. return val
  1894. };
  1895. Buffer$1.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1896. if (!noAssert) checkOffset(offset, 1, this.length);
  1897. return this[offset]
  1898. };
  1899. Buffer$1.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1900. if (!noAssert) checkOffset(offset, 2, this.length);
  1901. return this[offset] | (this[offset + 1] << 8)
  1902. };
  1903. Buffer$1.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1904. if (!noAssert) checkOffset(offset, 2, this.length);
  1905. return (this[offset] << 8) | this[offset + 1]
  1906. };
  1907. Buffer$1.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1908. if (!noAssert) checkOffset(offset, 4, this.length);
  1909. return ((this[offset]) |
  1910. (this[offset + 1] << 8) |
  1911. (this[offset + 2] << 16)) +
  1912. (this[offset + 3] * 0x1000000)
  1913. };
  1914. Buffer$1.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1915. if (!noAssert) checkOffset(offset, 4, this.length);
  1916. return (this[offset] * 0x1000000) +
  1917. ((this[offset + 1] << 16) |
  1918. (this[offset + 2] << 8) |
  1919. this[offset + 3])
  1920. };
  1921. Buffer$1.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1922. offset = offset | 0;
  1923. byteLength = byteLength | 0;
  1924. if (!noAssert) checkOffset(offset, byteLength, this.length);
  1925. var val = this[offset];
  1926. var mul = 1;
  1927. var i = 0;
  1928. while (++i < byteLength && (mul *= 0x100)) {
  1929. val += this[offset + i] * mul;
  1930. }
  1931. mul *= 0x80;
  1932. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  1933. return val
  1934. };
  1935. Buffer$1.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1936. offset = offset | 0;
  1937. byteLength = byteLength | 0;
  1938. if (!noAssert) checkOffset(offset, byteLength, this.length);
  1939. var i = byteLength;
  1940. var mul = 1;
  1941. var val = this[offset + --i];
  1942. while (i > 0 && (mul *= 0x100)) {
  1943. val += this[offset + --i] * mul;
  1944. }
  1945. mul *= 0x80;
  1946. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  1947. return val
  1948. };
  1949. Buffer$1.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1950. if (!noAssert) checkOffset(offset, 1, this.length);
  1951. if (!(this[offset] & 0x80)) return (this[offset])
  1952. return ((0xff - this[offset] + 1) * -1)
  1953. };
  1954. Buffer$1.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1955. if (!noAssert) checkOffset(offset, 2, this.length);
  1956. var val = this[offset] | (this[offset + 1] << 8);
  1957. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1958. };
  1959. Buffer$1.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1960. if (!noAssert) checkOffset(offset, 2, this.length);
  1961. var val = this[offset + 1] | (this[offset] << 8);
  1962. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1963. };
  1964. Buffer$1.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1965. if (!noAssert) checkOffset(offset, 4, this.length);
  1966. return (this[offset]) |
  1967. (this[offset + 1] << 8) |
  1968. (this[offset + 2] << 16) |
  1969. (this[offset + 3] << 24)
  1970. };
  1971. Buffer$1.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1972. if (!noAssert) checkOffset(offset, 4, this.length);
  1973. return (this[offset] << 24) |
  1974. (this[offset + 1] << 16) |
  1975. (this[offset + 2] << 8) |
  1976. (this[offset + 3])
  1977. };
  1978. Buffer$1.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1979. if (!noAssert) checkOffset(offset, 4, this.length);
  1980. return read(this, offset, true, 23, 4)
  1981. };
  1982. Buffer$1.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1983. if (!noAssert) checkOffset(offset, 4, this.length);
  1984. return read(this, offset, false, 23, 4)
  1985. };
  1986. Buffer$1.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1987. if (!noAssert) checkOffset(offset, 8, this.length);
  1988. return read(this, offset, true, 52, 8)
  1989. };
  1990. Buffer$1.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1991. if (!noAssert) checkOffset(offset, 8, this.length);
  1992. return read(this, offset, false, 52, 8)
  1993. };
  1994. function checkInt (buf, value, offset, ext, max, min) {
  1995. if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1996. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1997. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1998. }
  1999. Buffer$1.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  2000. value = +value;
  2001. offset = offset | 0;
  2002. byteLength = byteLength | 0;
  2003. if (!noAssert) {
  2004. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  2005. checkInt(this, value, offset, byteLength, maxBytes, 0);
  2006. }
  2007. var mul = 1;
  2008. var i = 0;
  2009. this[offset] = value & 0xFF;
  2010. while (++i < byteLength && (mul *= 0x100)) {
  2011. this[offset + i] = (value / mul) & 0xFF;
  2012. }
  2013. return offset + byteLength
  2014. };
  2015. Buffer$1.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  2016. value = +value;
  2017. offset = offset | 0;
  2018. byteLength = byteLength | 0;
  2019. if (!noAssert) {
  2020. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  2021. checkInt(this, value, offset, byteLength, maxBytes, 0);
  2022. }
  2023. var i = byteLength - 1;
  2024. var mul = 1;
  2025. this[offset + i] = value & 0xFF;
  2026. while (--i >= 0 && (mul *= 0x100)) {
  2027. this[offset + i] = (value / mul) & 0xFF;
  2028. }
  2029. return offset + byteLength
  2030. };
  2031. Buffer$1.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  2032. value = +value;
  2033. offset = offset | 0;
  2034. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
  2035. if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
  2036. this[offset] = (value & 0xff);
  2037. return offset + 1
  2038. };
  2039. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  2040. if (value < 0) value = 0xffff + value + 1;
  2041. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  2042. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  2043. (littleEndian ? i : 1 - i) * 8;
  2044. }
  2045. }
  2046. Buffer$1.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  2047. value = +value;
  2048. offset = offset | 0;
  2049. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  2050. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  2051. this[offset] = (value & 0xff);
  2052. this[offset + 1] = (value >>> 8);
  2053. } else {
  2054. objectWriteUInt16(this, value, offset, true);
  2055. }
  2056. return offset + 2
  2057. };
  2058. Buffer$1.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  2059. value = +value;
  2060. offset = offset | 0;
  2061. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  2062. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  2063. this[offset] = (value >>> 8);
  2064. this[offset + 1] = (value & 0xff);
  2065. } else {
  2066. objectWriteUInt16(this, value, offset, false);
  2067. }
  2068. return offset + 2
  2069. };
  2070. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  2071. if (value < 0) value = 0xffffffff + value + 1;
  2072. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  2073. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;
  2074. }
  2075. }
  2076. Buffer$1.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  2077. value = +value;
  2078. offset = offset | 0;
  2079. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  2080. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  2081. this[offset + 3] = (value >>> 24);
  2082. this[offset + 2] = (value >>> 16);
  2083. this[offset + 1] = (value >>> 8);
  2084. this[offset] = (value & 0xff);
  2085. } else {
  2086. objectWriteUInt32(this, value, offset, true);
  2087. }
  2088. return offset + 4
  2089. };
  2090. Buffer$1.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  2091. value = +value;
  2092. offset = offset | 0;
  2093. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  2094. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  2095. this[offset] = (value >>> 24);
  2096. this[offset + 1] = (value >>> 16);
  2097. this[offset + 2] = (value >>> 8);
  2098. this[offset + 3] = (value & 0xff);
  2099. } else {
  2100. objectWriteUInt32(this, value, offset, false);
  2101. }
  2102. return offset + 4
  2103. };
  2104. Buffer$1.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  2105. value = +value;
  2106. offset = offset | 0;
  2107. if (!noAssert) {
  2108. var limit = Math.pow(2, 8 * byteLength - 1);
  2109. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  2110. }
  2111. var i = 0;
  2112. var mul = 1;
  2113. var sub = 0;
  2114. this[offset] = value & 0xFF;
  2115. while (++i < byteLength && (mul *= 0x100)) {
  2116. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  2117. sub = 1;
  2118. }
  2119. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  2120. }
  2121. return offset + byteLength
  2122. };
  2123. Buffer$1.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  2124. value = +value;
  2125. offset = offset | 0;
  2126. if (!noAssert) {
  2127. var limit = Math.pow(2, 8 * byteLength - 1);
  2128. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  2129. }
  2130. var i = byteLength - 1;
  2131. var mul = 1;
  2132. var sub = 0;
  2133. this[offset + i] = value & 0xFF;
  2134. while (--i >= 0 && (mul *= 0x100)) {
  2135. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  2136. sub = 1;
  2137. }
  2138. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  2139. }
  2140. return offset + byteLength
  2141. };
  2142. Buffer$1.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  2143. value = +value;
  2144. offset = offset | 0;
  2145. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -128);
  2146. if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
  2147. if (value < 0) value = 0xff + value + 1;
  2148. this[offset] = (value & 0xff);
  2149. return offset + 1
  2150. };
  2151. Buffer$1.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  2152. value = +value;
  2153. offset = offset | 0;
  2154. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -32768);
  2155. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  2156. this[offset] = (value & 0xff);
  2157. this[offset + 1] = (value >>> 8);
  2158. } else {
  2159. objectWriteUInt16(this, value, offset, true);
  2160. }
  2161. return offset + 2
  2162. };
  2163. Buffer$1.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  2164. value = +value;
  2165. offset = offset | 0;
  2166. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -32768);
  2167. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  2168. this[offset] = (value >>> 8);
  2169. this[offset + 1] = (value & 0xff);
  2170. } else {
  2171. objectWriteUInt16(this, value, offset, false);
  2172. }
  2173. return offset + 2
  2174. };
  2175. Buffer$1.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  2176. value = +value;
  2177. offset = offset | 0;
  2178. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -2147483648);
  2179. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  2180. this[offset] = (value & 0xff);
  2181. this[offset + 1] = (value >>> 8);
  2182. this[offset + 2] = (value >>> 16);
  2183. this[offset + 3] = (value >>> 24);
  2184. } else {
  2185. objectWriteUInt32(this, value, offset, true);
  2186. }
  2187. return offset + 4
  2188. };
  2189. Buffer$1.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  2190. value = +value;
  2191. offset = offset | 0;
  2192. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -2147483648);
  2193. if (value < 0) value = 0xffffffff + value + 1;
  2194. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  2195. this[offset] = (value >>> 24);
  2196. this[offset + 1] = (value >>> 16);
  2197. this[offset + 2] = (value >>> 8);
  2198. this[offset + 3] = (value & 0xff);
  2199. } else {
  2200. objectWriteUInt32(this, value, offset, false);
  2201. }
  2202. return offset + 4
  2203. };
  2204. function checkIEEE754 (buf, value, offset, ext, max, min) {
  2205. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  2206. if (offset < 0) throw new RangeError('Index out of range')
  2207. }
  2208. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  2209. if (!noAssert) {
  2210. checkIEEE754(buf, value, offset, 4);
  2211. }
  2212. write(buf, value, offset, littleEndian, 23, 4);
  2213. return offset + 4
  2214. }
  2215. Buffer$1.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  2216. return writeFloat(this, value, offset, true, noAssert)
  2217. };
  2218. Buffer$1.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  2219. return writeFloat(this, value, offset, false, noAssert)
  2220. };
  2221. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  2222. if (!noAssert) {
  2223. checkIEEE754(buf, value, offset, 8);
  2224. }
  2225. write(buf, value, offset, littleEndian, 52, 8);
  2226. return offset + 8
  2227. }
  2228. Buffer$1.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  2229. return writeDouble(this, value, offset, true, noAssert)
  2230. };
  2231. Buffer$1.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  2232. return writeDouble(this, value, offset, false, noAssert)
  2233. };
  2234. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  2235. Buffer$1.prototype.copy = function copy (target, targetStart, start, end) {
  2236. if (!start) start = 0;
  2237. if (!end && end !== 0) end = this.length;
  2238. if (targetStart >= target.length) targetStart = target.length;
  2239. if (!targetStart) targetStart = 0;
  2240. if (end > 0 && end < start) end = start;
  2241. // Copy 0 bytes; we're done
  2242. if (end === start) return 0
  2243. if (target.length === 0 || this.length === 0) return 0
  2244. // Fatal error conditions
  2245. if (targetStart < 0) {
  2246. throw new RangeError('targetStart out of bounds')
  2247. }
  2248. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  2249. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  2250. // Are we oob?
  2251. if (end > this.length) end = this.length;
  2252. if (target.length - targetStart < end - start) {
  2253. end = target.length - targetStart + start;
  2254. }
  2255. var len = end - start;
  2256. var i;
  2257. if (this === target && start < targetStart && targetStart < end) {
  2258. // descending copy from end
  2259. for (i = len - 1; i >= 0; --i) {
  2260. target[i + targetStart] = this[i + start];
  2261. }
  2262. } else if (len < 1000 || !Buffer$1.TYPED_ARRAY_SUPPORT) {
  2263. // ascending copy from start
  2264. for (i = 0; i < len; ++i) {
  2265. target[i + targetStart] = this[i + start];
  2266. }
  2267. } else {
  2268. Uint8Array.prototype.set.call(
  2269. target,
  2270. this.subarray(start, start + len),
  2271. targetStart
  2272. );
  2273. }
  2274. return len
  2275. };
  2276. // Usage:
  2277. // buffer.fill(number[, offset[, end]])
  2278. // buffer.fill(buffer[, offset[, end]])
  2279. // buffer.fill(string[, offset[, end]][, encoding])
  2280. Buffer$1.prototype.fill = function fill (val, start, end, encoding) {
  2281. // Handle string cases:
  2282. if (typeof val === 'string') {
  2283. if (typeof start === 'string') {
  2284. encoding = start;
  2285. start = 0;
  2286. end = this.length;
  2287. } else if (typeof end === 'string') {
  2288. encoding = end;
  2289. end = this.length;
  2290. }
  2291. if (val.length === 1) {
  2292. var code = val.charCodeAt(0);
  2293. if (code < 256) {
  2294. val = code;
  2295. }
  2296. }
  2297. if (encoding !== undefined && typeof encoding !== 'string') {
  2298. throw new TypeError('encoding must be a string')
  2299. }
  2300. if (typeof encoding === 'string' && !Buffer$1.isEncoding(encoding)) {
  2301. throw new TypeError('Unknown encoding: ' + encoding)
  2302. }
  2303. } else if (typeof val === 'number') {
  2304. val = val & 255;
  2305. }
  2306. // Invalid ranges are not set to a default, so can range check early.
  2307. if (start < 0 || this.length < start || this.length < end) {
  2308. throw new RangeError('Out of range index')
  2309. }
  2310. if (end <= start) {
  2311. return this
  2312. }
  2313. start = start >>> 0;
  2314. end = end === undefined ? this.length : end >>> 0;
  2315. if (!val) val = 0;
  2316. var i;
  2317. if (typeof val === 'number') {
  2318. for (i = start; i < end; ++i) {
  2319. this[i] = val;
  2320. }
  2321. } else {
  2322. var bytes = internalIsBuffer(val)
  2323. ? val
  2324. : utf8ToBytes(new Buffer$1(val, encoding).toString());
  2325. var len = bytes.length;
  2326. for (i = 0; i < end - start; ++i) {
  2327. this[i + start] = bytes[i % len];
  2328. }
  2329. }
  2330. return this
  2331. };
  2332. // HELPER FUNCTIONS
  2333. // ================
  2334. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
  2335. function base64clean (str) {
  2336. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  2337. str = stringtrim(str).replace(INVALID_BASE64_RE, '');
  2338. // Node converts strings with length < 2 to ''
  2339. if (str.length < 2) return ''
  2340. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  2341. while (str.length % 4 !== 0) {
  2342. str = str + '=';
  2343. }
  2344. return str
  2345. }
  2346. function stringtrim (str) {
  2347. if (str.trim) return str.trim()
  2348. return str.replace(/^\s+|\s+$/g, '')
  2349. }
  2350. function toHex (n) {
  2351. if (n < 16) return '0' + n.toString(16)
  2352. return n.toString(16)
  2353. }
  2354. function utf8ToBytes (string, units) {
  2355. units = units || Infinity;
  2356. var codePoint;
  2357. var length = string.length;
  2358. var leadSurrogate = null;
  2359. var bytes = [];
  2360. for (var i = 0; i < length; ++i) {
  2361. codePoint = string.charCodeAt(i);
  2362. // is surrogate component
  2363. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  2364. // last char was a lead
  2365. if (!leadSurrogate) {
  2366. // no lead yet
  2367. if (codePoint > 0xDBFF) {
  2368. // unexpected trail
  2369. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  2370. continue
  2371. } else if (i + 1 === length) {
  2372. // unpaired lead
  2373. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  2374. continue
  2375. }
  2376. // valid lead
  2377. leadSurrogate = codePoint;
  2378. continue
  2379. }
  2380. // 2 leads in a row
  2381. if (codePoint < 0xDC00) {
  2382. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  2383. leadSurrogate = codePoint;
  2384. continue
  2385. }
  2386. // valid surrogate pair
  2387. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
  2388. } else if (leadSurrogate) {
  2389. // valid bmp char, but last char was a lead
  2390. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  2391. }
  2392. leadSurrogate = null;
  2393. // encode utf8
  2394. if (codePoint < 0x80) {
  2395. if ((units -= 1) < 0) break
  2396. bytes.push(codePoint);
  2397. } else if (codePoint < 0x800) {
  2398. if ((units -= 2) < 0) break
  2399. bytes.push(
  2400. codePoint >> 0x6 | 0xC0,
  2401. codePoint & 0x3F | 0x80
  2402. );
  2403. } else if (codePoint < 0x10000) {
  2404. if ((units -= 3) < 0) break
  2405. bytes.push(
  2406. codePoint >> 0xC | 0xE0,
  2407. codePoint >> 0x6 & 0x3F | 0x80,
  2408. codePoint & 0x3F | 0x80
  2409. );
  2410. } else if (codePoint < 0x110000) {
  2411. if ((units -= 4) < 0) break
  2412. bytes.push(
  2413. codePoint >> 0x12 | 0xF0,
  2414. codePoint >> 0xC & 0x3F | 0x80,
  2415. codePoint >> 0x6 & 0x3F | 0x80,
  2416. codePoint & 0x3F | 0x80
  2417. );
  2418. } else {
  2419. throw new Error('Invalid code point')
  2420. }
  2421. }
  2422. return bytes
  2423. }
  2424. function asciiToBytes (str) {
  2425. var byteArray = [];
  2426. for (var i = 0; i < str.length; ++i) {
  2427. // Node's code seems to be doing this and not & 0x7F..
  2428. byteArray.push(str.charCodeAt(i) & 0xFF);
  2429. }
  2430. return byteArray
  2431. }
  2432. function utf16leToBytes (str, units) {
  2433. var c, hi, lo;
  2434. var byteArray = [];
  2435. for (var i = 0; i < str.length; ++i) {
  2436. if ((units -= 2) < 0) break
  2437. c = str.charCodeAt(i);
  2438. hi = c >> 8;
  2439. lo = c % 256;
  2440. byteArray.push(lo);
  2441. byteArray.push(hi);
  2442. }
  2443. return byteArray
  2444. }
  2445. function base64ToBytes (str) {
  2446. return toByteArray(base64clean(str))
  2447. }
  2448. function blitBuffer (src, dst, offset, length) {
  2449. for (var i = 0; i < length; ++i) {
  2450. if ((i + offset >= dst.length) || (i >= src.length)) break
  2451. dst[i + offset] = src[i];
  2452. }
  2453. return i
  2454. }
  2455. function isnan (val) {
  2456. return val !== val // eslint-disable-line no-self-compare
  2457. }
  2458. // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
  2459. // The _isBuffer check is for Safari 5-7 support, because it's missing
  2460. // Object.prototype.constructor. Remove this eventually
  2461. function isBuffer$1(obj) {
  2462. return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
  2463. }
  2464. function isFastBuffer (obj) {
  2465. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  2466. }
  2467. // For Node v0.10 support. Remove this eventually.
  2468. function isSlowBuffer (obj) {
  2469. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
  2470. }
  2471. /*
  2472. * Shared base64 decode helper for generated decode data.
  2473. * Assumes global atob is available.
  2474. */
  2475. function decodeBase64(input) {
  2476. const binary =
  2477. // eslint-disable-next-line n/no-unsupported-features/node-builtins
  2478. typeof atob === "function"
  2479. ? // Browser (and Node >=16)
  2480. // eslint-disable-next-line n/no-unsupported-features/node-builtins
  2481. atob(input)
  2482. : // Older Node versions (<16)
  2483. // eslint-disable-next-line n/no-unsupported-features/node-builtins
  2484. typeof Buffer$1.from === "function"
  2485. ? // eslint-disable-next-line n/no-unsupported-features/node-builtins
  2486. Buffer$1.from(input, "base64").toString("binary")
  2487. : // eslint-disable-next-line unicorn/no-new-buffer, n/no-deprecated-api
  2488. new Buffer$1(input, "base64").toString("binary");
  2489. const evenLength = binary.length & -2; // Round down to even length
  2490. const out = new Uint16Array(evenLength / 2);
  2491. for (let index = 0, outIndex = 0; index < evenLength; index += 2) {
  2492. const lo = binary.charCodeAt(index);
  2493. const hi = binary.charCodeAt(index + 1);
  2494. out[outIndex++] = lo | (hi << 8);
  2495. }
  2496. return out;
  2497. }
  2498. // Generated using scripts/write-decode-map.ts
  2499. const htmlDecodeTree = /* #__PURE__ */ decodeBase64("QR08ALkAAgH6AYsDNQR2BO0EPgXZBQEGLAbdBxMISQrvCmQLfQurDKQNLw4fD4YPpA+6D/IPAAAAAAAAAAAAAAAAKhBMEY8TmxUWF2EYLBkxGuAa3RsJHDscWR8YIC8jSCSIJcMl6ie3Ku8rEC0CLjoupS7kLgAIRU1hYmNmZ2xtbm9wcnN0dVQAWgBeAGUAaQBzAHcAfgCBAIQAhwCSAJoAoACsALMAbABpAGcAO4DGAMZAUAA7gCYAJkBjAHUAdABlADuAwQDBQHIiZXZlAAJhAAFpeW0AcgByAGMAO4DCAMJAEGRyAADgNdgE3XIAYQB2AGUAO4DAAMBA8CFoYZFj4SFjcgBhZAAAoFMqAAFncIsAjgBvAG4ABGFmAADgNdg43fAlbHlGdW5jdGlvbgCgYSBpAG4AZwA7gMUAxUAAAWNzpACoAHIAAOA12Jzc6SFnbgCgVCJpAGwAZABlADuAwwDDQG0AbAA7gMQAxEAABGFjZWZvcnN1xQDYANoA7QDxAPYA+QD8AAABY3LJAM8AayNzbGFzaAAAoBYidgHTANUAAKDnKmUAZAAAoAYjeQARZIABY3J0AOAA5QDrAGEidXNlAACgNSLuI291bGxpcwCgLCFhAJJjcgAA4DXYBd1wAGYAAOA12Dnd5SF2ZdhiYwDyAOoAbSJwZXEAAKBOIgAHSE9hY2RlZmhpbG9yc3UXARoBHwE6AVIBVQFiAWQBZgGCAakB6QHtAfIBYwB5ACdkUABZADuAqQCpQIABY3B5ACUBKAE1AfUhdGUGYWmg0iJ0KGFsRGlmZmVyZW50aWFsRAAAoEUhbCJleXMAAKAtIQACYWVpb0EBRAFKAU0B8iFvbgxhZABpAGwAO4DHAMdAcgBjAAhhbiJpbnQAAKAwIm8AdAAKYQABZG5ZAV0BaSJsbGEAuGB0I2VyRG90ALdg8gA5AWkAp2NyImNsZQAAAkRNUFRwAXQBeQF9AW8AdAAAoJkiaSJudXMAAKCWIuwhdXMAoJUiaSJtZXMAAKCXIm8AAAFjc4cBlAFrKndpc2VDb250b3VySW50ZWdyYWwAAKAyImUjQ3VybHkAAAFEUZwBpAFvJXVibGVRdW90ZQAAoB0gdSJvdGUAAKAZIAACbG5wdbABtgHNAdgBbwBuAGWgNyIAoHQqgAFnaXQAvAHBAcUB8iJ1ZW50AKBhIm4AdAAAoC8i7yV1ckludGVncmFsAKAuIgABZnLRAdMBAKACIe8iZHVjdACgECJuLnRlckNsb2Nrd2lzZUNvbnRvdXJJbnRlZ3JhbAAAoDMi7yFzcwCgLypjAHIAAOA12J7ccABDoNMiYQBwAACgTSKABURKU1phY2VmaW9zAAsCEgIVAhgCGwIsAjQCOQI9AnMCfwNvoEUh9CJyYWhkAKARKWMAeQACZGMAeQAFZGMAeQAPZIABZ3JzACECJQIoAuchZXIAoCEgcgAAoKEhaAB2AACg5CoAAWF5MAIzAvIhb24OYRRkbAB0oAciYQCUY3IAAOA12AfdAAFhZkECawIAAWNtRQJnAvIjaXRpY2FsAAJBREdUUAJUAl8CYwJjInV0ZQC0YG8AdAFZAloC2WJiJGxlQWN1dGUA3WJyImF2ZQBgYGkibGRlANxi7yFuZACgxCJmJWVyZW50aWFsRAAAoEYhcAR9AgAAAAAAAIECjgIAABoDZgAA4DXYO91EoagAhQKJAm8AdAAAoNwgcSJ1YWwAAKBQIuIhbGUAA0NETFJVVpkCqAK1Au8C/wIRA28AbgB0AG8AdQByAEkAbgB0AGUAZwByAGEA7ADEAW8AdAKvAgAAAACwAqhgbiNBcnJvdwAAoNMhAAFlb7kC0AJmAHQAgAFBUlQAwQLGAs0CciJyb3cAAKDQIekkZ2h0QXJyb3cAoNQhZQDlACsCbgBnAAABTFLWAugC5SFmdAABQVLcAuECciJyb3cAAKD4J+kkZ2h0QXJyb3cAoPon6SRnaHRBcnJvdwCg+SdpImdodAAAAUFU9gL7AnIicm93AACg0iFlAGUAAKCoInAAQQIGAwAAAAALA3Iicm93AACg0SFvJHduQXJyb3cAAKDVIWUlcnRpY2FsQmFyAACgJSJuAAADQUJMUlRhJAM2AzoDWgNxA3oDciJyb3cAAKGTIUJVLAMwA2EAcgAAoBMpcCNBcnJvdwAAoPUhciJldmUAEWPlIWZ00gJDAwAASwMAAFIDaSVnaHRWZWN0b3IAAKBQKWUkZVZlY3RvcgAAoF4p5SJjdG9yQqC9IWEAcgAAoFYpaSJnaHQA1AFiAwAAaQNlJGVWZWN0b3IAAKBfKeUiY3RvckKgwSFhAHIAAKBXKWUAZQBBoKQiciJyb3cAAKCnIXIAcgBvAPcAtAIAAWN0gwOHA3IAAOA12J/c8iFvaxBhAAhOVGFjZGZnbG1vcHFzdHV4owOlA6kDsAO/A8IDxgPNA9ID8gP9AwEEFAQeBCAEJQRHAEphSAA7gNAA0EBjAHUAdABlADuAyQDJQIABYWl5ALYDuQO+A/Ihb24aYXIAYwA7gMoAykAtZG8AdAAWYXIAAOA12AjdcgBhAHYAZQA7gMgAyEDlIm1lbnQAoAgiAAFhcNYD2QNjAHIAEmF0AHkAUwLhAwAAAADpA20lYWxsU3F1YXJlAACg+yVlJ3J5U21hbGxTcXVhcmUAAKCrJQABZ3D2A/kDbwBuABhhZgAA4DXYPN3zImlsb26VY3UAAAFhaQYEDgRsAFSgdSppImxkZQAAoEIi7CNpYnJpdW0AoMwhAAFjaRgEGwRyAACgMCFtAACgcyphAJdjbQBsADuAywDLQAABaXApBC0E8yF0cwCgAyLvJG5lbnRpYWxFAKBHIYACY2Zpb3MAPQQ/BEMEXQRyBHkAJGRyAADgNdgJ3WwibGVkAFMCTAQAAAAAVARtJWFsbFNxdWFyZQAAoPwlZSdyeVNtYWxsU3F1YXJlAACgqiVwA2UEAABpBAAAAABtBGYAAOA12D3dwSFsbACgACLyI2llcnRyZgCgMSFjAPIAcQQABkpUYWJjZGZnb3JzdIgEiwSOBJMElwSkBKcEqwStBLIE5QTqBGMAeQADZDuAPgA+QO0hbWFkoJMD3GNyImV2ZQAeYYABZWl5AJ0EoASjBOQhaWwiYXIAYwAcYRNkbwB0ACBhcgAA4DXYCt0AoNkicABmAADgNdg+3eUiYXRlcgADRUZHTFNUvwTIBM8E1QTZBOAEcSJ1YWwATKBlIuUhc3MAoNsidSRsbEVxdWFsAACgZyJyI2VhdGVyAACgoirlIXNzAKB3IuwkYW50RXF1YWwAoH4qaSJsZGUAAKBzImMAcgAA4DXYotwAoGsiAARBYWNmaW9zdfkE/QQFBQgFCwUTBSIFKwVSIkRjeQAqZAABY3QBBQQFZQBrAMdiXmDpIXJjJGFyAACgDCFsJWJlcnRTcGFjZQAAoAsh8AEYBQAAGwVmAACgDSHpJXpvbnRhbExpbmUAoAAlAAFjdCYFKAXyABIF8iFvayZhbQBwAEQBMQU5BW8AdwBuAEgAdQBtAPAAAAFxInVhbAAAoE8iAAdFSk9hY2RmZ21ub3N0dVMFVgVZBVwFYwVtBXAFcwV6BZAFtgXFBckFzQVjAHkAFWTsIWlnMmFjAHkAAWRjAHUAdABlADuAzQDNQAABaXlnBWwFcgBjADuAzgDOQBhkbwB0ADBhcgAAoBEhcgBhAHYAZQA7gMwAzEAAoREhYXB/BYsFAAFjZ4MFhQVyACphaSNuYXJ5SQAAoEghbABpAGUA8wD6AvQBlQUAAKUFZaAsIgABZ3KaBZ4F8iFhbACgKyLzI2VjdGlvbgCgwiJpI3NpYmxlAAABQ1SsBbEFbyJtbWEAAKBjIGkibWVzAACgYiCAAWdwdAC8Bb8FwwVvAG4ALmFmAADgNdhA3WEAmWNjAHIAAKAQIWkibGRlAChh6wHSBQAA1QVjAHkABmRsADuAzwDPQIACY2Zvc3UA4QXpBe0F8gX9BQABaXnlBegFcgBjADRhGWRyAADgNdgN3XAAZgAA4DXYQd3jAfcFAAD7BXIAAOA12KXc8iFjeQhk6yFjeQRkgANISmFjZm9zAAwGDwYSBhUGHQYhBiYGYwB5ACVkYwB5AAxk8CFwYZpjAAFleRkGHAbkIWlsNmEaZHIAAOA12A7dcABmAADgNdhC3WMAcgAA4DXYptyABUpUYWNlZmxtb3N0AD0GQAZDBl4GawZkB2gHcAd0B80H2gdjAHkACWQ7gDwAPECAAmNtbnByAEwGTwZSBlUGWwb1IXRlOWHiIWRhm2NnAACg6ifsI2FjZXRyZgCgEiFyAACgniGAAWFleQBkBmcGagbyIW9uPWHkIWlsO2EbZAABZnNvBjQHdAAABUFDREZSVFVWYXKABp4GpAbGBssG3AYDByEHwQIqBwABbnKEBowGZyVsZUJyYWNrZXQAAKDoJ/Ihb3cAoZAhQlKTBpcGYQByAACg5CHpJGdodEFycm93AKDGIWUjaWxpbmcAAKAII28A9QGqBgAAsgZiJWxlQnJhY2tldAAAoOYnbgDUAbcGAAC+BmUkZVZlY3RvcgAAoGEp5SJjdG9yQqDDIWEAcgAAoFkpbCJvb3IAAKAKI2kiZ2h0AAABQVbSBtcGciJyb3cAAKCUIeUiY3RvcgCgTikAAWVy4AbwBmUAAKGjIkFW5gbrBnIicm93AACgpCHlImN0b3IAoFopaSNhbmdsZQBCorIi+wYAAAAA/wZhAHIAAKDPKXEidWFsAACgtCJwAIABRFRWAAoHEQcYB+8kd25WZWN0b3IAoFEpZSRlVmVjdG9yAACgYCnlImN0b3JCoL8hYQByAACgWCnlImN0b3JCoLwhYQByAACgUilpAGcAaAB0AGEAcgByAG8A9wDMAnMAAANFRkdMU1Q/B0cHTgdUB1gHXwfxJXVhbEdyZWF0ZXIAoNoidSRsbEVxdWFsAACgZiJyI2VhdGVyAACgdiLlIXNzAKChKuwkYW50RXF1YWwAoH0qaSJsZGUAAKByInIAAOA12A/dZaDYIuYjdGFycm93AKDaIWkiZG90AD9hgAFucHcAege1B7kHZwAAAkxSbHKCB5QHmwerB+UhZnQAAUFSiAeNB3Iicm93AACg9SfpJGdodEFycm93AKD3J+kkZ2h0QXJyb3cAoPYn5SFmdAABYXLcAqEHaQBnAGgAdABhAHIAcgBvAPcA5wJpAGcAaAB0AGEAcgByAG8A9wDuAmYAAOA12EPdZQByAAABTFK/B8YHZSRmdEFycm93AACgmSHpJGdodEFycm93AKCYIYABY2h0ANMH1QfXB/IAWgYAoLAh8iFva0FhAKBqIgAEYWNlZmlvc3XpB+wH7gf/BwMICQgOCBEIcAAAoAUpeQAcZAABZGzyB/kHaSR1bVNwYWNlAACgXyBsI2ludHJmAACgMyFyAADgNdgQ3e4jdXNQbHVzAKATInAAZgAA4DXYRN1jAPIA/gecY4AESmFjZWZvc3R1ACEIJAgoCDUIgQiFCDsKQApHCmMAeQAKZGMidXRlAENhgAFhZXkALggxCDQI8iFvbkdh5CFpbEVhHWSAAWdzdwA7CGEIfQjhInRpdmWAAU1UVgBECEwIWQhlJWRpdW1TcGFjZQAAoAsgaABpAAABY25SCFMIawBTAHAAYQBjAOUASwhlAHIAeQBUAGgAaQDuAFQI9CFlZAABR0xnCHUIcgBlAGEAdABlAHIARwByAGUAYQB0AGUA8gDrBGUAcwBzAEwAZQBzAPMA2wdMImluZQAKYHIAAOA12BHdAAJCbnB0jAiRCJkInAhyImVhawAAoGAgwiZyZWFraW5nU3BhY2WgYGYAAKAVIUOq7CqzCMIIzQgAAOcIGwkAAAAAAAAtCQAAbwkAAIcJAACdCcAJGQoAADQKAAFvdbYIvAjuI2dydWVudACgYiJwIkNhcAAAoG0ibyh1YmxlVmVydGljYWxCYXIAAKAmIoABbHF4ANII1wjhCOUibWVudACgCSL1IWFsVKBgImkibGRlAADgQiI4A2kic3RzAACgBCJyI2VhdGVyAACjbyJFRkdMU1T1CPoIAgkJCQ0JFQlxInVhbAAAoHEidSRsbEVxdWFsAADgZyI4A3IjZWF0ZXIAAOBrIjgD5SFzcwCgeSLsJGFudEVxdWFsAOB+KjgDaSJsZGUAAKB1IvUhbXBEASAJJwnvI3duSHVtcADgTiI4A3EidWFsAADgTyI4A2UAAAFmczEJRgn0JFRyaWFuZ2xlQqLqIj0JAAAAAEIJYQByAADgzyk4A3EidWFsAACg7CJzAICibiJFR0xTVABRCVYJXAlhCWkJcSJ1YWwAAKBwInIjZWF0ZXIAAKB4IuUhc3MA4GoiOAPsJGFudEVxdWFsAOB9KjgDaSJsZGUAAKB0IuUic3RlZAABR0x1CX8J8iZlYXRlckdyZWF0ZXIA4KIqOAPlI3NzTGVzcwDgoSo4A/IjZWNlZGVzAKGAIkVTjwmVCXEidWFsAADgryo4A+wkYW50RXF1YWwAoOAiAAFlaaAJqQl2JmVyc2VFbGVtZW50AACgDCLnJWh0VHJpYW5nbGVCousitgkAAAAAuwlhAHIAAODQKTgDcSJ1YWwAAKDtIgABcXXDCeAJdSNhcmVTdQAAAWJwywnVCfMhZXRF4I8iOANxInVhbAAAoOIi5SJyc2V0ReCQIjgDcSJ1YWwAAKDjIoABYmNwAOYJ8AkNCvMhZXRF4IIi0iBxInVhbAAAoIgi4yJlZWRzgKGBIkVTVAD6CQAKBwpxInVhbAAA4LAqOAPsJGFudEVxdWFsAKDhImkibGRlAADgfyI4A+UicnNldEXggyLSIHEidWFsAACgiSJpImxkZQCAoUEiRUZUACIKJwouCnEidWFsAACgRCJ1JGxsRXF1YWwAAKBHImkibGRlAACgSSJlJXJ0aWNhbEJhcgAAoCQiYwByAADgNdip3GkAbABkAGUAO4DRANFAnWMAB0VhY2RmZ21vcHJzdHV2XgphCmgKcgp2CnoKgQqRCpYKqwqtCrsKyArNCuwhaWdSYWMAdQB0AGUAO4DTANNAAAFpeWwKcQpyAGMAO4DUANRAHmRiImxhYwBQYXIAAOA12BLdcgBhAHYAZQA7gNIA0kCAAWFlaQCHCooKjQpjAHIATGFnAGEAqWNjInJvbgCfY3AAZgAA4DXYRt3lI25DdXJseQABRFGeCqYKbyV1YmxlUXVvdGUAAKAcIHUib3RlAACgGCAAoFQqAAFjbLEKtQpyAADgNdiq3GEAcwBoADuA2ADYQGkAbAHACsUKZABlADuA1QDVQGUAcwAAoDcqbQBsADuA1gDWQGUAcgAAAUJQ0wrmCgABYXLXCtoKcgAAoD4gYQBjAAABZWvgCuIKAKDeI2UAdAAAoLQjYSVyZW50aGVzaXMAAKDcI4AEYWNmaGlsb3JzAP0KAwsFCwkLCwsMCxELIwtaC3IjdGlhbEQAAKACInkAH2RyAADgNdgT3WkApmOgY/Ujc01pbnVzsWAAAWlwFQsgC24AYwBhAHIAZQBwAGwAYQBuAOUACgVmAACgGSGAobsqZWlvACoLRQtJC+MiZWRlc4CheiJFU1QANAs5C0ALcSJ1YWwAAKCvKuwkYW50RXF1YWwAoHwiaSJsZGUAAKB+Im0AZQAAoDMgAAFkcE0LUQv1IWN0AKAPIm8jcnRpb24AYaA3ImwAAKAdIgABY2leC2ILcgAA4DXYq9yoYwACVWZvc2oLbwtzC3cLTwBUADuAIgAiQHIAAOA12BTdcABmAACgGiFjAHIAAOA12KzcAAZCRWFjZWZoaW9yc3WPC5MLlwupC7YL2AvbC90LhQyTDJoMowzhIXJyAKAQKUcAO4CuAK5AgAFjbnIAnQugC6ML9SF0ZVRhZwAAoOsncgB0oKAhbAAAoBYpgAFhZXkArwuyC7UL8iFvblhh5CFpbFZhIGR2oBwhZSJyc2UAAAFFVb8LzwsAAWxxwwvIC+UibWVudACgCyL1JGlsaWJyaXVtAKDLIXAmRXF1aWxpYnJpdW0AAKBvKXIAAKAcIW8AoWPnIWh0AARBQ0RGVFVWYewLCgwQDDIMNwxeDHwM9gIAAW5y8Av4C2clbGVCcmFja2V0AACg6SfyIW93AKGSIUJM/wsDDGEAcgAAoOUhZSRmdEFycm93AACgxCFlI2lsaW5nAACgCSNvAPUBFgwAAB4MYiVsZUJyYWNrZXQAAKDnJ24A1AEjDAAAKgxlJGVWZWN0b3IAAKBdKeUiY3RvckKgwiFhAHIAAKBVKWwib29yAACgCyMAAWVyOwxLDGUAAKGiIkFWQQxGDHIicm93AACgpiHlImN0b3IAoFspaSNhbmdsZQBCorMiVgwAAAAAWgxhAHIAAKDQKXEidWFsAACgtSJwAIABRFRWAGUMbAxzDO8kd25WZWN0b3IAoE8pZSRlVmVjdG9yAACgXCnlImN0b3JCoL4hYQByAACgVCnlImN0b3JCoMAhYQByAACgUykAAXB1iQyMDGYAAKAdIe4kZEltcGxpZXMAoHAp6SRnaHRhcnJvdwCg2yEAAWNongyhDHIAAKAbIQCgsSHsJGVEZWxheWVkAKD0KYAGSE9hY2ZoaW1vcXN0dQC/DMgMzAzQDOIM5gwKDQ0NFA0ZDU8NVA1YDQABQ2PDDMYMyCFjeSlkeQAoZEYiVGN5ACxkYyJ1dGUAWmEAorwqYWVpedgM2wzeDOEM8iFvbmBh5CFpbF5hcgBjAFxhIWRyAADgNdgW3e8hcnQAAkRMUlXvDPYM/QwEDW8kd25BcnJvdwAAoJMhZSRmdEFycm93AACgkCHpJGdodEFycm93AKCSIXAjQXJyb3cAAKCRIechbWGjY+EkbGxDaXJjbGUAoBgicABmAADgNdhK3XICHw0AAAAAIg10AACgGiLhIXJlgKGhJUlTVQAqDTINSg3uJXRlcnNlY3Rpb24AoJMidQAAAWJwNw1ADfMhZXRFoI8icSJ1YWwAAKCRIuUicnNldEWgkCJxInVhbAAAoJIibiJpb24AAKCUImMAcgAA4DXYrtxhAHIAAKDGIgACYmNtcF8Nag2ODZANc6DQImUAdABFoNAicSJ1YWwAAKCGIgABY2huDYkNZSJlZHMAgKF7IkVTVAB4DX0NhA1xInVhbAAAoLAq7CRhbnRFcXVhbACgfSJpImxkZQAAoH8iVABoAGEA9ADHCwCgESIAodEiZXOVDZ8NciJzZXQARaCDInEidWFsAACghyJlAHQAAKDRIoAFSFJTYWNmaGlvcnMAtQ27Db8NyA3ODdsN3w3+DRgOHQ4jDk8AUgBOADuA3gDeQMEhREUAoCIhAAFIY8MNxg1jAHkAC2R5ACZkAAFidcwNzQ0JYKRjgAFhZXkA1A3XDdoN8iFvbmRh5CFpbGJhImRyAADgNdgX3QABZWnjDe4N8gHoDQAA7Q3lImZvcmUAoDQiYQCYYwABY27yDfkNayNTcGFjZQAA4F8gCiDTInBhY2UAoAkg7CFkZYChPCJFRlQABw4MDhMOcSJ1YWwAAKBDInUkbGxFcXVhbAAAoEUiaSJsZGUAAKBIInAAZgAA4DXYS93pI3BsZURvdACg2yAAAWN0Jw4rDnIAAOA12K/c8iFva2Zh4QpFDlYOYA5qDgAAbg5yDgAAAAAAAAAAAAB5DnwOqA6zDgAADg8RDxYPGg8AAWNySA5ODnUAdABlADuA2gDaQHIAb6CfIeMhaXIAoEkpcgDjAVsOAABdDnkADmR2AGUAbGEAAWl5Yw5oDnIAYwA7gNsA20AjZGIibGFjAHBhcgAA4DXYGN1yAGEAdgBlADuA2QDZQOEhY3JqYQABZGl/Dp8OZQByAAABQlCFDpcOAAFhcokOiw5yAF9gYQBjAAABZWuRDpMOAKDfI2UAdAAAoLUjYSVyZW50aGVzaXMAAKDdI28AbgBQoMMi7CF1cwCgjiIAAWdwqw6uDm8AbgByYWYAAOA12EzdAARBREVUYWRwc78O0g7ZDuEOBQPqDvMOBw9yInJvdwDCoZEhyA4AAMwOYQByAACgEilvJHduQXJyb3cAAKDFIW8kd25BcnJvdwAAoJUhcSV1aWxpYnJpdW0AAKBuKWUAZQBBoKUiciJyb3cAAKClIW8AdwBuAGEAcgByAG8A9wAQA2UAcgAAAUxS+Q4AD2UkZnRBcnJvdwAAoJYh6SRnaHRBcnJvdwCglyFpAGyg0gNvAG4ApWPpIW5nbmFjAHIAAOA12LDcaSJsZGUAaGFtAGwAO4DcANxAgAREYmNkZWZvc3YALQ8xDzUPNw89D3IPdg97D4AP4SFzaACgqyJhAHIAAKDrKnkAEmThIXNobKCpIgCg5ioAAWVyQQ9DDwCgwSKAAWJ0eQBJD00Paw9hAHIAAKAWIGmgFiDjIWFsAAJCTFNUWA9cD18PZg9hAHIAAKAjIukhbmV8YGUkcGFyYXRvcgAAoFgnaSJsZGUAAKBAItQkaGluU3BhY2UAoAogcgAA4DXYGd1wAGYAAOA12E3dYwByAADgNdix3GQiYXNoAACgqiKAAmNlZm9zAI4PkQ+VD5kPng/pIXJjdGHkIWdlAKDAInIAAOA12BrdcABmAADgNdhO3WMAcgAA4DXYstwAAmZpb3OqD64Prw+0D3IAAOA12BvdnmNwAGYAAOA12E/dYwByAADgNdiz3IAEQUlVYWNmb3N1AMgPyw/OD9EP2A/gD+QP6Q/uD2MAeQAvZGMAeQAHZGMAeQAuZGMAdQB0AGUAO4DdAN1AAAFpedwP3w9yAGMAdmErZHIAAOA12BzdcABmAADgNdhQ3WMAcgAA4DXYtNxtAGwAeGEABEhhY2RlZm9z/g8BEAUQDRAQEB0QIBAkEGMAeQAWZGMidXRlAHlhAAFheQkQDBDyIW9ufWEXZG8AdAB7YfIBFRAAABwQbwBXAGkAZAB0AOgAVAhhAJZjcgAAoCghcABmAACgJCFjAHIAAOA12LXc4QtCEEkQTRAAAGcQbRByEAAAAAAAAAAAeRCKEJcQ8hD9EAAAGxEhETIROREAAD4RYwB1AHQAZQA7gOEA4UByImV2ZQADYYCiPiJFZGl1eQBWEFkQWxBgEGUQAOA+IjMDAKA/InIAYwA7gOIA4kB0AGUAO4C0ALRAMGRsAGkAZwA7gOYA5kByoGEgAOA12B7dcgBhAHYAZQA7gOAA4EAAAWVwfBCGEAABZnCAEIQQ8yF5bQCgNSHoAIMQaABhALFjAAFhcI0QWwAAAWNskRCTEHIAAWFnAACgPypkApwQAAAAALEQAKInImFkc3ajEKcQqRCuEG4AZAAAoFUqAKBcKmwib3BlAACgWCoAoFoqAKMgImVsbXJzersQvRDAEN0Q5RDtEACgpCllAACgICJzAGQAYaAhImEEzhDQENIQ1BDWENgQ2hDcEACgqCkAoKkpAKCqKQCgqykAoKwpAKCtKQCgrikAoK8pdAB2oB8iYgBkoL4iAKCdKQABcHTpEOwQaAAAoCIixWDhIXJyAKB8IwABZ3D1EPgQbwBuAAVhZgAA4DXYUt0Ao0giRWFlaW9wBxEJEQ0RDxESERQRAKBwKuMhaXIAoG8qAKBKImQAAKBLInMAJ2DyIW94ZaBIIvEADhFpAG4AZwA7gOUA5UCAAWN0eQAmESoRKxFyAADgNdi23CpgbQBwAGWgSCLxAPgBaQBsAGQAZQA7gOMA40BtAGwAO4DkAORAAAFjaUERRxFvAG4AaQBuAPQA6AFuAHQAAKARKgAITmFiY2RlZmlrbG5vcHJzdWQRaBGXEZ8RpxGrEdIR1hErEjASexKKEn0RThNbE3oTbwB0AACg7SoAAWNybBGJEWsAAAJjZXBzdBF4EX0RghHvIW5nAKBMInAjc2lsb24A9mNyImltZQAAoDUgaQBtAGWgPSJxAACgzSJ2AY0RkRFlAGUAAKC9ImUAZABnoAUjZQAAoAUjcgBrAHSgtSPiIXJrAKC2IwABb3mjEaYRbgDnAHcRMWTxIXVvAKAeIIACY21wcnQAtBG5Eb4RwRHFEeEhdXPloDUi5ABwInR5dgAAoLApcwDpAH0RbgBvAPUA6gCAAWFodwDLEcwRzhGyYwCgNiHlIWVuAKBsInIAAOA12B/dZwCAA2Nvc3R1dncA4xHyEQUSEhIhEiYSKRKAAWFpdQDpEesR7xHwAKMFcgBjAACg7yVwAACgwyKAAWRwdAD4EfwRABJvAHQAAKAAKuwhdXMAoAEqaSJtZXMAAKACKnECCxIAAAAADxLjIXVwAKAGKmEAcgAAoAUm8iNpYW5nbGUAAWR1GhIeEu8hd24AoL0lcAAAoLMlcCJsdXMAAKAEKmUA5QBCD+UAkg9hInJvdwAAoA0pgAFha28ANhJoEncSAAFjbjoSZRJrAIABbHN0AEESRxJNEm8jemVuZ2UAAKDrKXEAdQBhAHIA5QBcBPIjaWFuZ2xlgKG0JWRscgBYElwSYBLvIXduAKC+JeUhZnQAoMIlaSJnaHQAAKC4JWsAAKAjJLEBbRIAAHUSsgFxEgAAcxIAoJIlAKCRJTQAAKCTJWMAawAAoIglAAFlb38ShxJx4D0A5SD1IWl2AOBhIuUgdAAAoBAjAAJwdHd4kRKVEpsSnxJmAADgNdhT3XSgpSJvAG0AAKClIvQhaWUAoMgiAAZESFVWYmRobXB0dXayEsES0RLgEvcS+xIKExoTHxMjEygTNxMAAkxSbHK5ErsSvRK/EgCgVyUAoFQlAKBWJQCgUyUAolAlRFVkdckSyxLNEs8SAKBmJQCgaSUAoGQlAKBnJQACTFJsctgS2hLcEt4SAKBdJQCgWiUAoFwlAKBZJQCjUSVITFJobHLrEu0S7xLxEvMS9RIAoGwlAKBjJQCgYCUAoGslAKBiJQCgXyVvAHgAAKDJKQACTFJscgITBBMGEwgTAKBVJQCgUiUAoBAlAKAMJQCiACVEVWR1EhMUExYTGBMAoGUlAKBoJQCgLCUAoDQlaSJudXMAAKCfIuwhdXMAoJ4iaSJtZXMAAKCgIgACTFJsci8TMRMzEzUTAKBbJQCgWCUAoBglAKAUJQCjAiVITFJobHJCE0QTRhNIE0oTTBMAoGolAKBhJQCgXiUAoDwlAKAkJQCgHCUAAWV2UhNVE3YA5QD5AGIAYQByADuApgCmQAACY2Vpb2ITZhNqE24TcgAA4DXYt9xtAGkAAKBPIG0A5aA9IogRbAAAoVwAYmh0E3YTAKDFKfMhdWIAoMgnbAF+E4QTbABloCIgdAAAoCIgcAAAoU4iRWWJE4sTAKCuKvGgTyI8BeEMqRMAAN8TABQDFB8UAAAjFDQUAAAAAIUUAAAAAI0UAAAAANcU4xT3FPsUAACIFQAAlhWAAWNwcgCuE7ET1RP1IXRlB2GAoikiYWJjZHMAuxO/E8QTzhPSE24AZAAAoEQqciJjdXAAAKBJKgABYXXIE8sTcAAAoEsqcAAAoEcqbwB0AACgQCoA4CkiAP4AAWVv2RPcE3QAAKBBIO4ABAUAAmFlaXXlE+8T9RP4E/AB6hMAAO0TcwAAoE0qbwBuAA1hZABpAGwAO4DnAOdAcgBjAAlhcABzAHOgTCptAACgUCpvAHQAC2GAAWRtbgAIFA0UEhRpAGwAO4C4ALhAcCJ0eXYAAKCyKXQAAIGiADtlGBQZFKJAcgBkAG8A9ABiAXIAAOA12CDdgAFjZWkAKBQqFDIUeQBHZGMAawBtoBMn4SFyawCgEyfHY3IAAKPLJUVjZWZtcz8UQRRHFHcUfBSAFACgwykAocYCZWxGFEkUcQAAoFciZQBhAlAUAAAAAGAUciJyb3cAAAFsclYUWhTlIWZ0AKC6IWkiZ2h0AACguyGAAlJTYWNkAGgUaRRrFG8UcxSuYACgyCRzAHQAAKCbIukhcmMAoJoi4SFzaACgnSJuImludAAAoBAqaQBkAACg7yrjIWlyAKDCKfUhYnN1oGMmaQB0AACgYybsApMUmhS2FAAAwxRvAG4AZaA6APGgVCKrAG0CnxQAAAAAoxRhAHSgLABAYAChASJmbKcUqRTuABMNZQAAAW14rhSyFOUhbnQAoAEiZQDzANIB5wG6FAAAwBRkoEUibwB0AACgbSpuAPQAzAGAAWZyeQDIFMsUzhQA4DXYVN1vAOQA1wEAgakAO3MeAdMUcgAAoBchAAFhb9oU3hRyAHIAAKC1IXMAcwAAoBcnAAFjdeYU6hRyAADgNdi43AABYnDuFPIUZaDPKgCg0SploNAqAKDSKuQhb3QAoO8igANkZWxwcnZ3AAYVEBUbFSEVRBVlFYQV4SFycgABbHIMFQ4VAKA4KQCgNSlwAhYVAAAAABkVcgAAoN4iYwAAoN8i4SFycnCgtiEAoD0pgKIqImJjZG9zACsVMBU6FT4VQRVyImNhcAAAoEgqAAFhdTQVNxVwAACgRipwAACgSipvAHQAAKCNInIAAKBFKgDgKiIA/gACYWxydksVURVuFXMVcgByAG2gtyEAoDwpeQCAAWV2dwBYFWUVaRVxAHACXxUAAAAAYxVyAGUA4wAXFXUA4wAZFWUAZQAAoM4iZSJkZ2UAAKDPImUAbgA7gKQApEBlI2Fycm93AAABbHJ7FX8V5SFmdACgtiFpImdodAAAoLchZQDkAG0VAAFjaYsVkRVvAG4AaQBuAPQAkwFuAHQAAKAxImwiY3R5AACgLSOACUFIYWJjZGVmaGlqbG9yc3R1d3oAuBW7Fb8V1RXgFegV+RUKFhUWHxZUFlcWZRbFFtsW7xb7FgUXChdyAPIAtAJhAHIAAKBlKQACZ2xyc8YVyhXOFdAV5yFlcgCgICDlIXRoAKA4IfIA9QxoAHagECAAoKMiawHZFd4VYSJyb3cAAKAPKWEA4wBfAgABYXnkFecV8iFvbg9hNGQAoUYhYW/tFfQVAAFnciEC8RVyAACgyiF0InNlcQAAoHcqgAFnbG0A/xUCFgUWO4CwALBAdABhALRjcCJ0eXYAAKCxKQABaXIOFhIW8yFodACgfykA4DXYId1hAHIAAAFschsWHRYAoMMhAKDCIYACYWVnc3YAKBauAjYWOhY+Fm0AAKHEIm9zLhY0Fm4AZABzoMQi9SFpdACgZiZhIm1tYQDdY2kAbgAAoPIiAKH3AGlvQxZRFmQAZQAAgfcAO29KFksW90BuI3RpbWVzAACgxyJuAPgAUBZjAHkAUmRjAG8CXhYAAAAAYhZyAG4AAKAeI28AcAAAoA0jgAJscHR1dwBuFnEWdRaSFp4W7CFhciRgZgAA4DXYVd0AotkCZW1wc30WhBaJFo0WcQBkoFAibwB0AACgUSJpIm51cwAAoDgi7CF1cwCgFCLxInVhcmUAoKEiYgBsAGUAYgBhAHIAdwBlAGQAZwDlANcAbgCAAWFkaAClFqoWtBZyAHIAbwD3APUMbwB3AG4AYQByAHIAbwB3APMA8xVhI3Jwb29uAAABbHK8FsAWZQBmAPQAHBZpAGcAaAD0AB4WYgHJFs8WawBhAHIAbwD3AJILbwLUFgAAAADYFnIAbgAAoB8jbwBwAACgDCOAAWNvdADhFukW7BYAAXJ55RboFgDgNdi53FVkbAAAoPYp8iFvaxFhAAFkcvMW9xZvAHQAAKDxImkA5qC/JVsSAAFhaP8WAhdyAPIANQNhAPIA1wvhIm5nbGUAoKYpAAFjaQ4XEBd5AF9k5yJyYXJyAKD/JwAJRGFjZGVmZ2xtbm9wcXJzdHV4MRc4F0YXWxcyBF4XaRd5F40XrBe0F78X2RcVGCEYLRg1GEAYAAFEbzUXgRZvAPQA+BUAAWNzPBdCF3UAdABlADuA6QDpQPQhZXIAoG4qAAJhaW95TRdQF1YXWhfyIW9uG2FyAGOgViI7gOoA6kDsIW9uAKBVIk1kbwB0ABdhAAFEcmIXZhdvAHQAAKBSIgDgNdgi3XKhmipuF3QXYQB2AGUAO4DoAOhAZKCWKm8AdAAAoJgqgKGZKmlscwCAF4UXhxfuInRlcnMAoOcjAKATIWSglSpvAHQAAKCXKoABYXBzAJMXlheiF2MAcgATYXQAeQBzogUinxcAAAAAoRdlAHQAAKAFInAAMaADIDMBqRerFwCgBCAAoAUgAAFnc7AXsRdLYXAAAKACIAABZ3C4F7sXbwBuABlhZgAA4DXYVt2AAWFscwDFF8sXzxdyAHOg1SJsAACg4yl1AHMAAKBxKmkAAKG1A2x21RfYF28AbgC1Y/VjAAJjc3V24BfoF/0XEBgAAWlv5BdWF3IAYwAAoFYiaQLuFwAAAADwF+0ADQThIW50AAFnbPUX+Rd0AHIAAKCWKuUhc3MAoJUqgAFhZWkAAxgGGAoYbABzAD1gcwB0AACgXyJ2AESgYSJEAACgeCrwImFyc2wAoOUpAAFEYRkYHRhvAHQAAKBTInIAcgAAoHEpgAFjZGkAJxgqGO0XcgAAoC8hbwD0AIwCAAFhaDEYMhi3YzuA8ADwQAABbXI5GD0YbAA7gOsA60BvAACgrCCAAWNpcABGGEgYSxhsACFgcwD0ACwEAAFlb08YVxhjAHQAYQB0AGkAbwDuABoEbgBlAG4AdABpAGEAbADlADME4Ql1GAAAgRgAAIMYiBgAAAAAoRilGAAAqhgAALsYvhjRGAAA1xgnGWwAbABpAG4AZwBkAG8AdABzAGUA8QBlF3kARGRtImFsZQAAoEAmgAFpbHIAjRiRGJ0Y7CFpZwCgA/tpApcYAAAAAJoYZwAAoAD7aQBnAACgBPsA4DXYI93sIWlnAKAB++whaWcA4GYAagCAAWFsdACvGLIYthh0AACgbSZpAGcAAKAC+24AcwAAoLElbwBmAJJh8AHCGAAAxhhmAADgNdhX3QABYWvJGMwYbADsAGsEdqDUIgCg2SphI3J0aW50AACgDSoAAWFv2hgiGQABY3PeGB8ZsQPnGP0YBRkSGRUZAAAdGbID7xjyGPQY9xj5GAAA+xg7gL0AvUAAoFMhO4C8ALxAAKBVIQCgWSEAoFshswEBGQAAAxkAoFQhAKBWIbQCCxkOGQAAAAAQGTuAvgC+QACgVyEAoFwhNQAAoFghtgEZGQAAGxkAoFohAKBdITgAAKBeIWwAAKBEIHcAbgAAoCIjYwByAADgNdi73IAIRWFiY2RlZmdpamxub3JzdHYARhlKGVoZXhlmGWkZkhmWGZkZnRmgGa0ZxhnLGc8Z4BkjGmygZyIAoIwqgAFjbXAAUBlTGVgZ9SF0ZfVhbQBhAOSgswM6FgCghipyImV2ZQAfYQABaXliGWUZcgBjAB1hM2RvAHQAIWGAoWUibHFzAMYEcBl6GfGhZSLOBAAAdhlsAGEAbgD0AN8EgKF+KmNkbACBGYQZjBljAACgqSpvAHQAb6CAKmyggioAoIQqZeDbIgD+cwAAoJQqcgAA4DXYJN3noGsirATtIWVsAKA3IWMAeQBTZIChdyJFYWoApxmpGasZAKCSKgCgpSoAoKQqAAJFYWVztBm2Gb0ZwhkAoGkicABwoIoq8iFveACgiipxoIgq8aCIKrUZaQBtAACg5yJwAGYAAOA12FjdYQB2AOUAYwIAAWNp0xnWGXIAAKAKIW0AAKFzImVs3BneGQCgjioAoJAqAIM+ADtjZGxxco0E6xn0GfgZ/BkBGgABY2nvGfEZAKCnKnIAAKB6Km8AdAAAoNci0CFhcgCglSl1ImVzdAAAoHwqgAJhZGVscwAKGvQZFhrVBCAa8AEPGgAAFBpwAHIAbwD4AFkZcgAAoHgpcQAAAWxxxAQbGmwAZQBzAPMASRlpAO0A5AQAAWVuJxouGnIjdG5lcXEAAOBpIgD+xQAsGgAFQWFiY2Vma29zeUAaQxpmGmoabRqDGocalhrCGtMacgDyAMwCAAJpbG1yShpOGlAaVBpyAHMA8ABxD2YAvWBpAGwA9AASBQABZHJYGlsaYwB5AEpkAKGUIWN3YBpkGmkAcgAAoEgpAKCtIWEAcgAAoA8h6SFyYyVhgAFhbHIAcxp7Gn8a8iF0c3WgZSZpAHQAAKBlJuwhaXAAoCYg4yFvbgCguSJyAADgNdgl3XMAAAFld4wakRphInJvdwAAoCUpYSJyb3cAAKAmKYACYW1vcHIAnxqjGqcauhq+GnIAcgAAoP8h9CFodACgOyJrAAABbHKsGrMaZSRmdGFycm93AACgqSHpJGdodGFycm93AKCqIWYAAOA12Fnd4iFhcgCgFSCAAWNsdADIGswa0BpyAADgNdi93GEAcwDoAGka8iFvaydhAAFicNca2xr1IWxsAKBDIOghZW4AoBAg4Qr2GgAA/RoAAAgbExsaGwAAIRs7GwAAAAA+G2IbmRuVG6sbAACyG80b0htjAHUAdABlADuA7QDtQAChYyBpeQEbBhtyAGMAO4DuAO5AOGQAAWN4CxsNG3kANWRjAGwAO4ChAKFAAAFmcssCFhsA4DXYJt1yAGEAdgBlADuA7ADsQIChSCFpbm8AJxsyGzYbAAFpbisbLxtuAHQAAKAMKnQAAKAtIuYhaW4AoNwpdABhAACgKSHsIWlnM2GAAWFvcABDG1sbXhuAAWNndABJG0sbWRtyACthgAFlbHAAcQVRG1UbaQBuAOUAyAVhAHIA9AByBWgAMWFmAACgtyJlAGQAtWEAoggiY2ZvdGkbbRt1G3kb4SFyZQCgBSFpAG4AdKAeImkAZQAAoN0pZABvAPQAWxsAoisiY2VscIEbhRuPG5QbYQBsAACguiIAAWdyiRuNG2UAcgDzACMQ4wCCG2EicmhrAACgFyryIW9kAKA8KgACY2dwdJ8boRukG6gbeQBRZG8AbgAvYWYAAOA12FrdYQC5Y3UAZQBzAHQAO4C/AL9AAAFjabUbuRtyAADgNdi+3G4AAKIIIkVkc3bCG8QbyBvQAwCg+SJvAHQAAKD1Inag9CIAoPMiaaBiIOwhZGUpYesB1hsAANkbYwB5AFZkbAA7gO8A70AAA2NmbW9zdeYb7hvyG/Ub+hsFHAABaXnqG+0bcgBjADVhOWRyAADgNdgn3eEhdGg3YnAAZgAA4DXYW93jAf8bAAADHHIAAOA12L/c8iFjeVhk6yFjeVRkAARhY2ZnaGpvcxUcGhwiHCYcKhwtHDAcNRzwIXBhdqC6A/BjAAFleR4cIRzkIWlsN2E6ZHIAAOA12CjdciJlZW4AOGFjAHkARWRjAHkAXGRwAGYAAOA12FzdYwByAADgNdjA3IALQUJFSGFiY2RlZmdoamxtbm9wcnN0dXYAXhxtHHEcdRx5HN8cBx0dHTwd3B3tHfEdAR4EHh0eLB5FHrwewx7hHgkfPR9LH4ABYXJ0AGQcZxxpHHIA8gBvB/IAxQLhIWlsAKAbKeEhcnIAoA4pZ6BmIgCgiyphAHIAAKBiKWMJjRwAAJAcAACVHAAAAAAAAAAAAACZHJwcAACmHKgcrRwAANIc9SF0ZTph7SJwdHl2AKC0KXIAYQDuAFoG4iFkYbtjZwAAoegnZGyhHKMcAKCRKeUAiwYAoIUqdQBvADuAqwCrQHIAgKOQIWJmaGxwc3QAuhy/HMIcxBzHHMoczhxmoOQhcwAAoB8pcwAAoB0p6wCyGnAAAKCrIWwAAKA5KWkAbQAAoHMpbAAAoKIhAKGrKmFl1hzaHGkAbAAAoBkpc6CtKgDgrSoA/oABYWJyAOUc6RztHHIAcgAAoAwpcgBrAACgcicAAWFr8Rz4HGMAAAFla/Yc9xx7YFtgAAFlc/wc/hwAoIspbAAAAWR1Ax0FHQCgjykAoI0pAAJhZXV5Dh0RHRodHB3yIW9uPmEAAWRpFR0YHWkAbAA8YewAowbiAPccO2QAAmNxcnMkHScdLB05HWEAAKA2KXUAbwDyoBwgqhEAAWR1MB00HeghYXIAoGcpcyJoYXIAAKBLKWgAAKCyIQCiZCJmZ3FzRB1FB5Qdnh10AIACYWhscnQATh1WHWUdbB2NHXIicm93AHSgkCFhAOkAzxxhI3Jwb29uAAABZHVeHWId7yF3bgCgvSFwAACgvCHlJGZ0YXJyb3dzAKDHIWkiZ2h0AIABYWhzAHUdex2DHXIicm93APOglCGdBmEAcgBwAG8AbwBuAPMAzgtxAHUAaQBnAGEAcgByAG8A9wBlGugkcmVldGltZXMAoMsi8aFkIk0HAACaHWwAYQBuAPQAXgcAon0qY2Rnc6YdqR2xHbcdYwAAoKgqbwB0AG+gfypyoIEqAKCDKmXg2iIA/nMAAKCTKoACYWRlZ3MAwB3GHcod1h3ZHXAAcAByAG8A+ACmHG8AdAAAoNYicQAAAWdxzx3SHXQA8gBGB2cAdADyAHQcdADyAFMHaQDtAGMHgAFpbHIA4h3mHeod8yFodACgfClvAG8A8gDKBgDgNdgp3UWgdiIAoJEqYQH1Hf4dcgAAAWR1YB35HWygvCEAoGopbABrAACghCVjAHkAWWQAomoiYWNodAweDx4VHhkecgDyAGsdbwByAG4AZQDyAGAW4SFyZACgaylyAGkAAKD6JQABaW8hHiQe5CFvdEBh9SFzdGGgsCPjIWhlAKCwIwACRWFlczMeNR48HkEeAKBoInAAcKCJKvIhb3gAoIkqcaCHKvGghyo0HmkAbQAAoOYiAARhYm5vcHR3elIeXB5fHoUelh6mHqsetB4AAW5yVh5ZHmcAAKDsJ3IAAKD9IXIA6wCwBmcAgAFsbXIAZh52Hnse5SFmdAABYXKIB2weaQBnAGgAdABhAHIAcgBvAPcAkwfhInBzdG8AoPwnaQBnAGgAdABhAHIAcgBvAPcAmgdwI2Fycm93AAABbHKNHpEeZQBmAPQAxhxpImdodAAAoKwhgAFhZmwAnB6fHqIecgAAoIUpAOA12F3ddQBzAACgLSppIm1lcwAAoDQqYQGvHrMecwB0AACgFyLhAIoOZaHKJbkeRhLuIWdlAKDKJWEAcgBsoCgAdAAAoJMpgAJhY2htdADMHs8e1R7bHt0ecgDyAJ0GbwByAG4AZQDyANYWYQByAGSgyyEAoG0pAKAOIHIAaQAAoL8iAANhY2hpcXTrHu8e1QfzHv0eBh/xIXVvAKA5IHIAAOA12MHcbQDloXIi+h4AAPweAKCNKgCgjyoAAWJ19xwBH28AcqAYIACgGiDyIW9rQmEAhDwAO2NkaGlscXJCBhcfxh0gHyQfKB8sHzEfAAFjaRsfHR8AoKYqcgAAoHkqcgBlAOUAkx3tIWVzAKDJIuEhcnIAoHYpdSJlc3QAAKB7KgABUGk1HzkfYQByAACglillocMlAgdfEnIAAAFkdUIfRx9zImhhcgAAoEop6CFhcgCgZikAAWVuTx9WH3IjdG5lcXEAAOBoIgD+xQBUHwAHRGFjZGVmaGlsbm9wc3VuH3Ifoh+rH68ftx+7H74f5h/uH/MfBwj/HwsgxCFvdACgOiIAAmNscHJ5H30fiR+eH3IAO4CvAK9AAAFldIEfgx8AoEImZaAgJ3MAZQAAoCAnc6CmIXQAbwCAoaYhZGx1AJQfmB+cH28AdwDuAHkDZQBmAPQA6gbwAOkO6yFlcgCgriUAAW95ph+qH+0hbWEAoCkqPGThIXNoAKAUIOElc3VyZWRhbmdsZQCgISJyAADgNdgq3W8AAKAnIYABY2RuAMQfyR/bH3IAbwA7gLUAtUBhoiMi0B8AANMf1x9zAPQAKxFpAHIAAKDwKm8AdAA7gLcAt0B1AHMA4qESIh4TAADjH3WgOCIAoCoqYwHqH+0fcAAAoNsq8gB+GnAAbAB1APMACAgAAWRw9x/7H+UhbHMAoKciZgAA4DXYXt0AAWN0AyAHIHIAAOA12MLc8CFvcwCgPiJsobwDECAVIPQiaW1hcACguCJhAPAAEyAADEdMUlZhYmNkZWZnaGlqbG1vcHJzdHV2dzwgRyBmIG0geSCqILgg2iDeIBEhFSEyIUMhTSFQIZwhnyHSIQAiIyKLIrEivyIUIwABZ3RAIEMgAODZIjgD9uBrItIgBwmAAWVsdABNIF8gYiBmAHQAAAFhclMgWCByInJvdwAAoM0h6SRnaHRhcnJvdwCgziEA4NgiOAP24Goi0iBfCekkZ2h0YXJyb3cAoM8hAAFEZHEgdSDhIXNoAKCvIuEhc2gAoK4igAJiY25wdACCIIYgiSCNIKIgbABhAACgByL1IXRlRGFnAADgICLSIACiSSJFaW9wlSCYIJwgniAA4HAqOANkAADgSyI4A3MASWFyAG8A+AAyCnUAcgBhoG4mbADzoG4mmwjzAa8gAACzIHAAO4CgAKBAbQBwAOXgTiI4AyoJgAJhZW91eQDBIMogzSDWINkg8AHGIAAAyCAAoEMqbwBuAEhh5CFpbEZhbgBnAGSgRyJvAHQAAOBtKjgDcAAAoEIqPWThIXNoAKATIACjYCJBYWRxc3jpIO0g+SD+IAIhDCFyAHIAAKDXIXIAAAFocvIg9SBrAACgJClvoJch9wAGD28AdAAA4FAiOAN1AGkA9gC7CAABZWkGIQohYQByAACgKCntAN8I6SFzdPOgBCLlCHIAAOA12CvdAAJFZXN0/wgcISshLiHxoXEiIiEAABMJ8aFxIgAJAAAnIWwAYQBuAPQAEwlpAO0AGQlyoG8iAKBvIoABQWFwADghOyE/IXIA8gBeIHIAcgAAoK4hYQByAACg8ipzogsiSiEAAAAAxwtkoPwiAKD6ImMAeQBaZIADQUVhZGVzdABcIV8hYiFmIWkhkyGWIXIA8gBXIADgZiI4A3IAcgAAoJohcgAAoCUggKFwImZxcwBwIYQhjiF0AAABYXJ1IXohcgByAG8A9wBlIWkAZwBoAHQAYQByAHIAbwD3AD4h8aFwImAhAACKIWwAYQBuAPQAZwlz4H0qOAMAoG4iaQDtAG0JcqBuImkA5aDqIkUJaQDkADoKAAFwdKMhpyFmAADgNdhf3YCBrAA7aW4AriGvIcchrEBuAIChCSJFZHYAtyG6Ib8hAOD5IjgDbwB0AADg9SI4A+EB1gjEIcYhAKD3IgCg9iJpAHagDCLhAagJzyHRIQCg/iIAoP0igAFhb3IA2CHsIfEhcgCAoSYiYXN0AOAh5SHpIWwAbABlAOwAywhsAADg/SrlIADgAiI4A2wiaW50AACgFCrjoYAi9yEAAPohdQDlAJsJY+CvKjgDZaCAIvEAkwkAAkFhaXQHIgoiFyIeInIA8gBsIHIAcgAAoZshY3cRIhQiAOAzKTgDAOCdITgDZyRodGFycm93AACgmyFyAGkA5aDrIr4JgANjaGltcHF1AC8iPCJHIpwhTSJQIloigKGBImNlcgA2Iv0JOSJ1AOUABgoA4DXYw9zvIXJ0bQKdIQAAAABEImEAcgDhAOEhbQBloEEi8aBEIiYKYQDyAMsIcwB1AAABYnBWIlgi5QDUCeUA3wmAAWJjcABgInMieCKAoYQiRWVzAGci7glqIgDgxSo4A2UAdABl4IIi0iBxAPGgiCJoImMAZaCBIvEA/gmAoYUiRWVzAH8iFgqCIgDgxio4A2UAdABl4IMi0iBxAPGgiSKAIgACZ2lscpIilCKaIpwi7AAMCWwAZABlADuA8QDxQOcAWwlpI2FuZ2xlAAABbHKkIqoi5SFmdGWg6iLxAEUJaSJnaHQAZaDrIvEAvgltoL0DAKEjAGVzuCK8InIAbwAAoBYhcAAAoAcggARESGFkZ2lscnMAziLSItYi2iLeIugi7SICIw8j4SFzaACgrSLhIXJyAKAEKXAAAOBNItIg4SFzaACgrCIAAWV04iLlIgDgZSLSIADgPgDSIG4iZmluAACg3imAAUFldADzIvci+iJyAHIAAKACKQDgZCLSIHLgPADSIGkAZQAA4LQi0iAAAUF0BiMKI3IAcgAAoAMp8iFpZQDgtSLSIGkAbQAA4Dwi0iCAAUFhbgAaIx4jKiNyAHIAAKDWIXIAAAFociMjJiNrAACgIylvoJYh9wD/DuUhYXIAoCcpUxJqFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVCMAAF4jaSN/I4IjjSOeI8AUAAAAAKYjwCMAANoj3yMAAO8jHiQvJD8kRCQAAWNzVyNsFHUAdABlADuA8wDzQAABaXlhI2cjcgBjoJoiO4D0APRAPmSAAmFiaW9zAHEjdCN3I3EBeiNzAOgAdhTsIWFjUWF2AACgOCrvIWxkAKC8KewhaWdTYQABY3KFI4kjaQByAACgvykA4DXYLN1vA5QjAAAAAJYjAACcI24A22JhAHYAZQA7gPIA8kAAoMEpAAFibaEjjAphAHIAAKC1KQACYWNpdKwjryO6I70jcgDyAFkUAAFpcrMjtiNyAACgvinvIXNzAKC7KW4A5QDZCgCgwCmAAWFlaQDFI8gjyyNjAHIATWFnAGEAyWOAAWNkbgDRI9Qj1iPyIW9uv2MAoLYpdQDzAHgBcABmAADgNdhg3YABYWVsAOQj5yPrI3IAAKC3KXIAcAAAoLkpdQDzAHwBAKMoImFkaW9zdvkj/CMPJBMkFiQbJHIA8gBeFIChXSplZm0AAyQJJAwkcgBvoDQhZgAAoDQhO4CqAKpAO4C6ALpA5yFvZgCgtiJyAACgVipsIm9wZQAAoFcqAKBbKoABY2xvACMkJSQrJPIACCRhAHMAaAA7gPgA+EBsAACgmCJpAGwBMyQ4JGQAZQA7gPUA9UBlAHMAYaCXInMAAKA2Km0AbAA7gPYA9kDiIWFyAKA9I+EKXiQAAHokAAB8JJQkAACYJKkkAAAAALUkEQsAAPAkAAAAAAQleiUAAIMlcgCAoSUiYXN0AGUkbyQBCwCBtgA7bGokayS2QGwAZQDsABgDaQJ1JAAAAAB4JG0AAKDzKgCg/Sp5AD9kcgCAAmNpbXB0AIUkiCSLJJkSjyRuAHQAJWBvAGQALmBpAGwAAKAwIOUhbmsAoDEgcgAA4DXYLd2AAWltbwCdJKAkpCR2oMYD1WNtAGEA9AD+B24AZQAAoA4m9KHAA64kAAC0JGMjaGZvcmsAAKDUItZjAAFhdbgkxCRuAAABY2u9JMIkawBooA8hAKAOIfYAaRpzAACkKwBhYmNkZW1zdNMkIRPXJNsk4STjJOck6yTjIWlyAKAjKmkAcgAAoCIqAAFvdYsW3yQAoCUqAKByKm4AO4CxALFAaQBtAACgJip3AG8AAKAnKoABaXB1APUk+iT+JO4idGludACgFSpmAADgNdhh3W4AZAA7gKMAo0CApHoiRWFjZWlub3N1ABMlFSUYJRslTCVRJVklSSV1JQCgsypwAACgtyp1AOUAPwtjoK8qgKJ6ImFjZW5zACclLSU0JTYlSSVwAHAAcgBvAPgAFyV1AHIAbAB5AGUA8QA/C/EAOAuAAWFlcwA8JUElRSXwInByb3gAoLkqcQBxAACgtSppAG0AAKDoImkA7QBEC20AZQDzoDIgIguAAUVhcwBDJVclRSXwAEAlgAFkZnAATwtfJXElgAFhbHMAZSVpJW0l7CFhcgCgLiPpIW5lAKASI/UhcmYAoBMjdKAdIu8AWQvyIWVsAKCwIgABY2l9JYElcgAA4DXYxdzIY24iY3NwAACgCCAAA2Zpb3BzdZElKxuVJZolnyWkJXIAAOA12C7dcABmAADgNdhi3XIiaW1lAACgVyBjAHIAAOA12MbcgAFhZW8AqiW6JcAldAAAAWVpryW2JXIAbgBpAG8AbgDzABkFbgB0AACgFipzAHQAZaA/APEACRj0AG0LgApBQkhhYmNkZWZoaWxtbm9wcnN0dXgA4yXyJfYl+iVpJpAmpia9JtUm5ib4JlonaCdxJ3UnnietJ7EnyCfiJ+cngAFhcnQA6SXsJe4lcgDyAJkM8gD6AuEhaWwAoBwpYQByAPIA3BVhAHIAAKBkKYADY2RlbnFydAAGJhAmEyYYJiYmKyZaJgABZXUKJg0mAOA9IjEDdABlAFVhaQDjACAN7SJwdHl2AKCzKWcAgKHpJ2RlbAAgJiImJCYAoJIpAKClKeUA9wt1AG8AO4C7ALtAcgAApZIhYWJjZmhscHN0dz0mQCZFJkcmSiZMJk4mUSZVJlgmcAAAoHUpZqDlIXMAAKAgKQCgMylzAACgHinrALka8ACVHmwAAKBFKWkAbQAAoHQpbAAAoKMhAKCdIQABYWleJmImaQBsAACgGilvAG6gNiJhAGwA8wB2C4ABYWJyAG8mciZ2JnIA8gAvEnIAawAAoHMnAAFha3omgSZjAAABZWt/JoAmfWBdYAABZXOFJocmAKCMKWwAAAFkdYwmjiYAoI4pAKCQKQACYWV1eZcmmiajJqUm8iFvbllhAAFkaZ4moSZpAGwAV2HsAA8M4gCAJkBkAAJjbHFzrSawJrUmuiZhAACgNylkImhhcgAAoGkpdQBvAPKgHSCjAWgAAKCzIYABYWNnAMMm0iaUC2wAgKEcIWlwcwDLJs4migxuAOUAoAxhAHIA9ADaC3QAAKCtJYABaWxyANsm3ybjJvMhaHQAoH0pbwBvAPIANgwA4DXYL90AAWFv6ib1JnIAAAFkde8m8SYAoMEhbKDAIQCgbCl2oMED8WOAAWducwD+Jk4nUCdoAHQAAANhaGxyc3QKJxInISc1Jz0nRydyInJvdwB0oJIhYQDpAFYmYSNycG9vbgAAAWR1GiceJ28AdwDuAPAmcAAAoMAh5SFmdAABYWgnJy0ncgByAG8AdwDzAAkMYQByAHAAbwBvAG4A8wATBGklZ2h0YXJyb3dzAACgySFxAHUAaQBnAGEAcgByAG8A9wBZJugkcmVldGltZXMAoMwiZwDaYmkAbgBnAGQAbwB0AHMAZQDxABwYgAFhaG0AYCdjJ2YncgDyAAkMYQDyABMEAKAPIG8idXN0AGGgsSPjIWhlAKCxI+0haWQAoO4qAAJhYnB0fCeGJ4knmScAAW5ygCeDJ2cAAKDtJ3IAAKD+IXIA6wAcDIABYWZsAI8nkieVJ3IAAKCGKQDgNdhj3XUAcwAAoC4qaSJtZXMAAKA1KgABYXCiJ6gncgBnoCkAdAAAoJQp7yJsaW50AKASKmEAcgDyADwnAAJhY2hxuCe8J6EMwCfxIXVvAKA6IHIAAOA12MfcAAFidYAmxCdvAPKgGSCoAYABaGlyAM4n0ifWJ3IAZQDlAE0n7SFlcwCgyiJpAIChuSVlZmwAXAxjEt4n9CFyaQCgzinsInVoYXIAoGgpAKAeIWENBSgJKA0oSyhVKIYoAACLKLAoAAAAAOMo5ygAABApJCkxKW0pcSmHKaYpAACYKgAAAACxKmMidXRlAFthcQB1AO8ABR+ApHsiRWFjZWlucHN5ABwoHignKCooLygyKEEoRihJKACgtCrwASMoAAAlKACguCpvAG4AYWF1AOUAgw1koLAqaQBsAF9hcgBjAF1hgAFFYXMAOCg6KD0oAKC2KnAAAKC6KmkAbQAAoOki7yJsaW50AKATKmkA7QCIDUFkbwB0AGKixSKRFgAAAABTKACgZiqAA0FhY21zdHgAYChkKG8ocyh1KHkogihyAHIAAKDYIXIAAAFocmkoayjrAJAab6CYIfcAzAd0ADuApwCnQGkAO2D3IWFyAKApKW0AAAFpbn4ozQBuAHUA8wDOAHQAAKA2J3IA7+A12DDdIxkAAmFjb3mRKJUonSisKHIAcAAAoG8mAAFoeZkonChjAHkASWRIZHIAdABtAqUoAAAAAKgoaQDkAFsPYQByAGEA7ABsJDuArQCtQAABZ22zKLsobQBhAAChwwNmdroouijCY4CjPCJkZWdsbnByAMgozCjPKNMo1yjaKN4obwB0AACgairxoEMiCw5FoJ4qAKCgKkWgnSoAoJ8qZQAAoEYi7CF1cwCgJCrhIXJyAKByKWEAcgDyAPwMAAJhZWl07Sj8KAEpCCkAAWxz8Sj4KGwAcwBlAHQAbQDpAH8oaABwAACgMyrwImFyc2wAoOQpAAFkbFoPBSllAACgIyNloKoqc6CsKgDgrCoA/oABZmxwABUpGCkfKfQhY3lMZGKgLwBhoMQpcgAAoD8jZgAA4DXYZN1hAAABZHIoKRcDZQBzAHWgYCZpAHQAAKBgJoABY3N1ADYpRilhKQABYXU6KUApcABzoJMiAOCTIgD+cABzoJQiAOCUIgD+dQAAAWJwSylWKQChjyJlcz4NUCllAHQAZaCPIvEAPw0AoZAiZXNIDVspZQB0AGWgkCLxAEkNAKGhJWFmZilbBHIAZQFrKVwEAKChJWEAcgDyAAMNAAJjZW10dyl7KX8pgilyAADgNdjI3HQAbQDuAM4AaQDsAAYpYQByAOYAVw0AAWFyiimOKXIA5qAGJhESAAFhbpIpoylpImdodAAAAWVwmSmgKXAAcwBpAGwAbwDuANkXaADpAKAkcwCvYIACYmNtbnAArin8KY4NJSooKgCkgiJFZGVtbnByc7wpvinCKcgpzCnUKdgp3CkAoMUqbwB0AACgvSpkoIYibwB0AACgwyr1IWx0AKDBKgABRWXQKdIpAKDLKgCgiiLsIXVzAKC/KuEhcnIAoHkpgAFlaXUA4inxKfQpdAAAoYIiZW7oKewpcQDxoIYivSllAHEA8aCKItEpbQAAoMcqAAFicPgp+ikAoNUqAKDTKmMAgKJ7ImFjZW5zAAcqDSoUKhYqRihwAHAAcgBvAPgAIyh1AHIAbAB5AGUA8QCDDfEAfA2AAWFlcwAcKiIqPShwAHAAcgBvAPgAPChxAPEAOShnAACgaiYApoMiMTIzRWRlaGxtbnBzPCo/KkIqRSpHKlIqWCpjKmcqaypzKncqO4C5ALlAO4CyALJAO4CzALNAAKDGKgABb3NLKk4qdAAAoL4qdQBiAACg2CpkoIcibwB0AACgxCpzAAABb3VdKmAqbAAAoMknYgAAoNcq4SFycgCgeyn1IWx0AKDCKgABRWVvKnEqAKDMKgCgiyLsIXVzAKDAKoABZWl1AH0qjCqPKnQAAKGDImVugyqHKnEA8aCHIkYqZQBxAPGgiyJwKm0AAKDIKgABYnCTKpUqAKDUKgCg1iqAAUFhbgCdKqEqrCpyAHIAAKDZIXIAAAFocqYqqCrrAJUab6CZIfcAxQf3IWFyAKAqKWwAaQBnADuA3wDfQOELzyrZKtwq6SrsKvEqAAD1KjQrAAAAAAAAAAAAAEwrbCsAAHErvSsAAAAAAADRK3IC1CoAAAAA2CrnIWV0AKAWI8RjcgDrAOUKgAFhZXkA4SrkKucq8iFvbmVh5CFpbGNhQmRvAPQAIg5sInJlYwAAoBUjcgAA4DXYMd0AAmVpa2/7KhIrKCsuK/IBACsAAAkrZQAAATRm6g0EK28AcgDlAOsNYQBzorgDECsAAAAAEit5AG0A0WMAAWNuFislK2sAAAFhcxsrIStwAHAAcgBvAPgAFw5pAG0AAKA8InMA8AD9DQABYXMsKyEr8AAXDnIAbgA7gP4A/kDsATgrOyswG2QA5QBnAmUAcwCAgdcAO2JkAEMrRCtJK9dAYaCgInIAAKAxKgCgMCqAAWVwcwBRK1MraSvhAAkh4qKkIlsrXysAAAAAYytvAHQAAKA2I2kAcgAAoPEqb+A12GXdcgBrAACg2irhAHgociJpbWUAAKA0IIABYWlwAHYreSu3K2QA5QC+DYADYWRlbXBzdACFK6MrmiunK6wrsCuzK24iZ2xlAACitSVkbHFykCuUK5ornCvvIXduAKC/JeUhZnRloMMl8QACBwCgXCJpImdodABloLkl8QBdDG8AdAAAoOwlaSJudXMAAKA6KuwhdXMAoDkqYgAAoM0p6SFtZQCgOyrlInppdW0AoOIjgAFjaHQAwivKK80rAAFyecYrySsA4DXYydxGZGMAeQBbZPIhb2tnYQABaW/UK9creAD0ANERaCJlYWQAAAFsct4r5ytlAGYAdABhAHIAcgBvAPcAXQbpJGdodGFycm93AKCgIQAJQUhhYmNkZmdobG1vcHJzdHV3CiwNLBEsHSwnLDEsQCxLLFIsYix6LIQsjyzLLOgs7Sz/LAotcgDyAAkDYQByAACgYykAAWNyFSwbLHUAdABlADuA+gD6QPIACQ1yAOMBIywAACUseQBeZHYAZQBtYQABaXkrLDAscgBjADuA+wD7QENkgAFhYmgANyw6LD0scgDyANEO7CFhY3FhYQDyAOAOAAFpckQsSCzzIWh0AKB+KQDgNdgy3XIAYQB2AGUAO4D5APlAYQFWLF8scgAAAWxyWixcLACgvyEAoL4hbABrAACggCUAAWN0Zix2LG8CbCwAAAAAcyxyAG4AZaAcI3IAAKAcI28AcAAAoA8jcgBpAACg+CUAAWFsfiyBLGMAcgBrYTuAqACoQAABZ3CILIssbwBuAHNhZgAA4DXYZt0AA2FkaGxzdZksniynLLgsuyzFLHIAcgBvAPcACQ1vAHcAbgBhAHIAcgBvAPcA2A5hI3Jwb29uAAABbHKvLLMsZQBmAPQAWyxpAGcAaAD0AF0sdQDzAKYOaQAAocUDaGzBLMIs0mNvAG4AxWPwI2Fycm93cwCgyCGAAWNpdADRLOEs5CxvAtcsAAAAAN4scgBuAGWgHSNyAACgHSNvAHAAAKAOI24AZwBvYXIAaQAAoPklYwByAADgNdjK3IABZGlyAPMs9yz6LG8AdAAAoPAi7CFkZWlhaQBmoLUlAKC0JQABYW0DLQYtcgDyAMosbAA7gPwA/EDhIm5nbGUAoKcpgAdBQkRhY2RlZmxub3Byc3oAJy0qLTAtNC2bLZ0toS2/LcMtxy3TLdgt3C3gLfwtcgDyABADYQByAHag6CoAoOkqYQBzAOgA/gIAAW5yOC08LechcnQAoJwpgANla25wcnN0AJkpSC1NLVQtXi1iLYItYQBwAHAA4QAaHG8AdABoAGkAbgDnAKEXgAFoaXIAoSmzJFotbwBwAPQAdCVooJUh7wD4JgABaXVmLWotZwBtAOEAuygAAWJwbi14LXMjZXRuZXEAceCKIgD+AODLKgD+cyNldG5lcQBx4IsiAP4A4MwqAP4AAWhyhi2KLWUAdADhABIraSNhbmdsZQAAAWxyki2WLeUhZnQAoLIiaSJnaHQAAKCzInkAMmThIXNoAKCiIoABZWxyAKcttC24LWKiKCKuLQAAAACyLWEAcgAAoLsicQAAoFoi7CFpcACg7iIAAWJ0vC1eD2EA8gBfD3IAAOA12DPddAByAOkAlS1zAHUAAAFicM0t0C0A4IIi0iAA4IMi0iBwAGYAAOA12GfdcgBvAPAAWQt0AHIA6QCaLQABY3XkLegtcgAA4DXYy9wAAWJw7C30LW4AAAFFZXUt8S0A4IoiAP5uAAABRWV/LfktAOCLIgD+6SJnemFnAKCaKYADY2Vmb3BycwANLhAuJS4pLiMuLi40LukhcmN1YQABZGkULiEuAAFiZxguHC5hAHIAAKBfKmUAcaAnIgCgWSLlIXJwAKAYIXIAAOA12DTdcABmAADgNdho3WWgQCJhAHQA6ABqD2MAcgAA4DXYzNzjCuQRUC4AAFQuAABYLmIuAAAAAGMubS5wLnQuAAAAAIguki4AAJouJxIqEnQAcgDpAB0ScgAA4DXYNd0AAUFhWy5eLnIA8gDnAnIA8gCTB75jAAFBYWYuaS5yAPIA4AJyAPIAjAdhAPAAeh5pAHMAAKD7IoABZHB0APgReS6DLgABZmx9LoAuAOA12GnddQDzAP8RaQBtAOUABBIAAUFhiy6OLnIA8gDuAnIA8gCaBwABY3GVLgoScgAA4DXYzdwAAXB0nS6hLmwAdQDzACUScgDpACASAARhY2VmaW9zdbEuvC7ELsguzC7PLtQu2S5jAAABdXm2LrsudABlADuA/QD9QE9kAAFpecAuwy5yAGMAd2FLZG4AO4ClAKVAcgAA4DXYNt1jAHkAV2RwAGYAAOA12GrdYwByAADgNdjO3AABY23dLt8ueQBOZGwAO4D/AP9AAAVhY2RlZmhpb3N38y73Lv8uAi8MLxAvEy8YLx0vIi9jInV0ZQB6YQABYXn7Lv4u8iFvbn5hN2RvAHQAfGEAAWV0Bi8KL3QAcgDmAB8QYQC2Y3IAAOA12DfdYwB5ADZk5yJyYXJyAKDdIXAAZgAA4DXYa91jAHIAAOA12M/cAAFqbiYvKC8AoA0gagAAoAwg");
  2500. /**
  2501. * Bit flags & masks for the binary trie encoding used for entity decoding.
  2502. *
  2503. * Bit layout (16 bits total):
  2504. * 15..14 VALUE_LENGTH (+1 encoding; 0 => no value)
  2505. * 13 FLAG13. If valueLength>0: semicolon required flag (implicit ';').
  2506. * If valueLength==0: compact run flag.
  2507. * 12..7 BRANCH_LENGTH Branch length (0 => single branch in 6..0 if jumpOffset==char) OR run length (when compact run)
  2508. * 6..0 JUMP_TABLE Jump offset (jump table) OR single-branch char code OR first run char
  2509. */
  2510. var BinTrieFlags;
  2511. (function (BinTrieFlags) {
  2512. BinTrieFlags[BinTrieFlags["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH";
  2513. BinTrieFlags[BinTrieFlags["FLAG13"] = 8192] = "FLAG13";
  2514. BinTrieFlags[BinTrieFlags["BRANCH_LENGTH"] = 8064] = "BRANCH_LENGTH";
  2515. BinTrieFlags[BinTrieFlags["JUMP_TABLE"] = 127] = "JUMP_TABLE";
  2516. })(BinTrieFlags || (BinTrieFlags = {}));
  2517. var CharCodes;
  2518. (function (CharCodes) {
  2519. CharCodes[CharCodes["NUM"] = 35] = "NUM";
  2520. CharCodes[CharCodes["SEMI"] = 59] = "SEMI";
  2521. CharCodes[CharCodes["EQUALS"] = 61] = "EQUALS";
  2522. CharCodes[CharCodes["ZERO"] = 48] = "ZERO";
  2523. CharCodes[CharCodes["NINE"] = 57] = "NINE";
  2524. CharCodes[CharCodes["LOWER_A"] = 97] = "LOWER_A";
  2525. CharCodes[CharCodes["LOWER_F"] = 102] = "LOWER_F";
  2526. CharCodes[CharCodes["LOWER_X"] = 120] = "LOWER_X";
  2527. CharCodes[CharCodes["LOWER_Z"] = 122] = "LOWER_Z";
  2528. CharCodes[CharCodes["UPPER_A"] = 65] = "UPPER_A";
  2529. CharCodes[CharCodes["UPPER_F"] = 70] = "UPPER_F";
  2530. CharCodes[CharCodes["UPPER_Z"] = 90] = "UPPER_Z";
  2531. })(CharCodes || (CharCodes = {}));
  2532. /** Bit that needs to be set to convert an upper case ASCII character to lower case */
  2533. const TO_LOWER_BIT = 32;
  2534. function isNumber$1(code) {
  2535. return code >= CharCodes.ZERO && code <= CharCodes.NINE;
  2536. }
  2537. function isHexadecimalCharacter(code) {
  2538. return ((code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_F) ||
  2539. (code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_F));
  2540. }
  2541. function isAsciiAlphaNumeric(code) {
  2542. return ((code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_Z) ||
  2543. (code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_Z) ||
  2544. isNumber$1(code));
  2545. }
  2546. /**
  2547. * Checks if the given character is a valid end character for an entity in an attribute.
  2548. *
  2549. * Attribute values that aren't terminated properly aren't parsed, and shouldn't lead to a parser error.
  2550. * See the example in https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state
  2551. */
  2552. function isEntityInAttributeInvalidEnd(code) {
  2553. return code === CharCodes.EQUALS || isAsciiAlphaNumeric(code);
  2554. }
  2555. var EntityDecoderState;
  2556. (function (EntityDecoderState) {
  2557. EntityDecoderState[EntityDecoderState["EntityStart"] = 0] = "EntityStart";
  2558. EntityDecoderState[EntityDecoderState["NumericStart"] = 1] = "NumericStart";
  2559. EntityDecoderState[EntityDecoderState["NumericDecimal"] = 2] = "NumericDecimal";
  2560. EntityDecoderState[EntityDecoderState["NumericHex"] = 3] = "NumericHex";
  2561. EntityDecoderState[EntityDecoderState["NamedEntity"] = 4] = "NamedEntity";
  2562. })(EntityDecoderState || (EntityDecoderState = {}));
  2563. var DecodingMode;
  2564. (function (DecodingMode) {
  2565. /** Entities in text nodes that can end with any character. */
  2566. DecodingMode[DecodingMode["Legacy"] = 0] = "Legacy";
  2567. /** Only allow entities terminated with a semicolon. */
  2568. DecodingMode[DecodingMode["Strict"] = 1] = "Strict";
  2569. /** Entities in attributes have limitations on ending characters. */
  2570. DecodingMode[DecodingMode["Attribute"] = 2] = "Attribute";
  2571. })(DecodingMode || (DecodingMode = {}));
  2572. /**
  2573. * Token decoder with support of writing partial entities.
  2574. */
  2575. class EntityDecoder {
  2576. constructor(
  2577. /** The tree used to decode entities. */
  2578. // biome-ignore lint/correctness/noUnusedPrivateClassMembers: False positive
  2579. decodeTree,
  2580. /**
  2581. * The function that is called when a codepoint is decoded.
  2582. *
  2583. * For multi-byte named entities, this will be called multiple times,
  2584. * with the second codepoint, and the same `consumed` value.
  2585. *
  2586. * @param codepoint The decoded codepoint.
  2587. * @param consumed The number of bytes consumed by the decoder.
  2588. */
  2589. emitCodePoint,
  2590. /** An object that is used to produce errors. */
  2591. errors) {
  2592. this.decodeTree = decodeTree;
  2593. this.emitCodePoint = emitCodePoint;
  2594. this.errors = errors;
  2595. /** The current state of the decoder. */
  2596. this.state = EntityDecoderState.EntityStart;
  2597. /** Characters that were consumed while parsing an entity. */
  2598. this.consumed = 1;
  2599. /**
  2600. * The result of the entity.
  2601. *
  2602. * Either the result index of a numeric entity, or the codepoint of a
  2603. * numeric entity.
  2604. */
  2605. this.result = 0;
  2606. /** The current index in the decode tree. */
  2607. this.treeIndex = 0;
  2608. /** The number of characters that were consumed in excess. */
  2609. this.excess = 1;
  2610. /** The mode in which the decoder is operating. */
  2611. this.decodeMode = DecodingMode.Strict;
  2612. /** The number of characters that have been consumed in the current run. */
  2613. this.runConsumed = 0;
  2614. }
  2615. /** Resets the instance to make it reusable. */
  2616. startEntity(decodeMode) {
  2617. this.decodeMode = decodeMode;
  2618. this.state = EntityDecoderState.EntityStart;
  2619. this.result = 0;
  2620. this.treeIndex = 0;
  2621. this.excess = 1;
  2622. this.consumed = 1;
  2623. this.runConsumed = 0;
  2624. }
  2625. /**
  2626. * Write an entity to the decoder. This can be called multiple times with partial entities.
  2627. * If the entity is incomplete, the decoder will return -1.
  2628. *
  2629. * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the
  2630. * entity is incomplete, and resume when the next string is written.
  2631. *
  2632. * @param input The string containing the entity (or a continuation of the entity).
  2633. * @param offset The offset at which the entity begins. Should be 0 if this is not the first call.
  2634. * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
  2635. */
  2636. write(input, offset) {
  2637. switch (this.state) {
  2638. case EntityDecoderState.EntityStart: {
  2639. if (input.charCodeAt(offset) === CharCodes.NUM) {
  2640. this.state = EntityDecoderState.NumericStart;
  2641. this.consumed += 1;
  2642. return this.stateNumericStart(input, offset + 1);
  2643. }
  2644. this.state = EntityDecoderState.NamedEntity;
  2645. return this.stateNamedEntity(input, offset);
  2646. }
  2647. case EntityDecoderState.NumericStart: {
  2648. return this.stateNumericStart(input, offset);
  2649. }
  2650. case EntityDecoderState.NumericDecimal: {
  2651. return this.stateNumericDecimal(input, offset);
  2652. }
  2653. case EntityDecoderState.NumericHex: {
  2654. return this.stateNumericHex(input, offset);
  2655. }
  2656. case EntityDecoderState.NamedEntity: {
  2657. return this.stateNamedEntity(input, offset);
  2658. }
  2659. }
  2660. }
  2661. /**
  2662. * Switches between the numeric decimal and hexadecimal states.
  2663. *
  2664. * Equivalent to the `Numeric character reference state` in the HTML spec.
  2665. *
  2666. * @param input The string containing the entity (or a continuation of the entity).
  2667. * @param offset The current offset.
  2668. * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
  2669. */
  2670. stateNumericStart(input, offset) {
  2671. if (offset >= input.length) {
  2672. return -1;
  2673. }
  2674. if ((input.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) {
  2675. this.state = EntityDecoderState.NumericHex;
  2676. this.consumed += 1;
  2677. return this.stateNumericHex(input, offset + 1);
  2678. }
  2679. this.state = EntityDecoderState.NumericDecimal;
  2680. return this.stateNumericDecimal(input, offset);
  2681. }
  2682. /**
  2683. * Parses a hexadecimal numeric entity.
  2684. *
  2685. * Equivalent to the `Hexademical character reference state` in the HTML spec.
  2686. *
  2687. * @param input The string containing the entity (or a continuation of the entity).
  2688. * @param offset The current offset.
  2689. * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
  2690. */
  2691. stateNumericHex(input, offset) {
  2692. while (offset < input.length) {
  2693. const char = input.charCodeAt(offset);
  2694. if (isNumber$1(char) || isHexadecimalCharacter(char)) {
  2695. // Convert hex digit to value (0-15); 'a'/'A' -> 10.
  2696. const digit = char <= CharCodes.NINE
  2697. ? char - CharCodes.ZERO
  2698. : (char | TO_LOWER_BIT) - CharCodes.LOWER_A + 10;
  2699. this.result = this.result * 16 + digit;
  2700. this.consumed++;
  2701. offset++;
  2702. }
  2703. else {
  2704. return this.emitNumericEntity(char, 3);
  2705. }
  2706. }
  2707. return -1; // Incomplete entity
  2708. }
  2709. /**
  2710. * Parses a decimal numeric entity.
  2711. *
  2712. * Equivalent to the `Decimal character reference state` in the HTML spec.
  2713. *
  2714. * @param input The string containing the entity (or a continuation of the entity).
  2715. * @param offset The current offset.
  2716. * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
  2717. */
  2718. stateNumericDecimal(input, offset) {
  2719. while (offset < input.length) {
  2720. const char = input.charCodeAt(offset);
  2721. if (isNumber$1(char)) {
  2722. this.result = this.result * 10 + (char - CharCodes.ZERO);
  2723. this.consumed++;
  2724. offset++;
  2725. }
  2726. else {
  2727. return this.emitNumericEntity(char, 2);
  2728. }
  2729. }
  2730. return -1; // Incomplete entity
  2731. }
  2732. /**
  2733. * Validate and emit a numeric entity.
  2734. *
  2735. * Implements the logic from the `Hexademical character reference start
  2736. * state` and `Numeric character reference end state` in the HTML spec.
  2737. *
  2738. * @param lastCp The last code point of the entity. Used to see if the
  2739. * entity was terminated with a semicolon.
  2740. * @param expectedLength The minimum number of characters that should be
  2741. * consumed. Used to validate that at least one digit
  2742. * was consumed.
  2743. * @returns The number of characters that were consumed.
  2744. */
  2745. emitNumericEntity(lastCp, expectedLength) {
  2746. var _a;
  2747. // Ensure we consumed at least one digit.
  2748. if (this.consumed <= expectedLength) {
  2749. (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed);
  2750. return 0;
  2751. }
  2752. // Figure out if this is a legit end of the entity
  2753. if (lastCp === CharCodes.SEMI) {
  2754. this.consumed += 1;
  2755. }
  2756. else if (this.decodeMode === DecodingMode.Strict) {
  2757. return 0;
  2758. }
  2759. this.emitCodePoint(replaceCodePoint(this.result), this.consumed);
  2760. if (this.errors) {
  2761. if (lastCp !== CharCodes.SEMI) {
  2762. this.errors.missingSemicolonAfterCharacterReference();
  2763. }
  2764. this.errors.validateNumericCharacterReference(this.result);
  2765. }
  2766. return this.consumed;
  2767. }
  2768. /**
  2769. * Parses a named entity.
  2770. *
  2771. * Equivalent to the `Named character reference state` in the HTML spec.
  2772. *
  2773. * @param input The string containing the entity (or a continuation of the entity).
  2774. * @param offset The current offset.
  2775. * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
  2776. */
  2777. stateNamedEntity(input, offset) {
  2778. const { decodeTree } = this;
  2779. let current = decodeTree[this.treeIndex];
  2780. // The length is the number of bytes of the value, including the current byte.
  2781. let valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
  2782. while (offset < input.length) {
  2783. // Handle compact runs (possibly inline): valueLength == 0 and SEMI_REQUIRED bit set.
  2784. if (valueLength === 0 && (current & BinTrieFlags.FLAG13) !== 0) {
  2785. const runLength = (current & BinTrieFlags.BRANCH_LENGTH) >> 7; /* 2..63 */
  2786. // If we are starting a run, check the first char.
  2787. if (this.runConsumed === 0) {
  2788. const firstChar = current & BinTrieFlags.JUMP_TABLE;
  2789. if (input.charCodeAt(offset) !== firstChar) {
  2790. return this.result === 0
  2791. ? 0
  2792. : this.emitNotTerminatedNamedEntity();
  2793. }
  2794. offset++;
  2795. this.excess++;
  2796. this.runConsumed++;
  2797. }
  2798. // Check remaining characters in the run.
  2799. while (this.runConsumed < runLength) {
  2800. if (offset >= input.length) {
  2801. return -1;
  2802. }
  2803. const charIndexInPacked = this.runConsumed - 1;
  2804. const packedWord = decodeTree[this.treeIndex + 1 + (charIndexInPacked >> 1)];
  2805. const expectedChar = charIndexInPacked % 2 === 0
  2806. ? packedWord & 0xff
  2807. : (packedWord >> 8) & 0xff;
  2808. if (input.charCodeAt(offset) !== expectedChar) {
  2809. this.runConsumed = 0;
  2810. return this.result === 0
  2811. ? 0
  2812. : this.emitNotTerminatedNamedEntity();
  2813. }
  2814. offset++;
  2815. this.excess++;
  2816. this.runConsumed++;
  2817. }
  2818. this.runConsumed = 0;
  2819. this.treeIndex += 1 + (runLength >> 1);
  2820. current = decodeTree[this.treeIndex];
  2821. valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
  2822. }
  2823. if (offset >= input.length)
  2824. break;
  2825. const char = input.charCodeAt(offset);
  2826. /*
  2827. * Implicit semicolon handling for nodes that require a semicolon but
  2828. * don't have an explicit ';' branch stored in the trie. If we have
  2829. * a value on the current node, it requires a semicolon, and the
  2830. * current input character is a semicolon, emit the entity using the
  2831. * current node (without descending further).
  2832. */
  2833. if (char === CharCodes.SEMI &&
  2834. valueLength !== 0 &&
  2835. (current & BinTrieFlags.FLAG13) !== 0) {
  2836. return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess);
  2837. }
  2838. this.treeIndex = determineBranch(decodeTree, current, this.treeIndex + Math.max(1, valueLength), char);
  2839. if (this.treeIndex < 0) {
  2840. return this.result === 0 ||
  2841. // If we are parsing an attribute
  2842. (this.decodeMode === DecodingMode.Attribute &&
  2843. // We shouldn't have consumed any characters after the entity,
  2844. (valueLength === 0 ||
  2845. // And there should be no invalid characters.
  2846. isEntityInAttributeInvalidEnd(char)))
  2847. ? 0
  2848. : this.emitNotTerminatedNamedEntity();
  2849. }
  2850. current = decodeTree[this.treeIndex];
  2851. valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
  2852. // If the branch is a value, store it and continue
  2853. if (valueLength !== 0) {
  2854. // If the entity is terminated by a semicolon, we are done.
  2855. if (char === CharCodes.SEMI) {
  2856. return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess);
  2857. }
  2858. // If we encounter a non-terminated (legacy) entity while parsing strictly, then ignore it.
  2859. if (this.decodeMode !== DecodingMode.Strict &&
  2860. (current & BinTrieFlags.FLAG13) === 0) {
  2861. this.result = this.treeIndex;
  2862. this.consumed += this.excess;
  2863. this.excess = 0;
  2864. }
  2865. }
  2866. // Increment offset & excess for next iteration
  2867. offset++;
  2868. this.excess++;
  2869. }
  2870. return -1;
  2871. }
  2872. /**
  2873. * Emit a named entity that was not terminated with a semicolon.
  2874. *
  2875. * @returns The number of characters consumed.
  2876. */
  2877. emitNotTerminatedNamedEntity() {
  2878. var _a;
  2879. const { result, decodeTree } = this;
  2880. const valueLength = (decodeTree[result] & BinTrieFlags.VALUE_LENGTH) >> 14;
  2881. this.emitNamedEntityData(result, valueLength, this.consumed);
  2882. (_a = this.errors) === null || _a === void 0 ? void 0 : _a.missingSemicolonAfterCharacterReference();
  2883. return this.consumed;
  2884. }
  2885. /**
  2886. * Emit a named entity.
  2887. *
  2888. * @param result The index of the entity in the decode tree.
  2889. * @param valueLength The number of bytes in the entity.
  2890. * @param consumed The number of characters consumed.
  2891. *
  2892. * @returns The number of characters consumed.
  2893. */
  2894. emitNamedEntityData(result, valueLength, consumed) {
  2895. const { decodeTree } = this;
  2896. this.emitCodePoint(valueLength === 1
  2897. ? decodeTree[result] &
  2898. ~(BinTrieFlags.VALUE_LENGTH | BinTrieFlags.FLAG13)
  2899. : decodeTree[result + 1], consumed);
  2900. if (valueLength === 3) {
  2901. // For multi-byte values, we need to emit the second byte.
  2902. this.emitCodePoint(decodeTree[result + 2], consumed);
  2903. }
  2904. return consumed;
  2905. }
  2906. /**
  2907. * Signal to the parser that the end of the input was reached.
  2908. *
  2909. * Remaining data will be emitted and relevant errors will be produced.
  2910. *
  2911. * @returns The number of characters consumed.
  2912. */
  2913. end() {
  2914. var _a;
  2915. switch (this.state) {
  2916. case EntityDecoderState.NamedEntity: {
  2917. // Emit a named entity if we have one.
  2918. return this.result !== 0 &&
  2919. (this.decodeMode !== DecodingMode.Attribute ||
  2920. this.result === this.treeIndex)
  2921. ? this.emitNotTerminatedNamedEntity()
  2922. : 0;
  2923. }
  2924. // Otherwise, emit a numeric entity if we have one.
  2925. case EntityDecoderState.NumericDecimal: {
  2926. return this.emitNumericEntity(0, 2);
  2927. }
  2928. case EntityDecoderState.NumericHex: {
  2929. return this.emitNumericEntity(0, 3);
  2930. }
  2931. case EntityDecoderState.NumericStart: {
  2932. (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed);
  2933. return 0;
  2934. }
  2935. case EntityDecoderState.EntityStart: {
  2936. // Return 0 if we have no entity.
  2937. return 0;
  2938. }
  2939. }
  2940. }
  2941. }
  2942. /**
  2943. * Creates a function that decodes entities in a string.
  2944. *
  2945. * @param decodeTree The decode tree.
  2946. * @returns A function that decodes entities in a string.
  2947. */
  2948. function getDecoder(decodeTree) {
  2949. let returnValue = "";
  2950. const decoder = new EntityDecoder(decodeTree, (data) => (returnValue += fromCodePoint(data)));
  2951. return function decodeWithTrie(input, decodeMode) {
  2952. let lastIndex = 0;
  2953. let offset = 0;
  2954. while ((offset = input.indexOf("&", offset)) >= 0) {
  2955. returnValue += input.slice(lastIndex, offset);
  2956. decoder.startEntity(decodeMode);
  2957. const length = decoder.write(input,
  2958. // Skip the "&"
  2959. offset + 1);
  2960. if (length < 0) {
  2961. lastIndex = offset + decoder.end();
  2962. break;
  2963. }
  2964. lastIndex = offset + length;
  2965. // If `length` is 0, skip the current `&` and continue.
  2966. offset = length === 0 ? lastIndex + 1 : lastIndex;
  2967. }
  2968. const result = returnValue + input.slice(lastIndex);
  2969. // Make sure we don't keep a reference to the final string.
  2970. returnValue = "";
  2971. return result;
  2972. };
  2973. }
  2974. /**
  2975. * Determines the branch of the current node that is taken given the current
  2976. * character. This function is used to traverse the trie.
  2977. *
  2978. * @param decodeTree The trie.
  2979. * @param current The current node.
  2980. * @param nodeIdx The index right after the current node and its value.
  2981. * @param char The current character.
  2982. * @returns The index of the next node, or -1 if no branch is taken.
  2983. */
  2984. function determineBranch(decodeTree, current, nodeIndex, char) {
  2985. const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;
  2986. const jumpOffset = current & BinTrieFlags.JUMP_TABLE;
  2987. // Case 1: Single branch encoded in jump offset
  2988. if (branchCount === 0) {
  2989. return jumpOffset !== 0 && char === jumpOffset ? nodeIndex : -1;
  2990. }
  2991. // Case 2: Multiple branches encoded in jump table
  2992. if (jumpOffset) {
  2993. const value = char - jumpOffset;
  2994. return value < 0 || value >= branchCount
  2995. ? -1
  2996. : decodeTree[nodeIndex + value] - 1;
  2997. }
  2998. // Case 3: Multiple branches encoded in packed dictionary (two keys per uint16)
  2999. const packedKeySlots = (branchCount + 1) >> 1;
  3000. /*
  3001. * Treat packed keys as a virtual sorted array of length `branchCount`.
  3002. * Key(i) = low byte for even i, high byte for odd i in slot i>>1.
  3003. */
  3004. let lo = 0;
  3005. let hi = branchCount - 1;
  3006. while (lo <= hi) {
  3007. const mid = (lo + hi) >>> 1;
  3008. const slot = mid >> 1;
  3009. const packed = decodeTree[nodeIndex + slot];
  3010. const midKey = (packed >> ((mid & 1) * 8)) & 0xff;
  3011. if (midKey < char) {
  3012. lo = mid + 1;
  3013. }
  3014. else if (midKey > char) {
  3015. hi = mid - 1;
  3016. }
  3017. else {
  3018. return decodeTree[nodeIndex + packedKeySlots + mid];
  3019. }
  3020. }
  3021. return -1;
  3022. }
  3023. const htmlDecoder = /* #__PURE__ */ getDecoder(htmlDecodeTree);
  3024. /**
  3025. * Decodes an HTML string.
  3026. *
  3027. * @param htmlString The string to decode.
  3028. * @param mode The decoding mode.
  3029. * @returns The decoded string.
  3030. */
  3031. function decodeHTML(htmlString, mode = DecodingMode.Legacy) {
  3032. return htmlDecoder(htmlString, mode);
  3033. }
  3034. const defaultDelimitersOpen = new Uint8Array([123, 123]);
  3035. const defaultDelimitersClose = new Uint8Array([125, 125]);
  3036. function isTagStartChar(c) {
  3037. return c >= 97 && c <= 122 || c >= 65 && c <= 90;
  3038. }
  3039. function isWhitespace(c) {
  3040. return c === 32 || c === 10 || c === 9 || c === 12 || c === 13;
  3041. }
  3042. function isEndOfTagSection(c) {
  3043. return c === 47 || c === 62 || isWhitespace(c);
  3044. }
  3045. function toCharCodes(str) {
  3046. const ret = new Uint8Array(str.length);
  3047. for (let i = 0; i < str.length; i++) {
  3048. ret[i] = str.charCodeAt(i);
  3049. }
  3050. return ret;
  3051. }
  3052. const Sequences = {
  3053. Cdata: new Uint8Array([67, 68, 65, 84, 65, 91]),
  3054. // CDATA[
  3055. CdataEnd: new Uint8Array([93, 93, 62]),
  3056. // ]]>
  3057. CommentEnd: new Uint8Array([45, 45, 62]),
  3058. // `-->`
  3059. ScriptEnd: new Uint8Array([60, 47, 115, 99, 114, 105, 112, 116]),
  3060. // `<\/script`
  3061. StyleEnd: new Uint8Array([60, 47, 115, 116, 121, 108, 101]),
  3062. // `</style`
  3063. TitleEnd: new Uint8Array([60, 47, 116, 105, 116, 108, 101]),
  3064. // `</title`
  3065. TextareaEnd: new Uint8Array([
  3066. 60,
  3067. 47,
  3068. 116,
  3069. 101,
  3070. 120,
  3071. 116,
  3072. 97,
  3073. 114,
  3074. 101,
  3075. 97
  3076. ])
  3077. // `</textarea
  3078. };
  3079. class Tokenizer {
  3080. constructor(stack, cbs) {
  3081. this.stack = stack;
  3082. this.cbs = cbs;
  3083. /** The current state the tokenizer is in. */
  3084. this.state = 1;
  3085. /** The read buffer. */
  3086. this.buffer = "";
  3087. /** The beginning of the section that is currently being read. */
  3088. this.sectionStart = 0;
  3089. /** The index within the buffer that we are currently looking at. */
  3090. this.index = 0;
  3091. /** The start of the last entity. */
  3092. this.entityStart = 0;
  3093. /** Some behavior, eg. when decoding entities, is done while we are in another state. This keeps track of the other state type. */
  3094. this.baseState = 1;
  3095. /** For special parsing behavior inside of script and style tags. */
  3096. this.inRCDATA = false;
  3097. /** For disabling RCDATA tags handling */
  3098. this.inXML = false;
  3099. /** For disabling interpolation parsing in v-pre */
  3100. this.inVPre = false;
  3101. /** Record newline positions for fast line / column calculation */
  3102. this.newlines = [];
  3103. this.mode = 0;
  3104. this.delimiterOpen = defaultDelimitersOpen;
  3105. this.delimiterClose = defaultDelimitersClose;
  3106. this.delimiterIndex = -1;
  3107. this.currentSequence = void 0;
  3108. this.sequenceIndex = 0;
  3109. {
  3110. this.entityDecoder = new EntityDecoder(
  3111. htmlDecodeTree,
  3112. (cp, consumed) => this.emitCodePoint(cp, consumed)
  3113. );
  3114. }
  3115. }
  3116. get inSFCRoot() {
  3117. return this.mode === 2 && this.stack.length === 0;
  3118. }
  3119. reset() {
  3120. this.state = 1;
  3121. this.mode = 0;
  3122. this.buffer = "";
  3123. this.sectionStart = 0;
  3124. this.index = 0;
  3125. this.baseState = 1;
  3126. this.inRCDATA = false;
  3127. this.currentSequence = void 0;
  3128. this.newlines.length = 0;
  3129. this.delimiterOpen = defaultDelimitersOpen;
  3130. this.delimiterClose = defaultDelimitersClose;
  3131. }
  3132. /**
  3133. * Generate Position object with line / column information using recorded
  3134. * newline positions. We know the index is always going to be an already
  3135. * processed index, so all the newlines up to this index should have been
  3136. * recorded.
  3137. */
  3138. getPos(index) {
  3139. let line = 1;
  3140. let column = index + 1;
  3141. const length = this.newlines.length;
  3142. let j = -1;
  3143. if (length > 100) {
  3144. let l = -1;
  3145. let r = length;
  3146. while (l + 1 < r) {
  3147. const m = l + r >>> 1;
  3148. this.newlines[m] < index ? l = m : r = m;
  3149. }
  3150. j = l;
  3151. } else {
  3152. for (let i = length - 1; i >= 0; i--) {
  3153. if (index > this.newlines[i]) {
  3154. j = i;
  3155. break;
  3156. }
  3157. }
  3158. }
  3159. if (j >= 0) {
  3160. line = j + 2;
  3161. column = index - this.newlines[j];
  3162. }
  3163. return {
  3164. column,
  3165. line,
  3166. offset: index
  3167. };
  3168. }
  3169. peek() {
  3170. return this.buffer.charCodeAt(this.index + 1);
  3171. }
  3172. stateText(c) {
  3173. if (c === 60) {
  3174. if (this.index > this.sectionStart) {
  3175. this.cbs.ontext(this.sectionStart, this.index);
  3176. }
  3177. this.state = 5;
  3178. this.sectionStart = this.index;
  3179. } else if (c === 38) {
  3180. this.startEntity();
  3181. } else if (!this.inVPre && c === this.delimiterOpen[0]) {
  3182. this.state = 2;
  3183. this.delimiterIndex = 0;
  3184. this.stateInterpolationOpen(c);
  3185. }
  3186. }
  3187. stateInterpolationOpen(c) {
  3188. if (c === this.delimiterOpen[this.delimiterIndex]) {
  3189. if (this.delimiterIndex === this.delimiterOpen.length - 1) {
  3190. const start = this.index + 1 - this.delimiterOpen.length;
  3191. if (start > this.sectionStart) {
  3192. this.cbs.ontext(this.sectionStart, start);
  3193. }
  3194. this.state = 3;
  3195. this.sectionStart = start;
  3196. } else {
  3197. this.delimiterIndex++;
  3198. }
  3199. } else if (this.inRCDATA) {
  3200. this.state = 32;
  3201. this.stateInRCDATA(c);
  3202. } else {
  3203. this.state = 1;
  3204. this.stateText(c);
  3205. }
  3206. }
  3207. stateInterpolation(c) {
  3208. if (c === this.delimiterClose[0]) {
  3209. this.state = 4;
  3210. this.delimiterIndex = 0;
  3211. this.stateInterpolationClose(c);
  3212. }
  3213. }
  3214. stateInterpolationClose(c) {
  3215. if (c === this.delimiterClose[this.delimiterIndex]) {
  3216. if (this.delimiterIndex === this.delimiterClose.length - 1) {
  3217. this.cbs.oninterpolation(this.sectionStart, this.index + 1);
  3218. if (this.inRCDATA) {
  3219. this.state = 32;
  3220. } else {
  3221. this.state = 1;
  3222. }
  3223. this.sectionStart = this.index + 1;
  3224. } else {
  3225. this.delimiterIndex++;
  3226. }
  3227. } else {
  3228. this.state = 3;
  3229. this.stateInterpolation(c);
  3230. }
  3231. }
  3232. stateSpecialStartSequence(c) {
  3233. const isEnd = this.sequenceIndex === this.currentSequence.length;
  3234. const isMatch = isEnd ? (
  3235. // If we are at the end of the sequence, make sure the tag name has ended
  3236. isEndOfTagSection(c)
  3237. ) : (
  3238. // Otherwise, do a case-insensitive comparison
  3239. (c | 32) === this.currentSequence[this.sequenceIndex]
  3240. );
  3241. if (!isMatch) {
  3242. this.inRCDATA = false;
  3243. } else if (!isEnd) {
  3244. this.sequenceIndex++;
  3245. return;
  3246. }
  3247. this.sequenceIndex = 0;
  3248. this.state = 6;
  3249. this.stateInTagName(c);
  3250. }
  3251. /** Look for an end tag. For <title> and <textarea>, also decode entities. */
  3252. stateInRCDATA(c) {
  3253. if (this.sequenceIndex === this.currentSequence.length) {
  3254. if (c === 62 || isWhitespace(c)) {
  3255. const endOfText = this.index - this.currentSequence.length;
  3256. if (this.sectionStart < endOfText) {
  3257. const actualIndex = this.index;
  3258. this.index = endOfText;
  3259. this.cbs.ontext(this.sectionStart, endOfText);
  3260. this.index = actualIndex;
  3261. }
  3262. this.sectionStart = endOfText + 2;
  3263. this.stateInClosingTagName(c);
  3264. this.inRCDATA = false;
  3265. return;
  3266. }
  3267. this.sequenceIndex = 0;
  3268. }
  3269. if ((c | 32) === this.currentSequence[this.sequenceIndex]) {
  3270. this.sequenceIndex += 1;
  3271. } else if (this.sequenceIndex === 0) {
  3272. if (this.currentSequence === Sequences.TitleEnd || this.currentSequence === Sequences.TextareaEnd && !this.inSFCRoot) {
  3273. if (c === 38) {
  3274. this.startEntity();
  3275. } else if (!this.inVPre && c === this.delimiterOpen[0]) {
  3276. this.state = 2;
  3277. this.delimiterIndex = 0;
  3278. this.stateInterpolationOpen(c);
  3279. }
  3280. } else if (this.fastForwardTo(60)) {
  3281. this.sequenceIndex = 1;
  3282. }
  3283. } else {
  3284. this.sequenceIndex = Number(c === 60);
  3285. }
  3286. }
  3287. stateCDATASequence(c) {
  3288. if (c === Sequences.Cdata[this.sequenceIndex]) {
  3289. if (++this.sequenceIndex === Sequences.Cdata.length) {
  3290. this.state = 28;
  3291. this.currentSequence = Sequences.CdataEnd;
  3292. this.sequenceIndex = 0;
  3293. this.sectionStart = this.index + 1;
  3294. }
  3295. } else {
  3296. this.sequenceIndex = 0;
  3297. this.state = 23;
  3298. this.stateInDeclaration(c);
  3299. }
  3300. }
  3301. /**
  3302. * When we wait for one specific character, we can speed things up
  3303. * by skipping through the buffer until we find it.
  3304. *
  3305. * @returns Whether the character was found.
  3306. */
  3307. fastForwardTo(c) {
  3308. while (++this.index < this.buffer.length) {
  3309. const cc = this.buffer.charCodeAt(this.index);
  3310. if (cc === 10) {
  3311. this.newlines.push(this.index);
  3312. }
  3313. if (cc === c) {
  3314. return true;
  3315. }
  3316. }
  3317. this.index = this.buffer.length - 1;
  3318. return false;
  3319. }
  3320. /**
  3321. * Comments and CDATA end with `-->` and `]]>`.
  3322. *
  3323. * Their common qualities are:
  3324. * - Their end sequences have a distinct character they start with.
  3325. * - That character is then repeated, so we have to check multiple repeats.
  3326. * - All characters but the start character of the sequence can be skipped.
  3327. */
  3328. stateInCommentLike(c) {
  3329. if (c === this.currentSequence[this.sequenceIndex]) {
  3330. if (++this.sequenceIndex === this.currentSequence.length) {
  3331. if (this.currentSequence === Sequences.CdataEnd) {
  3332. this.cbs.oncdata(this.sectionStart, this.index - 2);
  3333. } else {
  3334. this.cbs.oncomment(this.sectionStart, this.index - 2);
  3335. }
  3336. this.sequenceIndex = 0;
  3337. this.sectionStart = this.index + 1;
  3338. this.state = 1;
  3339. }
  3340. } else if (this.sequenceIndex === 0) {
  3341. if (this.fastForwardTo(this.currentSequence[0])) {
  3342. this.sequenceIndex = 1;
  3343. }
  3344. } else if (c !== this.currentSequence[this.sequenceIndex - 1]) {
  3345. this.sequenceIndex = 0;
  3346. }
  3347. }
  3348. startSpecial(sequence, offset) {
  3349. this.enterRCDATA(sequence, offset);
  3350. this.state = 31;
  3351. }
  3352. enterRCDATA(sequence, offset) {
  3353. this.inRCDATA = true;
  3354. this.currentSequence = sequence;
  3355. this.sequenceIndex = offset;
  3356. }
  3357. stateBeforeTagName(c) {
  3358. if (c === 33) {
  3359. this.state = 22;
  3360. this.sectionStart = this.index + 1;
  3361. } else if (c === 63) {
  3362. this.state = 24;
  3363. this.sectionStart = this.index + 1;
  3364. } else if (isTagStartChar(c)) {
  3365. this.sectionStart = this.index;
  3366. if (this.mode === 0) {
  3367. this.state = 6;
  3368. } else if (this.inSFCRoot) {
  3369. this.state = 34;
  3370. } else if (!this.inXML) {
  3371. if (c === 116) {
  3372. this.state = 30;
  3373. } else {
  3374. this.state = c === 115 ? 29 : 6;
  3375. }
  3376. } else {
  3377. this.state = 6;
  3378. }
  3379. } else if (c === 47) {
  3380. this.state = 8;
  3381. } else {
  3382. this.state = 1;
  3383. this.stateText(c);
  3384. }
  3385. }
  3386. stateInTagName(c) {
  3387. if (isEndOfTagSection(c)) {
  3388. this.handleTagName(c);
  3389. }
  3390. }
  3391. stateInSFCRootTagName(c) {
  3392. if (isEndOfTagSection(c)) {
  3393. const tag = this.buffer.slice(this.sectionStart, this.index);
  3394. if (tag !== "template") {
  3395. this.enterRCDATA(toCharCodes(`</` + tag), 0);
  3396. }
  3397. this.handleTagName(c);
  3398. }
  3399. }
  3400. handleTagName(c) {
  3401. this.cbs.onopentagname(this.sectionStart, this.index);
  3402. this.sectionStart = -1;
  3403. this.state = 11;
  3404. this.stateBeforeAttrName(c);
  3405. }
  3406. stateBeforeClosingTagName(c) {
  3407. if (isWhitespace(c)) ; else if (c === 62) {
  3408. {
  3409. this.cbs.onerr(14, this.index);
  3410. }
  3411. this.state = 1;
  3412. this.sectionStart = this.index + 1;
  3413. } else {
  3414. this.state = isTagStartChar(c) ? 9 : 27;
  3415. this.sectionStart = this.index;
  3416. }
  3417. }
  3418. stateInClosingTagName(c) {
  3419. if (c === 62 || isWhitespace(c)) {
  3420. this.cbs.onclosetag(this.sectionStart, this.index);
  3421. this.sectionStart = -1;
  3422. this.state = 10;
  3423. this.stateAfterClosingTagName(c);
  3424. }
  3425. }
  3426. stateAfterClosingTagName(c) {
  3427. if (c === 62) {
  3428. this.state = 1;
  3429. this.sectionStart = this.index + 1;
  3430. }
  3431. }
  3432. stateBeforeAttrName(c) {
  3433. if (c === 62) {
  3434. this.cbs.onopentagend(this.index);
  3435. if (this.inRCDATA) {
  3436. this.state = 32;
  3437. } else {
  3438. this.state = 1;
  3439. }
  3440. this.sectionStart = this.index + 1;
  3441. } else if (c === 47) {
  3442. this.state = 7;
  3443. if (this.peek() !== 62) {
  3444. this.cbs.onerr(22, this.index);
  3445. }
  3446. } else if (c === 60 && this.peek() === 47) {
  3447. this.cbs.onopentagend(this.index);
  3448. this.state = 5;
  3449. this.sectionStart = this.index;
  3450. } else if (!isWhitespace(c)) {
  3451. if (c === 61) {
  3452. this.cbs.onerr(
  3453. 19,
  3454. this.index
  3455. );
  3456. }
  3457. this.handleAttrStart(c);
  3458. }
  3459. }
  3460. handleAttrStart(c) {
  3461. if (c === 118 && this.peek() === 45) {
  3462. this.state = 13;
  3463. this.sectionStart = this.index;
  3464. } else if (c === 46 || c === 58 || c === 64 || c === 35) {
  3465. this.cbs.ondirname(this.index, this.index + 1);
  3466. this.state = 14;
  3467. this.sectionStart = this.index + 1;
  3468. } else {
  3469. this.state = 12;
  3470. this.sectionStart = this.index;
  3471. }
  3472. }
  3473. stateInSelfClosingTag(c) {
  3474. if (c === 62) {
  3475. this.cbs.onselfclosingtag(this.index);
  3476. this.state = 1;
  3477. this.sectionStart = this.index + 1;
  3478. this.inRCDATA = false;
  3479. } else if (!isWhitespace(c)) {
  3480. this.state = 11;
  3481. this.stateBeforeAttrName(c);
  3482. }
  3483. }
  3484. stateInAttrName(c) {
  3485. if (c === 61 || isEndOfTagSection(c)) {
  3486. this.cbs.onattribname(this.sectionStart, this.index);
  3487. this.handleAttrNameEnd(c);
  3488. } else if (c === 34 || c === 39 || c === 60) {
  3489. this.cbs.onerr(
  3490. 17,
  3491. this.index
  3492. );
  3493. }
  3494. }
  3495. stateInDirName(c) {
  3496. if (c === 61 || isEndOfTagSection(c)) {
  3497. this.cbs.ondirname(this.sectionStart, this.index);
  3498. this.handleAttrNameEnd(c);
  3499. } else if (c === 58) {
  3500. this.cbs.ondirname(this.sectionStart, this.index);
  3501. this.state = 14;
  3502. this.sectionStart = this.index + 1;
  3503. } else if (c === 46) {
  3504. this.cbs.ondirname(this.sectionStart, this.index);
  3505. this.state = 16;
  3506. this.sectionStart = this.index + 1;
  3507. }
  3508. }
  3509. stateInDirArg(c) {
  3510. if (c === 61 || isEndOfTagSection(c)) {
  3511. this.cbs.ondirarg(this.sectionStart, this.index);
  3512. this.handleAttrNameEnd(c);
  3513. } else if (c === 91) {
  3514. this.state = 15;
  3515. } else if (c === 46) {
  3516. this.cbs.ondirarg(this.sectionStart, this.index);
  3517. this.state = 16;
  3518. this.sectionStart = this.index + 1;
  3519. }
  3520. }
  3521. stateInDynamicDirArg(c) {
  3522. if (c === 93) {
  3523. this.state = 14;
  3524. } else if (c === 61 || isEndOfTagSection(c)) {
  3525. this.cbs.ondirarg(this.sectionStart, this.index + 1);
  3526. this.handleAttrNameEnd(c);
  3527. {
  3528. this.cbs.onerr(
  3529. 27,
  3530. this.index
  3531. );
  3532. }
  3533. }
  3534. }
  3535. stateInDirModifier(c) {
  3536. if (c === 61 || isEndOfTagSection(c)) {
  3537. this.cbs.ondirmodifier(this.sectionStart, this.index);
  3538. this.handleAttrNameEnd(c);
  3539. } else if (c === 46) {
  3540. this.cbs.ondirmodifier(this.sectionStart, this.index);
  3541. this.sectionStart = this.index + 1;
  3542. }
  3543. }
  3544. handleAttrNameEnd(c) {
  3545. this.sectionStart = this.index;
  3546. this.state = 17;
  3547. this.cbs.onattribnameend(this.index);
  3548. this.stateAfterAttrName(c);
  3549. }
  3550. stateAfterAttrName(c) {
  3551. if (c === 61) {
  3552. this.state = 18;
  3553. } else if (c === 47 || c === 62) {
  3554. this.cbs.onattribend(0, this.sectionStart);
  3555. this.sectionStart = -1;
  3556. this.state = 11;
  3557. this.stateBeforeAttrName(c);
  3558. } else if (!isWhitespace(c)) {
  3559. this.cbs.onattribend(0, this.sectionStart);
  3560. this.handleAttrStart(c);
  3561. }
  3562. }
  3563. stateBeforeAttrValue(c) {
  3564. if (c === 34) {
  3565. this.state = 19;
  3566. this.sectionStart = this.index + 1;
  3567. } else if (c === 39) {
  3568. this.state = 20;
  3569. this.sectionStart = this.index + 1;
  3570. } else if (!isWhitespace(c)) {
  3571. this.sectionStart = this.index;
  3572. this.state = 21;
  3573. this.stateInAttrValueNoQuotes(c);
  3574. }
  3575. }
  3576. handleInAttrValue(c, quote) {
  3577. if (c === quote || false) {
  3578. this.cbs.onattribdata(this.sectionStart, this.index);
  3579. this.sectionStart = -1;
  3580. this.cbs.onattribend(
  3581. quote === 34 ? 3 : 2,
  3582. this.index + 1
  3583. );
  3584. this.state = 11;
  3585. } else if (c === 38) {
  3586. this.startEntity();
  3587. }
  3588. }
  3589. stateInAttrValueDoubleQuotes(c) {
  3590. this.handleInAttrValue(c, 34);
  3591. }
  3592. stateInAttrValueSingleQuotes(c) {
  3593. this.handleInAttrValue(c, 39);
  3594. }
  3595. stateInAttrValueNoQuotes(c) {
  3596. if (isWhitespace(c) || c === 62) {
  3597. this.cbs.onattribdata(this.sectionStart, this.index);
  3598. this.sectionStart = -1;
  3599. this.cbs.onattribend(1, this.index);
  3600. this.state = 11;
  3601. this.stateBeforeAttrName(c);
  3602. } else if (c === 34 || c === 39 || c === 60 || c === 61 || c === 96) {
  3603. this.cbs.onerr(
  3604. 18,
  3605. this.index
  3606. );
  3607. } else if (c === 38) {
  3608. this.startEntity();
  3609. }
  3610. }
  3611. stateBeforeDeclaration(c) {
  3612. if (c === 91) {
  3613. this.state = 26;
  3614. this.sequenceIndex = 0;
  3615. } else {
  3616. this.state = c === 45 ? 25 : 23;
  3617. }
  3618. }
  3619. stateInDeclaration(c) {
  3620. if (c === 62 || this.fastForwardTo(62)) {
  3621. this.state = 1;
  3622. this.sectionStart = this.index + 1;
  3623. }
  3624. }
  3625. stateInProcessingInstruction(c) {
  3626. if (c === 62 || this.fastForwardTo(62)) {
  3627. this.cbs.onprocessinginstruction(this.sectionStart, this.index);
  3628. this.state = 1;
  3629. this.sectionStart = this.index + 1;
  3630. }
  3631. }
  3632. stateBeforeComment(c) {
  3633. if (c === 45) {
  3634. this.state = 28;
  3635. this.currentSequence = Sequences.CommentEnd;
  3636. this.sequenceIndex = 2;
  3637. this.sectionStart = this.index + 1;
  3638. } else {
  3639. this.state = 23;
  3640. }
  3641. }
  3642. stateInSpecialComment(c) {
  3643. if (c === 62 || this.fastForwardTo(62)) {
  3644. this.cbs.oncomment(this.sectionStart, this.index);
  3645. this.state = 1;
  3646. this.sectionStart = this.index + 1;
  3647. }
  3648. }
  3649. stateBeforeSpecialS(c) {
  3650. if (c === Sequences.ScriptEnd[3]) {
  3651. this.startSpecial(Sequences.ScriptEnd, 4);
  3652. } else if (c === Sequences.StyleEnd[3]) {
  3653. this.startSpecial(Sequences.StyleEnd, 4);
  3654. } else {
  3655. this.state = 6;
  3656. this.stateInTagName(c);
  3657. }
  3658. }
  3659. stateBeforeSpecialT(c) {
  3660. if (c === Sequences.TitleEnd[3]) {
  3661. this.startSpecial(Sequences.TitleEnd, 4);
  3662. } else if (c === Sequences.TextareaEnd[3]) {
  3663. this.startSpecial(Sequences.TextareaEnd, 4);
  3664. } else {
  3665. this.state = 6;
  3666. this.stateInTagName(c);
  3667. }
  3668. }
  3669. startEntity() {
  3670. {
  3671. this.baseState = this.state;
  3672. this.state = 33;
  3673. this.entityStart = this.index;
  3674. this.entityDecoder.startEntity(
  3675. this.baseState === 1 || this.baseState === 32 ? DecodingMode.Legacy : DecodingMode.Attribute
  3676. );
  3677. }
  3678. }
  3679. stateInEntity() {
  3680. {
  3681. const length = this.entityDecoder.write(this.buffer, this.index);
  3682. if (length >= 0) {
  3683. this.state = this.baseState;
  3684. if (length === 0) {
  3685. this.index = this.entityStart;
  3686. }
  3687. } else {
  3688. this.index = this.buffer.length - 1;
  3689. }
  3690. }
  3691. }
  3692. /**
  3693. * Iterates through the buffer, calling the function corresponding to the current state.
  3694. *
  3695. * States that are more likely to be hit are higher up, as a performance improvement.
  3696. */
  3697. parse(input) {
  3698. this.buffer = input;
  3699. while (this.index < this.buffer.length) {
  3700. const c = this.buffer.charCodeAt(this.index);
  3701. if (c === 10 && this.state !== 33) {
  3702. this.newlines.push(this.index);
  3703. }
  3704. switch (this.state) {
  3705. case 1: {
  3706. this.stateText(c);
  3707. break;
  3708. }
  3709. case 2: {
  3710. this.stateInterpolationOpen(c);
  3711. break;
  3712. }
  3713. case 3: {
  3714. this.stateInterpolation(c);
  3715. break;
  3716. }
  3717. case 4: {
  3718. this.stateInterpolationClose(c);
  3719. break;
  3720. }
  3721. case 31: {
  3722. this.stateSpecialStartSequence(c);
  3723. break;
  3724. }
  3725. case 32: {
  3726. this.stateInRCDATA(c);
  3727. break;
  3728. }
  3729. case 26: {
  3730. this.stateCDATASequence(c);
  3731. break;
  3732. }
  3733. case 19: {
  3734. this.stateInAttrValueDoubleQuotes(c);
  3735. break;
  3736. }
  3737. case 12: {
  3738. this.stateInAttrName(c);
  3739. break;
  3740. }
  3741. case 13: {
  3742. this.stateInDirName(c);
  3743. break;
  3744. }
  3745. case 14: {
  3746. this.stateInDirArg(c);
  3747. break;
  3748. }
  3749. case 15: {
  3750. this.stateInDynamicDirArg(c);
  3751. break;
  3752. }
  3753. case 16: {
  3754. this.stateInDirModifier(c);
  3755. break;
  3756. }
  3757. case 28: {
  3758. this.stateInCommentLike(c);
  3759. break;
  3760. }
  3761. case 27: {
  3762. this.stateInSpecialComment(c);
  3763. break;
  3764. }
  3765. case 11: {
  3766. this.stateBeforeAttrName(c);
  3767. break;
  3768. }
  3769. case 6: {
  3770. this.stateInTagName(c);
  3771. break;
  3772. }
  3773. case 34: {
  3774. this.stateInSFCRootTagName(c);
  3775. break;
  3776. }
  3777. case 9: {
  3778. this.stateInClosingTagName(c);
  3779. break;
  3780. }
  3781. case 5: {
  3782. this.stateBeforeTagName(c);
  3783. break;
  3784. }
  3785. case 17: {
  3786. this.stateAfterAttrName(c);
  3787. break;
  3788. }
  3789. case 20: {
  3790. this.stateInAttrValueSingleQuotes(c);
  3791. break;
  3792. }
  3793. case 18: {
  3794. this.stateBeforeAttrValue(c);
  3795. break;
  3796. }
  3797. case 8: {
  3798. this.stateBeforeClosingTagName(c);
  3799. break;
  3800. }
  3801. case 10: {
  3802. this.stateAfterClosingTagName(c);
  3803. break;
  3804. }
  3805. case 29: {
  3806. this.stateBeforeSpecialS(c);
  3807. break;
  3808. }
  3809. case 30: {
  3810. this.stateBeforeSpecialT(c);
  3811. break;
  3812. }
  3813. case 21: {
  3814. this.stateInAttrValueNoQuotes(c);
  3815. break;
  3816. }
  3817. case 7: {
  3818. this.stateInSelfClosingTag(c);
  3819. break;
  3820. }
  3821. case 23: {
  3822. this.stateInDeclaration(c);
  3823. break;
  3824. }
  3825. case 22: {
  3826. this.stateBeforeDeclaration(c);
  3827. break;
  3828. }
  3829. case 25: {
  3830. this.stateBeforeComment(c);
  3831. break;
  3832. }
  3833. case 24: {
  3834. this.stateInProcessingInstruction(c);
  3835. break;
  3836. }
  3837. case 33: {
  3838. this.stateInEntity();
  3839. break;
  3840. }
  3841. }
  3842. this.index++;
  3843. }
  3844. this.cleanup();
  3845. this.finish();
  3846. }
  3847. /**
  3848. * Remove data that has already been consumed from the buffer.
  3849. */
  3850. cleanup() {
  3851. if (this.sectionStart !== this.index) {
  3852. if (this.state === 1 || this.state === 32 && this.sequenceIndex === 0) {
  3853. this.cbs.ontext(this.sectionStart, this.index);
  3854. this.sectionStart = this.index;
  3855. } else if (this.state === 19 || this.state === 20 || this.state === 21) {
  3856. this.cbs.onattribdata(this.sectionStart, this.index);
  3857. this.sectionStart = this.index;
  3858. }
  3859. }
  3860. }
  3861. finish() {
  3862. if (this.state === 33) {
  3863. this.entityDecoder.end();
  3864. this.state = this.baseState;
  3865. }
  3866. this.handleTrailingData();
  3867. this.cbs.onend();
  3868. }
  3869. /** Handle any trailing data. */
  3870. handleTrailingData() {
  3871. const endIndex = this.buffer.length;
  3872. if (this.sectionStart >= endIndex) {
  3873. return;
  3874. }
  3875. if (this.state === 28) {
  3876. if (this.currentSequence === Sequences.CdataEnd) {
  3877. this.cbs.oncdata(this.sectionStart, endIndex);
  3878. } else {
  3879. this.cbs.oncomment(this.sectionStart, endIndex);
  3880. }
  3881. } else if (this.state === 6 || this.state === 11 || this.state === 18 || this.state === 17 || this.state === 12 || this.state === 13 || this.state === 14 || this.state === 15 || this.state === 16 || this.state === 20 || this.state === 19 || this.state === 21 || this.state === 9) ; else {
  3882. this.cbs.ontext(this.sectionStart, endIndex);
  3883. }
  3884. }
  3885. emitCodePoint(cp, consumed) {
  3886. {
  3887. if (this.baseState !== 1 && this.baseState !== 32) {
  3888. if (this.sectionStart < this.entityStart) {
  3889. this.cbs.onattribdata(this.sectionStart, this.entityStart);
  3890. }
  3891. this.sectionStart = this.entityStart + consumed;
  3892. this.index = this.sectionStart - 1;
  3893. this.cbs.onattribentity(
  3894. fromCodePoint(cp),
  3895. this.entityStart,
  3896. this.sectionStart
  3897. );
  3898. } else {
  3899. if (this.sectionStart < this.entityStart) {
  3900. this.cbs.ontext(this.sectionStart, this.entityStart);
  3901. }
  3902. this.sectionStart = this.entityStart + consumed;
  3903. this.index = this.sectionStart - 1;
  3904. this.cbs.ontextentity(
  3905. fromCodePoint(cp),
  3906. this.entityStart,
  3907. this.sectionStart
  3908. );
  3909. }
  3910. }
  3911. }
  3912. }
  3913. const CompilerDeprecationTypes = {
  3914. "COMPILER_IS_ON_ELEMENT": "COMPILER_IS_ON_ELEMENT",
  3915. "COMPILER_V_BIND_SYNC": "COMPILER_V_BIND_SYNC",
  3916. "COMPILER_V_BIND_OBJECT_ORDER": "COMPILER_V_BIND_OBJECT_ORDER",
  3917. "COMPILER_V_ON_NATIVE": "COMPILER_V_ON_NATIVE",
  3918. "COMPILER_V_IF_V_FOR_PRECEDENCE": "COMPILER_V_IF_V_FOR_PRECEDENCE",
  3919. "COMPILER_NATIVE_TEMPLATE": "COMPILER_NATIVE_TEMPLATE",
  3920. "COMPILER_INLINE_TEMPLATE": "COMPILER_INLINE_TEMPLATE",
  3921. "COMPILER_FILTERS": "COMPILER_FILTERS"
  3922. };
  3923. const deprecationData = {
  3924. ["COMPILER_IS_ON_ELEMENT"]: {
  3925. message: `Platform-native elements with "is" prop will no longer be treated as components in Vue 3 unless the "is" value is explicitly prefixed with "vue:".`,
  3926. link: `https://v3-migration.vuejs.org/breaking-changes/custom-elements-interop.html`
  3927. },
  3928. ["COMPILER_V_BIND_SYNC"]: {
  3929. message: (key) => `.sync modifier for v-bind has been removed. Use v-model with argument instead. \`v-bind:${key}.sync\` should be changed to \`v-model:${key}\`.`,
  3930. link: `https://v3-migration.vuejs.org/breaking-changes/v-model.html`
  3931. },
  3932. ["COMPILER_V_BIND_OBJECT_ORDER"]: {
  3933. message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript object spread: it will now overwrite an existing non-mergeable attribute that appears before v-bind in the case of conflict. To retain 2.x behavior, move v-bind to make it the first attribute. You can also suppress this warning if the usage is intended.`,
  3934. link: `https://v3-migration.vuejs.org/breaking-changes/v-bind.html`
  3935. },
  3936. ["COMPILER_V_ON_NATIVE"]: {
  3937. message: `.native modifier for v-on has been removed as is no longer necessary.`,
  3938. link: `https://v3-migration.vuejs.org/breaking-changes/v-on-native-modifier-removed.html`
  3939. },
  3940. ["COMPILER_V_IF_V_FOR_PRECEDENCE"]: {
  3941. message: `v-if / v-for precedence when used on the same element has changed in Vue 3: v-if now takes higher precedence and will no longer have access to v-for scope variables. It is best to avoid the ambiguity with <template> tags or use a computed property that filters v-for data source.`,
  3942. link: `https://v3-migration.vuejs.org/breaking-changes/v-if-v-for.html`
  3943. },
  3944. ["COMPILER_NATIVE_TEMPLATE"]: {
  3945. message: `<template> with no special directives will render as a native template element instead of its inner content in Vue 3.`
  3946. },
  3947. ["COMPILER_INLINE_TEMPLATE"]: {
  3948. message: `"inline-template" has been removed in Vue 3.`,
  3949. link: `https://v3-migration.vuejs.org/breaking-changes/inline-template-attribute.html`
  3950. },
  3951. ["COMPILER_FILTERS"]: {
  3952. message: `filters have been removed in Vue 3. The "|" symbol will be treated as native JavaScript bitwise OR operator. Use method calls or computed properties instead.`,
  3953. link: `https://v3-migration.vuejs.org/breaking-changes/filters.html`
  3954. }
  3955. };
  3956. function getCompatValue(key, { compatConfig }) {
  3957. const value = compatConfig && compatConfig[key];
  3958. if (key === "MODE") {
  3959. return value || 3;
  3960. } else {
  3961. return value;
  3962. }
  3963. }
  3964. function isCompatEnabled(key, context) {
  3965. const mode = getCompatValue("MODE", context);
  3966. const value = getCompatValue(key, context);
  3967. return mode === 3 ? value === true : value !== false;
  3968. }
  3969. function checkCompatEnabled(key, context, loc, ...args) {
  3970. const enabled = isCompatEnabled(key, context);
  3971. if (enabled) {
  3972. warnDeprecation(key, context, loc, ...args);
  3973. }
  3974. return enabled;
  3975. }
  3976. function warnDeprecation(key, context, loc, ...args) {
  3977. const val = getCompatValue(key, context);
  3978. if (val === "suppress-warning") {
  3979. return;
  3980. }
  3981. const { message, link } = deprecationData[key];
  3982. const msg = `(deprecation ${key}) ${typeof message === "function" ? message(...args) : message}${link ? `
  3983. Details: ${link}` : ``}`;
  3984. const err = new SyntaxError(msg);
  3985. err.code = key;
  3986. if (loc) err.loc = loc;
  3987. context.onWarn(err);
  3988. }
  3989. function defaultOnError(error) {
  3990. throw error;
  3991. }
  3992. function defaultOnWarn(msg) {
  3993. console.warn(`[Vue warn] ${msg.message}`);
  3994. }
  3995. function createCompilerError(code, loc, messages, additionalMessage) {
  3996. const msg = (messages || errorMessages$1)[code] + (additionalMessage || ``) ;
  3997. const error = new SyntaxError(String(msg));
  3998. error.code = code;
  3999. error.loc = loc;
  4000. return error;
  4001. }
  4002. const ErrorCodes = {
  4003. "ABRUPT_CLOSING_OF_EMPTY_COMMENT": 0,
  4004. "0": "ABRUPT_CLOSING_OF_EMPTY_COMMENT",
  4005. "CDATA_IN_HTML_CONTENT": 1,
  4006. "1": "CDATA_IN_HTML_CONTENT",
  4007. "DUPLICATE_ATTRIBUTE": 2,
  4008. "2": "DUPLICATE_ATTRIBUTE",
  4009. "END_TAG_WITH_ATTRIBUTES": 3,
  4010. "3": "END_TAG_WITH_ATTRIBUTES",
  4011. "END_TAG_WITH_TRAILING_SOLIDUS": 4,
  4012. "4": "END_TAG_WITH_TRAILING_SOLIDUS",
  4013. "EOF_BEFORE_TAG_NAME": 5,
  4014. "5": "EOF_BEFORE_TAG_NAME",
  4015. "EOF_IN_CDATA": 6,
  4016. "6": "EOF_IN_CDATA",
  4017. "EOF_IN_COMMENT": 7,
  4018. "7": "EOF_IN_COMMENT",
  4019. "EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT": 8,
  4020. "8": "EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT",
  4021. "EOF_IN_TAG": 9,
  4022. "9": "EOF_IN_TAG",
  4023. "INCORRECTLY_CLOSED_COMMENT": 10,
  4024. "10": "INCORRECTLY_CLOSED_COMMENT",
  4025. "INCORRECTLY_OPENED_COMMENT": 11,
  4026. "11": "INCORRECTLY_OPENED_COMMENT",
  4027. "INVALID_FIRST_CHARACTER_OF_TAG_NAME": 12,
  4028. "12": "INVALID_FIRST_CHARACTER_OF_TAG_NAME",
  4029. "MISSING_ATTRIBUTE_VALUE": 13,
  4030. "13": "MISSING_ATTRIBUTE_VALUE",
  4031. "MISSING_END_TAG_NAME": 14,
  4032. "14": "MISSING_END_TAG_NAME",
  4033. "MISSING_WHITESPACE_BETWEEN_ATTRIBUTES": 15,
  4034. "15": "MISSING_WHITESPACE_BETWEEN_ATTRIBUTES",
  4035. "NESTED_COMMENT": 16,
  4036. "16": "NESTED_COMMENT",
  4037. "UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME": 17,
  4038. "17": "UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME",
  4039. "UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE": 18,
  4040. "18": "UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE",
  4041. "UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME": 19,
  4042. "19": "UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME",
  4043. "UNEXPECTED_NULL_CHARACTER": 20,
  4044. "20": "UNEXPECTED_NULL_CHARACTER",
  4045. "UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME": 21,
  4046. "21": "UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME",
  4047. "UNEXPECTED_SOLIDUS_IN_TAG": 22,
  4048. "22": "UNEXPECTED_SOLIDUS_IN_TAG",
  4049. "X_INVALID_END_TAG": 23,
  4050. "23": "X_INVALID_END_TAG",
  4051. "X_MISSING_END_TAG": 24,
  4052. "24": "X_MISSING_END_TAG",
  4053. "X_MISSING_INTERPOLATION_END": 25,
  4054. "25": "X_MISSING_INTERPOLATION_END",
  4055. "X_MISSING_DIRECTIVE_NAME": 26,
  4056. "26": "X_MISSING_DIRECTIVE_NAME",
  4057. "X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END": 27,
  4058. "27": "X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END",
  4059. "X_V_IF_NO_EXPRESSION": 28,
  4060. "28": "X_V_IF_NO_EXPRESSION",
  4061. "X_V_IF_SAME_KEY": 29,
  4062. "29": "X_V_IF_SAME_KEY",
  4063. "X_V_ELSE_NO_ADJACENT_IF": 30,
  4064. "30": "X_V_ELSE_NO_ADJACENT_IF",
  4065. "X_V_FOR_NO_EXPRESSION": 31,
  4066. "31": "X_V_FOR_NO_EXPRESSION",
  4067. "X_V_FOR_MALFORMED_EXPRESSION": 32,
  4068. "32": "X_V_FOR_MALFORMED_EXPRESSION",
  4069. "X_V_FOR_TEMPLATE_KEY_PLACEMENT": 33,
  4070. "33": "X_V_FOR_TEMPLATE_KEY_PLACEMENT",
  4071. "X_V_BIND_NO_EXPRESSION": 34,
  4072. "34": "X_V_BIND_NO_EXPRESSION",
  4073. "X_V_ON_NO_EXPRESSION": 35,
  4074. "35": "X_V_ON_NO_EXPRESSION",
  4075. "X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET": 36,
  4076. "36": "X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET",
  4077. "X_V_SLOT_MIXED_SLOT_USAGE": 37,
  4078. "37": "X_V_SLOT_MIXED_SLOT_USAGE",
  4079. "X_V_SLOT_DUPLICATE_SLOT_NAMES": 38,
  4080. "38": "X_V_SLOT_DUPLICATE_SLOT_NAMES",
  4081. "X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN": 39,
  4082. "39": "X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN",
  4083. "X_V_SLOT_MISPLACED": 40,
  4084. "40": "X_V_SLOT_MISPLACED",
  4085. "X_V_MODEL_NO_EXPRESSION": 41,
  4086. "41": "X_V_MODEL_NO_EXPRESSION",
  4087. "X_V_MODEL_MALFORMED_EXPRESSION": 42,
  4088. "42": "X_V_MODEL_MALFORMED_EXPRESSION",
  4089. "X_V_MODEL_ON_SCOPE_VARIABLE": 43,
  4090. "43": "X_V_MODEL_ON_SCOPE_VARIABLE",
  4091. "X_V_MODEL_ON_PROPS": 44,
  4092. "44": "X_V_MODEL_ON_PROPS",
  4093. "X_V_MODEL_ON_CONST": 45,
  4094. "45": "X_V_MODEL_ON_CONST",
  4095. "X_INVALID_EXPRESSION": 46,
  4096. "46": "X_INVALID_EXPRESSION",
  4097. "X_KEEP_ALIVE_INVALID_CHILDREN": 47,
  4098. "47": "X_KEEP_ALIVE_INVALID_CHILDREN",
  4099. "X_PREFIX_ID_NOT_SUPPORTED": 48,
  4100. "48": "X_PREFIX_ID_NOT_SUPPORTED",
  4101. "X_MODULE_MODE_NOT_SUPPORTED": 49,
  4102. "49": "X_MODULE_MODE_NOT_SUPPORTED",
  4103. "X_CACHE_HANDLER_NOT_SUPPORTED": 50,
  4104. "50": "X_CACHE_HANDLER_NOT_SUPPORTED",
  4105. "X_SCOPE_ID_NOT_SUPPORTED": 51,
  4106. "51": "X_SCOPE_ID_NOT_SUPPORTED",
  4107. "X_VNODE_HOOKS": 52,
  4108. "52": "X_VNODE_HOOKS",
  4109. "X_V_BIND_INVALID_SAME_NAME_ARGUMENT": 53,
  4110. "53": "X_V_BIND_INVALID_SAME_NAME_ARGUMENT",
  4111. "__EXTEND_POINT__": 54,
  4112. "54": "__EXTEND_POINT__"
  4113. };
  4114. const errorMessages$1 = {
  4115. // parse errors
  4116. [0]: "Illegal comment.",
  4117. [1]: "CDATA section is allowed only in XML context.",
  4118. [2]: "Duplicate attribute.",
  4119. [3]: "End tag cannot have attributes.",
  4120. [4]: "Illegal '/' in tags.",
  4121. [5]: "Unexpected EOF in tag.",
  4122. [6]: "Unexpected EOF in CDATA section.",
  4123. [7]: "Unexpected EOF in comment.",
  4124. [8]: "Unexpected EOF in script.",
  4125. [9]: "Unexpected EOF in tag.",
  4126. [10]: "Incorrectly closed comment.",
  4127. [11]: "Incorrectly opened comment.",
  4128. [12]: "Illegal tag name. Use '&lt;' to print '<'.",
  4129. [13]: "Attribute value was expected.",
  4130. [14]: "End tag name was expected.",
  4131. [15]: "Whitespace was expected.",
  4132. [16]: "Unexpected '<!--' in comment.",
  4133. [17]: `Attribute name cannot contain U+0022 ("), U+0027 ('), and U+003C (<).`,
  4134. [18]: "Unquoted attribute value cannot contain U+0022 (\"), U+0027 ('), U+003C (<), U+003D (=), and U+0060 (`).",
  4135. [19]: "Attribute name cannot start with '='.",
  4136. [21]: "'<?' is allowed only in XML context.",
  4137. [20]: `Unexpected null character.`,
  4138. [22]: "Illegal '/' in tags.",
  4139. // Vue-specific parse errors
  4140. [23]: "Invalid end tag.",
  4141. [24]: "Element is missing end tag.",
  4142. [25]: "Interpolation end sign was not found.",
  4143. [27]: "End bracket for dynamic directive argument was not found. Note that dynamic directive argument cannot contain spaces.",
  4144. [26]: "Legal directive name was expected.",
  4145. // transform errors
  4146. [28]: `v-if/v-else-if is missing expression.`,
  4147. [29]: `v-if/else branches must use unique keys.`,
  4148. [30]: `v-else/v-else-if has no adjacent v-if or v-else-if.`,
  4149. [31]: `v-for is missing expression.`,
  4150. [32]: `v-for has invalid expression.`,
  4151. [33]: `<template v-for> key should be placed on the <template> tag.`,
  4152. [34]: `v-bind is missing expression.`,
  4153. [53]: `v-bind with same-name shorthand only allows static argument.`,
  4154. [35]: `v-on is missing expression.`,
  4155. [36]: `Unexpected custom directive on <slot> outlet.`,
  4156. [37]: `Mixed v-slot usage on both the component and nested <template>. When there are multiple named slots, all slots should use <template> syntax to avoid scope ambiguity.`,
  4157. [38]: `Duplicate slot names found. `,
  4158. [39]: `Extraneous children found when component already has explicitly named default slot. These children will be ignored.`,
  4159. [40]: `v-slot can only be used on components or <template> tags.`,
  4160. [41]: `v-model is missing expression.`,
  4161. [42]: `v-model value must be a valid JavaScript member expression.`,
  4162. [43]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
  4163. [44]: `v-model cannot be used on a prop, because local prop bindings are not writable.
  4164. Use a v-bind binding combined with a v-on listener that emits update:x event instead.`,
  4165. [45]: `v-model cannot be used on a const binding because it is not writable.`,
  4166. [46]: `Error parsing JavaScript expression: `,
  4167. [47]: `<KeepAlive> expects exactly one child component.`,
  4168. [52]: `@vnode-* hooks in templates are no longer supported. Use the vue: prefix instead. For example, @vnode-mounted should be changed to @vue:mounted. @vnode-* hooks support has been removed in 3.4.`,
  4169. // generic errors
  4170. [48]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
  4171. [49]: `ES module mode is not supported in this build of compiler.`,
  4172. [50]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
  4173. [51]: `"scopeId" option is only supported in module mode.`,
  4174. // just to fulfill types
  4175. [54]: ``
  4176. };
  4177. function getDefaultExportFromCjs (x) {
  4178. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  4179. }
  4180. function getAugmentedNamespace(n) {
  4181. if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n;
  4182. var f = n.default;
  4183. if (typeof f == "function") {
  4184. var a = function a () {
  4185. var isInstance = false;
  4186. try {
  4187. isInstance = this instanceof a;
  4188. } catch {}
  4189. if (isInstance) {
  4190. return Reflect.construct(f, arguments, this.constructor);
  4191. }
  4192. return f.apply(this, arguments);
  4193. };
  4194. a.prototype = f.prototype;
  4195. } else a = {};
  4196. Object.defineProperty(a, '__esModule', {value: true});
  4197. Object.keys(n).forEach(function (k) {
  4198. var d = Object.getOwnPropertyDescriptor(n, k);
  4199. Object.defineProperty(a, k, d.get ? d : {
  4200. enumerable: true,
  4201. get: function () {
  4202. return n[k];
  4203. }
  4204. });
  4205. });
  4206. return a;
  4207. }
  4208. var lib = {};
  4209. var hasRequiredLib;
  4210. function requireLib () {
  4211. if (hasRequiredLib) return lib;
  4212. hasRequiredLib = 1;
  4213. Object.defineProperty(lib, '__esModule', {
  4214. value: true
  4215. });
  4216. function _objectWithoutPropertiesLoose(r, e) {
  4217. if (null == r) return {};
  4218. var t = {};
  4219. for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
  4220. if (-1 !== e.indexOf(n)) continue;
  4221. t[n] = r[n];
  4222. }
  4223. return t;
  4224. }
  4225. class Position {
  4226. constructor(line, col, index) {
  4227. this.line = void 0;
  4228. this.column = void 0;
  4229. this.index = void 0;
  4230. this.line = line;
  4231. this.column = col;
  4232. this.index = index;
  4233. }
  4234. }
  4235. class SourceLocation {
  4236. constructor(start, end) {
  4237. this.start = void 0;
  4238. this.end = void 0;
  4239. this.filename = void 0;
  4240. this.identifierName = void 0;
  4241. this.start = start;
  4242. this.end = end;
  4243. }
  4244. }
  4245. function createPositionWithColumnOffset(position, columnOffset) {
  4246. const {
  4247. line,
  4248. column,
  4249. index
  4250. } = position;
  4251. return new Position(line, column + columnOffset, index + columnOffset);
  4252. }
  4253. const code = "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED";
  4254. var ModuleErrors = {
  4255. ImportMetaOutsideModule: {
  4256. message: `import.meta may appear only with 'sourceType: "module"'`,
  4257. code
  4258. },
  4259. ImportOutsideModule: {
  4260. message: `'import' and 'export' may appear only with 'sourceType: "module"'`,
  4261. code
  4262. }
  4263. };
  4264. const NodeDescriptions = {
  4265. ArrayPattern: "array destructuring pattern",
  4266. AssignmentExpression: "assignment expression",
  4267. AssignmentPattern: "assignment expression",
  4268. ArrowFunctionExpression: "arrow function expression",
  4269. ConditionalExpression: "conditional expression",
  4270. CatchClause: "catch clause",
  4271. ForOfStatement: "for-of statement",
  4272. ForInStatement: "for-in statement",
  4273. ForStatement: "for-loop",
  4274. FormalParameters: "function parameter list",
  4275. Identifier: "identifier",
  4276. ImportSpecifier: "import specifier",
  4277. ImportDefaultSpecifier: "import default specifier",
  4278. ImportNamespaceSpecifier: "import namespace specifier",
  4279. ObjectPattern: "object destructuring pattern",
  4280. ParenthesizedExpression: "parenthesized expression",
  4281. RestElement: "rest element",
  4282. UpdateExpression: {
  4283. true: "prefix operation",
  4284. false: "postfix operation"
  4285. },
  4286. VariableDeclarator: "variable declaration",
  4287. YieldExpression: "yield expression"
  4288. };
  4289. const toNodeDescription = node => node.type === "UpdateExpression" ? NodeDescriptions.UpdateExpression[`${node.prefix}`] : NodeDescriptions[node.type];
  4290. var StandardErrors = {
  4291. AccessorIsGenerator: ({
  4292. kind
  4293. }) => `A ${kind}ter cannot be a generator.`,
  4294. ArgumentsInClass: "'arguments' is only allowed in functions and class methods.",
  4295. AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block.",
  4296. AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function.",
  4297. AwaitBindingIdentifierInStaticBlock: "Can not use 'await' as identifier inside a static block.",
  4298. AwaitExpressionFormalParameter: "'await' is not allowed in async function parameters.",
  4299. AwaitUsingNotInAsyncContext: "'await using' is only allowed within async functions and at the top levels of modules.",
  4300. AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules.",
  4301. BadGetterArity: "A 'get' accessor must not have any formal parameters.",
  4302. BadSetterArity: "A 'set' accessor must have exactly one formal parameter.",
  4303. BadSetterRestParameter: "A 'set' accessor function argument must not be a rest parameter.",
  4304. ConstructorClassField: "Classes may not have a field named 'constructor'.",
  4305. ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'.",
  4306. ConstructorIsAccessor: "Class constructor may not be an accessor.",
  4307. ConstructorIsAsync: "Constructor can't be an async function.",
  4308. ConstructorIsGenerator: "Constructor can't be a generator.",
  4309. DeclarationMissingInitializer: ({
  4310. kind
  4311. }) => `Missing initializer in ${kind} declaration.`,
  4312. DecoratorArgumentsOutsideParentheses: "Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.",
  4313. DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.",
  4314. DecoratorsBeforeAfterExport: "Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.",
  4315. DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",
  4316. DecoratorExportClass: "Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.",
  4317. DecoratorSemicolon: "Decorators must not be followed by a semicolon.",
  4318. DecoratorStaticBlock: "Decorators can't be used with a static block.",
  4319. DeferImportRequiresNamespace: 'Only `import defer * as x from "./module"` is valid.',
  4320. DeletePrivateField: "Deleting a private field is not allowed.",
  4321. DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.",
  4322. DuplicateConstructor: "Duplicate constructor in the same class.",
  4323. DuplicateDefaultExport: "Only one default export allowed per module.",
  4324. DuplicateExport: ({
  4325. exportName
  4326. }) => `\`${exportName}\` has already been exported. Exported identifiers must be unique.`,
  4327. DuplicateProto: "Redefinition of __proto__ property.",
  4328. DuplicateRegExpFlags: "Duplicate regular expression flag.",
  4329. ElementAfterRest: "Rest element must be last element.",
  4330. EscapedCharNotAnIdentifier: "Invalid Unicode escape.",
  4331. ExportBindingIsString: ({
  4332. localName,
  4333. exportName
  4334. }) => `A string literal cannot be used as an exported binding without \`from\`.\n- Did you mean \`export { '${localName}' as '${exportName}' } from 'some-module'\`?`,
  4335. ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'.",
  4336. ForInOfLoopInitializer: ({
  4337. type
  4338. }) => `'${type === "ForInStatement" ? "for-in" : "for-of"}' loop variable declaration may not have an initializer.`,
  4339. ForInUsing: "For-in loop may not start with 'using' declaration.",
  4340. ForOfAsync: "The left-hand side of a for-of loop may not be 'async'.",
  4341. ForOfLet: "The left-hand side of a for-of loop may not start with 'let'.",
  4342. GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block.",
  4343. IllegalBreakContinue: ({
  4344. type
  4345. }) => `Unsyntactic ${type === "BreakStatement" ? "break" : "continue"}.`,
  4346. IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list.",
  4347. IllegalReturn: "'return' outside of function.",
  4348. ImportAttributesUseAssert: "The `assert` keyword in import attributes is deprecated and it has been replaced by the `with` keyword. You can enable the `deprecatedImportAssert` parser plugin to suppress this error.",
  4349. ImportBindingIsString: ({
  4350. importName
  4351. }) => `A string literal cannot be used as an imported binding.\n- Did you mean \`import { "${importName}" as foo }\`?`,
  4352. ImportCallArity: `\`import()\` requires exactly one or two arguments.`,
  4353. ImportCallNotNewExpression: "Cannot use new with import(...).",
  4354. ImportCallSpreadArgument: "`...` is not allowed in `import()`.",
  4355. ImportJSONBindingNotDefault: "A JSON module can only be imported with `default`.",
  4356. ImportReflectionHasAssertion: "`import module x` cannot have assertions.",
  4357. ImportReflectionNotBinding: 'Only `import module x from "./module"` is valid.',
  4358. IncompatibleRegExpUVFlags: "The 'u' and 'v' regular expression flags cannot be enabled at the same time.",
  4359. InvalidBigIntLiteral: "Invalid BigIntLiteral.",
  4360. InvalidCodePoint: "Code point out of bounds.",
  4361. InvalidCoverDiscardElement: "'void' must be followed by an expression when not used in a binding position.",
  4362. InvalidCoverInitializedName: "Invalid shorthand property initializer.",
  4363. InvalidDecimal: "Invalid decimal.",
  4364. InvalidDigit: ({
  4365. radix
  4366. }) => `Expected number in radix ${radix}.`,
  4367. InvalidEscapeSequence: "Bad character escape sequence.",
  4368. InvalidEscapeSequenceTemplate: "Invalid escape sequence in template.",
  4369. InvalidEscapedReservedWord: ({
  4370. reservedWord
  4371. }) => `Escape sequence in keyword ${reservedWord}.`,
  4372. InvalidIdentifier: ({
  4373. identifierName
  4374. }) => `Invalid identifier ${identifierName}.`,
  4375. InvalidLhs: ({
  4376. ancestor
  4377. }) => `Invalid left-hand side in ${toNodeDescription(ancestor)}.`,
  4378. InvalidLhsBinding: ({
  4379. ancestor
  4380. }) => `Binding invalid left-hand side in ${toNodeDescription(ancestor)}.`,
  4381. InvalidLhsOptionalChaining: ({
  4382. ancestor
  4383. }) => `Invalid optional chaining in the left-hand side of ${toNodeDescription(ancestor)}.`,
  4384. InvalidNumber: "Invalid number.",
  4385. InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'.",
  4386. InvalidOrUnexpectedToken: ({
  4387. unexpected
  4388. }) => `Unexpected character '${unexpected}'.`,
  4389. InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern.",
  4390. InvalidPrivateFieldResolution: ({
  4391. identifierName
  4392. }) => `Private name #${identifierName} is not defined.`,
  4393. InvalidPropertyBindingPattern: "Binding member expression.",
  4394. InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions.",
  4395. InvalidRestAssignmentPattern: "Invalid rest operator's argument.",
  4396. LabelRedeclaration: ({
  4397. labelName
  4398. }) => `Label '${labelName}' is already declared.`,
  4399. LetInLexicalBinding: "'let' is disallowed as a lexically bound name.",
  4400. LineTerminatorBeforeArrow: "No line break is allowed before '=>'.",
  4401. MalformedRegExpFlags: "Invalid regular expression flag.",
  4402. MissingClassName: "A class name is required.",
  4403. MissingEqInAssignment: "Only '=' operator can be used for specifying default value.",
  4404. MissingSemicolon: "Missing semicolon.",
  4405. MissingPlugin: ({
  4406. missingPlugin
  4407. }) => `This experimental syntax requires enabling the parser plugin: ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`,
  4408. MissingOneOfPlugins: ({
  4409. missingPlugin
  4410. }) => `This experimental syntax requires enabling one of the following parser plugin(s): ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`,
  4411. MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX.",
  4412. MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators.",
  4413. ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`.",
  4414. ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values.",
  4415. ModuleAttributesWithDuplicateKeys: ({
  4416. key
  4417. }) => `Duplicate key "${key}" is not allowed in module attributes.`,
  4418. ModuleExportNameHasLoneSurrogate: ({
  4419. surrogateCharCode
  4420. }) => `An export name cannot include a lone surrogate, found '\\u${surrogateCharCode.toString(16)}'.`,
  4421. ModuleExportUndefined: ({
  4422. localName
  4423. }) => `Export '${localName}' is not defined.`,
  4424. MultipleDefaultsInSwitch: "Multiple default clauses.",
  4425. NewlineAfterThrow: "Illegal newline after throw.",
  4426. NoCatchOrFinally: "Missing catch or finally clause.",
  4427. NumberIdentifier: "Identifier directly after number.",
  4428. NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.",
  4429. ObsoleteAwaitStar: "'await*' has been removed from the async functions proposal. Use Promise.all() instead.",
  4430. OptionalChainingNoNew: "Constructors in/after an Optional Chain are not allowed.",
  4431. OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain.",
  4432. OverrideOnConstructor: "'override' modifier cannot appear on a constructor declaration.",
  4433. ParamDupe: "Argument name clash.",
  4434. PatternHasAccessor: "Object pattern can't contain getter or setter.",
  4435. PatternHasMethod: "Object pattern can't contain methods.",
  4436. PrivateInExpectedIn: ({
  4437. identifierName
  4438. }) => `Private names are only allowed in property accesses (\`obj.#${identifierName}\`) or in \`in\` expressions (\`#${identifierName} in obj\`).`,
  4439. PrivateNameRedeclaration: ({
  4440. identifierName
  4441. }) => `Duplicate private name #${identifierName}.`,
  4442. RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  4443. RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  4444. RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",
  4445. RecordNoProto: "'__proto__' is not allowed in Record expressions.",
  4446. RestTrailingComma: "Unexpected trailing comma after rest element.",
  4447. SloppyFunction: "In non-strict mode code, functions can only be declared at top level or inside a block.",
  4448. SloppyFunctionAnnexB: "In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.",
  4449. SourcePhaseImportRequiresDefault: 'Only `import source x from "./module"` is valid.',
  4450. StaticPrototype: "Classes may not have static property named prototype.",
  4451. SuperNotAllowed: "`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?",
  4452. SuperPrivateField: "Private fields can't be accessed on super.",
  4453. TrailingDecorator: "Decorators must be attached to a class element.",
  4454. TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  4455. TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  4456. TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",
  4457. UnexpectedArgumentPlaceholder: "Unexpected argument placeholder.",
  4458. UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal.',
  4459. UnexpectedDigitAfterHash: "Unexpected digit after hash token.",
  4460. UnexpectedImportExport: "'import' and 'export' may only appear at the top level.",
  4461. UnexpectedKeyword: ({
  4462. keyword
  4463. }) => `Unexpected keyword '${keyword}'.`,
  4464. UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration.",
  4465. UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context.",
  4466. UnexpectedNewTarget: "`new.target` can only be used in functions or class properties.",
  4467. UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits.",
  4468. UnexpectedPrivateField: "Unexpected private name.",
  4469. UnexpectedReservedWord: ({
  4470. reservedWord
  4471. }) => `Unexpected reserved word '${reservedWord}'.`,
  4472. UnexpectedSuper: "'super' is only allowed in object methods and classes.",
  4473. UnexpectedToken: ({
  4474. expected,
  4475. unexpected
  4476. }) => `Unexpected token${unexpected ? ` '${unexpected}'.` : ""}${expected ? `, expected "${expected}"` : ""}`,
  4477. UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",
  4478. UnexpectedUsingDeclaration: "Using declaration cannot appear in the top level when source type is `script` or in the bare case statement.",
  4479. UnexpectedVoidPattern: "Unexpected void binding.",
  4480. UnsupportedBind: "Binding should be performed on object property.",
  4481. UnsupportedDecoratorExport: "A decorated export must export a class declaration.",
  4482. UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.",
  4483. UnsupportedImport: "`import` can only be used in `import()` or `import.meta`.",
  4484. UnsupportedMetaProperty: ({
  4485. target,
  4486. onlyValidPropertyName
  4487. }) => `The only valid meta property for ${target} is ${target}.${onlyValidPropertyName}.`,
  4488. UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters.",
  4489. UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties.",
  4490. UnsupportedSuper: "'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).",
  4491. UnterminatedComment: "Unterminated comment.",
  4492. UnterminatedRegExp: "Unterminated regular expression.",
  4493. UnterminatedString: "Unterminated string constant.",
  4494. UnterminatedTemplate: "Unterminated template.",
  4495. UsingDeclarationExport: "Using declaration cannot be exported.",
  4496. UsingDeclarationHasBindingPattern: "Using declaration cannot have destructuring patterns.",
  4497. VarRedeclaration: ({
  4498. identifierName
  4499. }) => `Identifier '${identifierName}' has already been declared.`,
  4500. VoidPatternCatchClauseParam: "A void binding can not be the catch clause parameter. Use `try { ... } catch { ... }` if you want to discard the caught error.",
  4501. VoidPatternInitializer: "A void binding may not have an initializer.",
  4502. YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator.",
  4503. YieldInParameter: "Yield expression is not allowed in formal parameters.",
  4504. YieldNotInGeneratorFunction: "'yield' is only allowed within generator functions.",
  4505. ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0."
  4506. };
  4507. var StrictModeErrors = {
  4508. StrictDelete: "Deleting local variable in strict mode.",
  4509. StrictEvalArguments: ({
  4510. referenceName
  4511. }) => `Assigning to '${referenceName}' in strict mode.`,
  4512. StrictEvalArgumentsBinding: ({
  4513. bindingName
  4514. }) => `Binding '${bindingName}' in strict mode.`,
  4515. StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block.",
  4516. StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'.",
  4517. StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode.",
  4518. StrictWith: "'with' in strict mode."
  4519. };
  4520. var ParseExpressionErrors = {
  4521. ParseExpressionEmptyInput: "Unexpected parseExpression() input: The input is empty or contains only comments.",
  4522. ParseExpressionExpectsEOF: ({
  4523. unexpected
  4524. }) => `Unexpected parseExpression() input: The input should contain exactly one expression, but the first expression is followed by the unexpected character \`${String.fromCodePoint(unexpected)}\`.`
  4525. };
  4526. const UnparenthesizedPipeBodyDescriptions = new Set(["ArrowFunctionExpression", "AssignmentExpression", "ConditionalExpression", "YieldExpression"]);
  4527. var PipelineOperatorErrors = Object.assign({
  4528. PipeBodyIsTighter: "Unexpected yield after pipeline body; any yield expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.",
  4529. PipeTopicRequiresHackPipes: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.',
  4530. PipeTopicUnbound: "Topic reference is unbound; it must be inside a pipe body.",
  4531. PipeTopicUnconfiguredToken: ({
  4532. token
  4533. }) => `Invalid topic token ${token}. In order to use ${token} as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "${token}" }.`,
  4534. PipeTopicUnused: "Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.",
  4535. PipeUnparenthesizedBody: ({
  4536. type
  4537. }) => `Hack-style pipe body cannot be an unparenthesized ${toNodeDescription({
  4538. type
  4539. })}; please wrap it in parentheses.`
  4540. }, {
  4541. PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized.',
  4542. PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression.",
  4543. PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression.",
  4544. PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference.",
  4545. PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding.",
  4546. PrimaryTopicRequiresSmartPipeline: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.'
  4547. });
  4548. const _excluded = ["message"];
  4549. function defineHidden(obj, key, value) {
  4550. Object.defineProperty(obj, key, {
  4551. enumerable: false,
  4552. configurable: true,
  4553. value
  4554. });
  4555. }
  4556. function toParseErrorConstructor({
  4557. toMessage,
  4558. code,
  4559. reasonCode,
  4560. syntaxPlugin
  4561. }) {
  4562. const hasMissingPlugin = reasonCode === "MissingPlugin" || reasonCode === "MissingOneOfPlugins";
  4563. const oldReasonCodes = {
  4564. AccessorCannotDeclareThisParameter: "AccesorCannotDeclareThisParameter",
  4565. AccessorCannotHaveTypeParameters: "AccesorCannotHaveTypeParameters",
  4566. ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference: "ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference",
  4567. SetAccessorCannotHaveOptionalParameter: "SetAccesorCannotHaveOptionalParameter",
  4568. SetAccessorCannotHaveRestParameter: "SetAccesorCannotHaveRestParameter",
  4569. SetAccessorCannotHaveReturnType: "SetAccesorCannotHaveReturnType"
  4570. };
  4571. if (oldReasonCodes[reasonCode]) {
  4572. reasonCode = oldReasonCodes[reasonCode];
  4573. }
  4574. return function constructor(loc, details) {
  4575. const error = new SyntaxError();
  4576. error.code = code;
  4577. error.reasonCode = reasonCode;
  4578. error.loc = loc;
  4579. error.pos = loc.index;
  4580. error.syntaxPlugin = syntaxPlugin;
  4581. if (hasMissingPlugin) {
  4582. error.missingPlugin = details.missingPlugin;
  4583. }
  4584. defineHidden(error, "clone", function clone(overrides = {}) {
  4585. var _overrides$loc;
  4586. const {
  4587. line,
  4588. column,
  4589. index
  4590. } = (_overrides$loc = overrides.loc) != null ? _overrides$loc : loc;
  4591. return constructor(new Position(line, column, index), Object.assign({}, details, overrides.details));
  4592. });
  4593. defineHidden(error, "details", details);
  4594. Object.defineProperty(error, "message", {
  4595. configurable: true,
  4596. get() {
  4597. const message = `${toMessage(details)} (${loc.line}:${loc.column})`;
  4598. this.message = message;
  4599. return message;
  4600. },
  4601. set(value) {
  4602. Object.defineProperty(this, "message", {
  4603. value,
  4604. writable: true
  4605. });
  4606. }
  4607. });
  4608. return error;
  4609. };
  4610. }
  4611. function ParseErrorEnum(argument, syntaxPlugin) {
  4612. if (Array.isArray(argument)) {
  4613. return parseErrorTemplates => ParseErrorEnum(parseErrorTemplates, argument[0]);
  4614. }
  4615. const ParseErrorConstructors = {};
  4616. for (const reasonCode of Object.keys(argument)) {
  4617. const template = argument[reasonCode];
  4618. const _ref = typeof template === "string" ? {
  4619. message: () => template
  4620. } : typeof template === "function" ? {
  4621. message: template
  4622. } : template,
  4623. {
  4624. message
  4625. } = _ref,
  4626. rest = _objectWithoutPropertiesLoose(_ref, _excluded);
  4627. const toMessage = typeof message === "string" ? () => message : message;
  4628. ParseErrorConstructors[reasonCode] = toParseErrorConstructor(Object.assign({
  4629. code: "BABEL_PARSER_SYNTAX_ERROR",
  4630. reasonCode,
  4631. toMessage
  4632. }, syntaxPlugin ? {
  4633. syntaxPlugin
  4634. } : {}, rest));
  4635. }
  4636. return ParseErrorConstructors;
  4637. }
  4638. const Errors = Object.assign({}, ParseErrorEnum(ModuleErrors), ParseErrorEnum(StandardErrors), ParseErrorEnum(StrictModeErrors), ParseErrorEnum(ParseExpressionErrors), ParseErrorEnum`pipelineOperator`(PipelineOperatorErrors));
  4639. function createDefaultOptions() {
  4640. return {
  4641. sourceType: "script",
  4642. sourceFilename: undefined,
  4643. startIndex: 0,
  4644. startColumn: 0,
  4645. startLine: 1,
  4646. allowAwaitOutsideFunction: false,
  4647. allowReturnOutsideFunction: false,
  4648. allowNewTargetOutsideFunction: false,
  4649. allowImportExportEverywhere: false,
  4650. allowSuperOutsideMethod: false,
  4651. allowUndeclaredExports: false,
  4652. allowYieldOutsideFunction: false,
  4653. plugins: [],
  4654. strictMode: undefined,
  4655. ranges: false,
  4656. tokens: false,
  4657. createImportExpressions: false,
  4658. createParenthesizedExpressions: false,
  4659. errorRecovery: false,
  4660. attachComment: true,
  4661. annexB: true
  4662. };
  4663. }
  4664. function getOptions(opts) {
  4665. const options = createDefaultOptions();
  4666. if (opts == null) {
  4667. return options;
  4668. }
  4669. if (opts.annexB != null && opts.annexB !== false) {
  4670. throw new Error("The `annexB` option can only be set to `false`.");
  4671. }
  4672. for (const key of Object.keys(options)) {
  4673. if (opts[key] != null) options[key] = opts[key];
  4674. }
  4675. if (options.startLine === 1) {
  4676. if (opts.startIndex == null && options.startColumn > 0) {
  4677. options.startIndex = options.startColumn;
  4678. } else if (opts.startColumn == null && options.startIndex > 0) {
  4679. options.startColumn = options.startIndex;
  4680. }
  4681. } else if (opts.startColumn == null || opts.startIndex == null) {
  4682. if (opts.startIndex != null) {
  4683. throw new Error("With a `startLine > 1` you must also specify `startIndex` and `startColumn`.");
  4684. }
  4685. }
  4686. if (options.sourceType === "commonjs") {
  4687. if (opts.allowAwaitOutsideFunction != null) {
  4688. throw new Error("The `allowAwaitOutsideFunction` option cannot be used with `sourceType: 'commonjs'`.");
  4689. }
  4690. if (opts.allowReturnOutsideFunction != null) {
  4691. throw new Error("`sourceType: 'commonjs'` implies `allowReturnOutsideFunction: true`, please remove the `allowReturnOutsideFunction` option or use `sourceType: 'script'`.");
  4692. }
  4693. if (opts.allowNewTargetOutsideFunction != null) {
  4694. throw new Error("`sourceType: 'commonjs'` implies `allowNewTargetOutsideFunction: true`, please remove the `allowNewTargetOutsideFunction` option or use `sourceType: 'script'`.");
  4695. }
  4696. }
  4697. return options;
  4698. }
  4699. const {
  4700. defineProperty
  4701. } = Object;
  4702. const toUnenumerable = (object, key) => {
  4703. if (object) {
  4704. defineProperty(object, key, {
  4705. enumerable: false,
  4706. value: object[key]
  4707. });
  4708. }
  4709. };
  4710. function toESTreeLocation(node) {
  4711. toUnenumerable(node.loc.start, "index");
  4712. toUnenumerable(node.loc.end, "index");
  4713. return node;
  4714. }
  4715. var estree = superClass => class ESTreeParserMixin extends superClass {
  4716. parse() {
  4717. const file = toESTreeLocation(super.parse());
  4718. if (this.optionFlags & 256) {
  4719. file.tokens = file.tokens.map(toESTreeLocation);
  4720. }
  4721. return file;
  4722. }
  4723. parseRegExpLiteral({
  4724. pattern,
  4725. flags
  4726. }) {
  4727. let regex = null;
  4728. try {
  4729. regex = new RegExp(pattern, flags);
  4730. } catch (_) {}
  4731. const node = this.estreeParseLiteral(regex);
  4732. node.regex = {
  4733. pattern,
  4734. flags
  4735. };
  4736. return node;
  4737. }
  4738. parseBigIntLiteral(value) {
  4739. let bigInt;
  4740. try {
  4741. bigInt = BigInt(value);
  4742. } catch (_unused) {
  4743. bigInt = null;
  4744. }
  4745. const node = this.estreeParseLiteral(bigInt);
  4746. node.bigint = String(node.value || value);
  4747. return node;
  4748. }
  4749. parseDecimalLiteral(value) {
  4750. const decimal = null;
  4751. const node = this.estreeParseLiteral(decimal);
  4752. node.decimal = String(node.value || value);
  4753. return node;
  4754. }
  4755. estreeParseLiteral(value) {
  4756. return this.parseLiteral(value, "Literal");
  4757. }
  4758. parseStringLiteral(value) {
  4759. return this.estreeParseLiteral(value);
  4760. }
  4761. parseNumericLiteral(value) {
  4762. return this.estreeParseLiteral(value);
  4763. }
  4764. parseNullLiteral() {
  4765. return this.estreeParseLiteral(null);
  4766. }
  4767. parseBooleanLiteral(value) {
  4768. return this.estreeParseLiteral(value);
  4769. }
  4770. estreeParseChainExpression(node, endLoc) {
  4771. const chain = this.startNodeAtNode(node);
  4772. chain.expression = node;
  4773. return this.finishNodeAt(chain, "ChainExpression", endLoc);
  4774. }
  4775. directiveToStmt(directive) {
  4776. const expression = directive.value;
  4777. delete directive.value;
  4778. this.castNodeTo(expression, "Literal");
  4779. expression.raw = expression.extra.raw;
  4780. expression.value = expression.extra.expressionValue;
  4781. const stmt = this.castNodeTo(directive, "ExpressionStatement");
  4782. stmt.expression = expression;
  4783. stmt.directive = expression.extra.rawValue;
  4784. delete expression.extra;
  4785. return stmt;
  4786. }
  4787. fillOptionalPropertiesForTSESLint(node) {}
  4788. cloneEstreeStringLiteral(node) {
  4789. const {
  4790. start,
  4791. end,
  4792. loc,
  4793. range,
  4794. raw,
  4795. value
  4796. } = node;
  4797. const cloned = Object.create(node.constructor.prototype);
  4798. cloned.type = "Literal";
  4799. cloned.start = start;
  4800. cloned.end = end;
  4801. cloned.loc = loc;
  4802. cloned.range = range;
  4803. cloned.raw = raw;
  4804. cloned.value = value;
  4805. return cloned;
  4806. }
  4807. initFunction(node, isAsync) {
  4808. super.initFunction(node, isAsync);
  4809. node.expression = false;
  4810. }
  4811. checkDeclaration(node) {
  4812. if (node != null && this.isObjectProperty(node)) {
  4813. this.checkDeclaration(node.value);
  4814. } else {
  4815. super.checkDeclaration(node);
  4816. }
  4817. }
  4818. getObjectOrClassMethodParams(method) {
  4819. return method.value.params;
  4820. }
  4821. isValidDirective(stmt) {
  4822. var _stmt$expression$extr;
  4823. return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) != null && _stmt$expression$extr.parenthesized);
  4824. }
  4825. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  4826. super.parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse);
  4827. const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
  4828. node.body = directiveStatements.concat(node.body);
  4829. delete node.directives;
  4830. }
  4831. parsePrivateName() {
  4832. const node = super.parsePrivateName();
  4833. if (!this.getPluginOption("estree", "classFeatures")) {
  4834. return node;
  4835. }
  4836. return this.convertPrivateNameToPrivateIdentifier(node);
  4837. }
  4838. convertPrivateNameToPrivateIdentifier(node) {
  4839. const name = super.getPrivateNameSV(node);
  4840. delete node.id;
  4841. node.name = name;
  4842. return this.castNodeTo(node, "PrivateIdentifier");
  4843. }
  4844. isPrivateName(node) {
  4845. if (!this.getPluginOption("estree", "classFeatures")) {
  4846. return super.isPrivateName(node);
  4847. }
  4848. return node.type === "PrivateIdentifier";
  4849. }
  4850. getPrivateNameSV(node) {
  4851. if (!this.getPluginOption("estree", "classFeatures")) {
  4852. return super.getPrivateNameSV(node);
  4853. }
  4854. return node.name;
  4855. }
  4856. parseLiteral(value, type) {
  4857. const node = super.parseLiteral(value, type);
  4858. node.raw = node.extra.raw;
  4859. delete node.extra;
  4860. return node;
  4861. }
  4862. parseFunctionBody(node, allowExpression, isMethod = false) {
  4863. super.parseFunctionBody(node, allowExpression, isMethod);
  4864. node.expression = node.body.type !== "BlockStatement";
  4865. }
  4866. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  4867. let funcNode = this.startNode();
  4868. funcNode.kind = node.kind;
  4869. funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  4870. delete funcNode.kind;
  4871. const {
  4872. typeParameters
  4873. } = node;
  4874. if (typeParameters) {
  4875. delete node.typeParameters;
  4876. funcNode.typeParameters = typeParameters;
  4877. this.resetStartLocationFromNode(funcNode, typeParameters);
  4878. }
  4879. const valueNode = this.castNodeTo(funcNode, "FunctionExpression");
  4880. node.value = valueNode;
  4881. if (type === "ClassPrivateMethod") {
  4882. node.computed = false;
  4883. }
  4884. if (type === "ObjectMethod") {
  4885. if (node.kind === "method") {
  4886. node.kind = "init";
  4887. }
  4888. node.shorthand = false;
  4889. return this.finishNode(node, "Property");
  4890. } else {
  4891. return this.finishNode(node, "MethodDefinition");
  4892. }
  4893. }
  4894. nameIsConstructor(key) {
  4895. if (key.type === "Literal") return key.value === "constructor";
  4896. return super.nameIsConstructor(key);
  4897. }
  4898. parseClassProperty(...args) {
  4899. const propertyNode = super.parseClassProperty(...args);
  4900. if (!this.getPluginOption("estree", "classFeatures")) {
  4901. return propertyNode;
  4902. }
  4903. this.castNodeTo(propertyNode, "PropertyDefinition");
  4904. return propertyNode;
  4905. }
  4906. parseClassPrivateProperty(...args) {
  4907. const propertyNode = super.parseClassPrivateProperty(...args);
  4908. if (!this.getPluginOption("estree", "classFeatures")) {
  4909. return propertyNode;
  4910. }
  4911. this.castNodeTo(propertyNode, "PropertyDefinition");
  4912. propertyNode.computed = false;
  4913. return propertyNode;
  4914. }
  4915. parseClassAccessorProperty(node) {
  4916. const accessorPropertyNode = super.parseClassAccessorProperty(node);
  4917. if (!this.getPluginOption("estree", "classFeatures")) {
  4918. return accessorPropertyNode;
  4919. }
  4920. if (accessorPropertyNode.abstract && this.hasPlugin("typescript")) {
  4921. delete accessorPropertyNode.abstract;
  4922. this.castNodeTo(accessorPropertyNode, "TSAbstractAccessorProperty");
  4923. } else {
  4924. this.castNodeTo(accessorPropertyNode, "AccessorProperty");
  4925. }
  4926. return accessorPropertyNode;
  4927. }
  4928. parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) {
  4929. const node = super.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors);
  4930. if (node) {
  4931. node.kind = "init";
  4932. this.castNodeTo(node, "Property");
  4933. }
  4934. return node;
  4935. }
  4936. finishObjectProperty(node) {
  4937. node.kind = "init";
  4938. return this.finishNode(node, "Property");
  4939. }
  4940. isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding) {
  4941. return type === "Property" ? "value" : super.isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding);
  4942. }
  4943. isAssignable(node, isBinding) {
  4944. if (node != null && this.isObjectProperty(node)) {
  4945. return this.isAssignable(node.value, isBinding);
  4946. }
  4947. return super.isAssignable(node, isBinding);
  4948. }
  4949. toAssignable(node, isLHS = false) {
  4950. if (node != null && this.isObjectProperty(node)) {
  4951. const {
  4952. key,
  4953. value
  4954. } = node;
  4955. if (this.isPrivateName(key)) {
  4956. this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start);
  4957. }
  4958. this.toAssignable(value, isLHS);
  4959. } else {
  4960. super.toAssignable(node, isLHS);
  4961. }
  4962. }
  4963. toAssignableObjectExpressionProp(prop, isLast, isLHS) {
  4964. if (prop.type === "Property" && (prop.kind === "get" || prop.kind === "set")) {
  4965. this.raise(Errors.PatternHasAccessor, prop.key);
  4966. } else if (prop.type === "Property" && prop.method) {
  4967. this.raise(Errors.PatternHasMethod, prop.key);
  4968. } else {
  4969. super.toAssignableObjectExpressionProp(prop, isLast, isLHS);
  4970. }
  4971. }
  4972. finishCallExpression(unfinished, optional) {
  4973. const node = super.finishCallExpression(unfinished, optional);
  4974. if (node.callee.type === "Import") {
  4975. var _ref, _ref2;
  4976. this.castNodeTo(node, "ImportExpression");
  4977. node.source = node.arguments[0];
  4978. node.options = (_ref = node.arguments[1]) != null ? _ref : null;
  4979. node.attributes = (_ref2 = node.arguments[1]) != null ? _ref2 : null;
  4980. delete node.arguments;
  4981. delete node.callee;
  4982. } else if (node.type === "OptionalCallExpression") {
  4983. this.castNodeTo(node, "CallExpression");
  4984. } else {
  4985. node.optional = false;
  4986. }
  4987. return node;
  4988. }
  4989. toReferencedArguments(node) {
  4990. if (node.type === "ImportExpression") {
  4991. return;
  4992. }
  4993. super.toReferencedArguments(node);
  4994. }
  4995. parseExport(unfinished, decorators) {
  4996. const exportStartLoc = this.state.lastTokStartLoc;
  4997. const node = super.parseExport(unfinished, decorators);
  4998. switch (node.type) {
  4999. case "ExportAllDeclaration":
  5000. node.exported = null;
  5001. break;
  5002. case "ExportNamedDeclaration":
  5003. if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") {
  5004. this.castNodeTo(node, "ExportAllDeclaration");
  5005. node.exported = node.specifiers[0].exported;
  5006. delete node.specifiers;
  5007. }
  5008. case "ExportDefaultDeclaration":
  5009. {
  5010. var _declaration$decorato;
  5011. const {
  5012. declaration
  5013. } = node;
  5014. if ((declaration == null ? void 0 : declaration.type) === "ClassDeclaration" && ((_declaration$decorato = declaration.decorators) == null ? void 0 : _declaration$decorato.length) > 0 && declaration.start === node.start) {
  5015. this.resetStartLocation(node, exportStartLoc);
  5016. }
  5017. }
  5018. break;
  5019. }
  5020. return node;
  5021. }
  5022. stopParseSubscript(base, state) {
  5023. const node = super.stopParseSubscript(base, state);
  5024. if (state.optionalChainMember) {
  5025. return this.estreeParseChainExpression(node, base.loc.end);
  5026. }
  5027. return node;
  5028. }
  5029. parseMember(base, startLoc, state, computed, optional) {
  5030. const node = super.parseMember(base, startLoc, state, computed, optional);
  5031. if (node.type === "OptionalMemberExpression") {
  5032. this.castNodeTo(node, "MemberExpression");
  5033. } else {
  5034. node.optional = false;
  5035. }
  5036. return node;
  5037. }
  5038. isOptionalMemberExpression(node) {
  5039. if (node.type === "ChainExpression") {
  5040. return node.expression.type === "MemberExpression";
  5041. }
  5042. return super.isOptionalMemberExpression(node);
  5043. }
  5044. hasPropertyAsPrivateName(node) {
  5045. if (node.type === "ChainExpression") {
  5046. node = node.expression;
  5047. }
  5048. return super.hasPropertyAsPrivateName(node);
  5049. }
  5050. isObjectProperty(node) {
  5051. return node.type === "Property" && node.kind === "init" && !node.method;
  5052. }
  5053. isObjectMethod(node) {
  5054. return node.type === "Property" && (node.method || node.kind === "get" || node.kind === "set");
  5055. }
  5056. castNodeTo(node, type) {
  5057. const result = super.castNodeTo(node, type);
  5058. this.fillOptionalPropertiesForTSESLint(result);
  5059. return result;
  5060. }
  5061. cloneIdentifier(node) {
  5062. const cloned = super.cloneIdentifier(node);
  5063. this.fillOptionalPropertiesForTSESLint(cloned);
  5064. return cloned;
  5065. }
  5066. cloneStringLiteral(node) {
  5067. if (node.type === "Literal") {
  5068. return this.cloneEstreeStringLiteral(node);
  5069. }
  5070. return super.cloneStringLiteral(node);
  5071. }
  5072. finishNodeAt(node, type, endLoc) {
  5073. return toESTreeLocation(super.finishNodeAt(node, type, endLoc));
  5074. }
  5075. finishNode(node, type) {
  5076. const result = super.finishNode(node, type);
  5077. this.fillOptionalPropertiesForTSESLint(result);
  5078. return result;
  5079. }
  5080. resetStartLocation(node, startLoc) {
  5081. super.resetStartLocation(node, startLoc);
  5082. toESTreeLocation(node);
  5083. }
  5084. resetEndLocation(node, endLoc = this.state.lastTokEndLoc) {
  5085. super.resetEndLocation(node, endLoc);
  5086. toESTreeLocation(node);
  5087. }
  5088. };
  5089. class TokContext {
  5090. constructor(token, preserveSpace) {
  5091. this.token = void 0;
  5092. this.preserveSpace = void 0;
  5093. this.token = token;
  5094. this.preserveSpace = !!preserveSpace;
  5095. }
  5096. }
  5097. const types = {
  5098. brace: new TokContext("{"),
  5099. j_oTag: new TokContext("<tag"),
  5100. j_cTag: new TokContext("</tag"),
  5101. j_expr: new TokContext("<tag>...</tag>", true)
  5102. };
  5103. types.template = new TokContext("`", true);
  5104. const beforeExpr = true;
  5105. const startsExpr = true;
  5106. const isLoop = true;
  5107. const isAssign = true;
  5108. const prefix = true;
  5109. const postfix = true;
  5110. class ExportedTokenType {
  5111. constructor(label, conf = {}) {
  5112. this.label = void 0;
  5113. this.keyword = void 0;
  5114. this.beforeExpr = void 0;
  5115. this.startsExpr = void 0;
  5116. this.rightAssociative = void 0;
  5117. this.isLoop = void 0;
  5118. this.isAssign = void 0;
  5119. this.prefix = void 0;
  5120. this.postfix = void 0;
  5121. this.binop = void 0;
  5122. this.label = label;
  5123. this.keyword = conf.keyword;
  5124. this.beforeExpr = !!conf.beforeExpr;
  5125. this.startsExpr = !!conf.startsExpr;
  5126. this.rightAssociative = !!conf.rightAssociative;
  5127. this.isLoop = !!conf.isLoop;
  5128. this.isAssign = !!conf.isAssign;
  5129. this.prefix = !!conf.prefix;
  5130. this.postfix = !!conf.postfix;
  5131. this.binop = conf.binop != null ? conf.binop : null;
  5132. this.updateContext = null;
  5133. }
  5134. }
  5135. const keywords$1 = new Map();
  5136. function createKeyword(name, options = {}) {
  5137. options.keyword = name;
  5138. const token = createToken(name, options);
  5139. keywords$1.set(name, token);
  5140. return token;
  5141. }
  5142. function createBinop(name, binop) {
  5143. return createToken(name, {
  5144. beforeExpr,
  5145. binop
  5146. });
  5147. }
  5148. let tokenTypeCounter = -1;
  5149. const tokenTypes = [];
  5150. const tokenLabels = [];
  5151. const tokenBinops = [];
  5152. const tokenBeforeExprs = [];
  5153. const tokenStartsExprs = [];
  5154. const tokenPrefixes = [];
  5155. function createToken(name, options = {}) {
  5156. var _options$binop, _options$beforeExpr, _options$startsExpr, _options$prefix;
  5157. ++tokenTypeCounter;
  5158. tokenLabels.push(name);
  5159. tokenBinops.push((_options$binop = options.binop) != null ? _options$binop : -1);
  5160. tokenBeforeExprs.push((_options$beforeExpr = options.beforeExpr) != null ? _options$beforeExpr : false);
  5161. tokenStartsExprs.push((_options$startsExpr = options.startsExpr) != null ? _options$startsExpr : false);
  5162. tokenPrefixes.push((_options$prefix = options.prefix) != null ? _options$prefix : false);
  5163. tokenTypes.push(new ExportedTokenType(name, options));
  5164. return tokenTypeCounter;
  5165. }
  5166. function createKeywordLike(name, options = {}) {
  5167. var _options$binop2, _options$beforeExpr2, _options$startsExpr2, _options$prefix2;
  5168. ++tokenTypeCounter;
  5169. keywords$1.set(name, tokenTypeCounter);
  5170. tokenLabels.push(name);
  5171. tokenBinops.push((_options$binop2 = options.binop) != null ? _options$binop2 : -1);
  5172. tokenBeforeExprs.push((_options$beforeExpr2 = options.beforeExpr) != null ? _options$beforeExpr2 : false);
  5173. tokenStartsExprs.push((_options$startsExpr2 = options.startsExpr) != null ? _options$startsExpr2 : false);
  5174. tokenPrefixes.push((_options$prefix2 = options.prefix) != null ? _options$prefix2 : false);
  5175. tokenTypes.push(new ExportedTokenType("name", options));
  5176. return tokenTypeCounter;
  5177. }
  5178. const tt = {
  5179. bracketL: createToken("[", {
  5180. beforeExpr,
  5181. startsExpr
  5182. }),
  5183. bracketHashL: createToken("#[", {
  5184. beforeExpr,
  5185. startsExpr
  5186. }),
  5187. bracketBarL: createToken("[|", {
  5188. beforeExpr,
  5189. startsExpr
  5190. }),
  5191. bracketR: createToken("]"),
  5192. bracketBarR: createToken("|]"),
  5193. braceL: createToken("{", {
  5194. beforeExpr,
  5195. startsExpr
  5196. }),
  5197. braceBarL: createToken("{|", {
  5198. beforeExpr,
  5199. startsExpr
  5200. }),
  5201. braceHashL: createToken("#{", {
  5202. beforeExpr,
  5203. startsExpr
  5204. }),
  5205. braceR: createToken("}"),
  5206. braceBarR: createToken("|}"),
  5207. parenL: createToken("(", {
  5208. beforeExpr,
  5209. startsExpr
  5210. }),
  5211. parenR: createToken(")"),
  5212. comma: createToken(",", {
  5213. beforeExpr
  5214. }),
  5215. semi: createToken(";", {
  5216. beforeExpr
  5217. }),
  5218. colon: createToken(":", {
  5219. beforeExpr
  5220. }),
  5221. doubleColon: createToken("::", {
  5222. beforeExpr
  5223. }),
  5224. dot: createToken("."),
  5225. question: createToken("?", {
  5226. beforeExpr
  5227. }),
  5228. questionDot: createToken("?."),
  5229. arrow: createToken("=>", {
  5230. beforeExpr
  5231. }),
  5232. template: createToken("template"),
  5233. ellipsis: createToken("...", {
  5234. beforeExpr
  5235. }),
  5236. backQuote: createToken("`", {
  5237. startsExpr
  5238. }),
  5239. dollarBraceL: createToken("${", {
  5240. beforeExpr,
  5241. startsExpr
  5242. }),
  5243. templateTail: createToken("...`", {
  5244. startsExpr
  5245. }),
  5246. templateNonTail: createToken("...${", {
  5247. beforeExpr,
  5248. startsExpr
  5249. }),
  5250. at: createToken("@"),
  5251. hash: createToken("#", {
  5252. startsExpr
  5253. }),
  5254. interpreterDirective: createToken("#!..."),
  5255. eq: createToken("=", {
  5256. beforeExpr,
  5257. isAssign
  5258. }),
  5259. assign: createToken("_=", {
  5260. beforeExpr,
  5261. isAssign
  5262. }),
  5263. slashAssign: createToken("_=", {
  5264. beforeExpr,
  5265. isAssign
  5266. }),
  5267. xorAssign: createToken("_=", {
  5268. beforeExpr,
  5269. isAssign
  5270. }),
  5271. moduloAssign: createToken("_=", {
  5272. beforeExpr,
  5273. isAssign
  5274. }),
  5275. incDec: createToken("++/--", {
  5276. prefix,
  5277. postfix,
  5278. startsExpr
  5279. }),
  5280. bang: createToken("!", {
  5281. beforeExpr,
  5282. prefix,
  5283. startsExpr
  5284. }),
  5285. tilde: createToken("~", {
  5286. beforeExpr,
  5287. prefix,
  5288. startsExpr
  5289. }),
  5290. doubleCaret: createToken("^^", {
  5291. startsExpr
  5292. }),
  5293. doubleAt: createToken("@@", {
  5294. startsExpr
  5295. }),
  5296. pipeline: createBinop("|>", 0),
  5297. nullishCoalescing: createBinop("??", 1),
  5298. logicalOR: createBinop("||", 1),
  5299. logicalAND: createBinop("&&", 2),
  5300. bitwiseOR: createBinop("|", 3),
  5301. bitwiseXOR: createBinop("^", 4),
  5302. bitwiseAND: createBinop("&", 5),
  5303. equality: createBinop("==/!=/===/!==", 6),
  5304. lt: createBinop("</>/<=/>=", 7),
  5305. gt: createBinop("</>/<=/>=", 7),
  5306. relational: createBinop("</>/<=/>=", 7),
  5307. bitShift: createBinop("<</>>/>>>", 8),
  5308. bitShiftL: createBinop("<</>>/>>>", 8),
  5309. bitShiftR: createBinop("<</>>/>>>", 8),
  5310. plusMin: createToken("+/-", {
  5311. beforeExpr,
  5312. binop: 9,
  5313. prefix,
  5314. startsExpr
  5315. }),
  5316. modulo: createToken("%", {
  5317. binop: 10,
  5318. startsExpr
  5319. }),
  5320. star: createToken("*", {
  5321. binop: 10
  5322. }),
  5323. slash: createBinop("/", 10),
  5324. exponent: createToken("**", {
  5325. beforeExpr,
  5326. binop: 11,
  5327. rightAssociative: true
  5328. }),
  5329. _in: createKeyword("in", {
  5330. beforeExpr,
  5331. binop: 7
  5332. }),
  5333. _instanceof: createKeyword("instanceof", {
  5334. beforeExpr,
  5335. binop: 7
  5336. }),
  5337. _break: createKeyword("break"),
  5338. _case: createKeyword("case", {
  5339. beforeExpr
  5340. }),
  5341. _catch: createKeyword("catch"),
  5342. _continue: createKeyword("continue"),
  5343. _debugger: createKeyword("debugger"),
  5344. _default: createKeyword("default", {
  5345. beforeExpr
  5346. }),
  5347. _else: createKeyword("else", {
  5348. beforeExpr
  5349. }),
  5350. _finally: createKeyword("finally"),
  5351. _function: createKeyword("function", {
  5352. startsExpr
  5353. }),
  5354. _if: createKeyword("if"),
  5355. _return: createKeyword("return", {
  5356. beforeExpr
  5357. }),
  5358. _switch: createKeyword("switch"),
  5359. _throw: createKeyword("throw", {
  5360. beforeExpr,
  5361. prefix,
  5362. startsExpr
  5363. }),
  5364. _try: createKeyword("try"),
  5365. _var: createKeyword("var"),
  5366. _const: createKeyword("const"),
  5367. _with: createKeyword("with"),
  5368. _new: createKeyword("new", {
  5369. beforeExpr,
  5370. startsExpr
  5371. }),
  5372. _this: createKeyword("this", {
  5373. startsExpr
  5374. }),
  5375. _super: createKeyword("super", {
  5376. startsExpr
  5377. }),
  5378. _class: createKeyword("class", {
  5379. startsExpr
  5380. }),
  5381. _extends: createKeyword("extends", {
  5382. beforeExpr
  5383. }),
  5384. _export: createKeyword("export"),
  5385. _import: createKeyword("import", {
  5386. startsExpr
  5387. }),
  5388. _null: createKeyword("null", {
  5389. startsExpr
  5390. }),
  5391. _true: createKeyword("true", {
  5392. startsExpr
  5393. }),
  5394. _false: createKeyword("false", {
  5395. startsExpr
  5396. }),
  5397. _typeof: createKeyword("typeof", {
  5398. beforeExpr,
  5399. prefix,
  5400. startsExpr
  5401. }),
  5402. _void: createKeyword("void", {
  5403. beforeExpr,
  5404. prefix,
  5405. startsExpr
  5406. }),
  5407. _delete: createKeyword("delete", {
  5408. beforeExpr,
  5409. prefix,
  5410. startsExpr
  5411. }),
  5412. _do: createKeyword("do", {
  5413. isLoop,
  5414. beforeExpr
  5415. }),
  5416. _for: createKeyword("for", {
  5417. isLoop
  5418. }),
  5419. _while: createKeyword("while", {
  5420. isLoop
  5421. }),
  5422. _as: createKeywordLike("as", {
  5423. startsExpr
  5424. }),
  5425. _assert: createKeywordLike("assert", {
  5426. startsExpr
  5427. }),
  5428. _async: createKeywordLike("async", {
  5429. startsExpr
  5430. }),
  5431. _await: createKeywordLike("await", {
  5432. startsExpr
  5433. }),
  5434. _defer: createKeywordLike("defer", {
  5435. startsExpr
  5436. }),
  5437. _from: createKeywordLike("from", {
  5438. startsExpr
  5439. }),
  5440. _get: createKeywordLike("get", {
  5441. startsExpr
  5442. }),
  5443. _let: createKeywordLike("let", {
  5444. startsExpr
  5445. }),
  5446. _meta: createKeywordLike("meta", {
  5447. startsExpr
  5448. }),
  5449. _of: createKeywordLike("of", {
  5450. startsExpr
  5451. }),
  5452. _sent: createKeywordLike("sent", {
  5453. startsExpr
  5454. }),
  5455. _set: createKeywordLike("set", {
  5456. startsExpr
  5457. }),
  5458. _source: createKeywordLike("source", {
  5459. startsExpr
  5460. }),
  5461. _static: createKeywordLike("static", {
  5462. startsExpr
  5463. }),
  5464. _using: createKeywordLike("using", {
  5465. startsExpr
  5466. }),
  5467. _yield: createKeywordLike("yield", {
  5468. startsExpr
  5469. }),
  5470. _asserts: createKeywordLike("asserts", {
  5471. startsExpr
  5472. }),
  5473. _checks: createKeywordLike("checks", {
  5474. startsExpr
  5475. }),
  5476. _exports: createKeywordLike("exports", {
  5477. startsExpr
  5478. }),
  5479. _global: createKeywordLike("global", {
  5480. startsExpr
  5481. }),
  5482. _implements: createKeywordLike("implements", {
  5483. startsExpr
  5484. }),
  5485. _intrinsic: createKeywordLike("intrinsic", {
  5486. startsExpr
  5487. }),
  5488. _infer: createKeywordLike("infer", {
  5489. startsExpr
  5490. }),
  5491. _is: createKeywordLike("is", {
  5492. startsExpr
  5493. }),
  5494. _mixins: createKeywordLike("mixins", {
  5495. startsExpr
  5496. }),
  5497. _proto: createKeywordLike("proto", {
  5498. startsExpr
  5499. }),
  5500. _require: createKeywordLike("require", {
  5501. startsExpr
  5502. }),
  5503. _satisfies: createKeywordLike("satisfies", {
  5504. startsExpr
  5505. }),
  5506. _keyof: createKeywordLike("keyof", {
  5507. startsExpr
  5508. }),
  5509. _readonly: createKeywordLike("readonly", {
  5510. startsExpr
  5511. }),
  5512. _unique: createKeywordLike("unique", {
  5513. startsExpr
  5514. }),
  5515. _abstract: createKeywordLike("abstract", {
  5516. startsExpr
  5517. }),
  5518. _declare: createKeywordLike("declare", {
  5519. startsExpr
  5520. }),
  5521. _enum: createKeywordLike("enum", {
  5522. startsExpr
  5523. }),
  5524. _module: createKeywordLike("module", {
  5525. startsExpr
  5526. }),
  5527. _namespace: createKeywordLike("namespace", {
  5528. startsExpr
  5529. }),
  5530. _interface: createKeywordLike("interface", {
  5531. startsExpr
  5532. }),
  5533. _type: createKeywordLike("type", {
  5534. startsExpr
  5535. }),
  5536. _opaque: createKeywordLike("opaque", {
  5537. startsExpr
  5538. }),
  5539. name: createToken("name", {
  5540. startsExpr
  5541. }),
  5542. placeholder: createToken("%%", {
  5543. startsExpr
  5544. }),
  5545. string: createToken("string", {
  5546. startsExpr
  5547. }),
  5548. num: createToken("num", {
  5549. startsExpr
  5550. }),
  5551. bigint: createToken("bigint", {
  5552. startsExpr
  5553. }),
  5554. decimal: createToken("decimal", {
  5555. startsExpr
  5556. }),
  5557. regexp: createToken("regexp", {
  5558. startsExpr
  5559. }),
  5560. privateName: createToken("#name", {
  5561. startsExpr
  5562. }),
  5563. eof: createToken("eof"),
  5564. jsxName: createToken("jsxName"),
  5565. jsxText: createToken("jsxText", {
  5566. beforeExpr
  5567. }),
  5568. jsxTagStart: createToken("jsxTagStart", {
  5569. startsExpr
  5570. }),
  5571. jsxTagEnd: createToken("jsxTagEnd")
  5572. };
  5573. function tokenIsIdentifier(token) {
  5574. return token >= 93 && token <= 133;
  5575. }
  5576. function tokenKeywordOrIdentifierIsKeyword(token) {
  5577. return token <= 92;
  5578. }
  5579. function tokenIsKeywordOrIdentifier(token) {
  5580. return token >= 58 && token <= 133;
  5581. }
  5582. function tokenIsLiteralPropertyName(token) {
  5583. return token >= 58 && token <= 137;
  5584. }
  5585. function tokenComesBeforeExpression(token) {
  5586. return tokenBeforeExprs[token];
  5587. }
  5588. function tokenCanStartExpression(token) {
  5589. return tokenStartsExprs[token];
  5590. }
  5591. function tokenIsAssignment(token) {
  5592. return token >= 29 && token <= 33;
  5593. }
  5594. function tokenIsFlowInterfaceOrTypeOrOpaque(token) {
  5595. return token >= 129 && token <= 131;
  5596. }
  5597. function tokenIsLoop(token) {
  5598. return token >= 90 && token <= 92;
  5599. }
  5600. function tokenIsKeyword(token) {
  5601. return token >= 58 && token <= 92;
  5602. }
  5603. function tokenIsOperator(token) {
  5604. return token >= 39 && token <= 59;
  5605. }
  5606. function tokenIsPostfix(token) {
  5607. return token === 34;
  5608. }
  5609. function tokenIsPrefix(token) {
  5610. return tokenPrefixes[token];
  5611. }
  5612. function tokenIsTSTypeOperator(token) {
  5613. return token >= 121 && token <= 123;
  5614. }
  5615. function tokenIsTSDeclarationStart(token) {
  5616. return token >= 124 && token <= 130;
  5617. }
  5618. function tokenLabelName(token) {
  5619. return tokenLabels[token];
  5620. }
  5621. function tokenOperatorPrecedence(token) {
  5622. return tokenBinops[token];
  5623. }
  5624. function tokenIsRightAssociative(token) {
  5625. return token === 57;
  5626. }
  5627. function tokenIsTemplate(token) {
  5628. return token >= 24 && token <= 25;
  5629. }
  5630. function getExportedToken(token) {
  5631. return tokenTypes[token];
  5632. }
  5633. tokenTypes[8].updateContext = context => {
  5634. context.pop();
  5635. };
  5636. tokenTypes[5].updateContext = tokenTypes[7].updateContext = tokenTypes[23].updateContext = context => {
  5637. context.push(types.brace);
  5638. };
  5639. tokenTypes[22].updateContext = context => {
  5640. if (context[context.length - 1] === types.template) {
  5641. context.pop();
  5642. } else {
  5643. context.push(types.template);
  5644. }
  5645. };
  5646. tokenTypes[143].updateContext = context => {
  5647. context.push(types.j_expr, types.j_oTag);
  5648. };
  5649. let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088f\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5c\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdc-\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7dc\ua7f1-\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";
  5650. let nonASCIIidentifierChars = "\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\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\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-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1add\u1ae0-\u1aeb\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\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\uff65";
  5651. const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  5652. const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  5653. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  5654. const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 7, 25, 39, 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, 39, 27, 10, 22, 251, 41, 7, 1, 17, 5, 57, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 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, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 24, 43, 261, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 33, 24, 3, 24, 45, 74, 6, 0, 67, 12, 65, 1, 2, 0, 15, 4, 10, 7381, 42, 31, 98, 114, 8702, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 208, 30, 2, 2, 2, 1, 2, 6, 3, 4, 10, 1, 225, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4381, 3, 5773, 3, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 8489];
  5655. const 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, 7, 9, 32, 4, 318, 1, 78, 5, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 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, 199, 7, 137, 9, 54, 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, 55, 9, 266, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 233, 0, 3, 0, 8, 1, 6, 0, 475, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
  5656. function isInAstralSet(code, set) {
  5657. let pos = 0x10000;
  5658. for (let i = 0, length = set.length; i < length; i += 2) {
  5659. pos += set[i];
  5660. if (pos > code) return false;
  5661. pos += set[i + 1];
  5662. if (pos >= code) return true;
  5663. }
  5664. return false;
  5665. }
  5666. function isIdentifierStart(code) {
  5667. if (code < 65) return code === 36;
  5668. if (code <= 90) return true;
  5669. if (code < 97) return code === 95;
  5670. if (code <= 122) return true;
  5671. if (code <= 0xffff) {
  5672. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  5673. }
  5674. return isInAstralSet(code, astralIdentifierStartCodes);
  5675. }
  5676. function isIdentifierChar(code) {
  5677. if (code < 48) return code === 36;
  5678. if (code < 58) return true;
  5679. if (code < 65) return false;
  5680. if (code <= 90) return true;
  5681. if (code < 97) return code === 95;
  5682. if (code <= 122) return true;
  5683. if (code <= 0xffff) {
  5684. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  5685. }
  5686. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  5687. }
  5688. const reservedWords = {
  5689. keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"],
  5690. strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  5691. strictBind: ["eval", "arguments"]
  5692. };
  5693. const keywords = new Set(reservedWords.keyword);
  5694. const reservedWordsStrictSet = new Set(reservedWords.strict);
  5695. const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
  5696. function isReservedWord(word, inModule) {
  5697. return inModule && word === "await" || word === "enum";
  5698. }
  5699. function isStrictReservedWord(word, inModule) {
  5700. return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
  5701. }
  5702. function isStrictBindOnlyReservedWord(word) {
  5703. return reservedWordsStrictBindSet.has(word);
  5704. }
  5705. function isStrictBindReservedWord(word, inModule) {
  5706. return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
  5707. }
  5708. function isKeyword(word) {
  5709. return keywords.has(word);
  5710. }
  5711. function isIteratorStart(current, next, next2) {
  5712. return current === 64 && next === 64 && isIdentifierStart(next2);
  5713. }
  5714. const reservedWordLikeSet = new Set(["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete", "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield", "eval", "arguments", "enum", "await"]);
  5715. function canBeReservedWord(word) {
  5716. return reservedWordLikeSet.has(word);
  5717. }
  5718. class Scope {
  5719. constructor(flags) {
  5720. this.flags = 0;
  5721. this.names = new Map();
  5722. this.firstLexicalName = "";
  5723. this.flags = flags;
  5724. }
  5725. }
  5726. class ScopeHandler {
  5727. constructor(parser, inModule) {
  5728. this.parser = void 0;
  5729. this.scopeStack = [];
  5730. this.inModule = void 0;
  5731. this.undefinedExports = new Map();
  5732. this.parser = parser;
  5733. this.inModule = inModule;
  5734. }
  5735. get inTopLevel() {
  5736. return (this.currentScope().flags & 1) > 0;
  5737. }
  5738. get inFunction() {
  5739. return (this.currentVarScopeFlags() & 2) > 0;
  5740. }
  5741. get allowSuper() {
  5742. return (this.currentThisScopeFlags() & 16) > 0;
  5743. }
  5744. get allowDirectSuper() {
  5745. return (this.currentThisScopeFlags() & 32) > 0;
  5746. }
  5747. get allowNewTarget() {
  5748. return (this.currentThisScopeFlags() & 512) > 0;
  5749. }
  5750. get inClass() {
  5751. return (this.currentThisScopeFlags() & 64) > 0;
  5752. }
  5753. get inClassAndNotInNonArrowFunction() {
  5754. const flags = this.currentThisScopeFlags();
  5755. return (flags & 64) > 0 && (flags & 2) === 0;
  5756. }
  5757. get inStaticBlock() {
  5758. for (let i = this.scopeStack.length - 1;; i--) {
  5759. const {
  5760. flags
  5761. } = this.scopeStack[i];
  5762. if (flags & 128) {
  5763. return true;
  5764. }
  5765. if (flags & (1667 | 64)) {
  5766. return false;
  5767. }
  5768. }
  5769. }
  5770. get inNonArrowFunction() {
  5771. return (this.currentThisScopeFlags() & 2) > 0;
  5772. }
  5773. get inBareCaseStatement() {
  5774. return (this.currentScope().flags & 256) > 0;
  5775. }
  5776. get treatFunctionsAsVar() {
  5777. return this.treatFunctionsAsVarInScope(this.currentScope());
  5778. }
  5779. createScope(flags) {
  5780. return new Scope(flags);
  5781. }
  5782. enter(flags) {
  5783. this.scopeStack.push(this.createScope(flags));
  5784. }
  5785. exit() {
  5786. const scope = this.scopeStack.pop();
  5787. return scope.flags;
  5788. }
  5789. treatFunctionsAsVarInScope(scope) {
  5790. return !!(scope.flags & (2 | 128) || !this.parser.inModule && scope.flags & 1);
  5791. }
  5792. declareName(name, bindingType, loc) {
  5793. let scope = this.currentScope();
  5794. if (bindingType & 8 || bindingType & 16) {
  5795. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  5796. let type = scope.names.get(name) || 0;
  5797. if (bindingType & 16) {
  5798. type = type | 4;
  5799. } else {
  5800. if (!scope.firstLexicalName) {
  5801. scope.firstLexicalName = name;
  5802. }
  5803. type = type | 2;
  5804. }
  5805. scope.names.set(name, type);
  5806. if (bindingType & 8) {
  5807. this.maybeExportDefined(scope, name);
  5808. }
  5809. } else if (bindingType & 4) {
  5810. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  5811. scope = this.scopeStack[i];
  5812. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  5813. scope.names.set(name, (scope.names.get(name) || 0) | 1);
  5814. this.maybeExportDefined(scope, name);
  5815. if (scope.flags & 1667) break;
  5816. }
  5817. }
  5818. if (this.parser.inModule && scope.flags & 1) {
  5819. this.undefinedExports.delete(name);
  5820. }
  5821. }
  5822. maybeExportDefined(scope, name) {
  5823. if (this.parser.inModule && scope.flags & 1) {
  5824. this.undefinedExports.delete(name);
  5825. }
  5826. }
  5827. checkRedeclarationInScope(scope, name, bindingType, loc) {
  5828. if (this.isRedeclaredInScope(scope, name, bindingType)) {
  5829. this.parser.raise(Errors.VarRedeclaration, loc, {
  5830. identifierName: name
  5831. });
  5832. }
  5833. }
  5834. isRedeclaredInScope(scope, name, bindingType) {
  5835. if (!(bindingType & 1)) return false;
  5836. if (bindingType & 8) {
  5837. return scope.names.has(name);
  5838. }
  5839. const type = scope.names.get(name) || 0;
  5840. if (bindingType & 16) {
  5841. return (type & 2) > 0 || !this.treatFunctionsAsVarInScope(scope) && (type & 1) > 0;
  5842. }
  5843. return (type & 2) > 0 && !(scope.flags & 8 && scope.firstLexicalName === name) || !this.treatFunctionsAsVarInScope(scope) && (type & 4) > 0;
  5844. }
  5845. checkLocalExport(id) {
  5846. const {
  5847. name
  5848. } = id;
  5849. const topLevelScope = this.scopeStack[0];
  5850. if (!topLevelScope.names.has(name)) {
  5851. this.undefinedExports.set(name, id.loc.start);
  5852. }
  5853. }
  5854. currentScope() {
  5855. return this.scopeStack[this.scopeStack.length - 1];
  5856. }
  5857. currentVarScopeFlags() {
  5858. for (let i = this.scopeStack.length - 1;; i--) {
  5859. const {
  5860. flags
  5861. } = this.scopeStack[i];
  5862. if (flags & 1667) {
  5863. return flags;
  5864. }
  5865. }
  5866. }
  5867. currentThisScopeFlags() {
  5868. for (let i = this.scopeStack.length - 1;; i--) {
  5869. const {
  5870. flags
  5871. } = this.scopeStack[i];
  5872. if (flags & (1667 | 64) && !(flags & 4)) {
  5873. return flags;
  5874. }
  5875. }
  5876. }
  5877. }
  5878. class FlowScope extends Scope {
  5879. constructor(...args) {
  5880. super(...args);
  5881. this.declareFunctions = new Set();
  5882. }
  5883. }
  5884. class FlowScopeHandler extends ScopeHandler {
  5885. createScope(flags) {
  5886. return new FlowScope(flags);
  5887. }
  5888. declareName(name, bindingType, loc) {
  5889. const scope = this.currentScope();
  5890. if (bindingType & 2048) {
  5891. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  5892. this.maybeExportDefined(scope, name);
  5893. scope.declareFunctions.add(name);
  5894. return;
  5895. }
  5896. super.declareName(name, bindingType, loc);
  5897. }
  5898. isRedeclaredInScope(scope, name, bindingType) {
  5899. if (super.isRedeclaredInScope(scope, name, bindingType)) return true;
  5900. if (bindingType & 2048 && !scope.declareFunctions.has(name)) {
  5901. const type = scope.names.get(name);
  5902. return (type & 4) > 0 || (type & 2) > 0;
  5903. }
  5904. return false;
  5905. }
  5906. checkLocalExport(id) {
  5907. if (!this.scopeStack[0].declareFunctions.has(id.name)) {
  5908. super.checkLocalExport(id);
  5909. }
  5910. }
  5911. }
  5912. const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
  5913. const FlowErrors = ParseErrorEnum`flow`({
  5914. AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
  5915. AmbiguousDeclareModuleKind: "Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.",
  5916. AssignReservedType: ({
  5917. reservedType
  5918. }) => `Cannot overwrite reserved type ${reservedType}.`,
  5919. DeclareClassElement: "The `declare` modifier can only appear on class fields.",
  5920. DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.",
  5921. DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement.",
  5922. EnumBooleanMemberNotInitialized: ({
  5923. memberName,
  5924. enumName
  5925. }) => `Boolean enum members need to be initialized. Use either \`${memberName} = true,\` or \`${memberName} = false,\` in enum \`${enumName}\`.`,
  5926. EnumDuplicateMemberName: ({
  5927. memberName,
  5928. enumName
  5929. }) => `Enum member names need to be unique, but the name \`${memberName}\` has already been used before in enum \`${enumName}\`.`,
  5930. EnumInconsistentMemberValues: ({
  5931. enumName
  5932. }) => `Enum \`${enumName}\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`,
  5933. EnumInvalidExplicitType: ({
  5934. invalidEnumType,
  5935. enumName
  5936. }) => `Enum type \`${invalidEnumType}\` is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`,
  5937. EnumInvalidExplicitTypeUnknownSupplied: ({
  5938. enumName
  5939. }) => `Supplied enum type is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`,
  5940. EnumInvalidMemberInitializerPrimaryType: ({
  5941. enumName,
  5942. memberName,
  5943. explicitType
  5944. }) => `Enum \`${enumName}\` has type \`${explicitType}\`, so the initializer of \`${memberName}\` needs to be a ${explicitType} literal.`,
  5945. EnumInvalidMemberInitializerSymbolType: ({
  5946. enumName,
  5947. memberName
  5948. }) => `Symbol enum members cannot be initialized. Use \`${memberName},\` in enum \`${enumName}\`.`,
  5949. EnumInvalidMemberInitializerUnknownType: ({
  5950. enumName,
  5951. memberName
  5952. }) => `The enum member initializer for \`${memberName}\` needs to be a literal (either a boolean, number, or string) in enum \`${enumName}\`.`,
  5953. EnumInvalidMemberName: ({
  5954. enumName,
  5955. memberName,
  5956. suggestion
  5957. }) => `Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \`${memberName}\`, consider using \`${suggestion}\`, in enum \`${enumName}\`.`,
  5958. EnumNumberMemberNotInitialized: ({
  5959. enumName,
  5960. memberName
  5961. }) => `Number enum members need to be initialized, e.g. \`${memberName} = 1\` in enum \`${enumName}\`.`,
  5962. EnumStringMemberInconsistentlyInitialized: ({
  5963. enumName
  5964. }) => `String enum members need to consistently either all use initializers, or use no initializers, in enum \`${enumName}\`.`,
  5965. GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.",
  5966. ImportReflectionHasImportType: "An `import module` declaration can not use `type` or `typeof` keyword.",
  5967. ImportTypeShorthandOnlyInPureImport: "The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements.",
  5968. InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type.",
  5969. InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions.",
  5970. InexactVariance: "Explicit inexact syntax cannot have variance.",
  5971. InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`.",
  5972. MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
  5973. NestedDeclareModule: "`declare module` cannot be used inside another `declare module`.",
  5974. NestedFlowComment: "Cannot have a flow comment inside another flow comment.",
  5975. PatternIsOptional: Object.assign({
  5976. message: "A binding pattern parameter cannot be optional in an implementation signature."
  5977. }, {
  5978. reasonCode: "OptionalBindingPattern"
  5979. }),
  5980. SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.",
  5981. SpreadVariance: "Spread properties cannot have variance.",
  5982. ThisParamAnnotationRequired: "A type annotation is required for the `this` parameter.",
  5983. ThisParamBannedInConstructor: "Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",
  5984. ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.",
  5985. ThisParamMustBeFirst: "The `this` parameter must be the first function parameter.",
  5986. ThisParamNoDefault: "The `this` parameter may not have a default value.",
  5987. TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
  5988. TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis.",
  5989. UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object.",
  5990. UnexpectedReservedType: ({
  5991. reservedType
  5992. }) => `Unexpected reserved type ${reservedType}.`,
  5993. UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new.",
  5994. UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.",
  5995. UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions.",
  5996. UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint".',
  5997. UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration.",
  5998. UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`.",
  5999. UnsupportedDeclareExportKind: ({
  6000. unsupportedExportKind,
  6001. suggestion
  6002. }) => `\`declare export ${unsupportedExportKind}\` is not supported. Use \`${suggestion}\` instead.`,
  6003. UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module.",
  6004. UnterminatedFlowComment: "Unterminated flow-comment."
  6005. });
  6006. function isEsModuleType(bodyElement) {
  6007. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  6008. }
  6009. function hasTypeImportKind(node) {
  6010. return node.importKind === "type" || node.importKind === "typeof";
  6011. }
  6012. const exportSuggestions = {
  6013. const: "declare export var",
  6014. let: "declare export var",
  6015. type: "export type",
  6016. interface: "export interface"
  6017. };
  6018. function partition(list, test) {
  6019. const list1 = [];
  6020. const list2 = [];
  6021. for (let i = 0; i < list.length; i++) {
  6022. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  6023. }
  6024. return [list1, list2];
  6025. }
  6026. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  6027. var flow = superClass => class FlowParserMixin extends superClass {
  6028. constructor(...args) {
  6029. super(...args);
  6030. this.flowPragma = undefined;
  6031. }
  6032. getScopeHandler() {
  6033. return FlowScopeHandler;
  6034. }
  6035. shouldParseTypes() {
  6036. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  6037. }
  6038. finishToken(type, val) {
  6039. if (type !== 134 && type !== 13 && type !== 28) {
  6040. if (this.flowPragma === undefined) {
  6041. this.flowPragma = null;
  6042. }
  6043. }
  6044. super.finishToken(type, val);
  6045. }
  6046. addComment(comment) {
  6047. if (this.flowPragma === undefined) {
  6048. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  6049. if (!matches) ;else if (matches[1] === "flow") {
  6050. this.flowPragma = "flow";
  6051. } else if (matches[1] === "noflow") {
  6052. this.flowPragma = "noflow";
  6053. } else {
  6054. throw new Error("Unexpected flow pragma");
  6055. }
  6056. }
  6057. super.addComment(comment);
  6058. }
  6059. flowParseTypeInitialiser(tok) {
  6060. const oldInType = this.state.inType;
  6061. this.state.inType = true;
  6062. this.expect(tok || 14);
  6063. const type = this.flowParseType();
  6064. this.state.inType = oldInType;
  6065. return type;
  6066. }
  6067. flowParsePredicate() {
  6068. const node = this.startNode();
  6069. const moduloLoc = this.state.startLoc;
  6070. this.next();
  6071. this.expectContextual(110);
  6072. if (this.state.lastTokStartLoc.index > moduloLoc.index + 1) {
  6073. this.raise(FlowErrors.UnexpectedSpaceBetweenModuloChecks, moduloLoc);
  6074. }
  6075. if (this.eat(10)) {
  6076. node.value = super.parseExpression();
  6077. this.expect(11);
  6078. return this.finishNode(node, "DeclaredPredicate");
  6079. } else {
  6080. return this.finishNode(node, "InferredPredicate");
  6081. }
  6082. }
  6083. flowParseTypeAndPredicateInitialiser() {
  6084. const oldInType = this.state.inType;
  6085. this.state.inType = true;
  6086. this.expect(14);
  6087. let type = null;
  6088. let predicate = null;
  6089. if (this.match(54)) {
  6090. this.state.inType = oldInType;
  6091. predicate = this.flowParsePredicate();
  6092. } else {
  6093. type = this.flowParseType();
  6094. this.state.inType = oldInType;
  6095. if (this.match(54)) {
  6096. predicate = this.flowParsePredicate();
  6097. }
  6098. }
  6099. return [type, predicate];
  6100. }
  6101. flowParseDeclareClass(node) {
  6102. this.next();
  6103. this.flowParseInterfaceish(node, true);
  6104. return this.finishNode(node, "DeclareClass");
  6105. }
  6106. flowParseDeclareFunction(node) {
  6107. this.next();
  6108. const id = node.id = this.parseIdentifier();
  6109. const typeNode = this.startNode();
  6110. const typeContainer = this.startNode();
  6111. if (this.match(47)) {
  6112. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  6113. } else {
  6114. typeNode.typeParameters = null;
  6115. }
  6116. this.expect(10);
  6117. const tmp = this.flowParseFunctionTypeParams();
  6118. typeNode.params = tmp.params;
  6119. typeNode.rest = tmp.rest;
  6120. typeNode.this = tmp._this;
  6121. this.expect(11);
  6122. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  6123. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  6124. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  6125. this.resetEndLocation(id);
  6126. this.semicolon();
  6127. this.scope.declareName(node.id.name, 2048, node.id.loc.start);
  6128. return this.finishNode(node, "DeclareFunction");
  6129. }
  6130. flowParseDeclare(node, insideModule) {
  6131. if (this.match(80)) {
  6132. return this.flowParseDeclareClass(node);
  6133. } else if (this.match(68)) {
  6134. return this.flowParseDeclareFunction(node);
  6135. } else if (this.match(74)) {
  6136. return this.flowParseDeclareVariable(node);
  6137. } else if (this.eatContextual(127)) {
  6138. if (this.match(16)) {
  6139. return this.flowParseDeclareModuleExports(node);
  6140. } else {
  6141. if (insideModule) {
  6142. this.raise(FlowErrors.NestedDeclareModule, this.state.lastTokStartLoc);
  6143. }
  6144. return this.flowParseDeclareModule(node);
  6145. }
  6146. } else if (this.isContextual(130)) {
  6147. return this.flowParseDeclareTypeAlias(node);
  6148. } else if (this.isContextual(131)) {
  6149. return this.flowParseDeclareOpaqueType(node);
  6150. } else if (this.isContextual(129)) {
  6151. return this.flowParseDeclareInterface(node);
  6152. } else if (this.match(82)) {
  6153. return this.flowParseDeclareExportDeclaration(node, insideModule);
  6154. }
  6155. throw this.unexpected();
  6156. }
  6157. flowParseDeclareVariable(node) {
  6158. this.next();
  6159. node.id = this.flowParseTypeAnnotatableIdentifier();
  6160. this.scope.declareName(node.id.name, 5, node.id.loc.start);
  6161. this.semicolon();
  6162. return this.finishNode(node, "DeclareVariable");
  6163. }
  6164. flowParseDeclareModule(node) {
  6165. this.scope.enter(0);
  6166. if (this.match(134)) {
  6167. node.id = super.parseExprAtom();
  6168. } else {
  6169. node.id = this.parseIdentifier();
  6170. }
  6171. const bodyNode = node.body = this.startNode();
  6172. const body = bodyNode.body = [];
  6173. this.expect(5);
  6174. while (!this.match(8)) {
  6175. const bodyNode = this.startNode();
  6176. if (this.match(83)) {
  6177. this.next();
  6178. if (!this.isContextual(130) && !this.match(87)) {
  6179. this.raise(FlowErrors.InvalidNonTypeImportInDeclareModule, this.state.lastTokStartLoc);
  6180. }
  6181. body.push(super.parseImport(bodyNode));
  6182. } else {
  6183. this.expectContextual(125, FlowErrors.UnsupportedStatementInDeclareModule);
  6184. body.push(this.flowParseDeclare(bodyNode, true));
  6185. }
  6186. }
  6187. this.scope.exit();
  6188. this.expect(8);
  6189. this.finishNode(bodyNode, "BlockStatement");
  6190. let kind = null;
  6191. let hasModuleExport = false;
  6192. body.forEach(bodyElement => {
  6193. if (isEsModuleType(bodyElement)) {
  6194. if (kind === "CommonJS") {
  6195. this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement);
  6196. }
  6197. kind = "ES";
  6198. } else if (bodyElement.type === "DeclareModuleExports") {
  6199. if (hasModuleExport) {
  6200. this.raise(FlowErrors.DuplicateDeclareModuleExports, bodyElement);
  6201. }
  6202. if (kind === "ES") {
  6203. this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement);
  6204. }
  6205. kind = "CommonJS";
  6206. hasModuleExport = true;
  6207. }
  6208. });
  6209. node.kind = kind || "CommonJS";
  6210. return this.finishNode(node, "DeclareModule");
  6211. }
  6212. flowParseDeclareExportDeclaration(node, insideModule) {
  6213. this.expect(82);
  6214. if (this.eat(65)) {
  6215. if (this.match(68) || this.match(80)) {
  6216. node.declaration = this.flowParseDeclare(this.startNode());
  6217. } else {
  6218. node.declaration = this.flowParseType();
  6219. this.semicolon();
  6220. }
  6221. node.default = true;
  6222. return this.finishNode(node, "DeclareExportDeclaration");
  6223. } else {
  6224. if (this.match(75) || this.isLet() || (this.isContextual(130) || this.isContextual(129)) && !insideModule) {
  6225. const label = this.state.value;
  6226. throw this.raise(FlowErrors.UnsupportedDeclareExportKind, this.state.startLoc, {
  6227. unsupportedExportKind: label,
  6228. suggestion: exportSuggestions[label]
  6229. });
  6230. }
  6231. if (this.match(74) || this.match(68) || this.match(80) || this.isContextual(131)) {
  6232. node.declaration = this.flowParseDeclare(this.startNode());
  6233. node.default = false;
  6234. return this.finishNode(node, "DeclareExportDeclaration");
  6235. } else if (this.match(55) || this.match(5) || this.isContextual(129) || this.isContextual(130) || this.isContextual(131)) {
  6236. node = this.parseExport(node, null);
  6237. if (node.type === "ExportNamedDeclaration") {
  6238. node.default = false;
  6239. delete node.exportKind;
  6240. return this.castNodeTo(node, "DeclareExportDeclaration");
  6241. } else {
  6242. return this.castNodeTo(node, "DeclareExportAllDeclaration");
  6243. }
  6244. }
  6245. }
  6246. throw this.unexpected();
  6247. }
  6248. flowParseDeclareModuleExports(node) {
  6249. this.next();
  6250. this.expectContextual(111);
  6251. node.typeAnnotation = this.flowParseTypeAnnotation();
  6252. this.semicolon();
  6253. return this.finishNode(node, "DeclareModuleExports");
  6254. }
  6255. flowParseDeclareTypeAlias(node) {
  6256. this.next();
  6257. const finished = this.flowParseTypeAlias(node);
  6258. this.castNodeTo(finished, "DeclareTypeAlias");
  6259. return finished;
  6260. }
  6261. flowParseDeclareOpaqueType(node) {
  6262. this.next();
  6263. const finished = this.flowParseOpaqueType(node, true);
  6264. this.castNodeTo(finished, "DeclareOpaqueType");
  6265. return finished;
  6266. }
  6267. flowParseDeclareInterface(node) {
  6268. this.next();
  6269. this.flowParseInterfaceish(node, false);
  6270. return this.finishNode(node, "DeclareInterface");
  6271. }
  6272. flowParseInterfaceish(node, isClass) {
  6273. node.id = this.flowParseRestrictedIdentifier(!isClass, true);
  6274. this.scope.declareName(node.id.name, isClass ? 17 : 8201, node.id.loc.start);
  6275. if (this.match(47)) {
  6276. node.typeParameters = this.flowParseTypeParameterDeclaration();
  6277. } else {
  6278. node.typeParameters = null;
  6279. }
  6280. node.extends = [];
  6281. if (this.eat(81)) {
  6282. do {
  6283. node.extends.push(this.flowParseInterfaceExtends());
  6284. } while (!isClass && this.eat(12));
  6285. }
  6286. if (isClass) {
  6287. node.implements = [];
  6288. node.mixins = [];
  6289. if (this.eatContextual(117)) {
  6290. do {
  6291. node.mixins.push(this.flowParseInterfaceExtends());
  6292. } while (this.eat(12));
  6293. }
  6294. if (this.eatContextual(113)) {
  6295. do {
  6296. node.implements.push(this.flowParseInterfaceExtends());
  6297. } while (this.eat(12));
  6298. }
  6299. }
  6300. node.body = this.flowParseObjectType({
  6301. allowStatic: isClass,
  6302. allowExact: false,
  6303. allowSpread: false,
  6304. allowProto: isClass,
  6305. allowInexact: false
  6306. });
  6307. }
  6308. flowParseInterfaceExtends() {
  6309. const node = this.startNode();
  6310. node.id = this.flowParseQualifiedTypeIdentifier();
  6311. if (this.match(47)) {
  6312. node.typeParameters = this.flowParseTypeParameterInstantiation();
  6313. } else {
  6314. node.typeParameters = null;
  6315. }
  6316. return this.finishNode(node, "InterfaceExtends");
  6317. }
  6318. flowParseInterface(node) {
  6319. this.flowParseInterfaceish(node, false);
  6320. return this.finishNode(node, "InterfaceDeclaration");
  6321. }
  6322. checkNotUnderscore(word) {
  6323. if (word === "_") {
  6324. this.raise(FlowErrors.UnexpectedReservedUnderscore, this.state.startLoc);
  6325. }
  6326. }
  6327. checkReservedType(word, startLoc, declaration) {
  6328. if (!reservedTypes.has(word)) return;
  6329. this.raise(declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, startLoc, {
  6330. reservedType: word
  6331. });
  6332. }
  6333. flowParseRestrictedIdentifierName(liberal, declaration) {
  6334. this.checkReservedType(this.state.value, this.state.startLoc, declaration);
  6335. return this.parseIdentifierName(liberal);
  6336. }
  6337. flowParseRestrictedIdentifier(liberal, declaration) {
  6338. const node = this.startNode();
  6339. const name = this.flowParseRestrictedIdentifierName(liberal, declaration);
  6340. return this.createIdentifier(node, name);
  6341. }
  6342. flowParseTypeAlias(node) {
  6343. node.id = this.flowParseRestrictedIdentifier(false, true);
  6344. this.scope.declareName(node.id.name, 8201, node.id.loc.start);
  6345. if (this.match(47)) {
  6346. node.typeParameters = this.flowParseTypeParameterDeclaration();
  6347. } else {
  6348. node.typeParameters = null;
  6349. }
  6350. node.right = this.flowParseTypeInitialiser(29);
  6351. this.semicolon();
  6352. return this.finishNode(node, "TypeAlias");
  6353. }
  6354. flowParseOpaqueType(node, declare) {
  6355. this.expectContextual(130);
  6356. node.id = this.flowParseRestrictedIdentifier(true, true);
  6357. this.scope.declareName(node.id.name, 8201, node.id.loc.start);
  6358. if (this.match(47)) {
  6359. node.typeParameters = this.flowParseTypeParameterDeclaration();
  6360. } else {
  6361. node.typeParameters = null;
  6362. }
  6363. node.supertype = null;
  6364. if (this.match(14)) {
  6365. node.supertype = this.flowParseTypeInitialiser(14);
  6366. }
  6367. node.impltype = null;
  6368. if (!declare) {
  6369. node.impltype = this.flowParseTypeInitialiser(29);
  6370. }
  6371. this.semicolon();
  6372. return this.finishNode(node, "OpaqueType");
  6373. }
  6374. flowParseTypeParameterBound() {
  6375. if (this.match(14) || this.isContextual(81)) {
  6376. const node = this.startNode();
  6377. this.next();
  6378. node.typeAnnotation = this.flowParseType();
  6379. return this.finishNode(node, "TypeAnnotation");
  6380. }
  6381. }
  6382. flowParseTypeParameter(requireDefault = false) {
  6383. const nodeStartLoc = this.state.startLoc;
  6384. const node = this.startNode();
  6385. const variance = this.flowParseVariance();
  6386. node.name = this.flowParseRestrictedIdentifierName();
  6387. node.variance = variance;
  6388. node.bound = this.flowParseTypeParameterBound();
  6389. if (this.match(29)) {
  6390. this.eat(29);
  6391. node.default = this.flowParseType();
  6392. } else {
  6393. if (requireDefault) {
  6394. this.raise(FlowErrors.MissingTypeParamDefault, nodeStartLoc);
  6395. }
  6396. }
  6397. return this.finishNode(node, "TypeParameter");
  6398. }
  6399. flowParseTypeParameterDeclaration() {
  6400. const oldInType = this.state.inType;
  6401. const node = this.startNode();
  6402. node.params = [];
  6403. this.state.inType = true;
  6404. if (this.match(47) || this.match(143)) {
  6405. this.next();
  6406. } else {
  6407. this.unexpected();
  6408. }
  6409. let defaultRequired = false;
  6410. do {
  6411. const typeParameter = this.flowParseTypeParameter(defaultRequired);
  6412. node.params.push(typeParameter);
  6413. if (typeParameter.default) {
  6414. defaultRequired = true;
  6415. }
  6416. if (!this.match(48)) {
  6417. this.expect(12);
  6418. }
  6419. } while (!this.match(48));
  6420. this.expect(48);
  6421. this.state.inType = oldInType;
  6422. return this.finishNode(node, "TypeParameterDeclaration");
  6423. }
  6424. flowInTopLevelContext(cb) {
  6425. if (this.curContext() !== types.brace) {
  6426. const oldContext = this.state.context;
  6427. this.state.context = [oldContext[0]];
  6428. try {
  6429. return cb();
  6430. } finally {
  6431. this.state.context = oldContext;
  6432. }
  6433. } else {
  6434. return cb();
  6435. }
  6436. }
  6437. flowParseTypeParameterInstantiationInExpression() {
  6438. if (this.reScan_lt() !== 47) return;
  6439. return this.flowParseTypeParameterInstantiation();
  6440. }
  6441. flowParseTypeParameterInstantiation() {
  6442. const node = this.startNode();
  6443. const oldInType = this.state.inType;
  6444. this.state.inType = true;
  6445. node.params = [];
  6446. this.flowInTopLevelContext(() => {
  6447. this.expect(47);
  6448. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  6449. this.state.noAnonFunctionType = false;
  6450. while (!this.match(48)) {
  6451. node.params.push(this.flowParseType());
  6452. if (!this.match(48)) {
  6453. this.expect(12);
  6454. }
  6455. }
  6456. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  6457. });
  6458. this.state.inType = oldInType;
  6459. if (!this.state.inType && this.curContext() === types.brace) {
  6460. this.reScan_lt_gt();
  6461. }
  6462. this.expect(48);
  6463. return this.finishNode(node, "TypeParameterInstantiation");
  6464. }
  6465. flowParseTypeParameterInstantiationCallOrNew() {
  6466. if (this.reScan_lt() !== 47) return null;
  6467. const node = this.startNode();
  6468. const oldInType = this.state.inType;
  6469. node.params = [];
  6470. this.state.inType = true;
  6471. this.expect(47);
  6472. while (!this.match(48)) {
  6473. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  6474. if (!this.match(48)) {
  6475. this.expect(12);
  6476. }
  6477. }
  6478. this.expect(48);
  6479. this.state.inType = oldInType;
  6480. return this.finishNode(node, "TypeParameterInstantiation");
  6481. }
  6482. flowParseInterfaceType() {
  6483. const node = this.startNode();
  6484. this.expectContextual(129);
  6485. node.extends = [];
  6486. if (this.eat(81)) {
  6487. do {
  6488. node.extends.push(this.flowParseInterfaceExtends());
  6489. } while (this.eat(12));
  6490. }
  6491. node.body = this.flowParseObjectType({
  6492. allowStatic: false,
  6493. allowExact: false,
  6494. allowSpread: false,
  6495. allowProto: false,
  6496. allowInexact: false
  6497. });
  6498. return this.finishNode(node, "InterfaceTypeAnnotation");
  6499. }
  6500. flowParseObjectPropertyKey() {
  6501. return this.match(135) || this.match(134) ? super.parseExprAtom() : this.parseIdentifier(true);
  6502. }
  6503. flowParseObjectTypeIndexer(node, isStatic, variance) {
  6504. node.static = isStatic;
  6505. if (this.lookahead().type === 14) {
  6506. node.id = this.flowParseObjectPropertyKey();
  6507. node.key = this.flowParseTypeInitialiser();
  6508. } else {
  6509. node.id = null;
  6510. node.key = this.flowParseType();
  6511. }
  6512. this.expect(3);
  6513. node.value = this.flowParseTypeInitialiser();
  6514. node.variance = variance;
  6515. return this.finishNode(node, "ObjectTypeIndexer");
  6516. }
  6517. flowParseObjectTypeInternalSlot(node, isStatic) {
  6518. node.static = isStatic;
  6519. node.id = this.flowParseObjectPropertyKey();
  6520. this.expect(3);
  6521. this.expect(3);
  6522. if (this.match(47) || this.match(10)) {
  6523. node.method = true;
  6524. node.optional = false;
  6525. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start));
  6526. } else {
  6527. node.method = false;
  6528. if (this.eat(17)) {
  6529. node.optional = true;
  6530. }
  6531. node.value = this.flowParseTypeInitialiser();
  6532. }
  6533. return this.finishNode(node, "ObjectTypeInternalSlot");
  6534. }
  6535. flowParseObjectTypeMethodish(node) {
  6536. node.params = [];
  6537. node.rest = null;
  6538. node.typeParameters = null;
  6539. node.this = null;
  6540. if (this.match(47)) {
  6541. node.typeParameters = this.flowParseTypeParameterDeclaration();
  6542. }
  6543. this.expect(10);
  6544. if (this.match(78)) {
  6545. node.this = this.flowParseFunctionTypeParam(true);
  6546. node.this.name = null;
  6547. if (!this.match(11)) {
  6548. this.expect(12);
  6549. }
  6550. }
  6551. while (!this.match(11) && !this.match(21)) {
  6552. node.params.push(this.flowParseFunctionTypeParam(false));
  6553. if (!this.match(11)) {
  6554. this.expect(12);
  6555. }
  6556. }
  6557. if (this.eat(21)) {
  6558. node.rest = this.flowParseFunctionTypeParam(false);
  6559. }
  6560. this.expect(11);
  6561. node.returnType = this.flowParseTypeInitialiser();
  6562. return this.finishNode(node, "FunctionTypeAnnotation");
  6563. }
  6564. flowParseObjectTypeCallProperty(node, isStatic) {
  6565. const valueNode = this.startNode();
  6566. node.static = isStatic;
  6567. node.value = this.flowParseObjectTypeMethodish(valueNode);
  6568. return this.finishNode(node, "ObjectTypeCallProperty");
  6569. }
  6570. flowParseObjectType({
  6571. allowStatic,
  6572. allowExact,
  6573. allowSpread,
  6574. allowProto,
  6575. allowInexact
  6576. }) {
  6577. const oldInType = this.state.inType;
  6578. this.state.inType = true;
  6579. const nodeStart = this.startNode();
  6580. nodeStart.callProperties = [];
  6581. nodeStart.properties = [];
  6582. nodeStart.indexers = [];
  6583. nodeStart.internalSlots = [];
  6584. let endDelim;
  6585. let exact;
  6586. let inexact = false;
  6587. if (allowExact && this.match(6)) {
  6588. this.expect(6);
  6589. endDelim = 9;
  6590. exact = true;
  6591. } else {
  6592. this.expect(5);
  6593. endDelim = 8;
  6594. exact = false;
  6595. }
  6596. nodeStart.exact = exact;
  6597. while (!this.match(endDelim)) {
  6598. let isStatic = false;
  6599. let protoStartLoc = null;
  6600. let inexactStartLoc = null;
  6601. const node = this.startNode();
  6602. if (allowProto && this.isContextual(118)) {
  6603. const lookahead = this.lookahead();
  6604. if (lookahead.type !== 14 && lookahead.type !== 17) {
  6605. this.next();
  6606. protoStartLoc = this.state.startLoc;
  6607. allowStatic = false;
  6608. }
  6609. }
  6610. if (allowStatic && this.isContextual(106)) {
  6611. const lookahead = this.lookahead();
  6612. if (lookahead.type !== 14 && lookahead.type !== 17) {
  6613. this.next();
  6614. isStatic = true;
  6615. }
  6616. }
  6617. const variance = this.flowParseVariance();
  6618. if (this.eat(0)) {
  6619. if (protoStartLoc != null) {
  6620. this.unexpected(protoStartLoc);
  6621. }
  6622. if (this.eat(0)) {
  6623. if (variance) {
  6624. this.unexpected(variance.loc.start);
  6625. }
  6626. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  6627. } else {
  6628. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  6629. }
  6630. } else if (this.match(10) || this.match(47)) {
  6631. if (protoStartLoc != null) {
  6632. this.unexpected(protoStartLoc);
  6633. }
  6634. if (variance) {
  6635. this.unexpected(variance.loc.start);
  6636. }
  6637. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  6638. } else {
  6639. let kind = "init";
  6640. if (this.isContextual(99) || this.isContextual(104)) {
  6641. const lookahead = this.lookahead();
  6642. if (tokenIsLiteralPropertyName(lookahead.type)) {
  6643. kind = this.state.value;
  6644. this.next();
  6645. }
  6646. }
  6647. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact);
  6648. if (propOrInexact === null) {
  6649. inexact = true;
  6650. inexactStartLoc = this.state.lastTokStartLoc;
  6651. } else {
  6652. nodeStart.properties.push(propOrInexact);
  6653. }
  6654. }
  6655. this.flowObjectTypeSemicolon();
  6656. if (inexactStartLoc && !this.match(8) && !this.match(9)) {
  6657. this.raise(FlowErrors.UnexpectedExplicitInexactInObject, inexactStartLoc);
  6658. }
  6659. }
  6660. this.expect(endDelim);
  6661. if (allowSpread) {
  6662. nodeStart.inexact = inexact;
  6663. }
  6664. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  6665. this.state.inType = oldInType;
  6666. return out;
  6667. }
  6668. flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact) {
  6669. if (this.eat(21)) {
  6670. const isInexactToken = this.match(12) || this.match(13) || this.match(8) || this.match(9);
  6671. if (isInexactToken) {
  6672. if (!allowSpread) {
  6673. this.raise(FlowErrors.InexactInsideNonObject, this.state.lastTokStartLoc);
  6674. } else if (!allowInexact) {
  6675. this.raise(FlowErrors.InexactInsideExact, this.state.lastTokStartLoc);
  6676. }
  6677. if (variance) {
  6678. this.raise(FlowErrors.InexactVariance, variance);
  6679. }
  6680. return null;
  6681. }
  6682. if (!allowSpread) {
  6683. this.raise(FlowErrors.UnexpectedSpreadType, this.state.lastTokStartLoc);
  6684. }
  6685. if (protoStartLoc != null) {
  6686. this.unexpected(protoStartLoc);
  6687. }
  6688. if (variance) {
  6689. this.raise(FlowErrors.SpreadVariance, variance);
  6690. }
  6691. node.argument = this.flowParseType();
  6692. return this.finishNode(node, "ObjectTypeSpreadProperty");
  6693. } else {
  6694. node.key = this.flowParseObjectPropertyKey();
  6695. node.static = isStatic;
  6696. node.proto = protoStartLoc != null;
  6697. node.kind = kind;
  6698. let optional = false;
  6699. if (this.match(47) || this.match(10)) {
  6700. node.method = true;
  6701. if (protoStartLoc != null) {
  6702. this.unexpected(protoStartLoc);
  6703. }
  6704. if (variance) {
  6705. this.unexpected(variance.loc.start);
  6706. }
  6707. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start));
  6708. if (kind === "get" || kind === "set") {
  6709. this.flowCheckGetterSetterParams(node);
  6710. }
  6711. if (!allowSpread && node.key.name === "constructor" && node.value.this) {
  6712. this.raise(FlowErrors.ThisParamBannedInConstructor, node.value.this);
  6713. }
  6714. } else {
  6715. if (kind !== "init") this.unexpected();
  6716. node.method = false;
  6717. if (this.eat(17)) {
  6718. optional = true;
  6719. }
  6720. node.value = this.flowParseTypeInitialiser();
  6721. node.variance = variance;
  6722. }
  6723. node.optional = optional;
  6724. return this.finishNode(node, "ObjectTypeProperty");
  6725. }
  6726. }
  6727. flowCheckGetterSetterParams(property) {
  6728. const paramCount = property.kind === "get" ? 0 : 1;
  6729. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  6730. if (property.value.this) {
  6731. this.raise(property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam : FlowErrors.SetterMayNotHaveThisParam, property.value.this);
  6732. }
  6733. if (length !== paramCount) {
  6734. this.raise(property.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, property);
  6735. }
  6736. if (property.kind === "set" && property.value.rest) {
  6737. this.raise(Errors.BadSetterRestParameter, property);
  6738. }
  6739. }
  6740. flowObjectTypeSemicolon() {
  6741. if (!this.eat(13) && !this.eat(12) && !this.match(8) && !this.match(9)) {
  6742. this.unexpected();
  6743. }
  6744. }
  6745. flowParseQualifiedTypeIdentifier(startLoc, id) {
  6746. startLoc != null ? startLoc : startLoc = this.state.startLoc;
  6747. let node = id || this.flowParseRestrictedIdentifier(true);
  6748. while (this.eat(16)) {
  6749. const node2 = this.startNodeAt(startLoc);
  6750. node2.qualification = node;
  6751. node2.id = this.flowParseRestrictedIdentifier(true);
  6752. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  6753. }
  6754. return node;
  6755. }
  6756. flowParseGenericType(startLoc, id) {
  6757. const node = this.startNodeAt(startLoc);
  6758. node.typeParameters = null;
  6759. node.id = this.flowParseQualifiedTypeIdentifier(startLoc, id);
  6760. if (this.match(47)) {
  6761. node.typeParameters = this.flowParseTypeParameterInstantiation();
  6762. }
  6763. return this.finishNode(node, "GenericTypeAnnotation");
  6764. }
  6765. flowParseTypeofType() {
  6766. const node = this.startNode();
  6767. this.expect(87);
  6768. node.argument = this.flowParsePrimaryType();
  6769. return this.finishNode(node, "TypeofTypeAnnotation");
  6770. }
  6771. flowParseTupleType() {
  6772. const node = this.startNode();
  6773. node.types = [];
  6774. this.expect(0);
  6775. while (this.state.pos < this.length && !this.match(3)) {
  6776. node.types.push(this.flowParseType());
  6777. if (this.match(3)) break;
  6778. this.expect(12);
  6779. }
  6780. this.expect(3);
  6781. return this.finishNode(node, "TupleTypeAnnotation");
  6782. }
  6783. flowParseFunctionTypeParam(first) {
  6784. let name = null;
  6785. let optional = false;
  6786. let typeAnnotation = null;
  6787. const node = this.startNode();
  6788. const lh = this.lookahead();
  6789. const isThis = this.state.type === 78;
  6790. if (lh.type === 14 || lh.type === 17) {
  6791. if (isThis && !first) {
  6792. this.raise(FlowErrors.ThisParamMustBeFirst, node);
  6793. }
  6794. name = this.parseIdentifier(isThis);
  6795. if (this.eat(17)) {
  6796. optional = true;
  6797. if (isThis) {
  6798. this.raise(FlowErrors.ThisParamMayNotBeOptional, node);
  6799. }
  6800. }
  6801. typeAnnotation = this.flowParseTypeInitialiser();
  6802. } else {
  6803. typeAnnotation = this.flowParseType();
  6804. }
  6805. node.name = name;
  6806. node.optional = optional;
  6807. node.typeAnnotation = typeAnnotation;
  6808. return this.finishNode(node, "FunctionTypeParam");
  6809. }
  6810. reinterpretTypeAsFunctionTypeParam(type) {
  6811. const node = this.startNodeAt(type.loc.start);
  6812. node.name = null;
  6813. node.optional = false;
  6814. node.typeAnnotation = type;
  6815. return this.finishNode(node, "FunctionTypeParam");
  6816. }
  6817. flowParseFunctionTypeParams(params = []) {
  6818. let rest = null;
  6819. let _this = null;
  6820. if (this.match(78)) {
  6821. _this = this.flowParseFunctionTypeParam(true);
  6822. _this.name = null;
  6823. if (!this.match(11)) {
  6824. this.expect(12);
  6825. }
  6826. }
  6827. while (!this.match(11) && !this.match(21)) {
  6828. params.push(this.flowParseFunctionTypeParam(false));
  6829. if (!this.match(11)) {
  6830. this.expect(12);
  6831. }
  6832. }
  6833. if (this.eat(21)) {
  6834. rest = this.flowParseFunctionTypeParam(false);
  6835. }
  6836. return {
  6837. params,
  6838. rest,
  6839. _this
  6840. };
  6841. }
  6842. flowIdentToTypeAnnotation(startLoc, node, id) {
  6843. switch (id.name) {
  6844. case "any":
  6845. return this.finishNode(node, "AnyTypeAnnotation");
  6846. case "bool":
  6847. case "boolean":
  6848. return this.finishNode(node, "BooleanTypeAnnotation");
  6849. case "mixed":
  6850. return this.finishNode(node, "MixedTypeAnnotation");
  6851. case "empty":
  6852. return this.finishNode(node, "EmptyTypeAnnotation");
  6853. case "number":
  6854. return this.finishNode(node, "NumberTypeAnnotation");
  6855. case "string":
  6856. return this.finishNode(node, "StringTypeAnnotation");
  6857. case "symbol":
  6858. return this.finishNode(node, "SymbolTypeAnnotation");
  6859. default:
  6860. this.checkNotUnderscore(id.name);
  6861. return this.flowParseGenericType(startLoc, id);
  6862. }
  6863. }
  6864. flowParsePrimaryType() {
  6865. const startLoc = this.state.startLoc;
  6866. const node = this.startNode();
  6867. let tmp;
  6868. let type;
  6869. let isGroupedType = false;
  6870. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  6871. switch (this.state.type) {
  6872. case 5:
  6873. return this.flowParseObjectType({
  6874. allowStatic: false,
  6875. allowExact: false,
  6876. allowSpread: true,
  6877. allowProto: false,
  6878. allowInexact: true
  6879. });
  6880. case 6:
  6881. return this.flowParseObjectType({
  6882. allowStatic: false,
  6883. allowExact: true,
  6884. allowSpread: true,
  6885. allowProto: false,
  6886. allowInexact: false
  6887. });
  6888. case 0:
  6889. this.state.noAnonFunctionType = false;
  6890. type = this.flowParseTupleType();
  6891. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  6892. return type;
  6893. case 47:
  6894. {
  6895. const node = this.startNode();
  6896. node.typeParameters = this.flowParseTypeParameterDeclaration();
  6897. this.expect(10);
  6898. tmp = this.flowParseFunctionTypeParams();
  6899. node.params = tmp.params;
  6900. node.rest = tmp.rest;
  6901. node.this = tmp._this;
  6902. this.expect(11);
  6903. this.expect(19);
  6904. node.returnType = this.flowParseType();
  6905. return this.finishNode(node, "FunctionTypeAnnotation");
  6906. }
  6907. case 10:
  6908. {
  6909. const node = this.startNode();
  6910. this.next();
  6911. if (!this.match(11) && !this.match(21)) {
  6912. if (tokenIsIdentifier(this.state.type) || this.match(78)) {
  6913. const token = this.lookahead().type;
  6914. isGroupedType = token !== 17 && token !== 14;
  6915. } else {
  6916. isGroupedType = true;
  6917. }
  6918. }
  6919. if (isGroupedType) {
  6920. this.state.noAnonFunctionType = false;
  6921. type = this.flowParseType();
  6922. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  6923. if (this.state.noAnonFunctionType || !(this.match(12) || this.match(11) && this.lookahead().type === 19)) {
  6924. this.expect(11);
  6925. return type;
  6926. } else {
  6927. this.eat(12);
  6928. }
  6929. }
  6930. if (type) {
  6931. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  6932. } else {
  6933. tmp = this.flowParseFunctionTypeParams();
  6934. }
  6935. node.params = tmp.params;
  6936. node.rest = tmp.rest;
  6937. node.this = tmp._this;
  6938. this.expect(11);
  6939. this.expect(19);
  6940. node.returnType = this.flowParseType();
  6941. node.typeParameters = null;
  6942. return this.finishNode(node, "FunctionTypeAnnotation");
  6943. }
  6944. case 134:
  6945. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  6946. case 85:
  6947. case 86:
  6948. node.value = this.match(85);
  6949. this.next();
  6950. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  6951. case 53:
  6952. if (this.state.value === "-") {
  6953. this.next();
  6954. if (this.match(135)) {
  6955. return this.parseLiteralAtNode(-this.state.value, "NumberLiteralTypeAnnotation", node);
  6956. }
  6957. if (this.match(136)) {
  6958. return this.parseLiteralAtNode(-this.state.value, "BigIntLiteralTypeAnnotation", node);
  6959. }
  6960. throw this.raise(FlowErrors.UnexpectedSubtractionOperand, this.state.startLoc);
  6961. }
  6962. throw this.unexpected();
  6963. case 135:
  6964. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  6965. case 136:
  6966. return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
  6967. case 88:
  6968. this.next();
  6969. return this.finishNode(node, "VoidTypeAnnotation");
  6970. case 84:
  6971. this.next();
  6972. return this.finishNode(node, "NullLiteralTypeAnnotation");
  6973. case 78:
  6974. this.next();
  6975. return this.finishNode(node, "ThisTypeAnnotation");
  6976. case 55:
  6977. this.next();
  6978. return this.finishNode(node, "ExistsTypeAnnotation");
  6979. case 87:
  6980. return this.flowParseTypeofType();
  6981. default:
  6982. if (tokenIsKeyword(this.state.type)) {
  6983. const label = tokenLabelName(this.state.type);
  6984. this.next();
  6985. return super.createIdentifier(node, label);
  6986. } else if (tokenIsIdentifier(this.state.type)) {
  6987. if (this.isContextual(129)) {
  6988. return this.flowParseInterfaceType();
  6989. }
  6990. return this.flowIdentToTypeAnnotation(startLoc, node, this.parseIdentifier());
  6991. }
  6992. }
  6993. throw this.unexpected();
  6994. }
  6995. flowParsePostfixType() {
  6996. const startLoc = this.state.startLoc;
  6997. let type = this.flowParsePrimaryType();
  6998. let seenOptionalIndexedAccess = false;
  6999. while ((this.match(0) || this.match(18)) && !this.canInsertSemicolon()) {
  7000. const node = this.startNodeAt(startLoc);
  7001. const optional = this.eat(18);
  7002. seenOptionalIndexedAccess = seenOptionalIndexedAccess || optional;
  7003. this.expect(0);
  7004. if (!optional && this.match(3)) {
  7005. node.elementType = type;
  7006. this.next();
  7007. type = this.finishNode(node, "ArrayTypeAnnotation");
  7008. } else {
  7009. node.objectType = type;
  7010. node.indexType = this.flowParseType();
  7011. this.expect(3);
  7012. if (seenOptionalIndexedAccess) {
  7013. node.optional = optional;
  7014. type = this.finishNode(node, "OptionalIndexedAccessType");
  7015. } else {
  7016. type = this.finishNode(node, "IndexedAccessType");
  7017. }
  7018. }
  7019. }
  7020. return type;
  7021. }
  7022. flowParsePrefixType() {
  7023. const node = this.startNode();
  7024. if (this.eat(17)) {
  7025. node.typeAnnotation = this.flowParsePrefixType();
  7026. return this.finishNode(node, "NullableTypeAnnotation");
  7027. } else {
  7028. return this.flowParsePostfixType();
  7029. }
  7030. }
  7031. flowParseAnonFunctionWithoutParens() {
  7032. const param = this.flowParsePrefixType();
  7033. if (!this.state.noAnonFunctionType && this.eat(19)) {
  7034. const node = this.startNodeAt(param.loc.start);
  7035. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  7036. node.rest = null;
  7037. node.this = null;
  7038. node.returnType = this.flowParseType();
  7039. node.typeParameters = null;
  7040. return this.finishNode(node, "FunctionTypeAnnotation");
  7041. }
  7042. return param;
  7043. }
  7044. flowParseIntersectionType() {
  7045. const node = this.startNode();
  7046. this.eat(45);
  7047. const type = this.flowParseAnonFunctionWithoutParens();
  7048. node.types = [type];
  7049. while (this.eat(45)) {
  7050. node.types.push(this.flowParseAnonFunctionWithoutParens());
  7051. }
  7052. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  7053. }
  7054. flowParseUnionType() {
  7055. const node = this.startNode();
  7056. this.eat(43);
  7057. const type = this.flowParseIntersectionType();
  7058. node.types = [type];
  7059. while (this.eat(43)) {
  7060. node.types.push(this.flowParseIntersectionType());
  7061. }
  7062. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  7063. }
  7064. flowParseType() {
  7065. const oldInType = this.state.inType;
  7066. this.state.inType = true;
  7067. const type = this.flowParseUnionType();
  7068. this.state.inType = oldInType;
  7069. return type;
  7070. }
  7071. flowParseTypeOrImplicitInstantiation() {
  7072. if (this.state.type === 132 && this.state.value === "_") {
  7073. const startLoc = this.state.startLoc;
  7074. const node = this.parseIdentifier();
  7075. return this.flowParseGenericType(startLoc, node);
  7076. } else {
  7077. return this.flowParseType();
  7078. }
  7079. }
  7080. flowParseTypeAnnotation() {
  7081. const node = this.startNode();
  7082. node.typeAnnotation = this.flowParseTypeInitialiser();
  7083. return this.finishNode(node, "TypeAnnotation");
  7084. }
  7085. flowParseTypeAnnotatableIdentifier() {
  7086. const node = this.startNode();
  7087. const name = this.parseIdentifierName();
  7088. if (this.match(14)) {
  7089. node.typeAnnotation = this.flowParseTypeAnnotation();
  7090. }
  7091. return this.createIdentifier(node, name);
  7092. }
  7093. typeCastToParameter(node) {
  7094. node.expression.typeAnnotation = node.typeAnnotation;
  7095. this.resetEndLocation(node.expression, node.typeAnnotation.loc.end);
  7096. return node.expression;
  7097. }
  7098. flowParseVariance() {
  7099. let variance = null;
  7100. if (this.match(53)) {
  7101. variance = this.startNode();
  7102. if (this.state.value === "+") {
  7103. variance.kind = "plus";
  7104. } else {
  7105. variance.kind = "minus";
  7106. }
  7107. this.next();
  7108. return this.finishNode(variance, "Variance");
  7109. }
  7110. return variance;
  7111. }
  7112. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  7113. if (allowExpressionBody) {
  7114. this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  7115. return;
  7116. }
  7117. super.parseFunctionBody(node, false, isMethod);
  7118. }
  7119. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  7120. if (this.match(14)) {
  7121. const typeNode = this.startNode();
  7122. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  7123. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  7124. }
  7125. return super.parseFunctionBodyAndFinish(node, type, isMethod);
  7126. }
  7127. parseStatementLike(flags) {
  7128. if (this.state.strict && this.isContextual(129)) {
  7129. const lookahead = this.lookahead();
  7130. if (tokenIsKeywordOrIdentifier(lookahead.type)) {
  7131. const node = this.startNode();
  7132. this.next();
  7133. return this.flowParseInterface(node);
  7134. }
  7135. } else if (this.isContextual(126)) {
  7136. const node = this.startNode();
  7137. this.next();
  7138. return this.flowParseEnumDeclaration(node);
  7139. }
  7140. const stmt = super.parseStatementLike(flags);
  7141. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  7142. this.flowPragma = null;
  7143. }
  7144. return stmt;
  7145. }
  7146. parseExpressionStatement(node, expr, decorators) {
  7147. if (expr.type === "Identifier") {
  7148. if (expr.name === "declare") {
  7149. if (this.match(80) || tokenIsIdentifier(this.state.type) || this.match(68) || this.match(74) || this.match(82)) {
  7150. return this.flowParseDeclare(node);
  7151. }
  7152. } else if (tokenIsIdentifier(this.state.type)) {
  7153. if (expr.name === "interface") {
  7154. return this.flowParseInterface(node);
  7155. } else if (expr.name === "type") {
  7156. return this.flowParseTypeAlias(node);
  7157. } else if (expr.name === "opaque") {
  7158. return this.flowParseOpaqueType(node, false);
  7159. }
  7160. }
  7161. }
  7162. return super.parseExpressionStatement(node, expr, decorators);
  7163. }
  7164. shouldParseExportDeclaration() {
  7165. const {
  7166. type
  7167. } = this.state;
  7168. if (type === 126 || tokenIsFlowInterfaceOrTypeOrOpaque(type)) {
  7169. return !this.state.containsEsc;
  7170. }
  7171. return super.shouldParseExportDeclaration();
  7172. }
  7173. isExportDefaultSpecifier() {
  7174. const {
  7175. type
  7176. } = this.state;
  7177. if (type === 126 || tokenIsFlowInterfaceOrTypeOrOpaque(type)) {
  7178. return this.state.containsEsc;
  7179. }
  7180. return super.isExportDefaultSpecifier();
  7181. }
  7182. parseExportDefaultExpression() {
  7183. if (this.isContextual(126)) {
  7184. const node = this.startNode();
  7185. this.next();
  7186. return this.flowParseEnumDeclaration(node);
  7187. }
  7188. return super.parseExportDefaultExpression();
  7189. }
  7190. parseConditional(expr, startLoc, refExpressionErrors) {
  7191. if (!this.match(17)) return expr;
  7192. if (this.state.maybeInArrowParameters) {
  7193. const nextCh = this.lookaheadCharCode();
  7194. if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) {
  7195. this.setOptionalParametersError(refExpressionErrors);
  7196. return expr;
  7197. }
  7198. }
  7199. this.expect(17);
  7200. const state = this.state.clone();
  7201. const originalNoArrowAt = this.state.noArrowAt;
  7202. const node = this.startNodeAt(startLoc);
  7203. let {
  7204. consequent,
  7205. failed
  7206. } = this.tryParseConditionalConsequent();
  7207. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  7208. if (failed || invalid.length > 0) {
  7209. const noArrowAt = [...originalNoArrowAt];
  7210. if (invalid.length > 0) {
  7211. this.state = state;
  7212. this.state.noArrowAt = noArrowAt;
  7213. for (let i = 0; i < invalid.length; i++) {
  7214. noArrowAt.push(invalid[i].start);
  7215. }
  7216. ({
  7217. consequent,
  7218. failed
  7219. } = this.tryParseConditionalConsequent());
  7220. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  7221. }
  7222. if (failed && valid.length > 1) {
  7223. this.raise(FlowErrors.AmbiguousConditionalArrow, state.startLoc);
  7224. }
  7225. if (failed && valid.length === 1) {
  7226. this.state = state;
  7227. noArrowAt.push(valid[0].start);
  7228. this.state.noArrowAt = noArrowAt;
  7229. ({
  7230. consequent,
  7231. failed
  7232. } = this.tryParseConditionalConsequent());
  7233. }
  7234. }
  7235. this.getArrowLikeExpressions(consequent, true);
  7236. this.state.noArrowAt = originalNoArrowAt;
  7237. this.expect(14);
  7238. node.test = expr;
  7239. node.consequent = consequent;
  7240. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined));
  7241. return this.finishNode(node, "ConditionalExpression");
  7242. }
  7243. tryParseConditionalConsequent() {
  7244. this.state.noArrowParamsConversionAt.push(this.state.start);
  7245. const consequent = this.parseMaybeAssignAllowIn();
  7246. const failed = !this.match(14);
  7247. this.state.noArrowParamsConversionAt.pop();
  7248. return {
  7249. consequent,
  7250. failed
  7251. };
  7252. }
  7253. getArrowLikeExpressions(node, disallowInvalid) {
  7254. const stack = [node];
  7255. const arrows = [];
  7256. while (stack.length !== 0) {
  7257. const node = stack.pop();
  7258. if (node.type === "ArrowFunctionExpression" && node.body.type !== "BlockStatement") {
  7259. if (node.typeParameters || !node.returnType) {
  7260. this.finishArrowValidation(node);
  7261. } else {
  7262. arrows.push(node);
  7263. }
  7264. stack.push(node.body);
  7265. } else if (node.type === "ConditionalExpression") {
  7266. stack.push(node.consequent);
  7267. stack.push(node.alternate);
  7268. }
  7269. }
  7270. if (disallowInvalid) {
  7271. arrows.forEach(node => this.finishArrowValidation(node));
  7272. return [arrows, []];
  7273. }
  7274. return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
  7275. }
  7276. finishArrowValidation(node) {
  7277. var _node$extra;
  7278. this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingCommaLoc, false);
  7279. this.scope.enter(514 | 4);
  7280. super.checkParams(node, false, true);
  7281. this.scope.exit();
  7282. }
  7283. forwardNoArrowParamsConversionAt(node, parse) {
  7284. let result;
  7285. if (this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))) {
  7286. this.state.noArrowParamsConversionAt.push(this.state.start);
  7287. result = parse();
  7288. this.state.noArrowParamsConversionAt.pop();
  7289. } else {
  7290. result = parse();
  7291. }
  7292. return result;
  7293. }
  7294. parseParenItem(node, startLoc) {
  7295. const newNode = super.parseParenItem(node, startLoc);
  7296. if (this.eat(17)) {
  7297. newNode.optional = true;
  7298. this.resetEndLocation(node);
  7299. }
  7300. if (this.match(14)) {
  7301. const typeCastNode = this.startNodeAt(startLoc);
  7302. typeCastNode.expression = newNode;
  7303. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  7304. return this.finishNode(typeCastNode, "TypeCastExpression");
  7305. }
  7306. return newNode;
  7307. }
  7308. assertModuleNodeAllowed(node) {
  7309. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  7310. return;
  7311. }
  7312. super.assertModuleNodeAllowed(node);
  7313. }
  7314. parseExportDeclaration(node) {
  7315. if (this.isContextual(130)) {
  7316. node.exportKind = "type";
  7317. const declarationNode = this.startNode();
  7318. this.next();
  7319. if (this.match(5)) {
  7320. node.specifiers = this.parseExportSpecifiers(true);
  7321. super.parseExportFrom(node);
  7322. return null;
  7323. } else {
  7324. return this.flowParseTypeAlias(declarationNode);
  7325. }
  7326. } else if (this.isContextual(131)) {
  7327. node.exportKind = "type";
  7328. const declarationNode = this.startNode();
  7329. this.next();
  7330. return this.flowParseOpaqueType(declarationNode, false);
  7331. } else if (this.isContextual(129)) {
  7332. node.exportKind = "type";
  7333. const declarationNode = this.startNode();
  7334. this.next();
  7335. return this.flowParseInterface(declarationNode);
  7336. } else if (this.isContextual(126)) {
  7337. node.exportKind = "value";
  7338. const declarationNode = this.startNode();
  7339. this.next();
  7340. return this.flowParseEnumDeclaration(declarationNode);
  7341. } else {
  7342. return super.parseExportDeclaration(node);
  7343. }
  7344. }
  7345. eatExportStar(node) {
  7346. if (super.eatExportStar(node)) return true;
  7347. if (this.isContextual(130) && this.lookahead().type === 55) {
  7348. node.exportKind = "type";
  7349. this.next();
  7350. this.next();
  7351. return true;
  7352. }
  7353. return false;
  7354. }
  7355. maybeParseExportNamespaceSpecifier(node) {
  7356. const {
  7357. startLoc
  7358. } = this.state;
  7359. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  7360. if (hasNamespace && node.exportKind === "type") {
  7361. this.unexpected(startLoc);
  7362. }
  7363. return hasNamespace;
  7364. }
  7365. parseClassId(node, isStatement, optionalId) {
  7366. super.parseClassId(node, isStatement, optionalId);
  7367. if (this.match(47)) {
  7368. node.typeParameters = this.flowParseTypeParameterDeclaration();
  7369. }
  7370. }
  7371. parseClassMember(classBody, member, state) {
  7372. const {
  7373. startLoc
  7374. } = this.state;
  7375. if (this.isContextual(125)) {
  7376. if (super.parseClassMemberFromModifier(classBody, member)) {
  7377. return;
  7378. }
  7379. member.declare = true;
  7380. }
  7381. super.parseClassMember(classBody, member, state);
  7382. if (member.declare) {
  7383. if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty" && member.type !== "PropertyDefinition") {
  7384. this.raise(FlowErrors.DeclareClassElement, startLoc);
  7385. } else if (member.value) {
  7386. this.raise(FlowErrors.DeclareClassFieldInitializer, member.value);
  7387. }
  7388. }
  7389. }
  7390. isIterator(word) {
  7391. return word === "iterator" || word === "asyncIterator";
  7392. }
  7393. readIterator() {
  7394. const word = super.readWord1();
  7395. const fullWord = "@@" + word;
  7396. if (!this.isIterator(word) || !this.state.inType) {
  7397. this.raise(Errors.InvalidIdentifier, this.state.curPosition(), {
  7398. identifierName: fullWord
  7399. });
  7400. }
  7401. this.finishToken(132, fullWord);
  7402. }
  7403. getTokenFromCode(code) {
  7404. const next = this.input.charCodeAt(this.state.pos + 1);
  7405. if (code === 123 && next === 124) {
  7406. this.finishOp(6, 2);
  7407. } else if (this.state.inType && (code === 62 || code === 60)) {
  7408. this.finishOp(code === 62 ? 48 : 47, 1);
  7409. } else if (this.state.inType && code === 63) {
  7410. if (next === 46) {
  7411. this.finishOp(18, 2);
  7412. } else {
  7413. this.finishOp(17, 1);
  7414. }
  7415. } else if (isIteratorStart(code, next, this.input.charCodeAt(this.state.pos + 2))) {
  7416. this.state.pos += 2;
  7417. this.readIterator();
  7418. } else {
  7419. super.getTokenFromCode(code);
  7420. }
  7421. }
  7422. isAssignable(node, isBinding) {
  7423. if (node.type === "TypeCastExpression") {
  7424. return this.isAssignable(node.expression, isBinding);
  7425. } else {
  7426. return super.isAssignable(node, isBinding);
  7427. }
  7428. }
  7429. toAssignable(node, isLHS = false) {
  7430. if (!isLHS && node.type === "AssignmentExpression" && node.left.type === "TypeCastExpression") {
  7431. node.left = this.typeCastToParameter(node.left);
  7432. }
  7433. super.toAssignable(node, isLHS);
  7434. }
  7435. toAssignableList(exprList, trailingCommaLoc, isLHS) {
  7436. for (let i = 0; i < exprList.length; i++) {
  7437. const expr = exprList[i];
  7438. if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") {
  7439. exprList[i] = this.typeCastToParameter(expr);
  7440. }
  7441. }
  7442. super.toAssignableList(exprList, trailingCommaLoc, isLHS);
  7443. }
  7444. toReferencedList(exprList, isParenthesizedExpr) {
  7445. for (let i = 0; i < exprList.length; i++) {
  7446. var _expr$extra;
  7447. const expr = exprList[i];
  7448. if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) != null && _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
  7449. this.raise(FlowErrors.TypeCastInPattern, expr.typeAnnotation);
  7450. }
  7451. }
  7452. return exprList;
  7453. }
  7454. parseArrayLike(close, isTuple, refExpressionErrors) {
  7455. const node = super.parseArrayLike(close, isTuple, refExpressionErrors);
  7456. if (refExpressionErrors != null && !this.state.maybeInArrowParameters) {
  7457. this.toReferencedList(node.elements);
  7458. }
  7459. return node;
  7460. }
  7461. isValidLVal(type, disallowCallExpression, isParenthesized, binding) {
  7462. return type === "TypeCastExpression" || super.isValidLVal(type, disallowCallExpression, isParenthesized, binding);
  7463. }
  7464. parseClassProperty(node) {
  7465. if (this.match(14)) {
  7466. node.typeAnnotation = this.flowParseTypeAnnotation();
  7467. }
  7468. return super.parseClassProperty(node);
  7469. }
  7470. parseClassPrivateProperty(node) {
  7471. if (this.match(14)) {
  7472. node.typeAnnotation = this.flowParseTypeAnnotation();
  7473. }
  7474. return super.parseClassPrivateProperty(node);
  7475. }
  7476. isClassMethod() {
  7477. return this.match(47) || super.isClassMethod();
  7478. }
  7479. isClassProperty() {
  7480. return this.match(14) || super.isClassProperty();
  7481. }
  7482. isNonstaticConstructor(method) {
  7483. return !this.match(14) && super.isNonstaticConstructor(method);
  7484. }
  7485. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  7486. if (method.variance) {
  7487. this.unexpected(method.variance.loc.start);
  7488. }
  7489. delete method.variance;
  7490. if (this.match(47)) {
  7491. method.typeParameters = this.flowParseTypeParameterDeclaration();
  7492. }
  7493. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  7494. if (method.params && isConstructor) {
  7495. const params = method.params;
  7496. if (params.length > 0 && this.isThisParam(params[0])) {
  7497. this.raise(FlowErrors.ThisParamBannedInConstructor, method);
  7498. }
  7499. } else if (method.type === "MethodDefinition" && isConstructor && method.value.params) {
  7500. const params = method.value.params;
  7501. if (params.length > 0 && this.isThisParam(params[0])) {
  7502. this.raise(FlowErrors.ThisParamBannedInConstructor, method);
  7503. }
  7504. }
  7505. }
  7506. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  7507. if (method.variance) {
  7508. this.unexpected(method.variance.loc.start);
  7509. }
  7510. delete method.variance;
  7511. if (this.match(47)) {
  7512. method.typeParameters = this.flowParseTypeParameterDeclaration();
  7513. }
  7514. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  7515. }
  7516. parseClassSuper(node) {
  7517. super.parseClassSuper(node);
  7518. if (node.superClass && (this.match(47) || this.match(51))) {
  7519. node.superTypeParameters = this.flowParseTypeParameterInstantiationInExpression();
  7520. }
  7521. if (this.isContextual(113)) {
  7522. this.next();
  7523. const implemented = node.implements = [];
  7524. do {
  7525. const node = this.startNode();
  7526. node.id = this.flowParseRestrictedIdentifier(true);
  7527. if (this.match(47)) {
  7528. node.typeParameters = this.flowParseTypeParameterInstantiation();
  7529. } else {
  7530. node.typeParameters = null;
  7531. }
  7532. implemented.push(this.finishNode(node, "ClassImplements"));
  7533. } while (this.eat(12));
  7534. }
  7535. }
  7536. checkGetterSetterParams(method) {
  7537. super.checkGetterSetterParams(method);
  7538. const params = this.getObjectOrClassMethodParams(method);
  7539. if (params.length > 0) {
  7540. const param = params[0];
  7541. if (this.isThisParam(param) && method.kind === "get") {
  7542. this.raise(FlowErrors.GetterMayNotHaveThisParam, param);
  7543. } else if (this.isThisParam(param)) {
  7544. this.raise(FlowErrors.SetterMayNotHaveThisParam, param);
  7545. }
  7546. }
  7547. }
  7548. parsePropertyNamePrefixOperator(node) {
  7549. node.variance = this.flowParseVariance();
  7550. }
  7551. parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  7552. if (prop.variance) {
  7553. this.unexpected(prop.variance.loc.start);
  7554. }
  7555. delete prop.variance;
  7556. let typeParameters;
  7557. if (this.match(47) && !isAccessor) {
  7558. typeParameters = this.flowParseTypeParameterDeclaration();
  7559. if (!this.match(10)) this.unexpected();
  7560. }
  7561. const result = super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  7562. if (typeParameters) {
  7563. (result.value || result).typeParameters = typeParameters;
  7564. }
  7565. return result;
  7566. }
  7567. parseFunctionParamType(param) {
  7568. if (this.eat(17)) {
  7569. if (param.type !== "Identifier") {
  7570. this.raise(FlowErrors.PatternIsOptional, param);
  7571. }
  7572. if (this.isThisParam(param)) {
  7573. this.raise(FlowErrors.ThisParamMayNotBeOptional, param);
  7574. }
  7575. param.optional = true;
  7576. }
  7577. if (this.match(14)) {
  7578. param.typeAnnotation = this.flowParseTypeAnnotation();
  7579. } else if (this.isThisParam(param)) {
  7580. this.raise(FlowErrors.ThisParamAnnotationRequired, param);
  7581. }
  7582. if (this.match(29) && this.isThisParam(param)) {
  7583. this.raise(FlowErrors.ThisParamNoDefault, param);
  7584. }
  7585. this.resetEndLocation(param);
  7586. return param;
  7587. }
  7588. parseMaybeDefault(startLoc, left) {
  7589. const node = super.parseMaybeDefault(startLoc, left);
  7590. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  7591. this.raise(FlowErrors.TypeBeforeInitializer, node.typeAnnotation);
  7592. }
  7593. return node;
  7594. }
  7595. checkImportReflection(node) {
  7596. super.checkImportReflection(node);
  7597. if (node.module && node.importKind !== "value") {
  7598. this.raise(FlowErrors.ImportReflectionHasImportType, node.specifiers[0].loc.start);
  7599. }
  7600. }
  7601. parseImportSpecifierLocal(node, specifier, type) {
  7602. specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
  7603. node.specifiers.push(this.finishImportSpecifier(specifier, type));
  7604. }
  7605. isPotentialImportPhase(isExport) {
  7606. if (super.isPotentialImportPhase(isExport)) return true;
  7607. if (this.isContextual(130)) {
  7608. if (!isExport) return true;
  7609. const ch = this.lookaheadCharCode();
  7610. return ch === 123 || ch === 42;
  7611. }
  7612. return !isExport && this.isContextual(87);
  7613. }
  7614. applyImportPhase(node, isExport, phase, loc) {
  7615. super.applyImportPhase(node, isExport, phase, loc);
  7616. if (isExport) {
  7617. if (!phase && this.match(65)) {
  7618. return;
  7619. }
  7620. node.exportKind = phase === "type" ? phase : "value";
  7621. } else {
  7622. if (phase === "type" && this.match(55)) this.unexpected();
  7623. node.importKind = phase === "type" || phase === "typeof" ? phase : "value";
  7624. }
  7625. }
  7626. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) {
  7627. const firstIdent = specifier.imported;
  7628. let specifierTypeKind = null;
  7629. if (firstIdent.type === "Identifier") {
  7630. if (firstIdent.name === "type") {
  7631. specifierTypeKind = "type";
  7632. } else if (firstIdent.name === "typeof") {
  7633. specifierTypeKind = "typeof";
  7634. }
  7635. }
  7636. let isBinding = false;
  7637. if (this.isContextual(93) && !this.isLookaheadContextual("as")) {
  7638. const as_ident = this.parseIdentifier(true);
  7639. if (specifierTypeKind !== null && !tokenIsKeywordOrIdentifier(this.state.type)) {
  7640. specifier.imported = as_ident;
  7641. specifier.importKind = specifierTypeKind;
  7642. specifier.local = this.cloneIdentifier(as_ident);
  7643. } else {
  7644. specifier.imported = firstIdent;
  7645. specifier.importKind = null;
  7646. specifier.local = this.parseIdentifier();
  7647. }
  7648. } else {
  7649. if (specifierTypeKind !== null && tokenIsKeywordOrIdentifier(this.state.type)) {
  7650. specifier.imported = this.parseIdentifier(true);
  7651. specifier.importKind = specifierTypeKind;
  7652. } else {
  7653. if (importedIsString) {
  7654. throw this.raise(Errors.ImportBindingIsString, specifier, {
  7655. importName: firstIdent.value
  7656. });
  7657. }
  7658. specifier.imported = firstIdent;
  7659. specifier.importKind = null;
  7660. }
  7661. if (this.eatContextual(93)) {
  7662. specifier.local = this.parseIdentifier();
  7663. } else {
  7664. isBinding = true;
  7665. specifier.local = this.cloneIdentifier(specifier.imported);
  7666. }
  7667. }
  7668. const specifierIsTypeImport = hasTypeImportKind(specifier);
  7669. if (isInTypeOnlyImport && specifierIsTypeImport) {
  7670. this.raise(FlowErrors.ImportTypeShorthandOnlyInPureImport, specifier);
  7671. }
  7672. if (isInTypeOnlyImport || specifierIsTypeImport) {
  7673. this.checkReservedType(specifier.local.name, specifier.local.loc.start, true);
  7674. }
  7675. if (isBinding && !isInTypeOnlyImport && !specifierIsTypeImport) {
  7676. this.checkReservedWord(specifier.local.name, specifier.loc.start, true, true);
  7677. }
  7678. return this.finishImportSpecifier(specifier, "ImportSpecifier");
  7679. }
  7680. parseBindingAtom() {
  7681. switch (this.state.type) {
  7682. case 78:
  7683. return this.parseIdentifier(true);
  7684. default:
  7685. return super.parseBindingAtom();
  7686. }
  7687. }
  7688. parseFunctionParams(node, isConstructor) {
  7689. const kind = node.kind;
  7690. if (kind !== "get" && kind !== "set" && this.match(47)) {
  7691. node.typeParameters = this.flowParseTypeParameterDeclaration();
  7692. }
  7693. super.parseFunctionParams(node, isConstructor);
  7694. }
  7695. parseVarId(decl, kind) {
  7696. super.parseVarId(decl, kind);
  7697. if (this.match(14)) {
  7698. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  7699. this.resetEndLocation(decl.id);
  7700. }
  7701. }
  7702. parseAsyncArrowFromCallExpression(node, call) {
  7703. if (this.match(14)) {
  7704. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  7705. this.state.noAnonFunctionType = true;
  7706. node.returnType = this.flowParseTypeAnnotation();
  7707. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  7708. }
  7709. return super.parseAsyncArrowFromCallExpression(node, call);
  7710. }
  7711. shouldParseAsyncArrow() {
  7712. return this.match(14) || super.shouldParseAsyncArrow();
  7713. }
  7714. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  7715. var _jsx;
  7716. let state = null;
  7717. let jsx;
  7718. if (this.hasPlugin("jsx") && (this.match(143) || this.match(47))) {
  7719. state = this.state.clone();
  7720. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  7721. if (!jsx.error) return jsx.node;
  7722. const {
  7723. context
  7724. } = this.state;
  7725. const currentContext = context[context.length - 1];
  7726. if (currentContext === types.j_oTag || currentContext === types.j_expr) {
  7727. context.pop();
  7728. }
  7729. }
  7730. if ((_jsx = jsx) != null && _jsx.error || this.match(47)) {
  7731. var _jsx2, _jsx3;
  7732. state = state || this.state.clone();
  7733. let typeParameters;
  7734. const arrow = this.tryParse(abort => {
  7735. var _arrowExpression$extr;
  7736. typeParameters = this.flowParseTypeParameterDeclaration();
  7737. const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => {
  7738. const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  7739. this.resetStartLocationFromNode(result, typeParameters);
  7740. return result;
  7741. });
  7742. if ((_arrowExpression$extr = arrowExpression.extra) != null && _arrowExpression$extr.parenthesized) abort();
  7743. const expr = this.maybeUnwrapTypeCastExpression(arrowExpression);
  7744. if (expr.type !== "ArrowFunctionExpression") abort();
  7745. expr.typeParameters = typeParameters;
  7746. this.resetStartLocationFromNode(expr, typeParameters);
  7747. return arrowExpression;
  7748. }, state);
  7749. let arrowExpression = null;
  7750. if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") {
  7751. if (!arrow.error && !arrow.aborted) {
  7752. if (arrow.node.async) {
  7753. this.raise(FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction, typeParameters);
  7754. }
  7755. return arrow.node;
  7756. }
  7757. arrowExpression = arrow.node;
  7758. }
  7759. if ((_jsx2 = jsx) != null && _jsx2.node) {
  7760. this.state = jsx.failState;
  7761. return jsx.node;
  7762. }
  7763. if (arrowExpression) {
  7764. this.state = arrow.failState;
  7765. return arrowExpression;
  7766. }
  7767. if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error;
  7768. if (arrow.thrown) throw arrow.error;
  7769. throw this.raise(FlowErrors.UnexpectedTokenAfterTypeParameter, typeParameters);
  7770. }
  7771. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  7772. }
  7773. parseArrow(node) {
  7774. if (this.match(14)) {
  7775. const result = this.tryParse(() => {
  7776. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  7777. this.state.noAnonFunctionType = true;
  7778. const typeNode = this.startNode();
  7779. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  7780. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  7781. if (this.canInsertSemicolon()) this.unexpected();
  7782. if (!this.match(19)) this.unexpected();
  7783. return typeNode;
  7784. });
  7785. if (result.thrown) return null;
  7786. if (result.error) this.state = result.failState;
  7787. node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
  7788. }
  7789. return super.parseArrow(node);
  7790. }
  7791. shouldParseArrow(params) {
  7792. return this.match(14) || super.shouldParseArrow(params);
  7793. }
  7794. setArrowFunctionParameters(node, params) {
  7795. if (this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))) {
  7796. node.params = params;
  7797. } else {
  7798. super.setArrowFunctionParameters(node, params);
  7799. }
  7800. }
  7801. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  7802. if (isArrowFunction && this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))) {
  7803. return;
  7804. }
  7805. for (let i = 0; i < node.params.length; i++) {
  7806. if (this.isThisParam(node.params[i]) && i > 0) {
  7807. this.raise(FlowErrors.ThisParamMustBeFirst, node.params[i]);
  7808. }
  7809. }
  7810. super.checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged);
  7811. }
  7812. parseParenAndDistinguishExpression(canBeArrow) {
  7813. return super.parseParenAndDistinguishExpression(canBeArrow && !this.state.noArrowAt.includes(this.sourceToOffsetPos(this.state.start)));
  7814. }
  7815. parseSubscripts(base, startLoc, noCalls) {
  7816. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.includes(startLoc.index)) {
  7817. this.next();
  7818. const node = this.startNodeAt(startLoc);
  7819. node.callee = base;
  7820. node.arguments = super.parseCallExpressionArguments();
  7821. base = this.finishNode(node, "CallExpression");
  7822. } else if (base.type === "Identifier" && base.name === "async" && this.match(47)) {
  7823. const state = this.state.clone();
  7824. const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startLoc) || abort(), state);
  7825. if (!arrow.error && !arrow.aborted) return arrow.node;
  7826. const result = this.tryParse(() => super.parseSubscripts(base, startLoc, noCalls), state);
  7827. if (result.node && !result.error) return result.node;
  7828. if (arrow.node) {
  7829. this.state = arrow.failState;
  7830. return arrow.node;
  7831. }
  7832. if (result.node) {
  7833. this.state = result.failState;
  7834. return result.node;
  7835. }
  7836. throw arrow.error || result.error;
  7837. }
  7838. return super.parseSubscripts(base, startLoc, noCalls);
  7839. }
  7840. parseSubscript(base, startLoc, noCalls, subscriptState) {
  7841. if (this.match(18) && this.isLookaheadToken_lt()) {
  7842. subscriptState.optionalChainMember = true;
  7843. if (noCalls) {
  7844. subscriptState.stop = true;
  7845. return base;
  7846. }
  7847. this.next();
  7848. const node = this.startNodeAt(startLoc);
  7849. node.callee = base;
  7850. node.typeArguments = this.flowParseTypeParameterInstantiationInExpression();
  7851. this.expect(10);
  7852. node.arguments = this.parseCallExpressionArguments();
  7853. node.optional = true;
  7854. return this.finishCallExpression(node, true);
  7855. } else if (!noCalls && this.shouldParseTypes() && (this.match(47) || this.match(51))) {
  7856. const node = this.startNodeAt(startLoc);
  7857. node.callee = base;
  7858. const result = this.tryParse(() => {
  7859. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  7860. this.expect(10);
  7861. node.arguments = super.parseCallExpressionArguments();
  7862. if (subscriptState.optionalChainMember) {
  7863. node.optional = false;
  7864. }
  7865. return this.finishCallExpression(node, subscriptState.optionalChainMember);
  7866. });
  7867. if (result.node) {
  7868. if (result.error) this.state = result.failState;
  7869. return result.node;
  7870. }
  7871. }
  7872. return super.parseSubscript(base, startLoc, noCalls, subscriptState);
  7873. }
  7874. parseNewCallee(node) {
  7875. super.parseNewCallee(node);
  7876. let targs = null;
  7877. if (this.shouldParseTypes() && this.match(47)) {
  7878. targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
  7879. }
  7880. node.typeArguments = targs;
  7881. }
  7882. parseAsyncArrowWithTypeParameters(startLoc) {
  7883. const node = this.startNodeAt(startLoc);
  7884. this.parseFunctionParams(node, false);
  7885. if (!this.parseArrow(node)) return;
  7886. return super.parseArrowExpression(node, undefined, true);
  7887. }
  7888. readToken_mult_modulo(code) {
  7889. const next = this.input.charCodeAt(this.state.pos + 1);
  7890. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  7891. this.state.hasFlowComment = false;
  7892. this.state.pos += 2;
  7893. this.nextToken();
  7894. return;
  7895. }
  7896. super.readToken_mult_modulo(code);
  7897. }
  7898. readToken_pipe_amp(code) {
  7899. const next = this.input.charCodeAt(this.state.pos + 1);
  7900. if (code === 124 && next === 125) {
  7901. this.finishOp(9, 2);
  7902. return;
  7903. }
  7904. super.readToken_pipe_amp(code);
  7905. }
  7906. parseTopLevel(file, program) {
  7907. const fileNode = super.parseTopLevel(file, program);
  7908. if (this.state.hasFlowComment) {
  7909. this.raise(FlowErrors.UnterminatedFlowComment, this.state.curPosition());
  7910. }
  7911. return fileNode;
  7912. }
  7913. skipBlockComment() {
  7914. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  7915. if (this.state.hasFlowComment) {
  7916. throw this.raise(FlowErrors.NestedFlowComment, this.state.startLoc);
  7917. }
  7918. this.hasFlowCommentCompletion();
  7919. const commentSkip = this.skipFlowComment();
  7920. if (commentSkip) {
  7921. this.state.pos += commentSkip;
  7922. this.state.hasFlowComment = true;
  7923. }
  7924. return;
  7925. }
  7926. return super.skipBlockComment(this.state.hasFlowComment ? "*-/" : "*/");
  7927. }
  7928. skipFlowComment() {
  7929. const {
  7930. pos
  7931. } = this.state;
  7932. let shiftToFirstNonWhiteSpace = 2;
  7933. while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  7934. shiftToFirstNonWhiteSpace++;
  7935. }
  7936. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  7937. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  7938. if (ch2 === 58 && ch3 === 58) {
  7939. return shiftToFirstNonWhiteSpace + 2;
  7940. }
  7941. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  7942. return shiftToFirstNonWhiteSpace + 12;
  7943. }
  7944. if (ch2 === 58 && ch3 !== 58) {
  7945. return shiftToFirstNonWhiteSpace;
  7946. }
  7947. return false;
  7948. }
  7949. hasFlowCommentCompletion() {
  7950. const end = this.input.indexOf("*/", this.state.pos);
  7951. if (end === -1) {
  7952. throw this.raise(Errors.UnterminatedComment, this.state.curPosition());
  7953. }
  7954. }
  7955. flowEnumErrorBooleanMemberNotInitialized(loc, {
  7956. enumName,
  7957. memberName
  7958. }) {
  7959. this.raise(FlowErrors.EnumBooleanMemberNotInitialized, loc, {
  7960. memberName,
  7961. enumName
  7962. });
  7963. }
  7964. flowEnumErrorInvalidMemberInitializer(loc, enumContext) {
  7965. return this.raise(!enumContext.explicitType ? FlowErrors.EnumInvalidMemberInitializerUnknownType : enumContext.explicitType === "symbol" ? FlowErrors.EnumInvalidMemberInitializerSymbolType : FlowErrors.EnumInvalidMemberInitializerPrimaryType, loc, enumContext);
  7966. }
  7967. flowEnumErrorNumberMemberNotInitialized(loc, details) {
  7968. this.raise(FlowErrors.EnumNumberMemberNotInitialized, loc, details);
  7969. }
  7970. flowEnumErrorStringMemberInconsistentlyInitialized(node, details) {
  7971. this.raise(FlowErrors.EnumStringMemberInconsistentlyInitialized, node, details);
  7972. }
  7973. flowEnumMemberInit() {
  7974. const startLoc = this.state.startLoc;
  7975. const endOfInit = () => this.match(12) || this.match(8);
  7976. switch (this.state.type) {
  7977. case 135:
  7978. {
  7979. const literal = this.parseNumericLiteral(this.state.value);
  7980. if (endOfInit()) {
  7981. return {
  7982. type: "number",
  7983. loc: literal.loc.start,
  7984. value: literal
  7985. };
  7986. }
  7987. return {
  7988. type: "invalid",
  7989. loc: startLoc
  7990. };
  7991. }
  7992. case 134:
  7993. {
  7994. const literal = this.parseStringLiteral(this.state.value);
  7995. if (endOfInit()) {
  7996. return {
  7997. type: "string",
  7998. loc: literal.loc.start,
  7999. value: literal
  8000. };
  8001. }
  8002. return {
  8003. type: "invalid",
  8004. loc: startLoc
  8005. };
  8006. }
  8007. case 85:
  8008. case 86:
  8009. {
  8010. const literal = this.parseBooleanLiteral(this.match(85));
  8011. if (endOfInit()) {
  8012. return {
  8013. type: "boolean",
  8014. loc: literal.loc.start,
  8015. value: literal
  8016. };
  8017. }
  8018. return {
  8019. type: "invalid",
  8020. loc: startLoc
  8021. };
  8022. }
  8023. default:
  8024. return {
  8025. type: "invalid",
  8026. loc: startLoc
  8027. };
  8028. }
  8029. }
  8030. flowEnumMemberRaw() {
  8031. const loc = this.state.startLoc;
  8032. const id = this.parseIdentifier(true);
  8033. const init = this.eat(29) ? this.flowEnumMemberInit() : {
  8034. type: "none",
  8035. loc
  8036. };
  8037. return {
  8038. id,
  8039. init
  8040. };
  8041. }
  8042. flowEnumCheckExplicitTypeMismatch(loc, context, expectedType) {
  8043. const {
  8044. explicitType
  8045. } = context;
  8046. if (explicitType === null) {
  8047. return;
  8048. }
  8049. if (explicitType !== expectedType) {
  8050. this.flowEnumErrorInvalidMemberInitializer(loc, context);
  8051. }
  8052. }
  8053. flowEnumMembers({
  8054. enumName,
  8055. explicitType
  8056. }) {
  8057. const seenNames = new Set();
  8058. const members = {
  8059. booleanMembers: [],
  8060. numberMembers: [],
  8061. stringMembers: [],
  8062. defaultedMembers: []
  8063. };
  8064. let hasUnknownMembers = false;
  8065. while (!this.match(8)) {
  8066. if (this.eat(21)) {
  8067. hasUnknownMembers = true;
  8068. break;
  8069. }
  8070. const memberNode = this.startNode();
  8071. const {
  8072. id,
  8073. init
  8074. } = this.flowEnumMemberRaw();
  8075. const memberName = id.name;
  8076. if (memberName === "") {
  8077. continue;
  8078. }
  8079. if (/^[a-z]/.test(memberName)) {
  8080. this.raise(FlowErrors.EnumInvalidMemberName, id, {
  8081. memberName,
  8082. suggestion: memberName[0].toUpperCase() + memberName.slice(1),
  8083. enumName
  8084. });
  8085. }
  8086. if (seenNames.has(memberName)) {
  8087. this.raise(FlowErrors.EnumDuplicateMemberName, id, {
  8088. memberName,
  8089. enumName
  8090. });
  8091. }
  8092. seenNames.add(memberName);
  8093. const context = {
  8094. enumName,
  8095. explicitType,
  8096. memberName
  8097. };
  8098. memberNode.id = id;
  8099. switch (init.type) {
  8100. case "boolean":
  8101. {
  8102. this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "boolean");
  8103. memberNode.init = init.value;
  8104. members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
  8105. break;
  8106. }
  8107. case "number":
  8108. {
  8109. this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "number");
  8110. memberNode.init = init.value;
  8111. members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
  8112. break;
  8113. }
  8114. case "string":
  8115. {
  8116. this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "string");
  8117. memberNode.init = init.value;
  8118. members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
  8119. break;
  8120. }
  8121. case "invalid":
  8122. {
  8123. throw this.flowEnumErrorInvalidMemberInitializer(init.loc, context);
  8124. }
  8125. case "none":
  8126. {
  8127. switch (explicitType) {
  8128. case "boolean":
  8129. this.flowEnumErrorBooleanMemberNotInitialized(init.loc, context);
  8130. break;
  8131. case "number":
  8132. this.flowEnumErrorNumberMemberNotInitialized(init.loc, context);
  8133. break;
  8134. default:
  8135. members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
  8136. }
  8137. }
  8138. }
  8139. if (!this.match(8)) {
  8140. this.expect(12);
  8141. }
  8142. }
  8143. return {
  8144. members,
  8145. hasUnknownMembers
  8146. };
  8147. }
  8148. flowEnumStringMembers(initializedMembers, defaultedMembers, {
  8149. enumName
  8150. }) {
  8151. if (initializedMembers.length === 0) {
  8152. return defaultedMembers;
  8153. } else if (defaultedMembers.length === 0) {
  8154. return initializedMembers;
  8155. } else if (defaultedMembers.length > initializedMembers.length) {
  8156. for (const member of initializedMembers) {
  8157. this.flowEnumErrorStringMemberInconsistentlyInitialized(member, {
  8158. enumName
  8159. });
  8160. }
  8161. return defaultedMembers;
  8162. } else {
  8163. for (const member of defaultedMembers) {
  8164. this.flowEnumErrorStringMemberInconsistentlyInitialized(member, {
  8165. enumName
  8166. });
  8167. }
  8168. return initializedMembers;
  8169. }
  8170. }
  8171. flowEnumParseExplicitType({
  8172. enumName
  8173. }) {
  8174. if (!this.eatContextual(102)) return null;
  8175. if (!tokenIsIdentifier(this.state.type)) {
  8176. throw this.raise(FlowErrors.EnumInvalidExplicitTypeUnknownSupplied, this.state.startLoc, {
  8177. enumName
  8178. });
  8179. }
  8180. const {
  8181. value
  8182. } = this.state;
  8183. this.next();
  8184. if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
  8185. this.raise(FlowErrors.EnumInvalidExplicitType, this.state.startLoc, {
  8186. enumName,
  8187. invalidEnumType: value
  8188. });
  8189. }
  8190. return value;
  8191. }
  8192. flowEnumBody(node, id) {
  8193. const enumName = id.name;
  8194. const nameLoc = id.loc.start;
  8195. const explicitType = this.flowEnumParseExplicitType({
  8196. enumName
  8197. });
  8198. this.expect(5);
  8199. const {
  8200. members,
  8201. hasUnknownMembers
  8202. } = this.flowEnumMembers({
  8203. enumName,
  8204. explicitType
  8205. });
  8206. node.hasUnknownMembers = hasUnknownMembers;
  8207. switch (explicitType) {
  8208. case "boolean":
  8209. node.explicitType = true;
  8210. node.members = members.booleanMembers;
  8211. this.expect(8);
  8212. return this.finishNode(node, "EnumBooleanBody");
  8213. case "number":
  8214. node.explicitType = true;
  8215. node.members = members.numberMembers;
  8216. this.expect(8);
  8217. return this.finishNode(node, "EnumNumberBody");
  8218. case "string":
  8219. node.explicitType = true;
  8220. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  8221. enumName
  8222. });
  8223. this.expect(8);
  8224. return this.finishNode(node, "EnumStringBody");
  8225. case "symbol":
  8226. node.members = members.defaultedMembers;
  8227. this.expect(8);
  8228. return this.finishNode(node, "EnumSymbolBody");
  8229. default:
  8230. {
  8231. const empty = () => {
  8232. node.members = [];
  8233. this.expect(8);
  8234. return this.finishNode(node, "EnumStringBody");
  8235. };
  8236. node.explicitType = false;
  8237. const boolsLen = members.booleanMembers.length;
  8238. const numsLen = members.numberMembers.length;
  8239. const strsLen = members.stringMembers.length;
  8240. const defaultedLen = members.defaultedMembers.length;
  8241. if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
  8242. return empty();
  8243. } else if (!boolsLen && !numsLen) {
  8244. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  8245. enumName
  8246. });
  8247. this.expect(8);
  8248. return this.finishNode(node, "EnumStringBody");
  8249. } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
  8250. for (const member of members.defaultedMembers) {
  8251. this.flowEnumErrorBooleanMemberNotInitialized(member.loc.start, {
  8252. enumName,
  8253. memberName: member.id.name
  8254. });
  8255. }
  8256. node.members = members.booleanMembers;
  8257. this.expect(8);
  8258. return this.finishNode(node, "EnumBooleanBody");
  8259. } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
  8260. for (const member of members.defaultedMembers) {
  8261. this.flowEnumErrorNumberMemberNotInitialized(member.loc.start, {
  8262. enumName,
  8263. memberName: member.id.name
  8264. });
  8265. }
  8266. node.members = members.numberMembers;
  8267. this.expect(8);
  8268. return this.finishNode(node, "EnumNumberBody");
  8269. } else {
  8270. this.raise(FlowErrors.EnumInconsistentMemberValues, nameLoc, {
  8271. enumName
  8272. });
  8273. return empty();
  8274. }
  8275. }
  8276. }
  8277. }
  8278. flowParseEnumDeclaration(node) {
  8279. const id = this.parseIdentifier();
  8280. node.id = id;
  8281. node.body = this.flowEnumBody(this.startNode(), id);
  8282. return this.finishNode(node, "EnumDeclaration");
  8283. }
  8284. jsxParseOpeningElementAfterName(node) {
  8285. if (this.shouldParseTypes()) {
  8286. if (this.match(47) || this.match(51)) {
  8287. node.typeArguments = this.flowParseTypeParameterInstantiationInExpression();
  8288. }
  8289. }
  8290. return super.jsxParseOpeningElementAfterName(node);
  8291. }
  8292. isLookaheadToken_lt() {
  8293. const next = this.nextTokenStart();
  8294. if (this.input.charCodeAt(next) === 60) {
  8295. const afterNext = this.input.charCodeAt(next + 1);
  8296. return afterNext !== 60 && afterNext !== 61;
  8297. }
  8298. return false;
  8299. }
  8300. reScan_lt_gt() {
  8301. const {
  8302. type
  8303. } = this.state;
  8304. if (type === 47) {
  8305. this.state.pos -= 1;
  8306. this.readToken_lt();
  8307. } else if (type === 48) {
  8308. this.state.pos -= 1;
  8309. this.readToken_gt();
  8310. }
  8311. }
  8312. reScan_lt() {
  8313. const {
  8314. type
  8315. } = this.state;
  8316. if (type === 51) {
  8317. this.state.pos -= 2;
  8318. this.finishOp(47, 1);
  8319. return 47;
  8320. }
  8321. return type;
  8322. }
  8323. maybeUnwrapTypeCastExpression(node) {
  8324. return node.type === "TypeCastExpression" ? node.expression : node;
  8325. }
  8326. };
  8327. const entities = {
  8328. __proto__: null,
  8329. quot: "\u0022",
  8330. amp: "&",
  8331. apos: "\u0027",
  8332. lt: "<",
  8333. gt: ">",
  8334. nbsp: "\u00A0",
  8335. iexcl: "\u00A1",
  8336. cent: "\u00A2",
  8337. pound: "\u00A3",
  8338. curren: "\u00A4",
  8339. yen: "\u00A5",
  8340. brvbar: "\u00A6",
  8341. sect: "\u00A7",
  8342. uml: "\u00A8",
  8343. copy: "\u00A9",
  8344. ordf: "\u00AA",
  8345. laquo: "\u00AB",
  8346. not: "\u00AC",
  8347. shy: "\u00AD",
  8348. reg: "\u00AE",
  8349. macr: "\u00AF",
  8350. deg: "\u00B0",
  8351. plusmn: "\u00B1",
  8352. sup2: "\u00B2",
  8353. sup3: "\u00B3",
  8354. acute: "\u00B4",
  8355. micro: "\u00B5",
  8356. para: "\u00B6",
  8357. middot: "\u00B7",
  8358. cedil: "\u00B8",
  8359. sup1: "\u00B9",
  8360. ordm: "\u00BA",
  8361. raquo: "\u00BB",
  8362. frac14: "\u00BC",
  8363. frac12: "\u00BD",
  8364. frac34: "\u00BE",
  8365. iquest: "\u00BF",
  8366. Agrave: "\u00C0",
  8367. Aacute: "\u00C1",
  8368. Acirc: "\u00C2",
  8369. Atilde: "\u00C3",
  8370. Auml: "\u00C4",
  8371. Aring: "\u00C5",
  8372. AElig: "\u00C6",
  8373. Ccedil: "\u00C7",
  8374. Egrave: "\u00C8",
  8375. Eacute: "\u00C9",
  8376. Ecirc: "\u00CA",
  8377. Euml: "\u00CB",
  8378. Igrave: "\u00CC",
  8379. Iacute: "\u00CD",
  8380. Icirc: "\u00CE",
  8381. Iuml: "\u00CF",
  8382. ETH: "\u00D0",
  8383. Ntilde: "\u00D1",
  8384. Ograve: "\u00D2",
  8385. Oacute: "\u00D3",
  8386. Ocirc: "\u00D4",
  8387. Otilde: "\u00D5",
  8388. Ouml: "\u00D6",
  8389. times: "\u00D7",
  8390. Oslash: "\u00D8",
  8391. Ugrave: "\u00D9",
  8392. Uacute: "\u00DA",
  8393. Ucirc: "\u00DB",
  8394. Uuml: "\u00DC",
  8395. Yacute: "\u00DD",
  8396. THORN: "\u00DE",
  8397. szlig: "\u00DF",
  8398. agrave: "\u00E0",
  8399. aacute: "\u00E1",
  8400. acirc: "\u00E2",
  8401. atilde: "\u00E3",
  8402. auml: "\u00E4",
  8403. aring: "\u00E5",
  8404. aelig: "\u00E6",
  8405. ccedil: "\u00E7",
  8406. egrave: "\u00E8",
  8407. eacute: "\u00E9",
  8408. ecirc: "\u00EA",
  8409. euml: "\u00EB",
  8410. igrave: "\u00EC",
  8411. iacute: "\u00ED",
  8412. icirc: "\u00EE",
  8413. iuml: "\u00EF",
  8414. eth: "\u00F0",
  8415. ntilde: "\u00F1",
  8416. ograve: "\u00F2",
  8417. oacute: "\u00F3",
  8418. ocirc: "\u00F4",
  8419. otilde: "\u00F5",
  8420. ouml: "\u00F6",
  8421. divide: "\u00F7",
  8422. oslash: "\u00F8",
  8423. ugrave: "\u00F9",
  8424. uacute: "\u00FA",
  8425. ucirc: "\u00FB",
  8426. uuml: "\u00FC",
  8427. yacute: "\u00FD",
  8428. thorn: "\u00FE",
  8429. yuml: "\u00FF",
  8430. OElig: "\u0152",
  8431. oelig: "\u0153",
  8432. Scaron: "\u0160",
  8433. scaron: "\u0161",
  8434. Yuml: "\u0178",
  8435. fnof: "\u0192",
  8436. circ: "\u02C6",
  8437. tilde: "\u02DC",
  8438. Alpha: "\u0391",
  8439. Beta: "\u0392",
  8440. Gamma: "\u0393",
  8441. Delta: "\u0394",
  8442. Epsilon: "\u0395",
  8443. Zeta: "\u0396",
  8444. Eta: "\u0397",
  8445. Theta: "\u0398",
  8446. Iota: "\u0399",
  8447. Kappa: "\u039A",
  8448. Lambda: "\u039B",
  8449. Mu: "\u039C",
  8450. Nu: "\u039D",
  8451. Xi: "\u039E",
  8452. Omicron: "\u039F",
  8453. Pi: "\u03A0",
  8454. Rho: "\u03A1",
  8455. Sigma: "\u03A3",
  8456. Tau: "\u03A4",
  8457. Upsilon: "\u03A5",
  8458. Phi: "\u03A6",
  8459. Chi: "\u03A7",
  8460. Psi: "\u03A8",
  8461. Omega: "\u03A9",
  8462. alpha: "\u03B1",
  8463. beta: "\u03B2",
  8464. gamma: "\u03B3",
  8465. delta: "\u03B4",
  8466. epsilon: "\u03B5",
  8467. zeta: "\u03B6",
  8468. eta: "\u03B7",
  8469. theta: "\u03B8",
  8470. iota: "\u03B9",
  8471. kappa: "\u03BA",
  8472. lambda: "\u03BB",
  8473. mu: "\u03BC",
  8474. nu: "\u03BD",
  8475. xi: "\u03BE",
  8476. omicron: "\u03BF",
  8477. pi: "\u03C0",
  8478. rho: "\u03C1",
  8479. sigmaf: "\u03C2",
  8480. sigma: "\u03C3",
  8481. tau: "\u03C4",
  8482. upsilon: "\u03C5",
  8483. phi: "\u03C6",
  8484. chi: "\u03C7",
  8485. psi: "\u03C8",
  8486. omega: "\u03C9",
  8487. thetasym: "\u03D1",
  8488. upsih: "\u03D2",
  8489. piv: "\u03D6",
  8490. ensp: "\u2002",
  8491. emsp: "\u2003",
  8492. thinsp: "\u2009",
  8493. zwnj: "\u200C",
  8494. zwj: "\u200D",
  8495. lrm: "\u200E",
  8496. rlm: "\u200F",
  8497. ndash: "\u2013",
  8498. mdash: "\u2014",
  8499. lsquo: "\u2018",
  8500. rsquo: "\u2019",
  8501. sbquo: "\u201A",
  8502. ldquo: "\u201C",
  8503. rdquo: "\u201D",
  8504. bdquo: "\u201E",
  8505. dagger: "\u2020",
  8506. Dagger: "\u2021",
  8507. bull: "\u2022",
  8508. hellip: "\u2026",
  8509. permil: "\u2030",
  8510. prime: "\u2032",
  8511. Prime: "\u2033",
  8512. lsaquo: "\u2039",
  8513. rsaquo: "\u203A",
  8514. oline: "\u203E",
  8515. frasl: "\u2044",
  8516. euro: "\u20AC",
  8517. image: "\u2111",
  8518. weierp: "\u2118",
  8519. real: "\u211C",
  8520. trade: "\u2122",
  8521. alefsym: "\u2135",
  8522. larr: "\u2190",
  8523. uarr: "\u2191",
  8524. rarr: "\u2192",
  8525. darr: "\u2193",
  8526. harr: "\u2194",
  8527. crarr: "\u21B5",
  8528. lArr: "\u21D0",
  8529. uArr: "\u21D1",
  8530. rArr: "\u21D2",
  8531. dArr: "\u21D3",
  8532. hArr: "\u21D4",
  8533. forall: "\u2200",
  8534. part: "\u2202",
  8535. exist: "\u2203",
  8536. empty: "\u2205",
  8537. nabla: "\u2207",
  8538. isin: "\u2208",
  8539. notin: "\u2209",
  8540. ni: "\u220B",
  8541. prod: "\u220F",
  8542. sum: "\u2211",
  8543. minus: "\u2212",
  8544. lowast: "\u2217",
  8545. radic: "\u221A",
  8546. prop: "\u221D",
  8547. infin: "\u221E",
  8548. ang: "\u2220",
  8549. and: "\u2227",
  8550. or: "\u2228",
  8551. cap: "\u2229",
  8552. cup: "\u222A",
  8553. int: "\u222B",
  8554. there4: "\u2234",
  8555. sim: "\u223C",
  8556. cong: "\u2245",
  8557. asymp: "\u2248",
  8558. ne: "\u2260",
  8559. equiv: "\u2261",
  8560. le: "\u2264",
  8561. ge: "\u2265",
  8562. sub: "\u2282",
  8563. sup: "\u2283",
  8564. nsub: "\u2284",
  8565. sube: "\u2286",
  8566. supe: "\u2287",
  8567. oplus: "\u2295",
  8568. otimes: "\u2297",
  8569. perp: "\u22A5",
  8570. sdot: "\u22C5",
  8571. lceil: "\u2308",
  8572. rceil: "\u2309",
  8573. lfloor: "\u230A",
  8574. rfloor: "\u230B",
  8575. lang: "\u2329",
  8576. rang: "\u232A",
  8577. loz: "\u25CA",
  8578. spades: "\u2660",
  8579. clubs: "\u2663",
  8580. hearts: "\u2665",
  8581. diams: "\u2666"
  8582. };
  8583. const lineBreak = /\r\n|[\r\n\u2028\u2029]/;
  8584. const lineBreakG = new RegExp(lineBreak.source, "g");
  8585. function isNewLine(code) {
  8586. switch (code) {
  8587. case 10:
  8588. case 13:
  8589. case 8232:
  8590. case 8233:
  8591. return true;
  8592. default:
  8593. return false;
  8594. }
  8595. }
  8596. function hasNewLine(input, start, end) {
  8597. for (let i = start; i < end; i++) {
  8598. if (isNewLine(input.charCodeAt(i))) {
  8599. return true;
  8600. }
  8601. }
  8602. return false;
  8603. }
  8604. const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  8605. const skipWhiteSpaceInLine = /(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/g;
  8606. function isWhitespace(code) {
  8607. switch (code) {
  8608. case 0x0009:
  8609. case 0x000b:
  8610. case 0x000c:
  8611. case 32:
  8612. case 160:
  8613. case 5760:
  8614. case 0x2000:
  8615. case 0x2001:
  8616. case 0x2002:
  8617. case 0x2003:
  8618. case 0x2004:
  8619. case 0x2005:
  8620. case 0x2006:
  8621. case 0x2007:
  8622. case 0x2008:
  8623. case 0x2009:
  8624. case 0x200a:
  8625. case 0x202f:
  8626. case 0x205f:
  8627. case 0x3000:
  8628. case 0xfeff:
  8629. return true;
  8630. default:
  8631. return false;
  8632. }
  8633. }
  8634. const JsxErrors = ParseErrorEnum`jsx`({
  8635. AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression.",
  8636. MissingClosingTagElement: ({
  8637. openingTagName
  8638. }) => `Expected corresponding JSX closing tag for <${openingTagName}>.`,
  8639. MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>.",
  8640. UnexpectedSequenceExpression: "Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",
  8641. UnexpectedToken: ({
  8642. unexpected,
  8643. HTMLEntity
  8644. }) => `Unexpected token \`${unexpected}\`. Did you mean \`${HTMLEntity}\` or \`{'${unexpected}'}\`?`,
  8645. UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text.",
  8646. UnterminatedJsxContent: "Unterminated JSX contents.",
  8647. UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"
  8648. });
  8649. function isFragment(object) {
  8650. return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
  8651. }
  8652. function getQualifiedJSXName(object) {
  8653. if (object.type === "JSXIdentifier") {
  8654. return object.name;
  8655. }
  8656. if (object.type === "JSXNamespacedName") {
  8657. return object.namespace.name + ":" + object.name.name;
  8658. }
  8659. if (object.type === "JSXMemberExpression") {
  8660. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  8661. }
  8662. throw new Error("Node had unexpected type: " + object.type);
  8663. }
  8664. var jsx = superClass => class JSXParserMixin extends superClass {
  8665. jsxReadToken() {
  8666. let out = "";
  8667. let chunkStart = this.state.pos;
  8668. for (;;) {
  8669. if (this.state.pos >= this.length) {
  8670. throw this.raise(JsxErrors.UnterminatedJsxContent, this.state.startLoc);
  8671. }
  8672. const ch = this.input.charCodeAt(this.state.pos);
  8673. switch (ch) {
  8674. case 60:
  8675. case 123:
  8676. if (this.state.pos === this.state.start) {
  8677. if (ch === 60 && this.state.canStartJSXElement) {
  8678. ++this.state.pos;
  8679. this.finishToken(143);
  8680. } else {
  8681. super.getTokenFromCode(ch);
  8682. }
  8683. return;
  8684. }
  8685. out += this.input.slice(chunkStart, this.state.pos);
  8686. this.finishToken(142, out);
  8687. return;
  8688. case 38:
  8689. out += this.input.slice(chunkStart, this.state.pos);
  8690. out += this.jsxReadEntity();
  8691. chunkStart = this.state.pos;
  8692. break;
  8693. case 62:
  8694. case 125:
  8695. default:
  8696. if (isNewLine(ch)) {
  8697. out += this.input.slice(chunkStart, this.state.pos);
  8698. out += this.jsxReadNewLine(true);
  8699. chunkStart = this.state.pos;
  8700. } else {
  8701. ++this.state.pos;
  8702. }
  8703. }
  8704. }
  8705. }
  8706. jsxReadNewLine(normalizeCRLF) {
  8707. const ch = this.input.charCodeAt(this.state.pos);
  8708. let out;
  8709. ++this.state.pos;
  8710. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  8711. ++this.state.pos;
  8712. out = normalizeCRLF ? "\n" : "\r\n";
  8713. } else {
  8714. out = String.fromCharCode(ch);
  8715. }
  8716. ++this.state.curLine;
  8717. this.state.lineStart = this.state.pos;
  8718. return out;
  8719. }
  8720. jsxReadString(quote) {
  8721. let out = "";
  8722. let chunkStart = ++this.state.pos;
  8723. for (;;) {
  8724. if (this.state.pos >= this.length) {
  8725. throw this.raise(Errors.UnterminatedString, this.state.startLoc);
  8726. }
  8727. const ch = this.input.charCodeAt(this.state.pos);
  8728. if (ch === quote) break;
  8729. if (ch === 38) {
  8730. out += this.input.slice(chunkStart, this.state.pos);
  8731. out += this.jsxReadEntity();
  8732. chunkStart = this.state.pos;
  8733. } else if (isNewLine(ch)) {
  8734. out += this.input.slice(chunkStart, this.state.pos);
  8735. out += this.jsxReadNewLine(false);
  8736. chunkStart = this.state.pos;
  8737. } else {
  8738. ++this.state.pos;
  8739. }
  8740. }
  8741. out += this.input.slice(chunkStart, this.state.pos++);
  8742. this.finishToken(134, out);
  8743. }
  8744. jsxReadEntity() {
  8745. const startPos = ++this.state.pos;
  8746. if (this.codePointAtPos(this.state.pos) === 35) {
  8747. ++this.state.pos;
  8748. let radix = 10;
  8749. if (this.codePointAtPos(this.state.pos) === 120) {
  8750. radix = 16;
  8751. ++this.state.pos;
  8752. }
  8753. const codePoint = this.readInt(radix, undefined, false, "bail");
  8754. if (codePoint !== null && this.codePointAtPos(this.state.pos) === 59) {
  8755. ++this.state.pos;
  8756. return String.fromCodePoint(codePoint);
  8757. }
  8758. } else {
  8759. let count = 0;
  8760. let semi = false;
  8761. while (count++ < 10 && this.state.pos < this.length && !(semi = this.codePointAtPos(this.state.pos) === 59)) {
  8762. ++this.state.pos;
  8763. }
  8764. if (semi) {
  8765. const desc = this.input.slice(startPos, this.state.pos);
  8766. const entity = entities[desc];
  8767. ++this.state.pos;
  8768. if (entity) {
  8769. return entity;
  8770. }
  8771. }
  8772. }
  8773. this.state.pos = startPos;
  8774. return "&";
  8775. }
  8776. jsxReadWord() {
  8777. let ch;
  8778. const start = this.state.pos;
  8779. do {
  8780. ch = this.input.charCodeAt(++this.state.pos);
  8781. } while (isIdentifierChar(ch) || ch === 45);
  8782. this.finishToken(141, this.input.slice(start, this.state.pos));
  8783. }
  8784. jsxParseIdentifier() {
  8785. const node = this.startNode();
  8786. if (this.match(141)) {
  8787. node.name = this.state.value;
  8788. } else if (tokenIsKeyword(this.state.type)) {
  8789. node.name = tokenLabelName(this.state.type);
  8790. } else {
  8791. this.unexpected();
  8792. }
  8793. this.next();
  8794. return this.finishNode(node, "JSXIdentifier");
  8795. }
  8796. jsxParseNamespacedName() {
  8797. const startLoc = this.state.startLoc;
  8798. const name = this.jsxParseIdentifier();
  8799. if (!this.eat(14)) return name;
  8800. const node = this.startNodeAt(startLoc);
  8801. node.namespace = name;
  8802. node.name = this.jsxParseIdentifier();
  8803. return this.finishNode(node, "JSXNamespacedName");
  8804. }
  8805. jsxParseElementName() {
  8806. const startLoc = this.state.startLoc;
  8807. let node = this.jsxParseNamespacedName();
  8808. if (node.type === "JSXNamespacedName") {
  8809. return node;
  8810. }
  8811. while (this.eat(16)) {
  8812. const newNode = this.startNodeAt(startLoc);
  8813. newNode.object = node;
  8814. newNode.property = this.jsxParseIdentifier();
  8815. node = this.finishNode(newNode, "JSXMemberExpression");
  8816. }
  8817. return node;
  8818. }
  8819. jsxParseAttributeValue() {
  8820. let node;
  8821. switch (this.state.type) {
  8822. case 5:
  8823. node = this.startNode();
  8824. this.setContext(types.brace);
  8825. this.next();
  8826. node = this.jsxParseExpressionContainer(node, types.j_oTag);
  8827. if (node.expression.type === "JSXEmptyExpression") {
  8828. this.raise(JsxErrors.AttributeIsEmpty, node);
  8829. }
  8830. return node;
  8831. case 143:
  8832. case 134:
  8833. return this.parseExprAtom();
  8834. default:
  8835. throw this.raise(JsxErrors.UnsupportedJsxValue, this.state.startLoc);
  8836. }
  8837. }
  8838. jsxParseEmptyExpression() {
  8839. const node = this.startNodeAt(this.state.lastTokEndLoc);
  8840. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.startLoc);
  8841. }
  8842. jsxParseSpreadChild(node) {
  8843. this.next();
  8844. node.expression = this.parseExpression();
  8845. this.setContext(types.j_expr);
  8846. this.state.canStartJSXElement = true;
  8847. this.expect(8);
  8848. return this.finishNode(node, "JSXSpreadChild");
  8849. }
  8850. jsxParseExpressionContainer(node, previousContext) {
  8851. if (this.match(8)) {
  8852. node.expression = this.jsxParseEmptyExpression();
  8853. } else {
  8854. const expression = this.parseExpression();
  8855. node.expression = expression;
  8856. }
  8857. this.setContext(previousContext);
  8858. this.state.canStartJSXElement = true;
  8859. this.expect(8);
  8860. return this.finishNode(node, "JSXExpressionContainer");
  8861. }
  8862. jsxParseAttribute() {
  8863. const node = this.startNode();
  8864. if (this.match(5)) {
  8865. this.setContext(types.brace);
  8866. this.next();
  8867. this.expect(21);
  8868. node.argument = this.parseMaybeAssignAllowIn();
  8869. this.setContext(types.j_oTag);
  8870. this.state.canStartJSXElement = true;
  8871. this.expect(8);
  8872. return this.finishNode(node, "JSXSpreadAttribute");
  8873. }
  8874. node.name = this.jsxParseNamespacedName();
  8875. node.value = this.eat(29) ? this.jsxParseAttributeValue() : null;
  8876. return this.finishNode(node, "JSXAttribute");
  8877. }
  8878. jsxParseOpeningElementAt(startLoc) {
  8879. const node = this.startNodeAt(startLoc);
  8880. if (this.eat(144)) {
  8881. return this.finishNode(node, "JSXOpeningFragment");
  8882. }
  8883. node.name = this.jsxParseElementName();
  8884. return this.jsxParseOpeningElementAfterName(node);
  8885. }
  8886. jsxParseOpeningElementAfterName(node) {
  8887. const attributes = [];
  8888. while (!this.match(56) && !this.match(144)) {
  8889. attributes.push(this.jsxParseAttribute());
  8890. }
  8891. node.attributes = attributes;
  8892. node.selfClosing = this.eat(56);
  8893. this.expect(144);
  8894. return this.finishNode(node, "JSXOpeningElement");
  8895. }
  8896. jsxParseClosingElementAt(startLoc) {
  8897. const node = this.startNodeAt(startLoc);
  8898. if (this.eat(144)) {
  8899. return this.finishNode(node, "JSXClosingFragment");
  8900. }
  8901. node.name = this.jsxParseElementName();
  8902. this.expect(144);
  8903. return this.finishNode(node, "JSXClosingElement");
  8904. }
  8905. jsxParseElementAt(startLoc) {
  8906. const node = this.startNodeAt(startLoc);
  8907. const children = [];
  8908. const openingElement = this.jsxParseOpeningElementAt(startLoc);
  8909. let closingElement = null;
  8910. if (!openingElement.selfClosing) {
  8911. contents: for (;;) {
  8912. switch (this.state.type) {
  8913. case 143:
  8914. startLoc = this.state.startLoc;
  8915. this.next();
  8916. if (this.eat(56)) {
  8917. closingElement = this.jsxParseClosingElementAt(startLoc);
  8918. break contents;
  8919. }
  8920. children.push(this.jsxParseElementAt(startLoc));
  8921. break;
  8922. case 142:
  8923. children.push(this.parseLiteral(this.state.value, "JSXText"));
  8924. break;
  8925. case 5:
  8926. {
  8927. const node = this.startNode();
  8928. this.setContext(types.brace);
  8929. this.next();
  8930. if (this.match(21)) {
  8931. children.push(this.jsxParseSpreadChild(node));
  8932. } else {
  8933. children.push(this.jsxParseExpressionContainer(node, types.j_expr));
  8934. }
  8935. break;
  8936. }
  8937. default:
  8938. this.unexpected();
  8939. }
  8940. }
  8941. if (isFragment(openingElement) && !isFragment(closingElement) && closingElement !== null) {
  8942. this.raise(JsxErrors.MissingClosingTagFragment, closingElement);
  8943. } else if (!isFragment(openingElement) && isFragment(closingElement)) {
  8944. this.raise(JsxErrors.MissingClosingTagElement, closingElement, {
  8945. openingTagName: getQualifiedJSXName(openingElement.name)
  8946. });
  8947. } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
  8948. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  8949. this.raise(JsxErrors.MissingClosingTagElement, closingElement, {
  8950. openingTagName: getQualifiedJSXName(openingElement.name)
  8951. });
  8952. }
  8953. }
  8954. }
  8955. if (isFragment(openingElement)) {
  8956. node.openingFragment = openingElement;
  8957. node.closingFragment = closingElement;
  8958. } else {
  8959. node.openingElement = openingElement;
  8960. node.closingElement = closingElement;
  8961. }
  8962. node.children = children;
  8963. if (this.match(47)) {
  8964. throw this.raise(JsxErrors.UnwrappedAdjacentJSXElements, this.state.startLoc);
  8965. }
  8966. return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
  8967. }
  8968. jsxParseElement() {
  8969. const startLoc = this.state.startLoc;
  8970. this.next();
  8971. return this.jsxParseElementAt(startLoc);
  8972. }
  8973. setContext(newContext) {
  8974. const {
  8975. context
  8976. } = this.state;
  8977. context[context.length - 1] = newContext;
  8978. }
  8979. parseExprAtom(refExpressionErrors) {
  8980. if (this.match(143)) {
  8981. return this.jsxParseElement();
  8982. } else if (this.match(47) && this.input.charCodeAt(this.state.pos) !== 33) {
  8983. this.replaceToken(143);
  8984. return this.jsxParseElement();
  8985. } else {
  8986. return super.parseExprAtom(refExpressionErrors);
  8987. }
  8988. }
  8989. skipSpace() {
  8990. const curContext = this.curContext();
  8991. if (!curContext.preserveSpace) super.skipSpace();
  8992. }
  8993. getTokenFromCode(code) {
  8994. const context = this.curContext();
  8995. if (context === types.j_expr) {
  8996. this.jsxReadToken();
  8997. return;
  8998. }
  8999. if (context === types.j_oTag || context === types.j_cTag) {
  9000. if (isIdentifierStart(code)) {
  9001. this.jsxReadWord();
  9002. return;
  9003. }
  9004. if (code === 62) {
  9005. ++this.state.pos;
  9006. this.finishToken(144);
  9007. return;
  9008. }
  9009. if ((code === 34 || code === 39) && context === types.j_oTag) {
  9010. this.jsxReadString(code);
  9011. return;
  9012. }
  9013. }
  9014. if (code === 60 && this.state.canStartJSXElement && this.input.charCodeAt(this.state.pos + 1) !== 33) {
  9015. ++this.state.pos;
  9016. this.finishToken(143);
  9017. return;
  9018. }
  9019. super.getTokenFromCode(code);
  9020. }
  9021. updateContext(prevType) {
  9022. const {
  9023. context,
  9024. type
  9025. } = this.state;
  9026. if (type === 56 && prevType === 143) {
  9027. context.splice(-2, 2, types.j_cTag);
  9028. this.state.canStartJSXElement = false;
  9029. } else if (type === 143) {
  9030. context.push(types.j_oTag);
  9031. } else if (type === 144) {
  9032. const out = context[context.length - 1];
  9033. if (out === types.j_oTag && prevType === 56 || out === types.j_cTag) {
  9034. context.pop();
  9035. this.state.canStartJSXElement = context[context.length - 1] === types.j_expr;
  9036. } else {
  9037. this.setContext(types.j_expr);
  9038. this.state.canStartJSXElement = true;
  9039. }
  9040. } else {
  9041. this.state.canStartJSXElement = tokenComesBeforeExpression(type);
  9042. }
  9043. }
  9044. };
  9045. class TypeScriptScope extends Scope {
  9046. constructor(...args) {
  9047. super(...args);
  9048. this.tsNames = new Map();
  9049. }
  9050. }
  9051. class TypeScriptScopeHandler extends ScopeHandler {
  9052. constructor(...args) {
  9053. super(...args);
  9054. this.importsStack = [];
  9055. }
  9056. createScope(flags) {
  9057. this.importsStack.push(new Set());
  9058. return new TypeScriptScope(flags);
  9059. }
  9060. enter(flags) {
  9061. if (flags === 1024) {
  9062. this.importsStack.push(new Set());
  9063. }
  9064. super.enter(flags);
  9065. }
  9066. exit() {
  9067. const flags = super.exit();
  9068. if (flags === 1024) {
  9069. this.importsStack.pop();
  9070. }
  9071. return flags;
  9072. }
  9073. hasImport(name, allowShadow) {
  9074. const len = this.importsStack.length;
  9075. if (this.importsStack[len - 1].has(name)) {
  9076. return true;
  9077. }
  9078. if (!allowShadow && len > 1) {
  9079. for (let i = 0; i < len - 1; i++) {
  9080. if (this.importsStack[i].has(name)) return true;
  9081. }
  9082. }
  9083. return false;
  9084. }
  9085. declareName(name, bindingType, loc) {
  9086. if (bindingType & 4096) {
  9087. if (this.hasImport(name, true)) {
  9088. this.parser.raise(Errors.VarRedeclaration, loc, {
  9089. identifierName: name
  9090. });
  9091. }
  9092. this.importsStack[this.importsStack.length - 1].add(name);
  9093. return;
  9094. }
  9095. const scope = this.currentScope();
  9096. let type = scope.tsNames.get(name) || 0;
  9097. if (bindingType & 1024) {
  9098. this.maybeExportDefined(scope, name);
  9099. scope.tsNames.set(name, type | 16);
  9100. return;
  9101. }
  9102. super.declareName(name, bindingType, loc);
  9103. if (bindingType & 2) {
  9104. if (!(bindingType & 1)) {
  9105. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  9106. this.maybeExportDefined(scope, name);
  9107. }
  9108. type = type | 1;
  9109. }
  9110. if (bindingType & 256) {
  9111. type = type | 2;
  9112. }
  9113. if (bindingType & 512) {
  9114. type = type | 4;
  9115. }
  9116. if (bindingType & 128) {
  9117. type = type | 8;
  9118. }
  9119. if (type) scope.tsNames.set(name, type);
  9120. }
  9121. isRedeclaredInScope(scope, name, bindingType) {
  9122. const type = scope.tsNames.get(name);
  9123. if ((type & 2) > 0) {
  9124. if (bindingType & 256) {
  9125. const isConst = !!(bindingType & 512);
  9126. const wasConst = (type & 4) > 0;
  9127. return isConst !== wasConst;
  9128. }
  9129. return true;
  9130. }
  9131. if (bindingType & 128 && (type & 8) > 0) {
  9132. if (scope.names.get(name) & 2) {
  9133. return !!(bindingType & 1);
  9134. } else {
  9135. return false;
  9136. }
  9137. }
  9138. if (bindingType & 2 && (type & 1) > 0) {
  9139. return true;
  9140. }
  9141. return super.isRedeclaredInScope(scope, name, bindingType);
  9142. }
  9143. checkLocalExport(id) {
  9144. const {
  9145. name
  9146. } = id;
  9147. if (this.hasImport(name)) return;
  9148. const len = this.scopeStack.length;
  9149. for (let i = len - 1; i >= 0; i--) {
  9150. const scope = this.scopeStack[i];
  9151. const type = scope.tsNames.get(name);
  9152. if ((type & 1) > 0 || (type & 16) > 0) {
  9153. return;
  9154. }
  9155. }
  9156. super.checkLocalExport(id);
  9157. }
  9158. }
  9159. class ProductionParameterHandler {
  9160. constructor() {
  9161. this.stacks = [];
  9162. }
  9163. enter(flags) {
  9164. this.stacks.push(flags);
  9165. }
  9166. exit() {
  9167. this.stacks.pop();
  9168. }
  9169. currentFlags() {
  9170. return this.stacks[this.stacks.length - 1];
  9171. }
  9172. get hasAwait() {
  9173. return (this.currentFlags() & 2) > 0;
  9174. }
  9175. get hasYield() {
  9176. return (this.currentFlags() & 1) > 0;
  9177. }
  9178. get hasReturn() {
  9179. return (this.currentFlags() & 4) > 0;
  9180. }
  9181. get hasIn() {
  9182. return (this.currentFlags() & 8) > 0;
  9183. }
  9184. }
  9185. function functionFlags(isAsync, isGenerator) {
  9186. return (isAsync ? 2 : 0) | (isGenerator ? 1 : 0);
  9187. }
  9188. class BaseParser {
  9189. constructor() {
  9190. this.sawUnambiguousESM = false;
  9191. this.ambiguousScriptDifferentAst = false;
  9192. }
  9193. sourceToOffsetPos(sourcePos) {
  9194. return sourcePos + this.startIndex;
  9195. }
  9196. offsetToSourcePos(offsetPos) {
  9197. return offsetPos - this.startIndex;
  9198. }
  9199. hasPlugin(pluginConfig) {
  9200. if (typeof pluginConfig === "string") {
  9201. return this.plugins.has(pluginConfig);
  9202. } else {
  9203. const [pluginName, pluginOptions] = pluginConfig;
  9204. if (!this.hasPlugin(pluginName)) {
  9205. return false;
  9206. }
  9207. const actualOptions = this.plugins.get(pluginName);
  9208. for (const key of Object.keys(pluginOptions)) {
  9209. if ((actualOptions == null ? void 0 : actualOptions[key]) !== pluginOptions[key]) {
  9210. return false;
  9211. }
  9212. }
  9213. return true;
  9214. }
  9215. }
  9216. getPluginOption(plugin, name) {
  9217. var _this$plugins$get;
  9218. return (_this$plugins$get = this.plugins.get(plugin)) == null ? void 0 : _this$plugins$get[name];
  9219. }
  9220. }
  9221. function setTrailingComments(node, comments) {
  9222. if (node.trailingComments === undefined) {
  9223. node.trailingComments = comments;
  9224. } else {
  9225. node.trailingComments.unshift(...comments);
  9226. }
  9227. }
  9228. function setLeadingComments(node, comments) {
  9229. if (node.leadingComments === undefined) {
  9230. node.leadingComments = comments;
  9231. } else {
  9232. node.leadingComments.unshift(...comments);
  9233. }
  9234. }
  9235. function setInnerComments(node, comments) {
  9236. if (node.innerComments === undefined) {
  9237. node.innerComments = comments;
  9238. } else {
  9239. node.innerComments.unshift(...comments);
  9240. }
  9241. }
  9242. function adjustInnerComments(node, elements, commentWS) {
  9243. let lastElement = null;
  9244. let i = elements.length;
  9245. while (lastElement === null && i > 0) {
  9246. lastElement = elements[--i];
  9247. }
  9248. if (lastElement === null || lastElement.start > commentWS.start) {
  9249. setInnerComments(node, commentWS.comments);
  9250. } else {
  9251. setTrailingComments(lastElement, commentWS.comments);
  9252. }
  9253. }
  9254. class CommentsParser extends BaseParser {
  9255. addComment(comment) {
  9256. if (this.filename) comment.loc.filename = this.filename;
  9257. const {
  9258. commentsLen
  9259. } = this.state;
  9260. if (this.comments.length !== commentsLen) {
  9261. this.comments.length = commentsLen;
  9262. }
  9263. this.comments.push(comment);
  9264. this.state.commentsLen++;
  9265. }
  9266. processComment(node) {
  9267. const {
  9268. commentStack
  9269. } = this.state;
  9270. const commentStackLength = commentStack.length;
  9271. if (commentStackLength === 0) return;
  9272. let i = commentStackLength - 1;
  9273. const lastCommentWS = commentStack[i];
  9274. if (lastCommentWS.start === node.end) {
  9275. lastCommentWS.leadingNode = node;
  9276. i--;
  9277. }
  9278. const {
  9279. start: nodeStart
  9280. } = node;
  9281. for (; i >= 0; i--) {
  9282. const commentWS = commentStack[i];
  9283. const commentEnd = commentWS.end;
  9284. if (commentEnd > nodeStart) {
  9285. commentWS.containingNode = node;
  9286. this.finalizeComment(commentWS);
  9287. commentStack.splice(i, 1);
  9288. } else {
  9289. if (commentEnd === nodeStart) {
  9290. commentWS.trailingNode = node;
  9291. }
  9292. break;
  9293. }
  9294. }
  9295. }
  9296. finalizeComment(commentWS) {
  9297. var _node$options;
  9298. const {
  9299. comments
  9300. } = commentWS;
  9301. if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) {
  9302. if (commentWS.leadingNode !== null) {
  9303. setTrailingComments(commentWS.leadingNode, comments);
  9304. }
  9305. if (commentWS.trailingNode !== null) {
  9306. setLeadingComments(commentWS.trailingNode, comments);
  9307. }
  9308. } else {
  9309. const node = commentWS.containingNode;
  9310. const commentStart = commentWS.start;
  9311. if (this.input.charCodeAt(this.offsetToSourcePos(commentStart) - 1) === 44) {
  9312. switch (node.type) {
  9313. case "ObjectExpression":
  9314. case "ObjectPattern":
  9315. adjustInnerComments(node, node.properties, commentWS);
  9316. break;
  9317. case "CallExpression":
  9318. case "NewExpression":
  9319. case "OptionalCallExpression":
  9320. adjustInnerComments(node, node.arguments, commentWS);
  9321. break;
  9322. case "ImportExpression":
  9323. adjustInnerComments(node, [node.source, (_node$options = node.options) != null ? _node$options : null], commentWS);
  9324. break;
  9325. case "FunctionDeclaration":
  9326. case "FunctionExpression":
  9327. case "ArrowFunctionExpression":
  9328. case "ObjectMethod":
  9329. case "ClassMethod":
  9330. case "ClassPrivateMethod":
  9331. case "TSTypeParameterDeclaration":
  9332. adjustInnerComments(node, node.params, commentWS);
  9333. break;
  9334. case "ArrayExpression":
  9335. case "ArrayPattern":
  9336. adjustInnerComments(node, node.elements, commentWS);
  9337. break;
  9338. case "ExportNamedDeclaration":
  9339. case "ImportDeclaration":
  9340. adjustInnerComments(node, node.specifiers, commentWS);
  9341. break;
  9342. case "TSEnumDeclaration":
  9343. adjustInnerComments(node, node.members, commentWS);
  9344. break;
  9345. case "TSEnumBody":
  9346. adjustInnerComments(node, node.members, commentWS);
  9347. break;
  9348. case "TSInterfaceBody":
  9349. adjustInnerComments(node, node.body, commentWS);
  9350. break;
  9351. default:
  9352. {
  9353. if (node.type === "RecordExpression") {
  9354. adjustInnerComments(node, node.properties, commentWS);
  9355. break;
  9356. }
  9357. if (node.type === "TupleExpression") {
  9358. adjustInnerComments(node, node.elements, commentWS);
  9359. break;
  9360. }
  9361. setInnerComments(node, comments);
  9362. }
  9363. }
  9364. } else {
  9365. setInnerComments(node, comments);
  9366. }
  9367. }
  9368. }
  9369. finalizeRemainingComments() {
  9370. const {
  9371. commentStack
  9372. } = this.state;
  9373. for (let i = commentStack.length - 1; i >= 0; i--) {
  9374. this.finalizeComment(commentStack[i]);
  9375. }
  9376. this.state.commentStack = [];
  9377. }
  9378. resetPreviousNodeTrailingComments(node) {
  9379. const {
  9380. commentStack
  9381. } = this.state;
  9382. const {
  9383. length
  9384. } = commentStack;
  9385. if (length === 0) return;
  9386. const commentWS = commentStack[length - 1];
  9387. if (commentWS.leadingNode === node) {
  9388. commentWS.leadingNode = null;
  9389. }
  9390. }
  9391. takeSurroundingComments(node, start, end) {
  9392. const {
  9393. commentStack
  9394. } = this.state;
  9395. const commentStackLength = commentStack.length;
  9396. if (commentStackLength === 0) return;
  9397. let i = commentStackLength - 1;
  9398. for (; i >= 0; i--) {
  9399. const commentWS = commentStack[i];
  9400. const commentEnd = commentWS.end;
  9401. const commentStart = commentWS.start;
  9402. if (commentStart === end) {
  9403. commentWS.leadingNode = node;
  9404. } else if (commentEnd === start) {
  9405. commentWS.trailingNode = node;
  9406. } else if (commentEnd < start) {
  9407. break;
  9408. }
  9409. }
  9410. }
  9411. }
  9412. class State {
  9413. constructor() {
  9414. this.flags = 1024;
  9415. this.startIndex = void 0;
  9416. this.curLine = void 0;
  9417. this.lineStart = void 0;
  9418. this.startLoc = void 0;
  9419. this.endLoc = void 0;
  9420. this.errors = [];
  9421. this.potentialArrowAt = -1;
  9422. this.noArrowAt = [];
  9423. this.noArrowParamsConversionAt = [];
  9424. this.topicContext = {
  9425. maxNumOfResolvableTopics: 0,
  9426. maxTopicIndex: null
  9427. };
  9428. this.labels = [];
  9429. this.commentsLen = 0;
  9430. this.commentStack = [];
  9431. this.pos = 0;
  9432. this.type = 140;
  9433. this.value = null;
  9434. this.start = 0;
  9435. this.end = 0;
  9436. this.lastTokEndLoc = null;
  9437. this.lastTokStartLoc = null;
  9438. this.context = [types.brace];
  9439. this.firstInvalidTemplateEscapePos = null;
  9440. this.strictErrors = new Map();
  9441. this.tokensLength = 0;
  9442. }
  9443. get strict() {
  9444. return (this.flags & 1) > 0;
  9445. }
  9446. set strict(v) {
  9447. if (v) this.flags |= 1;else this.flags &= -2;
  9448. }
  9449. init({
  9450. strictMode,
  9451. sourceType,
  9452. startIndex,
  9453. startLine,
  9454. startColumn
  9455. }) {
  9456. this.strict = strictMode === false ? false : strictMode === true ? true : sourceType === "module";
  9457. this.startIndex = startIndex;
  9458. this.curLine = startLine;
  9459. this.lineStart = -startColumn;
  9460. this.startLoc = this.endLoc = new Position(startLine, startColumn, startIndex);
  9461. }
  9462. get maybeInArrowParameters() {
  9463. return (this.flags & 2) > 0;
  9464. }
  9465. set maybeInArrowParameters(v) {
  9466. if (v) this.flags |= 2;else this.flags &= -3;
  9467. }
  9468. get inType() {
  9469. return (this.flags & 4) > 0;
  9470. }
  9471. set inType(v) {
  9472. if (v) this.flags |= 4;else this.flags &= -5;
  9473. }
  9474. get noAnonFunctionType() {
  9475. return (this.flags & 8) > 0;
  9476. }
  9477. set noAnonFunctionType(v) {
  9478. if (v) this.flags |= 8;else this.flags &= -9;
  9479. }
  9480. get hasFlowComment() {
  9481. return (this.flags & 16) > 0;
  9482. }
  9483. set hasFlowComment(v) {
  9484. if (v) this.flags |= 16;else this.flags &= -17;
  9485. }
  9486. get isAmbientContext() {
  9487. return (this.flags & 32) > 0;
  9488. }
  9489. set isAmbientContext(v) {
  9490. if (v) this.flags |= 32;else this.flags &= -33;
  9491. }
  9492. get inAbstractClass() {
  9493. return (this.flags & 64) > 0;
  9494. }
  9495. set inAbstractClass(v) {
  9496. if (v) this.flags |= 64;else this.flags &= -65;
  9497. }
  9498. get inDisallowConditionalTypesContext() {
  9499. return (this.flags & 128) > 0;
  9500. }
  9501. set inDisallowConditionalTypesContext(v) {
  9502. if (v) this.flags |= 128;else this.flags &= -129;
  9503. }
  9504. get soloAwait() {
  9505. return (this.flags & 256) > 0;
  9506. }
  9507. set soloAwait(v) {
  9508. if (v) this.flags |= 256;else this.flags &= -257;
  9509. }
  9510. get inFSharpPipelineDirectBody() {
  9511. return (this.flags & 512) > 0;
  9512. }
  9513. set inFSharpPipelineDirectBody(v) {
  9514. if (v) this.flags |= 512;else this.flags &= -513;
  9515. }
  9516. get canStartJSXElement() {
  9517. return (this.flags & 1024) > 0;
  9518. }
  9519. set canStartJSXElement(v) {
  9520. if (v) this.flags |= 1024;else this.flags &= -1025;
  9521. }
  9522. get containsEsc() {
  9523. return (this.flags & 2048) > 0;
  9524. }
  9525. set containsEsc(v) {
  9526. if (v) this.flags |= 2048;else this.flags &= -2049;
  9527. }
  9528. get hasTopLevelAwait() {
  9529. return (this.flags & 4096) > 0;
  9530. }
  9531. set hasTopLevelAwait(v) {
  9532. if (v) this.flags |= 4096;else this.flags &= -4097;
  9533. }
  9534. curPosition() {
  9535. return new Position(this.curLine, this.pos - this.lineStart, this.pos + this.startIndex);
  9536. }
  9537. clone() {
  9538. const state = new State();
  9539. state.flags = this.flags;
  9540. state.startIndex = this.startIndex;
  9541. state.curLine = this.curLine;
  9542. state.lineStart = this.lineStart;
  9543. state.startLoc = this.startLoc;
  9544. state.endLoc = this.endLoc;
  9545. state.errors = this.errors.slice();
  9546. state.potentialArrowAt = this.potentialArrowAt;
  9547. state.noArrowAt = this.noArrowAt.slice();
  9548. state.noArrowParamsConversionAt = this.noArrowParamsConversionAt.slice();
  9549. state.topicContext = this.topicContext;
  9550. state.labels = this.labels.slice();
  9551. state.commentsLen = this.commentsLen;
  9552. state.commentStack = this.commentStack.slice();
  9553. state.pos = this.pos;
  9554. state.type = this.type;
  9555. state.value = this.value;
  9556. state.start = this.start;
  9557. state.end = this.end;
  9558. state.lastTokEndLoc = this.lastTokEndLoc;
  9559. state.lastTokStartLoc = this.lastTokStartLoc;
  9560. state.context = this.context.slice();
  9561. state.firstInvalidTemplateEscapePos = this.firstInvalidTemplateEscapePos;
  9562. state.strictErrors = this.strictErrors;
  9563. state.tokensLength = this.tokensLength;
  9564. return state;
  9565. }
  9566. }
  9567. var _isDigit = function isDigit(code) {
  9568. return code >= 48 && code <= 57;
  9569. };
  9570. const forbiddenNumericSeparatorSiblings = {
  9571. decBinOct: new Set([46, 66, 69, 79, 95, 98, 101, 111]),
  9572. hex: new Set([46, 88, 95, 120])
  9573. };
  9574. const isAllowedNumericSeparatorSibling = {
  9575. bin: ch => ch === 48 || ch === 49,
  9576. oct: ch => ch >= 48 && ch <= 55,
  9577. dec: ch => ch >= 48 && ch <= 57,
  9578. hex: ch => ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102
  9579. };
  9580. function readStringContents(type, input, pos, lineStart, curLine, errors) {
  9581. const initialPos = pos;
  9582. const initialLineStart = lineStart;
  9583. const initialCurLine = curLine;
  9584. let out = "";
  9585. let firstInvalidLoc = null;
  9586. let chunkStart = pos;
  9587. const {
  9588. length
  9589. } = input;
  9590. for (;;) {
  9591. if (pos >= length) {
  9592. errors.unterminated(initialPos, initialLineStart, initialCurLine);
  9593. out += input.slice(chunkStart, pos);
  9594. break;
  9595. }
  9596. const ch = input.charCodeAt(pos);
  9597. if (isStringEnd(type, ch, input, pos)) {
  9598. out += input.slice(chunkStart, pos);
  9599. break;
  9600. }
  9601. if (ch === 92) {
  9602. out += input.slice(chunkStart, pos);
  9603. const res = readEscapedChar(input, pos, lineStart, curLine, type === "template", errors);
  9604. if (res.ch === null && !firstInvalidLoc) {
  9605. firstInvalidLoc = {
  9606. pos,
  9607. lineStart,
  9608. curLine
  9609. };
  9610. } else {
  9611. out += res.ch;
  9612. }
  9613. ({
  9614. pos,
  9615. lineStart,
  9616. curLine
  9617. } = res);
  9618. chunkStart = pos;
  9619. } else if (ch === 8232 || ch === 8233) {
  9620. ++pos;
  9621. ++curLine;
  9622. lineStart = pos;
  9623. } else if (ch === 10 || ch === 13) {
  9624. if (type === "template") {
  9625. out += input.slice(chunkStart, pos) + "\n";
  9626. ++pos;
  9627. if (ch === 13 && input.charCodeAt(pos) === 10) {
  9628. ++pos;
  9629. }
  9630. ++curLine;
  9631. chunkStart = lineStart = pos;
  9632. } else {
  9633. errors.unterminated(initialPos, initialLineStart, initialCurLine);
  9634. }
  9635. } else {
  9636. ++pos;
  9637. }
  9638. }
  9639. return {
  9640. pos,
  9641. str: out,
  9642. firstInvalidLoc,
  9643. lineStart,
  9644. curLine,
  9645. containsInvalid: !!firstInvalidLoc
  9646. };
  9647. }
  9648. function isStringEnd(type, ch, input, pos) {
  9649. if (type === "template") {
  9650. return ch === 96 || ch === 36 && input.charCodeAt(pos + 1) === 123;
  9651. }
  9652. return ch === (type === "double" ? 34 : 39);
  9653. }
  9654. function readEscapedChar(input, pos, lineStart, curLine, inTemplate, errors) {
  9655. const throwOnInvalid = !inTemplate;
  9656. pos++;
  9657. const res = ch => ({
  9658. pos,
  9659. ch,
  9660. lineStart,
  9661. curLine
  9662. });
  9663. const ch = input.charCodeAt(pos++);
  9664. switch (ch) {
  9665. case 110:
  9666. return res("\n");
  9667. case 114:
  9668. return res("\r");
  9669. case 120:
  9670. {
  9671. let code;
  9672. ({
  9673. code,
  9674. pos
  9675. } = readHexChar(input, pos, lineStart, curLine, 2, false, throwOnInvalid, errors));
  9676. return res(code === null ? null : String.fromCharCode(code));
  9677. }
  9678. case 117:
  9679. {
  9680. let code;
  9681. ({
  9682. code,
  9683. pos
  9684. } = readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors));
  9685. return res(code === null ? null : String.fromCodePoint(code));
  9686. }
  9687. case 116:
  9688. return res("\t");
  9689. case 98:
  9690. return res("\b");
  9691. case 118:
  9692. return res("\u000b");
  9693. case 102:
  9694. return res("\f");
  9695. case 13:
  9696. if (input.charCodeAt(pos) === 10) {
  9697. ++pos;
  9698. }
  9699. case 10:
  9700. lineStart = pos;
  9701. ++curLine;
  9702. case 8232:
  9703. case 8233:
  9704. return res("");
  9705. case 56:
  9706. case 57:
  9707. if (inTemplate) {
  9708. return res(null);
  9709. } else {
  9710. errors.strictNumericEscape(pos - 1, lineStart, curLine);
  9711. }
  9712. default:
  9713. if (ch >= 48 && ch <= 55) {
  9714. const startPos = pos - 1;
  9715. const match = /^[0-7]+/.exec(input.slice(startPos, pos + 2));
  9716. let octalStr = match[0];
  9717. let octal = parseInt(octalStr, 8);
  9718. if (octal > 255) {
  9719. octalStr = octalStr.slice(0, -1);
  9720. octal = parseInt(octalStr, 8);
  9721. }
  9722. pos += octalStr.length - 1;
  9723. const next = input.charCodeAt(pos);
  9724. if (octalStr !== "0" || next === 56 || next === 57) {
  9725. if (inTemplate) {
  9726. return res(null);
  9727. } else {
  9728. errors.strictNumericEscape(startPos, lineStart, curLine);
  9729. }
  9730. }
  9731. return res(String.fromCharCode(octal));
  9732. }
  9733. return res(String.fromCharCode(ch));
  9734. }
  9735. }
  9736. function readHexChar(input, pos, lineStart, curLine, len, forceLen, throwOnInvalid, errors) {
  9737. const initialPos = pos;
  9738. let n;
  9739. ({
  9740. n,
  9741. pos
  9742. } = readInt(input, pos, lineStart, curLine, 16, len, forceLen, false, errors, !throwOnInvalid));
  9743. if (n === null) {
  9744. if (throwOnInvalid) {
  9745. errors.invalidEscapeSequence(initialPos, lineStart, curLine);
  9746. } else {
  9747. pos = initialPos - 1;
  9748. }
  9749. }
  9750. return {
  9751. code: n,
  9752. pos
  9753. };
  9754. }
  9755. function readInt(input, pos, lineStart, curLine, radix, len, forceLen, allowNumSeparator, errors, bailOnError) {
  9756. const start = pos;
  9757. const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  9758. const isAllowedSibling = radix === 16 ? isAllowedNumericSeparatorSibling.hex : radix === 10 ? isAllowedNumericSeparatorSibling.dec : radix === 8 ? isAllowedNumericSeparatorSibling.oct : isAllowedNumericSeparatorSibling.bin;
  9759. let invalid = false;
  9760. let total = 0;
  9761. for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  9762. const code = input.charCodeAt(pos);
  9763. let val;
  9764. if (code === 95 && allowNumSeparator !== "bail") {
  9765. const prev = input.charCodeAt(pos - 1);
  9766. const next = input.charCodeAt(pos + 1);
  9767. if (!allowNumSeparator) {
  9768. if (bailOnError) return {
  9769. n: null,
  9770. pos
  9771. };
  9772. errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine);
  9773. } else if (Number.isNaN(next) || !isAllowedSibling(next) || forbiddenSiblings.has(prev) || forbiddenSiblings.has(next)) {
  9774. if (bailOnError) return {
  9775. n: null,
  9776. pos
  9777. };
  9778. errors.unexpectedNumericSeparator(pos, lineStart, curLine);
  9779. }
  9780. ++pos;
  9781. continue;
  9782. }
  9783. if (code >= 97) {
  9784. val = code - 97 + 10;
  9785. } else if (code >= 65) {
  9786. val = code - 65 + 10;
  9787. } else if (_isDigit(code)) {
  9788. val = code - 48;
  9789. } else {
  9790. val = Infinity;
  9791. }
  9792. if (val >= radix) {
  9793. if (val <= 9 && bailOnError) {
  9794. return {
  9795. n: null,
  9796. pos
  9797. };
  9798. } else if (val <= 9 && errors.invalidDigit(pos, lineStart, curLine, radix)) {
  9799. val = 0;
  9800. } else if (forceLen) {
  9801. val = 0;
  9802. invalid = true;
  9803. } else {
  9804. break;
  9805. }
  9806. }
  9807. ++pos;
  9808. total = total * radix + val;
  9809. }
  9810. if (pos === start || len != null && pos - start !== len || invalid) {
  9811. return {
  9812. n: null,
  9813. pos
  9814. };
  9815. }
  9816. return {
  9817. n: total,
  9818. pos
  9819. };
  9820. }
  9821. function readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors) {
  9822. const ch = input.charCodeAt(pos);
  9823. let code;
  9824. if (ch === 123) {
  9825. ++pos;
  9826. ({
  9827. code,
  9828. pos
  9829. } = readHexChar(input, pos, lineStart, curLine, input.indexOf("}", pos) - pos, true, throwOnInvalid, errors));
  9830. ++pos;
  9831. if (code !== null && code > 0x10ffff) {
  9832. if (throwOnInvalid) {
  9833. errors.invalidCodePoint(pos, lineStart, curLine);
  9834. } else {
  9835. return {
  9836. code: null,
  9837. pos
  9838. };
  9839. }
  9840. }
  9841. } else {
  9842. ({
  9843. code,
  9844. pos
  9845. } = readHexChar(input, pos, lineStart, curLine, 4, false, throwOnInvalid, errors));
  9846. }
  9847. return {
  9848. code,
  9849. pos
  9850. };
  9851. }
  9852. function buildPosition(pos, lineStart, curLine) {
  9853. return new Position(curLine, pos - lineStart, pos);
  9854. }
  9855. const VALID_REGEX_FLAGS = new Set([103, 109, 115, 105, 121, 117, 100, 118]);
  9856. class Token {
  9857. constructor(state) {
  9858. const startIndex = state.startIndex || 0;
  9859. this.type = state.type;
  9860. this.value = state.value;
  9861. this.start = startIndex + state.start;
  9862. this.end = startIndex + state.end;
  9863. this.loc = new SourceLocation(state.startLoc, state.endLoc);
  9864. }
  9865. }
  9866. class Tokenizer extends CommentsParser {
  9867. constructor(options, input) {
  9868. super();
  9869. this.isLookahead = void 0;
  9870. this.tokens = [];
  9871. this.errorHandlers_readInt = {
  9872. invalidDigit: (pos, lineStart, curLine, radix) => {
  9873. if (!(this.optionFlags & 2048)) return false;
  9874. this.raise(Errors.InvalidDigit, buildPosition(pos, lineStart, curLine), {
  9875. radix
  9876. });
  9877. return true;
  9878. },
  9879. numericSeparatorInEscapeSequence: this.errorBuilder(Errors.NumericSeparatorInEscapeSequence),
  9880. unexpectedNumericSeparator: this.errorBuilder(Errors.UnexpectedNumericSeparator)
  9881. };
  9882. this.errorHandlers_readCodePoint = Object.assign({}, this.errorHandlers_readInt, {
  9883. invalidEscapeSequence: this.errorBuilder(Errors.InvalidEscapeSequence),
  9884. invalidCodePoint: this.errorBuilder(Errors.InvalidCodePoint)
  9885. });
  9886. this.errorHandlers_readStringContents_string = Object.assign({}, this.errorHandlers_readCodePoint, {
  9887. strictNumericEscape: (pos, lineStart, curLine) => {
  9888. this.recordStrictModeErrors(Errors.StrictNumericEscape, buildPosition(pos, lineStart, curLine));
  9889. },
  9890. unterminated: (pos, lineStart, curLine) => {
  9891. throw this.raise(Errors.UnterminatedString, buildPosition(pos - 1, lineStart, curLine));
  9892. }
  9893. });
  9894. this.errorHandlers_readStringContents_template = Object.assign({}, this.errorHandlers_readCodePoint, {
  9895. strictNumericEscape: this.errorBuilder(Errors.StrictNumericEscape),
  9896. unterminated: (pos, lineStart, curLine) => {
  9897. throw this.raise(Errors.UnterminatedTemplate, buildPosition(pos, lineStart, curLine));
  9898. }
  9899. });
  9900. this.state = new State();
  9901. this.state.init(options);
  9902. this.input = input;
  9903. this.length = input.length;
  9904. this.comments = [];
  9905. this.isLookahead = false;
  9906. }
  9907. pushToken(token) {
  9908. this.tokens.length = this.state.tokensLength;
  9909. this.tokens.push(token);
  9910. ++this.state.tokensLength;
  9911. }
  9912. next() {
  9913. this.checkKeywordEscapes();
  9914. if (this.optionFlags & 256) {
  9915. this.pushToken(new Token(this.state));
  9916. }
  9917. this.state.lastTokEndLoc = this.state.endLoc;
  9918. this.state.lastTokStartLoc = this.state.startLoc;
  9919. this.nextToken();
  9920. }
  9921. eat(type) {
  9922. if (this.match(type)) {
  9923. this.next();
  9924. return true;
  9925. } else {
  9926. return false;
  9927. }
  9928. }
  9929. match(type) {
  9930. return this.state.type === type;
  9931. }
  9932. createLookaheadState(state) {
  9933. return {
  9934. pos: state.pos,
  9935. value: null,
  9936. type: state.type,
  9937. start: state.start,
  9938. end: state.end,
  9939. context: [this.curContext()],
  9940. inType: state.inType,
  9941. startLoc: state.startLoc,
  9942. lastTokEndLoc: state.lastTokEndLoc,
  9943. curLine: state.curLine,
  9944. lineStart: state.lineStart,
  9945. curPosition: state.curPosition
  9946. };
  9947. }
  9948. lookahead() {
  9949. const old = this.state;
  9950. this.state = this.createLookaheadState(old);
  9951. this.isLookahead = true;
  9952. this.nextToken();
  9953. this.isLookahead = false;
  9954. const curr = this.state;
  9955. this.state = old;
  9956. return curr;
  9957. }
  9958. nextTokenStart() {
  9959. return this.nextTokenStartSince(this.state.pos);
  9960. }
  9961. nextTokenStartSince(pos) {
  9962. skipWhiteSpace.lastIndex = pos;
  9963. return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos;
  9964. }
  9965. lookaheadCharCode() {
  9966. return this.lookaheadCharCodeSince(this.state.pos);
  9967. }
  9968. lookaheadCharCodeSince(pos) {
  9969. return this.input.charCodeAt(this.nextTokenStartSince(pos));
  9970. }
  9971. nextTokenInLineStart() {
  9972. return this.nextTokenInLineStartSince(this.state.pos);
  9973. }
  9974. nextTokenInLineStartSince(pos) {
  9975. skipWhiteSpaceInLine.lastIndex = pos;
  9976. return skipWhiteSpaceInLine.test(this.input) ? skipWhiteSpaceInLine.lastIndex : pos;
  9977. }
  9978. lookaheadInLineCharCode() {
  9979. return this.input.charCodeAt(this.nextTokenInLineStart());
  9980. }
  9981. codePointAtPos(pos) {
  9982. let cp = this.input.charCodeAt(pos);
  9983. if ((cp & 0xfc00) === 0xd800 && ++pos < this.input.length) {
  9984. const trail = this.input.charCodeAt(pos);
  9985. if ((trail & 0xfc00) === 0xdc00) {
  9986. cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);
  9987. }
  9988. }
  9989. return cp;
  9990. }
  9991. setStrict(strict) {
  9992. this.state.strict = strict;
  9993. if (strict) {
  9994. this.state.strictErrors.forEach(([toParseError, at]) => this.raise(toParseError, at));
  9995. this.state.strictErrors.clear();
  9996. }
  9997. }
  9998. curContext() {
  9999. return this.state.context[this.state.context.length - 1];
  10000. }
  10001. nextToken() {
  10002. this.skipSpace();
  10003. this.state.start = this.state.pos;
  10004. if (!this.isLookahead) this.state.startLoc = this.state.curPosition();
  10005. if (this.state.pos >= this.length) {
  10006. this.finishToken(140);
  10007. return;
  10008. }
  10009. this.getTokenFromCode(this.codePointAtPos(this.state.pos));
  10010. }
  10011. skipBlockComment(commentEnd) {
  10012. let startLoc;
  10013. if (!this.isLookahead) startLoc = this.state.curPosition();
  10014. const start = this.state.pos;
  10015. const end = this.input.indexOf(commentEnd, start + 2);
  10016. if (end === -1) {
  10017. throw this.raise(Errors.UnterminatedComment, this.state.curPosition());
  10018. }
  10019. this.state.pos = end + commentEnd.length;
  10020. lineBreakG.lastIndex = start + 2;
  10021. while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) {
  10022. ++this.state.curLine;
  10023. this.state.lineStart = lineBreakG.lastIndex;
  10024. }
  10025. if (this.isLookahead) return;
  10026. const comment = {
  10027. type: "CommentBlock",
  10028. value: this.input.slice(start + 2, end),
  10029. start: this.sourceToOffsetPos(start),
  10030. end: this.sourceToOffsetPos(end + commentEnd.length),
  10031. loc: new SourceLocation(startLoc, this.state.curPosition())
  10032. };
  10033. if (this.optionFlags & 256) this.pushToken(comment);
  10034. return comment;
  10035. }
  10036. skipLineComment(startSkip) {
  10037. const start = this.state.pos;
  10038. let startLoc;
  10039. if (!this.isLookahead) startLoc = this.state.curPosition();
  10040. let ch = this.input.charCodeAt(this.state.pos += startSkip);
  10041. if (this.state.pos < this.length) {
  10042. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  10043. ch = this.input.charCodeAt(this.state.pos);
  10044. }
  10045. }
  10046. if (this.isLookahead) return;
  10047. const end = this.state.pos;
  10048. const value = this.input.slice(start + startSkip, end);
  10049. const comment = {
  10050. type: "CommentLine",
  10051. value,
  10052. start: this.sourceToOffsetPos(start),
  10053. end: this.sourceToOffsetPos(end),
  10054. loc: new SourceLocation(startLoc, this.state.curPosition())
  10055. };
  10056. if (this.optionFlags & 256) this.pushToken(comment);
  10057. return comment;
  10058. }
  10059. skipSpace() {
  10060. const spaceStart = this.state.pos;
  10061. const comments = this.optionFlags & 4096 ? [] : null;
  10062. loop: while (this.state.pos < this.length) {
  10063. const ch = this.input.charCodeAt(this.state.pos);
  10064. switch (ch) {
  10065. case 32:
  10066. case 160:
  10067. case 9:
  10068. ++this.state.pos;
  10069. break;
  10070. case 13:
  10071. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  10072. ++this.state.pos;
  10073. }
  10074. case 10:
  10075. case 8232:
  10076. case 8233:
  10077. ++this.state.pos;
  10078. ++this.state.curLine;
  10079. this.state.lineStart = this.state.pos;
  10080. break;
  10081. case 47:
  10082. switch (this.input.charCodeAt(this.state.pos + 1)) {
  10083. case 42:
  10084. {
  10085. const comment = this.skipBlockComment("*/");
  10086. if (comment !== undefined) {
  10087. this.addComment(comment);
  10088. comments == null || comments.push(comment);
  10089. }
  10090. break;
  10091. }
  10092. case 47:
  10093. {
  10094. const comment = this.skipLineComment(2);
  10095. if (comment !== undefined) {
  10096. this.addComment(comment);
  10097. comments == null || comments.push(comment);
  10098. }
  10099. break;
  10100. }
  10101. default:
  10102. break loop;
  10103. }
  10104. break;
  10105. default:
  10106. if (isWhitespace(ch)) {
  10107. ++this.state.pos;
  10108. } else if (ch === 45 && !this.inModule && this.optionFlags & 8192) {
  10109. const pos = this.state.pos;
  10110. if (this.input.charCodeAt(pos + 1) === 45 && this.input.charCodeAt(pos + 2) === 62 && (spaceStart === 0 || this.state.lineStart > spaceStart)) {
  10111. const comment = this.skipLineComment(3);
  10112. if (comment !== undefined) {
  10113. this.addComment(comment);
  10114. comments == null || comments.push(comment);
  10115. }
  10116. } else {
  10117. break loop;
  10118. }
  10119. } else if (ch === 60 && !this.inModule && this.optionFlags & 8192) {
  10120. const pos = this.state.pos;
  10121. if (this.input.charCodeAt(pos + 1) === 33 && this.input.charCodeAt(pos + 2) === 45 && this.input.charCodeAt(pos + 3) === 45) {
  10122. const comment = this.skipLineComment(4);
  10123. if (comment !== undefined) {
  10124. this.addComment(comment);
  10125. comments == null || comments.push(comment);
  10126. }
  10127. } else {
  10128. break loop;
  10129. }
  10130. } else {
  10131. break loop;
  10132. }
  10133. }
  10134. }
  10135. if ((comments == null ? void 0 : comments.length) > 0) {
  10136. const end = this.state.pos;
  10137. const commentWhitespace = {
  10138. start: this.sourceToOffsetPos(spaceStart),
  10139. end: this.sourceToOffsetPos(end),
  10140. comments: comments,
  10141. leadingNode: null,
  10142. trailingNode: null,
  10143. containingNode: null
  10144. };
  10145. this.state.commentStack.push(commentWhitespace);
  10146. }
  10147. }
  10148. finishToken(type, val) {
  10149. this.state.end = this.state.pos;
  10150. this.state.endLoc = this.state.curPosition();
  10151. const prevType = this.state.type;
  10152. this.state.type = type;
  10153. this.state.value = val;
  10154. if (!this.isLookahead) {
  10155. this.updateContext(prevType);
  10156. }
  10157. }
  10158. replaceToken(type) {
  10159. this.state.type = type;
  10160. this.updateContext();
  10161. }
  10162. readToken_numberSign() {
  10163. if (this.state.pos === 0 && this.readToken_interpreter()) {
  10164. return;
  10165. }
  10166. const nextPos = this.state.pos + 1;
  10167. const next = this.codePointAtPos(nextPos);
  10168. if (next >= 48 && next <= 57) {
  10169. throw this.raise(Errors.UnexpectedDigitAfterHash, this.state.curPosition());
  10170. }
  10171. if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) {
  10172. this.expectPlugin("recordAndTuple");
  10173. if (this.getPluginOption("recordAndTuple", "syntaxType") === "bar") {
  10174. throw this.raise(next === 123 ? Errors.RecordExpressionHashIncorrectStartSyntaxType : Errors.TupleExpressionHashIncorrectStartSyntaxType, this.state.curPosition());
  10175. }
  10176. this.state.pos += 2;
  10177. if (next === 123) {
  10178. this.finishToken(7);
  10179. } else {
  10180. this.finishToken(1);
  10181. }
  10182. } else if (isIdentifierStart(next)) {
  10183. ++this.state.pos;
  10184. this.finishToken(139, this.readWord1(next));
  10185. } else if (next === 92) {
  10186. ++this.state.pos;
  10187. this.finishToken(139, this.readWord1());
  10188. } else {
  10189. this.finishOp(27, 1);
  10190. }
  10191. }
  10192. readToken_dot() {
  10193. const next = this.input.charCodeAt(this.state.pos + 1);
  10194. if (next >= 48 && next <= 57) {
  10195. this.readNumber(true);
  10196. return;
  10197. }
  10198. if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
  10199. this.state.pos += 3;
  10200. this.finishToken(21);
  10201. } else {
  10202. ++this.state.pos;
  10203. this.finishToken(16);
  10204. }
  10205. }
  10206. readToken_slash() {
  10207. const next = this.input.charCodeAt(this.state.pos + 1);
  10208. if (next === 61) {
  10209. this.finishOp(31, 2);
  10210. } else {
  10211. this.finishOp(56, 1);
  10212. }
  10213. }
  10214. readToken_interpreter() {
  10215. if (this.state.pos !== 0 || this.length < 2) return false;
  10216. let ch = this.input.charCodeAt(this.state.pos + 1);
  10217. if (ch !== 33) return false;
  10218. const start = this.state.pos;
  10219. this.state.pos += 1;
  10220. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  10221. ch = this.input.charCodeAt(this.state.pos);
  10222. }
  10223. const value = this.input.slice(start + 2, this.state.pos);
  10224. this.finishToken(28, value);
  10225. return true;
  10226. }
  10227. readToken_mult_modulo(code) {
  10228. let type = code === 42 ? 55 : 54;
  10229. let width = 1;
  10230. let next = this.input.charCodeAt(this.state.pos + 1);
  10231. if (code === 42 && next === 42) {
  10232. width++;
  10233. next = this.input.charCodeAt(this.state.pos + 2);
  10234. type = 57;
  10235. }
  10236. if (next === 61 && !this.state.inType) {
  10237. width++;
  10238. type = code === 37 ? 33 : 30;
  10239. }
  10240. this.finishOp(type, width);
  10241. }
  10242. readToken_pipe_amp(code) {
  10243. const next = this.input.charCodeAt(this.state.pos + 1);
  10244. if (next === code) {
  10245. if (this.input.charCodeAt(this.state.pos + 2) === 61) {
  10246. this.finishOp(30, 3);
  10247. } else {
  10248. this.finishOp(code === 124 ? 41 : 42, 2);
  10249. }
  10250. return;
  10251. }
  10252. if (code === 124) {
  10253. if (next === 62) {
  10254. this.finishOp(39, 2);
  10255. return;
  10256. }
  10257. if (this.hasPlugin("recordAndTuple") && next === 125) {
  10258. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  10259. throw this.raise(Errors.RecordExpressionBarIncorrectEndSyntaxType, this.state.curPosition());
  10260. }
  10261. this.state.pos += 2;
  10262. this.finishToken(9);
  10263. return;
  10264. }
  10265. if (this.hasPlugin("recordAndTuple") && next === 93) {
  10266. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  10267. throw this.raise(Errors.TupleExpressionBarIncorrectEndSyntaxType, this.state.curPosition());
  10268. }
  10269. this.state.pos += 2;
  10270. this.finishToken(4);
  10271. return;
  10272. }
  10273. }
  10274. if (next === 61) {
  10275. this.finishOp(30, 2);
  10276. return;
  10277. }
  10278. this.finishOp(code === 124 ? 43 : 45, 1);
  10279. }
  10280. readToken_caret() {
  10281. const next = this.input.charCodeAt(this.state.pos + 1);
  10282. if (next === 61 && !this.state.inType) {
  10283. this.finishOp(32, 2);
  10284. } else if (next === 94 && this.hasPlugin(["pipelineOperator", {
  10285. proposal: "hack",
  10286. topicToken: "^^"
  10287. }])) {
  10288. this.finishOp(37, 2);
  10289. const lookaheadCh = this.input.codePointAt(this.state.pos);
  10290. if (lookaheadCh === 94) {
  10291. this.unexpected();
  10292. }
  10293. } else {
  10294. this.finishOp(44, 1);
  10295. }
  10296. }
  10297. readToken_atSign() {
  10298. const next = this.input.charCodeAt(this.state.pos + 1);
  10299. if (next === 64 && this.hasPlugin(["pipelineOperator", {
  10300. proposal: "hack",
  10301. topicToken: "@@"
  10302. }])) {
  10303. this.finishOp(38, 2);
  10304. } else {
  10305. this.finishOp(26, 1);
  10306. }
  10307. }
  10308. readToken_plus_min(code) {
  10309. const next = this.input.charCodeAt(this.state.pos + 1);
  10310. if (next === code) {
  10311. this.finishOp(34, 2);
  10312. return;
  10313. }
  10314. if (next === 61) {
  10315. this.finishOp(30, 2);
  10316. } else {
  10317. this.finishOp(53, 1);
  10318. }
  10319. }
  10320. readToken_lt() {
  10321. const {
  10322. pos
  10323. } = this.state;
  10324. const next = this.input.charCodeAt(pos + 1);
  10325. if (next === 60) {
  10326. if (this.input.charCodeAt(pos + 2) === 61) {
  10327. this.finishOp(30, 3);
  10328. return;
  10329. }
  10330. this.finishOp(51, 2);
  10331. return;
  10332. }
  10333. if (next === 61) {
  10334. this.finishOp(49, 2);
  10335. return;
  10336. }
  10337. this.finishOp(47, 1);
  10338. }
  10339. readToken_gt() {
  10340. const {
  10341. pos
  10342. } = this.state;
  10343. const next = this.input.charCodeAt(pos + 1);
  10344. if (next === 62) {
  10345. const size = this.input.charCodeAt(pos + 2) === 62 ? 3 : 2;
  10346. if (this.input.charCodeAt(pos + size) === 61) {
  10347. this.finishOp(30, size + 1);
  10348. return;
  10349. }
  10350. this.finishOp(52, size);
  10351. return;
  10352. }
  10353. if (next === 61) {
  10354. this.finishOp(49, 2);
  10355. return;
  10356. }
  10357. this.finishOp(48, 1);
  10358. }
  10359. readToken_eq_excl(code) {
  10360. const next = this.input.charCodeAt(this.state.pos + 1);
  10361. if (next === 61) {
  10362. this.finishOp(46, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  10363. return;
  10364. }
  10365. if (code === 61 && next === 62) {
  10366. this.state.pos += 2;
  10367. this.finishToken(19);
  10368. return;
  10369. }
  10370. this.finishOp(code === 61 ? 29 : 35, 1);
  10371. }
  10372. readToken_question() {
  10373. const next = this.input.charCodeAt(this.state.pos + 1);
  10374. const next2 = this.input.charCodeAt(this.state.pos + 2);
  10375. if (next === 63) {
  10376. if (next2 === 61) {
  10377. this.finishOp(30, 3);
  10378. } else {
  10379. this.finishOp(40, 2);
  10380. }
  10381. } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
  10382. this.state.pos += 2;
  10383. this.finishToken(18);
  10384. } else {
  10385. ++this.state.pos;
  10386. this.finishToken(17);
  10387. }
  10388. }
  10389. getTokenFromCode(code) {
  10390. switch (code) {
  10391. case 46:
  10392. this.readToken_dot();
  10393. return;
  10394. case 40:
  10395. ++this.state.pos;
  10396. this.finishToken(10);
  10397. return;
  10398. case 41:
  10399. ++this.state.pos;
  10400. this.finishToken(11);
  10401. return;
  10402. case 59:
  10403. ++this.state.pos;
  10404. this.finishToken(13);
  10405. return;
  10406. case 44:
  10407. ++this.state.pos;
  10408. this.finishToken(12);
  10409. return;
  10410. case 91:
  10411. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  10412. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  10413. throw this.raise(Errors.TupleExpressionBarIncorrectStartSyntaxType, this.state.curPosition());
  10414. }
  10415. this.state.pos += 2;
  10416. this.finishToken(2);
  10417. } else {
  10418. ++this.state.pos;
  10419. this.finishToken(0);
  10420. }
  10421. return;
  10422. case 93:
  10423. ++this.state.pos;
  10424. this.finishToken(3);
  10425. return;
  10426. case 123:
  10427. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  10428. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  10429. throw this.raise(Errors.RecordExpressionBarIncorrectStartSyntaxType, this.state.curPosition());
  10430. }
  10431. this.state.pos += 2;
  10432. this.finishToken(6);
  10433. } else {
  10434. ++this.state.pos;
  10435. this.finishToken(5);
  10436. }
  10437. return;
  10438. case 125:
  10439. ++this.state.pos;
  10440. this.finishToken(8);
  10441. return;
  10442. case 58:
  10443. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  10444. this.finishOp(15, 2);
  10445. } else {
  10446. ++this.state.pos;
  10447. this.finishToken(14);
  10448. }
  10449. return;
  10450. case 63:
  10451. this.readToken_question();
  10452. return;
  10453. case 96:
  10454. this.readTemplateToken();
  10455. return;
  10456. case 48:
  10457. {
  10458. const next = this.input.charCodeAt(this.state.pos + 1);
  10459. if (next === 120 || next === 88) {
  10460. this.readRadixNumber(16);
  10461. return;
  10462. }
  10463. if (next === 111 || next === 79) {
  10464. this.readRadixNumber(8);
  10465. return;
  10466. }
  10467. if (next === 98 || next === 66) {
  10468. this.readRadixNumber(2);
  10469. return;
  10470. }
  10471. }
  10472. case 49:
  10473. case 50:
  10474. case 51:
  10475. case 52:
  10476. case 53:
  10477. case 54:
  10478. case 55:
  10479. case 56:
  10480. case 57:
  10481. this.readNumber(false);
  10482. return;
  10483. case 34:
  10484. case 39:
  10485. this.readString(code);
  10486. return;
  10487. case 47:
  10488. this.readToken_slash();
  10489. return;
  10490. case 37:
  10491. case 42:
  10492. this.readToken_mult_modulo(code);
  10493. return;
  10494. case 124:
  10495. case 38:
  10496. this.readToken_pipe_amp(code);
  10497. return;
  10498. case 94:
  10499. this.readToken_caret();
  10500. return;
  10501. case 43:
  10502. case 45:
  10503. this.readToken_plus_min(code);
  10504. return;
  10505. case 60:
  10506. this.readToken_lt();
  10507. return;
  10508. case 62:
  10509. this.readToken_gt();
  10510. return;
  10511. case 61:
  10512. case 33:
  10513. this.readToken_eq_excl(code);
  10514. return;
  10515. case 126:
  10516. this.finishOp(36, 1);
  10517. return;
  10518. case 64:
  10519. this.readToken_atSign();
  10520. return;
  10521. case 35:
  10522. this.readToken_numberSign();
  10523. return;
  10524. case 92:
  10525. this.readWord();
  10526. return;
  10527. default:
  10528. if (isIdentifierStart(code)) {
  10529. this.readWord(code);
  10530. return;
  10531. }
  10532. }
  10533. throw this.raise(Errors.InvalidOrUnexpectedToken, this.state.curPosition(), {
  10534. unexpected: String.fromCodePoint(code)
  10535. });
  10536. }
  10537. finishOp(type, size) {
  10538. const str = this.input.slice(this.state.pos, this.state.pos + size);
  10539. this.state.pos += size;
  10540. this.finishToken(type, str);
  10541. }
  10542. readRegexp() {
  10543. const startLoc = this.state.startLoc;
  10544. const start = this.state.start + 1;
  10545. let escaped, inClass;
  10546. let {
  10547. pos
  10548. } = this.state;
  10549. for (;; ++pos) {
  10550. if (pos >= this.length) {
  10551. throw this.raise(Errors.UnterminatedRegExp, createPositionWithColumnOffset(startLoc, 1));
  10552. }
  10553. const ch = this.input.charCodeAt(pos);
  10554. if (isNewLine(ch)) {
  10555. throw this.raise(Errors.UnterminatedRegExp, createPositionWithColumnOffset(startLoc, 1));
  10556. }
  10557. if (escaped) {
  10558. escaped = false;
  10559. } else {
  10560. if (ch === 91) {
  10561. inClass = true;
  10562. } else if (ch === 93 && inClass) {
  10563. inClass = false;
  10564. } else if (ch === 47 && !inClass) {
  10565. break;
  10566. }
  10567. escaped = ch === 92;
  10568. }
  10569. }
  10570. const content = this.input.slice(start, pos);
  10571. ++pos;
  10572. let mods = "";
  10573. const nextPos = () => createPositionWithColumnOffset(startLoc, pos + 2 - start);
  10574. while (pos < this.length) {
  10575. const cp = this.codePointAtPos(pos);
  10576. const char = String.fromCharCode(cp);
  10577. if (VALID_REGEX_FLAGS.has(cp)) {
  10578. if (cp === 118) {
  10579. if (mods.includes("u")) {
  10580. this.raise(Errors.IncompatibleRegExpUVFlags, nextPos());
  10581. }
  10582. } else if (cp === 117) {
  10583. if (mods.includes("v")) {
  10584. this.raise(Errors.IncompatibleRegExpUVFlags, nextPos());
  10585. }
  10586. }
  10587. if (mods.includes(char)) {
  10588. this.raise(Errors.DuplicateRegExpFlags, nextPos());
  10589. }
  10590. } else if (isIdentifierChar(cp) || cp === 92) {
  10591. this.raise(Errors.MalformedRegExpFlags, nextPos());
  10592. } else {
  10593. break;
  10594. }
  10595. ++pos;
  10596. mods += char;
  10597. }
  10598. this.state.pos = pos;
  10599. this.finishToken(138, {
  10600. pattern: content,
  10601. flags: mods
  10602. });
  10603. }
  10604. readInt(radix, len, forceLen = false, allowNumSeparator = true) {
  10605. const {
  10606. n,
  10607. pos
  10608. } = readInt(this.input, this.state.pos, this.state.lineStart, this.state.curLine, radix, len, forceLen, allowNumSeparator, this.errorHandlers_readInt, false);
  10609. this.state.pos = pos;
  10610. return n;
  10611. }
  10612. readRadixNumber(radix) {
  10613. const start = this.state.pos;
  10614. const startLoc = this.state.curPosition();
  10615. let isBigInt = false;
  10616. this.state.pos += 2;
  10617. const val = this.readInt(radix);
  10618. if (val == null) {
  10619. this.raise(Errors.InvalidDigit, createPositionWithColumnOffset(startLoc, 2), {
  10620. radix
  10621. });
  10622. }
  10623. const next = this.input.charCodeAt(this.state.pos);
  10624. if (next === 110) {
  10625. ++this.state.pos;
  10626. isBigInt = true;
  10627. } else if (next === 109) {
  10628. throw this.raise(Errors.InvalidDecimal, startLoc);
  10629. }
  10630. if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
  10631. throw this.raise(Errors.NumberIdentifier, this.state.curPosition());
  10632. }
  10633. if (isBigInt) {
  10634. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  10635. this.finishToken(136, str);
  10636. return;
  10637. }
  10638. this.finishToken(135, val);
  10639. }
  10640. readNumber(startsWithDot) {
  10641. const start = this.state.pos;
  10642. const startLoc = this.state.curPosition();
  10643. let isFloat = false;
  10644. let isBigInt = false;
  10645. let hasExponent = false;
  10646. let isOctal = false;
  10647. if (!startsWithDot && this.readInt(10) === null) {
  10648. this.raise(Errors.InvalidNumber, this.state.curPosition());
  10649. }
  10650. const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  10651. if (hasLeadingZero) {
  10652. const integer = this.input.slice(start, this.state.pos);
  10653. this.recordStrictModeErrors(Errors.StrictOctalLiteral, startLoc);
  10654. if (!this.state.strict) {
  10655. const underscorePos = integer.indexOf("_");
  10656. if (underscorePos > 0) {
  10657. this.raise(Errors.ZeroDigitNumericSeparator, createPositionWithColumnOffset(startLoc, underscorePos));
  10658. }
  10659. }
  10660. isOctal = hasLeadingZero && !/[89]/.test(integer);
  10661. }
  10662. let next = this.input.charCodeAt(this.state.pos);
  10663. if (next === 46 && !isOctal) {
  10664. ++this.state.pos;
  10665. this.readInt(10);
  10666. isFloat = true;
  10667. next = this.input.charCodeAt(this.state.pos);
  10668. }
  10669. if ((next === 69 || next === 101) && !isOctal) {
  10670. next = this.input.charCodeAt(++this.state.pos);
  10671. if (next === 43 || next === 45) {
  10672. ++this.state.pos;
  10673. }
  10674. if (this.readInt(10) === null) {
  10675. this.raise(Errors.InvalidOrMissingExponent, startLoc);
  10676. }
  10677. isFloat = true;
  10678. hasExponent = true;
  10679. next = this.input.charCodeAt(this.state.pos);
  10680. }
  10681. if (next === 110) {
  10682. if (isFloat || hasLeadingZero) {
  10683. this.raise(Errors.InvalidBigIntLiteral, startLoc);
  10684. }
  10685. ++this.state.pos;
  10686. isBigInt = true;
  10687. }
  10688. if (next === 109) {
  10689. this.expectPlugin("decimal", this.state.curPosition());
  10690. if (hasExponent || hasLeadingZero) {
  10691. this.raise(Errors.InvalidDecimal, startLoc);
  10692. }
  10693. ++this.state.pos;
  10694. var isDecimal = true;
  10695. }
  10696. if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
  10697. throw this.raise(Errors.NumberIdentifier, this.state.curPosition());
  10698. }
  10699. const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, "");
  10700. if (isBigInt) {
  10701. this.finishToken(136, str);
  10702. return;
  10703. }
  10704. if (isDecimal) {
  10705. this.finishToken(137, str);
  10706. return;
  10707. }
  10708. const val = isOctal ? parseInt(str, 8) : parseFloat(str);
  10709. this.finishToken(135, val);
  10710. }
  10711. readCodePoint(throwOnInvalid) {
  10712. const {
  10713. code,
  10714. pos
  10715. } = readCodePoint(this.input, this.state.pos, this.state.lineStart, this.state.curLine, throwOnInvalid, this.errorHandlers_readCodePoint);
  10716. this.state.pos = pos;
  10717. return code;
  10718. }
  10719. readString(quote) {
  10720. const {
  10721. str,
  10722. pos,
  10723. curLine,
  10724. lineStart
  10725. } = readStringContents(quote === 34 ? "double" : "single", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_string);
  10726. this.state.pos = pos + 1;
  10727. this.state.lineStart = lineStart;
  10728. this.state.curLine = curLine;
  10729. this.finishToken(134, str);
  10730. }
  10731. readTemplateContinuation() {
  10732. if (!this.match(8)) {
  10733. this.unexpected(null, 8);
  10734. }
  10735. this.state.pos--;
  10736. this.readTemplateToken();
  10737. }
  10738. readTemplateToken() {
  10739. const opening = this.input[this.state.pos];
  10740. const {
  10741. str,
  10742. firstInvalidLoc,
  10743. pos,
  10744. curLine,
  10745. lineStart
  10746. } = readStringContents("template", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_template);
  10747. this.state.pos = pos + 1;
  10748. this.state.lineStart = lineStart;
  10749. this.state.curLine = curLine;
  10750. if (firstInvalidLoc) {
  10751. this.state.firstInvalidTemplateEscapePos = new Position(firstInvalidLoc.curLine, firstInvalidLoc.pos - firstInvalidLoc.lineStart, this.sourceToOffsetPos(firstInvalidLoc.pos));
  10752. }
  10753. if (this.input.codePointAt(pos) === 96) {
  10754. this.finishToken(24, firstInvalidLoc ? null : opening + str + "`");
  10755. } else {
  10756. this.state.pos++;
  10757. this.finishToken(25, firstInvalidLoc ? null : opening + str + "${");
  10758. }
  10759. }
  10760. recordStrictModeErrors(toParseError, at) {
  10761. const index = at.index;
  10762. if (this.state.strict && !this.state.strictErrors.has(index)) {
  10763. this.raise(toParseError, at);
  10764. } else {
  10765. this.state.strictErrors.set(index, [toParseError, at]);
  10766. }
  10767. }
  10768. readWord1(firstCode) {
  10769. this.state.containsEsc = false;
  10770. let word = "";
  10771. const start = this.state.pos;
  10772. let chunkStart = this.state.pos;
  10773. if (firstCode !== undefined) {
  10774. this.state.pos += firstCode <= 0xffff ? 1 : 2;
  10775. }
  10776. while (this.state.pos < this.length) {
  10777. const ch = this.codePointAtPos(this.state.pos);
  10778. if (isIdentifierChar(ch)) {
  10779. this.state.pos += ch <= 0xffff ? 1 : 2;
  10780. } else if (ch === 92) {
  10781. this.state.containsEsc = true;
  10782. word += this.input.slice(chunkStart, this.state.pos);
  10783. const escStart = this.state.curPosition();
  10784. const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
  10785. if (this.input.charCodeAt(++this.state.pos) !== 117) {
  10786. this.raise(Errors.MissingUnicodeEscape, this.state.curPosition());
  10787. chunkStart = this.state.pos - 1;
  10788. continue;
  10789. }
  10790. ++this.state.pos;
  10791. const esc = this.readCodePoint(true);
  10792. if (esc !== null) {
  10793. if (!identifierCheck(esc)) {
  10794. this.raise(Errors.EscapedCharNotAnIdentifier, escStart);
  10795. }
  10796. word += String.fromCodePoint(esc);
  10797. }
  10798. chunkStart = this.state.pos;
  10799. } else {
  10800. break;
  10801. }
  10802. }
  10803. return word + this.input.slice(chunkStart, this.state.pos);
  10804. }
  10805. readWord(firstCode) {
  10806. const word = this.readWord1(firstCode);
  10807. const type = keywords$1.get(word);
  10808. if (type !== undefined) {
  10809. this.finishToken(type, tokenLabelName(type));
  10810. } else {
  10811. this.finishToken(132, word);
  10812. }
  10813. }
  10814. checkKeywordEscapes() {
  10815. const {
  10816. type
  10817. } = this.state;
  10818. if (tokenIsKeyword(type) && this.state.containsEsc) {
  10819. this.raise(Errors.InvalidEscapedReservedWord, this.state.startLoc, {
  10820. reservedWord: tokenLabelName(type)
  10821. });
  10822. }
  10823. }
  10824. raise(toParseError, at, details = {}) {
  10825. const loc = at instanceof Position ? at : at.loc.start;
  10826. const error = toParseError(loc, details);
  10827. if (!(this.optionFlags & 2048)) throw error;
  10828. if (!this.isLookahead) this.state.errors.push(error);
  10829. return error;
  10830. }
  10831. raiseOverwrite(toParseError, at, details = {}) {
  10832. const loc = at instanceof Position ? at : at.loc.start;
  10833. const pos = loc.index;
  10834. const errors = this.state.errors;
  10835. for (let i = errors.length - 1; i >= 0; i--) {
  10836. const error = errors[i];
  10837. if (error.loc.index === pos) {
  10838. return errors[i] = toParseError(loc, details);
  10839. }
  10840. if (error.loc.index < pos) break;
  10841. }
  10842. return this.raise(toParseError, at, details);
  10843. }
  10844. updateContext(prevType) {}
  10845. unexpected(loc, type) {
  10846. throw this.raise(Errors.UnexpectedToken, loc != null ? loc : this.state.startLoc, {
  10847. expected: type ? tokenLabelName(type) : null
  10848. });
  10849. }
  10850. expectPlugin(pluginName, loc) {
  10851. if (this.hasPlugin(pluginName)) {
  10852. return true;
  10853. }
  10854. throw this.raise(Errors.MissingPlugin, loc != null ? loc : this.state.startLoc, {
  10855. missingPlugin: [pluginName]
  10856. });
  10857. }
  10858. expectOnePlugin(pluginNames) {
  10859. if (!pluginNames.some(name => this.hasPlugin(name))) {
  10860. throw this.raise(Errors.MissingOneOfPlugins, this.state.startLoc, {
  10861. missingPlugin: pluginNames
  10862. });
  10863. }
  10864. }
  10865. errorBuilder(error) {
  10866. return (pos, lineStart, curLine) => {
  10867. this.raise(error, buildPosition(pos, lineStart, curLine));
  10868. };
  10869. }
  10870. }
  10871. class ClassScope {
  10872. constructor() {
  10873. this.privateNames = new Set();
  10874. this.loneAccessors = new Map();
  10875. this.undefinedPrivateNames = new Map();
  10876. }
  10877. }
  10878. class ClassScopeHandler {
  10879. constructor(parser) {
  10880. this.parser = void 0;
  10881. this.stack = [];
  10882. this.undefinedPrivateNames = new Map();
  10883. this.parser = parser;
  10884. }
  10885. current() {
  10886. return this.stack[this.stack.length - 1];
  10887. }
  10888. enter() {
  10889. this.stack.push(new ClassScope());
  10890. }
  10891. exit() {
  10892. const oldClassScope = this.stack.pop();
  10893. const current = this.current();
  10894. for (const [name, loc] of Array.from(oldClassScope.undefinedPrivateNames)) {
  10895. if (current) {
  10896. if (!current.undefinedPrivateNames.has(name)) {
  10897. current.undefinedPrivateNames.set(name, loc);
  10898. }
  10899. } else {
  10900. this.parser.raise(Errors.InvalidPrivateFieldResolution, loc, {
  10901. identifierName: name
  10902. });
  10903. }
  10904. }
  10905. }
  10906. declarePrivateName(name, elementType, loc) {
  10907. const {
  10908. privateNames,
  10909. loneAccessors,
  10910. undefinedPrivateNames
  10911. } = this.current();
  10912. let redefined = privateNames.has(name);
  10913. if (elementType & 3) {
  10914. const accessor = redefined && loneAccessors.get(name);
  10915. if (accessor) {
  10916. const oldStatic = accessor & 4;
  10917. const newStatic = elementType & 4;
  10918. const oldKind = accessor & 3;
  10919. const newKind = elementType & 3;
  10920. redefined = oldKind === newKind || oldStatic !== newStatic;
  10921. if (!redefined) loneAccessors.delete(name);
  10922. } else if (!redefined) {
  10923. loneAccessors.set(name, elementType);
  10924. }
  10925. }
  10926. if (redefined) {
  10927. this.parser.raise(Errors.PrivateNameRedeclaration, loc, {
  10928. identifierName: name
  10929. });
  10930. }
  10931. privateNames.add(name);
  10932. undefinedPrivateNames.delete(name);
  10933. }
  10934. usePrivateName(name, loc) {
  10935. let classScope;
  10936. for (classScope of this.stack) {
  10937. if (classScope.privateNames.has(name)) return;
  10938. }
  10939. if (classScope) {
  10940. classScope.undefinedPrivateNames.set(name, loc);
  10941. } else {
  10942. this.parser.raise(Errors.InvalidPrivateFieldResolution, loc, {
  10943. identifierName: name
  10944. });
  10945. }
  10946. }
  10947. }
  10948. class ExpressionScope {
  10949. constructor(type = 0) {
  10950. this.type = type;
  10951. }
  10952. canBeArrowParameterDeclaration() {
  10953. return this.type === 2 || this.type === 1;
  10954. }
  10955. isCertainlyParameterDeclaration() {
  10956. return this.type === 3;
  10957. }
  10958. }
  10959. class ArrowHeadParsingScope extends ExpressionScope {
  10960. constructor(type) {
  10961. super(type);
  10962. this.declarationErrors = new Map();
  10963. }
  10964. recordDeclarationError(ParsingErrorClass, at) {
  10965. const index = at.index;
  10966. this.declarationErrors.set(index, [ParsingErrorClass, at]);
  10967. }
  10968. clearDeclarationError(index) {
  10969. this.declarationErrors.delete(index);
  10970. }
  10971. iterateErrors(iterator) {
  10972. this.declarationErrors.forEach(iterator);
  10973. }
  10974. }
  10975. class ExpressionScopeHandler {
  10976. constructor(parser) {
  10977. this.parser = void 0;
  10978. this.stack = [new ExpressionScope()];
  10979. this.parser = parser;
  10980. }
  10981. enter(scope) {
  10982. this.stack.push(scope);
  10983. }
  10984. exit() {
  10985. this.stack.pop();
  10986. }
  10987. recordParameterInitializerError(toParseError, node) {
  10988. const origin = node.loc.start;
  10989. const {
  10990. stack
  10991. } = this;
  10992. let i = stack.length - 1;
  10993. let scope = stack[i];
  10994. while (!scope.isCertainlyParameterDeclaration()) {
  10995. if (scope.canBeArrowParameterDeclaration()) {
  10996. scope.recordDeclarationError(toParseError, origin);
  10997. } else {
  10998. return;
  10999. }
  11000. scope = stack[--i];
  11001. }
  11002. this.parser.raise(toParseError, origin);
  11003. }
  11004. recordArrowParameterBindingError(error, node) {
  11005. const {
  11006. stack
  11007. } = this;
  11008. const scope = stack[stack.length - 1];
  11009. const origin = node.loc.start;
  11010. if (scope.isCertainlyParameterDeclaration()) {
  11011. this.parser.raise(error, origin);
  11012. } else if (scope.canBeArrowParameterDeclaration()) {
  11013. scope.recordDeclarationError(error, origin);
  11014. } else {
  11015. return;
  11016. }
  11017. }
  11018. recordAsyncArrowParametersError(at) {
  11019. const {
  11020. stack
  11021. } = this;
  11022. let i = stack.length - 1;
  11023. let scope = stack[i];
  11024. while (scope.canBeArrowParameterDeclaration()) {
  11025. if (scope.type === 2) {
  11026. scope.recordDeclarationError(Errors.AwaitBindingIdentifier, at);
  11027. }
  11028. scope = stack[--i];
  11029. }
  11030. }
  11031. validateAsPattern() {
  11032. const {
  11033. stack
  11034. } = this;
  11035. const currentScope = stack[stack.length - 1];
  11036. if (!currentScope.canBeArrowParameterDeclaration()) return;
  11037. currentScope.iterateErrors(([toParseError, loc]) => {
  11038. this.parser.raise(toParseError, loc);
  11039. let i = stack.length - 2;
  11040. let scope = stack[i];
  11041. while (scope.canBeArrowParameterDeclaration()) {
  11042. scope.clearDeclarationError(loc.index);
  11043. scope = stack[--i];
  11044. }
  11045. });
  11046. }
  11047. }
  11048. function newParameterDeclarationScope() {
  11049. return new ExpressionScope(3);
  11050. }
  11051. function newArrowHeadScope() {
  11052. return new ArrowHeadParsingScope(1);
  11053. }
  11054. function newAsyncArrowScope() {
  11055. return new ArrowHeadParsingScope(2);
  11056. }
  11057. function newExpressionScope() {
  11058. return new ExpressionScope();
  11059. }
  11060. class UtilParser extends Tokenizer {
  11061. addExtra(node, key, value, enumerable = true) {
  11062. if (!node) return;
  11063. let {
  11064. extra
  11065. } = node;
  11066. if (extra == null) {
  11067. extra = {};
  11068. node.extra = extra;
  11069. }
  11070. if (enumerable) {
  11071. extra[key] = value;
  11072. } else {
  11073. Object.defineProperty(extra, key, {
  11074. enumerable,
  11075. value
  11076. });
  11077. }
  11078. }
  11079. isContextual(token) {
  11080. return this.state.type === token && !this.state.containsEsc;
  11081. }
  11082. isUnparsedContextual(nameStart, name) {
  11083. if (this.input.startsWith(name, nameStart)) {
  11084. const nextCh = this.input.charCodeAt(nameStart + name.length);
  11085. return !(isIdentifierChar(nextCh) || (nextCh & 0xfc00) === 0xd800);
  11086. }
  11087. return false;
  11088. }
  11089. isLookaheadContextual(name) {
  11090. const next = this.nextTokenStart();
  11091. return this.isUnparsedContextual(next, name);
  11092. }
  11093. eatContextual(token) {
  11094. if (this.isContextual(token)) {
  11095. this.next();
  11096. return true;
  11097. }
  11098. return false;
  11099. }
  11100. expectContextual(token, toParseError) {
  11101. if (!this.eatContextual(token)) {
  11102. if (toParseError != null) {
  11103. throw this.raise(toParseError, this.state.startLoc);
  11104. }
  11105. this.unexpected(null, token);
  11106. }
  11107. }
  11108. canInsertSemicolon() {
  11109. return this.match(140) || this.match(8) || this.hasPrecedingLineBreak();
  11110. }
  11111. hasPrecedingLineBreak() {
  11112. return hasNewLine(this.input, this.offsetToSourcePos(this.state.lastTokEndLoc.index), this.state.start);
  11113. }
  11114. hasFollowingLineBreak() {
  11115. return hasNewLine(this.input, this.state.end, this.nextTokenStart());
  11116. }
  11117. isLineTerminator() {
  11118. return this.eat(13) || this.canInsertSemicolon();
  11119. }
  11120. semicolon(allowAsi = true) {
  11121. if (allowAsi ? this.isLineTerminator() : this.eat(13)) return;
  11122. this.raise(Errors.MissingSemicolon, this.state.lastTokEndLoc);
  11123. }
  11124. expect(type, loc) {
  11125. if (!this.eat(type)) {
  11126. this.unexpected(loc, type);
  11127. }
  11128. }
  11129. tryParse(fn, oldState = this.state.clone()) {
  11130. const abortSignal = {
  11131. node: null
  11132. };
  11133. try {
  11134. const node = fn((node = null) => {
  11135. abortSignal.node = node;
  11136. throw abortSignal;
  11137. });
  11138. if (this.state.errors.length > oldState.errors.length) {
  11139. const failState = this.state;
  11140. this.state = oldState;
  11141. this.state.tokensLength = failState.tokensLength;
  11142. return {
  11143. node,
  11144. error: failState.errors[oldState.errors.length],
  11145. thrown: false,
  11146. aborted: false,
  11147. failState
  11148. };
  11149. }
  11150. return {
  11151. node: node,
  11152. error: null,
  11153. thrown: false,
  11154. aborted: false,
  11155. failState: null
  11156. };
  11157. } catch (error) {
  11158. const failState = this.state;
  11159. this.state = oldState;
  11160. if (error instanceof SyntaxError) {
  11161. return {
  11162. node: null,
  11163. error,
  11164. thrown: true,
  11165. aborted: false,
  11166. failState
  11167. };
  11168. }
  11169. if (error === abortSignal) {
  11170. return {
  11171. node: abortSignal.node,
  11172. error: null,
  11173. thrown: false,
  11174. aborted: true,
  11175. failState
  11176. };
  11177. }
  11178. throw error;
  11179. }
  11180. }
  11181. checkExpressionErrors(refExpressionErrors, andThrow) {
  11182. if (!refExpressionErrors) return false;
  11183. const {
  11184. shorthandAssignLoc,
  11185. doubleProtoLoc,
  11186. privateKeyLoc,
  11187. optionalParametersLoc,
  11188. voidPatternLoc
  11189. } = refExpressionErrors;
  11190. const hasErrors = !!shorthandAssignLoc || !!doubleProtoLoc || !!optionalParametersLoc || !!privateKeyLoc || !!voidPatternLoc;
  11191. if (!andThrow) {
  11192. return hasErrors;
  11193. }
  11194. if (shorthandAssignLoc != null) {
  11195. this.raise(Errors.InvalidCoverInitializedName, shorthandAssignLoc);
  11196. }
  11197. if (doubleProtoLoc != null) {
  11198. this.raise(Errors.DuplicateProto, doubleProtoLoc);
  11199. }
  11200. if (privateKeyLoc != null) {
  11201. this.raise(Errors.UnexpectedPrivateField, privateKeyLoc);
  11202. }
  11203. if (optionalParametersLoc != null) {
  11204. this.unexpected(optionalParametersLoc);
  11205. }
  11206. if (voidPatternLoc != null) {
  11207. this.raise(Errors.InvalidCoverDiscardElement, voidPatternLoc);
  11208. }
  11209. }
  11210. isLiteralPropertyName() {
  11211. return tokenIsLiteralPropertyName(this.state.type);
  11212. }
  11213. isPrivateName(node) {
  11214. return node.type === "PrivateName";
  11215. }
  11216. getPrivateNameSV(node) {
  11217. return node.id.name;
  11218. }
  11219. hasPropertyAsPrivateName(node) {
  11220. return (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && this.isPrivateName(node.property);
  11221. }
  11222. isObjectProperty(node) {
  11223. return node.type === "ObjectProperty";
  11224. }
  11225. isObjectMethod(node) {
  11226. return node.type === "ObjectMethod";
  11227. }
  11228. initializeScopes(inModule = this.options.sourceType === "module") {
  11229. const oldLabels = this.state.labels;
  11230. this.state.labels = [];
  11231. const oldExportedIdentifiers = this.exportedIdentifiers;
  11232. this.exportedIdentifiers = new Set();
  11233. const oldInModule = this.inModule;
  11234. this.inModule = inModule;
  11235. const oldScope = this.scope;
  11236. const ScopeHandler = this.getScopeHandler();
  11237. this.scope = new ScopeHandler(this, inModule);
  11238. const oldProdParam = this.prodParam;
  11239. this.prodParam = new ProductionParameterHandler();
  11240. const oldClassScope = this.classScope;
  11241. this.classScope = new ClassScopeHandler(this);
  11242. const oldExpressionScope = this.expressionScope;
  11243. this.expressionScope = new ExpressionScopeHandler(this);
  11244. return () => {
  11245. this.state.labels = oldLabels;
  11246. this.exportedIdentifiers = oldExportedIdentifiers;
  11247. this.inModule = oldInModule;
  11248. this.scope = oldScope;
  11249. this.prodParam = oldProdParam;
  11250. this.classScope = oldClassScope;
  11251. this.expressionScope = oldExpressionScope;
  11252. };
  11253. }
  11254. enterInitialScopes() {
  11255. let paramFlags = 0;
  11256. if (this.inModule || this.optionFlags & 1) {
  11257. paramFlags |= 2;
  11258. }
  11259. if (this.optionFlags & 32) {
  11260. paramFlags |= 1;
  11261. }
  11262. const isCommonJS = !this.inModule && this.options.sourceType === "commonjs";
  11263. if (isCommonJS || this.optionFlags & 2) {
  11264. paramFlags |= 4;
  11265. }
  11266. this.prodParam.enter(paramFlags);
  11267. let scopeFlags = isCommonJS ? 514 : 1;
  11268. if (this.optionFlags & 4) {
  11269. scopeFlags |= 512;
  11270. }
  11271. this.scope.enter(scopeFlags);
  11272. }
  11273. checkDestructuringPrivate(refExpressionErrors) {
  11274. const {
  11275. privateKeyLoc
  11276. } = refExpressionErrors;
  11277. if (privateKeyLoc !== null) {
  11278. this.expectPlugin("destructuringPrivate", privateKeyLoc);
  11279. }
  11280. }
  11281. }
  11282. class ExpressionErrors {
  11283. constructor() {
  11284. this.shorthandAssignLoc = null;
  11285. this.doubleProtoLoc = null;
  11286. this.privateKeyLoc = null;
  11287. this.optionalParametersLoc = null;
  11288. this.voidPatternLoc = null;
  11289. }
  11290. }
  11291. class Node {
  11292. constructor(parser, pos, loc) {
  11293. this.type = "";
  11294. this.start = pos;
  11295. this.end = 0;
  11296. this.loc = new SourceLocation(loc);
  11297. if ((parser == null ? void 0 : parser.optionFlags) & 128) this.range = [pos, 0];
  11298. if (parser != null && parser.filename) this.loc.filename = parser.filename;
  11299. }
  11300. }
  11301. const NodePrototype = Node.prototype;
  11302. NodePrototype.__clone = function () {
  11303. const newNode = new Node(undefined, this.start, this.loc.start);
  11304. const keys = Object.keys(this);
  11305. for (let i = 0, length = keys.length; i < length; i++) {
  11306. const key = keys[i];
  11307. if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
  11308. newNode[key] = this[key];
  11309. }
  11310. }
  11311. return newNode;
  11312. };
  11313. class NodeUtils extends UtilParser {
  11314. startNode() {
  11315. const loc = this.state.startLoc;
  11316. return new Node(this, loc.index, loc);
  11317. }
  11318. startNodeAt(loc) {
  11319. return new Node(this, loc.index, loc);
  11320. }
  11321. startNodeAtNode(type) {
  11322. return this.startNodeAt(type.loc.start);
  11323. }
  11324. finishNode(node, type) {
  11325. return this.finishNodeAt(node, type, this.state.lastTokEndLoc);
  11326. }
  11327. finishNodeAt(node, type, endLoc) {
  11328. node.type = type;
  11329. node.end = endLoc.index;
  11330. node.loc.end = endLoc;
  11331. if (this.optionFlags & 128) node.range[1] = endLoc.index;
  11332. if (this.optionFlags & 4096) {
  11333. this.processComment(node);
  11334. }
  11335. return node;
  11336. }
  11337. resetStartLocation(node, startLoc) {
  11338. node.start = startLoc.index;
  11339. node.loc.start = startLoc;
  11340. if (this.optionFlags & 128) node.range[0] = startLoc.index;
  11341. }
  11342. resetEndLocation(node, endLoc = this.state.lastTokEndLoc) {
  11343. node.end = endLoc.index;
  11344. node.loc.end = endLoc;
  11345. if (this.optionFlags & 128) node.range[1] = endLoc.index;
  11346. }
  11347. resetStartLocationFromNode(node, locationNode) {
  11348. this.resetStartLocation(node, locationNode.loc.start);
  11349. }
  11350. castNodeTo(node, type) {
  11351. node.type = type;
  11352. return node;
  11353. }
  11354. cloneIdentifier(node) {
  11355. const {
  11356. type,
  11357. start,
  11358. end,
  11359. loc,
  11360. range,
  11361. name
  11362. } = node;
  11363. const cloned = Object.create(NodePrototype);
  11364. cloned.type = type;
  11365. cloned.start = start;
  11366. cloned.end = end;
  11367. cloned.loc = loc;
  11368. cloned.range = range;
  11369. cloned.name = name;
  11370. if (node.extra) cloned.extra = node.extra;
  11371. return cloned;
  11372. }
  11373. cloneStringLiteral(node) {
  11374. const {
  11375. type,
  11376. start,
  11377. end,
  11378. loc,
  11379. range,
  11380. extra
  11381. } = node;
  11382. const cloned = Object.create(NodePrototype);
  11383. cloned.type = type;
  11384. cloned.start = start;
  11385. cloned.end = end;
  11386. cloned.loc = loc;
  11387. cloned.range = range;
  11388. cloned.extra = extra;
  11389. cloned.value = node.value;
  11390. return cloned;
  11391. }
  11392. }
  11393. const unwrapParenthesizedExpression = node => {
  11394. return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
  11395. };
  11396. class LValParser extends NodeUtils {
  11397. toAssignable(node, isLHS = false) {
  11398. var _node$extra, _node$extra3;
  11399. let parenthesized = undefined;
  11400. if (node.type === "ParenthesizedExpression" || (_node$extra = node.extra) != null && _node$extra.parenthesized) {
  11401. parenthesized = unwrapParenthesizedExpression(node);
  11402. if (isLHS) {
  11403. if (parenthesized.type === "Identifier") {
  11404. this.expressionScope.recordArrowParameterBindingError(Errors.InvalidParenthesizedAssignment, node);
  11405. } else if (parenthesized.type !== "CallExpression" && parenthesized.type !== "MemberExpression" && !this.isOptionalMemberExpression(parenthesized)) {
  11406. this.raise(Errors.InvalidParenthesizedAssignment, node);
  11407. }
  11408. } else {
  11409. this.raise(Errors.InvalidParenthesizedAssignment, node);
  11410. }
  11411. }
  11412. switch (node.type) {
  11413. case "Identifier":
  11414. case "ObjectPattern":
  11415. case "ArrayPattern":
  11416. case "AssignmentPattern":
  11417. case "RestElement":
  11418. case "VoidPattern":
  11419. break;
  11420. case "ObjectExpression":
  11421. this.castNodeTo(node, "ObjectPattern");
  11422. for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
  11423. var _node$extra2;
  11424. const prop = node.properties[i];
  11425. const isLast = i === last;
  11426. this.toAssignableObjectExpressionProp(prop, isLast, isLHS);
  11427. if (isLast && prop.type === "RestElement" && (_node$extra2 = node.extra) != null && _node$extra2.trailingCommaLoc) {
  11428. this.raise(Errors.RestTrailingComma, node.extra.trailingCommaLoc);
  11429. }
  11430. }
  11431. break;
  11432. case "ObjectProperty":
  11433. {
  11434. const {
  11435. key,
  11436. value
  11437. } = node;
  11438. if (this.isPrivateName(key)) {
  11439. this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start);
  11440. }
  11441. this.toAssignable(value, isLHS);
  11442. break;
  11443. }
  11444. case "SpreadElement":
  11445. {
  11446. throw new Error("Internal @babel/parser error (this is a bug, please report it)." + " SpreadElement should be converted by .toAssignable's caller.");
  11447. }
  11448. case "ArrayExpression":
  11449. this.castNodeTo(node, "ArrayPattern");
  11450. this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingCommaLoc, isLHS);
  11451. break;
  11452. case "AssignmentExpression":
  11453. if (node.operator !== "=") {
  11454. this.raise(Errors.MissingEqInAssignment, node.left.loc.end);
  11455. }
  11456. this.castNodeTo(node, "AssignmentPattern");
  11457. delete node.operator;
  11458. if (node.left.type === "VoidPattern") {
  11459. this.raise(Errors.VoidPatternInitializer, node.left);
  11460. }
  11461. this.toAssignable(node.left, isLHS);
  11462. break;
  11463. case "ParenthesizedExpression":
  11464. this.toAssignable(parenthesized, isLHS);
  11465. break;
  11466. }
  11467. }
  11468. toAssignableObjectExpressionProp(prop, isLast, isLHS) {
  11469. if (prop.type === "ObjectMethod") {
  11470. this.raise(prop.kind === "get" || prop.kind === "set" ? Errors.PatternHasAccessor : Errors.PatternHasMethod, prop.key);
  11471. } else if (prop.type === "SpreadElement") {
  11472. this.castNodeTo(prop, "RestElement");
  11473. const arg = prop.argument;
  11474. this.checkToRestConversion(arg, false);
  11475. this.toAssignable(arg, isLHS);
  11476. if (!isLast) {
  11477. this.raise(Errors.RestTrailingComma, prop);
  11478. }
  11479. } else {
  11480. this.toAssignable(prop, isLHS);
  11481. }
  11482. }
  11483. toAssignableList(exprList, trailingCommaLoc, isLHS) {
  11484. const end = exprList.length - 1;
  11485. for (let i = 0; i <= end; i++) {
  11486. const elt = exprList[i];
  11487. if (!elt) continue;
  11488. this.toAssignableListItem(exprList, i, isLHS);
  11489. if (elt.type === "RestElement") {
  11490. if (i < end) {
  11491. this.raise(Errors.RestTrailingComma, elt);
  11492. } else if (trailingCommaLoc) {
  11493. this.raise(Errors.RestTrailingComma, trailingCommaLoc);
  11494. }
  11495. }
  11496. }
  11497. }
  11498. toAssignableListItem(exprList, index, isLHS) {
  11499. const node = exprList[index];
  11500. if (node.type === "SpreadElement") {
  11501. this.castNodeTo(node, "RestElement");
  11502. const arg = node.argument;
  11503. this.checkToRestConversion(arg, true);
  11504. this.toAssignable(arg, isLHS);
  11505. } else {
  11506. this.toAssignable(node, isLHS);
  11507. }
  11508. }
  11509. isAssignable(node, isBinding) {
  11510. switch (node.type) {
  11511. case "Identifier":
  11512. case "ObjectPattern":
  11513. case "ArrayPattern":
  11514. case "AssignmentPattern":
  11515. case "RestElement":
  11516. case "VoidPattern":
  11517. return true;
  11518. case "ObjectExpression":
  11519. {
  11520. const last = node.properties.length - 1;
  11521. return node.properties.every((prop, i) => {
  11522. return prop.type !== "ObjectMethod" && (i === last || prop.type !== "SpreadElement") && this.isAssignable(prop);
  11523. });
  11524. }
  11525. case "ObjectProperty":
  11526. return this.isAssignable(node.value);
  11527. case "SpreadElement":
  11528. return this.isAssignable(node.argument);
  11529. case "ArrayExpression":
  11530. return node.elements.every(element => element === null || this.isAssignable(element));
  11531. case "AssignmentExpression":
  11532. return node.operator === "=";
  11533. case "ParenthesizedExpression":
  11534. return this.isAssignable(node.expression);
  11535. case "MemberExpression":
  11536. case "OptionalMemberExpression":
  11537. return !isBinding;
  11538. default:
  11539. return false;
  11540. }
  11541. }
  11542. toReferencedList(exprList, isParenthesizedExpr) {
  11543. return exprList;
  11544. }
  11545. toReferencedListDeep(exprList, isParenthesizedExpr) {
  11546. this.toReferencedList(exprList, isParenthesizedExpr);
  11547. for (const expr of exprList) {
  11548. if ((expr == null ? void 0 : expr.type) === "ArrayExpression") {
  11549. this.toReferencedListDeep(expr.elements);
  11550. }
  11551. }
  11552. }
  11553. parseSpread(refExpressionErrors) {
  11554. const node = this.startNode();
  11555. this.next();
  11556. node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined);
  11557. return this.finishNode(node, "SpreadElement");
  11558. }
  11559. parseRestBinding() {
  11560. const node = this.startNode();
  11561. this.next();
  11562. const argument = this.parseBindingAtom();
  11563. if (argument.type === "VoidPattern") {
  11564. this.raise(Errors.UnexpectedVoidPattern, argument);
  11565. }
  11566. node.argument = argument;
  11567. return this.finishNode(node, "RestElement");
  11568. }
  11569. parseBindingAtom() {
  11570. switch (this.state.type) {
  11571. case 0:
  11572. {
  11573. const node = this.startNode();
  11574. this.next();
  11575. node.elements = this.parseBindingList(3, 93, 1);
  11576. return this.finishNode(node, "ArrayPattern");
  11577. }
  11578. case 5:
  11579. return this.parseObjectLike(8, true);
  11580. case 88:
  11581. return this.parseVoidPattern(null);
  11582. }
  11583. return this.parseIdentifier();
  11584. }
  11585. parseBindingList(close, closeCharCode, flags) {
  11586. const allowEmpty = flags & 1;
  11587. const elts = [];
  11588. let first = true;
  11589. while (!this.eat(close)) {
  11590. if (first) {
  11591. first = false;
  11592. } else {
  11593. this.expect(12);
  11594. }
  11595. if (allowEmpty && this.match(12)) {
  11596. elts.push(null);
  11597. } else if (this.eat(close)) {
  11598. break;
  11599. } else if (this.match(21)) {
  11600. let rest = this.parseRestBinding();
  11601. if (this.hasPlugin("flow") || flags & 2) {
  11602. rest = this.parseFunctionParamType(rest);
  11603. }
  11604. elts.push(rest);
  11605. if (!this.checkCommaAfterRest(closeCharCode)) {
  11606. this.expect(close);
  11607. break;
  11608. }
  11609. } else {
  11610. const decorators = [];
  11611. if (flags & 2) {
  11612. if (this.match(26) && this.hasPlugin("decorators")) {
  11613. this.raise(Errors.UnsupportedParameterDecorator, this.state.startLoc);
  11614. }
  11615. while (this.match(26)) {
  11616. decorators.push(this.parseDecorator());
  11617. }
  11618. }
  11619. elts.push(this.parseBindingElement(flags, decorators));
  11620. }
  11621. }
  11622. return elts;
  11623. }
  11624. parseBindingRestProperty(prop) {
  11625. this.next();
  11626. if (this.hasPlugin("discardBinding") && this.match(88)) {
  11627. prop.argument = this.parseVoidPattern(null);
  11628. this.raise(Errors.UnexpectedVoidPattern, prop.argument);
  11629. } else {
  11630. prop.argument = this.parseIdentifier();
  11631. }
  11632. this.checkCommaAfterRest(125);
  11633. return this.finishNode(prop, "RestElement");
  11634. }
  11635. parseBindingProperty() {
  11636. const {
  11637. type,
  11638. startLoc
  11639. } = this.state;
  11640. if (type === 21) {
  11641. return this.parseBindingRestProperty(this.startNode());
  11642. }
  11643. const prop = this.startNode();
  11644. if (type === 139) {
  11645. this.expectPlugin("destructuringPrivate", startLoc);
  11646. this.classScope.usePrivateName(this.state.value, startLoc);
  11647. prop.key = this.parsePrivateName();
  11648. } else {
  11649. this.parsePropertyName(prop);
  11650. }
  11651. prop.method = false;
  11652. return this.parseObjPropValue(prop, startLoc, false, false, true, false);
  11653. }
  11654. parseBindingElement(flags, decorators) {
  11655. const left = this.parseMaybeDefault();
  11656. if (this.hasPlugin("flow") || flags & 2) {
  11657. this.parseFunctionParamType(left);
  11658. }
  11659. if (decorators.length) {
  11660. left.decorators = decorators;
  11661. this.resetStartLocationFromNode(left, decorators[0]);
  11662. }
  11663. const elt = this.parseMaybeDefault(left.loc.start, left);
  11664. return elt;
  11665. }
  11666. parseFunctionParamType(param) {
  11667. return param;
  11668. }
  11669. parseMaybeDefault(startLoc, left) {
  11670. startLoc != null ? startLoc : startLoc = this.state.startLoc;
  11671. left = left != null ? left : this.parseBindingAtom();
  11672. if (!this.eat(29)) return left;
  11673. const node = this.startNodeAt(startLoc);
  11674. if (left.type === "VoidPattern") {
  11675. this.raise(Errors.VoidPatternInitializer, left);
  11676. }
  11677. node.left = left;
  11678. node.right = this.parseMaybeAssignAllowIn();
  11679. return this.finishNode(node, "AssignmentPattern");
  11680. }
  11681. isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding) {
  11682. switch (type) {
  11683. case "AssignmentPattern":
  11684. return "left";
  11685. case "RestElement":
  11686. return "argument";
  11687. case "ObjectProperty":
  11688. return "value";
  11689. case "ParenthesizedExpression":
  11690. return "expression";
  11691. case "ArrayPattern":
  11692. return "elements";
  11693. case "ObjectPattern":
  11694. return "properties";
  11695. case "VoidPattern":
  11696. return true;
  11697. case "CallExpression":
  11698. if (!disallowCallExpression && !this.state.strict && this.optionFlags & 8192) {
  11699. return true;
  11700. }
  11701. }
  11702. return false;
  11703. }
  11704. isOptionalMemberExpression(expression) {
  11705. return expression.type === "OptionalMemberExpression";
  11706. }
  11707. checkLVal(expression, ancestor, binding = 64, checkClashes = false, strictModeChanged = false, hasParenthesizedAncestor = false, disallowCallExpression = false) {
  11708. var _expression$extra;
  11709. const type = expression.type;
  11710. if (this.isObjectMethod(expression)) return;
  11711. const isOptionalMemberExpression = this.isOptionalMemberExpression(expression);
  11712. if (isOptionalMemberExpression || type === "MemberExpression") {
  11713. if (isOptionalMemberExpression) {
  11714. this.expectPlugin("optionalChainingAssign", expression.loc.start);
  11715. if (ancestor.type !== "AssignmentExpression") {
  11716. this.raise(Errors.InvalidLhsOptionalChaining, expression, {
  11717. ancestor
  11718. });
  11719. }
  11720. }
  11721. if (binding !== 64) {
  11722. this.raise(Errors.InvalidPropertyBindingPattern, expression);
  11723. }
  11724. return;
  11725. }
  11726. if (type === "Identifier") {
  11727. this.checkIdentifier(expression, binding, strictModeChanged);
  11728. const {
  11729. name
  11730. } = expression;
  11731. if (checkClashes) {
  11732. if (checkClashes.has(name)) {
  11733. this.raise(Errors.ParamDupe, expression);
  11734. } else {
  11735. checkClashes.add(name);
  11736. }
  11737. }
  11738. return;
  11739. } else if (type === "VoidPattern" && ancestor.type === "CatchClause") {
  11740. this.raise(Errors.VoidPatternCatchClauseParam, expression);
  11741. }
  11742. const unwrappedExpression = unwrapParenthesizedExpression(expression);
  11743. disallowCallExpression || (disallowCallExpression = unwrappedExpression.type === "CallExpression" && (unwrappedExpression.callee.type === "Import" || unwrappedExpression.callee.type === "Super"));
  11744. const validity = this.isValidLVal(type, disallowCallExpression, !(hasParenthesizedAncestor || (_expression$extra = expression.extra) != null && _expression$extra.parenthesized) && ancestor.type === "AssignmentExpression", binding);
  11745. if (validity === true) return;
  11746. if (validity === false) {
  11747. const ParseErrorClass = binding === 64 ? Errors.InvalidLhs : Errors.InvalidLhsBinding;
  11748. this.raise(ParseErrorClass, expression, {
  11749. ancestor
  11750. });
  11751. return;
  11752. }
  11753. let key, isParenthesizedExpression;
  11754. if (typeof validity === "string") {
  11755. key = validity;
  11756. isParenthesizedExpression = type === "ParenthesizedExpression";
  11757. } else {
  11758. [key, isParenthesizedExpression] = validity;
  11759. }
  11760. const nextAncestor = type === "ArrayPattern" || type === "ObjectPattern" ? {
  11761. type
  11762. } : ancestor;
  11763. const val = expression[key];
  11764. if (Array.isArray(val)) {
  11765. for (const child of val) {
  11766. if (child) {
  11767. this.checkLVal(child, nextAncestor, binding, checkClashes, strictModeChanged, isParenthesizedExpression, true);
  11768. }
  11769. }
  11770. } else if (val) {
  11771. this.checkLVal(val, nextAncestor, binding, checkClashes, strictModeChanged, isParenthesizedExpression, disallowCallExpression);
  11772. }
  11773. }
  11774. checkIdentifier(at, bindingType, strictModeChanged = false) {
  11775. if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(at.name, this.inModule) : isStrictBindOnlyReservedWord(at.name))) {
  11776. if (bindingType === 64) {
  11777. this.raise(Errors.StrictEvalArguments, at, {
  11778. referenceName: at.name
  11779. });
  11780. } else {
  11781. this.raise(Errors.StrictEvalArgumentsBinding, at, {
  11782. bindingName: at.name
  11783. });
  11784. }
  11785. }
  11786. if (bindingType & 8192 && at.name === "let") {
  11787. this.raise(Errors.LetInLexicalBinding, at);
  11788. }
  11789. if (!(bindingType & 64)) {
  11790. this.declareNameFromIdentifier(at, bindingType);
  11791. }
  11792. }
  11793. declareNameFromIdentifier(identifier, binding) {
  11794. this.scope.declareName(identifier.name, binding, identifier.loc.start);
  11795. }
  11796. checkToRestConversion(node, allowPattern) {
  11797. switch (node.type) {
  11798. case "ParenthesizedExpression":
  11799. this.checkToRestConversion(node.expression, allowPattern);
  11800. break;
  11801. case "Identifier":
  11802. case "MemberExpression":
  11803. break;
  11804. case "ArrayExpression":
  11805. case "ObjectExpression":
  11806. if (allowPattern) break;
  11807. default:
  11808. this.raise(Errors.InvalidRestAssignmentPattern, node);
  11809. }
  11810. }
  11811. checkCommaAfterRest(close) {
  11812. if (!this.match(12)) {
  11813. return false;
  11814. }
  11815. this.raise(this.lookaheadCharCode() === close ? Errors.RestTrailingComma : Errors.ElementAfterRest, this.state.startLoc);
  11816. return true;
  11817. }
  11818. }
  11819. const keywordAndTSRelationalOperator = /in(?:stanceof)?|as|satisfies/y;
  11820. function nonNull(x) {
  11821. if (x == null) {
  11822. throw new Error(`Unexpected ${x} value.`);
  11823. }
  11824. return x;
  11825. }
  11826. function assert(x) {
  11827. if (!x) {
  11828. throw new Error("Assert fail");
  11829. }
  11830. }
  11831. const TSErrors = ParseErrorEnum`typescript`({
  11832. AbstractMethodHasImplementation: ({
  11833. methodName
  11834. }) => `Method '${methodName}' cannot have an implementation because it is marked abstract.`,
  11835. AbstractPropertyHasInitializer: ({
  11836. propertyName
  11837. }) => `Property '${propertyName}' cannot have an initializer because it is marked abstract.`,
  11838. AccessorCannotBeOptional: "An 'accessor' property cannot be declared optional.",
  11839. AccessorCannotDeclareThisParameter: "'get' and 'set' accessors cannot declare 'this' parameters.",
  11840. AccessorCannotHaveTypeParameters: "An accessor cannot have type parameters.",
  11841. ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier.",
  11842. ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier.",
  11843. ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference: "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.",
  11844. ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.",
  11845. DeclareAccessor: ({
  11846. kind
  11847. }) => `'declare' is not allowed in ${kind}ters.`,
  11848. DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.",
  11849. DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.",
  11850. DuplicateAccessibilityModifier: ({
  11851. modifier
  11852. }) => `Accessibility modifier already seen: '${modifier}'.`,
  11853. DuplicateModifier: ({
  11854. modifier
  11855. }) => `Duplicate modifier: '${modifier}'.`,
  11856. EmptyHeritageClauseType: ({
  11857. token
  11858. }) => `'${token}' list cannot be empty.`,
  11859. EmptyTypeArguments: "Type argument list cannot be empty.",
  11860. EmptyTypeParameters: "Type parameter list cannot be empty.",
  11861. ExpectedAmbientAfterExportDeclare: "'export declare' must be followed by an ambient declaration.",
  11862. ImportAliasHasImportType: "An import alias can not use 'import type'.",
  11863. ImportReflectionHasImportType: "An `import module` declaration can not use `type` modifier",
  11864. IncompatibleModifiers: ({
  11865. modifiers
  11866. }) => `'${modifiers[0]}' modifier cannot be used with '${modifiers[1]}' modifier.`,
  11867. IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier.",
  11868. IndexSignatureHasAccessibility: ({
  11869. modifier
  11870. }) => `Index signatures cannot have an accessibility modifier ('${modifier}').`,
  11871. IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier.",
  11872. IndexSignatureHasOverride: "'override' modifier cannot appear on an index signature.",
  11873. IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier.",
  11874. InitializerNotAllowedInAmbientContext: "Initializers are not allowed in ambient contexts.",
  11875. InvalidHeritageClauseType: ({
  11876. token
  11877. }) => `'${token}' list can only include identifiers or qualified-names with optional type arguments.`,
  11878. InvalidModifierOnAwaitUsingDeclaration: modifier => `'${modifier}' modifier cannot appear on an await using declaration.`,
  11879. InvalidModifierOnTypeMember: ({
  11880. modifier
  11881. }) => `'${modifier}' modifier cannot appear on a type member.`,
  11882. InvalidModifierOnTypeParameter: ({
  11883. modifier
  11884. }) => `'${modifier}' modifier cannot appear on a type parameter.`,
  11885. InvalidModifierOnTypeParameterPositions: ({
  11886. modifier
  11887. }) => `'${modifier}' modifier can only appear on a type parameter of a class, interface or type alias.`,
  11888. InvalidModifierOnUsingDeclaration: modifier => `'${modifier}' modifier cannot appear on a using declaration.`,
  11889. InvalidModifiersOrder: ({
  11890. orderedModifiers
  11891. }) => `'${orderedModifiers[0]}' modifier must precede '${orderedModifiers[1]}' modifier.`,
  11892. InvalidPropertyAccessAfterInstantiationExpression: "Invalid property access after an instantiation expression. " + "You can either wrap the instantiation expression in parentheses, or delete the type arguments.",
  11893. InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.",
  11894. MissingInterfaceName: "'interface' declarations must be followed by an identifier.",
  11895. NonAbstractClassHasAbstractMethod: "Abstract methods can only appear within an abstract class.",
  11896. NonClassMethodPropertyHasAbstractModifier: "'abstract' modifier can only appear on a class, method, or property declaration.",
  11897. OptionalTypeBeforeRequired: "A required element cannot follow an optional element.",
  11898. OverrideNotInSubClass: "This member cannot have an 'override' modifier because its containing class does not extend another class.",
  11899. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  11900. PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.",
  11901. PrivateElementHasAccessibility: ({
  11902. modifier
  11903. }) => `Private elements cannot have an accessibility modifier ('${modifier}').`,
  11904. ReadonlyForMethodSignature: "'readonly' modifier can only appear on a property declaration or index signature.",
  11905. ReservedArrowTypeParam: "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `<T,>() => ...`.",
  11906. ReservedTypeAssertion: "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.",
  11907. SetAccessorCannotHaveOptionalParameter: "A 'set' accessor cannot have an optional parameter.",
  11908. SetAccessorCannotHaveRestParameter: "A 'set' accessor cannot have rest parameter.",
  11909. SetAccessorCannotHaveReturnType: "A 'set' accessor cannot have a return type annotation.",
  11910. SingleTypeParameterWithoutTrailingComma: ({
  11911. typeParameterName
  11912. }) => `Single type parameter ${typeParameterName} should have a trailing comma. Example usage: <${typeParameterName},>.`,
  11913. StaticBlockCannotHaveModifier: "Static class blocks cannot have any modifier.",
  11914. TupleOptionalAfterType: "A labeled tuple optional element must be declared using a question mark after the name and before the colon (`name?: type`), rather than after the type (`name: type?`).",
  11915. TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
  11916. TypeImportCannotSpecifyDefaultAndNamed: "A type-only import can specify a default import or named bindings, but not both.",
  11917. TypeModifierIsUsedInTypeExports: "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.",
  11918. TypeModifierIsUsedInTypeImports: "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.",
  11919. UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.",
  11920. UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.",
  11921. UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
  11922. UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.",
  11923. UnsupportedImportTypeArgument: "Argument in a type import must be a string literal.",
  11924. UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.",
  11925. UnsupportedSignatureParameterKind: ({
  11926. type
  11927. }) => `Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${type}.`,
  11928. UsingDeclarationInAmbientContext: kind => `'${kind}' declarations are not allowed in ambient contexts.`
  11929. });
  11930. function keywordTypeFromName(value) {
  11931. switch (value) {
  11932. case "any":
  11933. return "TSAnyKeyword";
  11934. case "boolean":
  11935. return "TSBooleanKeyword";
  11936. case "bigint":
  11937. return "TSBigIntKeyword";
  11938. case "never":
  11939. return "TSNeverKeyword";
  11940. case "number":
  11941. return "TSNumberKeyword";
  11942. case "object":
  11943. return "TSObjectKeyword";
  11944. case "string":
  11945. return "TSStringKeyword";
  11946. case "symbol":
  11947. return "TSSymbolKeyword";
  11948. case "undefined":
  11949. return "TSUndefinedKeyword";
  11950. case "unknown":
  11951. return "TSUnknownKeyword";
  11952. default:
  11953. return undefined;
  11954. }
  11955. }
  11956. function tsIsAccessModifier(modifier) {
  11957. return modifier === "private" || modifier === "public" || modifier === "protected";
  11958. }
  11959. function tsIsVarianceAnnotations(modifier) {
  11960. return modifier === "in" || modifier === "out";
  11961. }
  11962. var typescript = superClass => class TypeScriptParserMixin extends superClass {
  11963. constructor(...args) {
  11964. super(...args);
  11965. this.tsParseInOutModifiers = this.tsParseModifiers.bind(this, {
  11966. allowedModifiers: ["in", "out"],
  11967. disallowedModifiers: ["const", "public", "private", "protected", "readonly", "declare", "abstract", "override"],
  11968. errorTemplate: TSErrors.InvalidModifierOnTypeParameter
  11969. });
  11970. this.tsParseConstModifier = this.tsParseModifiers.bind(this, {
  11971. allowedModifiers: ["const"],
  11972. disallowedModifiers: ["in", "out"],
  11973. errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions
  11974. });
  11975. this.tsParseInOutConstModifiers = this.tsParseModifiers.bind(this, {
  11976. allowedModifiers: ["in", "out", "const"],
  11977. disallowedModifiers: ["public", "private", "protected", "readonly", "declare", "abstract", "override"],
  11978. errorTemplate: TSErrors.InvalidModifierOnTypeParameter
  11979. });
  11980. }
  11981. getScopeHandler() {
  11982. return TypeScriptScopeHandler;
  11983. }
  11984. tsIsIdentifier() {
  11985. return tokenIsIdentifier(this.state.type);
  11986. }
  11987. tsTokenCanFollowModifier() {
  11988. return this.match(0) || this.match(5) || this.match(55) || this.match(21) || this.match(139) || this.isLiteralPropertyName();
  11989. }
  11990. tsNextTokenOnSameLineAndCanFollowModifier() {
  11991. this.next();
  11992. if (this.hasPrecedingLineBreak()) {
  11993. return false;
  11994. }
  11995. return this.tsTokenCanFollowModifier();
  11996. }
  11997. tsNextTokenCanFollowModifier() {
  11998. if (this.match(106)) {
  11999. this.next();
  12000. return this.tsTokenCanFollowModifier();
  12001. }
  12002. return this.tsNextTokenOnSameLineAndCanFollowModifier();
  12003. }
  12004. tsParseModifier(allowedModifiers, stopOnStartOfClassStaticBlock, hasSeenStaticModifier) {
  12005. if (!tokenIsIdentifier(this.state.type) && this.state.type !== 58 && this.state.type !== 75) {
  12006. return undefined;
  12007. }
  12008. const modifier = this.state.value;
  12009. if (allowedModifiers.includes(modifier)) {
  12010. if (hasSeenStaticModifier && this.match(106)) {
  12011. return undefined;
  12012. }
  12013. if (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) {
  12014. return undefined;
  12015. }
  12016. if (this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
  12017. return modifier;
  12018. }
  12019. }
  12020. return undefined;
  12021. }
  12022. tsParseModifiers({
  12023. allowedModifiers,
  12024. disallowedModifiers,
  12025. stopOnStartOfClassStaticBlock,
  12026. errorTemplate = TSErrors.InvalidModifierOnTypeMember
  12027. }, modified) {
  12028. const enforceOrder = (loc, modifier, before, after) => {
  12029. if (modifier === before && modified[after]) {
  12030. this.raise(TSErrors.InvalidModifiersOrder, loc, {
  12031. orderedModifiers: [before, after]
  12032. });
  12033. }
  12034. };
  12035. const incompatible = (loc, modifier, mod1, mod2) => {
  12036. if (modified[mod1] && modifier === mod2 || modified[mod2] && modifier === mod1) {
  12037. this.raise(TSErrors.IncompatibleModifiers, loc, {
  12038. modifiers: [mod1, mod2]
  12039. });
  12040. }
  12041. };
  12042. for (;;) {
  12043. const {
  12044. startLoc
  12045. } = this.state;
  12046. const modifier = this.tsParseModifier(allowedModifiers.concat(disallowedModifiers != null ? disallowedModifiers : []), stopOnStartOfClassStaticBlock, modified.static);
  12047. if (!modifier) break;
  12048. if (tsIsAccessModifier(modifier)) {
  12049. if (modified.accessibility) {
  12050. this.raise(TSErrors.DuplicateAccessibilityModifier, startLoc, {
  12051. modifier
  12052. });
  12053. } else {
  12054. enforceOrder(startLoc, modifier, modifier, "override");
  12055. enforceOrder(startLoc, modifier, modifier, "static");
  12056. enforceOrder(startLoc, modifier, modifier, "readonly");
  12057. modified.accessibility = modifier;
  12058. }
  12059. } else if (tsIsVarianceAnnotations(modifier)) {
  12060. if (modified[modifier]) {
  12061. this.raise(TSErrors.DuplicateModifier, startLoc, {
  12062. modifier
  12063. });
  12064. }
  12065. modified[modifier] = true;
  12066. enforceOrder(startLoc, modifier, "in", "out");
  12067. } else {
  12068. if (hasOwnProperty.call(modified, modifier)) {
  12069. this.raise(TSErrors.DuplicateModifier, startLoc, {
  12070. modifier
  12071. });
  12072. } else {
  12073. enforceOrder(startLoc, modifier, "static", "readonly");
  12074. enforceOrder(startLoc, modifier, "static", "override");
  12075. enforceOrder(startLoc, modifier, "override", "readonly");
  12076. enforceOrder(startLoc, modifier, "abstract", "override");
  12077. incompatible(startLoc, modifier, "declare", "override");
  12078. incompatible(startLoc, modifier, "static", "abstract");
  12079. }
  12080. modified[modifier] = true;
  12081. }
  12082. if (disallowedModifiers != null && disallowedModifiers.includes(modifier)) {
  12083. this.raise(errorTemplate, startLoc, {
  12084. modifier
  12085. });
  12086. }
  12087. }
  12088. }
  12089. tsIsListTerminator(kind) {
  12090. switch (kind) {
  12091. case "EnumMembers":
  12092. case "TypeMembers":
  12093. return this.match(8);
  12094. case "HeritageClauseElement":
  12095. return this.match(5);
  12096. case "TupleElementTypes":
  12097. return this.match(3);
  12098. case "TypeParametersOrArguments":
  12099. return this.match(48);
  12100. }
  12101. }
  12102. tsParseList(kind, parseElement) {
  12103. const result = [];
  12104. while (!this.tsIsListTerminator(kind)) {
  12105. result.push(parseElement());
  12106. }
  12107. return result;
  12108. }
  12109. tsParseDelimitedList(kind, parseElement, refTrailingCommaPos) {
  12110. return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true, refTrailingCommaPos));
  12111. }
  12112. tsParseDelimitedListWorker(kind, parseElement, expectSuccess, refTrailingCommaPos) {
  12113. const result = [];
  12114. let trailingCommaPos = -1;
  12115. for (;;) {
  12116. if (this.tsIsListTerminator(kind)) {
  12117. break;
  12118. }
  12119. trailingCommaPos = -1;
  12120. const element = parseElement();
  12121. if (element == null) {
  12122. return undefined;
  12123. }
  12124. result.push(element);
  12125. if (this.eat(12)) {
  12126. trailingCommaPos = this.state.lastTokStartLoc.index;
  12127. continue;
  12128. }
  12129. if (this.tsIsListTerminator(kind)) {
  12130. break;
  12131. }
  12132. if (expectSuccess) {
  12133. this.expect(12);
  12134. }
  12135. return undefined;
  12136. }
  12137. if (refTrailingCommaPos) {
  12138. refTrailingCommaPos.value = trailingCommaPos;
  12139. }
  12140. return result;
  12141. }
  12142. tsParseBracketedList(kind, parseElement, bracket, skipFirstToken, refTrailingCommaPos) {
  12143. if (!skipFirstToken) {
  12144. if (bracket) {
  12145. this.expect(0);
  12146. } else {
  12147. this.expect(47);
  12148. }
  12149. }
  12150. const result = this.tsParseDelimitedList(kind, parseElement, refTrailingCommaPos);
  12151. if (bracket) {
  12152. this.expect(3);
  12153. } else {
  12154. this.expect(48);
  12155. }
  12156. return result;
  12157. }
  12158. tsParseImportType() {
  12159. const node = this.startNode();
  12160. this.expect(83);
  12161. this.expect(10);
  12162. if (!this.match(134)) {
  12163. this.raise(TSErrors.UnsupportedImportTypeArgument, this.state.startLoc);
  12164. node.argument = super.parseExprAtom();
  12165. } else {
  12166. node.argument = this.parseStringLiteral(this.state.value);
  12167. }
  12168. if (this.eat(12)) {
  12169. node.options = this.tsParseImportTypeOptions();
  12170. } else {
  12171. node.options = null;
  12172. }
  12173. this.expect(11);
  12174. if (this.eat(16)) {
  12175. node.qualifier = this.tsParseEntityName(1 | 2);
  12176. }
  12177. if (this.match(47)) {
  12178. node.typeParameters = this.tsParseTypeArguments();
  12179. }
  12180. return this.finishNode(node, "TSImportType");
  12181. }
  12182. tsParseImportTypeOptions() {
  12183. const node = this.startNode();
  12184. this.expect(5);
  12185. const withProperty = this.startNode();
  12186. if (this.isContextual(76)) {
  12187. withProperty.method = false;
  12188. withProperty.key = this.parseIdentifier(true);
  12189. withProperty.computed = false;
  12190. withProperty.shorthand = false;
  12191. } else {
  12192. this.unexpected(null, 76);
  12193. }
  12194. this.expect(14);
  12195. withProperty.value = this.tsParseImportTypeWithPropertyValue();
  12196. node.properties = [this.finishObjectProperty(withProperty)];
  12197. this.eat(12);
  12198. this.expect(8);
  12199. return this.finishNode(node, "ObjectExpression");
  12200. }
  12201. tsParseImportTypeWithPropertyValue() {
  12202. const node = this.startNode();
  12203. const properties = [];
  12204. this.expect(5);
  12205. while (!this.match(8)) {
  12206. const type = this.state.type;
  12207. if (tokenIsIdentifier(type) || type === 134) {
  12208. properties.push(super.parsePropertyDefinition(null));
  12209. } else {
  12210. this.unexpected();
  12211. }
  12212. this.eat(12);
  12213. }
  12214. node.properties = properties;
  12215. this.next();
  12216. return this.finishNode(node, "ObjectExpression");
  12217. }
  12218. tsParseEntityName(flags) {
  12219. let entity;
  12220. if (flags & 1 && this.match(78)) {
  12221. if (flags & 2) {
  12222. entity = this.parseIdentifier(true);
  12223. } else {
  12224. const node = this.startNode();
  12225. this.next();
  12226. entity = this.finishNode(node, "ThisExpression");
  12227. }
  12228. } else {
  12229. entity = this.parseIdentifier(!!(flags & 1));
  12230. }
  12231. while (this.eat(16)) {
  12232. const node = this.startNodeAtNode(entity);
  12233. node.left = entity;
  12234. node.right = this.parseIdentifier(!!(flags & 1));
  12235. entity = this.finishNode(node, "TSQualifiedName");
  12236. }
  12237. return entity;
  12238. }
  12239. tsParseTypeReference() {
  12240. const node = this.startNode();
  12241. node.typeName = this.tsParseEntityName(1);
  12242. if (!this.hasPrecedingLineBreak() && this.match(47)) {
  12243. node.typeParameters = this.tsParseTypeArguments();
  12244. }
  12245. return this.finishNode(node, "TSTypeReference");
  12246. }
  12247. tsParseThisTypePredicate(lhs) {
  12248. this.next();
  12249. const node = this.startNodeAtNode(lhs);
  12250. node.parameterName = lhs;
  12251. node.typeAnnotation = this.tsParseTypeAnnotation(false);
  12252. node.asserts = false;
  12253. return this.finishNode(node, "TSTypePredicate");
  12254. }
  12255. tsParseThisTypeNode() {
  12256. const node = this.startNode();
  12257. this.next();
  12258. return this.finishNode(node, "TSThisType");
  12259. }
  12260. tsParseTypeQuery() {
  12261. const node = this.startNode();
  12262. this.expect(87);
  12263. if (this.match(83)) {
  12264. node.exprName = this.tsParseImportType();
  12265. } else {
  12266. node.exprName = this.tsParseEntityName(1 | 2);
  12267. }
  12268. if (!this.hasPrecedingLineBreak() && this.match(47)) {
  12269. node.typeParameters = this.tsParseTypeArguments();
  12270. }
  12271. return this.finishNode(node, "TSTypeQuery");
  12272. }
  12273. tsParseTypeParameter(parseModifiers) {
  12274. const node = this.startNode();
  12275. parseModifiers(node);
  12276. node.name = this.tsParseTypeParameterName();
  12277. node.constraint = this.tsEatThenParseType(81);
  12278. node.default = this.tsEatThenParseType(29);
  12279. return this.finishNode(node, "TSTypeParameter");
  12280. }
  12281. tsTryParseTypeParameters(parseModifiers) {
  12282. if (this.match(47)) {
  12283. return this.tsParseTypeParameters(parseModifiers);
  12284. }
  12285. }
  12286. tsParseTypeParameters(parseModifiers) {
  12287. const node = this.startNode();
  12288. if (this.match(47) || this.match(143)) {
  12289. this.next();
  12290. } else {
  12291. this.unexpected();
  12292. }
  12293. const refTrailingCommaPos = {
  12294. value: -1
  12295. };
  12296. node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this, parseModifiers), false, true, refTrailingCommaPos);
  12297. if (node.params.length === 0) {
  12298. this.raise(TSErrors.EmptyTypeParameters, node);
  12299. }
  12300. if (refTrailingCommaPos.value !== -1) {
  12301. this.addExtra(node, "trailingComma", refTrailingCommaPos.value);
  12302. }
  12303. return this.finishNode(node, "TSTypeParameterDeclaration");
  12304. }
  12305. tsFillSignature(returnToken, signature) {
  12306. const returnTokenRequired = returnToken === 19;
  12307. const paramsKey = "parameters";
  12308. const returnTypeKey = "typeAnnotation";
  12309. signature.typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  12310. this.expect(10);
  12311. signature[paramsKey] = this.tsParseBindingListForSignature();
  12312. if (returnTokenRequired) {
  12313. signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  12314. } else if (this.match(returnToken)) {
  12315. signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  12316. }
  12317. }
  12318. tsParseBindingListForSignature() {
  12319. const list = super.parseBindingList(11, 41, 2);
  12320. for (const pattern of list) {
  12321. const {
  12322. type
  12323. } = pattern;
  12324. if (type === "AssignmentPattern" || type === "TSParameterProperty") {
  12325. this.raise(TSErrors.UnsupportedSignatureParameterKind, pattern, {
  12326. type
  12327. });
  12328. }
  12329. }
  12330. return list;
  12331. }
  12332. tsParseTypeMemberSemicolon() {
  12333. if (!this.eat(12) && !this.isLineTerminator()) {
  12334. this.expect(13);
  12335. }
  12336. }
  12337. tsParseSignatureMember(kind, node) {
  12338. this.tsFillSignature(14, node);
  12339. this.tsParseTypeMemberSemicolon();
  12340. return this.finishNode(node, kind);
  12341. }
  12342. tsIsUnambiguouslyIndexSignature() {
  12343. this.next();
  12344. if (tokenIsIdentifier(this.state.type)) {
  12345. this.next();
  12346. return this.match(14);
  12347. }
  12348. return false;
  12349. }
  12350. tsTryParseIndexSignature(node) {
  12351. if (!(this.match(0) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
  12352. return;
  12353. }
  12354. this.expect(0);
  12355. const id = this.parseIdentifier();
  12356. id.typeAnnotation = this.tsParseTypeAnnotation();
  12357. this.resetEndLocation(id);
  12358. this.expect(3);
  12359. node.parameters = [id];
  12360. const type = this.tsTryParseTypeAnnotation();
  12361. if (type) node.typeAnnotation = type;
  12362. this.tsParseTypeMemberSemicolon();
  12363. return this.finishNode(node, "TSIndexSignature");
  12364. }
  12365. tsParsePropertyOrMethodSignature(node, readonly) {
  12366. if (this.eat(17)) node.optional = true;
  12367. if (this.match(10) || this.match(47)) {
  12368. if (readonly) {
  12369. this.raise(TSErrors.ReadonlyForMethodSignature, node);
  12370. }
  12371. const method = node;
  12372. if (method.kind && this.match(47)) {
  12373. this.raise(TSErrors.AccessorCannotHaveTypeParameters, this.state.curPosition());
  12374. }
  12375. this.tsFillSignature(14, method);
  12376. this.tsParseTypeMemberSemicolon();
  12377. const paramsKey = "parameters";
  12378. const returnTypeKey = "typeAnnotation";
  12379. if (method.kind === "get") {
  12380. if (method[paramsKey].length > 0) {
  12381. this.raise(Errors.BadGetterArity, this.state.curPosition());
  12382. if (this.isThisParam(method[paramsKey][0])) {
  12383. this.raise(TSErrors.AccessorCannotDeclareThisParameter, this.state.curPosition());
  12384. }
  12385. }
  12386. } else if (method.kind === "set") {
  12387. if (method[paramsKey].length !== 1) {
  12388. this.raise(Errors.BadSetterArity, this.state.curPosition());
  12389. } else {
  12390. const firstParameter = method[paramsKey][0];
  12391. if (this.isThisParam(firstParameter)) {
  12392. this.raise(TSErrors.AccessorCannotDeclareThisParameter, this.state.curPosition());
  12393. }
  12394. if (firstParameter.type === "Identifier" && firstParameter.optional) {
  12395. this.raise(TSErrors.SetAccessorCannotHaveOptionalParameter, this.state.curPosition());
  12396. }
  12397. if (firstParameter.type === "RestElement") {
  12398. this.raise(TSErrors.SetAccessorCannotHaveRestParameter, this.state.curPosition());
  12399. }
  12400. }
  12401. if (method[returnTypeKey]) {
  12402. this.raise(TSErrors.SetAccessorCannotHaveReturnType, method[returnTypeKey]);
  12403. }
  12404. } else {
  12405. method.kind = "method";
  12406. }
  12407. return this.finishNode(method, "TSMethodSignature");
  12408. } else {
  12409. const property = node;
  12410. if (readonly) property.readonly = true;
  12411. const type = this.tsTryParseTypeAnnotation();
  12412. if (type) property.typeAnnotation = type;
  12413. this.tsParseTypeMemberSemicolon();
  12414. return this.finishNode(property, "TSPropertySignature");
  12415. }
  12416. }
  12417. tsParseTypeMember() {
  12418. const node = this.startNode();
  12419. if (this.match(10) || this.match(47)) {
  12420. return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
  12421. }
  12422. if (this.match(77)) {
  12423. const id = this.startNode();
  12424. this.next();
  12425. if (this.match(10) || this.match(47)) {
  12426. return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
  12427. } else {
  12428. node.key = this.createIdentifier(id, "new");
  12429. return this.tsParsePropertyOrMethodSignature(node, false);
  12430. }
  12431. }
  12432. this.tsParseModifiers({
  12433. allowedModifiers: ["readonly"],
  12434. disallowedModifiers: ["declare", "abstract", "private", "protected", "public", "static", "override"]
  12435. }, node);
  12436. const idx = this.tsTryParseIndexSignature(node);
  12437. if (idx) {
  12438. return idx;
  12439. }
  12440. super.parsePropertyName(node);
  12441. if (!node.computed && node.key.type === "Identifier" && (node.key.name === "get" || node.key.name === "set") && this.tsTokenCanFollowModifier()) {
  12442. node.kind = node.key.name;
  12443. super.parsePropertyName(node);
  12444. if (!this.match(10) && !this.match(47)) {
  12445. this.unexpected(null, 10);
  12446. }
  12447. }
  12448. return this.tsParsePropertyOrMethodSignature(node, !!node.readonly);
  12449. }
  12450. tsParseTypeLiteral() {
  12451. const node = this.startNode();
  12452. node.members = this.tsParseObjectTypeMembers();
  12453. return this.finishNode(node, "TSTypeLiteral");
  12454. }
  12455. tsParseObjectTypeMembers() {
  12456. this.expect(5);
  12457. const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
  12458. this.expect(8);
  12459. return members;
  12460. }
  12461. tsIsStartOfMappedType() {
  12462. this.next();
  12463. if (this.eat(53)) {
  12464. return this.isContextual(122);
  12465. }
  12466. if (this.isContextual(122)) {
  12467. this.next();
  12468. }
  12469. if (!this.match(0)) {
  12470. return false;
  12471. }
  12472. this.next();
  12473. if (!this.tsIsIdentifier()) {
  12474. return false;
  12475. }
  12476. this.next();
  12477. return this.match(58);
  12478. }
  12479. tsParseMappedType() {
  12480. const node = this.startNode();
  12481. this.expect(5);
  12482. if (this.match(53)) {
  12483. node.readonly = this.state.value;
  12484. this.next();
  12485. this.expectContextual(122);
  12486. } else if (this.eatContextual(122)) {
  12487. node.readonly = true;
  12488. }
  12489. this.expect(0);
  12490. const typeParameter = this.startNode();
  12491. typeParameter.name = this.tsParseTypeParameterName();
  12492. typeParameter.constraint = this.tsExpectThenParseType(58);
  12493. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  12494. node.nameType = this.eatContextual(93) ? this.tsParseType() : null;
  12495. this.expect(3);
  12496. if (this.match(53)) {
  12497. node.optional = this.state.value;
  12498. this.next();
  12499. this.expect(17);
  12500. } else if (this.eat(17)) {
  12501. node.optional = true;
  12502. }
  12503. node.typeAnnotation = this.tsTryParseType();
  12504. this.semicolon();
  12505. this.expect(8);
  12506. return this.finishNode(node, "TSMappedType");
  12507. }
  12508. tsParseTupleType() {
  12509. const node = this.startNode();
  12510. node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
  12511. let seenOptionalElement = false;
  12512. node.elementTypes.forEach(elementNode => {
  12513. const {
  12514. type
  12515. } = elementNode;
  12516. if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) {
  12517. this.raise(TSErrors.OptionalTypeBeforeRequired, elementNode);
  12518. }
  12519. seenOptionalElement || (seenOptionalElement = type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType");
  12520. });
  12521. return this.finishNode(node, "TSTupleType");
  12522. }
  12523. tsParseTupleElementType() {
  12524. const restStartLoc = this.state.startLoc;
  12525. const rest = this.eat(21);
  12526. const {
  12527. startLoc
  12528. } = this.state;
  12529. let labeled;
  12530. let label;
  12531. let optional;
  12532. let type;
  12533. const isWord = tokenIsKeywordOrIdentifier(this.state.type);
  12534. const chAfterWord = isWord ? this.lookaheadCharCode() : null;
  12535. if (chAfterWord === 58) {
  12536. labeled = true;
  12537. optional = false;
  12538. label = this.parseIdentifier(true);
  12539. this.expect(14);
  12540. type = this.tsParseType();
  12541. } else if (chAfterWord === 63) {
  12542. optional = true;
  12543. const wordName = this.state.value;
  12544. const typeOrLabel = this.tsParseNonArrayType();
  12545. if (this.lookaheadCharCode() === 58) {
  12546. labeled = true;
  12547. label = this.createIdentifier(this.startNodeAt(startLoc), wordName);
  12548. this.expect(17);
  12549. this.expect(14);
  12550. type = this.tsParseType();
  12551. } else {
  12552. labeled = false;
  12553. type = typeOrLabel;
  12554. this.expect(17);
  12555. }
  12556. } else {
  12557. type = this.tsParseType();
  12558. optional = this.eat(17);
  12559. labeled = this.eat(14);
  12560. }
  12561. if (labeled) {
  12562. let labeledNode;
  12563. if (label) {
  12564. labeledNode = this.startNodeAt(startLoc);
  12565. labeledNode.optional = optional;
  12566. labeledNode.label = label;
  12567. labeledNode.elementType = type;
  12568. if (this.eat(17)) {
  12569. labeledNode.optional = true;
  12570. this.raise(TSErrors.TupleOptionalAfterType, this.state.lastTokStartLoc);
  12571. }
  12572. } else {
  12573. labeledNode = this.startNodeAt(startLoc);
  12574. labeledNode.optional = optional;
  12575. this.raise(TSErrors.InvalidTupleMemberLabel, type);
  12576. labeledNode.label = type;
  12577. labeledNode.elementType = this.tsParseType();
  12578. }
  12579. type = this.finishNode(labeledNode, "TSNamedTupleMember");
  12580. } else if (optional) {
  12581. const optionalTypeNode = this.startNodeAt(startLoc);
  12582. optionalTypeNode.typeAnnotation = type;
  12583. type = this.finishNode(optionalTypeNode, "TSOptionalType");
  12584. }
  12585. if (rest) {
  12586. const restNode = this.startNodeAt(restStartLoc);
  12587. restNode.typeAnnotation = type;
  12588. type = this.finishNode(restNode, "TSRestType");
  12589. }
  12590. return type;
  12591. }
  12592. tsParseParenthesizedType() {
  12593. const node = this.startNode();
  12594. this.expect(10);
  12595. node.typeAnnotation = this.tsParseType();
  12596. this.expect(11);
  12597. return this.finishNode(node, "TSParenthesizedType");
  12598. }
  12599. tsParseFunctionOrConstructorType(type, abstract) {
  12600. const node = this.startNode();
  12601. if (type === "TSConstructorType") {
  12602. node.abstract = !!abstract;
  12603. if (abstract) this.next();
  12604. this.next();
  12605. }
  12606. this.tsInAllowConditionalTypesContext(() => this.tsFillSignature(19, node));
  12607. return this.finishNode(node, type);
  12608. }
  12609. tsParseLiteralTypeNode() {
  12610. const node = this.startNode();
  12611. switch (this.state.type) {
  12612. case 135:
  12613. case 136:
  12614. case 134:
  12615. case 85:
  12616. case 86:
  12617. node.literal = super.parseExprAtom();
  12618. break;
  12619. default:
  12620. this.unexpected();
  12621. }
  12622. return this.finishNode(node, "TSLiteralType");
  12623. }
  12624. tsParseTemplateLiteralType() {
  12625. const node = this.startNode();
  12626. node.literal = super.parseTemplate(false);
  12627. return this.finishNode(node, "TSLiteralType");
  12628. }
  12629. parseTemplateSubstitution() {
  12630. if (this.state.inType) return this.tsParseType();
  12631. return super.parseTemplateSubstitution();
  12632. }
  12633. tsParseThisTypeOrThisTypePredicate() {
  12634. const thisKeyword = this.tsParseThisTypeNode();
  12635. if (this.isContextual(116) && !this.hasPrecedingLineBreak()) {
  12636. return this.tsParseThisTypePredicate(thisKeyword);
  12637. } else {
  12638. return thisKeyword;
  12639. }
  12640. }
  12641. tsParseNonArrayType() {
  12642. switch (this.state.type) {
  12643. case 134:
  12644. case 135:
  12645. case 136:
  12646. case 85:
  12647. case 86:
  12648. return this.tsParseLiteralTypeNode();
  12649. case 53:
  12650. if (this.state.value === "-") {
  12651. const node = this.startNode();
  12652. const nextToken = this.lookahead();
  12653. if (nextToken.type !== 135 && nextToken.type !== 136) {
  12654. this.unexpected();
  12655. }
  12656. node.literal = this.parseMaybeUnary();
  12657. return this.finishNode(node, "TSLiteralType");
  12658. }
  12659. break;
  12660. case 78:
  12661. return this.tsParseThisTypeOrThisTypePredicate();
  12662. case 87:
  12663. return this.tsParseTypeQuery();
  12664. case 83:
  12665. return this.tsParseImportType();
  12666. case 5:
  12667. return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
  12668. case 0:
  12669. return this.tsParseTupleType();
  12670. case 10:
  12671. return this.tsParseParenthesizedType();
  12672. case 25:
  12673. case 24:
  12674. return this.tsParseTemplateLiteralType();
  12675. default:
  12676. {
  12677. const {
  12678. type
  12679. } = this.state;
  12680. if (tokenIsIdentifier(type) || type === 88 || type === 84) {
  12681. const nodeType = type === 88 ? "TSVoidKeyword" : type === 84 ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
  12682. if (nodeType !== undefined && this.lookaheadCharCode() !== 46) {
  12683. const node = this.startNode();
  12684. this.next();
  12685. return this.finishNode(node, nodeType);
  12686. }
  12687. return this.tsParseTypeReference();
  12688. }
  12689. }
  12690. }
  12691. throw this.unexpected();
  12692. }
  12693. tsParseArrayTypeOrHigher() {
  12694. const {
  12695. startLoc
  12696. } = this.state;
  12697. let type = this.tsParseNonArrayType();
  12698. while (!this.hasPrecedingLineBreak() && this.eat(0)) {
  12699. if (this.match(3)) {
  12700. const node = this.startNodeAt(startLoc);
  12701. node.elementType = type;
  12702. this.expect(3);
  12703. type = this.finishNode(node, "TSArrayType");
  12704. } else {
  12705. const node = this.startNodeAt(startLoc);
  12706. node.objectType = type;
  12707. node.indexType = this.tsParseType();
  12708. this.expect(3);
  12709. type = this.finishNode(node, "TSIndexedAccessType");
  12710. }
  12711. }
  12712. return type;
  12713. }
  12714. tsParseTypeOperator() {
  12715. const node = this.startNode();
  12716. const operator = this.state.value;
  12717. this.next();
  12718. node.operator = operator;
  12719. node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
  12720. if (operator === "readonly") {
  12721. this.tsCheckTypeAnnotationForReadOnly(node);
  12722. }
  12723. return this.finishNode(node, "TSTypeOperator");
  12724. }
  12725. tsCheckTypeAnnotationForReadOnly(node) {
  12726. switch (node.typeAnnotation.type) {
  12727. case "TSTupleType":
  12728. case "TSArrayType":
  12729. return;
  12730. default:
  12731. this.raise(TSErrors.UnexpectedReadonly, node);
  12732. }
  12733. }
  12734. tsParseInferType() {
  12735. const node = this.startNode();
  12736. this.expectContextual(115);
  12737. const typeParameter = this.startNode();
  12738. typeParameter.name = this.tsParseTypeParameterName();
  12739. typeParameter.constraint = this.tsTryParse(() => this.tsParseConstraintForInferType());
  12740. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  12741. return this.finishNode(node, "TSInferType");
  12742. }
  12743. tsParseConstraintForInferType() {
  12744. if (this.eat(81)) {
  12745. const constraint = this.tsInDisallowConditionalTypesContext(() => this.tsParseType());
  12746. if (this.state.inDisallowConditionalTypesContext || !this.match(17)) {
  12747. return constraint;
  12748. }
  12749. }
  12750. }
  12751. tsParseTypeOperatorOrHigher() {
  12752. const isTypeOperator = tokenIsTSTypeOperator(this.state.type) && !this.state.containsEsc;
  12753. return isTypeOperator ? this.tsParseTypeOperator() : this.isContextual(115) ? this.tsParseInferType() : this.tsInAllowConditionalTypesContext(() => this.tsParseArrayTypeOrHigher());
  12754. }
  12755. tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  12756. const node = this.startNode();
  12757. const hasLeadingOperator = this.eat(operator);
  12758. const types = [];
  12759. do {
  12760. types.push(parseConstituentType());
  12761. } while (this.eat(operator));
  12762. if (types.length === 1 && !hasLeadingOperator) {
  12763. return types[0];
  12764. }
  12765. node.types = types;
  12766. return this.finishNode(node, kind);
  12767. }
  12768. tsParseIntersectionTypeOrHigher() {
  12769. return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), 45);
  12770. }
  12771. tsParseUnionTypeOrHigher() {
  12772. return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), 43);
  12773. }
  12774. tsIsStartOfFunctionType() {
  12775. if (this.match(47)) {
  12776. return true;
  12777. }
  12778. return this.match(10) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  12779. }
  12780. tsSkipParameterStart() {
  12781. if (tokenIsIdentifier(this.state.type) || this.match(78)) {
  12782. this.next();
  12783. return true;
  12784. }
  12785. if (this.match(5)) {
  12786. const {
  12787. errors
  12788. } = this.state;
  12789. const previousErrorCount = errors.length;
  12790. try {
  12791. this.parseObjectLike(8, true);
  12792. return errors.length === previousErrorCount;
  12793. } catch (_unused) {
  12794. return false;
  12795. }
  12796. }
  12797. if (this.match(0)) {
  12798. this.next();
  12799. const {
  12800. errors
  12801. } = this.state;
  12802. const previousErrorCount = errors.length;
  12803. try {
  12804. super.parseBindingList(3, 93, 1);
  12805. return errors.length === previousErrorCount;
  12806. } catch (_unused2) {
  12807. return false;
  12808. }
  12809. }
  12810. return false;
  12811. }
  12812. tsIsUnambiguouslyStartOfFunctionType() {
  12813. this.next();
  12814. if (this.match(11) || this.match(21)) {
  12815. return true;
  12816. }
  12817. if (this.tsSkipParameterStart()) {
  12818. if (this.match(14) || this.match(12) || this.match(17) || this.match(29)) {
  12819. return true;
  12820. }
  12821. if (this.match(11)) {
  12822. this.next();
  12823. if (this.match(19)) {
  12824. return true;
  12825. }
  12826. }
  12827. }
  12828. return false;
  12829. }
  12830. tsParseTypeOrTypePredicateAnnotation(returnToken) {
  12831. return this.tsInType(() => {
  12832. const t = this.startNode();
  12833. this.expect(returnToken);
  12834. const node = this.startNode();
  12835. const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
  12836. if (asserts && this.match(78)) {
  12837. let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
  12838. if (thisTypePredicate.type === "TSThisType") {
  12839. node.parameterName = thisTypePredicate;
  12840. node.asserts = true;
  12841. node.typeAnnotation = null;
  12842. thisTypePredicate = this.finishNode(node, "TSTypePredicate");
  12843. } else {
  12844. this.resetStartLocationFromNode(thisTypePredicate, node);
  12845. thisTypePredicate.asserts = true;
  12846. }
  12847. t.typeAnnotation = thisTypePredicate;
  12848. return this.finishNode(t, "TSTypeAnnotation");
  12849. }
  12850. const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
  12851. if (!typePredicateVariable) {
  12852. if (!asserts) {
  12853. return this.tsParseTypeAnnotation(false, t);
  12854. }
  12855. node.parameterName = this.parseIdentifier();
  12856. node.asserts = asserts;
  12857. node.typeAnnotation = null;
  12858. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  12859. return this.finishNode(t, "TSTypeAnnotation");
  12860. }
  12861. const type = this.tsParseTypeAnnotation(false);
  12862. node.parameterName = typePredicateVariable;
  12863. node.typeAnnotation = type;
  12864. node.asserts = asserts;
  12865. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  12866. return this.finishNode(t, "TSTypeAnnotation");
  12867. });
  12868. }
  12869. tsTryParseTypeOrTypePredicateAnnotation() {
  12870. if (this.match(14)) {
  12871. return this.tsParseTypeOrTypePredicateAnnotation(14);
  12872. }
  12873. }
  12874. tsTryParseTypeAnnotation() {
  12875. if (this.match(14)) {
  12876. return this.tsParseTypeAnnotation();
  12877. }
  12878. }
  12879. tsTryParseType() {
  12880. return this.tsEatThenParseType(14);
  12881. }
  12882. tsParseTypePredicatePrefix() {
  12883. const id = this.parseIdentifier();
  12884. if (this.isContextual(116) && !this.hasPrecedingLineBreak()) {
  12885. this.next();
  12886. return id;
  12887. }
  12888. }
  12889. tsParseTypePredicateAsserts() {
  12890. if (this.state.type !== 109) {
  12891. return false;
  12892. }
  12893. const containsEsc = this.state.containsEsc;
  12894. this.next();
  12895. if (!tokenIsIdentifier(this.state.type) && !this.match(78)) {
  12896. return false;
  12897. }
  12898. if (containsEsc) {
  12899. this.raise(Errors.InvalidEscapedReservedWord, this.state.lastTokStartLoc, {
  12900. reservedWord: "asserts"
  12901. });
  12902. }
  12903. return true;
  12904. }
  12905. tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
  12906. this.tsInType(() => {
  12907. if (eatColon) this.expect(14);
  12908. t.typeAnnotation = this.tsParseType();
  12909. });
  12910. return this.finishNode(t, "TSTypeAnnotation");
  12911. }
  12912. tsParseType() {
  12913. assert(this.state.inType);
  12914. const type = this.tsParseNonConditionalType();
  12915. if (this.state.inDisallowConditionalTypesContext || this.hasPrecedingLineBreak() || !this.eat(81)) {
  12916. return type;
  12917. }
  12918. const node = this.startNodeAtNode(type);
  12919. node.checkType = type;
  12920. node.extendsType = this.tsInDisallowConditionalTypesContext(() => this.tsParseNonConditionalType());
  12921. this.expect(17);
  12922. node.trueType = this.tsInAllowConditionalTypesContext(() => this.tsParseType());
  12923. this.expect(14);
  12924. node.falseType = this.tsInAllowConditionalTypesContext(() => this.tsParseType());
  12925. return this.finishNode(node, "TSConditionalType");
  12926. }
  12927. isAbstractConstructorSignature() {
  12928. return this.isContextual(124) && this.isLookaheadContextual("new");
  12929. }
  12930. tsParseNonConditionalType() {
  12931. if (this.tsIsStartOfFunctionType()) {
  12932. return this.tsParseFunctionOrConstructorType("TSFunctionType");
  12933. }
  12934. if (this.match(77)) {
  12935. return this.tsParseFunctionOrConstructorType("TSConstructorType");
  12936. } else if (this.isAbstractConstructorSignature()) {
  12937. return this.tsParseFunctionOrConstructorType("TSConstructorType", true);
  12938. }
  12939. return this.tsParseUnionTypeOrHigher();
  12940. }
  12941. tsParseTypeAssertion() {
  12942. if (this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) {
  12943. this.raise(TSErrors.ReservedTypeAssertion, this.state.startLoc);
  12944. }
  12945. const node = this.startNode();
  12946. node.typeAnnotation = this.tsInType(() => {
  12947. this.next();
  12948. return this.match(75) ? this.tsParseTypeReference() : this.tsParseType();
  12949. });
  12950. this.expect(48);
  12951. node.expression = this.parseMaybeUnary();
  12952. return this.finishNode(node, "TSTypeAssertion");
  12953. }
  12954. tsParseHeritageClause(token) {
  12955. const originalStartLoc = this.state.startLoc;
  12956. const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", () => {
  12957. const node = this.startNode();
  12958. node.expression = this.tsParseEntityName(1 | 2);
  12959. if (this.match(47)) {
  12960. node.typeParameters = this.tsParseTypeArguments();
  12961. }
  12962. return this.finishNode(node, "TSExpressionWithTypeArguments");
  12963. });
  12964. if (!delimitedList.length) {
  12965. this.raise(TSErrors.EmptyHeritageClauseType, originalStartLoc, {
  12966. token
  12967. });
  12968. }
  12969. return delimitedList;
  12970. }
  12971. tsParseInterfaceDeclaration(node, properties = {}) {
  12972. if (this.hasFollowingLineBreak()) return null;
  12973. this.expectContextual(129);
  12974. if (properties.declare) node.declare = true;
  12975. if (tokenIsIdentifier(this.state.type)) {
  12976. node.id = this.parseIdentifier();
  12977. this.checkIdentifier(node.id, 130);
  12978. } else {
  12979. node.id = null;
  12980. this.raise(TSErrors.MissingInterfaceName, this.state.startLoc);
  12981. }
  12982. node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);
  12983. if (this.eat(81)) {
  12984. node.extends = this.tsParseHeritageClause("extends");
  12985. }
  12986. const body = this.startNode();
  12987. body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
  12988. node.body = this.finishNode(body, "TSInterfaceBody");
  12989. return this.finishNode(node, "TSInterfaceDeclaration");
  12990. }
  12991. tsParseTypeAliasDeclaration(node) {
  12992. node.id = this.parseIdentifier();
  12993. this.checkIdentifier(node.id, 2);
  12994. node.typeAnnotation = this.tsInType(() => {
  12995. node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutModifiers);
  12996. this.expect(29);
  12997. if (this.isContextual(114) && this.lookaheadCharCode() !== 46) {
  12998. const node = this.startNode();
  12999. this.next();
  13000. return this.finishNode(node, "TSIntrinsicKeyword");
  13001. }
  13002. return this.tsParseType();
  13003. });
  13004. this.semicolon();
  13005. return this.finishNode(node, "TSTypeAliasDeclaration");
  13006. }
  13007. tsInTopLevelContext(cb) {
  13008. if (this.curContext() !== types.brace) {
  13009. const oldContext = this.state.context;
  13010. this.state.context = [oldContext[0]];
  13011. try {
  13012. return cb();
  13013. } finally {
  13014. this.state.context = oldContext;
  13015. }
  13016. } else {
  13017. return cb();
  13018. }
  13019. }
  13020. tsInType(cb) {
  13021. const oldInType = this.state.inType;
  13022. this.state.inType = true;
  13023. try {
  13024. return cb();
  13025. } finally {
  13026. this.state.inType = oldInType;
  13027. }
  13028. }
  13029. tsInDisallowConditionalTypesContext(cb) {
  13030. const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext;
  13031. this.state.inDisallowConditionalTypesContext = true;
  13032. try {
  13033. return cb();
  13034. } finally {
  13035. this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext;
  13036. }
  13037. }
  13038. tsInAllowConditionalTypesContext(cb) {
  13039. const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext;
  13040. this.state.inDisallowConditionalTypesContext = false;
  13041. try {
  13042. return cb();
  13043. } finally {
  13044. this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext;
  13045. }
  13046. }
  13047. tsEatThenParseType(token) {
  13048. if (this.match(token)) {
  13049. return this.tsNextThenParseType();
  13050. }
  13051. }
  13052. tsExpectThenParseType(token) {
  13053. return this.tsInType(() => {
  13054. this.expect(token);
  13055. return this.tsParseType();
  13056. });
  13057. }
  13058. tsNextThenParseType() {
  13059. return this.tsInType(() => {
  13060. this.next();
  13061. return this.tsParseType();
  13062. });
  13063. }
  13064. tsParseEnumMember() {
  13065. const node = this.startNode();
  13066. node.id = this.match(134) ? super.parseStringLiteral(this.state.value) : this.parseIdentifier(true);
  13067. if (this.eat(29)) {
  13068. node.initializer = super.parseMaybeAssignAllowIn();
  13069. }
  13070. return this.finishNode(node, "TSEnumMember");
  13071. }
  13072. tsParseEnumDeclaration(node, properties = {}) {
  13073. if (properties.const) node.const = true;
  13074. if (properties.declare) node.declare = true;
  13075. this.expectContextual(126);
  13076. node.id = this.parseIdentifier();
  13077. this.checkIdentifier(node.id, node.const ? 8971 : 8459);
  13078. this.expect(5);
  13079. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  13080. this.expect(8);
  13081. return this.finishNode(node, "TSEnumDeclaration");
  13082. }
  13083. tsParseEnumBody() {
  13084. const node = this.startNode();
  13085. this.expect(5);
  13086. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  13087. this.expect(8);
  13088. return this.finishNode(node, "TSEnumBody");
  13089. }
  13090. tsParseModuleBlock() {
  13091. const node = this.startNode();
  13092. this.scope.enter(0);
  13093. this.expect(5);
  13094. super.parseBlockOrModuleBlockBody(node.body = [], undefined, true, 8);
  13095. this.scope.exit();
  13096. return this.finishNode(node, "TSModuleBlock");
  13097. }
  13098. tsParseModuleOrNamespaceDeclaration(node, nested = false) {
  13099. node.id = this.parseIdentifier();
  13100. if (!nested) {
  13101. this.checkIdentifier(node.id, 1024);
  13102. }
  13103. if (this.eat(16)) {
  13104. const inner = this.startNode();
  13105. this.tsParseModuleOrNamespaceDeclaration(inner, true);
  13106. node.body = inner;
  13107. } else {
  13108. this.scope.enter(1024);
  13109. this.prodParam.enter(0);
  13110. node.body = this.tsParseModuleBlock();
  13111. this.prodParam.exit();
  13112. this.scope.exit();
  13113. }
  13114. return this.finishNode(node, "TSModuleDeclaration");
  13115. }
  13116. tsParseAmbientExternalModuleDeclaration(node) {
  13117. if (this.isContextual(112)) {
  13118. node.kind = "global";
  13119. node.global = true;
  13120. node.id = this.parseIdentifier();
  13121. } else if (this.match(134)) {
  13122. node.kind = "module";
  13123. node.id = super.parseStringLiteral(this.state.value);
  13124. } else {
  13125. this.unexpected();
  13126. }
  13127. if (this.match(5)) {
  13128. this.scope.enter(1024);
  13129. this.prodParam.enter(0);
  13130. node.body = this.tsParseModuleBlock();
  13131. this.prodParam.exit();
  13132. this.scope.exit();
  13133. } else {
  13134. this.semicolon();
  13135. }
  13136. return this.finishNode(node, "TSModuleDeclaration");
  13137. }
  13138. tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier, isExport) {
  13139. node.isExport = isExport || false;
  13140. node.id = maybeDefaultIdentifier || this.parseIdentifier();
  13141. this.checkIdentifier(node.id, 4096);
  13142. this.expect(29);
  13143. const moduleReference = this.tsParseModuleReference();
  13144. if (node.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") {
  13145. this.raise(TSErrors.ImportAliasHasImportType, moduleReference);
  13146. }
  13147. node.moduleReference = moduleReference;
  13148. this.semicolon();
  13149. return this.finishNode(node, "TSImportEqualsDeclaration");
  13150. }
  13151. tsIsExternalModuleReference() {
  13152. return this.isContextual(119) && this.lookaheadCharCode() === 40;
  13153. }
  13154. tsParseModuleReference() {
  13155. return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(0);
  13156. }
  13157. tsParseExternalModuleReference() {
  13158. const node = this.startNode();
  13159. this.expectContextual(119);
  13160. this.expect(10);
  13161. if (!this.match(134)) {
  13162. this.unexpected();
  13163. }
  13164. node.expression = super.parseExprAtom();
  13165. this.expect(11);
  13166. this.sawUnambiguousESM = true;
  13167. return this.finishNode(node, "TSExternalModuleReference");
  13168. }
  13169. tsLookAhead(f) {
  13170. const state = this.state.clone();
  13171. const res = f();
  13172. this.state = state;
  13173. return res;
  13174. }
  13175. tsTryParseAndCatch(f) {
  13176. const result = this.tryParse(abort => f() || abort());
  13177. if (result.aborted || !result.node) return;
  13178. if (result.error) this.state = result.failState;
  13179. return result.node;
  13180. }
  13181. tsTryParse(f) {
  13182. const state = this.state.clone();
  13183. const result = f();
  13184. if (result !== undefined && result !== false) {
  13185. return result;
  13186. }
  13187. this.state = state;
  13188. }
  13189. tsTryParseDeclare(node) {
  13190. if (this.isLineTerminator()) {
  13191. return;
  13192. }
  13193. const startType = this.state.type;
  13194. return this.tsInAmbientContext(() => {
  13195. switch (startType) {
  13196. case 68:
  13197. node.declare = true;
  13198. return super.parseFunctionStatement(node, false, false);
  13199. case 80:
  13200. node.declare = true;
  13201. return this.parseClass(node, true, false);
  13202. case 126:
  13203. return this.tsParseEnumDeclaration(node, {
  13204. declare: true
  13205. });
  13206. case 112:
  13207. return this.tsParseAmbientExternalModuleDeclaration(node);
  13208. case 100:
  13209. if (this.state.containsEsc) {
  13210. return;
  13211. }
  13212. case 75:
  13213. case 74:
  13214. if (!this.match(75) || !this.isLookaheadContextual("enum")) {
  13215. node.declare = true;
  13216. return this.parseVarStatement(node, this.state.value, true);
  13217. }
  13218. this.expect(75);
  13219. return this.tsParseEnumDeclaration(node, {
  13220. const: true,
  13221. declare: true
  13222. });
  13223. case 107:
  13224. if (this.isUsing()) {
  13225. this.raise(TSErrors.InvalidModifierOnUsingDeclaration, this.state.startLoc, "declare");
  13226. node.declare = true;
  13227. return this.parseVarStatement(node, "using", true);
  13228. }
  13229. break;
  13230. case 96:
  13231. if (this.isAwaitUsing()) {
  13232. this.raise(TSErrors.InvalidModifierOnAwaitUsingDeclaration, this.state.startLoc, "declare");
  13233. node.declare = true;
  13234. this.next();
  13235. return this.parseVarStatement(node, "await using", true);
  13236. }
  13237. break;
  13238. case 129:
  13239. {
  13240. const result = this.tsParseInterfaceDeclaration(node, {
  13241. declare: true
  13242. });
  13243. if (result) return result;
  13244. }
  13245. default:
  13246. if (tokenIsIdentifier(startType)) {
  13247. return this.tsParseDeclaration(node, this.state.type, true, null);
  13248. }
  13249. }
  13250. });
  13251. }
  13252. tsTryParseExportDeclaration() {
  13253. return this.tsParseDeclaration(this.startNode(), this.state.type, true, null);
  13254. }
  13255. tsParseDeclaration(node, type, next, decorators) {
  13256. switch (type) {
  13257. case 124:
  13258. if (this.tsCheckLineTerminator(next) && (this.match(80) || tokenIsIdentifier(this.state.type))) {
  13259. return this.tsParseAbstractDeclaration(node, decorators);
  13260. }
  13261. break;
  13262. case 127:
  13263. if (this.tsCheckLineTerminator(next)) {
  13264. if (this.match(134)) {
  13265. return this.tsParseAmbientExternalModuleDeclaration(node);
  13266. } else if (tokenIsIdentifier(this.state.type)) {
  13267. node.kind = "module";
  13268. return this.tsParseModuleOrNamespaceDeclaration(node);
  13269. }
  13270. }
  13271. break;
  13272. case 128:
  13273. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  13274. node.kind = "namespace";
  13275. return this.tsParseModuleOrNamespaceDeclaration(node);
  13276. }
  13277. break;
  13278. case 130:
  13279. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  13280. return this.tsParseTypeAliasDeclaration(node);
  13281. }
  13282. break;
  13283. }
  13284. }
  13285. tsCheckLineTerminator(next) {
  13286. if (next) {
  13287. if (this.hasFollowingLineBreak()) return false;
  13288. this.next();
  13289. return true;
  13290. }
  13291. return !this.isLineTerminator();
  13292. }
  13293. tsTryParseGenericAsyncArrowFunction(startLoc) {
  13294. if (!this.match(47)) return;
  13295. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  13296. this.state.maybeInArrowParameters = true;
  13297. const res = this.tsTryParseAndCatch(() => {
  13298. const node = this.startNodeAt(startLoc);
  13299. node.typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier);
  13300. super.parseFunctionParams(node);
  13301. node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
  13302. this.expect(19);
  13303. return node;
  13304. });
  13305. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  13306. if (!res) return;
  13307. return super.parseArrowExpression(res, null, true);
  13308. }
  13309. tsParseTypeArgumentsInExpression() {
  13310. if (this.reScan_lt() !== 47) return;
  13311. return this.tsParseTypeArguments();
  13312. }
  13313. tsParseTypeArguments() {
  13314. const node = this.startNode();
  13315. node.params = this.tsInType(() => this.tsInTopLevelContext(() => {
  13316. this.expect(47);
  13317. return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
  13318. }));
  13319. if (node.params.length === 0) {
  13320. this.raise(TSErrors.EmptyTypeArguments, node);
  13321. } else if (!this.state.inType && this.curContext() === types.brace) {
  13322. this.reScan_lt_gt();
  13323. }
  13324. this.expect(48);
  13325. return this.finishNode(node, "TSTypeParameterInstantiation");
  13326. }
  13327. tsIsDeclarationStart() {
  13328. return tokenIsTSDeclarationStart(this.state.type);
  13329. }
  13330. isExportDefaultSpecifier() {
  13331. if (this.tsIsDeclarationStart()) return false;
  13332. return super.isExportDefaultSpecifier();
  13333. }
  13334. parseBindingElement(flags, decorators) {
  13335. const startLoc = decorators.length ? decorators[0].loc.start : this.state.startLoc;
  13336. const modified = {};
  13337. this.tsParseModifiers({
  13338. allowedModifiers: ["public", "private", "protected", "override", "readonly"]
  13339. }, modified);
  13340. const accessibility = modified.accessibility;
  13341. const override = modified.override;
  13342. const readonly = modified.readonly;
  13343. if (!(flags & 4) && (accessibility || readonly || override)) {
  13344. this.raise(TSErrors.UnexpectedParameterModifier, startLoc);
  13345. }
  13346. const left = this.parseMaybeDefault();
  13347. if (flags & 2) {
  13348. this.parseFunctionParamType(left);
  13349. }
  13350. const elt = this.parseMaybeDefault(left.loc.start, left);
  13351. if (accessibility || readonly || override) {
  13352. const pp = this.startNodeAt(startLoc);
  13353. if (decorators.length) {
  13354. pp.decorators = decorators;
  13355. }
  13356. if (accessibility) pp.accessibility = accessibility;
  13357. if (readonly) pp.readonly = readonly;
  13358. if (override) pp.override = override;
  13359. if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
  13360. this.raise(TSErrors.UnsupportedParameterPropertyKind, pp);
  13361. }
  13362. pp.parameter = elt;
  13363. return this.finishNode(pp, "TSParameterProperty");
  13364. }
  13365. if (decorators.length) {
  13366. left.decorators = decorators;
  13367. }
  13368. return elt;
  13369. }
  13370. isSimpleParameter(node) {
  13371. return node.type === "TSParameterProperty" && super.isSimpleParameter(node.parameter) || super.isSimpleParameter(node);
  13372. }
  13373. tsDisallowOptionalPattern(node) {
  13374. for (const param of node.params) {
  13375. if (param.type !== "Identifier" && param.optional && !this.state.isAmbientContext) {
  13376. this.raise(TSErrors.PatternIsOptional, param);
  13377. }
  13378. }
  13379. }
  13380. setArrowFunctionParameters(node, params, trailingCommaLoc) {
  13381. super.setArrowFunctionParameters(node, params, trailingCommaLoc);
  13382. this.tsDisallowOptionalPattern(node);
  13383. }
  13384. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  13385. if (this.match(14)) {
  13386. node.returnType = this.tsParseTypeOrTypePredicateAnnotation(14);
  13387. }
  13388. const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" || type === "ClassPrivateMethod" ? "TSDeclareMethod" : undefined;
  13389. if (bodilessType && !this.match(5) && this.isLineTerminator()) {
  13390. return this.finishNode(node, bodilessType);
  13391. }
  13392. if (bodilessType === "TSDeclareFunction" && this.state.isAmbientContext) {
  13393. this.raise(TSErrors.DeclareFunctionHasImplementation, node);
  13394. if (node.declare) {
  13395. return super.parseFunctionBodyAndFinish(node, bodilessType, isMethod);
  13396. }
  13397. }
  13398. this.tsDisallowOptionalPattern(node);
  13399. return super.parseFunctionBodyAndFinish(node, type, isMethod);
  13400. }
  13401. registerFunctionStatementId(node) {
  13402. if (!node.body && node.id) {
  13403. this.checkIdentifier(node.id, 1024);
  13404. } else {
  13405. super.registerFunctionStatementId(node);
  13406. }
  13407. }
  13408. tsCheckForInvalidTypeCasts(items) {
  13409. items.forEach(node => {
  13410. if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") {
  13411. this.raise(TSErrors.UnexpectedTypeAnnotation, node.typeAnnotation);
  13412. }
  13413. });
  13414. }
  13415. toReferencedList(exprList, isInParens) {
  13416. this.tsCheckForInvalidTypeCasts(exprList);
  13417. return exprList;
  13418. }
  13419. parseArrayLike(close, isTuple, refExpressionErrors) {
  13420. const node = super.parseArrayLike(close, isTuple, refExpressionErrors);
  13421. if (node.type === "ArrayExpression") {
  13422. this.tsCheckForInvalidTypeCasts(node.elements);
  13423. }
  13424. return node;
  13425. }
  13426. parseSubscript(base, startLoc, noCalls, state) {
  13427. if (!this.hasPrecedingLineBreak() && this.match(35)) {
  13428. this.state.canStartJSXElement = false;
  13429. this.next();
  13430. const nonNullExpression = this.startNodeAt(startLoc);
  13431. nonNullExpression.expression = base;
  13432. return this.finishNode(nonNullExpression, "TSNonNullExpression");
  13433. }
  13434. let isOptionalCall = false;
  13435. if (this.match(18) && this.lookaheadCharCode() === 60) {
  13436. if (noCalls) {
  13437. state.stop = true;
  13438. return base;
  13439. }
  13440. state.optionalChainMember = isOptionalCall = true;
  13441. this.next();
  13442. }
  13443. if (this.match(47) || this.match(51)) {
  13444. let missingParenErrorLoc;
  13445. const result = this.tsTryParseAndCatch(() => {
  13446. if (!noCalls && this.atPossibleAsyncArrow(base)) {
  13447. const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startLoc);
  13448. if (asyncArrowFn) {
  13449. state.stop = true;
  13450. return asyncArrowFn;
  13451. }
  13452. }
  13453. const typeArguments = this.tsParseTypeArgumentsInExpression();
  13454. if (!typeArguments) return;
  13455. if (isOptionalCall && !this.match(10)) {
  13456. missingParenErrorLoc = this.state.curPosition();
  13457. return;
  13458. }
  13459. if (tokenIsTemplate(this.state.type)) {
  13460. const result = super.parseTaggedTemplateExpression(base, startLoc, state);
  13461. result.typeParameters = typeArguments;
  13462. return result;
  13463. }
  13464. if (!noCalls && this.eat(10)) {
  13465. const node = this.startNodeAt(startLoc);
  13466. node.callee = base;
  13467. node.arguments = this.parseCallExpressionArguments();
  13468. this.tsCheckForInvalidTypeCasts(node.arguments);
  13469. node.typeParameters = typeArguments;
  13470. if (state.optionalChainMember) {
  13471. node.optional = isOptionalCall;
  13472. }
  13473. return this.finishCallExpression(node, state.optionalChainMember);
  13474. }
  13475. const tokenType = this.state.type;
  13476. if (tokenType === 48 || tokenType === 52 || tokenType !== 10 && tokenType !== 93 && tokenType !== 120 && tokenCanStartExpression(tokenType) && !this.hasPrecedingLineBreak()) {
  13477. return;
  13478. }
  13479. const node = this.startNodeAt(startLoc);
  13480. node.expression = base;
  13481. node.typeParameters = typeArguments;
  13482. return this.finishNode(node, "TSInstantiationExpression");
  13483. });
  13484. if (missingParenErrorLoc) {
  13485. this.unexpected(missingParenErrorLoc, 10);
  13486. }
  13487. if (result) {
  13488. if (result.type === "TSInstantiationExpression") {
  13489. if (this.match(16) || this.match(18) && this.lookaheadCharCode() !== 40) {
  13490. this.raise(TSErrors.InvalidPropertyAccessAfterInstantiationExpression, this.state.startLoc);
  13491. }
  13492. if (!this.match(16) && !this.match(18)) {
  13493. result.expression = super.stopParseSubscript(base, state);
  13494. }
  13495. }
  13496. return result;
  13497. }
  13498. }
  13499. return super.parseSubscript(base, startLoc, noCalls, state);
  13500. }
  13501. parseNewCallee(node) {
  13502. var _callee$extra;
  13503. super.parseNewCallee(node);
  13504. const {
  13505. callee
  13506. } = node;
  13507. if (callee.type === "TSInstantiationExpression" && !((_callee$extra = callee.extra) != null && _callee$extra.parenthesized)) {
  13508. node.typeParameters = callee.typeParameters;
  13509. node.callee = callee.expression;
  13510. }
  13511. }
  13512. parseExprOp(left, leftStartLoc, minPrec) {
  13513. let isSatisfies;
  13514. if (tokenOperatorPrecedence(58) > minPrec && !this.hasPrecedingLineBreak() && (this.isContextual(93) || (isSatisfies = this.isContextual(120)))) {
  13515. const node = this.startNodeAt(leftStartLoc);
  13516. node.expression = left;
  13517. node.typeAnnotation = this.tsInType(() => {
  13518. this.next();
  13519. if (this.match(75)) {
  13520. if (isSatisfies) {
  13521. this.raise(Errors.UnexpectedKeyword, this.state.startLoc, {
  13522. keyword: "const"
  13523. });
  13524. }
  13525. return this.tsParseTypeReference();
  13526. }
  13527. return this.tsParseType();
  13528. });
  13529. this.finishNode(node, isSatisfies ? "TSSatisfiesExpression" : "TSAsExpression");
  13530. this.reScan_lt_gt();
  13531. return this.parseExprOp(node, leftStartLoc, minPrec);
  13532. }
  13533. return super.parseExprOp(left, leftStartLoc, minPrec);
  13534. }
  13535. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  13536. if (!this.state.isAmbientContext) {
  13537. super.checkReservedWord(word, startLoc, checkKeywords, isBinding);
  13538. }
  13539. }
  13540. checkImportReflection(node) {
  13541. super.checkImportReflection(node);
  13542. if (node.module && node.importKind !== "value") {
  13543. this.raise(TSErrors.ImportReflectionHasImportType, node.specifiers[0].loc.start);
  13544. }
  13545. }
  13546. checkDuplicateExports() {}
  13547. isPotentialImportPhase(isExport) {
  13548. if (super.isPotentialImportPhase(isExport)) return true;
  13549. if (this.isContextual(130)) {
  13550. const ch = this.lookaheadCharCode();
  13551. return isExport ? ch === 123 || ch === 42 : ch !== 61;
  13552. }
  13553. return !isExport && this.isContextual(87);
  13554. }
  13555. applyImportPhase(node, isExport, phase, loc) {
  13556. super.applyImportPhase(node, isExport, phase, loc);
  13557. if (isExport) {
  13558. node.exportKind = phase === "type" ? "type" : "value";
  13559. } else {
  13560. node.importKind = phase === "type" || phase === "typeof" ? phase : "value";
  13561. }
  13562. }
  13563. parseImport(node) {
  13564. if (this.match(134)) {
  13565. node.importKind = "value";
  13566. return super.parseImport(node);
  13567. }
  13568. let importNode;
  13569. if (tokenIsIdentifier(this.state.type) && this.lookaheadCharCode() === 61) {
  13570. node.importKind = "value";
  13571. return this.tsParseImportEqualsDeclaration(node);
  13572. } else if (this.isContextual(130)) {
  13573. const maybeDefaultIdentifier = this.parseMaybeImportPhase(node, false);
  13574. if (this.lookaheadCharCode() === 61) {
  13575. return this.tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier);
  13576. } else {
  13577. importNode = super.parseImportSpecifiersAndAfter(node, maybeDefaultIdentifier);
  13578. }
  13579. } else {
  13580. importNode = super.parseImport(node);
  13581. }
  13582. if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") {
  13583. this.raise(TSErrors.TypeImportCannotSpecifyDefaultAndNamed, importNode);
  13584. }
  13585. return importNode;
  13586. }
  13587. parseExport(node, decorators) {
  13588. if (this.match(83)) {
  13589. const nodeImportEquals = node;
  13590. this.next();
  13591. let maybeDefaultIdentifier = null;
  13592. if (this.isContextual(130) && this.isPotentialImportPhase(false)) {
  13593. maybeDefaultIdentifier = this.parseMaybeImportPhase(nodeImportEquals, false);
  13594. } else {
  13595. nodeImportEquals.importKind = "value";
  13596. }
  13597. const declaration = this.tsParseImportEqualsDeclaration(nodeImportEquals, maybeDefaultIdentifier, true);
  13598. return declaration;
  13599. } else if (this.eat(29)) {
  13600. const assign = node;
  13601. assign.expression = super.parseExpression();
  13602. this.semicolon();
  13603. this.sawUnambiguousESM = true;
  13604. return this.finishNode(assign, "TSExportAssignment");
  13605. } else if (this.eatContextual(93)) {
  13606. const decl = node;
  13607. this.expectContextual(128);
  13608. decl.id = this.parseIdentifier();
  13609. this.semicolon();
  13610. return this.finishNode(decl, "TSNamespaceExportDeclaration");
  13611. } else {
  13612. return super.parseExport(node, decorators);
  13613. }
  13614. }
  13615. isAbstractClass() {
  13616. return this.isContextual(124) && this.isLookaheadContextual("class");
  13617. }
  13618. parseExportDefaultExpression() {
  13619. if (this.isAbstractClass()) {
  13620. const cls = this.startNode();
  13621. this.next();
  13622. cls.abstract = true;
  13623. return this.parseClass(cls, true, true);
  13624. }
  13625. if (this.match(129)) {
  13626. const result = this.tsParseInterfaceDeclaration(this.startNode());
  13627. if (result) return result;
  13628. }
  13629. return super.parseExportDefaultExpression();
  13630. }
  13631. parseVarStatement(node, kind, allowMissingInitializer = false) {
  13632. const {
  13633. isAmbientContext
  13634. } = this.state;
  13635. const declaration = super.parseVarStatement(node, kind, allowMissingInitializer || isAmbientContext);
  13636. if (!isAmbientContext) return declaration;
  13637. if (!node.declare && (kind === "using" || kind === "await using")) {
  13638. this.raiseOverwrite(TSErrors.UsingDeclarationInAmbientContext, node, kind);
  13639. return declaration;
  13640. }
  13641. for (const {
  13642. id,
  13643. init
  13644. } of declaration.declarations) {
  13645. if (!init) continue;
  13646. if (kind === "var" || kind === "let" || !!id.typeAnnotation) {
  13647. this.raise(TSErrors.InitializerNotAllowedInAmbientContext, init);
  13648. } else if (!isValidAmbientConstInitializer(init, this.hasPlugin("estree"))) {
  13649. this.raise(TSErrors.ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference, init);
  13650. }
  13651. }
  13652. return declaration;
  13653. }
  13654. parseStatementContent(flags, decorators) {
  13655. if (!this.state.containsEsc) {
  13656. switch (this.state.type) {
  13657. case 75:
  13658. {
  13659. if (this.isLookaheadContextual("enum")) {
  13660. const node = this.startNode();
  13661. this.expect(75);
  13662. return this.tsParseEnumDeclaration(node, {
  13663. const: true
  13664. });
  13665. }
  13666. break;
  13667. }
  13668. case 124:
  13669. case 125:
  13670. {
  13671. if (this.nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine()) {
  13672. const token = this.state.type;
  13673. const node = this.startNode();
  13674. this.next();
  13675. const declaration = token === 125 ? this.tsTryParseDeclare(node) : this.tsParseAbstractDeclaration(node, decorators);
  13676. if (declaration) {
  13677. if (token === 125) {
  13678. declaration.declare = true;
  13679. }
  13680. return declaration;
  13681. } else {
  13682. node.expression = this.createIdentifier(this.startNodeAt(node.loc.start), token === 125 ? "declare" : "abstract");
  13683. this.semicolon(false);
  13684. return this.finishNode(node, "ExpressionStatement");
  13685. }
  13686. }
  13687. break;
  13688. }
  13689. case 126:
  13690. return this.tsParseEnumDeclaration(this.startNode());
  13691. case 112:
  13692. {
  13693. const nextCh = this.lookaheadCharCode();
  13694. if (nextCh === 123) {
  13695. const node = this.startNode();
  13696. return this.tsParseAmbientExternalModuleDeclaration(node);
  13697. }
  13698. break;
  13699. }
  13700. case 129:
  13701. {
  13702. const result = this.tsParseInterfaceDeclaration(this.startNode());
  13703. if (result) return result;
  13704. break;
  13705. }
  13706. case 127:
  13707. {
  13708. if (this.nextTokenIsIdentifierOrStringLiteralOnSameLine()) {
  13709. const node = this.startNode();
  13710. this.next();
  13711. return this.tsParseDeclaration(node, 127, false, decorators);
  13712. }
  13713. break;
  13714. }
  13715. case 128:
  13716. {
  13717. if (this.nextTokenIsIdentifierOnSameLine()) {
  13718. const node = this.startNode();
  13719. this.next();
  13720. return this.tsParseDeclaration(node, 128, false, decorators);
  13721. }
  13722. break;
  13723. }
  13724. case 130:
  13725. {
  13726. if (this.nextTokenIsIdentifierOnSameLine()) {
  13727. const node = this.startNode();
  13728. this.next();
  13729. return this.tsParseTypeAliasDeclaration(node);
  13730. }
  13731. break;
  13732. }
  13733. }
  13734. }
  13735. return super.parseStatementContent(flags, decorators);
  13736. }
  13737. parseAccessModifier() {
  13738. return this.tsParseModifier(["public", "protected", "private"]);
  13739. }
  13740. tsHasSomeModifiers(member, modifiers) {
  13741. return modifiers.some(modifier => {
  13742. if (tsIsAccessModifier(modifier)) {
  13743. return member.accessibility === modifier;
  13744. }
  13745. return !!member[modifier];
  13746. });
  13747. }
  13748. tsIsStartOfStaticBlocks() {
  13749. return this.isContextual(106) && this.lookaheadCharCode() === 123;
  13750. }
  13751. parseClassMember(classBody, member, state) {
  13752. const modifiers = ["declare", "private", "public", "protected", "override", "abstract", "readonly", "static"];
  13753. this.tsParseModifiers({
  13754. allowedModifiers: modifiers,
  13755. disallowedModifiers: ["in", "out"],
  13756. stopOnStartOfClassStaticBlock: true,
  13757. errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions
  13758. }, member);
  13759. const callParseClassMemberWithIsStatic = () => {
  13760. if (this.tsIsStartOfStaticBlocks()) {
  13761. this.next();
  13762. this.next();
  13763. if (this.tsHasSomeModifiers(member, modifiers)) {
  13764. this.raise(TSErrors.StaticBlockCannotHaveModifier, this.state.curPosition());
  13765. }
  13766. super.parseClassStaticBlock(classBody, member);
  13767. } else {
  13768. this.parseClassMemberWithIsStatic(classBody, member, state, !!member.static);
  13769. }
  13770. };
  13771. if (member.declare) {
  13772. this.tsInAmbientContext(callParseClassMemberWithIsStatic);
  13773. } else {
  13774. callParseClassMemberWithIsStatic();
  13775. }
  13776. }
  13777. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  13778. const idx = this.tsTryParseIndexSignature(member);
  13779. if (idx) {
  13780. classBody.body.push(idx);
  13781. if (member.abstract) {
  13782. this.raise(TSErrors.IndexSignatureHasAbstract, member);
  13783. }
  13784. if (member.accessibility) {
  13785. this.raise(TSErrors.IndexSignatureHasAccessibility, member, {
  13786. modifier: member.accessibility
  13787. });
  13788. }
  13789. if (member.declare) {
  13790. this.raise(TSErrors.IndexSignatureHasDeclare, member);
  13791. }
  13792. if (member.override) {
  13793. this.raise(TSErrors.IndexSignatureHasOverride, member);
  13794. }
  13795. return;
  13796. }
  13797. if (!this.state.inAbstractClass && member.abstract) {
  13798. this.raise(TSErrors.NonAbstractClassHasAbstractMethod, member);
  13799. }
  13800. if (member.override) {
  13801. if (!state.hadSuperClass) {
  13802. this.raise(TSErrors.OverrideNotInSubClass, member);
  13803. }
  13804. }
  13805. super.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  13806. }
  13807. parsePostMemberNameModifiers(methodOrProp) {
  13808. const optional = this.eat(17);
  13809. if (optional) methodOrProp.optional = true;
  13810. if (methodOrProp.readonly && this.match(10)) {
  13811. this.raise(TSErrors.ClassMethodHasReadonly, methodOrProp);
  13812. }
  13813. if (methodOrProp.declare && this.match(10)) {
  13814. this.raise(TSErrors.ClassMethodHasDeclare, methodOrProp);
  13815. }
  13816. }
  13817. shouldParseExportDeclaration() {
  13818. if (this.tsIsDeclarationStart()) return true;
  13819. return super.shouldParseExportDeclaration();
  13820. }
  13821. parseConditional(expr, startLoc, refExpressionErrors) {
  13822. if (!this.match(17)) return expr;
  13823. if (this.state.maybeInArrowParameters) {
  13824. const nextCh = this.lookaheadCharCode();
  13825. if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) {
  13826. this.setOptionalParametersError(refExpressionErrors);
  13827. return expr;
  13828. }
  13829. }
  13830. return super.parseConditional(expr, startLoc, refExpressionErrors);
  13831. }
  13832. parseParenItem(node, startLoc) {
  13833. const newNode = super.parseParenItem(node, startLoc);
  13834. if (this.eat(17)) {
  13835. newNode.optional = true;
  13836. this.resetEndLocation(node);
  13837. }
  13838. if (this.match(14)) {
  13839. const typeCastNode = this.startNodeAt(startLoc);
  13840. typeCastNode.expression = node;
  13841. typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
  13842. return this.finishNode(typeCastNode, "TSTypeCastExpression");
  13843. }
  13844. return node;
  13845. }
  13846. parseExportDeclaration(node) {
  13847. if (!this.state.isAmbientContext && this.isContextual(125)) {
  13848. return this.tsInAmbientContext(() => this.parseExportDeclaration(node));
  13849. }
  13850. const startLoc = this.state.startLoc;
  13851. const isDeclare = this.eatContextual(125);
  13852. if (isDeclare && (this.isContextual(125) || !this.shouldParseExportDeclaration())) {
  13853. throw this.raise(TSErrors.ExpectedAmbientAfterExportDeclare, this.state.startLoc);
  13854. }
  13855. const isIdentifier = tokenIsIdentifier(this.state.type);
  13856. const declaration = isIdentifier && this.tsTryParseExportDeclaration() || super.parseExportDeclaration(node);
  13857. if (!declaration) return null;
  13858. if (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare) {
  13859. node.exportKind = "type";
  13860. }
  13861. if (isDeclare && declaration.type !== "TSImportEqualsDeclaration") {
  13862. this.resetStartLocation(declaration, startLoc);
  13863. declaration.declare = true;
  13864. }
  13865. return declaration;
  13866. }
  13867. parseClassId(node, isStatement, optionalId, bindingType) {
  13868. if ((!isStatement || optionalId) && this.isContextual(113)) {
  13869. return;
  13870. }
  13871. super.parseClassId(node, isStatement, optionalId, node.declare ? 1024 : 8331);
  13872. const typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);
  13873. if (typeParameters) node.typeParameters = typeParameters;
  13874. }
  13875. parseClassPropertyAnnotation(node) {
  13876. if (!node.optional) {
  13877. if (this.eat(35)) {
  13878. node.definite = true;
  13879. } else if (this.eat(17)) {
  13880. node.optional = true;
  13881. }
  13882. }
  13883. const type = this.tsTryParseTypeAnnotation();
  13884. if (type) node.typeAnnotation = type;
  13885. }
  13886. parseClassProperty(node) {
  13887. this.parseClassPropertyAnnotation(node);
  13888. if (this.state.isAmbientContext && !(node.readonly && !node.typeAnnotation) && this.match(29)) {
  13889. this.raise(TSErrors.DeclareClassFieldHasInitializer, this.state.startLoc);
  13890. }
  13891. if (node.abstract && this.match(29)) {
  13892. const {
  13893. key
  13894. } = node;
  13895. this.raise(TSErrors.AbstractPropertyHasInitializer, this.state.startLoc, {
  13896. propertyName: key.type === "Identifier" && !node.computed ? key.name : `[${this.input.slice(this.offsetToSourcePos(key.start), this.offsetToSourcePos(key.end))}]`
  13897. });
  13898. }
  13899. return super.parseClassProperty(node);
  13900. }
  13901. parseClassPrivateProperty(node) {
  13902. if (node.abstract) {
  13903. this.raise(TSErrors.PrivateElementHasAbstract, node);
  13904. }
  13905. if (node.accessibility) {
  13906. this.raise(TSErrors.PrivateElementHasAccessibility, node, {
  13907. modifier: node.accessibility
  13908. });
  13909. }
  13910. this.parseClassPropertyAnnotation(node);
  13911. return super.parseClassPrivateProperty(node);
  13912. }
  13913. parseClassAccessorProperty(node) {
  13914. this.parseClassPropertyAnnotation(node);
  13915. if (node.optional) {
  13916. this.raise(TSErrors.AccessorCannotBeOptional, node);
  13917. }
  13918. return super.parseClassAccessorProperty(node);
  13919. }
  13920. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  13921. const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  13922. if (typeParameters && isConstructor) {
  13923. this.raise(TSErrors.ConstructorHasTypeParameters, typeParameters);
  13924. }
  13925. const {
  13926. declare = false,
  13927. kind
  13928. } = method;
  13929. if (declare && (kind === "get" || kind === "set")) {
  13930. this.raise(TSErrors.DeclareAccessor, method, {
  13931. kind
  13932. });
  13933. }
  13934. if (typeParameters) method.typeParameters = typeParameters;
  13935. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  13936. }
  13937. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  13938. const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  13939. if (typeParameters) method.typeParameters = typeParameters;
  13940. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  13941. }
  13942. declareClassPrivateMethodInScope(node, kind) {
  13943. if (node.type === "TSDeclareMethod") return;
  13944. if (node.type === "MethodDefinition" && node.value.body == null) {
  13945. return;
  13946. }
  13947. super.declareClassPrivateMethodInScope(node, kind);
  13948. }
  13949. parseClassSuper(node) {
  13950. super.parseClassSuper(node);
  13951. if (node.superClass) {
  13952. if (node.superClass.type === "TSInstantiationExpression") {
  13953. const tsInstantiationExpression = node.superClass;
  13954. const superClass = tsInstantiationExpression.expression;
  13955. this.takeSurroundingComments(superClass, superClass.start, superClass.end);
  13956. const superTypeArguments = tsInstantiationExpression.typeParameters;
  13957. this.takeSurroundingComments(superTypeArguments, superTypeArguments.start, superTypeArguments.end);
  13958. node.superClass = superClass;
  13959. node.superTypeParameters = superTypeArguments;
  13960. } else if (this.match(47) || this.match(51)) {
  13961. node.superTypeParameters = this.tsParseTypeArgumentsInExpression();
  13962. }
  13963. }
  13964. if (this.eatContextual(113)) {
  13965. node.implements = this.tsParseHeritageClause("implements");
  13966. }
  13967. }
  13968. parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  13969. const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  13970. if (typeParameters) prop.typeParameters = typeParameters;
  13971. return super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  13972. }
  13973. parseFunctionParams(node, isConstructor) {
  13974. const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  13975. if (typeParameters) node.typeParameters = typeParameters;
  13976. super.parseFunctionParams(node, isConstructor);
  13977. }
  13978. parseVarId(decl, kind) {
  13979. super.parseVarId(decl, kind);
  13980. if (decl.id.type === "Identifier" && !this.hasPrecedingLineBreak() && this.eat(35)) {
  13981. decl.definite = true;
  13982. }
  13983. const type = this.tsTryParseTypeAnnotation();
  13984. if (type) {
  13985. decl.id.typeAnnotation = type;
  13986. this.resetEndLocation(decl.id);
  13987. }
  13988. }
  13989. parseAsyncArrowFromCallExpression(node, call) {
  13990. if (this.match(14)) {
  13991. node.returnType = this.tsParseTypeAnnotation();
  13992. }
  13993. return super.parseAsyncArrowFromCallExpression(node, call);
  13994. }
  13995. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  13996. var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2;
  13997. let state;
  13998. let jsx;
  13999. let typeCast;
  14000. if (this.hasPlugin("jsx") && (this.match(143) || this.match(47))) {
  14001. state = this.state.clone();
  14002. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  14003. if (!jsx.error) return jsx.node;
  14004. const {
  14005. context
  14006. } = this.state;
  14007. const currentContext = context[context.length - 1];
  14008. if (currentContext === types.j_oTag || currentContext === types.j_expr) {
  14009. context.pop();
  14010. }
  14011. }
  14012. if (!((_jsx = jsx) != null && _jsx.error) && !this.match(47)) {
  14013. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  14014. }
  14015. if (!state || state === this.state) state = this.state.clone();
  14016. let typeParameters;
  14017. const arrow = this.tryParse(abort => {
  14018. var _expr$extra, _typeParameters;
  14019. typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier);
  14020. const expr = super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  14021. if (expr.type !== "ArrowFunctionExpression" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) {
  14022. abort();
  14023. }
  14024. if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) {
  14025. this.resetStartLocationFromNode(expr, typeParameters);
  14026. }
  14027. expr.typeParameters = typeParameters;
  14028. return expr;
  14029. }, state);
  14030. if (!arrow.error && !arrow.aborted) {
  14031. if (typeParameters) this.reportReservedArrowTypeParam(typeParameters);
  14032. return arrow.node;
  14033. }
  14034. if (!jsx) {
  14035. assert(!this.hasPlugin("jsx"));
  14036. typeCast = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  14037. if (!typeCast.error) return typeCast.node;
  14038. }
  14039. if ((_jsx2 = jsx) != null && _jsx2.node) {
  14040. this.state = jsx.failState;
  14041. return jsx.node;
  14042. }
  14043. if (arrow.node) {
  14044. this.state = arrow.failState;
  14045. if (typeParameters) this.reportReservedArrowTypeParam(typeParameters);
  14046. return arrow.node;
  14047. }
  14048. if ((_typeCast = typeCast) != null && _typeCast.node) {
  14049. this.state = typeCast.failState;
  14050. return typeCast.node;
  14051. }
  14052. throw ((_jsx3 = jsx) == null ? void 0 : _jsx3.error) || arrow.error || ((_typeCast2 = typeCast) == null ? void 0 : _typeCast2.error);
  14053. }
  14054. reportReservedArrowTypeParam(node) {
  14055. var _node$extra2;
  14056. if (node.params.length === 1 && !node.params[0].constraint && !((_node$extra2 = node.extra) != null && _node$extra2.trailingComma) && this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) {
  14057. this.raise(TSErrors.ReservedArrowTypeParam, node);
  14058. }
  14059. }
  14060. parseMaybeUnary(refExpressionErrors, sawUnary) {
  14061. if (!this.hasPlugin("jsx") && this.match(47)) {
  14062. return this.tsParseTypeAssertion();
  14063. }
  14064. return super.parseMaybeUnary(refExpressionErrors, sawUnary);
  14065. }
  14066. parseArrow(node) {
  14067. if (this.match(14)) {
  14068. const result = this.tryParse(abort => {
  14069. const returnType = this.tsParseTypeOrTypePredicateAnnotation(14);
  14070. if (this.canInsertSemicolon() || !this.match(19)) abort();
  14071. return returnType;
  14072. });
  14073. if (result.aborted) return;
  14074. if (!result.thrown) {
  14075. if (result.error) this.state = result.failState;
  14076. node.returnType = result.node;
  14077. }
  14078. }
  14079. return super.parseArrow(node);
  14080. }
  14081. parseFunctionParamType(param) {
  14082. if (this.eat(17)) {
  14083. param.optional = true;
  14084. }
  14085. const type = this.tsTryParseTypeAnnotation();
  14086. if (type) param.typeAnnotation = type;
  14087. this.resetEndLocation(param);
  14088. return param;
  14089. }
  14090. isAssignable(node, isBinding) {
  14091. switch (node.type) {
  14092. case "TSTypeCastExpression":
  14093. return this.isAssignable(node.expression, isBinding);
  14094. case "TSParameterProperty":
  14095. return true;
  14096. default:
  14097. return super.isAssignable(node, isBinding);
  14098. }
  14099. }
  14100. toAssignable(node, isLHS = false) {
  14101. switch (node.type) {
  14102. case "ParenthesizedExpression":
  14103. this.toAssignableParenthesizedExpression(node, isLHS);
  14104. break;
  14105. case "TSAsExpression":
  14106. case "TSSatisfiesExpression":
  14107. case "TSNonNullExpression":
  14108. case "TSTypeAssertion":
  14109. if (isLHS) {
  14110. this.expressionScope.recordArrowParameterBindingError(TSErrors.UnexpectedTypeCastInParameter, node);
  14111. } else {
  14112. this.raise(TSErrors.UnexpectedTypeCastInParameter, node);
  14113. }
  14114. this.toAssignable(node.expression, isLHS);
  14115. break;
  14116. case "AssignmentExpression":
  14117. if (!isLHS && node.left.type === "TSTypeCastExpression") {
  14118. node.left = this.typeCastToParameter(node.left);
  14119. }
  14120. default:
  14121. super.toAssignable(node, isLHS);
  14122. }
  14123. }
  14124. toAssignableParenthesizedExpression(node, isLHS) {
  14125. switch (node.expression.type) {
  14126. case "TSAsExpression":
  14127. case "TSSatisfiesExpression":
  14128. case "TSNonNullExpression":
  14129. case "TSTypeAssertion":
  14130. case "ParenthesizedExpression":
  14131. this.toAssignable(node.expression, isLHS);
  14132. break;
  14133. default:
  14134. super.toAssignable(node, isLHS);
  14135. }
  14136. }
  14137. checkToRestConversion(node, allowPattern) {
  14138. switch (node.type) {
  14139. case "TSAsExpression":
  14140. case "TSSatisfiesExpression":
  14141. case "TSTypeAssertion":
  14142. case "TSNonNullExpression":
  14143. this.checkToRestConversion(node.expression, false);
  14144. break;
  14145. default:
  14146. super.checkToRestConversion(node, allowPattern);
  14147. }
  14148. }
  14149. isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding) {
  14150. switch (type) {
  14151. case "TSTypeCastExpression":
  14152. return true;
  14153. case "TSParameterProperty":
  14154. return "parameter";
  14155. case "TSNonNullExpression":
  14156. return "expression";
  14157. case "TSAsExpression":
  14158. case "TSSatisfiesExpression":
  14159. case "TSTypeAssertion":
  14160. return (binding !== 64 || !isUnparenthesizedInAssign) && ["expression", true];
  14161. default:
  14162. return super.isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding);
  14163. }
  14164. }
  14165. parseBindingAtom() {
  14166. if (this.state.type === 78) {
  14167. return this.parseIdentifier(true);
  14168. }
  14169. return super.parseBindingAtom();
  14170. }
  14171. parseMaybeDecoratorArguments(expr, startLoc) {
  14172. if (this.match(47) || this.match(51)) {
  14173. const typeArguments = this.tsParseTypeArgumentsInExpression();
  14174. if (this.match(10)) {
  14175. const call = super.parseMaybeDecoratorArguments(expr, startLoc);
  14176. call.typeParameters = typeArguments;
  14177. return call;
  14178. }
  14179. this.unexpected(null, 10);
  14180. }
  14181. return super.parseMaybeDecoratorArguments(expr, startLoc);
  14182. }
  14183. checkCommaAfterRest(close) {
  14184. if (this.state.isAmbientContext && this.match(12) && this.lookaheadCharCode() === close) {
  14185. this.next();
  14186. return false;
  14187. }
  14188. return super.checkCommaAfterRest(close);
  14189. }
  14190. isClassMethod() {
  14191. return this.match(47) || super.isClassMethod();
  14192. }
  14193. isClassProperty() {
  14194. return this.match(35) || this.match(14) || super.isClassProperty();
  14195. }
  14196. parseMaybeDefault(startLoc, left) {
  14197. const node = super.parseMaybeDefault(startLoc, left);
  14198. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  14199. this.raise(TSErrors.TypeAnnotationAfterAssign, node.typeAnnotation);
  14200. }
  14201. return node;
  14202. }
  14203. getTokenFromCode(code) {
  14204. if (this.state.inType) {
  14205. if (code === 62) {
  14206. this.finishOp(48, 1);
  14207. return;
  14208. }
  14209. if (code === 60) {
  14210. this.finishOp(47, 1);
  14211. return;
  14212. }
  14213. }
  14214. super.getTokenFromCode(code);
  14215. }
  14216. reScan_lt_gt() {
  14217. const {
  14218. type
  14219. } = this.state;
  14220. if (type === 47) {
  14221. this.state.pos -= 1;
  14222. this.readToken_lt();
  14223. } else if (type === 48) {
  14224. this.state.pos -= 1;
  14225. this.readToken_gt();
  14226. }
  14227. }
  14228. reScan_lt() {
  14229. const {
  14230. type
  14231. } = this.state;
  14232. if (type === 51) {
  14233. this.state.pos -= 2;
  14234. this.finishOp(47, 1);
  14235. return 47;
  14236. }
  14237. return type;
  14238. }
  14239. toAssignableListItem(exprList, index, isLHS) {
  14240. const node = exprList[index];
  14241. if (node.type === "TSTypeCastExpression") {
  14242. exprList[index] = this.typeCastToParameter(node);
  14243. }
  14244. super.toAssignableListItem(exprList, index, isLHS);
  14245. }
  14246. typeCastToParameter(node) {
  14247. node.expression.typeAnnotation = node.typeAnnotation;
  14248. this.resetEndLocation(node.expression, node.typeAnnotation.loc.end);
  14249. return node.expression;
  14250. }
  14251. shouldParseArrow(params) {
  14252. if (this.match(14)) {
  14253. return params.every(expr => this.isAssignable(expr, true));
  14254. }
  14255. return super.shouldParseArrow(params);
  14256. }
  14257. shouldParseAsyncArrow() {
  14258. return this.match(14) || super.shouldParseAsyncArrow();
  14259. }
  14260. canHaveLeadingDecorator() {
  14261. return super.canHaveLeadingDecorator() || this.isAbstractClass();
  14262. }
  14263. jsxParseOpeningElementAfterName(node) {
  14264. if (this.match(47) || this.match(51)) {
  14265. const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArgumentsInExpression());
  14266. if (typeArguments) {
  14267. node.typeParameters = typeArguments;
  14268. }
  14269. }
  14270. return super.jsxParseOpeningElementAfterName(node);
  14271. }
  14272. getGetterSetterExpectedParamCount(method) {
  14273. const baseCount = super.getGetterSetterExpectedParamCount(method);
  14274. const params = this.getObjectOrClassMethodParams(method);
  14275. const firstParam = params[0];
  14276. const hasContextParam = firstParam && this.isThisParam(firstParam);
  14277. return hasContextParam ? baseCount + 1 : baseCount;
  14278. }
  14279. parseCatchClauseParam() {
  14280. const param = super.parseCatchClauseParam();
  14281. const type = this.tsTryParseTypeAnnotation();
  14282. if (type) {
  14283. param.typeAnnotation = type;
  14284. this.resetEndLocation(param);
  14285. }
  14286. return param;
  14287. }
  14288. tsInAmbientContext(cb) {
  14289. const {
  14290. isAmbientContext: oldIsAmbientContext,
  14291. strict: oldStrict
  14292. } = this.state;
  14293. this.state.isAmbientContext = true;
  14294. this.state.strict = false;
  14295. try {
  14296. return cb();
  14297. } finally {
  14298. this.state.isAmbientContext = oldIsAmbientContext;
  14299. this.state.strict = oldStrict;
  14300. }
  14301. }
  14302. parseClass(node, isStatement, optionalId) {
  14303. const oldInAbstractClass = this.state.inAbstractClass;
  14304. this.state.inAbstractClass = !!node.abstract;
  14305. try {
  14306. return super.parseClass(node, isStatement, optionalId);
  14307. } finally {
  14308. this.state.inAbstractClass = oldInAbstractClass;
  14309. }
  14310. }
  14311. tsParseAbstractDeclaration(node, decorators) {
  14312. if (this.match(80)) {
  14313. node.abstract = true;
  14314. return this.maybeTakeDecorators(decorators, this.parseClass(node, true, false));
  14315. } else if (this.isContextual(129)) {
  14316. if (!this.hasFollowingLineBreak()) {
  14317. node.abstract = true;
  14318. this.raise(TSErrors.NonClassMethodPropertyHasAbstractModifier, node);
  14319. return this.tsParseInterfaceDeclaration(node);
  14320. } else {
  14321. return null;
  14322. }
  14323. }
  14324. throw this.unexpected(null, 80);
  14325. }
  14326. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope) {
  14327. const method = super.parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  14328. if (method.abstract || method.type === "TSAbstractMethodDefinition") {
  14329. const hasEstreePlugin = this.hasPlugin("estree");
  14330. const methodFn = hasEstreePlugin ? method.value : method;
  14331. if (methodFn.body) {
  14332. const {
  14333. key
  14334. } = method;
  14335. this.raise(TSErrors.AbstractMethodHasImplementation, method, {
  14336. methodName: key.type === "Identifier" && !method.computed ? key.name : `[${this.input.slice(this.offsetToSourcePos(key.start), this.offsetToSourcePos(key.end))}]`
  14337. });
  14338. }
  14339. }
  14340. return method;
  14341. }
  14342. tsParseTypeParameterName() {
  14343. const typeName = this.parseIdentifier();
  14344. return typeName.name;
  14345. }
  14346. shouldParseAsAmbientContext() {
  14347. return !!this.getPluginOption("typescript", "dts");
  14348. }
  14349. parse() {
  14350. if (this.shouldParseAsAmbientContext()) {
  14351. this.state.isAmbientContext = true;
  14352. }
  14353. return super.parse();
  14354. }
  14355. getExpression() {
  14356. if (this.shouldParseAsAmbientContext()) {
  14357. this.state.isAmbientContext = true;
  14358. }
  14359. return super.getExpression();
  14360. }
  14361. parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) {
  14362. if (!isString && isMaybeTypeOnly) {
  14363. this.parseTypeOnlyImportExportSpecifier(node, false, isInTypeExport);
  14364. return this.finishNode(node, "ExportSpecifier");
  14365. }
  14366. node.exportKind = "value";
  14367. return super.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly);
  14368. }
  14369. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) {
  14370. if (!importedIsString && isMaybeTypeOnly) {
  14371. this.parseTypeOnlyImportExportSpecifier(specifier, true, isInTypeOnlyImport);
  14372. return this.finishNode(specifier, "ImportSpecifier");
  14373. }
  14374. specifier.importKind = "value";
  14375. return super.parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, isInTypeOnlyImport ? 4098 : 4096);
  14376. }
  14377. parseTypeOnlyImportExportSpecifier(node, isImport, isInTypeOnlyImportExport) {
  14378. const leftOfAsKey = isImport ? "imported" : "local";
  14379. const rightOfAsKey = isImport ? "local" : "exported";
  14380. let leftOfAs = node[leftOfAsKey];
  14381. let rightOfAs;
  14382. let hasTypeSpecifier = false;
  14383. let canParseAsKeyword = true;
  14384. const loc = leftOfAs.loc.start;
  14385. if (this.isContextual(93)) {
  14386. const firstAs = this.parseIdentifier();
  14387. if (this.isContextual(93)) {
  14388. const secondAs = this.parseIdentifier();
  14389. if (tokenIsKeywordOrIdentifier(this.state.type)) {
  14390. hasTypeSpecifier = true;
  14391. leftOfAs = firstAs;
  14392. rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  14393. canParseAsKeyword = false;
  14394. } else {
  14395. rightOfAs = secondAs;
  14396. canParseAsKeyword = false;
  14397. }
  14398. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  14399. canParseAsKeyword = false;
  14400. rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  14401. } else {
  14402. hasTypeSpecifier = true;
  14403. leftOfAs = firstAs;
  14404. }
  14405. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  14406. hasTypeSpecifier = true;
  14407. if (isImport) {
  14408. leftOfAs = this.parseIdentifier(true);
  14409. if (!this.isContextual(93)) {
  14410. this.checkReservedWord(leftOfAs.name, leftOfAs.loc.start, true, true);
  14411. }
  14412. } else {
  14413. leftOfAs = this.parseModuleExportName();
  14414. }
  14415. }
  14416. if (hasTypeSpecifier && isInTypeOnlyImportExport) {
  14417. this.raise(isImport ? TSErrors.TypeModifierIsUsedInTypeImports : TSErrors.TypeModifierIsUsedInTypeExports, loc);
  14418. }
  14419. node[leftOfAsKey] = leftOfAs;
  14420. node[rightOfAsKey] = rightOfAs;
  14421. const kindKey = isImport ? "importKind" : "exportKind";
  14422. node[kindKey] = hasTypeSpecifier ? "type" : "value";
  14423. if (canParseAsKeyword && this.eatContextual(93)) {
  14424. node[rightOfAsKey] = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  14425. }
  14426. if (!node[rightOfAsKey]) {
  14427. node[rightOfAsKey] = this.cloneIdentifier(node[leftOfAsKey]);
  14428. }
  14429. if (isImport) {
  14430. this.checkIdentifier(node[rightOfAsKey], hasTypeSpecifier ? 4098 : 4096);
  14431. }
  14432. }
  14433. fillOptionalPropertiesForTSESLint(node) {
  14434. var _node$directive, _node$decorators, _node$optional, _node$typeAnnotation, _node$accessibility, _node$decorators2, _node$override, _node$readonly, _node$static, _node$declare, _node$returnType, _node$typeParameters, _node$optional2, _node$optional3, _node$accessibility2, _node$readonly2, _node$static2, _node$declare2, _node$definite, _node$readonly3, _node$typeAnnotation2, _node$accessibility3, _node$decorators3, _node$override2, _node$optional4, _node$id, _node$abstract, _node$declare3, _node$decorators4, _node$implements, _node$superTypeArgume, _node$typeParameters2, _node$declare4, _node$definite2, _node$const, _node$declare5, _node$computed, _node$qualifier, _node$options, _node$declare6, _node$extends, _node$optional5, _node$readonly4, _node$declare7, _node$global, _node$const2, _node$in, _node$out;
  14435. switch (node.type) {
  14436. case "ExpressionStatement":
  14437. (_node$directive = node.directive) != null ? _node$directive : node.directive = undefined;
  14438. return;
  14439. case "RestElement":
  14440. node.value = undefined;
  14441. case "Identifier":
  14442. case "ArrayPattern":
  14443. case "AssignmentPattern":
  14444. case "ObjectPattern":
  14445. (_node$decorators = node.decorators) != null ? _node$decorators : node.decorators = [];
  14446. (_node$optional = node.optional) != null ? _node$optional : node.optional = false;
  14447. (_node$typeAnnotation = node.typeAnnotation) != null ? _node$typeAnnotation : node.typeAnnotation = undefined;
  14448. return;
  14449. case "TSParameterProperty":
  14450. (_node$accessibility = node.accessibility) != null ? _node$accessibility : node.accessibility = undefined;
  14451. (_node$decorators2 = node.decorators) != null ? _node$decorators2 : node.decorators = [];
  14452. (_node$override = node.override) != null ? _node$override : node.override = false;
  14453. (_node$readonly = node.readonly) != null ? _node$readonly : node.readonly = false;
  14454. (_node$static = node.static) != null ? _node$static : node.static = false;
  14455. return;
  14456. case "TSEmptyBodyFunctionExpression":
  14457. node.body = null;
  14458. case "TSDeclareFunction":
  14459. case "FunctionDeclaration":
  14460. case "FunctionExpression":
  14461. case "ClassMethod":
  14462. case "ClassPrivateMethod":
  14463. (_node$declare = node.declare) != null ? _node$declare : node.declare = false;
  14464. (_node$returnType = node.returnType) != null ? _node$returnType : node.returnType = undefined;
  14465. (_node$typeParameters = node.typeParameters) != null ? _node$typeParameters : node.typeParameters = undefined;
  14466. return;
  14467. case "Property":
  14468. (_node$optional2 = node.optional) != null ? _node$optional2 : node.optional = false;
  14469. return;
  14470. case "TSMethodSignature":
  14471. case "TSPropertySignature":
  14472. (_node$optional3 = node.optional) != null ? _node$optional3 : node.optional = false;
  14473. case "TSIndexSignature":
  14474. (_node$accessibility2 = node.accessibility) != null ? _node$accessibility2 : node.accessibility = undefined;
  14475. (_node$readonly2 = node.readonly) != null ? _node$readonly2 : node.readonly = false;
  14476. (_node$static2 = node.static) != null ? _node$static2 : node.static = false;
  14477. return;
  14478. case "TSAbstractPropertyDefinition":
  14479. case "PropertyDefinition":
  14480. case "TSAbstractAccessorProperty":
  14481. case "AccessorProperty":
  14482. (_node$declare2 = node.declare) != null ? _node$declare2 : node.declare = false;
  14483. (_node$definite = node.definite) != null ? _node$definite : node.definite = false;
  14484. (_node$readonly3 = node.readonly) != null ? _node$readonly3 : node.readonly = false;
  14485. (_node$typeAnnotation2 = node.typeAnnotation) != null ? _node$typeAnnotation2 : node.typeAnnotation = undefined;
  14486. case "TSAbstractMethodDefinition":
  14487. case "MethodDefinition":
  14488. (_node$accessibility3 = node.accessibility) != null ? _node$accessibility3 : node.accessibility = undefined;
  14489. (_node$decorators3 = node.decorators) != null ? _node$decorators3 : node.decorators = [];
  14490. (_node$override2 = node.override) != null ? _node$override2 : node.override = false;
  14491. (_node$optional4 = node.optional) != null ? _node$optional4 : node.optional = false;
  14492. return;
  14493. case "ClassExpression":
  14494. (_node$id = node.id) != null ? _node$id : node.id = null;
  14495. case "ClassDeclaration":
  14496. (_node$abstract = node.abstract) != null ? _node$abstract : node.abstract = false;
  14497. (_node$declare3 = node.declare) != null ? _node$declare3 : node.declare = false;
  14498. (_node$decorators4 = node.decorators) != null ? _node$decorators4 : node.decorators = [];
  14499. (_node$implements = node.implements) != null ? _node$implements : node.implements = [];
  14500. (_node$superTypeArgume = node.superTypeArguments) != null ? _node$superTypeArgume : node.superTypeArguments = undefined;
  14501. (_node$typeParameters2 = node.typeParameters) != null ? _node$typeParameters2 : node.typeParameters = undefined;
  14502. return;
  14503. case "TSTypeAliasDeclaration":
  14504. case "VariableDeclaration":
  14505. (_node$declare4 = node.declare) != null ? _node$declare4 : node.declare = false;
  14506. return;
  14507. case "VariableDeclarator":
  14508. (_node$definite2 = node.definite) != null ? _node$definite2 : node.definite = false;
  14509. return;
  14510. case "TSEnumDeclaration":
  14511. (_node$const = node.const) != null ? _node$const : node.const = false;
  14512. (_node$declare5 = node.declare) != null ? _node$declare5 : node.declare = false;
  14513. return;
  14514. case "TSEnumMember":
  14515. (_node$computed = node.computed) != null ? _node$computed : node.computed = false;
  14516. return;
  14517. case "TSImportType":
  14518. (_node$qualifier = node.qualifier) != null ? _node$qualifier : node.qualifier = null;
  14519. (_node$options = node.options) != null ? _node$options : node.options = null;
  14520. return;
  14521. case "TSInterfaceDeclaration":
  14522. (_node$declare6 = node.declare) != null ? _node$declare6 : node.declare = false;
  14523. (_node$extends = node.extends) != null ? _node$extends : node.extends = [];
  14524. return;
  14525. case "TSMappedType":
  14526. (_node$optional5 = node.optional) != null ? _node$optional5 : node.optional = false;
  14527. (_node$readonly4 = node.readonly) != null ? _node$readonly4 : node.readonly = undefined;
  14528. return;
  14529. case "TSModuleDeclaration":
  14530. (_node$declare7 = node.declare) != null ? _node$declare7 : node.declare = false;
  14531. (_node$global = node.global) != null ? _node$global : node.global = node.kind === "global";
  14532. return;
  14533. case "TSTypeParameter":
  14534. (_node$const2 = node.const) != null ? _node$const2 : node.const = false;
  14535. (_node$in = node.in) != null ? _node$in : node.in = false;
  14536. (_node$out = node.out) != null ? _node$out : node.out = false;
  14537. return;
  14538. }
  14539. }
  14540. chStartsBindingIdentifierAndNotRelationalOperator(ch, pos) {
  14541. if (isIdentifierStart(ch)) {
  14542. keywordAndTSRelationalOperator.lastIndex = pos;
  14543. if (keywordAndTSRelationalOperator.test(this.input)) {
  14544. const endCh = this.codePointAtPos(keywordAndTSRelationalOperator.lastIndex);
  14545. if (!isIdentifierChar(endCh) && endCh !== 92) {
  14546. return false;
  14547. }
  14548. }
  14549. return true;
  14550. } else if (ch === 92) {
  14551. return true;
  14552. } else {
  14553. return false;
  14554. }
  14555. }
  14556. nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine() {
  14557. const next = this.nextTokenInLineStart();
  14558. const nextCh = this.codePointAtPos(next);
  14559. return this.chStartsBindingIdentifierAndNotRelationalOperator(nextCh, next);
  14560. }
  14561. nextTokenIsIdentifierOrStringLiteralOnSameLine() {
  14562. const next = this.nextTokenInLineStart();
  14563. const nextCh = this.codePointAtPos(next);
  14564. return this.chStartsBindingIdentifier(nextCh, next) || nextCh === 34 || nextCh === 39;
  14565. }
  14566. };
  14567. function isPossiblyLiteralEnum(expression) {
  14568. if (expression.type !== "MemberExpression") return false;
  14569. const {
  14570. computed,
  14571. property
  14572. } = expression;
  14573. if (computed && property.type !== "StringLiteral" && (property.type !== "TemplateLiteral" || property.expressions.length > 0)) {
  14574. return false;
  14575. }
  14576. return isUncomputedMemberExpressionChain(expression.object);
  14577. }
  14578. function isValidAmbientConstInitializer(expression, estree) {
  14579. var _expression$extra;
  14580. const {
  14581. type
  14582. } = expression;
  14583. if ((_expression$extra = expression.extra) != null && _expression$extra.parenthesized) {
  14584. return false;
  14585. }
  14586. if (estree) {
  14587. if (type === "Literal") {
  14588. const {
  14589. value
  14590. } = expression;
  14591. if (typeof value === "string" || typeof value === "boolean") {
  14592. return true;
  14593. }
  14594. }
  14595. } else {
  14596. if (type === "StringLiteral" || type === "BooleanLiteral") {
  14597. return true;
  14598. }
  14599. }
  14600. if (isNumber(expression, estree) || isNegativeNumber(expression, estree)) {
  14601. return true;
  14602. }
  14603. if (type === "TemplateLiteral" && expression.expressions.length === 0) {
  14604. return true;
  14605. }
  14606. if (isPossiblyLiteralEnum(expression)) {
  14607. return true;
  14608. }
  14609. return false;
  14610. }
  14611. function isNumber(expression, estree) {
  14612. if (estree) {
  14613. return expression.type === "Literal" && (typeof expression.value === "number" || "bigint" in expression);
  14614. }
  14615. return expression.type === "NumericLiteral" || expression.type === "BigIntLiteral";
  14616. }
  14617. function isNegativeNumber(expression, estree) {
  14618. if (expression.type === "UnaryExpression") {
  14619. const {
  14620. operator,
  14621. argument
  14622. } = expression;
  14623. if (operator === "-" && isNumber(argument, estree)) {
  14624. return true;
  14625. }
  14626. }
  14627. return false;
  14628. }
  14629. function isUncomputedMemberExpressionChain(expression) {
  14630. if (expression.type === "Identifier") return true;
  14631. if (expression.type !== "MemberExpression" || expression.computed) {
  14632. return false;
  14633. }
  14634. return isUncomputedMemberExpressionChain(expression.object);
  14635. }
  14636. const PlaceholderErrors = ParseErrorEnum`placeholders`({
  14637. ClassNameIsRequired: "A class name is required.",
  14638. UnexpectedSpace: "Unexpected space in placeholder."
  14639. });
  14640. var placeholders = superClass => class PlaceholdersParserMixin extends superClass {
  14641. parsePlaceholder(expectedNode) {
  14642. if (this.match(133)) {
  14643. const node = this.startNode();
  14644. this.next();
  14645. this.assertNoSpace();
  14646. node.name = super.parseIdentifier(true);
  14647. this.assertNoSpace();
  14648. this.expect(133);
  14649. return this.finishPlaceholder(node, expectedNode);
  14650. }
  14651. }
  14652. finishPlaceholder(node, expectedNode) {
  14653. let placeholder = node;
  14654. if (!placeholder.expectedNode || !placeholder.type) {
  14655. placeholder = this.finishNode(placeholder, "Placeholder");
  14656. }
  14657. placeholder.expectedNode = expectedNode;
  14658. return placeholder;
  14659. }
  14660. getTokenFromCode(code) {
  14661. if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
  14662. this.finishOp(133, 2);
  14663. } else {
  14664. super.getTokenFromCode(code);
  14665. }
  14666. }
  14667. parseExprAtom(refExpressionErrors) {
  14668. return this.parsePlaceholder("Expression") || super.parseExprAtom(refExpressionErrors);
  14669. }
  14670. parseIdentifier(liberal) {
  14671. return this.parsePlaceholder("Identifier") || super.parseIdentifier(liberal);
  14672. }
  14673. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  14674. if (word !== undefined) {
  14675. super.checkReservedWord(word, startLoc, checkKeywords, isBinding);
  14676. }
  14677. }
  14678. cloneIdentifier(node) {
  14679. const cloned = super.cloneIdentifier(node);
  14680. if (cloned.type === "Placeholder") {
  14681. cloned.expectedNode = node.expectedNode;
  14682. }
  14683. return cloned;
  14684. }
  14685. cloneStringLiteral(node) {
  14686. if (node.type === "Placeholder") {
  14687. return this.cloneIdentifier(node);
  14688. }
  14689. return super.cloneStringLiteral(node);
  14690. }
  14691. parseBindingAtom() {
  14692. return this.parsePlaceholder("Pattern") || super.parseBindingAtom();
  14693. }
  14694. isValidLVal(type, disallowCallExpression, isParenthesized, binding) {
  14695. return type === "Placeholder" || super.isValidLVal(type, disallowCallExpression, isParenthesized, binding);
  14696. }
  14697. toAssignable(node, isLHS) {
  14698. if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
  14699. node.expectedNode = "Pattern";
  14700. } else {
  14701. super.toAssignable(node, isLHS);
  14702. }
  14703. }
  14704. chStartsBindingIdentifier(ch, pos) {
  14705. if (super.chStartsBindingIdentifier(ch, pos)) {
  14706. return true;
  14707. }
  14708. const next = this.nextTokenStart();
  14709. if (this.input.charCodeAt(next) === 37 && this.input.charCodeAt(next + 1) === 37) {
  14710. return true;
  14711. }
  14712. return false;
  14713. }
  14714. verifyBreakContinue(node, isBreak) {
  14715. var _node$label;
  14716. if (((_node$label = node.label) == null ? void 0 : _node$label.type) === "Placeholder") return;
  14717. super.verifyBreakContinue(node, isBreak);
  14718. }
  14719. parseExpressionStatement(node, expr) {
  14720. var _expr$extra;
  14721. if (expr.type !== "Placeholder" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) {
  14722. return super.parseExpressionStatement(node, expr);
  14723. }
  14724. if (this.match(14)) {
  14725. const stmt = node;
  14726. stmt.label = this.finishPlaceholder(expr, "Identifier");
  14727. this.next();
  14728. stmt.body = super.parseStatementOrSloppyAnnexBFunctionDeclaration();
  14729. return this.finishNode(stmt, "LabeledStatement");
  14730. }
  14731. this.semicolon();
  14732. const stmtPlaceholder = node;
  14733. stmtPlaceholder.name = expr.name;
  14734. return this.finishPlaceholder(stmtPlaceholder, "Statement");
  14735. }
  14736. parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse) {
  14737. return this.parsePlaceholder("BlockStatement") || super.parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse);
  14738. }
  14739. parseFunctionId(requireId) {
  14740. return this.parsePlaceholder("Identifier") || super.parseFunctionId(requireId);
  14741. }
  14742. parseClass(node, isStatement, optionalId) {
  14743. const type = isStatement ? "ClassDeclaration" : "ClassExpression";
  14744. this.next();
  14745. const oldStrict = this.state.strict;
  14746. const placeholder = this.parsePlaceholder("Identifier");
  14747. if (placeholder) {
  14748. if (this.match(81) || this.match(133) || this.match(5)) {
  14749. node.id = placeholder;
  14750. } else if (optionalId || !isStatement) {
  14751. node.id = null;
  14752. node.body = this.finishPlaceholder(placeholder, "ClassBody");
  14753. return this.finishNode(node, type);
  14754. } else {
  14755. throw this.raise(PlaceholderErrors.ClassNameIsRequired, this.state.startLoc);
  14756. }
  14757. } else {
  14758. this.parseClassId(node, isStatement, optionalId);
  14759. }
  14760. super.parseClassSuper(node);
  14761. node.body = this.parsePlaceholder("ClassBody") || super.parseClassBody(!!node.superClass, oldStrict);
  14762. return this.finishNode(node, type);
  14763. }
  14764. parseExport(node, decorators) {
  14765. const placeholder = this.parsePlaceholder("Identifier");
  14766. if (!placeholder) return super.parseExport(node, decorators);
  14767. const node2 = node;
  14768. if (!this.isContextual(98) && !this.match(12)) {
  14769. node2.specifiers = [];
  14770. node2.source = null;
  14771. node2.declaration = this.finishPlaceholder(placeholder, "Declaration");
  14772. return this.finishNode(node2, "ExportNamedDeclaration");
  14773. }
  14774. this.expectPlugin("exportDefaultFrom");
  14775. const specifier = this.startNode();
  14776. specifier.exported = placeholder;
  14777. node2.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  14778. return super.parseExport(node2, decorators);
  14779. }
  14780. isExportDefaultSpecifier() {
  14781. if (this.match(65)) {
  14782. const next = this.nextTokenStart();
  14783. if (this.isUnparsedContextual(next, "from")) {
  14784. if (this.input.startsWith(tokenLabelName(133), this.nextTokenStartSince(next + 4))) {
  14785. return true;
  14786. }
  14787. }
  14788. }
  14789. return super.isExportDefaultSpecifier();
  14790. }
  14791. maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier) {
  14792. var _specifiers;
  14793. if ((_specifiers = node.specifiers) != null && _specifiers.length) {
  14794. return true;
  14795. }
  14796. return super.maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier);
  14797. }
  14798. checkExport(node) {
  14799. const {
  14800. specifiers
  14801. } = node;
  14802. if (specifiers != null && specifiers.length) {
  14803. node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder");
  14804. }
  14805. super.checkExport(node);
  14806. node.specifiers = specifiers;
  14807. }
  14808. parseImport(node) {
  14809. const placeholder = this.parsePlaceholder("Identifier");
  14810. if (!placeholder) return super.parseImport(node);
  14811. node.specifiers = [];
  14812. if (!this.isContextual(98) && !this.match(12)) {
  14813. node.source = this.finishPlaceholder(placeholder, "StringLiteral");
  14814. this.semicolon();
  14815. return this.finishNode(node, "ImportDeclaration");
  14816. }
  14817. const specifier = this.startNodeAtNode(placeholder);
  14818. specifier.local = placeholder;
  14819. node.specifiers.push(this.finishNode(specifier, "ImportDefaultSpecifier"));
  14820. if (this.eat(12)) {
  14821. const hasStarImport = this.maybeParseStarImportSpecifier(node);
  14822. if (!hasStarImport) this.parseNamedImportSpecifiers(node);
  14823. }
  14824. this.expectContextual(98);
  14825. node.source = this.parseImportSource();
  14826. this.semicolon();
  14827. return this.finishNode(node, "ImportDeclaration");
  14828. }
  14829. parseImportSource() {
  14830. return this.parsePlaceholder("StringLiteral") || super.parseImportSource();
  14831. }
  14832. assertNoSpace() {
  14833. if (this.state.start > this.offsetToSourcePos(this.state.lastTokEndLoc.index)) {
  14834. this.raise(PlaceholderErrors.UnexpectedSpace, this.state.lastTokEndLoc);
  14835. }
  14836. }
  14837. };
  14838. var v8intrinsic = superClass => class V8IntrinsicMixin extends superClass {
  14839. parseV8Intrinsic() {
  14840. if (this.match(54)) {
  14841. const v8IntrinsicStartLoc = this.state.startLoc;
  14842. const node = this.startNode();
  14843. this.next();
  14844. if (tokenIsIdentifier(this.state.type)) {
  14845. const name = this.parseIdentifierName();
  14846. const identifier = this.createIdentifier(node, name);
  14847. this.castNodeTo(identifier, "V8IntrinsicIdentifier");
  14848. if (this.match(10)) {
  14849. return identifier;
  14850. }
  14851. }
  14852. this.unexpected(v8IntrinsicStartLoc);
  14853. }
  14854. }
  14855. parseExprAtom(refExpressionErrors) {
  14856. return this.parseV8Intrinsic() || super.parseExprAtom(refExpressionErrors);
  14857. }
  14858. };
  14859. const PIPELINE_PROPOSALS = ["minimal", "fsharp", "hack", "smart"];
  14860. const TOPIC_TOKENS = ["^^", "@@", "^", "%", "#"];
  14861. function validatePlugins(pluginsMap) {
  14862. if (pluginsMap.has("decorators")) {
  14863. if (pluginsMap.has("decorators-legacy")) {
  14864. throw new Error("Cannot use the decorators and decorators-legacy plugin together");
  14865. }
  14866. const decoratorsBeforeExport = pluginsMap.get("decorators").decoratorsBeforeExport;
  14867. if (decoratorsBeforeExport != null && typeof decoratorsBeforeExport !== "boolean") {
  14868. throw new Error("'decoratorsBeforeExport' must be a boolean, if specified.");
  14869. }
  14870. const allowCallParenthesized = pluginsMap.get("decorators").allowCallParenthesized;
  14871. if (allowCallParenthesized != null && typeof allowCallParenthesized !== "boolean") {
  14872. throw new Error("'allowCallParenthesized' must be a boolean.");
  14873. }
  14874. }
  14875. if (pluginsMap.has("flow") && pluginsMap.has("typescript")) {
  14876. throw new Error("Cannot combine flow and typescript plugins.");
  14877. }
  14878. if (pluginsMap.has("placeholders") && pluginsMap.has("v8intrinsic")) {
  14879. throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
  14880. }
  14881. if (pluginsMap.has("pipelineOperator")) {
  14882. var _pluginsMap$get2;
  14883. const proposal = pluginsMap.get("pipelineOperator").proposal;
  14884. if (!PIPELINE_PROPOSALS.includes(proposal)) {
  14885. const proposalList = PIPELINE_PROPOSALS.map(p => `"${p}"`).join(", ");
  14886. throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${proposalList}.`);
  14887. }
  14888. if (proposal === "hack") {
  14889. var _pluginsMap$get;
  14890. if (pluginsMap.has("placeholders")) {
  14891. throw new Error("Cannot combine placeholders plugin and Hack-style pipes.");
  14892. }
  14893. if (pluginsMap.has("v8intrinsic")) {
  14894. throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes.");
  14895. }
  14896. const topicToken = pluginsMap.get("pipelineOperator").topicToken;
  14897. if (!TOPIC_TOKENS.includes(topicToken)) {
  14898. const tokenList = TOPIC_TOKENS.map(t => `"${t}"`).join(", ");
  14899. throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${tokenList}.`);
  14900. }
  14901. if (topicToken === "#" && ((_pluginsMap$get = pluginsMap.get("recordAndTuple")) == null ? void 0 : _pluginsMap$get.syntaxType) === "hash") {
  14902. throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "hack", topicToken: "#" }]\` and \`${JSON.stringify(["recordAndTuple", pluginsMap.get("recordAndTuple")])}\`.`);
  14903. }
  14904. } else if (proposal === "smart" && ((_pluginsMap$get2 = pluginsMap.get("recordAndTuple")) == null ? void 0 : _pluginsMap$get2.syntaxType) === "hash") {
  14905. throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "smart" }]\` and \`${JSON.stringify(["recordAndTuple", pluginsMap.get("recordAndTuple")])}\`.`);
  14906. }
  14907. }
  14908. if (pluginsMap.has("moduleAttributes")) {
  14909. if (pluginsMap.has("deprecatedImportAssert") || pluginsMap.has("importAssertions")) {
  14910. throw new Error("Cannot combine importAssertions, deprecatedImportAssert and moduleAttributes plugins.");
  14911. }
  14912. const moduleAttributesVersionPluginOption = pluginsMap.get("moduleAttributes").version;
  14913. if (moduleAttributesVersionPluginOption !== "may-2020") {
  14914. throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'.");
  14915. }
  14916. }
  14917. if (pluginsMap.has("importAssertions")) {
  14918. if (pluginsMap.has("deprecatedImportAssert")) {
  14919. throw new Error("Cannot combine importAssertions and deprecatedImportAssert plugins.");
  14920. }
  14921. }
  14922. if (pluginsMap.has("deprecatedImportAssert")) ;else if (pluginsMap.has("importAttributes") && pluginsMap.get("importAttributes").deprecatedAssertSyntax) {
  14923. pluginsMap.set("deprecatedImportAssert", {});
  14924. }
  14925. if (pluginsMap.has("recordAndTuple")) {
  14926. const syntaxType = pluginsMap.get("recordAndTuple").syntaxType;
  14927. if (syntaxType != null) {
  14928. const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"];
  14929. if (!RECORD_AND_TUPLE_SYNTAX_TYPES.includes(syntaxType)) {
  14930. throw new Error("The 'syntaxType' option of the 'recordAndTuple' plugin must be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", "));
  14931. }
  14932. }
  14933. }
  14934. if (pluginsMap.has("asyncDoExpressions") && !pluginsMap.has("doExpressions")) {
  14935. const error = new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.");
  14936. error.missingPlugins = "doExpressions";
  14937. throw error;
  14938. }
  14939. if (pluginsMap.has("optionalChainingAssign") && pluginsMap.get("optionalChainingAssign").version !== "2023-07") {
  14940. throw new Error("The 'optionalChainingAssign' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is '2023-07'.");
  14941. }
  14942. if (pluginsMap.has("discardBinding") && pluginsMap.get("discardBinding").syntaxType !== "void") {
  14943. throw new Error("The 'discardBinding' plugin requires a 'syntaxType' option. Currently the only supported value is 'void'.");
  14944. }
  14945. }
  14946. const mixinPlugins = {
  14947. estree,
  14948. jsx,
  14949. flow,
  14950. typescript,
  14951. v8intrinsic,
  14952. placeholders
  14953. };
  14954. const mixinPluginNames = Object.keys(mixinPlugins);
  14955. class ExpressionParser extends LValParser {
  14956. checkProto(prop, isRecord, sawProto, refExpressionErrors) {
  14957. if (prop.type === "SpreadElement" || this.isObjectMethod(prop) || prop.computed || prop.shorthand) {
  14958. return sawProto;
  14959. }
  14960. const key = prop.key;
  14961. const name = key.type === "Identifier" ? key.name : key.value;
  14962. if (name === "__proto__") {
  14963. if (isRecord) {
  14964. this.raise(Errors.RecordNoProto, key);
  14965. return true;
  14966. }
  14967. if (sawProto) {
  14968. if (refExpressionErrors) {
  14969. if (refExpressionErrors.doubleProtoLoc === null) {
  14970. refExpressionErrors.doubleProtoLoc = key.loc.start;
  14971. }
  14972. } else {
  14973. this.raise(Errors.DuplicateProto, key);
  14974. }
  14975. }
  14976. return true;
  14977. }
  14978. return sawProto;
  14979. }
  14980. shouldExitDescending(expr, potentialArrowAt) {
  14981. return expr.type === "ArrowFunctionExpression" && this.offsetToSourcePos(expr.start) === potentialArrowAt;
  14982. }
  14983. getExpression() {
  14984. this.enterInitialScopes();
  14985. this.nextToken();
  14986. if (this.match(140)) {
  14987. throw this.raise(Errors.ParseExpressionEmptyInput, this.state.startLoc);
  14988. }
  14989. const expr = this.parseExpression();
  14990. if (!this.match(140)) {
  14991. throw this.raise(Errors.ParseExpressionExpectsEOF, this.state.startLoc, {
  14992. unexpected: this.input.codePointAt(this.state.start)
  14993. });
  14994. }
  14995. this.finalizeRemainingComments();
  14996. expr.comments = this.comments;
  14997. expr.errors = this.state.errors;
  14998. if (this.optionFlags & 256) {
  14999. expr.tokens = this.tokens;
  15000. }
  15001. return expr;
  15002. }
  15003. parseExpression(disallowIn, refExpressionErrors) {
  15004. if (disallowIn) {
  15005. return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  15006. }
  15007. return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  15008. }
  15009. parseExpressionBase(refExpressionErrors) {
  15010. const startLoc = this.state.startLoc;
  15011. const expr = this.parseMaybeAssign(refExpressionErrors);
  15012. if (this.match(12)) {
  15013. const node = this.startNodeAt(startLoc);
  15014. node.expressions = [expr];
  15015. while (this.eat(12)) {
  15016. node.expressions.push(this.parseMaybeAssign(refExpressionErrors));
  15017. }
  15018. this.toReferencedList(node.expressions);
  15019. return this.finishNode(node, "SequenceExpression");
  15020. }
  15021. return expr;
  15022. }
  15023. parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse) {
  15024. return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
  15025. }
  15026. parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse) {
  15027. return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
  15028. }
  15029. setOptionalParametersError(refExpressionErrors) {
  15030. refExpressionErrors.optionalParametersLoc = this.state.startLoc;
  15031. }
  15032. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  15033. const startLoc = this.state.startLoc;
  15034. const isYield = this.isContextual(108);
  15035. if (isYield) {
  15036. if (this.prodParam.hasYield) {
  15037. this.next();
  15038. let left = this.parseYield(startLoc);
  15039. if (afterLeftParse) {
  15040. left = afterLeftParse.call(this, left, startLoc);
  15041. }
  15042. return left;
  15043. }
  15044. }
  15045. let ownExpressionErrors;
  15046. if (refExpressionErrors) {
  15047. ownExpressionErrors = false;
  15048. } else {
  15049. refExpressionErrors = new ExpressionErrors();
  15050. ownExpressionErrors = true;
  15051. }
  15052. const {
  15053. type
  15054. } = this.state;
  15055. if (type === 10 || tokenIsIdentifier(type)) {
  15056. this.state.potentialArrowAt = this.state.start;
  15057. }
  15058. let left = this.parseMaybeConditional(refExpressionErrors);
  15059. if (afterLeftParse) {
  15060. left = afterLeftParse.call(this, left, startLoc);
  15061. }
  15062. if (tokenIsAssignment(this.state.type)) {
  15063. const node = this.startNodeAt(startLoc);
  15064. const operator = this.state.value;
  15065. node.operator = operator;
  15066. if (this.match(29)) {
  15067. this.toAssignable(left, true);
  15068. node.left = left;
  15069. const startIndex = startLoc.index;
  15070. if (refExpressionErrors.doubleProtoLoc != null && refExpressionErrors.doubleProtoLoc.index >= startIndex) {
  15071. refExpressionErrors.doubleProtoLoc = null;
  15072. }
  15073. if (refExpressionErrors.shorthandAssignLoc != null && refExpressionErrors.shorthandAssignLoc.index >= startIndex) {
  15074. refExpressionErrors.shorthandAssignLoc = null;
  15075. }
  15076. if (refExpressionErrors.privateKeyLoc != null && refExpressionErrors.privateKeyLoc.index >= startIndex) {
  15077. this.checkDestructuringPrivate(refExpressionErrors);
  15078. refExpressionErrors.privateKeyLoc = null;
  15079. }
  15080. if (refExpressionErrors.voidPatternLoc != null && refExpressionErrors.voidPatternLoc.index >= startIndex) {
  15081. refExpressionErrors.voidPatternLoc = null;
  15082. }
  15083. } else {
  15084. node.left = left;
  15085. }
  15086. this.next();
  15087. node.right = this.parseMaybeAssign();
  15088. this.checkLVal(left, this.finishNode(node, "AssignmentExpression"), undefined, undefined, undefined, undefined, operator === "||=" || operator === "&&=" || operator === "??=");
  15089. return node;
  15090. } else if (ownExpressionErrors) {
  15091. this.checkExpressionErrors(refExpressionErrors, true);
  15092. }
  15093. if (isYield) {
  15094. const {
  15095. type
  15096. } = this.state;
  15097. const startsExpr = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(54);
  15098. if (startsExpr && !this.isAmbiguousPrefixOrIdentifier()) {
  15099. this.raiseOverwrite(Errors.YieldNotInGeneratorFunction, startLoc);
  15100. return this.parseYield(startLoc);
  15101. }
  15102. }
  15103. return left;
  15104. }
  15105. parseMaybeConditional(refExpressionErrors) {
  15106. const startLoc = this.state.startLoc;
  15107. const potentialArrowAt = this.state.potentialArrowAt;
  15108. const expr = this.parseExprOps(refExpressionErrors);
  15109. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  15110. return expr;
  15111. }
  15112. return this.parseConditional(expr, startLoc, refExpressionErrors);
  15113. }
  15114. parseConditional(expr, startLoc, refExpressionErrors) {
  15115. if (this.eat(17)) {
  15116. const node = this.startNodeAt(startLoc);
  15117. node.test = expr;
  15118. node.consequent = this.parseMaybeAssignAllowIn();
  15119. this.expect(14);
  15120. node.alternate = this.parseMaybeAssign();
  15121. return this.finishNode(node, "ConditionalExpression");
  15122. }
  15123. return expr;
  15124. }
  15125. parseMaybeUnaryOrPrivate(refExpressionErrors) {
  15126. return this.match(139) ? this.parsePrivateName() : this.parseMaybeUnary(refExpressionErrors);
  15127. }
  15128. parseExprOps(refExpressionErrors) {
  15129. const startLoc = this.state.startLoc;
  15130. const potentialArrowAt = this.state.potentialArrowAt;
  15131. const expr = this.parseMaybeUnaryOrPrivate(refExpressionErrors);
  15132. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  15133. return expr;
  15134. }
  15135. return this.parseExprOp(expr, startLoc, -1);
  15136. }
  15137. parseExprOp(left, leftStartLoc, minPrec) {
  15138. if (this.isPrivateName(left)) {
  15139. const value = this.getPrivateNameSV(left);
  15140. if (minPrec >= tokenOperatorPrecedence(58) || !this.prodParam.hasIn || !this.match(58)) {
  15141. this.raise(Errors.PrivateInExpectedIn, left, {
  15142. identifierName: value
  15143. });
  15144. }
  15145. this.classScope.usePrivateName(value, left.loc.start);
  15146. }
  15147. const op = this.state.type;
  15148. if (tokenIsOperator(op) && (this.prodParam.hasIn || !this.match(58))) {
  15149. let prec = tokenOperatorPrecedence(op);
  15150. if (prec > minPrec) {
  15151. if (op === 39) {
  15152. this.expectPlugin("pipelineOperator");
  15153. if (this.state.inFSharpPipelineDirectBody) {
  15154. return left;
  15155. }
  15156. this.checkPipelineAtInfixOperator(left, leftStartLoc);
  15157. }
  15158. const node = this.startNodeAt(leftStartLoc);
  15159. node.left = left;
  15160. node.operator = this.state.value;
  15161. const logical = op === 41 || op === 42;
  15162. const coalesce = op === 40;
  15163. if (coalesce) {
  15164. prec = tokenOperatorPrecedence(42);
  15165. }
  15166. this.next();
  15167. if (op === 39 && this.hasPlugin(["pipelineOperator", {
  15168. proposal: "minimal"
  15169. }])) {
  15170. if (this.state.type === 96 && this.prodParam.hasAwait) {
  15171. throw this.raise(Errors.UnexpectedAwaitAfterPipelineBody, this.state.startLoc);
  15172. }
  15173. }
  15174. node.right = this.parseExprOpRightExpr(op, prec);
  15175. const finishedNode = this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression");
  15176. const nextOp = this.state.type;
  15177. if (coalesce && (nextOp === 41 || nextOp === 42) || logical && nextOp === 40) {
  15178. throw this.raise(Errors.MixingCoalesceWithLogical, this.state.startLoc);
  15179. }
  15180. return this.parseExprOp(finishedNode, leftStartLoc, minPrec);
  15181. }
  15182. }
  15183. return left;
  15184. }
  15185. parseExprOpRightExpr(op, prec) {
  15186. const startLoc = this.state.startLoc;
  15187. switch (op) {
  15188. case 39:
  15189. switch (this.getPluginOption("pipelineOperator", "proposal")) {
  15190. case "hack":
  15191. return this.withTopicBindingContext(() => {
  15192. return this.parseHackPipeBody();
  15193. });
  15194. case "fsharp":
  15195. return this.withSoloAwaitPermittingContext(() => {
  15196. return this.parseFSharpPipelineBody(prec);
  15197. });
  15198. }
  15199. if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  15200. return this.withTopicBindingContext(() => {
  15201. if (this.prodParam.hasYield && this.isContextual(108)) {
  15202. throw this.raise(Errors.PipeBodyIsTighter, this.state.startLoc);
  15203. }
  15204. return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(op, prec), startLoc);
  15205. });
  15206. }
  15207. default:
  15208. return this.parseExprOpBaseRightExpr(op, prec);
  15209. }
  15210. }
  15211. parseExprOpBaseRightExpr(op, prec) {
  15212. const startLoc = this.state.startLoc;
  15213. return this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, tokenIsRightAssociative(op) ? prec - 1 : prec);
  15214. }
  15215. parseHackPipeBody() {
  15216. var _body$extra;
  15217. const {
  15218. startLoc
  15219. } = this.state;
  15220. const body = this.parseMaybeAssign();
  15221. const requiredParentheses = UnparenthesizedPipeBodyDescriptions.has(body.type);
  15222. if (requiredParentheses && !((_body$extra = body.extra) != null && _body$extra.parenthesized)) {
  15223. this.raise(Errors.PipeUnparenthesizedBody, startLoc, {
  15224. type: body.type
  15225. });
  15226. }
  15227. if (!this.topicReferenceWasUsedInCurrentContext()) {
  15228. this.raise(Errors.PipeTopicUnused, startLoc);
  15229. }
  15230. return body;
  15231. }
  15232. checkExponentialAfterUnary(node) {
  15233. if (this.match(57)) {
  15234. this.raise(Errors.UnexpectedTokenUnaryExponentiation, node.argument);
  15235. }
  15236. }
  15237. parseMaybeUnary(refExpressionErrors, sawUnary) {
  15238. const startLoc = this.state.startLoc;
  15239. const isAwait = this.isContextual(96);
  15240. if (isAwait && this.recordAwaitIfAllowed()) {
  15241. this.next();
  15242. const expr = this.parseAwait(startLoc);
  15243. if (!sawUnary) this.checkExponentialAfterUnary(expr);
  15244. return expr;
  15245. }
  15246. const update = this.match(34);
  15247. const node = this.startNode();
  15248. if (tokenIsPrefix(this.state.type)) {
  15249. node.operator = this.state.value;
  15250. node.prefix = true;
  15251. if (this.match(72)) {
  15252. this.expectPlugin("throwExpressions");
  15253. }
  15254. const isDelete = this.match(89);
  15255. this.next();
  15256. node.argument = this.parseMaybeUnary(null, true);
  15257. this.checkExpressionErrors(refExpressionErrors, true);
  15258. if (this.state.strict && isDelete) {
  15259. const arg = node.argument;
  15260. if (arg.type === "Identifier") {
  15261. this.raise(Errors.StrictDelete, node);
  15262. } else if (this.hasPropertyAsPrivateName(arg)) {
  15263. this.raise(Errors.DeletePrivateField, node);
  15264. }
  15265. }
  15266. if (!update) {
  15267. if (!sawUnary) {
  15268. this.checkExponentialAfterUnary(node);
  15269. }
  15270. return this.finishNode(node, "UnaryExpression");
  15271. }
  15272. }
  15273. const expr = this.parseUpdate(node, update, refExpressionErrors);
  15274. if (isAwait) {
  15275. const {
  15276. type
  15277. } = this.state;
  15278. const startsExpr = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(54);
  15279. if (startsExpr && !this.isAmbiguousPrefixOrIdentifier()) {
  15280. this.raiseOverwrite(Errors.AwaitNotInAsyncContext, startLoc);
  15281. return this.parseAwait(startLoc);
  15282. }
  15283. }
  15284. return expr;
  15285. }
  15286. parseUpdate(node, update, refExpressionErrors) {
  15287. if (update) {
  15288. const updateExpressionNode = node;
  15289. this.checkLVal(updateExpressionNode.argument, this.finishNode(updateExpressionNode, "UpdateExpression"));
  15290. return node;
  15291. }
  15292. const startLoc = this.state.startLoc;
  15293. let expr = this.parseExprSubscripts(refExpressionErrors);
  15294. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  15295. while (tokenIsPostfix(this.state.type) && !this.canInsertSemicolon()) {
  15296. const node = this.startNodeAt(startLoc);
  15297. node.operator = this.state.value;
  15298. node.prefix = false;
  15299. node.argument = expr;
  15300. this.next();
  15301. this.checkLVal(expr, expr = this.finishNode(node, "UpdateExpression"));
  15302. }
  15303. return expr;
  15304. }
  15305. parseExprSubscripts(refExpressionErrors) {
  15306. const startLoc = this.state.startLoc;
  15307. const potentialArrowAt = this.state.potentialArrowAt;
  15308. const expr = this.parseExprAtom(refExpressionErrors);
  15309. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  15310. return expr;
  15311. }
  15312. return this.parseSubscripts(expr, startLoc);
  15313. }
  15314. parseSubscripts(base, startLoc, noCalls) {
  15315. const state = {
  15316. optionalChainMember: false,
  15317. maybeAsyncArrow: this.atPossibleAsyncArrow(base),
  15318. stop: false
  15319. };
  15320. do {
  15321. base = this.parseSubscript(base, startLoc, noCalls, state);
  15322. state.maybeAsyncArrow = false;
  15323. } while (!state.stop);
  15324. return base;
  15325. }
  15326. parseSubscript(base, startLoc, noCalls, state) {
  15327. const {
  15328. type
  15329. } = this.state;
  15330. if (!noCalls && type === 15) {
  15331. return this.parseBind(base, startLoc, noCalls, state);
  15332. } else if (tokenIsTemplate(type)) {
  15333. return this.parseTaggedTemplateExpression(base, startLoc, state);
  15334. }
  15335. let optional = false;
  15336. if (type === 18) {
  15337. if (noCalls) {
  15338. this.raise(Errors.OptionalChainingNoNew, this.state.startLoc);
  15339. if (this.lookaheadCharCode() === 40) {
  15340. return this.stopParseSubscript(base, state);
  15341. }
  15342. }
  15343. state.optionalChainMember = optional = true;
  15344. this.next();
  15345. }
  15346. if (!noCalls && this.match(10)) {
  15347. return this.parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional);
  15348. } else {
  15349. const computed = this.eat(0);
  15350. if (computed || optional || this.eat(16)) {
  15351. return this.parseMember(base, startLoc, state, computed, optional);
  15352. } else {
  15353. return this.stopParseSubscript(base, state);
  15354. }
  15355. }
  15356. }
  15357. stopParseSubscript(base, state) {
  15358. state.stop = true;
  15359. return base;
  15360. }
  15361. parseMember(base, startLoc, state, computed, optional) {
  15362. const node = this.startNodeAt(startLoc);
  15363. node.object = base;
  15364. node.computed = computed;
  15365. if (computed) {
  15366. node.property = this.parseExpression();
  15367. this.expect(3);
  15368. } else if (this.match(139)) {
  15369. if (base.type === "Super") {
  15370. this.raise(Errors.SuperPrivateField, startLoc);
  15371. }
  15372. this.classScope.usePrivateName(this.state.value, this.state.startLoc);
  15373. node.property = this.parsePrivateName();
  15374. } else {
  15375. node.property = this.parseIdentifier(true);
  15376. }
  15377. if (state.optionalChainMember) {
  15378. node.optional = optional;
  15379. return this.finishNode(node, "OptionalMemberExpression");
  15380. } else {
  15381. return this.finishNode(node, "MemberExpression");
  15382. }
  15383. }
  15384. parseBind(base, startLoc, noCalls, state) {
  15385. const node = this.startNodeAt(startLoc);
  15386. node.object = base;
  15387. this.next();
  15388. node.callee = this.parseNoCallExpr();
  15389. state.stop = true;
  15390. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startLoc, noCalls);
  15391. }
  15392. parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional) {
  15393. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  15394. let refExpressionErrors = null;
  15395. this.state.maybeInArrowParameters = true;
  15396. this.next();
  15397. const node = this.startNodeAt(startLoc);
  15398. node.callee = base;
  15399. const {
  15400. maybeAsyncArrow,
  15401. optionalChainMember
  15402. } = state;
  15403. if (maybeAsyncArrow) {
  15404. this.expressionScope.enter(newAsyncArrowScope());
  15405. refExpressionErrors = new ExpressionErrors();
  15406. }
  15407. if (optionalChainMember) {
  15408. node.optional = optional;
  15409. }
  15410. if (optional) {
  15411. node.arguments = this.parseCallExpressionArguments();
  15412. } else {
  15413. node.arguments = this.parseCallExpressionArguments(base.type !== "Super", node, refExpressionErrors);
  15414. }
  15415. let finishedNode = this.finishCallExpression(node, optionalChainMember);
  15416. if (maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
  15417. state.stop = true;
  15418. this.checkDestructuringPrivate(refExpressionErrors);
  15419. this.expressionScope.validateAsPattern();
  15420. this.expressionScope.exit();
  15421. finishedNode = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startLoc), finishedNode);
  15422. } else {
  15423. if (maybeAsyncArrow) {
  15424. this.checkExpressionErrors(refExpressionErrors, true);
  15425. this.expressionScope.exit();
  15426. }
  15427. this.toReferencedArguments(finishedNode);
  15428. }
  15429. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  15430. return finishedNode;
  15431. }
  15432. toReferencedArguments(node, isParenthesizedExpr) {
  15433. this.toReferencedListDeep(node.arguments, isParenthesizedExpr);
  15434. }
  15435. parseTaggedTemplateExpression(base, startLoc, state) {
  15436. const node = this.startNodeAt(startLoc);
  15437. node.tag = base;
  15438. node.quasi = this.parseTemplate(true);
  15439. if (state.optionalChainMember) {
  15440. this.raise(Errors.OptionalChainingNoTemplate, startLoc);
  15441. }
  15442. return this.finishNode(node, "TaggedTemplateExpression");
  15443. }
  15444. atPossibleAsyncArrow(base) {
  15445. return base.type === "Identifier" && base.name === "async" && this.state.lastTokEndLoc.index === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && this.offsetToSourcePos(base.start) === this.state.potentialArrowAt;
  15446. }
  15447. finishCallExpression(node, optional) {
  15448. if (node.callee.type === "Import") {
  15449. if (node.arguments.length === 0 || node.arguments.length > 2) {
  15450. this.raise(Errors.ImportCallArity, node);
  15451. } else {
  15452. for (const arg of node.arguments) {
  15453. if (arg.type === "SpreadElement") {
  15454. this.raise(Errors.ImportCallSpreadArgument, arg);
  15455. }
  15456. }
  15457. }
  15458. }
  15459. return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
  15460. }
  15461. parseCallExpressionArguments(allowPlaceholder, nodeForExtra, refExpressionErrors) {
  15462. const elts = [];
  15463. let first = true;
  15464. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  15465. this.state.inFSharpPipelineDirectBody = false;
  15466. while (!this.eat(11)) {
  15467. if (first) {
  15468. first = false;
  15469. } else {
  15470. this.expect(12);
  15471. if (this.match(11)) {
  15472. if (nodeForExtra) {
  15473. this.addTrailingCommaExtraToNode(nodeForExtra);
  15474. }
  15475. this.next();
  15476. break;
  15477. }
  15478. }
  15479. elts.push(this.parseExprListItem(11, false, refExpressionErrors, allowPlaceholder));
  15480. }
  15481. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  15482. return elts;
  15483. }
  15484. shouldParseAsyncArrow() {
  15485. return this.match(19) && !this.canInsertSemicolon();
  15486. }
  15487. parseAsyncArrowFromCallExpression(node, call) {
  15488. var _call$extra;
  15489. this.resetPreviousNodeTrailingComments(call);
  15490. this.expect(19);
  15491. this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingCommaLoc);
  15492. if (call.innerComments) {
  15493. setInnerComments(node, call.innerComments);
  15494. }
  15495. if (call.callee.trailingComments) {
  15496. setInnerComments(node, call.callee.trailingComments);
  15497. }
  15498. return node;
  15499. }
  15500. parseNoCallExpr() {
  15501. const startLoc = this.state.startLoc;
  15502. return this.parseSubscripts(this.parseExprAtom(), startLoc, true);
  15503. }
  15504. parseExprAtom(refExpressionErrors) {
  15505. let node;
  15506. let decorators = null;
  15507. const {
  15508. type
  15509. } = this.state;
  15510. switch (type) {
  15511. case 79:
  15512. return this.parseSuper();
  15513. case 83:
  15514. node = this.startNode();
  15515. this.next();
  15516. if (this.match(16)) {
  15517. return this.parseImportMetaPropertyOrPhaseCall(node);
  15518. }
  15519. if (this.match(10)) {
  15520. if (this.optionFlags & 512) {
  15521. return this.parseImportCall(node);
  15522. } else {
  15523. return this.finishNode(node, "Import");
  15524. }
  15525. } else {
  15526. this.raise(Errors.UnsupportedImport, this.state.lastTokStartLoc);
  15527. return this.finishNode(node, "Import");
  15528. }
  15529. case 78:
  15530. node = this.startNode();
  15531. this.next();
  15532. return this.finishNode(node, "ThisExpression");
  15533. case 90:
  15534. {
  15535. return this.parseDo(this.startNode(), false);
  15536. }
  15537. case 56:
  15538. case 31:
  15539. {
  15540. this.readRegexp();
  15541. return this.parseRegExpLiteral(this.state.value);
  15542. }
  15543. case 135:
  15544. return this.parseNumericLiteral(this.state.value);
  15545. case 136:
  15546. return this.parseBigIntLiteral(this.state.value);
  15547. case 134:
  15548. return this.parseStringLiteral(this.state.value);
  15549. case 84:
  15550. return this.parseNullLiteral();
  15551. case 85:
  15552. return this.parseBooleanLiteral(true);
  15553. case 86:
  15554. return this.parseBooleanLiteral(false);
  15555. case 10:
  15556. {
  15557. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  15558. return this.parseParenAndDistinguishExpression(canBeArrow);
  15559. }
  15560. case 0:
  15561. {
  15562. return this.parseArrayLike(3, false, refExpressionErrors);
  15563. }
  15564. case 5:
  15565. {
  15566. return this.parseObjectLike(8, false, false, refExpressionErrors);
  15567. }
  15568. case 68:
  15569. return this.parseFunctionOrFunctionSent();
  15570. case 26:
  15571. decorators = this.parseDecorators();
  15572. case 80:
  15573. return this.parseClass(this.maybeTakeDecorators(decorators, this.startNode()), false);
  15574. case 77:
  15575. return this.parseNewOrNewTarget();
  15576. case 25:
  15577. case 24:
  15578. return this.parseTemplate(false);
  15579. case 15:
  15580. {
  15581. node = this.startNode();
  15582. this.next();
  15583. node.object = null;
  15584. const callee = node.callee = this.parseNoCallExpr();
  15585. if (callee.type === "MemberExpression") {
  15586. return this.finishNode(node, "BindExpression");
  15587. } else {
  15588. throw this.raise(Errors.UnsupportedBind, callee);
  15589. }
  15590. }
  15591. case 139:
  15592. {
  15593. this.raise(Errors.PrivateInExpectedIn, this.state.startLoc, {
  15594. identifierName: this.state.value
  15595. });
  15596. return this.parsePrivateName();
  15597. }
  15598. case 33:
  15599. {
  15600. return this.parseTopicReferenceThenEqualsSign(54, "%");
  15601. }
  15602. case 32:
  15603. {
  15604. return this.parseTopicReferenceThenEqualsSign(44, "^");
  15605. }
  15606. case 37:
  15607. case 38:
  15608. {
  15609. return this.parseTopicReference("hack");
  15610. }
  15611. case 44:
  15612. case 54:
  15613. case 27:
  15614. {
  15615. const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
  15616. if (pipeProposal) {
  15617. return this.parseTopicReference(pipeProposal);
  15618. }
  15619. throw this.unexpected();
  15620. }
  15621. case 47:
  15622. {
  15623. const lookaheadCh = this.input.codePointAt(this.nextTokenStart());
  15624. if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) {
  15625. throw this.expectOnePlugin(["jsx", "flow", "typescript"]);
  15626. }
  15627. throw this.unexpected();
  15628. }
  15629. default:
  15630. if (type === 137) {
  15631. return this.parseDecimalLiteral(this.state.value);
  15632. } else if (type === 2 || type === 1) {
  15633. return this.parseArrayLike(this.state.type === 2 ? 4 : 3, true);
  15634. } else if (type === 6 || type === 7) {
  15635. return this.parseObjectLike(this.state.type === 6 ? 9 : 8, false, true);
  15636. }
  15637. if (tokenIsIdentifier(type)) {
  15638. if (this.isContextual(127) && this.lookaheadInLineCharCode() === 123) {
  15639. return this.parseModuleExpression();
  15640. }
  15641. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  15642. const containsEsc = this.state.containsEsc;
  15643. const id = this.parseIdentifier();
  15644. if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) {
  15645. const {
  15646. type
  15647. } = this.state;
  15648. if (type === 68) {
  15649. this.resetPreviousNodeTrailingComments(id);
  15650. this.next();
  15651. return this.parseAsyncFunctionExpression(this.startNodeAtNode(id));
  15652. } else if (tokenIsIdentifier(type)) {
  15653. if (canBeArrow && this.lookaheadCharCode() === 61) {
  15654. return this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(id));
  15655. } else {
  15656. return id;
  15657. }
  15658. } else if (type === 90) {
  15659. this.resetPreviousNodeTrailingComments(id);
  15660. return this.parseDo(this.startNodeAtNode(id), true);
  15661. }
  15662. }
  15663. if (canBeArrow && this.match(19) && !this.canInsertSemicolon()) {
  15664. this.next();
  15665. return this.parseArrowExpression(this.startNodeAtNode(id), [id], false);
  15666. }
  15667. return id;
  15668. } else {
  15669. throw this.unexpected();
  15670. }
  15671. }
  15672. }
  15673. parseTopicReferenceThenEqualsSign(topicTokenType, topicTokenValue) {
  15674. const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
  15675. if (pipeProposal) {
  15676. this.state.type = topicTokenType;
  15677. this.state.value = topicTokenValue;
  15678. this.state.pos--;
  15679. this.state.end--;
  15680. this.state.endLoc = createPositionWithColumnOffset(this.state.endLoc, -1);
  15681. return this.parseTopicReference(pipeProposal);
  15682. }
  15683. throw this.unexpected();
  15684. }
  15685. parseTopicReference(pipeProposal) {
  15686. const node = this.startNode();
  15687. const startLoc = this.state.startLoc;
  15688. const tokenType = this.state.type;
  15689. this.next();
  15690. return this.finishTopicReference(node, startLoc, pipeProposal, tokenType);
  15691. }
  15692. finishTopicReference(node, startLoc, pipeProposal, tokenType) {
  15693. if (this.testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType)) {
  15694. if (pipeProposal === "hack") {
  15695. if (!this.topicReferenceIsAllowedInCurrentContext()) {
  15696. this.raise(Errors.PipeTopicUnbound, startLoc);
  15697. }
  15698. this.registerTopicReference();
  15699. return this.finishNode(node, "TopicReference");
  15700. } else {
  15701. if (!this.topicReferenceIsAllowedInCurrentContext()) {
  15702. this.raise(Errors.PrimaryTopicNotAllowed, startLoc);
  15703. }
  15704. this.registerTopicReference();
  15705. return this.finishNode(node, "PipelinePrimaryTopicReference");
  15706. }
  15707. } else {
  15708. throw this.raise(Errors.PipeTopicUnconfiguredToken, startLoc, {
  15709. token: tokenLabelName(tokenType)
  15710. });
  15711. }
  15712. }
  15713. testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType) {
  15714. switch (pipeProposal) {
  15715. case "hack":
  15716. {
  15717. return this.hasPlugin(["pipelineOperator", {
  15718. topicToken: tokenLabelName(tokenType)
  15719. }]);
  15720. }
  15721. case "smart":
  15722. return tokenType === 27;
  15723. default:
  15724. throw this.raise(Errors.PipeTopicRequiresHackPipes, startLoc);
  15725. }
  15726. }
  15727. parseAsyncArrowUnaryFunction(node) {
  15728. this.prodParam.enter(functionFlags(true, this.prodParam.hasYield));
  15729. const params = [this.parseIdentifier()];
  15730. this.prodParam.exit();
  15731. if (this.hasPrecedingLineBreak()) {
  15732. this.raise(Errors.LineTerminatorBeforeArrow, this.state.curPosition());
  15733. }
  15734. this.expect(19);
  15735. return this.parseArrowExpression(node, params, true);
  15736. }
  15737. parseDo(node, isAsync) {
  15738. this.expectPlugin("doExpressions");
  15739. if (isAsync) {
  15740. this.expectPlugin("asyncDoExpressions");
  15741. }
  15742. node.async = isAsync;
  15743. this.next();
  15744. const oldLabels = this.state.labels;
  15745. this.state.labels = [];
  15746. if (isAsync) {
  15747. this.prodParam.enter(2);
  15748. node.body = this.parseBlock();
  15749. this.prodParam.exit();
  15750. } else {
  15751. node.body = this.parseBlock();
  15752. }
  15753. this.state.labels = oldLabels;
  15754. return this.finishNode(node, "DoExpression");
  15755. }
  15756. parseSuper() {
  15757. const node = this.startNode();
  15758. this.next();
  15759. if (this.match(10) && !this.scope.allowDirectSuper) {
  15760. if (!(this.optionFlags & 16)) {
  15761. this.raise(Errors.SuperNotAllowed, node);
  15762. }
  15763. } else if (!this.scope.allowSuper) {
  15764. if (!(this.optionFlags & 16)) {
  15765. this.raise(Errors.UnexpectedSuper, node);
  15766. }
  15767. }
  15768. if (!this.match(10) && !this.match(0) && !this.match(16)) {
  15769. this.raise(Errors.UnsupportedSuper, node);
  15770. }
  15771. return this.finishNode(node, "Super");
  15772. }
  15773. parsePrivateName() {
  15774. const node = this.startNode();
  15775. const id = this.startNodeAt(createPositionWithColumnOffset(this.state.startLoc, 1));
  15776. const name = this.state.value;
  15777. this.next();
  15778. node.id = this.createIdentifier(id, name);
  15779. return this.finishNode(node, "PrivateName");
  15780. }
  15781. parseFunctionOrFunctionSent() {
  15782. const node = this.startNode();
  15783. this.next();
  15784. if (this.prodParam.hasYield && this.match(16)) {
  15785. const meta = this.createIdentifier(this.startNodeAtNode(node), "function");
  15786. this.next();
  15787. if (this.match(103)) {
  15788. this.expectPlugin("functionSent");
  15789. } else if (!this.hasPlugin("functionSent")) {
  15790. this.unexpected();
  15791. }
  15792. return this.parseMetaProperty(node, meta, "sent");
  15793. }
  15794. return this.parseFunction(node);
  15795. }
  15796. parseMetaProperty(node, meta, propertyName) {
  15797. node.meta = meta;
  15798. const containsEsc = this.state.containsEsc;
  15799. node.property = this.parseIdentifier(true);
  15800. if (node.property.name !== propertyName || containsEsc) {
  15801. this.raise(Errors.UnsupportedMetaProperty, node.property, {
  15802. target: meta.name,
  15803. onlyValidPropertyName: propertyName
  15804. });
  15805. }
  15806. return this.finishNode(node, "MetaProperty");
  15807. }
  15808. parseImportMetaPropertyOrPhaseCall(node) {
  15809. this.next();
  15810. if (this.isContextual(105) || this.isContextual(97)) {
  15811. const isSource = this.isContextual(105);
  15812. this.expectPlugin(isSource ? "sourcePhaseImports" : "deferredImportEvaluation");
  15813. this.next();
  15814. node.phase = isSource ? "source" : "defer";
  15815. return this.parseImportCall(node);
  15816. } else {
  15817. const id = this.createIdentifierAt(this.startNodeAtNode(node), "import", this.state.lastTokStartLoc);
  15818. if (this.isContextual(101)) {
  15819. if (!this.inModule) {
  15820. this.raise(Errors.ImportMetaOutsideModule, id);
  15821. }
  15822. this.sawUnambiguousESM = true;
  15823. }
  15824. return this.parseMetaProperty(node, id, "meta");
  15825. }
  15826. }
  15827. parseLiteralAtNode(value, type, node) {
  15828. this.addExtra(node, "rawValue", value);
  15829. this.addExtra(node, "raw", this.input.slice(this.offsetToSourcePos(node.start), this.state.end));
  15830. node.value = value;
  15831. this.next();
  15832. return this.finishNode(node, type);
  15833. }
  15834. parseLiteral(value, type) {
  15835. const node = this.startNode();
  15836. return this.parseLiteralAtNode(value, type, node);
  15837. }
  15838. parseStringLiteral(value) {
  15839. return this.parseLiteral(value, "StringLiteral");
  15840. }
  15841. parseNumericLiteral(value) {
  15842. return this.parseLiteral(value, "NumericLiteral");
  15843. }
  15844. parseBigIntLiteral(value) {
  15845. return this.parseLiteral(value, "BigIntLiteral");
  15846. }
  15847. parseDecimalLiteral(value) {
  15848. return this.parseLiteral(value, "DecimalLiteral");
  15849. }
  15850. parseRegExpLiteral(value) {
  15851. const node = this.startNode();
  15852. this.addExtra(node, "raw", this.input.slice(this.offsetToSourcePos(node.start), this.state.end));
  15853. node.pattern = value.pattern;
  15854. node.flags = value.flags;
  15855. this.next();
  15856. return this.finishNode(node, "RegExpLiteral");
  15857. }
  15858. parseBooleanLiteral(value) {
  15859. const node = this.startNode();
  15860. node.value = value;
  15861. this.next();
  15862. return this.finishNode(node, "BooleanLiteral");
  15863. }
  15864. parseNullLiteral() {
  15865. const node = this.startNode();
  15866. this.next();
  15867. return this.finishNode(node, "NullLiteral");
  15868. }
  15869. parseParenAndDistinguishExpression(canBeArrow) {
  15870. const startLoc = this.state.startLoc;
  15871. let val;
  15872. this.next();
  15873. this.expressionScope.enter(newArrowHeadScope());
  15874. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  15875. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  15876. this.state.maybeInArrowParameters = true;
  15877. this.state.inFSharpPipelineDirectBody = false;
  15878. const innerStartLoc = this.state.startLoc;
  15879. const exprList = [];
  15880. const refExpressionErrors = new ExpressionErrors();
  15881. let first = true;
  15882. let spreadStartLoc;
  15883. let optionalCommaStartLoc;
  15884. while (!this.match(11)) {
  15885. if (first) {
  15886. first = false;
  15887. } else {
  15888. this.expect(12, refExpressionErrors.optionalParametersLoc === null ? null : refExpressionErrors.optionalParametersLoc);
  15889. if (this.match(11)) {
  15890. optionalCommaStartLoc = this.state.startLoc;
  15891. break;
  15892. }
  15893. }
  15894. if (this.match(21)) {
  15895. const spreadNodeStartLoc = this.state.startLoc;
  15896. spreadStartLoc = this.state.startLoc;
  15897. exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartLoc));
  15898. if (!this.checkCommaAfterRest(41)) {
  15899. break;
  15900. }
  15901. } else {
  15902. exprList.push(this.parseMaybeAssignAllowInOrVoidPattern(11, refExpressionErrors, this.parseParenItem));
  15903. }
  15904. }
  15905. const innerEndLoc = this.state.lastTokEndLoc;
  15906. this.expect(11);
  15907. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  15908. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  15909. let arrowNode = this.startNodeAt(startLoc);
  15910. if (canBeArrow && this.shouldParseArrow(exprList) && (arrowNode = this.parseArrow(arrowNode))) {
  15911. this.checkDestructuringPrivate(refExpressionErrors);
  15912. this.expressionScope.validateAsPattern();
  15913. this.expressionScope.exit();
  15914. this.parseArrowExpression(arrowNode, exprList, false);
  15915. return arrowNode;
  15916. }
  15917. this.expressionScope.exit();
  15918. if (!exprList.length) {
  15919. this.unexpected(this.state.lastTokStartLoc);
  15920. }
  15921. if (optionalCommaStartLoc) this.unexpected(optionalCommaStartLoc);
  15922. if (spreadStartLoc) this.unexpected(spreadStartLoc);
  15923. this.checkExpressionErrors(refExpressionErrors, true);
  15924. this.toReferencedListDeep(exprList, true);
  15925. if (exprList.length > 1) {
  15926. val = this.startNodeAt(innerStartLoc);
  15927. val.expressions = exprList;
  15928. this.finishNode(val, "SequenceExpression");
  15929. this.resetEndLocation(val, innerEndLoc);
  15930. } else {
  15931. val = exprList[0];
  15932. }
  15933. return this.wrapParenthesis(startLoc, val);
  15934. }
  15935. wrapParenthesis(startLoc, expression) {
  15936. if (!(this.optionFlags & 1024)) {
  15937. this.addExtra(expression, "parenthesized", true);
  15938. this.addExtra(expression, "parenStart", startLoc.index);
  15939. this.takeSurroundingComments(expression, startLoc.index, this.state.lastTokEndLoc.index);
  15940. return expression;
  15941. }
  15942. const parenExpression = this.startNodeAt(startLoc);
  15943. parenExpression.expression = expression;
  15944. return this.finishNode(parenExpression, "ParenthesizedExpression");
  15945. }
  15946. shouldParseArrow(params) {
  15947. return !this.canInsertSemicolon();
  15948. }
  15949. parseArrow(node) {
  15950. if (this.eat(19)) {
  15951. return node;
  15952. }
  15953. }
  15954. parseParenItem(node, startLoc) {
  15955. return node;
  15956. }
  15957. parseNewOrNewTarget() {
  15958. const node = this.startNode();
  15959. this.next();
  15960. if (this.match(16)) {
  15961. const meta = this.createIdentifier(this.startNodeAtNode(node), "new");
  15962. this.next();
  15963. const metaProp = this.parseMetaProperty(node, meta, "target");
  15964. if (!this.scope.allowNewTarget) {
  15965. this.raise(Errors.UnexpectedNewTarget, metaProp);
  15966. }
  15967. return metaProp;
  15968. }
  15969. return this.parseNew(node);
  15970. }
  15971. parseNew(node) {
  15972. this.parseNewCallee(node);
  15973. if (this.eat(10)) {
  15974. const args = this.parseExprList(11);
  15975. this.toReferencedList(args);
  15976. node.arguments = args;
  15977. } else {
  15978. node.arguments = [];
  15979. }
  15980. return this.finishNode(node, "NewExpression");
  15981. }
  15982. parseNewCallee(node) {
  15983. const isImport = this.match(83);
  15984. const callee = this.parseNoCallExpr();
  15985. node.callee = callee;
  15986. if (isImport && (callee.type === "Import" || callee.type === "ImportExpression")) {
  15987. this.raise(Errors.ImportCallNotNewExpression, callee);
  15988. }
  15989. }
  15990. parseTemplateElement(isTagged) {
  15991. const {
  15992. start,
  15993. startLoc,
  15994. end,
  15995. value
  15996. } = this.state;
  15997. const elemStart = start + 1;
  15998. const elem = this.startNodeAt(createPositionWithColumnOffset(startLoc, 1));
  15999. if (value === null) {
  16000. if (!isTagged) {
  16001. this.raise(Errors.InvalidEscapeSequenceTemplate, createPositionWithColumnOffset(this.state.firstInvalidTemplateEscapePos, 1));
  16002. }
  16003. }
  16004. const isTail = this.match(24);
  16005. const endOffset = isTail ? -1 : -2;
  16006. const elemEnd = end + endOffset;
  16007. elem.value = {
  16008. raw: this.input.slice(elemStart, elemEnd).replace(/\r\n?/g, "\n"),
  16009. cooked: value === null ? null : value.slice(1, endOffset)
  16010. };
  16011. elem.tail = isTail;
  16012. this.next();
  16013. const finishedNode = this.finishNode(elem, "TemplateElement");
  16014. this.resetEndLocation(finishedNode, createPositionWithColumnOffset(this.state.lastTokEndLoc, endOffset));
  16015. return finishedNode;
  16016. }
  16017. parseTemplate(isTagged) {
  16018. const node = this.startNode();
  16019. let curElt = this.parseTemplateElement(isTagged);
  16020. const quasis = [curElt];
  16021. const substitutions = [];
  16022. while (!curElt.tail) {
  16023. substitutions.push(this.parseTemplateSubstitution());
  16024. this.readTemplateContinuation();
  16025. quasis.push(curElt = this.parseTemplateElement(isTagged));
  16026. }
  16027. node.expressions = substitutions;
  16028. node.quasis = quasis;
  16029. return this.finishNode(node, "TemplateLiteral");
  16030. }
  16031. parseTemplateSubstitution() {
  16032. return this.parseExpression();
  16033. }
  16034. parseObjectLike(close, isPattern, isRecord, refExpressionErrors) {
  16035. if (isRecord) {
  16036. this.expectPlugin("recordAndTuple");
  16037. }
  16038. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  16039. this.state.inFSharpPipelineDirectBody = false;
  16040. let sawProto = false;
  16041. let first = true;
  16042. const node = this.startNode();
  16043. node.properties = [];
  16044. this.next();
  16045. while (!this.match(close)) {
  16046. if (first) {
  16047. first = false;
  16048. } else {
  16049. this.expect(12);
  16050. if (this.match(close)) {
  16051. this.addTrailingCommaExtraToNode(node);
  16052. break;
  16053. }
  16054. }
  16055. let prop;
  16056. if (isPattern) {
  16057. prop = this.parseBindingProperty();
  16058. } else {
  16059. prop = this.parsePropertyDefinition(refExpressionErrors);
  16060. sawProto = this.checkProto(prop, isRecord, sawProto, refExpressionErrors);
  16061. }
  16062. if (isRecord && !this.isObjectProperty(prop) && prop.type !== "SpreadElement") {
  16063. this.raise(Errors.InvalidRecordProperty, prop);
  16064. }
  16065. if (prop.shorthand) {
  16066. this.addExtra(prop, "shorthand", true);
  16067. }
  16068. node.properties.push(prop);
  16069. }
  16070. this.next();
  16071. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  16072. let type = "ObjectExpression";
  16073. if (isPattern) {
  16074. type = "ObjectPattern";
  16075. } else if (isRecord) {
  16076. type = "RecordExpression";
  16077. }
  16078. return this.finishNode(node, type);
  16079. }
  16080. addTrailingCommaExtraToNode(node) {
  16081. this.addExtra(node, "trailingComma", this.state.lastTokStartLoc.index);
  16082. this.addExtra(node, "trailingCommaLoc", this.state.lastTokStartLoc, false);
  16083. }
  16084. maybeAsyncOrAccessorProp(prop) {
  16085. return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(0) || this.match(55));
  16086. }
  16087. parsePropertyDefinition(refExpressionErrors) {
  16088. let decorators = [];
  16089. if (this.match(26)) {
  16090. if (this.hasPlugin("decorators")) {
  16091. this.raise(Errors.UnsupportedPropertyDecorator, this.state.startLoc);
  16092. }
  16093. while (this.match(26)) {
  16094. decorators.push(this.parseDecorator());
  16095. }
  16096. }
  16097. const prop = this.startNode();
  16098. let isAsync = false;
  16099. let isAccessor = false;
  16100. let startLoc;
  16101. if (this.match(21)) {
  16102. if (decorators.length) this.unexpected();
  16103. return this.parseSpread();
  16104. }
  16105. if (decorators.length) {
  16106. prop.decorators = decorators;
  16107. decorators = [];
  16108. }
  16109. prop.method = false;
  16110. if (refExpressionErrors) {
  16111. startLoc = this.state.startLoc;
  16112. }
  16113. let isGenerator = this.eat(55);
  16114. this.parsePropertyNamePrefixOperator(prop);
  16115. const containsEsc = this.state.containsEsc;
  16116. this.parsePropertyName(prop, refExpressionErrors);
  16117. if (!isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) {
  16118. const {
  16119. key
  16120. } = prop;
  16121. const keyName = key.name;
  16122. if (keyName === "async" && !this.hasPrecedingLineBreak()) {
  16123. isAsync = true;
  16124. this.resetPreviousNodeTrailingComments(key);
  16125. isGenerator = this.eat(55);
  16126. this.parsePropertyName(prop);
  16127. }
  16128. if (keyName === "get" || keyName === "set") {
  16129. isAccessor = true;
  16130. this.resetPreviousNodeTrailingComments(key);
  16131. prop.kind = keyName;
  16132. if (this.match(55)) {
  16133. isGenerator = true;
  16134. this.raise(Errors.AccessorIsGenerator, this.state.curPosition(), {
  16135. kind: keyName
  16136. });
  16137. this.next();
  16138. }
  16139. this.parsePropertyName(prop);
  16140. }
  16141. }
  16142. return this.parseObjPropValue(prop, startLoc, isGenerator, isAsync, false, isAccessor, refExpressionErrors);
  16143. }
  16144. getGetterSetterExpectedParamCount(method) {
  16145. return method.kind === "get" ? 0 : 1;
  16146. }
  16147. getObjectOrClassMethodParams(method) {
  16148. return method.params;
  16149. }
  16150. checkGetterSetterParams(method) {
  16151. var _params;
  16152. const paramCount = this.getGetterSetterExpectedParamCount(method);
  16153. const params = this.getObjectOrClassMethodParams(method);
  16154. if (params.length !== paramCount) {
  16155. this.raise(method.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, method);
  16156. }
  16157. if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") {
  16158. this.raise(Errors.BadSetterRestParameter, method);
  16159. }
  16160. }
  16161. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  16162. if (isAccessor) {
  16163. const finishedProp = this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod");
  16164. this.checkGetterSetterParams(finishedProp);
  16165. return finishedProp;
  16166. }
  16167. if (isAsync || isGenerator || this.match(10)) {
  16168. if (isPattern) this.unexpected();
  16169. prop.kind = "method";
  16170. prop.method = true;
  16171. return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
  16172. }
  16173. }
  16174. parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) {
  16175. prop.shorthand = false;
  16176. if (this.eat(14)) {
  16177. prop.value = isPattern ? this.parseMaybeDefault(this.state.startLoc) : this.parseMaybeAssignAllowInOrVoidPattern(8, refExpressionErrors);
  16178. return this.finishObjectProperty(prop);
  16179. }
  16180. if (!prop.computed && prop.key.type === "Identifier") {
  16181. this.checkReservedWord(prop.key.name, prop.key.loc.start, true, false);
  16182. if (isPattern) {
  16183. prop.value = this.parseMaybeDefault(startLoc, this.cloneIdentifier(prop.key));
  16184. } else if (this.match(29)) {
  16185. const shorthandAssignLoc = this.state.startLoc;
  16186. if (refExpressionErrors != null) {
  16187. if (refExpressionErrors.shorthandAssignLoc === null) {
  16188. refExpressionErrors.shorthandAssignLoc = shorthandAssignLoc;
  16189. }
  16190. } else {
  16191. this.raise(Errors.InvalidCoverInitializedName, shorthandAssignLoc);
  16192. }
  16193. prop.value = this.parseMaybeDefault(startLoc, this.cloneIdentifier(prop.key));
  16194. } else {
  16195. prop.value = this.cloneIdentifier(prop.key);
  16196. }
  16197. prop.shorthand = true;
  16198. return this.finishObjectProperty(prop);
  16199. }
  16200. }
  16201. finishObjectProperty(node) {
  16202. return this.finishNode(node, "ObjectProperty");
  16203. }
  16204. parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  16205. const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors);
  16206. if (!node) this.unexpected();
  16207. return node;
  16208. }
  16209. parsePropertyName(prop, refExpressionErrors) {
  16210. if (this.eat(0)) {
  16211. prop.computed = true;
  16212. prop.key = this.parseMaybeAssignAllowIn();
  16213. this.expect(3);
  16214. } else {
  16215. const {
  16216. type,
  16217. value
  16218. } = this.state;
  16219. let key;
  16220. if (tokenIsKeywordOrIdentifier(type)) {
  16221. key = this.parseIdentifier(true);
  16222. } else {
  16223. switch (type) {
  16224. case 135:
  16225. key = this.parseNumericLiteral(value);
  16226. break;
  16227. case 134:
  16228. key = this.parseStringLiteral(value);
  16229. break;
  16230. case 136:
  16231. key = this.parseBigIntLiteral(value);
  16232. break;
  16233. case 139:
  16234. {
  16235. const privateKeyLoc = this.state.startLoc;
  16236. if (refExpressionErrors != null) {
  16237. if (refExpressionErrors.privateKeyLoc === null) {
  16238. refExpressionErrors.privateKeyLoc = privateKeyLoc;
  16239. }
  16240. } else {
  16241. this.raise(Errors.UnexpectedPrivateField, privateKeyLoc);
  16242. }
  16243. key = this.parsePrivateName();
  16244. break;
  16245. }
  16246. default:
  16247. if (type === 137) {
  16248. key = this.parseDecimalLiteral(value);
  16249. break;
  16250. }
  16251. this.unexpected();
  16252. }
  16253. }
  16254. prop.key = key;
  16255. if (type !== 139) {
  16256. prop.computed = false;
  16257. }
  16258. }
  16259. }
  16260. initFunction(node, isAsync) {
  16261. node.id = null;
  16262. node.generator = false;
  16263. node.async = isAsync;
  16264. }
  16265. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  16266. this.initFunction(node, isAsync);
  16267. node.generator = isGenerator;
  16268. this.scope.enter(514 | 16 | (inClassScope ? 576 : 0) | (allowDirectSuper ? 32 : 0));
  16269. this.prodParam.enter(functionFlags(isAsync, node.generator));
  16270. this.parseFunctionParams(node, isConstructor);
  16271. const finishedNode = this.parseFunctionBodyAndFinish(node, type, true);
  16272. this.prodParam.exit();
  16273. this.scope.exit();
  16274. return finishedNode;
  16275. }
  16276. parseArrayLike(close, isTuple, refExpressionErrors) {
  16277. if (isTuple) {
  16278. this.expectPlugin("recordAndTuple");
  16279. }
  16280. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  16281. this.state.inFSharpPipelineDirectBody = false;
  16282. const node = this.startNode();
  16283. this.next();
  16284. node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node);
  16285. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  16286. return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression");
  16287. }
  16288. parseArrowExpression(node, params, isAsync, trailingCommaLoc) {
  16289. this.scope.enter(514 | 4);
  16290. let flags = functionFlags(isAsync, false);
  16291. if (!this.match(5) && this.prodParam.hasIn) {
  16292. flags |= 8;
  16293. }
  16294. this.prodParam.enter(flags);
  16295. this.initFunction(node, isAsync);
  16296. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  16297. if (params) {
  16298. this.state.maybeInArrowParameters = true;
  16299. this.setArrowFunctionParameters(node, params, trailingCommaLoc);
  16300. }
  16301. this.state.maybeInArrowParameters = false;
  16302. this.parseFunctionBody(node, true);
  16303. this.prodParam.exit();
  16304. this.scope.exit();
  16305. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  16306. return this.finishNode(node, "ArrowFunctionExpression");
  16307. }
  16308. setArrowFunctionParameters(node, params, trailingCommaLoc) {
  16309. this.toAssignableList(params, trailingCommaLoc, false);
  16310. node.params = params;
  16311. }
  16312. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  16313. this.parseFunctionBody(node, false, isMethod);
  16314. return this.finishNode(node, type);
  16315. }
  16316. parseFunctionBody(node, allowExpression, isMethod = false) {
  16317. const isExpression = allowExpression && !this.match(5);
  16318. this.expressionScope.enter(newExpressionScope());
  16319. if (isExpression) {
  16320. node.body = this.parseMaybeAssign();
  16321. this.checkParams(node, false, allowExpression, false);
  16322. } else {
  16323. const oldStrict = this.state.strict;
  16324. const oldLabels = this.state.labels;
  16325. this.state.labels = [];
  16326. this.prodParam.enter(this.prodParam.currentFlags() | 4);
  16327. node.body = this.parseBlock(true, false, hasStrictModeDirective => {
  16328. const nonSimple = !this.isSimpleParamList(node.params);
  16329. if (hasStrictModeDirective && nonSimple) {
  16330. this.raise(Errors.IllegalLanguageModeDirective, (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.loc.end : node);
  16331. }
  16332. const strictModeChanged = !oldStrict && this.state.strict;
  16333. this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
  16334. if (this.state.strict && node.id) {
  16335. this.checkIdentifier(node.id, 65, strictModeChanged);
  16336. }
  16337. });
  16338. this.prodParam.exit();
  16339. this.state.labels = oldLabels;
  16340. }
  16341. this.expressionScope.exit();
  16342. }
  16343. isSimpleParameter(node) {
  16344. return node.type === "Identifier";
  16345. }
  16346. isSimpleParamList(params) {
  16347. for (let i = 0, len = params.length; i < len; i++) {
  16348. if (!this.isSimpleParameter(params[i])) return false;
  16349. }
  16350. return true;
  16351. }
  16352. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  16353. const checkClashes = !allowDuplicates && new Set();
  16354. const formalParameters = {
  16355. type: "FormalParameters"
  16356. };
  16357. for (const param of node.params) {
  16358. this.checkLVal(param, formalParameters, 5, checkClashes, strictModeChanged);
  16359. }
  16360. }
  16361. parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) {
  16362. const elts = [];
  16363. let first = true;
  16364. while (!this.eat(close)) {
  16365. if (first) {
  16366. first = false;
  16367. } else {
  16368. this.expect(12);
  16369. if (this.match(close)) {
  16370. if (nodeForExtra) {
  16371. this.addTrailingCommaExtraToNode(nodeForExtra);
  16372. }
  16373. this.next();
  16374. break;
  16375. }
  16376. }
  16377. elts.push(this.parseExprListItem(close, allowEmpty, refExpressionErrors));
  16378. }
  16379. return elts;
  16380. }
  16381. parseExprListItem(close, allowEmpty, refExpressionErrors, allowPlaceholder) {
  16382. let elt;
  16383. if (this.match(12)) {
  16384. if (!allowEmpty) {
  16385. this.raise(Errors.UnexpectedToken, this.state.curPosition(), {
  16386. unexpected: ","
  16387. });
  16388. }
  16389. elt = null;
  16390. } else if (this.match(21)) {
  16391. const spreadNodeStartLoc = this.state.startLoc;
  16392. elt = this.parseParenItem(this.parseSpread(refExpressionErrors), spreadNodeStartLoc);
  16393. } else if (this.match(17)) {
  16394. this.expectPlugin("partialApplication");
  16395. if (!allowPlaceholder) {
  16396. this.raise(Errors.UnexpectedArgumentPlaceholder, this.state.startLoc);
  16397. }
  16398. const node = this.startNode();
  16399. this.next();
  16400. elt = this.finishNode(node, "ArgumentPlaceholder");
  16401. } else {
  16402. elt = this.parseMaybeAssignAllowInOrVoidPattern(close, refExpressionErrors, this.parseParenItem);
  16403. }
  16404. return elt;
  16405. }
  16406. parseIdentifier(liberal) {
  16407. const node = this.startNode();
  16408. const name = this.parseIdentifierName(liberal);
  16409. return this.createIdentifier(node, name);
  16410. }
  16411. createIdentifier(node, name) {
  16412. node.name = name;
  16413. node.loc.identifierName = name;
  16414. return this.finishNode(node, "Identifier");
  16415. }
  16416. createIdentifierAt(node, name, endLoc) {
  16417. node.name = name;
  16418. node.loc.identifierName = name;
  16419. return this.finishNodeAt(node, "Identifier", endLoc);
  16420. }
  16421. parseIdentifierName(liberal) {
  16422. let name;
  16423. const {
  16424. startLoc,
  16425. type
  16426. } = this.state;
  16427. if (tokenIsKeywordOrIdentifier(type)) {
  16428. name = this.state.value;
  16429. } else {
  16430. this.unexpected();
  16431. }
  16432. const tokenIsKeyword = tokenKeywordOrIdentifierIsKeyword(type);
  16433. if (liberal) {
  16434. if (tokenIsKeyword) {
  16435. this.replaceToken(132);
  16436. }
  16437. } else {
  16438. this.checkReservedWord(name, startLoc, tokenIsKeyword, false);
  16439. }
  16440. this.next();
  16441. return name;
  16442. }
  16443. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  16444. if (word.length > 10) {
  16445. return;
  16446. }
  16447. if (!canBeReservedWord(word)) {
  16448. return;
  16449. }
  16450. if (checkKeywords && isKeyword(word)) {
  16451. this.raise(Errors.UnexpectedKeyword, startLoc, {
  16452. keyword: word
  16453. });
  16454. return;
  16455. }
  16456. const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
  16457. if (reservedTest(word, this.inModule)) {
  16458. this.raise(Errors.UnexpectedReservedWord, startLoc, {
  16459. reservedWord: word
  16460. });
  16461. return;
  16462. } else if (word === "yield") {
  16463. if (this.prodParam.hasYield) {
  16464. this.raise(Errors.YieldBindingIdentifier, startLoc);
  16465. return;
  16466. }
  16467. } else if (word === "await") {
  16468. if (this.prodParam.hasAwait) {
  16469. this.raise(Errors.AwaitBindingIdentifier, startLoc);
  16470. return;
  16471. }
  16472. if (this.scope.inStaticBlock) {
  16473. this.raise(Errors.AwaitBindingIdentifierInStaticBlock, startLoc);
  16474. return;
  16475. }
  16476. this.expressionScope.recordAsyncArrowParametersError(startLoc);
  16477. } else if (word === "arguments") {
  16478. if (this.scope.inClassAndNotInNonArrowFunction) {
  16479. this.raise(Errors.ArgumentsInClass, startLoc);
  16480. return;
  16481. }
  16482. }
  16483. }
  16484. recordAwaitIfAllowed() {
  16485. const isAwaitAllowed = this.prodParam.hasAwait;
  16486. if (isAwaitAllowed && !this.scope.inFunction) {
  16487. this.state.hasTopLevelAwait = true;
  16488. }
  16489. return isAwaitAllowed;
  16490. }
  16491. parseAwait(startLoc) {
  16492. const node = this.startNodeAt(startLoc);
  16493. this.expressionScope.recordParameterInitializerError(Errors.AwaitExpressionFormalParameter, node);
  16494. if (this.eat(55)) {
  16495. this.raise(Errors.ObsoleteAwaitStar, node);
  16496. }
  16497. if (!this.scope.inFunction && !(this.optionFlags & 1)) {
  16498. if (this.isAmbiguousPrefixOrIdentifier()) {
  16499. this.ambiguousScriptDifferentAst = true;
  16500. } else {
  16501. this.sawUnambiguousESM = true;
  16502. }
  16503. }
  16504. if (!this.state.soloAwait) {
  16505. node.argument = this.parseMaybeUnary(null, true);
  16506. }
  16507. return this.finishNode(node, "AwaitExpression");
  16508. }
  16509. isAmbiguousPrefixOrIdentifier() {
  16510. if (this.hasPrecedingLineBreak()) return true;
  16511. const {
  16512. type
  16513. } = this.state;
  16514. return type === 53 || type === 10 || type === 0 || tokenIsTemplate(type) || type === 102 && !this.state.containsEsc || type === 138 || type === 56 || this.hasPlugin("v8intrinsic") && type === 54;
  16515. }
  16516. parseYield(startLoc) {
  16517. const node = this.startNodeAt(startLoc);
  16518. this.expressionScope.recordParameterInitializerError(Errors.YieldInParameter, node);
  16519. let delegating = false;
  16520. let argument = null;
  16521. if (!this.hasPrecedingLineBreak()) {
  16522. delegating = this.eat(55);
  16523. switch (this.state.type) {
  16524. case 13:
  16525. case 140:
  16526. case 8:
  16527. case 11:
  16528. case 3:
  16529. case 9:
  16530. case 14:
  16531. case 12:
  16532. if (!delegating) break;
  16533. default:
  16534. argument = this.parseMaybeAssign();
  16535. }
  16536. }
  16537. node.delegate = delegating;
  16538. node.argument = argument;
  16539. return this.finishNode(node, "YieldExpression");
  16540. }
  16541. parseImportCall(node) {
  16542. this.next();
  16543. node.source = this.parseMaybeAssignAllowIn();
  16544. node.options = null;
  16545. if (this.eat(12)) {
  16546. if (!this.match(11)) {
  16547. node.options = this.parseMaybeAssignAllowIn();
  16548. if (this.eat(12)) {
  16549. this.addTrailingCommaExtraToNode(node.options);
  16550. if (!this.match(11)) {
  16551. do {
  16552. this.parseMaybeAssignAllowIn();
  16553. } while (this.eat(12) && !this.match(11));
  16554. this.raise(Errors.ImportCallArity, node);
  16555. }
  16556. }
  16557. } else {
  16558. this.addTrailingCommaExtraToNode(node.source);
  16559. }
  16560. }
  16561. this.expect(11);
  16562. return this.finishNode(node, "ImportExpression");
  16563. }
  16564. checkPipelineAtInfixOperator(left, leftStartLoc) {
  16565. if (this.hasPlugin(["pipelineOperator", {
  16566. proposal: "smart"
  16567. }])) {
  16568. if (left.type === "SequenceExpression") {
  16569. this.raise(Errors.PipelineHeadSequenceExpression, leftStartLoc);
  16570. }
  16571. }
  16572. }
  16573. parseSmartPipelineBodyInStyle(childExpr, startLoc) {
  16574. if (this.isSimpleReference(childExpr)) {
  16575. const bodyNode = this.startNodeAt(startLoc);
  16576. bodyNode.callee = childExpr;
  16577. return this.finishNode(bodyNode, "PipelineBareFunction");
  16578. } else {
  16579. const bodyNode = this.startNodeAt(startLoc);
  16580. this.checkSmartPipeTopicBodyEarlyErrors(startLoc);
  16581. bodyNode.expression = childExpr;
  16582. return this.finishNode(bodyNode, "PipelineTopicExpression");
  16583. }
  16584. }
  16585. isSimpleReference(expression) {
  16586. switch (expression.type) {
  16587. case "MemberExpression":
  16588. return !expression.computed && this.isSimpleReference(expression.object);
  16589. case "Identifier":
  16590. return true;
  16591. default:
  16592. return false;
  16593. }
  16594. }
  16595. checkSmartPipeTopicBodyEarlyErrors(startLoc) {
  16596. if (this.match(19)) {
  16597. throw this.raise(Errors.PipelineBodyNoArrow, this.state.startLoc);
  16598. }
  16599. if (!this.topicReferenceWasUsedInCurrentContext()) {
  16600. this.raise(Errors.PipelineTopicUnused, startLoc);
  16601. }
  16602. }
  16603. withTopicBindingContext(callback) {
  16604. const outerContextTopicState = this.state.topicContext;
  16605. this.state.topicContext = {
  16606. maxNumOfResolvableTopics: 1,
  16607. maxTopicIndex: null
  16608. };
  16609. try {
  16610. return callback();
  16611. } finally {
  16612. this.state.topicContext = outerContextTopicState;
  16613. }
  16614. }
  16615. withSmartMixTopicForbiddingContext(callback) {
  16616. if (this.hasPlugin(["pipelineOperator", {
  16617. proposal: "smart"
  16618. }])) {
  16619. const outerContextTopicState = this.state.topicContext;
  16620. this.state.topicContext = {
  16621. maxNumOfResolvableTopics: 0,
  16622. maxTopicIndex: null
  16623. };
  16624. try {
  16625. return callback();
  16626. } finally {
  16627. this.state.topicContext = outerContextTopicState;
  16628. }
  16629. } else {
  16630. return callback();
  16631. }
  16632. }
  16633. withSoloAwaitPermittingContext(callback) {
  16634. const outerContextSoloAwaitState = this.state.soloAwait;
  16635. this.state.soloAwait = true;
  16636. try {
  16637. return callback();
  16638. } finally {
  16639. this.state.soloAwait = outerContextSoloAwaitState;
  16640. }
  16641. }
  16642. allowInAnd(callback) {
  16643. const flags = this.prodParam.currentFlags();
  16644. const prodParamToSet = 8 & ~flags;
  16645. if (prodParamToSet) {
  16646. this.prodParam.enter(flags | 8);
  16647. try {
  16648. return callback();
  16649. } finally {
  16650. this.prodParam.exit();
  16651. }
  16652. }
  16653. return callback();
  16654. }
  16655. disallowInAnd(callback) {
  16656. const flags = this.prodParam.currentFlags();
  16657. const prodParamToClear = 8 & flags;
  16658. if (prodParamToClear) {
  16659. this.prodParam.enter(flags & -9);
  16660. try {
  16661. return callback();
  16662. } finally {
  16663. this.prodParam.exit();
  16664. }
  16665. }
  16666. return callback();
  16667. }
  16668. registerTopicReference() {
  16669. this.state.topicContext.maxTopicIndex = 0;
  16670. }
  16671. topicReferenceIsAllowedInCurrentContext() {
  16672. return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  16673. }
  16674. topicReferenceWasUsedInCurrentContext() {
  16675. return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  16676. }
  16677. parseFSharpPipelineBody(prec) {
  16678. const startLoc = this.state.startLoc;
  16679. this.state.potentialArrowAt = this.state.start;
  16680. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  16681. this.state.inFSharpPipelineDirectBody = true;
  16682. const ret = this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, prec);
  16683. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  16684. return ret;
  16685. }
  16686. parseModuleExpression() {
  16687. this.expectPlugin("moduleBlocks");
  16688. const node = this.startNode();
  16689. this.next();
  16690. if (!this.match(5)) {
  16691. this.unexpected(null, 5);
  16692. }
  16693. const program = this.startNodeAt(this.state.endLoc);
  16694. this.next();
  16695. const revertScopes = this.initializeScopes(true);
  16696. this.enterInitialScopes();
  16697. try {
  16698. node.body = this.parseProgram(program, 8, "module");
  16699. } finally {
  16700. revertScopes();
  16701. }
  16702. return this.finishNode(node, "ModuleExpression");
  16703. }
  16704. parseVoidPattern(refExpressionErrors) {
  16705. this.expectPlugin("discardBinding");
  16706. const node = this.startNode();
  16707. if (refExpressionErrors != null) {
  16708. refExpressionErrors.voidPatternLoc = this.state.startLoc;
  16709. }
  16710. this.next();
  16711. return this.finishNode(node, "VoidPattern");
  16712. }
  16713. parseMaybeAssignAllowInOrVoidPattern(close, refExpressionErrors, afterLeftParse) {
  16714. if (refExpressionErrors != null && this.match(88)) {
  16715. const nextCode = this.lookaheadCharCode();
  16716. if (nextCode === 44 || nextCode === (close === 3 ? 93 : close === 8 ? 125 : 41) || nextCode === 61) {
  16717. return this.parseMaybeDefault(this.state.startLoc, this.parseVoidPattern(refExpressionErrors));
  16718. }
  16719. }
  16720. return this.parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse);
  16721. }
  16722. parsePropertyNamePrefixOperator(prop) {}
  16723. }
  16724. const loopLabel = {
  16725. kind: 1
  16726. },
  16727. switchLabel = {
  16728. kind: 2
  16729. };
  16730. const loneSurrogate = /[\uD800-\uDFFF]/u;
  16731. const keywordRelationalOperator = /in(?:stanceof)?/y;
  16732. function babel7CompatTokens(tokens, input, startIndex) {
  16733. for (let i = 0; i < tokens.length; i++) {
  16734. const token = tokens[i];
  16735. const {
  16736. type
  16737. } = token;
  16738. if (typeof type === "number") {
  16739. if (type === 139) {
  16740. const {
  16741. loc,
  16742. start,
  16743. value,
  16744. end
  16745. } = token;
  16746. const hashEndPos = start + 1;
  16747. const hashEndLoc = createPositionWithColumnOffset(loc.start, 1);
  16748. tokens.splice(i, 1, new Token({
  16749. type: getExportedToken(27),
  16750. value: "#",
  16751. start: start,
  16752. end: hashEndPos,
  16753. startLoc: loc.start,
  16754. endLoc: hashEndLoc
  16755. }), new Token({
  16756. type: getExportedToken(132),
  16757. value: value,
  16758. start: hashEndPos,
  16759. end: end,
  16760. startLoc: hashEndLoc,
  16761. endLoc: loc.end
  16762. }));
  16763. i++;
  16764. continue;
  16765. }
  16766. if (tokenIsTemplate(type)) {
  16767. const {
  16768. loc,
  16769. start,
  16770. value,
  16771. end
  16772. } = token;
  16773. const backquoteEnd = start + 1;
  16774. const backquoteEndLoc = createPositionWithColumnOffset(loc.start, 1);
  16775. let startToken;
  16776. if (input.charCodeAt(start - startIndex) === 96) {
  16777. startToken = new Token({
  16778. type: getExportedToken(22),
  16779. value: "`",
  16780. start: start,
  16781. end: backquoteEnd,
  16782. startLoc: loc.start,
  16783. endLoc: backquoteEndLoc
  16784. });
  16785. } else {
  16786. startToken = new Token({
  16787. type: getExportedToken(8),
  16788. value: "}",
  16789. start: start,
  16790. end: backquoteEnd,
  16791. startLoc: loc.start,
  16792. endLoc: backquoteEndLoc
  16793. });
  16794. }
  16795. let templateValue, templateElementEnd, templateElementEndLoc, endToken;
  16796. if (type === 24) {
  16797. templateElementEnd = end - 1;
  16798. templateElementEndLoc = createPositionWithColumnOffset(loc.end, -1);
  16799. templateValue = value === null ? null : value.slice(1, -1);
  16800. endToken = new Token({
  16801. type: getExportedToken(22),
  16802. value: "`",
  16803. start: templateElementEnd,
  16804. end: end,
  16805. startLoc: templateElementEndLoc,
  16806. endLoc: loc.end
  16807. });
  16808. } else {
  16809. templateElementEnd = end - 2;
  16810. templateElementEndLoc = createPositionWithColumnOffset(loc.end, -2);
  16811. templateValue = value === null ? null : value.slice(1, -2);
  16812. endToken = new Token({
  16813. type: getExportedToken(23),
  16814. value: "${",
  16815. start: templateElementEnd,
  16816. end: end,
  16817. startLoc: templateElementEndLoc,
  16818. endLoc: loc.end
  16819. });
  16820. }
  16821. tokens.splice(i, 1, startToken, new Token({
  16822. type: getExportedToken(20),
  16823. value: templateValue,
  16824. start: backquoteEnd,
  16825. end: templateElementEnd,
  16826. startLoc: backquoteEndLoc,
  16827. endLoc: templateElementEndLoc
  16828. }), endToken);
  16829. i += 2;
  16830. continue;
  16831. }
  16832. token.type = getExportedToken(type);
  16833. }
  16834. }
  16835. return tokens;
  16836. }
  16837. class StatementParser extends ExpressionParser {
  16838. parseTopLevel(file, program) {
  16839. file.program = this.parseProgram(program, 140, this.options.sourceType === "module" ? "module" : "script");
  16840. file.comments = this.comments;
  16841. if (this.optionFlags & 256) {
  16842. file.tokens = babel7CompatTokens(this.tokens, this.input, this.startIndex);
  16843. }
  16844. return this.finishNode(file, "File");
  16845. }
  16846. parseProgram(program, end, sourceType) {
  16847. program.sourceType = sourceType;
  16848. program.interpreter = this.parseInterpreterDirective();
  16849. this.parseBlockBody(program, true, true, end);
  16850. if (this.inModule) {
  16851. if (!(this.optionFlags & 64) && this.scope.undefinedExports.size > 0) {
  16852. for (const [localName, at] of Array.from(this.scope.undefinedExports)) {
  16853. this.raise(Errors.ModuleExportUndefined, at, {
  16854. localName
  16855. });
  16856. }
  16857. }
  16858. this.addExtra(program, "topLevelAwait", this.state.hasTopLevelAwait);
  16859. }
  16860. let finishedProgram;
  16861. if (end === 140) {
  16862. finishedProgram = this.finishNode(program, "Program");
  16863. } else {
  16864. finishedProgram = this.finishNodeAt(program, "Program", createPositionWithColumnOffset(this.state.startLoc, -1));
  16865. }
  16866. return finishedProgram;
  16867. }
  16868. stmtToDirective(stmt) {
  16869. const directive = this.castNodeTo(stmt, "Directive");
  16870. const directiveLiteral = this.castNodeTo(stmt.expression, "DirectiveLiteral");
  16871. const expressionValue = directiveLiteral.value;
  16872. const raw = this.input.slice(this.offsetToSourcePos(directiveLiteral.start), this.offsetToSourcePos(directiveLiteral.end));
  16873. const val = directiveLiteral.value = raw.slice(1, -1);
  16874. this.addExtra(directiveLiteral, "raw", raw);
  16875. this.addExtra(directiveLiteral, "rawValue", val);
  16876. this.addExtra(directiveLiteral, "expressionValue", expressionValue);
  16877. directive.value = directiveLiteral;
  16878. delete stmt.expression;
  16879. return directive;
  16880. }
  16881. parseInterpreterDirective() {
  16882. if (!this.match(28)) {
  16883. return null;
  16884. }
  16885. const node = this.startNode();
  16886. node.value = this.state.value;
  16887. this.next();
  16888. return this.finishNode(node, "InterpreterDirective");
  16889. }
  16890. isLet() {
  16891. if (!this.isContextual(100)) {
  16892. return false;
  16893. }
  16894. return this.hasFollowingBindingAtom();
  16895. }
  16896. isUsing() {
  16897. if (!this.isContextual(107)) {
  16898. return false;
  16899. }
  16900. return this.nextTokenIsIdentifierOnSameLine();
  16901. }
  16902. isForUsing() {
  16903. if (!this.isContextual(107)) {
  16904. return false;
  16905. }
  16906. const next = this.nextTokenInLineStart();
  16907. const nextCh = this.codePointAtPos(next);
  16908. if (this.isUnparsedContextual(next, "of")) {
  16909. const nextCharAfterOf = this.lookaheadCharCodeSince(next + 2);
  16910. if (nextCharAfterOf !== 61 && nextCharAfterOf !== 58 && nextCharAfterOf !== 59) {
  16911. return false;
  16912. }
  16913. }
  16914. if (this.chStartsBindingIdentifier(nextCh, next) || this.isUnparsedContextual(next, "void")) {
  16915. return true;
  16916. }
  16917. return false;
  16918. }
  16919. nextTokenIsIdentifierOnSameLine() {
  16920. const next = this.nextTokenInLineStart();
  16921. const nextCh = this.codePointAtPos(next);
  16922. return this.chStartsBindingIdentifier(nextCh, next);
  16923. }
  16924. isAwaitUsing() {
  16925. if (!this.isContextual(96)) {
  16926. return false;
  16927. }
  16928. let next = this.nextTokenInLineStart();
  16929. if (this.isUnparsedContextual(next, "using")) {
  16930. next = this.nextTokenInLineStartSince(next + 5);
  16931. const nextCh = this.codePointAtPos(next);
  16932. if (this.chStartsBindingIdentifier(nextCh, next)) {
  16933. return true;
  16934. }
  16935. }
  16936. return false;
  16937. }
  16938. chStartsBindingIdentifier(ch, pos) {
  16939. if (isIdentifierStart(ch)) {
  16940. keywordRelationalOperator.lastIndex = pos;
  16941. if (keywordRelationalOperator.test(this.input)) {
  16942. const endCh = this.codePointAtPos(keywordRelationalOperator.lastIndex);
  16943. if (!isIdentifierChar(endCh) && endCh !== 92) {
  16944. return false;
  16945. }
  16946. }
  16947. return true;
  16948. } else if (ch === 92) {
  16949. return true;
  16950. } else {
  16951. return false;
  16952. }
  16953. }
  16954. chStartsBindingPattern(ch) {
  16955. return ch === 91 || ch === 123;
  16956. }
  16957. hasFollowingBindingAtom() {
  16958. const next = this.nextTokenStart();
  16959. const nextCh = this.codePointAtPos(next);
  16960. return this.chStartsBindingPattern(nextCh) || this.chStartsBindingIdentifier(nextCh, next);
  16961. }
  16962. hasInLineFollowingBindingIdentifierOrBrace() {
  16963. const next = this.nextTokenInLineStart();
  16964. const nextCh = this.codePointAtPos(next);
  16965. return nextCh === 123 || this.chStartsBindingIdentifier(nextCh, next);
  16966. }
  16967. allowsUsing() {
  16968. return (this.scope.inModule || !this.scope.inTopLevel) && !this.scope.inBareCaseStatement;
  16969. }
  16970. parseModuleItem() {
  16971. return this.parseStatementLike(1 | 2 | 4 | 8);
  16972. }
  16973. parseStatementListItem() {
  16974. return this.parseStatementLike(2 | 4 | (!this.options.annexB || this.state.strict ? 0 : 8));
  16975. }
  16976. parseStatementOrSloppyAnnexBFunctionDeclaration(allowLabeledFunction = false) {
  16977. let flags = 0;
  16978. if (this.options.annexB && !this.state.strict) {
  16979. flags |= 4;
  16980. if (allowLabeledFunction) {
  16981. flags |= 8;
  16982. }
  16983. }
  16984. return this.parseStatementLike(flags);
  16985. }
  16986. parseStatement() {
  16987. return this.parseStatementLike(0);
  16988. }
  16989. parseStatementLike(flags) {
  16990. let decorators = null;
  16991. if (this.match(26)) {
  16992. decorators = this.parseDecorators(true);
  16993. }
  16994. return this.parseStatementContent(flags, decorators);
  16995. }
  16996. parseStatementContent(flags, decorators) {
  16997. const startType = this.state.type;
  16998. const node = this.startNode();
  16999. const allowDeclaration = !!(flags & 2);
  17000. const allowFunctionDeclaration = !!(flags & 4);
  17001. const topLevel = flags & 1;
  17002. switch (startType) {
  17003. case 60:
  17004. return this.parseBreakContinueStatement(node, true);
  17005. case 63:
  17006. return this.parseBreakContinueStatement(node, false);
  17007. case 64:
  17008. return this.parseDebuggerStatement(node);
  17009. case 90:
  17010. return this.parseDoWhileStatement(node);
  17011. case 91:
  17012. return this.parseForStatement(node);
  17013. case 68:
  17014. if (this.lookaheadCharCode() === 46) break;
  17015. if (!allowFunctionDeclaration) {
  17016. this.raise(this.state.strict ? Errors.StrictFunction : this.options.annexB ? Errors.SloppyFunctionAnnexB : Errors.SloppyFunction, this.state.startLoc);
  17017. }
  17018. return this.parseFunctionStatement(node, false, !allowDeclaration && allowFunctionDeclaration);
  17019. case 80:
  17020. if (!allowDeclaration) this.unexpected();
  17021. return this.parseClass(this.maybeTakeDecorators(decorators, node), true);
  17022. case 69:
  17023. return this.parseIfStatement(node);
  17024. case 70:
  17025. return this.parseReturnStatement(node);
  17026. case 71:
  17027. return this.parseSwitchStatement(node);
  17028. case 72:
  17029. return this.parseThrowStatement(node);
  17030. case 73:
  17031. return this.parseTryStatement(node);
  17032. case 96:
  17033. if (this.isAwaitUsing()) {
  17034. if (!this.allowsUsing()) {
  17035. this.raise(Errors.UnexpectedUsingDeclaration, node);
  17036. } else if (!allowDeclaration) {
  17037. this.raise(Errors.UnexpectedLexicalDeclaration, node);
  17038. } else if (!this.recordAwaitIfAllowed()) {
  17039. this.raise(Errors.AwaitUsingNotInAsyncContext, node);
  17040. }
  17041. this.next();
  17042. return this.parseVarStatement(node, "await using");
  17043. }
  17044. break;
  17045. case 107:
  17046. if (this.state.containsEsc || !this.hasInLineFollowingBindingIdentifierOrBrace()) {
  17047. break;
  17048. }
  17049. if (!this.allowsUsing()) {
  17050. this.raise(Errors.UnexpectedUsingDeclaration, this.state.startLoc);
  17051. } else if (!allowDeclaration) {
  17052. this.raise(Errors.UnexpectedLexicalDeclaration, this.state.startLoc);
  17053. }
  17054. return this.parseVarStatement(node, "using");
  17055. case 100:
  17056. {
  17057. if (this.state.containsEsc) {
  17058. break;
  17059. }
  17060. const next = this.nextTokenStart();
  17061. const nextCh = this.codePointAtPos(next);
  17062. if (nextCh !== 91) {
  17063. if (!allowDeclaration && this.hasFollowingLineBreak()) break;
  17064. if (!this.chStartsBindingIdentifier(nextCh, next) && nextCh !== 123) {
  17065. break;
  17066. }
  17067. }
  17068. }
  17069. case 75:
  17070. {
  17071. if (!allowDeclaration) {
  17072. this.raise(Errors.UnexpectedLexicalDeclaration, this.state.startLoc);
  17073. }
  17074. }
  17075. case 74:
  17076. {
  17077. const kind = this.state.value;
  17078. return this.parseVarStatement(node, kind);
  17079. }
  17080. case 92:
  17081. return this.parseWhileStatement(node);
  17082. case 76:
  17083. return this.parseWithStatement(node);
  17084. case 5:
  17085. return this.parseBlock();
  17086. case 13:
  17087. return this.parseEmptyStatement(node);
  17088. case 83:
  17089. {
  17090. const nextTokenCharCode = this.lookaheadCharCode();
  17091. if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
  17092. break;
  17093. }
  17094. }
  17095. case 82:
  17096. {
  17097. if (!(this.optionFlags & 8) && !topLevel) {
  17098. this.raise(Errors.UnexpectedImportExport, this.state.startLoc);
  17099. }
  17100. this.next();
  17101. let result;
  17102. if (startType === 83) {
  17103. result = this.parseImport(node);
  17104. } else {
  17105. result = this.parseExport(node, decorators);
  17106. }
  17107. this.assertModuleNodeAllowed(result);
  17108. return result;
  17109. }
  17110. default:
  17111. {
  17112. if (this.isAsyncFunction()) {
  17113. if (!allowDeclaration) {
  17114. this.raise(Errors.AsyncFunctionInSingleStatementContext, this.state.startLoc);
  17115. }
  17116. this.next();
  17117. return this.parseFunctionStatement(node, true, !allowDeclaration && allowFunctionDeclaration);
  17118. }
  17119. }
  17120. }
  17121. const maybeName = this.state.value;
  17122. const expr = this.parseExpression();
  17123. if (tokenIsIdentifier(startType) && expr.type === "Identifier" && this.eat(14)) {
  17124. return this.parseLabeledStatement(node, maybeName, expr, flags);
  17125. } else {
  17126. return this.parseExpressionStatement(node, expr, decorators);
  17127. }
  17128. }
  17129. assertModuleNodeAllowed(node) {
  17130. if (!(this.optionFlags & 8) && !this.inModule) {
  17131. this.raise(Errors.ImportOutsideModule, node);
  17132. }
  17133. }
  17134. decoratorsEnabledBeforeExport() {
  17135. if (this.hasPlugin("decorators-legacy")) return true;
  17136. return this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") !== false;
  17137. }
  17138. maybeTakeDecorators(maybeDecorators, classNode, exportNode) {
  17139. if (maybeDecorators) {
  17140. var _classNode$decorators;
  17141. if ((_classNode$decorators = classNode.decorators) != null && _classNode$decorators.length) {
  17142. if (typeof this.getPluginOption("decorators", "decoratorsBeforeExport") !== "boolean") {
  17143. this.raise(Errors.DecoratorsBeforeAfterExport, classNode.decorators[0]);
  17144. }
  17145. classNode.decorators.unshift(...maybeDecorators);
  17146. } else {
  17147. classNode.decorators = maybeDecorators;
  17148. }
  17149. this.resetStartLocationFromNode(classNode, maybeDecorators[0]);
  17150. if (exportNode) this.resetStartLocationFromNode(exportNode, classNode);
  17151. }
  17152. return classNode;
  17153. }
  17154. canHaveLeadingDecorator() {
  17155. return this.match(80);
  17156. }
  17157. parseDecorators(allowExport) {
  17158. const decorators = [];
  17159. do {
  17160. decorators.push(this.parseDecorator());
  17161. } while (this.match(26));
  17162. if (this.match(82)) {
  17163. if (!allowExport) {
  17164. this.unexpected();
  17165. }
  17166. if (!this.decoratorsEnabledBeforeExport()) {
  17167. this.raise(Errors.DecoratorExportClass, this.state.startLoc);
  17168. }
  17169. } else if (!this.canHaveLeadingDecorator()) {
  17170. throw this.raise(Errors.UnexpectedLeadingDecorator, this.state.startLoc);
  17171. }
  17172. return decorators;
  17173. }
  17174. parseDecorator() {
  17175. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  17176. const node = this.startNode();
  17177. this.next();
  17178. if (this.hasPlugin("decorators")) {
  17179. const startLoc = this.state.startLoc;
  17180. let expr;
  17181. if (this.match(10)) {
  17182. const startLoc = this.state.startLoc;
  17183. this.next();
  17184. expr = this.parseExpression();
  17185. this.expect(11);
  17186. expr = this.wrapParenthesis(startLoc, expr);
  17187. const paramsStartLoc = this.state.startLoc;
  17188. node.expression = this.parseMaybeDecoratorArguments(expr, startLoc);
  17189. if (this.getPluginOption("decorators", "allowCallParenthesized") === false && node.expression !== expr) {
  17190. this.raise(Errors.DecoratorArgumentsOutsideParentheses, paramsStartLoc);
  17191. }
  17192. } else {
  17193. expr = this.parseIdentifier(false);
  17194. while (this.eat(16)) {
  17195. const node = this.startNodeAt(startLoc);
  17196. node.object = expr;
  17197. if (this.match(139)) {
  17198. this.classScope.usePrivateName(this.state.value, this.state.startLoc);
  17199. node.property = this.parsePrivateName();
  17200. } else {
  17201. node.property = this.parseIdentifier(true);
  17202. }
  17203. node.computed = false;
  17204. expr = this.finishNode(node, "MemberExpression");
  17205. }
  17206. node.expression = this.parseMaybeDecoratorArguments(expr, startLoc);
  17207. }
  17208. } else {
  17209. node.expression = this.parseExprSubscripts();
  17210. }
  17211. return this.finishNode(node, "Decorator");
  17212. }
  17213. parseMaybeDecoratorArguments(expr, startLoc) {
  17214. if (this.eat(10)) {
  17215. const node = this.startNodeAt(startLoc);
  17216. node.callee = expr;
  17217. node.arguments = this.parseCallExpressionArguments();
  17218. this.toReferencedList(node.arguments);
  17219. return this.finishNode(node, "CallExpression");
  17220. }
  17221. return expr;
  17222. }
  17223. parseBreakContinueStatement(node, isBreak) {
  17224. this.next();
  17225. if (this.isLineTerminator()) {
  17226. node.label = null;
  17227. } else {
  17228. node.label = this.parseIdentifier();
  17229. this.semicolon();
  17230. }
  17231. this.verifyBreakContinue(node, isBreak);
  17232. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  17233. }
  17234. verifyBreakContinue(node, isBreak) {
  17235. let i;
  17236. for (i = 0; i < this.state.labels.length; ++i) {
  17237. const lab = this.state.labels[i];
  17238. if (node.label == null || lab.name === node.label.name) {
  17239. if (lab.kind != null && (isBreak || lab.kind === 1)) {
  17240. break;
  17241. }
  17242. if (node.label && isBreak) break;
  17243. }
  17244. }
  17245. if (i === this.state.labels.length) {
  17246. const type = isBreak ? "BreakStatement" : "ContinueStatement";
  17247. this.raise(Errors.IllegalBreakContinue, node, {
  17248. type
  17249. });
  17250. }
  17251. }
  17252. parseDebuggerStatement(node) {
  17253. this.next();
  17254. this.semicolon();
  17255. return this.finishNode(node, "DebuggerStatement");
  17256. }
  17257. parseHeaderExpression() {
  17258. this.expect(10);
  17259. const val = this.parseExpression();
  17260. this.expect(11);
  17261. return val;
  17262. }
  17263. parseDoWhileStatement(node) {
  17264. this.next();
  17265. this.state.labels.push(loopLabel);
  17266. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  17267. this.state.labels.pop();
  17268. this.expect(92);
  17269. node.test = this.parseHeaderExpression();
  17270. this.eat(13);
  17271. return this.finishNode(node, "DoWhileStatement");
  17272. }
  17273. parseForStatement(node) {
  17274. this.next();
  17275. this.state.labels.push(loopLabel);
  17276. let awaitAt = null;
  17277. if (this.isContextual(96) && this.recordAwaitIfAllowed()) {
  17278. awaitAt = this.state.startLoc;
  17279. this.next();
  17280. }
  17281. this.scope.enter(0);
  17282. this.expect(10);
  17283. if (this.match(13)) {
  17284. if (awaitAt !== null) {
  17285. this.unexpected(awaitAt);
  17286. }
  17287. return this.parseFor(node, null);
  17288. }
  17289. const startsWithLet = this.isContextual(100);
  17290. {
  17291. const startsWithAwaitUsing = this.isAwaitUsing();
  17292. const starsWithUsingDeclaration = startsWithAwaitUsing || this.isForUsing();
  17293. const isLetOrUsing = startsWithLet && this.hasFollowingBindingAtom() || starsWithUsingDeclaration;
  17294. if (this.match(74) || this.match(75) || isLetOrUsing) {
  17295. const initNode = this.startNode();
  17296. let kind;
  17297. if (startsWithAwaitUsing) {
  17298. kind = "await using";
  17299. if (!this.recordAwaitIfAllowed()) {
  17300. this.raise(Errors.AwaitUsingNotInAsyncContext, this.state.startLoc);
  17301. }
  17302. this.next();
  17303. } else {
  17304. kind = this.state.value;
  17305. }
  17306. this.next();
  17307. this.parseVar(initNode, true, kind);
  17308. const init = this.finishNode(initNode, "VariableDeclaration");
  17309. const isForIn = this.match(58);
  17310. if (isForIn && starsWithUsingDeclaration) {
  17311. this.raise(Errors.ForInUsing, init);
  17312. }
  17313. if ((isForIn || this.isContextual(102)) && init.declarations.length === 1) {
  17314. return this.parseForIn(node, init, awaitAt);
  17315. }
  17316. if (awaitAt !== null) {
  17317. this.unexpected(awaitAt);
  17318. }
  17319. return this.parseFor(node, init);
  17320. }
  17321. }
  17322. const startsWithAsync = this.isContextual(95);
  17323. const refExpressionErrors = new ExpressionErrors();
  17324. const init = this.parseExpression(true, refExpressionErrors);
  17325. const isForOf = this.isContextual(102);
  17326. if (isForOf) {
  17327. if (startsWithLet) {
  17328. this.raise(Errors.ForOfLet, init);
  17329. }
  17330. if (awaitAt === null && startsWithAsync && init.type === "Identifier") {
  17331. this.raise(Errors.ForOfAsync, init);
  17332. }
  17333. }
  17334. if (isForOf || this.match(58)) {
  17335. this.checkDestructuringPrivate(refExpressionErrors);
  17336. this.toAssignable(init, true);
  17337. const type = isForOf ? "ForOfStatement" : "ForInStatement";
  17338. this.checkLVal(init, {
  17339. type
  17340. });
  17341. return this.parseForIn(node, init, awaitAt);
  17342. } else {
  17343. this.checkExpressionErrors(refExpressionErrors, true);
  17344. }
  17345. if (awaitAt !== null) {
  17346. this.unexpected(awaitAt);
  17347. }
  17348. return this.parseFor(node, init);
  17349. }
  17350. parseFunctionStatement(node, isAsync, isHangingDeclaration) {
  17351. this.next();
  17352. return this.parseFunction(node, 1 | (isHangingDeclaration ? 2 : 0) | (isAsync ? 8 : 0));
  17353. }
  17354. parseIfStatement(node) {
  17355. this.next();
  17356. node.test = this.parseHeaderExpression();
  17357. node.consequent = this.parseStatementOrSloppyAnnexBFunctionDeclaration();
  17358. node.alternate = this.eat(66) ? this.parseStatementOrSloppyAnnexBFunctionDeclaration() : null;
  17359. return this.finishNode(node, "IfStatement");
  17360. }
  17361. parseReturnStatement(node) {
  17362. if (!this.prodParam.hasReturn) {
  17363. this.raise(Errors.IllegalReturn, this.state.startLoc);
  17364. }
  17365. this.next();
  17366. if (this.isLineTerminator()) {
  17367. node.argument = null;
  17368. } else {
  17369. node.argument = this.parseExpression();
  17370. this.semicolon();
  17371. }
  17372. return this.finishNode(node, "ReturnStatement");
  17373. }
  17374. parseSwitchStatement(node) {
  17375. this.next();
  17376. node.discriminant = this.parseHeaderExpression();
  17377. const cases = node.cases = [];
  17378. this.expect(5);
  17379. this.state.labels.push(switchLabel);
  17380. this.scope.enter(256);
  17381. let cur;
  17382. for (let sawDefault; !this.match(8);) {
  17383. if (this.match(61) || this.match(65)) {
  17384. const isCase = this.match(61);
  17385. if (cur) this.finishNode(cur, "SwitchCase");
  17386. cases.push(cur = this.startNode());
  17387. cur.consequent = [];
  17388. this.next();
  17389. if (isCase) {
  17390. cur.test = this.parseExpression();
  17391. } else {
  17392. if (sawDefault) {
  17393. this.raise(Errors.MultipleDefaultsInSwitch, this.state.lastTokStartLoc);
  17394. }
  17395. sawDefault = true;
  17396. cur.test = null;
  17397. }
  17398. this.expect(14);
  17399. } else {
  17400. if (cur) {
  17401. cur.consequent.push(this.parseStatementListItem());
  17402. } else {
  17403. this.unexpected();
  17404. }
  17405. }
  17406. }
  17407. this.scope.exit();
  17408. if (cur) this.finishNode(cur, "SwitchCase");
  17409. this.next();
  17410. this.state.labels.pop();
  17411. return this.finishNode(node, "SwitchStatement");
  17412. }
  17413. parseThrowStatement(node) {
  17414. this.next();
  17415. if (this.hasPrecedingLineBreak()) {
  17416. this.raise(Errors.NewlineAfterThrow, this.state.lastTokEndLoc);
  17417. }
  17418. node.argument = this.parseExpression();
  17419. this.semicolon();
  17420. return this.finishNode(node, "ThrowStatement");
  17421. }
  17422. parseCatchClauseParam() {
  17423. const param = this.parseBindingAtom();
  17424. this.scope.enter(this.options.annexB && param.type === "Identifier" ? 8 : 0);
  17425. this.checkLVal(param, {
  17426. type: "CatchClause"
  17427. }, 9);
  17428. return param;
  17429. }
  17430. parseTryStatement(node) {
  17431. this.next();
  17432. node.block = this.parseBlock();
  17433. node.handler = null;
  17434. if (this.match(62)) {
  17435. const clause = this.startNode();
  17436. this.next();
  17437. if (this.match(10)) {
  17438. this.expect(10);
  17439. clause.param = this.parseCatchClauseParam();
  17440. this.expect(11);
  17441. } else {
  17442. clause.param = null;
  17443. this.scope.enter(0);
  17444. }
  17445. clause.body = this.withSmartMixTopicForbiddingContext(() => this.parseBlock(false, false));
  17446. this.scope.exit();
  17447. node.handler = this.finishNode(clause, "CatchClause");
  17448. }
  17449. node.finalizer = this.eat(67) ? this.parseBlock() : null;
  17450. if (!node.handler && !node.finalizer) {
  17451. this.raise(Errors.NoCatchOrFinally, node);
  17452. }
  17453. return this.finishNode(node, "TryStatement");
  17454. }
  17455. parseVarStatement(node, kind, allowMissingInitializer = false) {
  17456. this.next();
  17457. this.parseVar(node, false, kind, allowMissingInitializer);
  17458. this.semicolon();
  17459. return this.finishNode(node, "VariableDeclaration");
  17460. }
  17461. parseWhileStatement(node) {
  17462. this.next();
  17463. node.test = this.parseHeaderExpression();
  17464. this.state.labels.push(loopLabel);
  17465. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  17466. this.state.labels.pop();
  17467. return this.finishNode(node, "WhileStatement");
  17468. }
  17469. parseWithStatement(node) {
  17470. if (this.state.strict) {
  17471. this.raise(Errors.StrictWith, this.state.startLoc);
  17472. }
  17473. this.next();
  17474. node.object = this.parseHeaderExpression();
  17475. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  17476. return this.finishNode(node, "WithStatement");
  17477. }
  17478. parseEmptyStatement(node) {
  17479. this.next();
  17480. return this.finishNode(node, "EmptyStatement");
  17481. }
  17482. parseLabeledStatement(node, maybeName, expr, flags) {
  17483. for (const label of this.state.labels) {
  17484. if (label.name === maybeName) {
  17485. this.raise(Errors.LabelRedeclaration, expr, {
  17486. labelName: maybeName
  17487. });
  17488. }
  17489. }
  17490. const kind = tokenIsLoop(this.state.type) ? 1 : this.match(71) ? 2 : null;
  17491. for (let i = this.state.labels.length - 1; i >= 0; i--) {
  17492. const label = this.state.labels[i];
  17493. if (label.statementStart === node.start) {
  17494. label.statementStart = this.sourceToOffsetPos(this.state.start);
  17495. label.kind = kind;
  17496. } else {
  17497. break;
  17498. }
  17499. }
  17500. this.state.labels.push({
  17501. name: maybeName,
  17502. kind: kind,
  17503. statementStart: this.sourceToOffsetPos(this.state.start)
  17504. });
  17505. node.body = flags & 8 ? this.parseStatementOrSloppyAnnexBFunctionDeclaration(true) : this.parseStatement();
  17506. this.state.labels.pop();
  17507. node.label = expr;
  17508. return this.finishNode(node, "LabeledStatement");
  17509. }
  17510. parseExpressionStatement(node, expr, decorators) {
  17511. node.expression = expr;
  17512. this.semicolon();
  17513. return this.finishNode(node, "ExpressionStatement");
  17514. }
  17515. parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) {
  17516. const node = this.startNode();
  17517. if (allowDirectives) {
  17518. this.state.strictErrors.clear();
  17519. }
  17520. this.expect(5);
  17521. if (createNewLexicalScope) {
  17522. this.scope.enter(0);
  17523. }
  17524. this.parseBlockBody(node, allowDirectives, false, 8, afterBlockParse);
  17525. if (createNewLexicalScope) {
  17526. this.scope.exit();
  17527. }
  17528. return this.finishNode(node, "BlockStatement");
  17529. }
  17530. isValidDirective(stmt) {
  17531. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  17532. }
  17533. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  17534. const body = node.body = [];
  17535. const directives = node.directives = [];
  17536. this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse);
  17537. }
  17538. parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) {
  17539. const oldStrict = this.state.strict;
  17540. let hasStrictModeDirective = false;
  17541. let parsedNonDirective = false;
  17542. while (!this.match(end)) {
  17543. const stmt = topLevel ? this.parseModuleItem() : this.parseStatementListItem();
  17544. if (directives && !parsedNonDirective) {
  17545. if (this.isValidDirective(stmt)) {
  17546. const directive = this.stmtToDirective(stmt);
  17547. directives.push(directive);
  17548. if (!hasStrictModeDirective && directive.value.value === "use strict") {
  17549. hasStrictModeDirective = true;
  17550. this.setStrict(true);
  17551. }
  17552. continue;
  17553. }
  17554. parsedNonDirective = true;
  17555. this.state.strictErrors.clear();
  17556. }
  17557. body.push(stmt);
  17558. }
  17559. afterBlockParse == null || afterBlockParse.call(this, hasStrictModeDirective);
  17560. if (!oldStrict) {
  17561. this.setStrict(false);
  17562. }
  17563. this.next();
  17564. }
  17565. parseFor(node, init) {
  17566. node.init = init;
  17567. this.semicolon(false);
  17568. node.test = this.match(13) ? null : this.parseExpression();
  17569. this.semicolon(false);
  17570. node.update = this.match(11) ? null : this.parseExpression();
  17571. this.expect(11);
  17572. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  17573. this.scope.exit();
  17574. this.state.labels.pop();
  17575. return this.finishNode(node, "ForStatement");
  17576. }
  17577. parseForIn(node, init, awaitAt) {
  17578. const isForIn = this.match(58);
  17579. this.next();
  17580. if (isForIn) {
  17581. if (awaitAt !== null) this.unexpected(awaitAt);
  17582. } else {
  17583. node.await = awaitAt !== null;
  17584. }
  17585. if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || !this.options.annexB || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
  17586. this.raise(Errors.ForInOfLoopInitializer, init, {
  17587. type: isForIn ? "ForInStatement" : "ForOfStatement"
  17588. });
  17589. }
  17590. if (init.type === "AssignmentPattern") {
  17591. this.raise(Errors.InvalidLhs, init, {
  17592. ancestor: {
  17593. type: "ForStatement"
  17594. }
  17595. });
  17596. }
  17597. node.left = init;
  17598. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn();
  17599. this.expect(11);
  17600. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  17601. this.scope.exit();
  17602. this.state.labels.pop();
  17603. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
  17604. }
  17605. parseVar(node, isFor, kind, allowMissingInitializer = false) {
  17606. const declarations = node.declarations = [];
  17607. node.kind = kind;
  17608. for (;;) {
  17609. const decl = this.startNode();
  17610. this.parseVarId(decl, kind);
  17611. decl.init = !this.eat(29) ? null : isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn();
  17612. if (decl.init === null && !allowMissingInitializer) {
  17613. if (decl.id.type !== "Identifier" && !(isFor && (this.match(58) || this.isContextual(102)))) {
  17614. this.raise(Errors.DeclarationMissingInitializer, this.state.lastTokEndLoc, {
  17615. kind: "destructuring"
  17616. });
  17617. } else if ((kind === "const" || kind === "using" || kind === "await using") && !(this.match(58) || this.isContextual(102))) {
  17618. this.raise(Errors.DeclarationMissingInitializer, this.state.lastTokEndLoc, {
  17619. kind
  17620. });
  17621. }
  17622. }
  17623. declarations.push(this.finishNode(decl, "VariableDeclarator"));
  17624. if (!this.eat(12)) break;
  17625. }
  17626. return node;
  17627. }
  17628. parseVarId(decl, kind) {
  17629. const id = this.parseBindingAtom();
  17630. if (kind === "using" || kind === "await using") {
  17631. if (id.type === "ArrayPattern" || id.type === "ObjectPattern") {
  17632. this.raise(Errors.UsingDeclarationHasBindingPattern, id.loc.start);
  17633. }
  17634. } else {
  17635. if (id.type === "VoidPattern") {
  17636. this.raise(Errors.UnexpectedVoidPattern, id.loc.start);
  17637. }
  17638. }
  17639. this.checkLVal(id, {
  17640. type: "VariableDeclarator"
  17641. }, kind === "var" ? 5 : 8201);
  17642. decl.id = id;
  17643. }
  17644. parseAsyncFunctionExpression(node) {
  17645. return this.parseFunction(node, 8);
  17646. }
  17647. parseFunction(node, flags = 0) {
  17648. const hangingDeclaration = flags & 2;
  17649. const isDeclaration = !!(flags & 1);
  17650. const requireId = isDeclaration && !(flags & 4);
  17651. const isAsync = !!(flags & 8);
  17652. this.initFunction(node, isAsync);
  17653. if (this.match(55)) {
  17654. if (hangingDeclaration) {
  17655. this.raise(Errors.GeneratorInSingleStatementContext, this.state.startLoc);
  17656. }
  17657. this.next();
  17658. node.generator = true;
  17659. }
  17660. if (isDeclaration) {
  17661. node.id = this.parseFunctionId(requireId);
  17662. }
  17663. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  17664. this.state.maybeInArrowParameters = false;
  17665. this.scope.enter(514);
  17666. this.prodParam.enter(functionFlags(isAsync, node.generator));
  17667. if (!isDeclaration) {
  17668. node.id = this.parseFunctionId();
  17669. }
  17670. this.parseFunctionParams(node, false);
  17671. this.withSmartMixTopicForbiddingContext(() => {
  17672. this.parseFunctionBodyAndFinish(node, isDeclaration ? "FunctionDeclaration" : "FunctionExpression");
  17673. });
  17674. this.prodParam.exit();
  17675. this.scope.exit();
  17676. if (isDeclaration && !hangingDeclaration) {
  17677. this.registerFunctionStatementId(node);
  17678. }
  17679. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  17680. return node;
  17681. }
  17682. parseFunctionId(requireId) {
  17683. return requireId || tokenIsIdentifier(this.state.type) ? this.parseIdentifier() : null;
  17684. }
  17685. parseFunctionParams(node, isConstructor) {
  17686. this.expect(10);
  17687. this.expressionScope.enter(newParameterDeclarationScope());
  17688. node.params = this.parseBindingList(11, 41, 2 | (isConstructor ? 4 : 0));
  17689. this.expressionScope.exit();
  17690. }
  17691. registerFunctionStatementId(node) {
  17692. if (!node.id) return;
  17693. this.scope.declareName(node.id.name, !this.options.annexB || this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? 5 : 8201 : 17, node.id.loc.start);
  17694. }
  17695. parseClass(node, isStatement, optionalId) {
  17696. this.next();
  17697. const oldStrict = this.state.strict;
  17698. this.state.strict = true;
  17699. this.parseClassId(node, isStatement, optionalId);
  17700. this.parseClassSuper(node);
  17701. node.body = this.parseClassBody(!!node.superClass, oldStrict);
  17702. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  17703. }
  17704. isClassProperty() {
  17705. return this.match(29) || this.match(13) || this.match(8);
  17706. }
  17707. isClassMethod() {
  17708. return this.match(10);
  17709. }
  17710. nameIsConstructor(key) {
  17711. return key.type === "Identifier" && key.name === "constructor" || key.type === "StringLiteral" && key.value === "constructor";
  17712. }
  17713. isNonstaticConstructor(method) {
  17714. return !method.computed && !method.static && this.nameIsConstructor(method.key);
  17715. }
  17716. parseClassBody(hadSuperClass, oldStrict) {
  17717. this.classScope.enter();
  17718. const state = {
  17719. hadConstructor: false,
  17720. hadSuperClass
  17721. };
  17722. let decorators = [];
  17723. const classBody = this.startNode();
  17724. classBody.body = [];
  17725. this.expect(5);
  17726. this.withSmartMixTopicForbiddingContext(() => {
  17727. while (!this.match(8)) {
  17728. if (this.eat(13)) {
  17729. if (decorators.length > 0) {
  17730. throw this.raise(Errors.DecoratorSemicolon, this.state.lastTokEndLoc);
  17731. }
  17732. continue;
  17733. }
  17734. if (this.match(26)) {
  17735. decorators.push(this.parseDecorator());
  17736. continue;
  17737. }
  17738. const member = this.startNode();
  17739. if (decorators.length) {
  17740. member.decorators = decorators;
  17741. this.resetStartLocationFromNode(member, decorators[0]);
  17742. decorators = [];
  17743. }
  17744. this.parseClassMember(classBody, member, state);
  17745. if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
  17746. this.raise(Errors.DecoratorConstructor, member);
  17747. }
  17748. }
  17749. });
  17750. this.state.strict = oldStrict;
  17751. this.next();
  17752. if (decorators.length) {
  17753. throw this.raise(Errors.TrailingDecorator, this.state.startLoc);
  17754. }
  17755. this.classScope.exit();
  17756. return this.finishNode(classBody, "ClassBody");
  17757. }
  17758. parseClassMemberFromModifier(classBody, member) {
  17759. const key = this.parseIdentifier(true);
  17760. if (this.isClassMethod()) {
  17761. const method = member;
  17762. method.kind = "method";
  17763. method.computed = false;
  17764. method.key = key;
  17765. method.static = false;
  17766. this.pushClassMethod(classBody, method, false, false, false, false);
  17767. return true;
  17768. } else if (this.isClassProperty()) {
  17769. const prop = member;
  17770. prop.computed = false;
  17771. prop.key = key;
  17772. prop.static = false;
  17773. classBody.body.push(this.parseClassProperty(prop));
  17774. return true;
  17775. }
  17776. this.resetPreviousNodeTrailingComments(key);
  17777. return false;
  17778. }
  17779. parseClassMember(classBody, member, state) {
  17780. const isStatic = this.isContextual(106);
  17781. if (isStatic) {
  17782. if (this.parseClassMemberFromModifier(classBody, member)) {
  17783. return;
  17784. }
  17785. if (this.eat(5)) {
  17786. this.parseClassStaticBlock(classBody, member);
  17787. return;
  17788. }
  17789. }
  17790. this.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  17791. }
  17792. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  17793. const publicMethod = member;
  17794. const privateMethod = member;
  17795. const publicProp = member;
  17796. const privateProp = member;
  17797. const accessorProp = member;
  17798. const method = publicMethod;
  17799. const publicMember = publicMethod;
  17800. member.static = isStatic;
  17801. this.parsePropertyNamePrefixOperator(member);
  17802. if (this.eat(55)) {
  17803. method.kind = "method";
  17804. const isPrivateName = this.match(139);
  17805. this.parseClassElementName(method);
  17806. this.parsePostMemberNameModifiers(method);
  17807. if (isPrivateName) {
  17808. this.pushClassPrivateMethod(classBody, privateMethod, true, false);
  17809. return;
  17810. }
  17811. if (this.isNonstaticConstructor(publicMethod)) {
  17812. this.raise(Errors.ConstructorIsGenerator, publicMethod.key);
  17813. }
  17814. this.pushClassMethod(classBody, publicMethod, true, false, false, false);
  17815. return;
  17816. }
  17817. const isContextual = !this.state.containsEsc && tokenIsIdentifier(this.state.type);
  17818. const key = this.parseClassElementName(member);
  17819. const maybeContextualKw = isContextual ? key.name : null;
  17820. const isPrivate = this.isPrivateName(key);
  17821. const maybeQuestionTokenStartLoc = this.state.startLoc;
  17822. this.parsePostMemberNameModifiers(publicMember);
  17823. if (this.isClassMethod()) {
  17824. method.kind = "method";
  17825. if (isPrivate) {
  17826. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  17827. return;
  17828. }
  17829. const isConstructor = this.isNonstaticConstructor(publicMethod);
  17830. let allowsDirectSuper = false;
  17831. if (isConstructor) {
  17832. publicMethod.kind = "constructor";
  17833. if (state.hadConstructor && !this.hasPlugin("typescript")) {
  17834. this.raise(Errors.DuplicateConstructor, key);
  17835. }
  17836. if (isConstructor && this.hasPlugin("typescript") && member.override) {
  17837. this.raise(Errors.OverrideOnConstructor, key);
  17838. }
  17839. state.hadConstructor = true;
  17840. allowsDirectSuper = state.hadSuperClass;
  17841. }
  17842. this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
  17843. } else if (this.isClassProperty()) {
  17844. if (isPrivate) {
  17845. this.pushClassPrivateProperty(classBody, privateProp);
  17846. } else {
  17847. this.pushClassProperty(classBody, publicProp);
  17848. }
  17849. } else if (maybeContextualKw === "async" && !this.isLineTerminator()) {
  17850. this.resetPreviousNodeTrailingComments(key);
  17851. const isGenerator = this.eat(55);
  17852. if (publicMember.optional) {
  17853. this.unexpected(maybeQuestionTokenStartLoc);
  17854. }
  17855. method.kind = "method";
  17856. const isPrivate = this.match(139);
  17857. this.parseClassElementName(method);
  17858. this.parsePostMemberNameModifiers(publicMember);
  17859. if (isPrivate) {
  17860. this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
  17861. } else {
  17862. if (this.isNonstaticConstructor(publicMethod)) {
  17863. this.raise(Errors.ConstructorIsAsync, publicMethod.key);
  17864. }
  17865. this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
  17866. }
  17867. } else if ((maybeContextualKw === "get" || maybeContextualKw === "set") && !(this.match(55) && this.isLineTerminator())) {
  17868. this.resetPreviousNodeTrailingComments(key);
  17869. method.kind = maybeContextualKw;
  17870. const isPrivate = this.match(139);
  17871. this.parseClassElementName(publicMethod);
  17872. if (isPrivate) {
  17873. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  17874. } else {
  17875. if (this.isNonstaticConstructor(publicMethod)) {
  17876. this.raise(Errors.ConstructorIsAccessor, publicMethod.key);
  17877. }
  17878. this.pushClassMethod(classBody, publicMethod, false, false, false, false);
  17879. }
  17880. this.checkGetterSetterParams(publicMethod);
  17881. } else if (maybeContextualKw === "accessor" && !this.isLineTerminator()) {
  17882. this.expectPlugin("decoratorAutoAccessors");
  17883. this.resetPreviousNodeTrailingComments(key);
  17884. const isPrivate = this.match(139);
  17885. this.parseClassElementName(publicProp);
  17886. this.pushClassAccessorProperty(classBody, accessorProp, isPrivate);
  17887. } else if (this.isLineTerminator()) {
  17888. if (isPrivate) {
  17889. this.pushClassPrivateProperty(classBody, privateProp);
  17890. } else {
  17891. this.pushClassProperty(classBody, publicProp);
  17892. }
  17893. } else {
  17894. this.unexpected();
  17895. }
  17896. }
  17897. parseClassElementName(member) {
  17898. const {
  17899. type,
  17900. value
  17901. } = this.state;
  17902. if ((type === 132 || type === 134) && member.static && value === "prototype") {
  17903. this.raise(Errors.StaticPrototype, this.state.startLoc);
  17904. }
  17905. if (type === 139) {
  17906. if (value === "constructor") {
  17907. this.raise(Errors.ConstructorClassPrivateField, this.state.startLoc);
  17908. }
  17909. const key = this.parsePrivateName();
  17910. member.key = key;
  17911. return key;
  17912. }
  17913. this.parsePropertyName(member);
  17914. return member.key;
  17915. }
  17916. parseClassStaticBlock(classBody, member) {
  17917. var _member$decorators;
  17918. this.scope.enter(576 | 128 | 16);
  17919. const oldLabels = this.state.labels;
  17920. this.state.labels = [];
  17921. this.prodParam.enter(0);
  17922. const body = member.body = [];
  17923. this.parseBlockOrModuleBlockBody(body, undefined, false, 8);
  17924. this.prodParam.exit();
  17925. this.scope.exit();
  17926. this.state.labels = oldLabels;
  17927. classBody.body.push(this.finishNode(member, "StaticBlock"));
  17928. if ((_member$decorators = member.decorators) != null && _member$decorators.length) {
  17929. this.raise(Errors.DecoratorStaticBlock, member);
  17930. }
  17931. }
  17932. pushClassProperty(classBody, prop) {
  17933. if (!prop.computed && this.nameIsConstructor(prop.key)) {
  17934. this.raise(Errors.ConstructorClassField, prop.key);
  17935. }
  17936. classBody.body.push(this.parseClassProperty(prop));
  17937. }
  17938. pushClassPrivateProperty(classBody, prop) {
  17939. const node = this.parseClassPrivateProperty(prop);
  17940. classBody.body.push(node);
  17941. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 0, node.key.loc.start);
  17942. }
  17943. pushClassAccessorProperty(classBody, prop, isPrivate) {
  17944. if (!isPrivate && !prop.computed && this.nameIsConstructor(prop.key)) {
  17945. this.raise(Errors.ConstructorClassField, prop.key);
  17946. }
  17947. const node = this.parseClassAccessorProperty(prop);
  17948. classBody.body.push(node);
  17949. if (isPrivate) {
  17950. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 0, node.key.loc.start);
  17951. }
  17952. }
  17953. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  17954. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  17955. }
  17956. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  17957. const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
  17958. classBody.body.push(node);
  17959. const kind = node.kind === "get" ? node.static ? 6 : 2 : node.kind === "set" ? node.static ? 5 : 1 : 0;
  17960. this.declareClassPrivateMethodInScope(node, kind);
  17961. }
  17962. declareClassPrivateMethodInScope(node, kind) {
  17963. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), kind, node.key.loc.start);
  17964. }
  17965. parsePostMemberNameModifiers(methodOrProp) {}
  17966. parseClassPrivateProperty(node) {
  17967. this.parseInitializer(node);
  17968. this.semicolon();
  17969. return this.finishNode(node, "ClassPrivateProperty");
  17970. }
  17971. parseClassProperty(node) {
  17972. this.parseInitializer(node);
  17973. this.semicolon();
  17974. return this.finishNode(node, "ClassProperty");
  17975. }
  17976. parseClassAccessorProperty(node) {
  17977. this.parseInitializer(node);
  17978. this.semicolon();
  17979. return this.finishNode(node, "ClassAccessorProperty");
  17980. }
  17981. parseInitializer(node) {
  17982. this.scope.enter(576 | 16);
  17983. this.expressionScope.enter(newExpressionScope());
  17984. this.prodParam.enter(0);
  17985. node.value = this.eat(29) ? this.parseMaybeAssignAllowIn() : null;
  17986. this.expressionScope.exit();
  17987. this.prodParam.exit();
  17988. this.scope.exit();
  17989. }
  17990. parseClassId(node, isStatement, optionalId, bindingType = 8331) {
  17991. if (tokenIsIdentifier(this.state.type)) {
  17992. node.id = this.parseIdentifier();
  17993. if (isStatement) {
  17994. this.declareNameFromIdentifier(node.id, bindingType);
  17995. }
  17996. } else {
  17997. if (optionalId || !isStatement) {
  17998. node.id = null;
  17999. } else {
  18000. throw this.raise(Errors.MissingClassName, this.state.startLoc);
  18001. }
  18002. }
  18003. }
  18004. parseClassSuper(node) {
  18005. node.superClass = this.eat(81) ? this.parseExprSubscripts() : null;
  18006. }
  18007. parseExport(node, decorators) {
  18008. const maybeDefaultIdentifier = this.parseMaybeImportPhase(node, true);
  18009. const hasDefault = this.maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier);
  18010. const parseAfterDefault = !hasDefault || this.eat(12);
  18011. const hasStar = parseAfterDefault && this.eatExportStar(node);
  18012. const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
  18013. const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(12));
  18014. const isFromRequired = hasDefault || hasStar;
  18015. if (hasStar && !hasNamespace) {
  18016. if (hasDefault) this.unexpected();
  18017. if (decorators) {
  18018. throw this.raise(Errors.UnsupportedDecoratorExport, node);
  18019. }
  18020. this.parseExportFrom(node, true);
  18021. this.sawUnambiguousESM = true;
  18022. return this.finishNode(node, "ExportAllDeclaration");
  18023. }
  18024. const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
  18025. if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers) {
  18026. this.unexpected(null, 5);
  18027. }
  18028. if (hasNamespace && parseAfterNamespace) {
  18029. this.unexpected(null, 98);
  18030. }
  18031. let hasDeclaration;
  18032. if (isFromRequired || hasSpecifiers) {
  18033. hasDeclaration = false;
  18034. if (decorators) {
  18035. throw this.raise(Errors.UnsupportedDecoratorExport, node);
  18036. }
  18037. this.parseExportFrom(node, isFromRequired);
  18038. } else {
  18039. hasDeclaration = this.maybeParseExportDeclaration(node);
  18040. }
  18041. if (isFromRequired || hasSpecifiers || hasDeclaration) {
  18042. var _node2$declaration;
  18043. const node2 = node;
  18044. this.checkExport(node2, true, false, !!node2.source);
  18045. if (((_node2$declaration = node2.declaration) == null ? void 0 : _node2$declaration.type) === "ClassDeclaration") {
  18046. this.maybeTakeDecorators(decorators, node2.declaration, node2);
  18047. } else if (decorators) {
  18048. throw this.raise(Errors.UnsupportedDecoratorExport, node);
  18049. }
  18050. this.sawUnambiguousESM = true;
  18051. return this.finishNode(node2, "ExportNamedDeclaration");
  18052. }
  18053. if (this.eat(65)) {
  18054. const node2 = node;
  18055. const decl = this.parseExportDefaultExpression();
  18056. node2.declaration = decl;
  18057. if (decl.type === "ClassDeclaration") {
  18058. this.maybeTakeDecorators(decorators, decl, node2);
  18059. } else if (decorators) {
  18060. throw this.raise(Errors.UnsupportedDecoratorExport, node);
  18061. }
  18062. this.checkExport(node2, true, true);
  18063. this.sawUnambiguousESM = true;
  18064. return this.finishNode(node2, "ExportDefaultDeclaration");
  18065. }
  18066. throw this.unexpected(null, 5);
  18067. }
  18068. eatExportStar(node) {
  18069. return this.eat(55);
  18070. }
  18071. maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier) {
  18072. if (maybeDefaultIdentifier || this.isExportDefaultSpecifier()) {
  18073. this.expectPlugin("exportDefaultFrom", maybeDefaultIdentifier == null ? void 0 : maybeDefaultIdentifier.loc.start);
  18074. const id = maybeDefaultIdentifier || this.parseIdentifier(true);
  18075. const specifier = this.startNodeAtNode(id);
  18076. specifier.exported = id;
  18077. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  18078. return true;
  18079. }
  18080. return false;
  18081. }
  18082. maybeParseExportNamespaceSpecifier(node) {
  18083. if (this.isContextual(93)) {
  18084. var _ref, _ref$specifiers;
  18085. (_ref$specifiers = (_ref = node).specifiers) != null ? _ref$specifiers : _ref.specifiers = [];
  18086. const specifier = this.startNodeAt(this.state.lastTokStartLoc);
  18087. this.next();
  18088. specifier.exported = this.parseModuleExportName();
  18089. node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
  18090. return true;
  18091. }
  18092. return false;
  18093. }
  18094. maybeParseExportNamedSpecifiers(node) {
  18095. if (this.match(5)) {
  18096. const node2 = node;
  18097. if (!node2.specifiers) node2.specifiers = [];
  18098. const isTypeExport = node2.exportKind === "type";
  18099. node2.specifiers.push(...this.parseExportSpecifiers(isTypeExport));
  18100. node2.source = null;
  18101. if (this.hasPlugin("importAssertions")) {
  18102. node2.assertions = [];
  18103. } else {
  18104. node2.attributes = [];
  18105. }
  18106. node2.declaration = null;
  18107. return true;
  18108. }
  18109. return false;
  18110. }
  18111. maybeParseExportDeclaration(node) {
  18112. if (this.shouldParseExportDeclaration()) {
  18113. node.specifiers = [];
  18114. node.source = null;
  18115. if (this.hasPlugin("importAssertions")) {
  18116. node.assertions = [];
  18117. } else {
  18118. node.attributes = [];
  18119. }
  18120. node.declaration = this.parseExportDeclaration(node);
  18121. return true;
  18122. }
  18123. return false;
  18124. }
  18125. isAsyncFunction() {
  18126. if (!this.isContextual(95)) return false;
  18127. const next = this.nextTokenInLineStart();
  18128. return this.isUnparsedContextual(next, "function");
  18129. }
  18130. parseExportDefaultExpression() {
  18131. const expr = this.startNode();
  18132. if (this.match(68)) {
  18133. this.next();
  18134. return this.parseFunction(expr, 1 | 4);
  18135. } else if (this.isAsyncFunction()) {
  18136. this.next();
  18137. this.next();
  18138. return this.parseFunction(expr, 1 | 4 | 8);
  18139. }
  18140. if (this.match(80)) {
  18141. return this.parseClass(expr, true, true);
  18142. }
  18143. if (this.match(26)) {
  18144. if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") === true) {
  18145. this.raise(Errors.DecoratorBeforeExport, this.state.startLoc);
  18146. }
  18147. return this.parseClass(this.maybeTakeDecorators(this.parseDecorators(false), this.startNode()), true, true);
  18148. }
  18149. if (this.match(75) || this.match(74) || this.isLet() || this.isUsing() || this.isAwaitUsing()) {
  18150. throw this.raise(Errors.UnsupportedDefaultExport, this.state.startLoc);
  18151. }
  18152. const res = this.parseMaybeAssignAllowIn();
  18153. this.semicolon();
  18154. return res;
  18155. }
  18156. parseExportDeclaration(node) {
  18157. if (this.match(80)) {
  18158. const node = this.parseClass(this.startNode(), true, false);
  18159. return node;
  18160. }
  18161. return this.parseStatementListItem();
  18162. }
  18163. isExportDefaultSpecifier() {
  18164. const {
  18165. type
  18166. } = this.state;
  18167. if (tokenIsIdentifier(type)) {
  18168. if (type === 95 && !this.state.containsEsc || type === 100) {
  18169. return false;
  18170. }
  18171. if ((type === 130 || type === 129) && !this.state.containsEsc) {
  18172. const next = this.nextTokenStart();
  18173. const nextChar = this.input.charCodeAt(next);
  18174. if (nextChar === 123 || this.chStartsBindingIdentifier(nextChar, next) && !this.input.startsWith("from", next)) {
  18175. this.expectOnePlugin(["flow", "typescript"]);
  18176. return false;
  18177. }
  18178. }
  18179. } else if (!this.match(65)) {
  18180. return false;
  18181. }
  18182. const next = this.nextTokenStart();
  18183. const hasFrom = this.isUnparsedContextual(next, "from");
  18184. if (this.input.charCodeAt(next) === 44 || tokenIsIdentifier(this.state.type) && hasFrom) {
  18185. return true;
  18186. }
  18187. if (this.match(65) && hasFrom) {
  18188. const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4));
  18189. return nextAfterFrom === 34 || nextAfterFrom === 39;
  18190. }
  18191. return false;
  18192. }
  18193. parseExportFrom(node, expect) {
  18194. if (this.eatContextual(98)) {
  18195. node.source = this.parseImportSource();
  18196. this.checkExport(node);
  18197. this.maybeParseImportAttributes(node);
  18198. this.checkJSONModuleImport(node);
  18199. } else if (expect) {
  18200. this.unexpected();
  18201. }
  18202. this.semicolon();
  18203. }
  18204. shouldParseExportDeclaration() {
  18205. const {
  18206. type
  18207. } = this.state;
  18208. if (type === 26) {
  18209. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  18210. if (this.hasPlugin("decorators")) {
  18211. if (this.getPluginOption("decorators", "decoratorsBeforeExport") === true) {
  18212. this.raise(Errors.DecoratorBeforeExport, this.state.startLoc);
  18213. }
  18214. return true;
  18215. }
  18216. }
  18217. if (this.isUsing()) {
  18218. this.raise(Errors.UsingDeclarationExport, this.state.startLoc);
  18219. return true;
  18220. }
  18221. if (this.isAwaitUsing()) {
  18222. this.raise(Errors.UsingDeclarationExport, this.state.startLoc);
  18223. return true;
  18224. }
  18225. return type === 74 || type === 75 || type === 68 || type === 80 || this.isLet() || this.isAsyncFunction();
  18226. }
  18227. checkExport(node, checkNames, isDefault, isFrom) {
  18228. if (checkNames) {
  18229. var _node$specifiers;
  18230. if (isDefault) {
  18231. this.checkDuplicateExports(node, "default");
  18232. if (this.hasPlugin("exportDefaultFrom")) {
  18233. var _declaration$extra;
  18234. const declaration = node.declaration;
  18235. if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) != null && _declaration$extra.parenthesized)) {
  18236. this.raise(Errors.ExportDefaultFromAsIdentifier, declaration);
  18237. }
  18238. }
  18239. } else if ((_node$specifiers = node.specifiers) != null && _node$specifiers.length) {
  18240. for (const specifier of node.specifiers) {
  18241. const {
  18242. exported
  18243. } = specifier;
  18244. const exportName = exported.type === "Identifier" ? exported.name : exported.value;
  18245. this.checkDuplicateExports(specifier, exportName);
  18246. if (!isFrom && specifier.local) {
  18247. const {
  18248. local
  18249. } = specifier;
  18250. if (local.type !== "Identifier") {
  18251. this.raise(Errors.ExportBindingIsString, specifier, {
  18252. localName: local.value,
  18253. exportName
  18254. });
  18255. } else {
  18256. this.checkReservedWord(local.name, local.loc.start, true, false);
  18257. this.scope.checkLocalExport(local);
  18258. }
  18259. }
  18260. }
  18261. } else if (node.declaration) {
  18262. const decl = node.declaration;
  18263. if (decl.type === "FunctionDeclaration" || decl.type === "ClassDeclaration") {
  18264. const {
  18265. id
  18266. } = decl;
  18267. if (!id) throw new Error("Assertion failure");
  18268. this.checkDuplicateExports(node, id.name);
  18269. } else if (decl.type === "VariableDeclaration") {
  18270. for (const declaration of decl.declarations) {
  18271. this.checkDeclaration(declaration.id);
  18272. }
  18273. }
  18274. }
  18275. }
  18276. }
  18277. checkDeclaration(node) {
  18278. if (node.type === "Identifier") {
  18279. this.checkDuplicateExports(node, node.name);
  18280. } else if (node.type === "ObjectPattern") {
  18281. for (const prop of node.properties) {
  18282. this.checkDeclaration(prop);
  18283. }
  18284. } else if (node.type === "ArrayPattern") {
  18285. for (const elem of node.elements) {
  18286. if (elem) {
  18287. this.checkDeclaration(elem);
  18288. }
  18289. }
  18290. } else if (node.type === "ObjectProperty") {
  18291. this.checkDeclaration(node.value);
  18292. } else if (node.type === "RestElement") {
  18293. this.checkDeclaration(node.argument);
  18294. } else if (node.type === "AssignmentPattern") {
  18295. this.checkDeclaration(node.left);
  18296. }
  18297. }
  18298. checkDuplicateExports(node, exportName) {
  18299. if (this.exportedIdentifiers.has(exportName)) {
  18300. if (exportName === "default") {
  18301. this.raise(Errors.DuplicateDefaultExport, node);
  18302. } else {
  18303. this.raise(Errors.DuplicateExport, node, {
  18304. exportName
  18305. });
  18306. }
  18307. }
  18308. this.exportedIdentifiers.add(exportName);
  18309. }
  18310. parseExportSpecifiers(isInTypeExport) {
  18311. const nodes = [];
  18312. let first = true;
  18313. this.expect(5);
  18314. while (!this.eat(8)) {
  18315. if (first) {
  18316. first = false;
  18317. } else {
  18318. this.expect(12);
  18319. if (this.eat(8)) break;
  18320. }
  18321. const isMaybeTypeOnly = this.isContextual(130);
  18322. const isString = this.match(134);
  18323. const node = this.startNode();
  18324. node.local = this.parseModuleExportName();
  18325. nodes.push(this.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly));
  18326. }
  18327. return nodes;
  18328. }
  18329. parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) {
  18330. if (this.eatContextual(93)) {
  18331. node.exported = this.parseModuleExportName();
  18332. } else if (isString) {
  18333. node.exported = this.cloneStringLiteral(node.local);
  18334. } else if (!node.exported) {
  18335. node.exported = this.cloneIdentifier(node.local);
  18336. }
  18337. return this.finishNode(node, "ExportSpecifier");
  18338. }
  18339. parseModuleExportName() {
  18340. if (this.match(134)) {
  18341. const result = this.parseStringLiteral(this.state.value);
  18342. const surrogate = loneSurrogate.exec(result.value);
  18343. if (surrogate) {
  18344. this.raise(Errors.ModuleExportNameHasLoneSurrogate, result, {
  18345. surrogateCharCode: surrogate[0].charCodeAt(0)
  18346. });
  18347. }
  18348. return result;
  18349. }
  18350. return this.parseIdentifier(true);
  18351. }
  18352. isJSONModuleImport(node) {
  18353. if (node.assertions != null) {
  18354. return node.assertions.some(({
  18355. key,
  18356. value
  18357. }) => {
  18358. return value.value === "json" && (key.type === "Identifier" ? key.name === "type" : key.value === "type");
  18359. });
  18360. }
  18361. return false;
  18362. }
  18363. checkImportReflection(node) {
  18364. const {
  18365. specifiers
  18366. } = node;
  18367. const singleBindingType = specifiers.length === 1 ? specifiers[0].type : null;
  18368. if (node.phase === "source") {
  18369. if (singleBindingType !== "ImportDefaultSpecifier") {
  18370. this.raise(Errors.SourcePhaseImportRequiresDefault, specifiers[0].loc.start);
  18371. }
  18372. } else if (node.phase === "defer") {
  18373. if (singleBindingType !== "ImportNamespaceSpecifier") {
  18374. this.raise(Errors.DeferImportRequiresNamespace, specifiers[0].loc.start);
  18375. }
  18376. } else if (node.module) {
  18377. var _node$assertions;
  18378. if (singleBindingType !== "ImportDefaultSpecifier") {
  18379. this.raise(Errors.ImportReflectionNotBinding, specifiers[0].loc.start);
  18380. }
  18381. if (((_node$assertions = node.assertions) == null ? void 0 : _node$assertions.length) > 0) {
  18382. this.raise(Errors.ImportReflectionHasAssertion, specifiers[0].loc.start);
  18383. }
  18384. }
  18385. }
  18386. checkJSONModuleImport(node) {
  18387. if (this.isJSONModuleImport(node) && node.type !== "ExportAllDeclaration") {
  18388. const {
  18389. specifiers
  18390. } = node;
  18391. if (specifiers != null) {
  18392. const nonDefaultNamedSpecifier = specifiers.find(specifier => {
  18393. let imported;
  18394. if (specifier.type === "ExportSpecifier") {
  18395. imported = specifier.local;
  18396. } else if (specifier.type === "ImportSpecifier") {
  18397. imported = specifier.imported;
  18398. }
  18399. if (imported !== undefined) {
  18400. return imported.type === "Identifier" ? imported.name !== "default" : imported.value !== "default";
  18401. }
  18402. });
  18403. if (nonDefaultNamedSpecifier !== undefined) {
  18404. this.raise(Errors.ImportJSONBindingNotDefault, nonDefaultNamedSpecifier.loc.start);
  18405. }
  18406. }
  18407. }
  18408. }
  18409. isPotentialImportPhase(isExport) {
  18410. if (isExport) return false;
  18411. return this.isContextual(105) || this.isContextual(97) || this.isContextual(127);
  18412. }
  18413. applyImportPhase(node, isExport, phase, loc) {
  18414. if (isExport) {
  18415. return;
  18416. }
  18417. if (phase === "module") {
  18418. this.expectPlugin("importReflection", loc);
  18419. node.module = true;
  18420. } else if (this.hasPlugin("importReflection")) {
  18421. node.module = false;
  18422. }
  18423. if (phase === "source") {
  18424. this.expectPlugin("sourcePhaseImports", loc);
  18425. node.phase = "source";
  18426. } else if (phase === "defer") {
  18427. this.expectPlugin("deferredImportEvaluation", loc);
  18428. node.phase = "defer";
  18429. } else if (this.hasPlugin("sourcePhaseImports")) {
  18430. node.phase = null;
  18431. }
  18432. }
  18433. parseMaybeImportPhase(node, isExport) {
  18434. if (!this.isPotentialImportPhase(isExport)) {
  18435. this.applyImportPhase(node, isExport, null);
  18436. return null;
  18437. }
  18438. const phaseIdentifier = this.startNode();
  18439. const phaseIdentifierName = this.parseIdentifierName(true);
  18440. const {
  18441. type
  18442. } = this.state;
  18443. const isImportPhase = tokenIsKeywordOrIdentifier(type) ? type !== 98 || this.lookaheadCharCode() === 102 : type !== 12;
  18444. if (isImportPhase) {
  18445. this.applyImportPhase(node, isExport, phaseIdentifierName, phaseIdentifier.loc.start);
  18446. return null;
  18447. } else {
  18448. this.applyImportPhase(node, isExport, null);
  18449. return this.createIdentifier(phaseIdentifier, phaseIdentifierName);
  18450. }
  18451. }
  18452. isPrecedingIdImportPhase(phase) {
  18453. const {
  18454. type
  18455. } = this.state;
  18456. return tokenIsIdentifier(type) ? type !== 98 || this.lookaheadCharCode() === 102 : type !== 12;
  18457. }
  18458. parseImport(node) {
  18459. if (this.match(134)) {
  18460. return this.parseImportSourceAndAttributes(node);
  18461. }
  18462. return this.parseImportSpecifiersAndAfter(node, this.parseMaybeImportPhase(node, false));
  18463. }
  18464. parseImportSpecifiersAndAfter(node, maybeDefaultIdentifier) {
  18465. node.specifiers = [];
  18466. const hasDefault = this.maybeParseDefaultImportSpecifier(node, maybeDefaultIdentifier);
  18467. const parseNext = !hasDefault || this.eat(12);
  18468. const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
  18469. if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
  18470. this.expectContextual(98);
  18471. return this.parseImportSourceAndAttributes(node);
  18472. }
  18473. parseImportSourceAndAttributes(node) {
  18474. var _node$specifiers2;
  18475. (_node$specifiers2 = node.specifiers) != null ? _node$specifiers2 : node.specifiers = [];
  18476. node.source = this.parseImportSource();
  18477. this.maybeParseImportAttributes(node);
  18478. this.checkImportReflection(node);
  18479. this.checkJSONModuleImport(node);
  18480. this.semicolon();
  18481. this.sawUnambiguousESM = true;
  18482. return this.finishNode(node, "ImportDeclaration");
  18483. }
  18484. parseImportSource() {
  18485. if (!this.match(134)) this.unexpected();
  18486. return this.parseExprAtom();
  18487. }
  18488. parseImportSpecifierLocal(node, specifier, type) {
  18489. specifier.local = this.parseIdentifier();
  18490. node.specifiers.push(this.finishImportSpecifier(specifier, type));
  18491. }
  18492. finishImportSpecifier(specifier, type, bindingType = 8201) {
  18493. this.checkLVal(specifier.local, {
  18494. type
  18495. }, bindingType);
  18496. return this.finishNode(specifier, type);
  18497. }
  18498. parseImportAttributes() {
  18499. this.expect(5);
  18500. const attrs = [];
  18501. const attrNames = new Set();
  18502. do {
  18503. if (this.match(8)) {
  18504. break;
  18505. }
  18506. const node = this.startNode();
  18507. const keyName = this.state.value;
  18508. if (attrNames.has(keyName)) {
  18509. this.raise(Errors.ModuleAttributesWithDuplicateKeys, this.state.startLoc, {
  18510. key: keyName
  18511. });
  18512. }
  18513. attrNames.add(keyName);
  18514. if (this.match(134)) {
  18515. node.key = this.parseStringLiteral(keyName);
  18516. } else {
  18517. node.key = this.parseIdentifier(true);
  18518. }
  18519. this.expect(14);
  18520. if (!this.match(134)) {
  18521. throw this.raise(Errors.ModuleAttributeInvalidValue, this.state.startLoc);
  18522. }
  18523. node.value = this.parseStringLiteral(this.state.value);
  18524. attrs.push(this.finishNode(node, "ImportAttribute"));
  18525. } while (this.eat(12));
  18526. this.expect(8);
  18527. return attrs;
  18528. }
  18529. parseModuleAttributes() {
  18530. const attrs = [];
  18531. const attributes = new Set();
  18532. do {
  18533. const node = this.startNode();
  18534. node.key = this.parseIdentifier(true);
  18535. if (node.key.name !== "type") {
  18536. this.raise(Errors.ModuleAttributeDifferentFromType, node.key);
  18537. }
  18538. if (attributes.has(node.key.name)) {
  18539. this.raise(Errors.ModuleAttributesWithDuplicateKeys, node.key, {
  18540. key: node.key.name
  18541. });
  18542. }
  18543. attributes.add(node.key.name);
  18544. this.expect(14);
  18545. if (!this.match(134)) {
  18546. throw this.raise(Errors.ModuleAttributeInvalidValue, this.state.startLoc);
  18547. }
  18548. node.value = this.parseStringLiteral(this.state.value);
  18549. attrs.push(this.finishNode(node, "ImportAttribute"));
  18550. } while (this.eat(12));
  18551. return attrs;
  18552. }
  18553. maybeParseImportAttributes(node) {
  18554. let attributes;
  18555. var useWith = false;
  18556. if (this.match(76)) {
  18557. if (this.hasPrecedingLineBreak() && this.lookaheadCharCode() === 40) {
  18558. return;
  18559. }
  18560. this.next();
  18561. if (this.hasPlugin("moduleAttributes")) {
  18562. attributes = this.parseModuleAttributes();
  18563. this.addExtra(node, "deprecatedWithLegacySyntax", true);
  18564. } else {
  18565. attributes = this.parseImportAttributes();
  18566. }
  18567. useWith = true;
  18568. } else if (this.isContextual(94) && !this.hasPrecedingLineBreak()) {
  18569. if (!this.hasPlugin("deprecatedImportAssert") && !this.hasPlugin("importAssertions")) {
  18570. this.raise(Errors.ImportAttributesUseAssert, this.state.startLoc);
  18571. }
  18572. if (!this.hasPlugin("importAssertions")) {
  18573. this.addExtra(node, "deprecatedAssertSyntax", true);
  18574. }
  18575. this.next();
  18576. attributes = this.parseImportAttributes();
  18577. } else {
  18578. attributes = [];
  18579. }
  18580. if (!useWith && this.hasPlugin("importAssertions")) {
  18581. node.assertions = attributes;
  18582. } else {
  18583. node.attributes = attributes;
  18584. }
  18585. }
  18586. maybeParseDefaultImportSpecifier(node, maybeDefaultIdentifier) {
  18587. if (maybeDefaultIdentifier) {
  18588. const specifier = this.startNodeAtNode(maybeDefaultIdentifier);
  18589. specifier.local = maybeDefaultIdentifier;
  18590. node.specifiers.push(this.finishImportSpecifier(specifier, "ImportDefaultSpecifier"));
  18591. return true;
  18592. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  18593. this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier");
  18594. return true;
  18595. }
  18596. return false;
  18597. }
  18598. maybeParseStarImportSpecifier(node) {
  18599. if (this.match(55)) {
  18600. const specifier = this.startNode();
  18601. this.next();
  18602. this.expectContextual(93);
  18603. this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier");
  18604. return true;
  18605. }
  18606. return false;
  18607. }
  18608. parseNamedImportSpecifiers(node) {
  18609. let first = true;
  18610. this.expect(5);
  18611. while (!this.eat(8)) {
  18612. if (first) {
  18613. first = false;
  18614. } else {
  18615. if (this.eat(14)) {
  18616. throw this.raise(Errors.DestructureNamedImport, this.state.startLoc);
  18617. }
  18618. this.expect(12);
  18619. if (this.eat(8)) break;
  18620. }
  18621. const specifier = this.startNode();
  18622. const importedIsString = this.match(134);
  18623. const isMaybeTypeOnly = this.isContextual(130);
  18624. specifier.imported = this.parseModuleExportName();
  18625. const importSpecifier = this.parseImportSpecifier(specifier, importedIsString, node.importKind === "type" || node.importKind === "typeof", isMaybeTypeOnly, undefined);
  18626. node.specifiers.push(importSpecifier);
  18627. }
  18628. }
  18629. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) {
  18630. if (this.eatContextual(93)) {
  18631. specifier.local = this.parseIdentifier();
  18632. } else {
  18633. const {
  18634. imported
  18635. } = specifier;
  18636. if (importedIsString) {
  18637. throw this.raise(Errors.ImportBindingIsString, specifier, {
  18638. importName: imported.value
  18639. });
  18640. }
  18641. this.checkReservedWord(imported.name, specifier.loc.start, true, true);
  18642. if (!specifier.local) {
  18643. specifier.local = this.cloneIdentifier(imported);
  18644. }
  18645. }
  18646. return this.finishImportSpecifier(specifier, "ImportSpecifier", bindingType);
  18647. }
  18648. isThisParam(param) {
  18649. return param.type === "Identifier" && param.name === "this";
  18650. }
  18651. }
  18652. class Parser extends StatementParser {
  18653. constructor(options, input, pluginsMap) {
  18654. const normalizedOptions = getOptions(options);
  18655. super(normalizedOptions, input);
  18656. this.options = normalizedOptions;
  18657. this.initializeScopes();
  18658. this.plugins = pluginsMap;
  18659. this.filename = normalizedOptions.sourceFilename;
  18660. this.startIndex = normalizedOptions.startIndex;
  18661. let optionFlags = 0;
  18662. if (normalizedOptions.allowAwaitOutsideFunction) {
  18663. optionFlags |= 1;
  18664. }
  18665. if (normalizedOptions.allowReturnOutsideFunction) {
  18666. optionFlags |= 2;
  18667. }
  18668. if (normalizedOptions.allowImportExportEverywhere) {
  18669. optionFlags |= 8;
  18670. }
  18671. if (normalizedOptions.allowSuperOutsideMethod) {
  18672. optionFlags |= 16;
  18673. }
  18674. if (normalizedOptions.allowUndeclaredExports) {
  18675. optionFlags |= 64;
  18676. }
  18677. if (normalizedOptions.allowNewTargetOutsideFunction) {
  18678. optionFlags |= 4;
  18679. }
  18680. if (normalizedOptions.allowYieldOutsideFunction) {
  18681. optionFlags |= 32;
  18682. }
  18683. if (normalizedOptions.ranges) {
  18684. optionFlags |= 128;
  18685. }
  18686. if (normalizedOptions.tokens) {
  18687. optionFlags |= 256;
  18688. }
  18689. if (normalizedOptions.createImportExpressions) {
  18690. optionFlags |= 512;
  18691. }
  18692. if (normalizedOptions.createParenthesizedExpressions) {
  18693. optionFlags |= 1024;
  18694. }
  18695. if (normalizedOptions.errorRecovery) {
  18696. optionFlags |= 2048;
  18697. }
  18698. if (normalizedOptions.attachComment) {
  18699. optionFlags |= 4096;
  18700. }
  18701. if (normalizedOptions.annexB) {
  18702. optionFlags |= 8192;
  18703. }
  18704. this.optionFlags = optionFlags;
  18705. }
  18706. getScopeHandler() {
  18707. return ScopeHandler;
  18708. }
  18709. parse() {
  18710. this.enterInitialScopes();
  18711. const file = this.startNode();
  18712. const program = this.startNode();
  18713. this.nextToken();
  18714. file.errors = null;
  18715. const result = this.parseTopLevel(file, program);
  18716. result.errors = this.state.errors;
  18717. result.comments.length = this.state.commentsLen;
  18718. return result;
  18719. }
  18720. }
  18721. function parse(input, options) {
  18722. var _options;
  18723. if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") {
  18724. options = Object.assign({}, options);
  18725. try {
  18726. options.sourceType = "module";
  18727. const parser = getParser(options, input);
  18728. const ast = parser.parse();
  18729. if (parser.sawUnambiguousESM) {
  18730. return ast;
  18731. }
  18732. if (parser.ambiguousScriptDifferentAst) {
  18733. try {
  18734. options.sourceType = "script";
  18735. return getParser(options, input).parse();
  18736. } catch (_unused) {}
  18737. } else {
  18738. ast.program.sourceType = "script";
  18739. }
  18740. return ast;
  18741. } catch (moduleError) {
  18742. try {
  18743. options.sourceType = "script";
  18744. return getParser(options, input).parse();
  18745. } catch (_unused2) {}
  18746. throw moduleError;
  18747. }
  18748. } else {
  18749. return getParser(options, input).parse();
  18750. }
  18751. }
  18752. function parseExpression(input, options) {
  18753. const parser = getParser(options, input);
  18754. if (parser.options.strictMode) {
  18755. parser.state.strict = true;
  18756. }
  18757. return parser.getExpression();
  18758. }
  18759. function generateExportedTokenTypes(internalTokenTypes) {
  18760. const tokenTypes = {};
  18761. for (const typeName of Object.keys(internalTokenTypes)) {
  18762. tokenTypes[typeName] = getExportedToken(internalTokenTypes[typeName]);
  18763. }
  18764. return tokenTypes;
  18765. }
  18766. const tokTypes = generateExportedTokenTypes(tt);
  18767. function getParser(options, input) {
  18768. let cls = Parser;
  18769. const pluginsMap = new Map();
  18770. if (options != null && options.plugins) {
  18771. for (const plugin of options.plugins) {
  18772. let name, opts;
  18773. if (typeof plugin === "string") {
  18774. name = plugin;
  18775. } else {
  18776. [name, opts] = plugin;
  18777. }
  18778. if (!pluginsMap.has(name)) {
  18779. pluginsMap.set(name, opts || {});
  18780. }
  18781. }
  18782. validatePlugins(pluginsMap);
  18783. cls = getParserClass(pluginsMap);
  18784. }
  18785. return new cls(options, input, pluginsMap);
  18786. }
  18787. const parserClassCache = new Map();
  18788. function getParserClass(pluginsMap) {
  18789. const pluginList = [];
  18790. for (const name of mixinPluginNames) {
  18791. if (pluginsMap.has(name)) {
  18792. pluginList.push(name);
  18793. }
  18794. }
  18795. const key = pluginList.join("|");
  18796. let cls = parserClassCache.get(key);
  18797. if (!cls) {
  18798. cls = Parser;
  18799. for (const plugin of pluginList) {
  18800. cls = mixinPlugins[plugin](cls);
  18801. }
  18802. parserClassCache.set(key, cls);
  18803. }
  18804. return cls;
  18805. }
  18806. lib.parse = parse;
  18807. lib.parseExpression = parseExpression;
  18808. lib.tokTypes = tokTypes;
  18809. return lib;
  18810. }
  18811. var libExports = /*@__PURE__*/ requireLib();
  18812. // @ts-check
  18813. /** @typedef { import('estree').BaseNode} BaseNode */
  18814. /** @typedef {{
  18815. skip: () => void;
  18816. remove: () => void;
  18817. replace: (node: BaseNode) => void;
  18818. }} WalkerContext */
  18819. class WalkerBase {
  18820. constructor() {
  18821. /** @type {boolean} */
  18822. this.should_skip = false;
  18823. /** @type {boolean} */
  18824. this.should_remove = false;
  18825. /** @type {BaseNode | null} */
  18826. this.replacement = null;
  18827. /** @type {WalkerContext} */
  18828. this.context = {
  18829. skip: () => (this.should_skip = true),
  18830. remove: () => (this.should_remove = true),
  18831. replace: (node) => (this.replacement = node)
  18832. };
  18833. }
  18834. /**
  18835. *
  18836. * @param {any} parent
  18837. * @param {string} prop
  18838. * @param {number} index
  18839. * @param {BaseNode} node
  18840. */
  18841. replace(parent, prop, index, node) {
  18842. if (parent) {
  18843. if (index !== null) {
  18844. parent[prop][index] = node;
  18845. } else {
  18846. parent[prop] = node;
  18847. }
  18848. }
  18849. }
  18850. /**
  18851. *
  18852. * @param {any} parent
  18853. * @param {string} prop
  18854. * @param {number} index
  18855. */
  18856. remove(parent, prop, index) {
  18857. if (parent) {
  18858. if (index !== null) {
  18859. parent[prop].splice(index, 1);
  18860. } else {
  18861. delete parent[prop];
  18862. }
  18863. }
  18864. }
  18865. }
  18866. // @ts-check
  18867. /** @typedef { import('estree').BaseNode} BaseNode */
  18868. /** @typedef { import('./walker.js').WalkerContext} WalkerContext */
  18869. /** @typedef {(
  18870. * this: WalkerContext,
  18871. * node: BaseNode,
  18872. * parent: BaseNode,
  18873. * key: string,
  18874. * index: number
  18875. * ) => void} SyncHandler */
  18876. class SyncWalker extends WalkerBase {
  18877. /**
  18878. *
  18879. * @param {SyncHandler} enter
  18880. * @param {SyncHandler} leave
  18881. */
  18882. constructor(enter, leave) {
  18883. super();
  18884. /** @type {SyncHandler} */
  18885. this.enter = enter;
  18886. /** @type {SyncHandler} */
  18887. this.leave = leave;
  18888. }
  18889. /**
  18890. *
  18891. * @param {BaseNode} node
  18892. * @param {BaseNode} parent
  18893. * @param {string} [prop]
  18894. * @param {number} [index]
  18895. * @returns {BaseNode}
  18896. */
  18897. visit(node, parent, prop, index) {
  18898. if (node) {
  18899. if (this.enter) {
  18900. const _should_skip = this.should_skip;
  18901. const _should_remove = this.should_remove;
  18902. const _replacement = this.replacement;
  18903. this.should_skip = false;
  18904. this.should_remove = false;
  18905. this.replacement = null;
  18906. this.enter.call(this.context, node, parent, prop, index);
  18907. if (this.replacement) {
  18908. node = this.replacement;
  18909. this.replace(parent, prop, index, node);
  18910. }
  18911. if (this.should_remove) {
  18912. this.remove(parent, prop, index);
  18913. }
  18914. const skipped = this.should_skip;
  18915. const removed = this.should_remove;
  18916. this.should_skip = _should_skip;
  18917. this.should_remove = _should_remove;
  18918. this.replacement = _replacement;
  18919. if (skipped) return node;
  18920. if (removed) return null;
  18921. }
  18922. for (const key in node) {
  18923. const value = node[key];
  18924. if (typeof value !== "object") {
  18925. continue;
  18926. } else if (Array.isArray(value)) {
  18927. for (let i = 0; i < value.length; i += 1) {
  18928. if (value[i] !== null && typeof value[i].type === 'string') {
  18929. if (!this.visit(value[i], node, key, i)) {
  18930. // removed
  18931. i--;
  18932. }
  18933. }
  18934. }
  18935. } else if (value !== null && typeof value.type === "string") {
  18936. this.visit(value, node, key, null);
  18937. }
  18938. }
  18939. if (this.leave) {
  18940. const _replacement = this.replacement;
  18941. const _should_remove = this.should_remove;
  18942. this.replacement = null;
  18943. this.should_remove = false;
  18944. this.leave.call(this.context, node, parent, prop, index);
  18945. if (this.replacement) {
  18946. node = this.replacement;
  18947. this.replace(parent, prop, index, node);
  18948. }
  18949. if (this.should_remove) {
  18950. this.remove(parent, prop, index);
  18951. }
  18952. const removed = this.should_remove;
  18953. this.replacement = _replacement;
  18954. this.should_remove = _should_remove;
  18955. if (removed) return null;
  18956. }
  18957. }
  18958. return node;
  18959. }
  18960. }
  18961. // @ts-check
  18962. /** @typedef { import('estree').BaseNode} BaseNode */
  18963. /** @typedef { import('./sync.js').SyncHandler} SyncHandler */
  18964. /** @typedef { import('./async.js').AsyncHandler} AsyncHandler */
  18965. /**
  18966. *
  18967. * @param {BaseNode} ast
  18968. * @param {{
  18969. * enter?: SyncHandler
  18970. * leave?: SyncHandler
  18971. * }} walker
  18972. * @returns {BaseNode}
  18973. */
  18974. function walk$2(ast, { enter, leave }) {
  18975. const instance = new SyncWalker(enter, leave);
  18976. return instance.visit(ast, null);
  18977. }
  18978. function walkIdentifiers(root, onIdentifier, includeAll = false, parentStack = [], knownIds = /* @__PURE__ */ Object.create(null)) {
  18979. const rootExp = root.type === "Program" ? root.body[0].type === "ExpressionStatement" && root.body[0].expression : root;
  18980. walk$2(root, {
  18981. enter(node, parent) {
  18982. parent && parentStack.push(parent);
  18983. if (parent && parent.type.startsWith("TS") && !TS_NODE_TYPES.includes(parent.type)) {
  18984. return this.skip();
  18985. }
  18986. if (node.type === "Identifier") {
  18987. const isLocal = !!knownIds[node.name];
  18988. const isRefed = isReferencedIdentifier(node, parent, parentStack);
  18989. if (includeAll || isRefed && !isLocal) {
  18990. onIdentifier(node, parent, parentStack, isRefed, isLocal);
  18991. }
  18992. } else if (node.type === "ObjectProperty" && // eslint-disable-next-line no-restricted-syntax
  18993. (parent == null ? void 0 : parent.type) === "ObjectPattern") {
  18994. node.inPattern = true;
  18995. } else if (isFunctionType(node)) {
  18996. if (node.scopeIds) {
  18997. node.scopeIds.forEach((id) => markKnownIds(id, knownIds));
  18998. } else {
  18999. walkFunctionParams(
  19000. node,
  19001. (id) => markScopeIdentifier(node, id, knownIds)
  19002. );
  19003. }
  19004. } else if (node.type === "BlockStatement") {
  19005. if (node.scopeIds) {
  19006. node.scopeIds.forEach((id) => markKnownIds(id, knownIds));
  19007. } else {
  19008. walkBlockDeclarations(
  19009. node,
  19010. (id) => markScopeIdentifier(node, id, knownIds)
  19011. );
  19012. }
  19013. } else if (node.type === "SwitchStatement") {
  19014. if (node.scopeIds) {
  19015. node.scopeIds.forEach((id) => markKnownIds(id, knownIds));
  19016. } else {
  19017. walkSwitchStatement(
  19018. node,
  19019. false,
  19020. (id) => markScopeIdentifier(node, id, knownIds)
  19021. );
  19022. }
  19023. } else if (node.type === "CatchClause" && node.param) {
  19024. if (node.scopeIds) {
  19025. node.scopeIds.forEach((id) => markKnownIds(id, knownIds));
  19026. } else {
  19027. for (const id of extractIdentifiers$1(node.param)) {
  19028. markScopeIdentifier(node, id, knownIds);
  19029. }
  19030. }
  19031. } else if (isForStatement(node)) {
  19032. if (node.scopeIds) {
  19033. node.scopeIds.forEach((id) => markKnownIds(id, knownIds));
  19034. } else {
  19035. walkForStatement(
  19036. node,
  19037. false,
  19038. (id) => markScopeIdentifier(node, id, knownIds)
  19039. );
  19040. }
  19041. }
  19042. },
  19043. leave(node, parent) {
  19044. parent && parentStack.pop();
  19045. if (node !== rootExp && node.scopeIds) {
  19046. for (const id of node.scopeIds) {
  19047. knownIds[id]--;
  19048. if (knownIds[id] === 0) {
  19049. delete knownIds[id];
  19050. }
  19051. }
  19052. }
  19053. }
  19054. });
  19055. }
  19056. function isReferencedIdentifier(id, parent, parentStack) {
  19057. if (!parent) {
  19058. return true;
  19059. }
  19060. if (id.name === "arguments") {
  19061. return false;
  19062. }
  19063. if (isReferenced(id, parent, parentStack[parentStack.length - 2])) {
  19064. return true;
  19065. }
  19066. switch (parent.type) {
  19067. case "AssignmentExpression":
  19068. case "AssignmentPattern":
  19069. return true;
  19070. case "ObjectProperty":
  19071. return parent.key !== id && isInDestructureAssignment(parent, parentStack);
  19072. case "ArrayPattern":
  19073. return isInDestructureAssignment(parent, parentStack);
  19074. }
  19075. return false;
  19076. }
  19077. function isInDestructureAssignment(parent, parentStack) {
  19078. if (parent && (parent.type === "ObjectProperty" || parent.type === "ArrayPattern")) {
  19079. let i = parentStack.length;
  19080. while (i--) {
  19081. const p = parentStack[i];
  19082. if (p.type === "AssignmentExpression") {
  19083. return true;
  19084. } else if (p.type !== "ObjectProperty" && !p.type.endsWith("Pattern")) {
  19085. break;
  19086. }
  19087. }
  19088. }
  19089. return false;
  19090. }
  19091. function isInNewExpression(parentStack) {
  19092. let i = parentStack.length;
  19093. while (i--) {
  19094. const p = parentStack[i];
  19095. if (p.type === "NewExpression") {
  19096. return true;
  19097. } else if (p.type !== "MemberExpression") {
  19098. break;
  19099. }
  19100. }
  19101. return false;
  19102. }
  19103. function walkFunctionParams(node, onIdent) {
  19104. for (const p of node.params) {
  19105. for (const id of extractIdentifiers$1(p)) {
  19106. onIdent(id);
  19107. }
  19108. }
  19109. }
  19110. function walkBlockDeclarations(block, onIdent) {
  19111. const body = block.type === "SwitchCase" ? block.consequent : block.body;
  19112. for (const stmt of body) {
  19113. if (stmt.type === "VariableDeclaration") {
  19114. if (stmt.declare) continue;
  19115. for (const decl of stmt.declarations) {
  19116. for (const id of extractIdentifiers$1(decl.id)) {
  19117. onIdent(id);
  19118. }
  19119. }
  19120. } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
  19121. if (stmt.declare || !stmt.id) continue;
  19122. onIdent(stmt.id);
  19123. } else if (isForStatement(stmt)) {
  19124. walkForStatement(stmt, true, onIdent);
  19125. } else if (stmt.type === "SwitchStatement") {
  19126. walkSwitchStatement(stmt, true, onIdent);
  19127. }
  19128. }
  19129. }
  19130. function isForStatement(stmt) {
  19131. return stmt.type === "ForOfStatement" || stmt.type === "ForInStatement" || stmt.type === "ForStatement";
  19132. }
  19133. function walkForStatement(stmt, isVar, onIdent) {
  19134. const variable = stmt.type === "ForStatement" ? stmt.init : stmt.left;
  19135. if (variable && variable.type === "VariableDeclaration" && (variable.kind === "var" ? isVar : !isVar)) {
  19136. for (const decl of variable.declarations) {
  19137. for (const id of extractIdentifiers$1(decl.id)) {
  19138. onIdent(id);
  19139. }
  19140. }
  19141. }
  19142. }
  19143. function walkSwitchStatement(stmt, isVar, onIdent) {
  19144. for (const cs of stmt.cases) {
  19145. for (const stmt2 of cs.consequent) {
  19146. if (stmt2.type === "VariableDeclaration" && (stmt2.kind === "var" ? isVar : !isVar)) {
  19147. for (const decl of stmt2.declarations) {
  19148. for (const id of extractIdentifiers$1(decl.id)) {
  19149. onIdent(id);
  19150. }
  19151. }
  19152. }
  19153. }
  19154. walkBlockDeclarations(cs, onIdent);
  19155. }
  19156. }
  19157. function extractIdentifiers$1(param, nodes = []) {
  19158. switch (param.type) {
  19159. case "Identifier":
  19160. nodes.push(param);
  19161. break;
  19162. case "MemberExpression":
  19163. let object = param;
  19164. while (object.type === "MemberExpression") {
  19165. object = object.object;
  19166. }
  19167. nodes.push(object);
  19168. break;
  19169. case "ObjectPattern":
  19170. for (const prop of param.properties) {
  19171. if (prop.type === "RestElement") {
  19172. extractIdentifiers$1(prop.argument, nodes);
  19173. } else {
  19174. extractIdentifiers$1(prop.value, nodes);
  19175. }
  19176. }
  19177. break;
  19178. case "ArrayPattern":
  19179. param.elements.forEach((element) => {
  19180. if (element) extractIdentifiers$1(element, nodes);
  19181. });
  19182. break;
  19183. case "RestElement":
  19184. extractIdentifiers$1(param.argument, nodes);
  19185. break;
  19186. case "AssignmentPattern":
  19187. extractIdentifiers$1(param.left, nodes);
  19188. break;
  19189. }
  19190. return nodes;
  19191. }
  19192. function markKnownIds(name, knownIds) {
  19193. if (name in knownIds) {
  19194. knownIds[name]++;
  19195. } else {
  19196. knownIds[name] = 1;
  19197. }
  19198. }
  19199. function markScopeIdentifier(node, child, knownIds) {
  19200. const { name } = child;
  19201. if (node.scopeIds && node.scopeIds.has(name)) {
  19202. return;
  19203. }
  19204. markKnownIds(name, knownIds);
  19205. (node.scopeIds || (node.scopeIds = /* @__PURE__ */ new Set())).add(name);
  19206. }
  19207. const isFunctionType = (node) => {
  19208. return /Function(?:Expression|Declaration)$|Method$/.test(node.type);
  19209. };
  19210. const isStaticProperty = (node) => node && (node.type === "ObjectProperty" || node.type === "ObjectMethod") && !node.computed;
  19211. const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
  19212. function isReferenced(node, parent, grandparent) {
  19213. switch (parent.type) {
  19214. // yes: PARENT[NODE]
  19215. // yes: NODE.child
  19216. // no: parent.NODE
  19217. case "MemberExpression":
  19218. case "OptionalMemberExpression":
  19219. if (parent.property === node) {
  19220. return !!parent.computed;
  19221. }
  19222. return parent.object === node;
  19223. case "JSXMemberExpression":
  19224. return parent.object === node;
  19225. // no: let NODE = init;
  19226. // yes: let id = NODE;
  19227. case "VariableDeclarator":
  19228. return parent.init === node;
  19229. // yes: () => NODE
  19230. // no: (NODE) => {}
  19231. case "ArrowFunctionExpression":
  19232. return parent.body === node;
  19233. // no: class { #NODE; }
  19234. // no: class { get #NODE() {} }
  19235. // no: class { #NODE() {} }
  19236. // no: class { fn() { return this.#NODE; } }
  19237. case "PrivateName":
  19238. return false;
  19239. // no: class { NODE() {} }
  19240. // yes: class { [NODE]() {} }
  19241. // no: class { foo(NODE) {} }
  19242. case "ClassMethod":
  19243. case "ClassPrivateMethod":
  19244. case "ObjectMethod":
  19245. if (parent.key === node) {
  19246. return !!parent.computed;
  19247. }
  19248. return false;
  19249. // yes: { [NODE]: "" }
  19250. // no: { NODE: "" }
  19251. // depends: { NODE }
  19252. // depends: { key: NODE }
  19253. case "ObjectProperty":
  19254. if (parent.key === node) {
  19255. return !!parent.computed;
  19256. }
  19257. return !grandparent || grandparent.type !== "ObjectPattern";
  19258. // no: class { NODE = value; }
  19259. // yes: class { [NODE] = value; }
  19260. // yes: class { key = NODE; }
  19261. case "ClassProperty":
  19262. if (parent.key === node) {
  19263. return !!parent.computed;
  19264. }
  19265. return true;
  19266. case "ClassPrivateProperty":
  19267. return parent.key !== node;
  19268. // no: class NODE {}
  19269. // yes: class Foo extends NODE {}
  19270. case "ClassDeclaration":
  19271. case "ClassExpression":
  19272. return parent.superClass === node;
  19273. // yes: left = NODE;
  19274. // no: NODE = right;
  19275. case "AssignmentExpression":
  19276. return parent.right === node;
  19277. // no: [NODE = foo] = [];
  19278. // yes: [foo = NODE] = [];
  19279. case "AssignmentPattern":
  19280. return parent.right === node;
  19281. // no: NODE: for (;;) {}
  19282. case "LabeledStatement":
  19283. return false;
  19284. // no: try {} catch (NODE) {}
  19285. case "CatchClause":
  19286. return false;
  19287. // no: function foo(...NODE) {}
  19288. case "RestElement":
  19289. return false;
  19290. case "BreakStatement":
  19291. case "ContinueStatement":
  19292. return false;
  19293. // no: function NODE() {}
  19294. // no: function foo(NODE) {}
  19295. case "FunctionDeclaration":
  19296. case "FunctionExpression":
  19297. return false;
  19298. // no: export NODE from "foo";
  19299. // no: export * as NODE from "foo";
  19300. case "ExportNamespaceSpecifier":
  19301. case "ExportDefaultSpecifier":
  19302. return false;
  19303. // no: export { foo as NODE };
  19304. // yes: export { NODE as foo };
  19305. // no: export { NODE as foo } from "foo";
  19306. case "ExportSpecifier":
  19307. if (grandparent == null ? void 0 : grandparent.source) {
  19308. return false;
  19309. }
  19310. return parent.local === node;
  19311. // no: import NODE from "foo";
  19312. // no: import * as NODE from "foo";
  19313. // no: import { NODE as foo } from "foo";
  19314. // no: import { foo as NODE } from "foo";
  19315. // no: import NODE from "bar";
  19316. case "ImportDefaultSpecifier":
  19317. case "ImportNamespaceSpecifier":
  19318. case "ImportSpecifier":
  19319. return false;
  19320. // no: import "foo" assert { NODE: "json" }
  19321. case "ImportAttribute":
  19322. return false;
  19323. // no: <div NODE="foo" />
  19324. case "JSXAttribute":
  19325. return false;
  19326. // no: [NODE] = [];
  19327. // no: ({ NODE }) = [];
  19328. case "ObjectPattern":
  19329. case "ArrayPattern":
  19330. return false;
  19331. // no: new.NODE
  19332. // no: NODE.target
  19333. case "MetaProperty":
  19334. return false;
  19335. // yes: type X = { someProperty: NODE }
  19336. // no: type X = { NODE: OtherType }
  19337. case "ObjectTypeProperty":
  19338. return parent.key !== node;
  19339. // yes: enum X { Foo = NODE }
  19340. // no: enum X { NODE }
  19341. case "TSEnumMember":
  19342. return parent.id !== node;
  19343. // yes: { [NODE]: value }
  19344. // no: { NODE: value }
  19345. case "TSPropertySignature":
  19346. if (parent.key === node) {
  19347. return !!parent.computed;
  19348. }
  19349. return true;
  19350. }
  19351. return true;
  19352. }
  19353. const TS_NODE_TYPES = [
  19354. "TSAsExpression",
  19355. // foo as number
  19356. "TSTypeAssertion",
  19357. // (<number>foo)
  19358. "TSNonNullExpression",
  19359. // foo!
  19360. "TSInstantiationExpression",
  19361. // foo<string>
  19362. "TSSatisfiesExpression"
  19363. // foo satisfies T
  19364. ];
  19365. function unwrapTSNode(node) {
  19366. if (TS_NODE_TYPES.includes(node.type)) {
  19367. return unwrapTSNode(node.expression);
  19368. } else {
  19369. return node;
  19370. }
  19371. }
  19372. const isStaticExp = (p) => p.type === 4 && p.isStatic;
  19373. function isCoreComponent(tag) {
  19374. switch (tag) {
  19375. case "Teleport":
  19376. case "teleport":
  19377. return TELEPORT;
  19378. case "Suspense":
  19379. case "suspense":
  19380. return SUSPENSE;
  19381. case "KeepAlive":
  19382. case "keep-alive":
  19383. return KEEP_ALIVE;
  19384. case "BaseTransition":
  19385. case "base-transition":
  19386. return BASE_TRANSITION;
  19387. }
  19388. }
  19389. const nonIdentifierRE = /^$|^\d|[^\$\w\xA0-\uFFFF]/;
  19390. const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
  19391. const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
  19392. const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
  19393. const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
  19394. const getExpSource = (exp) => exp.type === 4 ? exp.content : exp.loc.source;
  19395. const isMemberExpressionBrowser = (exp) => {
  19396. const path = getExpSource(exp).trim().replace(whitespaceRE, (s) => s.trim());
  19397. let state = 0 /* inMemberExp */;
  19398. let stateStack = [];
  19399. let currentOpenBracketCount = 0;
  19400. let currentOpenParensCount = 0;
  19401. let currentStringType = null;
  19402. for (let i = 0; i < path.length; i++) {
  19403. const char = path.charAt(i);
  19404. switch (state) {
  19405. case 0 /* inMemberExp */:
  19406. if (char === "[") {
  19407. stateStack.push(state);
  19408. state = 1 /* inBrackets */;
  19409. currentOpenBracketCount++;
  19410. } else if (char === "(") {
  19411. stateStack.push(state);
  19412. state = 2 /* inParens */;
  19413. currentOpenParensCount++;
  19414. } else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
  19415. return false;
  19416. }
  19417. break;
  19418. case 1 /* inBrackets */:
  19419. if (char === `'` || char === `"` || char === "`") {
  19420. stateStack.push(state);
  19421. state = 3 /* inString */;
  19422. currentStringType = char;
  19423. } else if (char === `[`) {
  19424. currentOpenBracketCount++;
  19425. } else if (char === `]`) {
  19426. if (!--currentOpenBracketCount) {
  19427. state = stateStack.pop();
  19428. }
  19429. }
  19430. break;
  19431. case 2 /* inParens */:
  19432. if (char === `'` || char === `"` || char === "`") {
  19433. stateStack.push(state);
  19434. state = 3 /* inString */;
  19435. currentStringType = char;
  19436. } else if (char === `(`) {
  19437. currentOpenParensCount++;
  19438. } else if (char === `)`) {
  19439. if (i === path.length - 1) {
  19440. return false;
  19441. }
  19442. if (!--currentOpenParensCount) {
  19443. state = stateStack.pop();
  19444. }
  19445. }
  19446. break;
  19447. case 3 /* inString */:
  19448. if (char === currentStringType) {
  19449. state = stateStack.pop();
  19450. currentStringType = null;
  19451. }
  19452. break;
  19453. }
  19454. }
  19455. return !currentOpenBracketCount && !currentOpenParensCount;
  19456. };
  19457. const isMemberExpressionNode = (exp, context) => {
  19458. try {
  19459. let ret = exp.ast || libExports.parseExpression(getExpSource(exp), {
  19460. plugins: context.expressionPlugins ? [...context.expressionPlugins, "typescript"] : ["typescript"]
  19461. });
  19462. ret = unwrapTSNode(ret);
  19463. return ret.type === "MemberExpression" || ret.type === "OptionalMemberExpression" || ret.type === "Identifier" && ret.name !== "undefined";
  19464. } catch (e) {
  19465. return false;
  19466. }
  19467. };
  19468. const isMemberExpression = isMemberExpressionNode;
  19469. const fnExpRE = /^\s*(?:async\s*)?(?:\([^)]*?\)|[\w$_]+)\s*(?::[^=]+)?=>|^\s*(?:async\s+)?function(?:\s+[\w$]+)?\s*\(/;
  19470. const isFnExpressionBrowser = (exp) => fnExpRE.test(getExpSource(exp));
  19471. const isFnExpressionNode = (exp, context) => {
  19472. try {
  19473. let ret = exp.ast || libExports.parseExpression(getExpSource(exp), {
  19474. plugins: context.expressionPlugins ? [...context.expressionPlugins, "typescript"] : ["typescript"]
  19475. });
  19476. if (ret.type === "Program") {
  19477. ret = ret.body[0];
  19478. if (ret.type === "ExpressionStatement") {
  19479. ret = ret.expression;
  19480. }
  19481. }
  19482. ret = unwrapTSNode(ret);
  19483. return ret.type === "FunctionExpression" || ret.type === "ArrowFunctionExpression";
  19484. } catch (e) {
  19485. return false;
  19486. }
  19487. };
  19488. const isFnExpression = isFnExpressionNode;
  19489. function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
  19490. return advancePositionWithMutation(
  19491. {
  19492. offset: pos.offset,
  19493. line: pos.line,
  19494. column: pos.column
  19495. },
  19496. source,
  19497. numberOfCharacters
  19498. );
  19499. }
  19500. function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
  19501. let linesCount = 0;
  19502. let lastNewLinePos = -1;
  19503. for (let i = 0; i < numberOfCharacters; i++) {
  19504. if (source.charCodeAt(i) === 10) {
  19505. linesCount++;
  19506. lastNewLinePos = i;
  19507. }
  19508. }
  19509. pos.offset += numberOfCharacters;
  19510. pos.line += linesCount;
  19511. pos.column = lastNewLinePos === -1 ? pos.column + numberOfCharacters : numberOfCharacters - lastNewLinePos;
  19512. return pos;
  19513. }
  19514. function assert(condition, msg) {
  19515. if (!condition) {
  19516. throw new Error(msg || `unexpected compiler condition`);
  19517. }
  19518. }
  19519. function findDir(node, name, allowEmpty = false) {
  19520. for (let i = 0; i < node.props.length; i++) {
  19521. const p = node.props[i];
  19522. if (p.type === 7 && (allowEmpty || p.exp) && (isString$1(name) ? p.name === name : name.test(p.name))) {
  19523. return p;
  19524. }
  19525. }
  19526. }
  19527. function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
  19528. for (let i = 0; i < node.props.length; i++) {
  19529. const p = node.props[i];
  19530. if (p.type === 6) {
  19531. if (dynamicOnly) continue;
  19532. if (p.name === name && (p.value || allowEmpty)) {
  19533. return p;
  19534. }
  19535. } else if (p.name === "bind" && (p.exp || allowEmpty) && isStaticArgOf(p.arg, name)) {
  19536. return p;
  19537. }
  19538. }
  19539. }
  19540. function isStaticArgOf(arg, name) {
  19541. return !!(arg && isStaticExp(arg) && arg.content === name);
  19542. }
  19543. function hasDynamicKeyVBind(node) {
  19544. return node.props.some(
  19545. (p) => p.type === 7 && p.name === "bind" && (!p.arg || // v-bind="obj"
  19546. p.arg.type !== 4 || // v-bind:[_ctx.foo]
  19547. !p.arg.isStatic)
  19548. // v-bind:[foo]
  19549. );
  19550. }
  19551. function isText$1(node) {
  19552. return node.type === 5 || node.type === 2;
  19553. }
  19554. function isVPre(p) {
  19555. return p.type === 7 && p.name === "pre";
  19556. }
  19557. function isVSlot(p) {
  19558. return p.type === 7 && p.name === "slot";
  19559. }
  19560. function isTemplateNode(node) {
  19561. return node.type === 1 && node.tagType === 3;
  19562. }
  19563. function isSlotOutlet(node) {
  19564. return node.type === 1 && node.tagType === 2;
  19565. }
  19566. const propsHelperSet = /* @__PURE__ */ new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
  19567. function getUnnormalizedProps(props, callPath = []) {
  19568. if (props && !isString$1(props) && props.type === 14) {
  19569. const callee = props.callee;
  19570. if (!isString$1(callee) && propsHelperSet.has(callee)) {
  19571. return getUnnormalizedProps(
  19572. props.arguments[0],
  19573. callPath.concat(props)
  19574. );
  19575. }
  19576. }
  19577. return [props, callPath];
  19578. }
  19579. function injectProp(node, prop, context) {
  19580. let propsWithInjection;
  19581. let props = node.type === 13 ? node.props : node.arguments[2];
  19582. let callPath = [];
  19583. let parentCall;
  19584. if (props && !isString$1(props) && props.type === 14) {
  19585. const ret = getUnnormalizedProps(props);
  19586. props = ret[0];
  19587. callPath = ret[1];
  19588. parentCall = callPath[callPath.length - 1];
  19589. }
  19590. if (props == null || isString$1(props)) {
  19591. propsWithInjection = createObjectExpression([prop]);
  19592. } else if (props.type === 14) {
  19593. const first = props.arguments[0];
  19594. if (!isString$1(first) && first.type === 15) {
  19595. if (!hasProp(prop, first)) {
  19596. first.properties.unshift(prop);
  19597. }
  19598. } else {
  19599. if (props.callee === TO_HANDLERS) {
  19600. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  19601. createObjectExpression([prop]),
  19602. props
  19603. ]);
  19604. } else {
  19605. props.arguments.unshift(createObjectExpression([prop]));
  19606. }
  19607. }
  19608. !propsWithInjection && (propsWithInjection = props);
  19609. } else if (props.type === 15) {
  19610. if (!hasProp(prop, props)) {
  19611. props.properties.unshift(prop);
  19612. }
  19613. propsWithInjection = props;
  19614. } else {
  19615. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  19616. createObjectExpression([prop]),
  19617. props
  19618. ]);
  19619. if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
  19620. parentCall = callPath[callPath.length - 2];
  19621. }
  19622. }
  19623. if (node.type === 13) {
  19624. if (parentCall) {
  19625. parentCall.arguments[0] = propsWithInjection;
  19626. } else {
  19627. node.props = propsWithInjection;
  19628. }
  19629. } else {
  19630. if (parentCall) {
  19631. parentCall.arguments[0] = propsWithInjection;
  19632. } else {
  19633. node.arguments[2] = propsWithInjection;
  19634. }
  19635. }
  19636. }
  19637. function hasProp(prop, props) {
  19638. let result = false;
  19639. if (prop.key.type === 4) {
  19640. const propKeyName = prop.key.content;
  19641. result = props.properties.some(
  19642. (p) => p.key.type === 4 && p.key.content === propKeyName
  19643. );
  19644. }
  19645. return result;
  19646. }
  19647. function toValidAssetId(name, type) {
  19648. return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
  19649. return searchValue === "-" ? "_" : name.charCodeAt(replaceValue).toString();
  19650. })}`;
  19651. }
  19652. function hasScopeRef(node, ids) {
  19653. if (!node || Object.keys(ids).length === 0) {
  19654. return false;
  19655. }
  19656. switch (node.type) {
  19657. case 1:
  19658. for (let i = 0; i < node.props.length; i++) {
  19659. const p = node.props[i];
  19660. if (p.type === 7 && (hasScopeRef(p.arg, ids) || hasScopeRef(p.exp, ids))) {
  19661. return true;
  19662. }
  19663. }
  19664. return node.children.some((c) => hasScopeRef(c, ids));
  19665. case 11:
  19666. if (hasScopeRef(node.source, ids)) {
  19667. return true;
  19668. }
  19669. return node.children.some((c) => hasScopeRef(c, ids));
  19670. case 9:
  19671. return node.branches.some((b) => hasScopeRef(b, ids));
  19672. case 10:
  19673. if (hasScopeRef(node.condition, ids)) {
  19674. return true;
  19675. }
  19676. return node.children.some((c) => hasScopeRef(c, ids));
  19677. case 4:
  19678. return !node.isStatic && isSimpleIdentifier(node.content) && !!ids[node.content];
  19679. case 8:
  19680. return node.children.some((c) => isObject$2(c) && hasScopeRef(c, ids));
  19681. case 5:
  19682. case 12:
  19683. return hasScopeRef(node.content, ids);
  19684. case 2:
  19685. case 3:
  19686. case 20:
  19687. return false;
  19688. default:
  19689. return false;
  19690. }
  19691. }
  19692. function getMemoedVNodeCall(node) {
  19693. if (node.type === 14 && node.callee === WITH_MEMO) {
  19694. return node.arguments[1].returns;
  19695. } else {
  19696. return node;
  19697. }
  19698. }
  19699. const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+(\S[\s\S]*)/;
  19700. function isAllWhitespace(str) {
  19701. for (let i = 0; i < str.length; i++) {
  19702. if (!isWhitespace(str.charCodeAt(i))) {
  19703. return false;
  19704. }
  19705. }
  19706. return true;
  19707. }
  19708. function isWhitespaceText(node) {
  19709. return node.type === 2 && isAllWhitespace(node.content) || node.type === 12 && isWhitespaceText(node.content);
  19710. }
  19711. function isCommentOrWhitespace(node) {
  19712. return node.type === 3 || isWhitespaceText(node);
  19713. }
  19714. const defaultParserOptions = {
  19715. parseMode: "base",
  19716. ns: 0,
  19717. delimiters: [`{{`, `}}`],
  19718. getNamespace: () => 0,
  19719. isVoidTag: NO,
  19720. isPreTag: NO,
  19721. isIgnoreNewlineTag: NO,
  19722. isCustomElement: NO,
  19723. onError: defaultOnError,
  19724. onWarn: defaultOnWarn,
  19725. comments: true,
  19726. prefixIdentifiers: false
  19727. };
  19728. let currentOptions = defaultParserOptions;
  19729. let currentRoot = null;
  19730. let currentInput = "";
  19731. let currentOpenTag = null;
  19732. let currentProp = null;
  19733. let currentAttrValue = "";
  19734. let currentAttrStartIndex = -1;
  19735. let currentAttrEndIndex = -1;
  19736. let inPre = 0;
  19737. let inVPre = false;
  19738. let currentVPreBoundary = null;
  19739. const stack = [];
  19740. const tokenizer = new Tokenizer(stack, {
  19741. onerr: emitError,
  19742. ontext(start, end) {
  19743. onText(getSlice(start, end), start, end);
  19744. },
  19745. ontextentity(char, start, end) {
  19746. onText(char, start, end);
  19747. },
  19748. oninterpolation(start, end) {
  19749. if (inVPre) {
  19750. return onText(getSlice(start, end), start, end);
  19751. }
  19752. let innerStart = start + tokenizer.delimiterOpen.length;
  19753. let innerEnd = end - tokenizer.delimiterClose.length;
  19754. while (isWhitespace(currentInput.charCodeAt(innerStart))) {
  19755. innerStart++;
  19756. }
  19757. while (isWhitespace(currentInput.charCodeAt(innerEnd - 1))) {
  19758. innerEnd--;
  19759. }
  19760. let exp = getSlice(innerStart, innerEnd);
  19761. if (exp.includes("&")) {
  19762. {
  19763. exp = decodeHTML(exp);
  19764. }
  19765. }
  19766. addNode({
  19767. type: 5,
  19768. content: createExp(exp, false, getLoc(innerStart, innerEnd)),
  19769. loc: getLoc(start, end)
  19770. });
  19771. },
  19772. onopentagname(start, end) {
  19773. const name = getSlice(start, end);
  19774. currentOpenTag = {
  19775. type: 1,
  19776. tag: name,
  19777. ns: currentOptions.getNamespace(name, stack[0], currentOptions.ns),
  19778. tagType: 0,
  19779. // will be refined on tag close
  19780. props: [],
  19781. children: [],
  19782. loc: getLoc(start - 1, end),
  19783. codegenNode: void 0
  19784. };
  19785. },
  19786. onopentagend(end) {
  19787. endOpenTag(end);
  19788. },
  19789. onclosetag(start, end) {
  19790. const name = getSlice(start, end);
  19791. if (!currentOptions.isVoidTag(name)) {
  19792. let found = false;
  19793. for (let i = 0; i < stack.length; i++) {
  19794. const e = stack[i];
  19795. if (e.tag.toLowerCase() === name.toLowerCase()) {
  19796. found = true;
  19797. if (i > 0) {
  19798. emitError(24, stack[0].loc.start.offset);
  19799. }
  19800. for (let j = 0; j <= i; j++) {
  19801. const el = stack.shift();
  19802. onCloseTag(el, end, j < i);
  19803. }
  19804. break;
  19805. }
  19806. }
  19807. if (!found) {
  19808. emitError(23, backTrack(start, 60));
  19809. }
  19810. }
  19811. },
  19812. onselfclosingtag(end) {
  19813. const name = currentOpenTag.tag;
  19814. currentOpenTag.isSelfClosing = true;
  19815. endOpenTag(end);
  19816. if (stack[0] && stack[0].tag === name) {
  19817. onCloseTag(stack.shift(), end);
  19818. }
  19819. },
  19820. onattribname(start, end) {
  19821. currentProp = {
  19822. type: 6,
  19823. name: getSlice(start, end),
  19824. nameLoc: getLoc(start, end),
  19825. value: void 0,
  19826. loc: getLoc(start)
  19827. };
  19828. },
  19829. ondirname(start, end) {
  19830. const raw = getSlice(start, end);
  19831. const name = raw === "." || raw === ":" ? "bind" : raw === "@" ? "on" : raw === "#" ? "slot" : raw.slice(2);
  19832. if (!inVPre && name === "") {
  19833. emitError(26, start);
  19834. }
  19835. if (inVPre || name === "") {
  19836. currentProp = {
  19837. type: 6,
  19838. name: raw,
  19839. nameLoc: getLoc(start, end),
  19840. value: void 0,
  19841. loc: getLoc(start)
  19842. };
  19843. } else {
  19844. currentProp = {
  19845. type: 7,
  19846. name,
  19847. rawName: raw,
  19848. exp: void 0,
  19849. arg: void 0,
  19850. modifiers: raw === "." ? [createSimpleExpression("prop")] : [],
  19851. loc: getLoc(start)
  19852. };
  19853. if (name === "pre") {
  19854. inVPre = tokenizer.inVPre = true;
  19855. currentVPreBoundary = currentOpenTag;
  19856. const props = currentOpenTag.props;
  19857. for (let i = 0; i < props.length; i++) {
  19858. if (props[i].type === 7) {
  19859. props[i] = dirToAttr(props[i]);
  19860. }
  19861. }
  19862. }
  19863. }
  19864. },
  19865. ondirarg(start, end) {
  19866. if (start === end) return;
  19867. const arg = getSlice(start, end);
  19868. if (inVPre && !isVPre(currentProp)) {
  19869. currentProp.name += arg;
  19870. setLocEnd(currentProp.nameLoc, end);
  19871. } else {
  19872. const isStatic = arg[0] !== `[`;
  19873. currentProp.arg = createExp(
  19874. isStatic ? arg : arg.slice(1, -1),
  19875. isStatic,
  19876. getLoc(start, end),
  19877. isStatic ? 3 : 0
  19878. );
  19879. }
  19880. },
  19881. ondirmodifier(start, end) {
  19882. const mod = getSlice(start, end);
  19883. if (inVPre && !isVPre(currentProp)) {
  19884. currentProp.name += "." + mod;
  19885. setLocEnd(currentProp.nameLoc, end);
  19886. } else if (currentProp.name === "slot") {
  19887. const arg = currentProp.arg;
  19888. if (arg) {
  19889. arg.content += "." + mod;
  19890. setLocEnd(arg.loc, end);
  19891. }
  19892. } else {
  19893. const exp = createSimpleExpression(mod, true, getLoc(start, end));
  19894. currentProp.modifiers.push(exp);
  19895. }
  19896. },
  19897. onattribdata(start, end) {
  19898. currentAttrValue += getSlice(start, end);
  19899. if (currentAttrStartIndex < 0) currentAttrStartIndex = start;
  19900. currentAttrEndIndex = end;
  19901. },
  19902. onattribentity(char, start, end) {
  19903. currentAttrValue += char;
  19904. if (currentAttrStartIndex < 0) currentAttrStartIndex = start;
  19905. currentAttrEndIndex = end;
  19906. },
  19907. onattribnameend(end) {
  19908. const start = currentProp.loc.start.offset;
  19909. const name = getSlice(start, end);
  19910. if (currentProp.type === 7) {
  19911. currentProp.rawName = name;
  19912. }
  19913. if (currentOpenTag.props.some(
  19914. (p) => (p.type === 7 ? p.rawName : p.name) === name
  19915. )) {
  19916. emitError(2, start);
  19917. }
  19918. },
  19919. onattribend(quote, end) {
  19920. if (currentOpenTag && currentProp) {
  19921. setLocEnd(currentProp.loc, end);
  19922. if (quote !== 0) {
  19923. if (currentProp.type === 6) {
  19924. if (currentProp.name === "class") {
  19925. currentAttrValue = condense(currentAttrValue).trim();
  19926. }
  19927. if (quote === 1 && !currentAttrValue) {
  19928. emitError(13, end);
  19929. }
  19930. currentProp.value = {
  19931. type: 2,
  19932. content: currentAttrValue,
  19933. loc: quote === 1 ? getLoc(currentAttrStartIndex, currentAttrEndIndex) : getLoc(currentAttrStartIndex - 1, currentAttrEndIndex + 1)
  19934. };
  19935. if (tokenizer.inSFCRoot && currentOpenTag.tag === "template" && currentProp.name === "lang" && currentAttrValue && currentAttrValue !== "html") {
  19936. tokenizer.enterRCDATA(toCharCodes(`</template`), 0);
  19937. }
  19938. } else {
  19939. let expParseMode = 0 /* Normal */;
  19940. {
  19941. if (currentProp.name === "for") {
  19942. expParseMode = 3 /* Skip */;
  19943. } else if (currentProp.name === "slot") {
  19944. expParseMode = 1 /* Params */;
  19945. } else if (currentProp.name === "on" && currentAttrValue.includes(";")) {
  19946. expParseMode = 2 /* Statements */;
  19947. }
  19948. }
  19949. currentProp.exp = createExp(
  19950. currentAttrValue,
  19951. false,
  19952. getLoc(currentAttrStartIndex, currentAttrEndIndex),
  19953. 0,
  19954. expParseMode
  19955. );
  19956. if (currentProp.name === "for") {
  19957. currentProp.forParseResult = parseForExpression(currentProp.exp);
  19958. }
  19959. }
  19960. }
  19961. if (currentProp.type !== 7 || currentProp.name !== "pre") {
  19962. currentOpenTag.props.push(currentProp);
  19963. }
  19964. }
  19965. currentAttrValue = "";
  19966. currentAttrStartIndex = currentAttrEndIndex = -1;
  19967. },
  19968. oncomment(start, end) {
  19969. if (currentOptions.comments) {
  19970. addNode({
  19971. type: 3,
  19972. content: getSlice(start, end),
  19973. loc: getLoc(start - 4, end + 3)
  19974. });
  19975. }
  19976. },
  19977. onend() {
  19978. const end = currentInput.length;
  19979. if (tokenizer.state !== 1) {
  19980. switch (tokenizer.state) {
  19981. case 5:
  19982. case 8:
  19983. emitError(5, end);
  19984. break;
  19985. case 3:
  19986. case 4:
  19987. emitError(
  19988. 25,
  19989. tokenizer.sectionStart
  19990. );
  19991. break;
  19992. case 28:
  19993. if (tokenizer.currentSequence === Sequences.CdataEnd) {
  19994. emitError(6, end);
  19995. } else {
  19996. emitError(7, end);
  19997. }
  19998. break;
  19999. case 6:
  20000. case 7:
  20001. case 9:
  20002. case 11:
  20003. case 12:
  20004. case 13:
  20005. case 14:
  20006. case 15:
  20007. case 16:
  20008. case 17:
  20009. case 18:
  20010. case 19:
  20011. // "
  20012. case 20:
  20013. // '
  20014. case 21:
  20015. emitError(9, end);
  20016. break;
  20017. }
  20018. }
  20019. for (let index = 0; index < stack.length; index++) {
  20020. onCloseTag(stack[index], end - 1);
  20021. emitError(24, stack[index].loc.start.offset);
  20022. }
  20023. },
  20024. oncdata(start, end) {
  20025. if (stack[0].ns !== 0) {
  20026. onText(getSlice(start, end), start, end);
  20027. } else {
  20028. emitError(1, start - 9);
  20029. }
  20030. },
  20031. onprocessinginstruction(start) {
  20032. if ((stack[0] ? stack[0].ns : currentOptions.ns) === 0) {
  20033. emitError(
  20034. 21,
  20035. start - 1
  20036. );
  20037. }
  20038. }
  20039. });
  20040. const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
  20041. const stripParensRE = /^\(|\)$/g;
  20042. function parseForExpression(input) {
  20043. const loc = input.loc;
  20044. const exp = input.content;
  20045. const inMatch = exp.match(forAliasRE);
  20046. if (!inMatch) return;
  20047. const [, LHS, RHS] = inMatch;
  20048. const createAliasExpression = (content, offset, asParam = false) => {
  20049. const start = loc.start.offset + offset;
  20050. const end = start + content.length;
  20051. return createExp(
  20052. content,
  20053. false,
  20054. getLoc(start, end),
  20055. 0,
  20056. asParam ? 1 /* Params */ : 0 /* Normal */
  20057. );
  20058. };
  20059. const result = {
  20060. source: createAliasExpression(RHS.trim(), exp.indexOf(RHS, LHS.length)),
  20061. value: void 0,
  20062. key: void 0,
  20063. index: void 0,
  20064. finalized: false
  20065. };
  20066. let valueContent = LHS.trim().replace(stripParensRE, "").trim();
  20067. const trimmedOffset = LHS.indexOf(valueContent);
  20068. const iteratorMatch = valueContent.match(forIteratorRE);
  20069. if (iteratorMatch) {
  20070. valueContent = valueContent.replace(forIteratorRE, "").trim();
  20071. const keyContent = iteratorMatch[1].trim();
  20072. let keyOffset;
  20073. if (keyContent) {
  20074. keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
  20075. result.key = createAliasExpression(keyContent, keyOffset, true);
  20076. }
  20077. if (iteratorMatch[2]) {
  20078. const indexContent = iteratorMatch[2].trim();
  20079. if (indexContent) {
  20080. result.index = createAliasExpression(
  20081. indexContent,
  20082. exp.indexOf(
  20083. indexContent,
  20084. result.key ? keyOffset + keyContent.length : trimmedOffset + valueContent.length
  20085. ),
  20086. true
  20087. );
  20088. }
  20089. }
  20090. }
  20091. if (valueContent) {
  20092. result.value = createAliasExpression(valueContent, trimmedOffset, true);
  20093. }
  20094. return result;
  20095. }
  20096. function getSlice(start, end) {
  20097. return currentInput.slice(start, end);
  20098. }
  20099. function endOpenTag(end) {
  20100. if (tokenizer.inSFCRoot) {
  20101. currentOpenTag.innerLoc = getLoc(end + 1, end + 1);
  20102. }
  20103. addNode(currentOpenTag);
  20104. const { tag, ns } = currentOpenTag;
  20105. if (ns === 0 && currentOptions.isPreTag(tag)) {
  20106. inPre++;
  20107. }
  20108. if (currentOptions.isVoidTag(tag)) {
  20109. onCloseTag(currentOpenTag, end);
  20110. } else {
  20111. stack.unshift(currentOpenTag);
  20112. if (ns === 1 || ns === 2) {
  20113. tokenizer.inXML = true;
  20114. }
  20115. }
  20116. currentOpenTag = null;
  20117. }
  20118. function onText(content, start, end) {
  20119. const parent = stack[0] || currentRoot;
  20120. const lastNode = parent.children[parent.children.length - 1];
  20121. if (lastNode && lastNode.type === 2) {
  20122. lastNode.content += content;
  20123. setLocEnd(lastNode.loc, end);
  20124. } else {
  20125. parent.children.push({
  20126. type: 2,
  20127. content,
  20128. loc: getLoc(start, end)
  20129. });
  20130. }
  20131. }
  20132. function onCloseTag(el, end, isImplied = false) {
  20133. if (isImplied) {
  20134. setLocEnd(el.loc, backTrack(end, 60));
  20135. } else {
  20136. setLocEnd(el.loc, lookAhead(end, 62) + 1);
  20137. }
  20138. if (tokenizer.inSFCRoot) {
  20139. if (el.children.length) {
  20140. el.innerLoc.end = extend({}, el.children[el.children.length - 1].loc.end);
  20141. } else {
  20142. el.innerLoc.end = extend({}, el.innerLoc.start);
  20143. }
  20144. el.innerLoc.source = getSlice(
  20145. el.innerLoc.start.offset,
  20146. el.innerLoc.end.offset
  20147. );
  20148. }
  20149. const { tag, ns, children } = el;
  20150. if (!inVPre) {
  20151. if (tag === "slot") {
  20152. el.tagType = 2;
  20153. } else if (isFragmentTemplate(el)) {
  20154. el.tagType = 3;
  20155. } else if (isComponent(el)) {
  20156. el.tagType = 1;
  20157. }
  20158. }
  20159. if (!tokenizer.inRCDATA) {
  20160. el.children = condenseWhitespace(children);
  20161. }
  20162. if (ns === 0 && currentOptions.isIgnoreNewlineTag(tag)) {
  20163. const first = children[0];
  20164. if (first && first.type === 2) {
  20165. first.content = first.content.replace(/^\r?\n/, "");
  20166. }
  20167. }
  20168. if (ns === 0 && currentOptions.isPreTag(tag)) {
  20169. inPre--;
  20170. }
  20171. if (currentVPreBoundary === el) {
  20172. inVPre = tokenizer.inVPre = false;
  20173. currentVPreBoundary = null;
  20174. }
  20175. if (tokenizer.inXML && (stack[0] ? stack[0].ns : currentOptions.ns) === 0) {
  20176. tokenizer.inXML = false;
  20177. }
  20178. }
  20179. function lookAhead(index, c) {
  20180. let i = index;
  20181. while (currentInput.charCodeAt(i) !== c && i < currentInput.length - 1) i++;
  20182. return i;
  20183. }
  20184. function backTrack(index, c) {
  20185. let i = index;
  20186. while (currentInput.charCodeAt(i) !== c && i >= 0) i--;
  20187. return i;
  20188. }
  20189. const specialTemplateDir = /* @__PURE__ */ new Set(["if", "else", "else-if", "for", "slot"]);
  20190. function isFragmentTemplate({ tag, props }) {
  20191. if (tag === "template") {
  20192. for (let i = 0; i < props.length; i++) {
  20193. if (props[i].type === 7 && specialTemplateDir.has(props[i].name)) {
  20194. return true;
  20195. }
  20196. }
  20197. }
  20198. return false;
  20199. }
  20200. function isComponent({ tag, props }) {
  20201. if (currentOptions.isCustomElement(tag)) {
  20202. return false;
  20203. }
  20204. if (tag === "component" || isUpperCase(tag.charCodeAt(0)) || isCoreComponent(tag) || currentOptions.isBuiltInComponent && currentOptions.isBuiltInComponent(tag) || currentOptions.isNativeTag && !currentOptions.isNativeTag(tag)) {
  20205. return true;
  20206. }
  20207. for (let i = 0; i < props.length; i++) {
  20208. const p = props[i];
  20209. if (p.type === 6) {
  20210. if (p.name === "is" && p.value) {
  20211. if (p.value.content.startsWith("vue:")) {
  20212. return true;
  20213. }
  20214. }
  20215. }
  20216. }
  20217. return false;
  20218. }
  20219. function isUpperCase(c) {
  20220. return c > 64 && c < 91;
  20221. }
  20222. const windowsNewlineRE = /\r\n/g;
  20223. function condenseWhitespace(nodes) {
  20224. const shouldCondense = currentOptions.whitespace !== "preserve";
  20225. let removedWhitespace = false;
  20226. for (let i = 0; i < nodes.length; i++) {
  20227. const node = nodes[i];
  20228. if (node.type === 2) {
  20229. if (!inPre) {
  20230. if (isAllWhitespace(node.content)) {
  20231. const prev = nodes[i - 1] && nodes[i - 1].type;
  20232. const next = nodes[i + 1] && nodes[i + 1].type;
  20233. if (!prev || !next || shouldCondense && (prev === 3 && (next === 3 || next === 1) || prev === 1 && (next === 3 || next === 1 && hasNewlineChar(node.content)))) {
  20234. removedWhitespace = true;
  20235. nodes[i] = null;
  20236. } else {
  20237. node.content = " ";
  20238. }
  20239. } else if (shouldCondense) {
  20240. node.content = condense(node.content);
  20241. }
  20242. } else {
  20243. node.content = node.content.replace(windowsNewlineRE, "\n");
  20244. }
  20245. }
  20246. }
  20247. return removedWhitespace ? nodes.filter(Boolean) : nodes;
  20248. }
  20249. function hasNewlineChar(str) {
  20250. for (let i = 0; i < str.length; i++) {
  20251. const c = str.charCodeAt(i);
  20252. if (c === 10 || c === 13) {
  20253. return true;
  20254. }
  20255. }
  20256. return false;
  20257. }
  20258. function condense(str) {
  20259. let ret = "";
  20260. let prevCharIsWhitespace = false;
  20261. for (let i = 0; i < str.length; i++) {
  20262. if (isWhitespace(str.charCodeAt(i))) {
  20263. if (!prevCharIsWhitespace) {
  20264. ret += " ";
  20265. prevCharIsWhitespace = true;
  20266. }
  20267. } else {
  20268. ret += str[i];
  20269. prevCharIsWhitespace = false;
  20270. }
  20271. }
  20272. return ret;
  20273. }
  20274. function addNode(node) {
  20275. (stack[0] || currentRoot).children.push(node);
  20276. }
  20277. function getLoc(start, end) {
  20278. return {
  20279. start: tokenizer.getPos(start),
  20280. // @ts-expect-error allow late attachment
  20281. end: end == null ? end : tokenizer.getPos(end),
  20282. // @ts-expect-error allow late attachment
  20283. source: end == null ? end : getSlice(start, end)
  20284. };
  20285. }
  20286. function cloneLoc(loc) {
  20287. return getLoc(loc.start.offset, loc.end.offset);
  20288. }
  20289. function setLocEnd(loc, end) {
  20290. loc.end = tokenizer.getPos(end);
  20291. loc.source = getSlice(loc.start.offset, end);
  20292. }
  20293. function dirToAttr(dir) {
  20294. const attr = {
  20295. type: 6,
  20296. name: dir.rawName,
  20297. nameLoc: getLoc(
  20298. dir.loc.start.offset,
  20299. dir.loc.start.offset + dir.rawName.length
  20300. ),
  20301. value: void 0,
  20302. loc: dir.loc
  20303. };
  20304. if (dir.exp) {
  20305. const loc = dir.exp.loc;
  20306. if (loc.end.offset < dir.loc.end.offset) {
  20307. loc.start.offset--;
  20308. loc.start.column--;
  20309. loc.end.offset++;
  20310. loc.end.column++;
  20311. }
  20312. attr.value = {
  20313. type: 2,
  20314. content: dir.exp.content,
  20315. loc
  20316. };
  20317. }
  20318. return attr;
  20319. }
  20320. function createExp(content, isStatic = false, loc, constType = 0, parseMode = 0 /* Normal */) {
  20321. const exp = createSimpleExpression(content, isStatic, loc, constType);
  20322. if (!isStatic && currentOptions.prefixIdentifiers && parseMode !== 3 /* Skip */ && content.trim()) {
  20323. if (isSimpleIdentifier(content)) {
  20324. exp.ast = null;
  20325. return exp;
  20326. }
  20327. try {
  20328. const plugins = currentOptions.expressionPlugins;
  20329. const options = {
  20330. plugins: plugins ? [...plugins, "typescript"] : ["typescript"]
  20331. };
  20332. if (parseMode === 2 /* Statements */) {
  20333. exp.ast = libExports.parse(` ${content} `, options).program;
  20334. } else if (parseMode === 1 /* Params */) {
  20335. exp.ast = libExports.parseExpression(`(${content})=>{}`, options);
  20336. } else {
  20337. exp.ast = libExports.parseExpression(`(${content})`, options);
  20338. }
  20339. } catch (e) {
  20340. exp.ast = false;
  20341. emitError(46, loc.start.offset, e.message);
  20342. }
  20343. }
  20344. return exp;
  20345. }
  20346. function emitError(code, index, message) {
  20347. currentOptions.onError(
  20348. createCompilerError(code, getLoc(index, index), void 0, message)
  20349. );
  20350. }
  20351. function reset() {
  20352. tokenizer.reset();
  20353. currentOpenTag = null;
  20354. currentProp = null;
  20355. currentAttrValue = "";
  20356. currentAttrStartIndex = -1;
  20357. currentAttrEndIndex = -1;
  20358. stack.length = 0;
  20359. }
  20360. function baseParse(input, options) {
  20361. reset();
  20362. currentInput = input;
  20363. currentOptions = extend({}, defaultParserOptions);
  20364. if (options) {
  20365. let key;
  20366. for (key in options) {
  20367. if (options[key] != null) {
  20368. currentOptions[key] = options[key];
  20369. }
  20370. }
  20371. }
  20372. {
  20373. if (currentOptions.decodeEntities) {
  20374. console.warn(
  20375. `[@vue/compiler-core] decodeEntities option is passed but will be ignored in non-browser builds.`
  20376. );
  20377. }
  20378. }
  20379. tokenizer.mode = currentOptions.parseMode === "html" ? 1 : currentOptions.parseMode === "sfc" ? 2 : 0;
  20380. tokenizer.inXML = currentOptions.ns === 1 || currentOptions.ns === 2;
  20381. const delimiters = options && options.delimiters;
  20382. if (delimiters) {
  20383. tokenizer.delimiterOpen = toCharCodes(delimiters[0]);
  20384. tokenizer.delimiterClose = toCharCodes(delimiters[1]);
  20385. }
  20386. const root = currentRoot = createRoot([], input);
  20387. tokenizer.parse(currentInput);
  20388. root.loc = getLoc(0, input.length);
  20389. root.children = condenseWhitespace(root.children);
  20390. currentRoot = null;
  20391. return root;
  20392. }
  20393. function cacheStatic(root, context) {
  20394. walk$1(
  20395. root,
  20396. void 0,
  20397. context,
  20398. // Root node is unfortunately non-hoistable due to potential parent
  20399. // fallthrough attributes.
  20400. !!getSingleElementRoot(root)
  20401. );
  20402. }
  20403. function getSingleElementRoot(root) {
  20404. const children = root.children.filter((x) => x.type !== 3);
  20405. return children.length === 1 && children[0].type === 1 && !isSlotOutlet(children[0]) ? children[0] : null;
  20406. }
  20407. function walk$1(node, parent, context, doNotHoistNode = false, inFor = false) {
  20408. const { children } = node;
  20409. const toCache = [];
  20410. for (let i = 0; i < children.length; i++) {
  20411. const child = children[i];
  20412. if (child.type === 1 && child.tagType === 0) {
  20413. const constantType = doNotHoistNode ? 0 : getConstantType(child, context);
  20414. if (constantType > 0) {
  20415. if (constantType >= 2) {
  20416. child.codegenNode.patchFlag = -1;
  20417. toCache.push(child);
  20418. continue;
  20419. }
  20420. } else {
  20421. const codegenNode = child.codegenNode;
  20422. if (codegenNode.type === 13) {
  20423. const flag = codegenNode.patchFlag;
  20424. if ((flag === void 0 || flag === 512 || flag === 1) && getGeneratedPropsConstantType(child, context) >= 2) {
  20425. const props = getNodeProps(child);
  20426. if (props) {
  20427. codegenNode.props = context.hoist(props);
  20428. }
  20429. }
  20430. if (codegenNode.dynamicProps) {
  20431. codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
  20432. }
  20433. }
  20434. }
  20435. } else if (child.type === 12) {
  20436. const constantType = doNotHoistNode ? 0 : getConstantType(child, context);
  20437. if (constantType >= 2) {
  20438. if (child.codegenNode.type === 14 && child.codegenNode.arguments.length > 0) {
  20439. child.codegenNode.arguments.push(
  20440. -1 + (` /* ${PatchFlagNames[-1]} */` )
  20441. );
  20442. }
  20443. toCache.push(child);
  20444. continue;
  20445. }
  20446. }
  20447. if (child.type === 1) {
  20448. const isComponent = child.tagType === 1;
  20449. if (isComponent) {
  20450. context.scopes.vSlot++;
  20451. }
  20452. walk$1(child, node, context, false, inFor);
  20453. if (isComponent) {
  20454. context.scopes.vSlot--;
  20455. }
  20456. } else if (child.type === 11) {
  20457. walk$1(child, node, context, child.children.length === 1, true);
  20458. } else if (child.type === 9) {
  20459. for (let i2 = 0; i2 < child.branches.length; i2++) {
  20460. walk$1(
  20461. child.branches[i2],
  20462. node,
  20463. context,
  20464. child.branches[i2].children.length === 1,
  20465. inFor
  20466. );
  20467. }
  20468. }
  20469. }
  20470. let cachedAsArray = false;
  20471. if (toCache.length === children.length && node.type === 1) {
  20472. if (node.tagType === 0 && node.codegenNode && node.codegenNode.type === 13 && isArray$3(node.codegenNode.children)) {
  20473. node.codegenNode.children = getCacheExpression(
  20474. createArrayExpression(node.codegenNode.children)
  20475. );
  20476. cachedAsArray = true;
  20477. } else if (node.tagType === 1 && node.codegenNode && node.codegenNode.type === 13 && node.codegenNode.children && !isArray$3(node.codegenNode.children) && node.codegenNode.children.type === 15) {
  20478. const slot = getSlotNode(node.codegenNode, "default");
  20479. if (slot) {
  20480. slot.returns = getCacheExpression(
  20481. createArrayExpression(slot.returns)
  20482. );
  20483. cachedAsArray = true;
  20484. }
  20485. } else if (node.tagType === 3 && parent && parent.type === 1 && parent.tagType === 1 && parent.codegenNode && parent.codegenNode.type === 13 && parent.codegenNode.children && !isArray$3(parent.codegenNode.children) && parent.codegenNode.children.type === 15) {
  20486. const slotName = findDir(node, "slot", true);
  20487. const slot = slotName && slotName.arg && getSlotNode(parent.codegenNode, slotName.arg);
  20488. if (slot) {
  20489. slot.returns = getCacheExpression(
  20490. createArrayExpression(slot.returns)
  20491. );
  20492. cachedAsArray = true;
  20493. }
  20494. }
  20495. }
  20496. if (!cachedAsArray) {
  20497. for (const child of toCache) {
  20498. child.codegenNode = context.cache(child.codegenNode);
  20499. }
  20500. }
  20501. function getCacheExpression(value) {
  20502. const exp = context.cache(value);
  20503. exp.needArraySpread = true;
  20504. return exp;
  20505. }
  20506. function getSlotNode(node2, name) {
  20507. if (node2.children && !isArray$3(node2.children) && node2.children.type === 15) {
  20508. const slot = node2.children.properties.find(
  20509. (p) => p.key === name || p.key.content === name
  20510. );
  20511. return slot && slot.value;
  20512. }
  20513. }
  20514. if (toCache.length && context.transformHoist) {
  20515. context.transformHoist(children, context, node);
  20516. }
  20517. }
  20518. function getConstantType(node, context) {
  20519. const { constantCache } = context;
  20520. switch (node.type) {
  20521. case 1:
  20522. if (node.tagType !== 0) {
  20523. return 0;
  20524. }
  20525. const cached = constantCache.get(node);
  20526. if (cached !== void 0) {
  20527. return cached;
  20528. }
  20529. const codegenNode = node.codegenNode;
  20530. if (codegenNode.type !== 13) {
  20531. return 0;
  20532. }
  20533. if (codegenNode.isBlock && node.tag !== "svg" && node.tag !== "foreignObject" && node.tag !== "math") {
  20534. return 0;
  20535. }
  20536. if (codegenNode.patchFlag === void 0) {
  20537. let returnType2 = 3;
  20538. const generatedPropsType = getGeneratedPropsConstantType(node, context);
  20539. if (generatedPropsType === 0) {
  20540. constantCache.set(node, 0);
  20541. return 0;
  20542. }
  20543. if (generatedPropsType < returnType2) {
  20544. returnType2 = generatedPropsType;
  20545. }
  20546. for (let i = 0; i < node.children.length; i++) {
  20547. const childType = getConstantType(node.children[i], context);
  20548. if (childType === 0) {
  20549. constantCache.set(node, 0);
  20550. return 0;
  20551. }
  20552. if (childType < returnType2) {
  20553. returnType2 = childType;
  20554. }
  20555. }
  20556. if (returnType2 > 1) {
  20557. for (let i = 0; i < node.props.length; i++) {
  20558. const p = node.props[i];
  20559. if (p.type === 7 && p.name === "bind" && p.exp) {
  20560. const expType = getConstantType(p.exp, context);
  20561. if (expType === 0) {
  20562. constantCache.set(node, 0);
  20563. return 0;
  20564. }
  20565. if (expType < returnType2) {
  20566. returnType2 = expType;
  20567. }
  20568. }
  20569. }
  20570. }
  20571. if (codegenNode.isBlock) {
  20572. for (let i = 0; i < node.props.length; i++) {
  20573. const p = node.props[i];
  20574. if (p.type === 7) {
  20575. constantCache.set(node, 0);
  20576. return 0;
  20577. }
  20578. }
  20579. context.removeHelper(OPEN_BLOCK);
  20580. context.removeHelper(
  20581. getVNodeBlockHelper(context.inSSR, codegenNode.isComponent)
  20582. );
  20583. codegenNode.isBlock = false;
  20584. context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
  20585. }
  20586. constantCache.set(node, returnType2);
  20587. return returnType2;
  20588. } else {
  20589. constantCache.set(node, 0);
  20590. return 0;
  20591. }
  20592. case 2:
  20593. case 3:
  20594. return 3;
  20595. case 9:
  20596. case 11:
  20597. case 10:
  20598. return 0;
  20599. case 5:
  20600. case 12:
  20601. return getConstantType(node.content, context);
  20602. case 4:
  20603. return node.constType;
  20604. case 8:
  20605. let returnType = 3;
  20606. for (let i = 0; i < node.children.length; i++) {
  20607. const child = node.children[i];
  20608. if (isString$1(child) || isSymbol$1(child)) {
  20609. continue;
  20610. }
  20611. const childType = getConstantType(child, context);
  20612. if (childType === 0) {
  20613. return 0;
  20614. } else if (childType < returnType) {
  20615. returnType = childType;
  20616. }
  20617. }
  20618. return returnType;
  20619. case 20:
  20620. return 2;
  20621. default:
  20622. return 0;
  20623. }
  20624. }
  20625. const allowHoistedHelperSet = /* @__PURE__ */ new Set([
  20626. NORMALIZE_CLASS,
  20627. NORMALIZE_STYLE,
  20628. NORMALIZE_PROPS,
  20629. GUARD_REACTIVE_PROPS
  20630. ]);
  20631. function getConstantTypeOfHelperCall(value, context) {
  20632. if (value.type === 14 && !isString$1(value.callee) && allowHoistedHelperSet.has(value.callee)) {
  20633. const arg = value.arguments[0];
  20634. if (arg.type === 4) {
  20635. return getConstantType(arg, context);
  20636. } else if (arg.type === 14) {
  20637. return getConstantTypeOfHelperCall(arg, context);
  20638. }
  20639. }
  20640. return 0;
  20641. }
  20642. function getGeneratedPropsConstantType(node, context) {
  20643. let returnType = 3;
  20644. const props = getNodeProps(node);
  20645. if (props && props.type === 15) {
  20646. const { properties } = props;
  20647. for (let i = 0; i < properties.length; i++) {
  20648. const { key, value } = properties[i];
  20649. const keyType = getConstantType(key, context);
  20650. if (keyType === 0) {
  20651. return keyType;
  20652. }
  20653. if (keyType < returnType) {
  20654. returnType = keyType;
  20655. }
  20656. let valueType;
  20657. if (value.type === 4) {
  20658. valueType = getConstantType(value, context);
  20659. } else if (value.type === 14) {
  20660. valueType = getConstantTypeOfHelperCall(value, context);
  20661. } else {
  20662. valueType = 0;
  20663. }
  20664. if (valueType === 0) {
  20665. return valueType;
  20666. }
  20667. if (valueType < returnType) {
  20668. returnType = valueType;
  20669. }
  20670. }
  20671. }
  20672. return returnType;
  20673. }
  20674. function getNodeProps(node) {
  20675. const codegenNode = node.codegenNode;
  20676. if (codegenNode.type === 13) {
  20677. return codegenNode.props;
  20678. }
  20679. }
  20680. function createTransformContext(root, {
  20681. filename = "",
  20682. prefixIdentifiers = false,
  20683. hoistStatic = false,
  20684. hmr = false,
  20685. cacheHandlers = false,
  20686. nodeTransforms = [],
  20687. directiveTransforms = {},
  20688. transformHoist = null,
  20689. isBuiltInComponent = NOOP,
  20690. isCustomElement = NOOP,
  20691. expressionPlugins = [],
  20692. scopeId = null,
  20693. slotted = true,
  20694. ssr = false,
  20695. inSSR = false,
  20696. ssrCssVars = ``,
  20697. bindingMetadata = EMPTY_OBJ,
  20698. inline = false,
  20699. isTS = false,
  20700. onError = defaultOnError,
  20701. onWarn = defaultOnWarn,
  20702. compatConfig
  20703. }) {
  20704. const nameMatch = filename.replace(/\?.*$/, "").match(/([^/\\]+)\.\w+$/);
  20705. const context = {
  20706. // options
  20707. filename,
  20708. selfName: nameMatch && capitalize(camelize(nameMatch[1])),
  20709. prefixIdentifiers,
  20710. hoistStatic,
  20711. hmr,
  20712. cacheHandlers,
  20713. nodeTransforms,
  20714. directiveTransforms,
  20715. transformHoist,
  20716. isBuiltInComponent,
  20717. isCustomElement,
  20718. expressionPlugins,
  20719. scopeId,
  20720. slotted,
  20721. ssr,
  20722. inSSR,
  20723. ssrCssVars,
  20724. bindingMetadata,
  20725. inline,
  20726. isTS,
  20727. onError,
  20728. onWarn,
  20729. compatConfig,
  20730. // state
  20731. root,
  20732. helpers: /* @__PURE__ */ new Map(),
  20733. components: /* @__PURE__ */ new Set(),
  20734. directives: /* @__PURE__ */ new Set(),
  20735. hoists: [],
  20736. imports: [],
  20737. cached: [],
  20738. constantCache: /* @__PURE__ */ new WeakMap(),
  20739. temps: 0,
  20740. identifiers: /* @__PURE__ */ Object.create(null),
  20741. scopes: {
  20742. vFor: 0,
  20743. vSlot: 0,
  20744. vPre: 0,
  20745. vOnce: 0
  20746. },
  20747. parent: null,
  20748. grandParent: null,
  20749. currentNode: root,
  20750. childIndex: 0,
  20751. inVOnce: false,
  20752. // methods
  20753. helper(name) {
  20754. const count = context.helpers.get(name) || 0;
  20755. context.helpers.set(name, count + 1);
  20756. return name;
  20757. },
  20758. removeHelper(name) {
  20759. const count = context.helpers.get(name);
  20760. if (count) {
  20761. const currentCount = count - 1;
  20762. if (!currentCount) {
  20763. context.helpers.delete(name);
  20764. } else {
  20765. context.helpers.set(name, currentCount);
  20766. }
  20767. }
  20768. },
  20769. helperString(name) {
  20770. return `_${helperNameMap[context.helper(name)]}`;
  20771. },
  20772. replaceNode(node) {
  20773. {
  20774. if (!context.currentNode) {
  20775. throw new Error(`Node being replaced is already removed.`);
  20776. }
  20777. if (!context.parent) {
  20778. throw new Error(`Cannot replace root node.`);
  20779. }
  20780. }
  20781. context.parent.children[context.childIndex] = context.currentNode = node;
  20782. },
  20783. removeNode(node) {
  20784. if (!context.parent) {
  20785. throw new Error(`Cannot remove root node.`);
  20786. }
  20787. const list = context.parent.children;
  20788. const removalIndex = node ? list.indexOf(node) : context.currentNode ? context.childIndex : -1;
  20789. if (removalIndex < 0) {
  20790. throw new Error(`node being removed is not a child of current parent`);
  20791. }
  20792. if (!node || node === context.currentNode) {
  20793. context.currentNode = null;
  20794. context.onNodeRemoved();
  20795. } else {
  20796. if (context.childIndex > removalIndex) {
  20797. context.childIndex--;
  20798. context.onNodeRemoved();
  20799. }
  20800. }
  20801. context.parent.children.splice(removalIndex, 1);
  20802. },
  20803. onNodeRemoved: NOOP,
  20804. addIdentifiers(exp) {
  20805. {
  20806. if (isString$1(exp)) {
  20807. addId(exp);
  20808. } else if (exp.identifiers) {
  20809. exp.identifiers.forEach(addId);
  20810. } else if (exp.type === 4) {
  20811. addId(exp.content);
  20812. }
  20813. }
  20814. },
  20815. removeIdentifiers(exp) {
  20816. {
  20817. if (isString$1(exp)) {
  20818. removeId(exp);
  20819. } else if (exp.identifiers) {
  20820. exp.identifiers.forEach(removeId);
  20821. } else if (exp.type === 4) {
  20822. removeId(exp.content);
  20823. }
  20824. }
  20825. },
  20826. hoist(exp) {
  20827. if (isString$1(exp)) exp = createSimpleExpression(exp);
  20828. context.hoists.push(exp);
  20829. const identifier = createSimpleExpression(
  20830. `_hoisted_${context.hoists.length}`,
  20831. false,
  20832. exp.loc,
  20833. 2
  20834. );
  20835. identifier.hoisted = exp;
  20836. return identifier;
  20837. },
  20838. cache(exp, isVNode = false, inVOnce = false) {
  20839. const cacheExp = createCacheExpression(
  20840. context.cached.length,
  20841. exp,
  20842. isVNode,
  20843. inVOnce
  20844. );
  20845. context.cached.push(cacheExp);
  20846. return cacheExp;
  20847. }
  20848. };
  20849. function addId(id) {
  20850. const { identifiers } = context;
  20851. if (identifiers[id] === void 0) {
  20852. identifiers[id] = 0;
  20853. }
  20854. identifiers[id]++;
  20855. }
  20856. function removeId(id) {
  20857. context.identifiers[id]--;
  20858. }
  20859. return context;
  20860. }
  20861. function transform(root, options) {
  20862. const context = createTransformContext(root, options);
  20863. traverseNode(root, context);
  20864. if (options.hoistStatic) {
  20865. cacheStatic(root, context);
  20866. }
  20867. if (!options.ssr) {
  20868. createRootCodegen(root, context);
  20869. }
  20870. root.helpers = /* @__PURE__ */ new Set([...context.helpers.keys()]);
  20871. root.components = [...context.components];
  20872. root.directives = [...context.directives];
  20873. root.imports = context.imports;
  20874. root.hoists = context.hoists;
  20875. root.temps = context.temps;
  20876. root.cached = context.cached;
  20877. root.transformed = true;
  20878. }
  20879. function createRootCodegen(root, context) {
  20880. const { helper } = context;
  20881. const { children } = root;
  20882. if (children.length === 1) {
  20883. const singleElementRootChild = getSingleElementRoot(root);
  20884. if (singleElementRootChild && singleElementRootChild.codegenNode) {
  20885. const codegenNode = singleElementRootChild.codegenNode;
  20886. if (codegenNode.type === 13) {
  20887. convertToBlock(codegenNode, context);
  20888. }
  20889. root.codegenNode = codegenNode;
  20890. } else {
  20891. root.codegenNode = children[0];
  20892. }
  20893. } else if (children.length > 1) {
  20894. let patchFlag = 64;
  20895. if (children.filter((c) => c.type !== 3).length === 1) {
  20896. patchFlag |= 2048;
  20897. }
  20898. root.codegenNode = createVNodeCall(
  20899. context,
  20900. helper(FRAGMENT),
  20901. void 0,
  20902. root.children,
  20903. patchFlag,
  20904. void 0,
  20905. void 0,
  20906. true,
  20907. void 0,
  20908. false
  20909. );
  20910. } else ;
  20911. }
  20912. function traverseChildren(parent, context) {
  20913. let i = 0;
  20914. const nodeRemoved = () => {
  20915. i--;
  20916. };
  20917. for (; i < parent.children.length; i++) {
  20918. const child = parent.children[i];
  20919. if (isString$1(child)) continue;
  20920. context.grandParent = context.parent;
  20921. context.parent = parent;
  20922. context.childIndex = i;
  20923. context.onNodeRemoved = nodeRemoved;
  20924. traverseNode(child, context);
  20925. }
  20926. }
  20927. function traverseNode(node, context) {
  20928. context.currentNode = node;
  20929. const { nodeTransforms } = context;
  20930. const exitFns = [];
  20931. for (let i2 = 0; i2 < nodeTransforms.length; i2++) {
  20932. const onExit = nodeTransforms[i2](node, context);
  20933. if (onExit) {
  20934. if (isArray$3(onExit)) {
  20935. exitFns.push(...onExit);
  20936. } else {
  20937. exitFns.push(onExit);
  20938. }
  20939. }
  20940. if (!context.currentNode) {
  20941. return;
  20942. } else {
  20943. node = context.currentNode;
  20944. }
  20945. }
  20946. switch (node.type) {
  20947. case 3:
  20948. if (!context.ssr) {
  20949. context.helper(CREATE_COMMENT);
  20950. }
  20951. break;
  20952. case 5:
  20953. if (!context.ssr) {
  20954. context.helper(TO_DISPLAY_STRING);
  20955. }
  20956. break;
  20957. // for container types, further traverse downwards
  20958. case 9:
  20959. for (let i2 = 0; i2 < node.branches.length; i2++) {
  20960. traverseNode(node.branches[i2], context);
  20961. }
  20962. break;
  20963. case 10:
  20964. case 11:
  20965. case 1:
  20966. case 0:
  20967. traverseChildren(node, context);
  20968. break;
  20969. }
  20970. context.currentNode = node;
  20971. let i = exitFns.length;
  20972. while (i--) {
  20973. exitFns[i]();
  20974. }
  20975. }
  20976. function createStructuralDirectiveTransform(name, fn) {
  20977. const matches = isString$1(name) ? (n) => n === name : (n) => name.test(n);
  20978. return (node, context) => {
  20979. if (node.type === 1) {
  20980. const { props } = node;
  20981. if (node.tagType === 3 && props.some(isVSlot)) {
  20982. return;
  20983. }
  20984. const exitFns = [];
  20985. for (let i = 0; i < props.length; i++) {
  20986. const prop = props[i];
  20987. if (prop.type === 7 && matches(prop.name)) {
  20988. props.splice(i, 1);
  20989. i--;
  20990. const onExit = fn(node, prop, context);
  20991. if (onExit) exitFns.push(onExit);
  20992. }
  20993. }
  20994. return exitFns;
  20995. }
  20996. };
  20997. }
  20998. var sourceMap$1 = {};
  20999. var sourceMapGenerator$1 = {};
  21000. var base64Vlq$1 = {};
  21001. var base64$1 = {};
  21002. /* -*- Mode: js; js-indent-level: 2; -*- */
  21003. var hasRequiredBase64$1;
  21004. function requireBase64$1 () {
  21005. if (hasRequiredBase64$1) return base64$1;
  21006. hasRequiredBase64$1 = 1;
  21007. /*
  21008. * Copyright 2011 Mozilla Foundation and contributors
  21009. * Licensed under the New BSD license. See LICENSE or:
  21010. * http://opensource.org/licenses/BSD-3-Clause
  21011. */
  21012. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  21013. /**
  21014. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  21015. */
  21016. base64$1.encode = function (number) {
  21017. if (0 <= number && number < intToCharMap.length) {
  21018. return intToCharMap[number];
  21019. }
  21020. throw new TypeError("Must be between 0 and 63: " + number);
  21021. };
  21022. /**
  21023. * Decode a single base 64 character code digit to an integer. Returns -1 on
  21024. * failure.
  21025. */
  21026. base64$1.decode = function (charCode) {
  21027. var bigA = 65; // 'A'
  21028. var bigZ = 90; // 'Z'
  21029. var littleA = 97; // 'a'
  21030. var littleZ = 122; // 'z'
  21031. var zero = 48; // '0'
  21032. var nine = 57; // '9'
  21033. var plus = 43; // '+'
  21034. var slash = 47; // '/'
  21035. var littleOffset = 26;
  21036. var numberOffset = 52;
  21037. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  21038. if (bigA <= charCode && charCode <= bigZ) {
  21039. return (charCode - bigA);
  21040. }
  21041. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  21042. if (littleA <= charCode && charCode <= littleZ) {
  21043. return (charCode - littleA + littleOffset);
  21044. }
  21045. // 52 - 61: 0123456789
  21046. if (zero <= charCode && charCode <= nine) {
  21047. return (charCode - zero + numberOffset);
  21048. }
  21049. // 62: +
  21050. if (charCode == plus) {
  21051. return 62;
  21052. }
  21053. // 63: /
  21054. if (charCode == slash) {
  21055. return 63;
  21056. }
  21057. // Invalid base64 digit.
  21058. return -1;
  21059. };
  21060. return base64$1;
  21061. }
  21062. /* -*- Mode: js; js-indent-level: 2; -*- */
  21063. var hasRequiredBase64Vlq$1;
  21064. function requireBase64Vlq$1 () {
  21065. if (hasRequiredBase64Vlq$1) return base64Vlq$1;
  21066. hasRequiredBase64Vlq$1 = 1;
  21067. /*
  21068. * Copyright 2011 Mozilla Foundation and contributors
  21069. * Licensed under the New BSD license. See LICENSE or:
  21070. * http://opensource.org/licenses/BSD-3-Clause
  21071. *
  21072. * Based on the Base 64 VLQ implementation in Closure Compiler:
  21073. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  21074. *
  21075. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  21076. * Redistribution and use in source and binary forms, with or without
  21077. * modification, are permitted provided that the following conditions are
  21078. * met:
  21079. *
  21080. * * Redistributions of source code must retain the above copyright
  21081. * notice, this list of conditions and the following disclaimer.
  21082. * * Redistributions in binary form must reproduce the above
  21083. * copyright notice, this list of conditions and the following
  21084. * disclaimer in the documentation and/or other materials provided
  21085. * with the distribution.
  21086. * * Neither the name of Google Inc. nor the names of its
  21087. * contributors may be used to endorse or promote products derived
  21088. * from this software without specific prior written permission.
  21089. *
  21090. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21091. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21092. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21093. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  21094. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  21095. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  21096. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  21097. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  21098. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  21099. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  21100. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  21101. */
  21102. var base64 = /*@__PURE__*/ requireBase64$1();
  21103. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  21104. // length quantities we use in the source map spec, the first bit is the sign,
  21105. // the next four bits are the actual value, and the 6th bit is the
  21106. // continuation bit. The continuation bit tells us whether there are more
  21107. // digits in this value following this digit.
  21108. //
  21109. // Continuation
  21110. // | Sign
  21111. // | |
  21112. // V V
  21113. // 101011
  21114. var VLQ_BASE_SHIFT = 5;
  21115. // binary: 100000
  21116. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  21117. // binary: 011111
  21118. var VLQ_BASE_MASK = VLQ_BASE - 1;
  21119. // binary: 100000
  21120. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  21121. /**
  21122. * Converts from a two-complement value to a value where the sign bit is
  21123. * placed in the least significant bit. For example, as decimals:
  21124. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  21125. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  21126. */
  21127. function toVLQSigned(aValue) {
  21128. return aValue < 0
  21129. ? ((-aValue) << 1) + 1
  21130. : (aValue << 1) + 0;
  21131. }
  21132. /**
  21133. * Converts to a two-complement value from a value where the sign bit is
  21134. * placed in the least significant bit. For example, as decimals:
  21135. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  21136. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  21137. */
  21138. function fromVLQSigned(aValue) {
  21139. var isNegative = (aValue & 1) === 1;
  21140. var shifted = aValue >> 1;
  21141. return isNegative
  21142. ? -shifted
  21143. : shifted;
  21144. }
  21145. /**
  21146. * Returns the base 64 VLQ encoded value.
  21147. */
  21148. base64Vlq$1.encode = function base64VLQ_encode(aValue) {
  21149. var encoded = "";
  21150. var digit;
  21151. var vlq = toVLQSigned(aValue);
  21152. do {
  21153. digit = vlq & VLQ_BASE_MASK;
  21154. vlq >>>= VLQ_BASE_SHIFT;
  21155. if (vlq > 0) {
  21156. // There are still more digits in this value, so we must make sure the
  21157. // continuation bit is marked.
  21158. digit |= VLQ_CONTINUATION_BIT;
  21159. }
  21160. encoded += base64.encode(digit);
  21161. } while (vlq > 0);
  21162. return encoded;
  21163. };
  21164. /**
  21165. * Decodes the next base 64 VLQ value from the given string and returns the
  21166. * value and the rest of the string via the out parameter.
  21167. */
  21168. base64Vlq$1.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  21169. var strLen = aStr.length;
  21170. var result = 0;
  21171. var shift = 0;
  21172. var continuation, digit;
  21173. do {
  21174. if (aIndex >= strLen) {
  21175. throw new Error("Expected more digits in base 64 VLQ value.");
  21176. }
  21177. digit = base64.decode(aStr.charCodeAt(aIndex++));
  21178. if (digit === -1) {
  21179. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  21180. }
  21181. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  21182. digit &= VLQ_BASE_MASK;
  21183. result = result + (digit << shift);
  21184. shift += VLQ_BASE_SHIFT;
  21185. } while (continuation);
  21186. aOutParam.value = fromVLQSigned(result);
  21187. aOutParam.rest = aIndex;
  21188. };
  21189. return base64Vlq$1;
  21190. }
  21191. var util$2 = {};
  21192. /* -*- Mode: js; js-indent-level: 2; -*- */
  21193. var hasRequiredUtil$2;
  21194. function requireUtil$2 () {
  21195. if (hasRequiredUtil$2) return util$2;
  21196. hasRequiredUtil$2 = 1;
  21197. (function (exports) {
  21198. /*
  21199. * Copyright 2011 Mozilla Foundation and contributors
  21200. * Licensed under the New BSD license. See LICENSE or:
  21201. * http://opensource.org/licenses/BSD-3-Clause
  21202. */
  21203. /**
  21204. * This is a helper function for getting values from parameter/options
  21205. * objects.
  21206. *
  21207. * @param args The object we are extracting values from
  21208. * @param name The name of the property we are getting.
  21209. * @param defaultValue An optional value to return if the property is missing
  21210. * from the object. If this is not specified and the property is missing, an
  21211. * error will be thrown.
  21212. */
  21213. function getArg(aArgs, aName, aDefaultValue) {
  21214. if (aName in aArgs) {
  21215. return aArgs[aName];
  21216. } else if (arguments.length === 3) {
  21217. return aDefaultValue;
  21218. } else {
  21219. throw new Error('"' + aName + '" is a required argument.');
  21220. }
  21221. }
  21222. exports.getArg = getArg;
  21223. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  21224. var dataUrlRegexp = /^data:.+\,.+$/;
  21225. function urlParse(aUrl) {
  21226. var match = aUrl.match(urlRegexp);
  21227. if (!match) {
  21228. return null;
  21229. }
  21230. return {
  21231. scheme: match[1],
  21232. auth: match[2],
  21233. host: match[3],
  21234. port: match[4],
  21235. path: match[5]
  21236. };
  21237. }
  21238. exports.urlParse = urlParse;
  21239. function urlGenerate(aParsedUrl) {
  21240. var url = '';
  21241. if (aParsedUrl.scheme) {
  21242. url += aParsedUrl.scheme + ':';
  21243. }
  21244. url += '//';
  21245. if (aParsedUrl.auth) {
  21246. url += aParsedUrl.auth + '@';
  21247. }
  21248. if (aParsedUrl.host) {
  21249. url += aParsedUrl.host;
  21250. }
  21251. if (aParsedUrl.port) {
  21252. url += ":" + aParsedUrl.port;
  21253. }
  21254. if (aParsedUrl.path) {
  21255. url += aParsedUrl.path;
  21256. }
  21257. return url;
  21258. }
  21259. exports.urlGenerate = urlGenerate;
  21260. var MAX_CACHED_INPUTS = 32;
  21261. /**
  21262. * Takes some function `f(input) -> result` and returns a memoized version of
  21263. * `f`.
  21264. *
  21265. * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The
  21266. * memoization is a dumb-simple, linear least-recently-used cache.
  21267. */
  21268. function lruMemoize(f) {
  21269. var cache = [];
  21270. return function(input) {
  21271. for (var i = 0; i < cache.length; i++) {
  21272. if (cache[i].input === input) {
  21273. var temp = cache[0];
  21274. cache[0] = cache[i];
  21275. cache[i] = temp;
  21276. return cache[0].result;
  21277. }
  21278. }
  21279. var result = f(input);
  21280. cache.unshift({
  21281. input,
  21282. result,
  21283. });
  21284. if (cache.length > MAX_CACHED_INPUTS) {
  21285. cache.pop();
  21286. }
  21287. return result;
  21288. };
  21289. }
  21290. /**
  21291. * Normalizes a path, or the path portion of a URL:
  21292. *
  21293. * - Replaces consecutive slashes with one slash.
  21294. * - Removes unnecessary '.' parts.
  21295. * - Removes unnecessary '<dir>/..' parts.
  21296. *
  21297. * Based on code in the Node.js 'path' core module.
  21298. *
  21299. * @param aPath The path or url to normalize.
  21300. */
  21301. var normalize = lruMemoize(function normalize(aPath) {
  21302. var path = aPath;
  21303. var url = urlParse(aPath);
  21304. if (url) {
  21305. if (!url.path) {
  21306. return aPath;
  21307. }
  21308. path = url.path;
  21309. }
  21310. var isAbsolute = exports.isAbsolute(path);
  21311. // Split the path into parts between `/` characters. This is much faster than
  21312. // using `.split(/\/+/g)`.
  21313. var parts = [];
  21314. var start = 0;
  21315. var i = 0;
  21316. while (true) {
  21317. start = i;
  21318. i = path.indexOf("/", start);
  21319. if (i === -1) {
  21320. parts.push(path.slice(start));
  21321. break;
  21322. } else {
  21323. parts.push(path.slice(start, i));
  21324. while (i < path.length && path[i] === "/") {
  21325. i++;
  21326. }
  21327. }
  21328. }
  21329. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  21330. part = parts[i];
  21331. if (part === '.') {
  21332. parts.splice(i, 1);
  21333. } else if (part === '..') {
  21334. up++;
  21335. } else if (up > 0) {
  21336. if (part === '') {
  21337. // The first part is blank if the path is absolute. Trying to go
  21338. // above the root is a no-op. Therefore we can remove all '..' parts
  21339. // directly after the root.
  21340. parts.splice(i + 1, up);
  21341. up = 0;
  21342. } else {
  21343. parts.splice(i, 2);
  21344. up--;
  21345. }
  21346. }
  21347. }
  21348. path = parts.join('/');
  21349. if (path === '') {
  21350. path = isAbsolute ? '/' : '.';
  21351. }
  21352. if (url) {
  21353. url.path = path;
  21354. return urlGenerate(url);
  21355. }
  21356. return path;
  21357. });
  21358. exports.normalize = normalize;
  21359. /**
  21360. * Joins two paths/URLs.
  21361. *
  21362. * @param aRoot The root path or URL.
  21363. * @param aPath The path or URL to be joined with the root.
  21364. *
  21365. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  21366. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  21367. * first.
  21368. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  21369. * is updated with the result and aRoot is returned. Otherwise the result
  21370. * is returned.
  21371. * - If aPath is absolute, the result is aPath.
  21372. * - Otherwise the two paths are joined with a slash.
  21373. * - Joining for example 'http://' and 'www.example.com' is also supported.
  21374. */
  21375. function join(aRoot, aPath) {
  21376. if (aRoot === "") {
  21377. aRoot = ".";
  21378. }
  21379. if (aPath === "") {
  21380. aPath = ".";
  21381. }
  21382. var aPathUrl = urlParse(aPath);
  21383. var aRootUrl = urlParse(aRoot);
  21384. if (aRootUrl) {
  21385. aRoot = aRootUrl.path || '/';
  21386. }
  21387. // `join(foo, '//www.example.org')`
  21388. if (aPathUrl && !aPathUrl.scheme) {
  21389. if (aRootUrl) {
  21390. aPathUrl.scheme = aRootUrl.scheme;
  21391. }
  21392. return urlGenerate(aPathUrl);
  21393. }
  21394. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  21395. return aPath;
  21396. }
  21397. // `join('http://', 'www.example.com')`
  21398. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  21399. aRootUrl.host = aPath;
  21400. return urlGenerate(aRootUrl);
  21401. }
  21402. var joined = aPath.charAt(0) === '/'
  21403. ? aPath
  21404. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  21405. if (aRootUrl) {
  21406. aRootUrl.path = joined;
  21407. return urlGenerate(aRootUrl);
  21408. }
  21409. return joined;
  21410. }
  21411. exports.join = join;
  21412. exports.isAbsolute = function (aPath) {
  21413. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  21414. };
  21415. /**
  21416. * Make a path relative to a URL or another path.
  21417. *
  21418. * @param aRoot The root path or URL.
  21419. * @param aPath The path or URL to be made relative to aRoot.
  21420. */
  21421. function relative(aRoot, aPath) {
  21422. if (aRoot === "") {
  21423. aRoot = ".";
  21424. }
  21425. aRoot = aRoot.replace(/\/$/, '');
  21426. // It is possible for the path to be above the root. In this case, simply
  21427. // checking whether the root is a prefix of the path won't work. Instead, we
  21428. // need to remove components from the root one by one, until either we find
  21429. // a prefix that fits, or we run out of components to remove.
  21430. var level = 0;
  21431. while (aPath.indexOf(aRoot + '/') !== 0) {
  21432. var index = aRoot.lastIndexOf("/");
  21433. if (index < 0) {
  21434. return aPath;
  21435. }
  21436. // If the only part of the root that is left is the scheme (i.e. http://,
  21437. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  21438. // have exhausted all components, so the path is not relative to the root.
  21439. aRoot = aRoot.slice(0, index);
  21440. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  21441. return aPath;
  21442. }
  21443. ++level;
  21444. }
  21445. // Make sure we add a "../" for each component we removed from the root.
  21446. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  21447. }
  21448. exports.relative = relative;
  21449. var supportsNullProto = (function () {
  21450. var obj = Object.create(null);
  21451. return !('__proto__' in obj);
  21452. }());
  21453. function identity (s) {
  21454. return s;
  21455. }
  21456. /**
  21457. * Because behavior goes wacky when you set `__proto__` on objects, we
  21458. * have to prefix all the strings in our set with an arbitrary character.
  21459. *
  21460. * See https://github.com/mozilla/source-map/pull/31 and
  21461. * https://github.com/mozilla/source-map/issues/30
  21462. *
  21463. * @param String aStr
  21464. */
  21465. function toSetString(aStr) {
  21466. if (isProtoString(aStr)) {
  21467. return '$' + aStr;
  21468. }
  21469. return aStr;
  21470. }
  21471. exports.toSetString = supportsNullProto ? identity : toSetString;
  21472. function fromSetString(aStr) {
  21473. if (isProtoString(aStr)) {
  21474. return aStr.slice(1);
  21475. }
  21476. return aStr;
  21477. }
  21478. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  21479. function isProtoString(s) {
  21480. if (!s) {
  21481. return false;
  21482. }
  21483. var length = s.length;
  21484. if (length < 9 /* "__proto__".length */) {
  21485. return false;
  21486. }
  21487. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  21488. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  21489. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  21490. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  21491. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  21492. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  21493. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  21494. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  21495. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  21496. return false;
  21497. }
  21498. for (var i = length - 10; i >= 0; i--) {
  21499. if (s.charCodeAt(i) !== 36 /* '$' */) {
  21500. return false;
  21501. }
  21502. }
  21503. return true;
  21504. }
  21505. /**
  21506. * Comparator between two mappings where the original positions are compared.
  21507. *
  21508. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  21509. * mappings with the same original source/line/column, but different generated
  21510. * line and column the same. Useful when searching for a mapping with a
  21511. * stubbed out mapping.
  21512. */
  21513. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  21514. var cmp = strcmp(mappingA.source, mappingB.source);
  21515. if (cmp !== 0) {
  21516. return cmp;
  21517. }
  21518. cmp = mappingA.originalLine - mappingB.originalLine;
  21519. if (cmp !== 0) {
  21520. return cmp;
  21521. }
  21522. cmp = mappingA.originalColumn - mappingB.originalColumn;
  21523. if (cmp !== 0 || onlyCompareOriginal) {
  21524. return cmp;
  21525. }
  21526. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  21527. if (cmp !== 0) {
  21528. return cmp;
  21529. }
  21530. cmp = mappingA.generatedLine - mappingB.generatedLine;
  21531. if (cmp !== 0) {
  21532. return cmp;
  21533. }
  21534. return strcmp(mappingA.name, mappingB.name);
  21535. }
  21536. exports.compareByOriginalPositions = compareByOriginalPositions;
  21537. function compareByOriginalPositionsNoSource(mappingA, mappingB, onlyCompareOriginal) {
  21538. var cmp;
  21539. cmp = mappingA.originalLine - mappingB.originalLine;
  21540. if (cmp !== 0) {
  21541. return cmp;
  21542. }
  21543. cmp = mappingA.originalColumn - mappingB.originalColumn;
  21544. if (cmp !== 0 || onlyCompareOriginal) {
  21545. return cmp;
  21546. }
  21547. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  21548. if (cmp !== 0) {
  21549. return cmp;
  21550. }
  21551. cmp = mappingA.generatedLine - mappingB.generatedLine;
  21552. if (cmp !== 0) {
  21553. return cmp;
  21554. }
  21555. return strcmp(mappingA.name, mappingB.name);
  21556. }
  21557. exports.compareByOriginalPositionsNoSource = compareByOriginalPositionsNoSource;
  21558. /**
  21559. * Comparator between two mappings with deflated source and name indices where
  21560. * the generated positions are compared.
  21561. *
  21562. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  21563. * mappings with the same generated line and column, but different
  21564. * source/name/original line and column the same. Useful when searching for a
  21565. * mapping with a stubbed out mapping.
  21566. */
  21567. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  21568. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  21569. if (cmp !== 0) {
  21570. return cmp;
  21571. }
  21572. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  21573. if (cmp !== 0 || onlyCompareGenerated) {
  21574. return cmp;
  21575. }
  21576. cmp = strcmp(mappingA.source, mappingB.source);
  21577. if (cmp !== 0) {
  21578. return cmp;
  21579. }
  21580. cmp = mappingA.originalLine - mappingB.originalLine;
  21581. if (cmp !== 0) {
  21582. return cmp;
  21583. }
  21584. cmp = mappingA.originalColumn - mappingB.originalColumn;
  21585. if (cmp !== 0) {
  21586. return cmp;
  21587. }
  21588. return strcmp(mappingA.name, mappingB.name);
  21589. }
  21590. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  21591. function compareByGeneratedPositionsDeflatedNoLine(mappingA, mappingB, onlyCompareGenerated) {
  21592. var cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  21593. if (cmp !== 0 || onlyCompareGenerated) {
  21594. return cmp;
  21595. }
  21596. cmp = strcmp(mappingA.source, mappingB.source);
  21597. if (cmp !== 0) {
  21598. return cmp;
  21599. }
  21600. cmp = mappingA.originalLine - mappingB.originalLine;
  21601. if (cmp !== 0) {
  21602. return cmp;
  21603. }
  21604. cmp = mappingA.originalColumn - mappingB.originalColumn;
  21605. if (cmp !== 0) {
  21606. return cmp;
  21607. }
  21608. return strcmp(mappingA.name, mappingB.name);
  21609. }
  21610. exports.compareByGeneratedPositionsDeflatedNoLine = compareByGeneratedPositionsDeflatedNoLine;
  21611. function strcmp(aStr1, aStr2) {
  21612. if (aStr1 === aStr2) {
  21613. return 0;
  21614. }
  21615. if (aStr1 === null) {
  21616. return 1; // aStr2 !== null
  21617. }
  21618. if (aStr2 === null) {
  21619. return -1; // aStr1 !== null
  21620. }
  21621. if (aStr1 > aStr2) {
  21622. return 1;
  21623. }
  21624. return -1;
  21625. }
  21626. /**
  21627. * Comparator between two mappings with inflated source and name strings where
  21628. * the generated positions are compared.
  21629. */
  21630. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  21631. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  21632. if (cmp !== 0) {
  21633. return cmp;
  21634. }
  21635. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  21636. if (cmp !== 0) {
  21637. return cmp;
  21638. }
  21639. cmp = strcmp(mappingA.source, mappingB.source);
  21640. if (cmp !== 0) {
  21641. return cmp;
  21642. }
  21643. cmp = mappingA.originalLine - mappingB.originalLine;
  21644. if (cmp !== 0) {
  21645. return cmp;
  21646. }
  21647. cmp = mappingA.originalColumn - mappingB.originalColumn;
  21648. if (cmp !== 0) {
  21649. return cmp;
  21650. }
  21651. return strcmp(mappingA.name, mappingB.name);
  21652. }
  21653. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  21654. /**
  21655. * Strip any JSON XSSI avoidance prefix from the string (as documented
  21656. * in the source maps specification), and then parse the string as
  21657. * JSON.
  21658. */
  21659. function parseSourceMapInput(str) {
  21660. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  21661. }
  21662. exports.parseSourceMapInput = parseSourceMapInput;
  21663. /**
  21664. * Compute the URL of a source given the the source root, the source's
  21665. * URL, and the source map's URL.
  21666. */
  21667. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  21668. sourceURL = sourceURL || '';
  21669. if (sourceRoot) {
  21670. // This follows what Chrome does.
  21671. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  21672. sourceRoot += '/';
  21673. }
  21674. // The spec says:
  21675. // Line 4: An optional source root, useful for relocating source
  21676. // files on a server or removing repeated values in the
  21677. // “sources” entry. This value is prepended to the individual
  21678. // entries in the “source” field.
  21679. sourceURL = sourceRoot + sourceURL;
  21680. }
  21681. // Historically, SourceMapConsumer did not take the sourceMapURL as
  21682. // a parameter. This mode is still somewhat supported, which is why
  21683. // this code block is conditional. However, it's preferable to pass
  21684. // the source map URL to SourceMapConsumer, so that this function
  21685. // can implement the source URL resolution algorithm as outlined in
  21686. // the spec. This block is basically the equivalent of:
  21687. // new URL(sourceURL, sourceMapURL).toString()
  21688. // ... except it avoids using URL, which wasn't available in the
  21689. // older releases of node still supported by this library.
  21690. //
  21691. // The spec says:
  21692. // If the sources are not absolute URLs after prepending of the
  21693. // “sourceRoot”, the sources are resolved relative to the
  21694. // SourceMap (like resolving script src in a html document).
  21695. if (sourceMapURL) {
  21696. var parsed = urlParse(sourceMapURL);
  21697. if (!parsed) {
  21698. throw new Error("sourceMapURL could not be parsed");
  21699. }
  21700. if (parsed.path) {
  21701. // Strip the last path component, but keep the "/".
  21702. var index = parsed.path.lastIndexOf('/');
  21703. if (index >= 0) {
  21704. parsed.path = parsed.path.substring(0, index + 1);
  21705. }
  21706. }
  21707. sourceURL = join(urlGenerate(parsed), sourceURL);
  21708. }
  21709. return normalize(sourceURL);
  21710. }
  21711. exports.computeSourceURL = computeSourceURL;
  21712. } (util$2));
  21713. return util$2;
  21714. }
  21715. var arraySet$1 = {};
  21716. /* -*- Mode: js; js-indent-level: 2; -*- */
  21717. var hasRequiredArraySet$1;
  21718. function requireArraySet$1 () {
  21719. if (hasRequiredArraySet$1) return arraySet$1;
  21720. hasRequiredArraySet$1 = 1;
  21721. /*
  21722. * Copyright 2011 Mozilla Foundation and contributors
  21723. * Licensed under the New BSD license. See LICENSE or:
  21724. * http://opensource.org/licenses/BSD-3-Clause
  21725. */
  21726. var util = /*@__PURE__*/ requireUtil$2();
  21727. var has = Object.prototype.hasOwnProperty;
  21728. var hasNativeMap = typeof Map !== "undefined";
  21729. /**
  21730. * A data structure which is a combination of an array and a set. Adding a new
  21731. * member is O(1), testing for membership is O(1), and finding the index of an
  21732. * element is O(1). Removing elements from the set is not supported. Only
  21733. * strings are supported for membership.
  21734. */
  21735. function ArraySet() {
  21736. this._array = [];
  21737. this._set = hasNativeMap ? new Map() : Object.create(null);
  21738. }
  21739. /**
  21740. * Static method for creating ArraySet instances from an existing array.
  21741. */
  21742. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  21743. var set = new ArraySet();
  21744. for (var i = 0, len = aArray.length; i < len; i++) {
  21745. set.add(aArray[i], aAllowDuplicates);
  21746. }
  21747. return set;
  21748. };
  21749. /**
  21750. * Return how many unique items are in this ArraySet. If duplicates have been
  21751. * added, than those do not count towards the size.
  21752. *
  21753. * @returns Number
  21754. */
  21755. ArraySet.prototype.size = function ArraySet_size() {
  21756. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  21757. };
  21758. /**
  21759. * Add the given string to this set.
  21760. *
  21761. * @param String aStr
  21762. */
  21763. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  21764. var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
  21765. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  21766. var idx = this._array.length;
  21767. if (!isDuplicate || aAllowDuplicates) {
  21768. this._array.push(aStr);
  21769. }
  21770. if (!isDuplicate) {
  21771. if (hasNativeMap) {
  21772. this._set.set(aStr, idx);
  21773. } else {
  21774. this._set[sStr] = idx;
  21775. }
  21776. }
  21777. };
  21778. /**
  21779. * Is the given string a member of this set?
  21780. *
  21781. * @param String aStr
  21782. */
  21783. ArraySet.prototype.has = function ArraySet_has(aStr) {
  21784. if (hasNativeMap) {
  21785. return this._set.has(aStr);
  21786. } else {
  21787. var sStr = util.toSetString(aStr);
  21788. return has.call(this._set, sStr);
  21789. }
  21790. };
  21791. /**
  21792. * What is the index of the given string in the array?
  21793. *
  21794. * @param String aStr
  21795. */
  21796. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  21797. if (hasNativeMap) {
  21798. var idx = this._set.get(aStr);
  21799. if (idx >= 0) {
  21800. return idx;
  21801. }
  21802. } else {
  21803. var sStr = util.toSetString(aStr);
  21804. if (has.call(this._set, sStr)) {
  21805. return this._set[sStr];
  21806. }
  21807. }
  21808. throw new Error('"' + aStr + '" is not in the set.');
  21809. };
  21810. /**
  21811. * What is the element at the given index?
  21812. *
  21813. * @param Number aIdx
  21814. */
  21815. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  21816. if (aIdx >= 0 && aIdx < this._array.length) {
  21817. return this._array[aIdx];
  21818. }
  21819. throw new Error('No element indexed by ' + aIdx);
  21820. };
  21821. /**
  21822. * Returns the array representation of this set (which has the proper indices
  21823. * indicated by indexOf). Note that this is a copy of the internal array used
  21824. * for storing the members so that no one can mess with internal state.
  21825. */
  21826. ArraySet.prototype.toArray = function ArraySet_toArray() {
  21827. return this._array.slice();
  21828. };
  21829. arraySet$1.ArraySet = ArraySet;
  21830. return arraySet$1;
  21831. }
  21832. var mappingList$1 = {};
  21833. /* -*- Mode: js; js-indent-level: 2; -*- */
  21834. var hasRequiredMappingList$1;
  21835. function requireMappingList$1 () {
  21836. if (hasRequiredMappingList$1) return mappingList$1;
  21837. hasRequiredMappingList$1 = 1;
  21838. /*
  21839. * Copyright 2014 Mozilla Foundation and contributors
  21840. * Licensed under the New BSD license. See LICENSE or:
  21841. * http://opensource.org/licenses/BSD-3-Clause
  21842. */
  21843. var util = /*@__PURE__*/ requireUtil$2();
  21844. /**
  21845. * Determine whether mappingB is after mappingA with respect to generated
  21846. * position.
  21847. */
  21848. function generatedPositionAfter(mappingA, mappingB) {
  21849. // Optimized for most common case
  21850. var lineA = mappingA.generatedLine;
  21851. var lineB = mappingB.generatedLine;
  21852. var columnA = mappingA.generatedColumn;
  21853. var columnB = mappingB.generatedColumn;
  21854. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  21855. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  21856. }
  21857. /**
  21858. * A data structure to provide a sorted view of accumulated mappings in a
  21859. * performance conscious manner. It trades a neglibable overhead in general
  21860. * case for a large speedup in case of mappings being added in order.
  21861. */
  21862. function MappingList() {
  21863. this._array = [];
  21864. this._sorted = true;
  21865. // Serves as infimum
  21866. this._last = {generatedLine: -1, generatedColumn: 0};
  21867. }
  21868. /**
  21869. * Iterate through internal items. This method takes the same arguments that
  21870. * `Array.prototype.forEach` takes.
  21871. *
  21872. * NOTE: The order of the mappings is NOT guaranteed.
  21873. */
  21874. MappingList.prototype.unsortedForEach =
  21875. function MappingList_forEach(aCallback, aThisArg) {
  21876. this._array.forEach(aCallback, aThisArg);
  21877. };
  21878. /**
  21879. * Add the given source mapping.
  21880. *
  21881. * @param Object aMapping
  21882. */
  21883. MappingList.prototype.add = function MappingList_add(aMapping) {
  21884. if (generatedPositionAfter(this._last, aMapping)) {
  21885. this._last = aMapping;
  21886. this._array.push(aMapping);
  21887. } else {
  21888. this._sorted = false;
  21889. this._array.push(aMapping);
  21890. }
  21891. };
  21892. /**
  21893. * Returns the flat, sorted array of mappings. The mappings are sorted by
  21894. * generated position.
  21895. *
  21896. * WARNING: This method returns internal data without copying, for
  21897. * performance. The return value must NOT be mutated, and should be treated as
  21898. * an immutable borrow. If you want to take ownership, you must make your own
  21899. * copy.
  21900. */
  21901. MappingList.prototype.toArray = function MappingList_toArray() {
  21902. if (!this._sorted) {
  21903. this._array.sort(util.compareByGeneratedPositionsInflated);
  21904. this._sorted = true;
  21905. }
  21906. return this._array;
  21907. };
  21908. mappingList$1.MappingList = MappingList;
  21909. return mappingList$1;
  21910. }
  21911. /* -*- Mode: js; js-indent-level: 2; -*- */
  21912. var hasRequiredSourceMapGenerator$1;
  21913. function requireSourceMapGenerator$1 () {
  21914. if (hasRequiredSourceMapGenerator$1) return sourceMapGenerator$1;
  21915. hasRequiredSourceMapGenerator$1 = 1;
  21916. /*
  21917. * Copyright 2011 Mozilla Foundation and contributors
  21918. * Licensed under the New BSD license. See LICENSE or:
  21919. * http://opensource.org/licenses/BSD-3-Clause
  21920. */
  21921. var base64VLQ = /*@__PURE__*/ requireBase64Vlq$1();
  21922. var util = /*@__PURE__*/ requireUtil$2();
  21923. var ArraySet = /*@__PURE__*/ requireArraySet$1().ArraySet;
  21924. var MappingList = /*@__PURE__*/ requireMappingList$1().MappingList;
  21925. /**
  21926. * An instance of the SourceMapGenerator represents a source map which is
  21927. * being built incrementally. You may pass an object with the following
  21928. * properties:
  21929. *
  21930. * - file: The filename of the generated source.
  21931. * - sourceRoot: A root for all relative URLs in this source map.
  21932. */
  21933. function SourceMapGenerator(aArgs) {
  21934. if (!aArgs) {
  21935. aArgs = {};
  21936. }
  21937. this._file = util.getArg(aArgs, 'file', null);
  21938. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  21939. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  21940. this._ignoreInvalidMapping = util.getArg(aArgs, 'ignoreInvalidMapping', false);
  21941. this._sources = new ArraySet();
  21942. this._names = new ArraySet();
  21943. this._mappings = new MappingList();
  21944. this._sourcesContents = null;
  21945. }
  21946. SourceMapGenerator.prototype._version = 3;
  21947. /**
  21948. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  21949. *
  21950. * @param aSourceMapConsumer The SourceMap.
  21951. */
  21952. SourceMapGenerator.fromSourceMap =
  21953. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer, generatorOps) {
  21954. var sourceRoot = aSourceMapConsumer.sourceRoot;
  21955. var generator = new SourceMapGenerator(Object.assign(generatorOps || {}, {
  21956. file: aSourceMapConsumer.file,
  21957. sourceRoot: sourceRoot
  21958. }));
  21959. aSourceMapConsumer.eachMapping(function (mapping) {
  21960. var newMapping = {
  21961. generated: {
  21962. line: mapping.generatedLine,
  21963. column: mapping.generatedColumn
  21964. }
  21965. };
  21966. if (mapping.source != null) {
  21967. newMapping.source = mapping.source;
  21968. if (sourceRoot != null) {
  21969. newMapping.source = util.relative(sourceRoot, newMapping.source);
  21970. }
  21971. newMapping.original = {
  21972. line: mapping.originalLine,
  21973. column: mapping.originalColumn
  21974. };
  21975. if (mapping.name != null) {
  21976. newMapping.name = mapping.name;
  21977. }
  21978. }
  21979. generator.addMapping(newMapping);
  21980. });
  21981. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  21982. var sourceRelative = sourceFile;
  21983. if (sourceRoot !== null) {
  21984. sourceRelative = util.relative(sourceRoot, sourceFile);
  21985. }
  21986. if (!generator._sources.has(sourceRelative)) {
  21987. generator._sources.add(sourceRelative);
  21988. }
  21989. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  21990. if (content != null) {
  21991. generator.setSourceContent(sourceFile, content);
  21992. }
  21993. });
  21994. return generator;
  21995. };
  21996. /**
  21997. * Add a single mapping from original source line and column to the generated
  21998. * source's line and column for this source map being created. The mapping
  21999. * object should have the following properties:
  22000. *
  22001. * - generated: An object with the generated line and column positions.
  22002. * - original: An object with the original line and column positions.
  22003. * - source: The original source file (relative to the sourceRoot).
  22004. * - name: An optional original token name for this mapping.
  22005. */
  22006. SourceMapGenerator.prototype.addMapping =
  22007. function SourceMapGenerator_addMapping(aArgs) {
  22008. var generated = util.getArg(aArgs, 'generated');
  22009. var original = util.getArg(aArgs, 'original', null);
  22010. var source = util.getArg(aArgs, 'source', null);
  22011. var name = util.getArg(aArgs, 'name', null);
  22012. if (!this._skipValidation) {
  22013. if (this._validateMapping(generated, original, source, name) === false) {
  22014. return;
  22015. }
  22016. }
  22017. if (source != null) {
  22018. source = String(source);
  22019. if (!this._sources.has(source)) {
  22020. this._sources.add(source);
  22021. }
  22022. }
  22023. if (name != null) {
  22024. name = String(name);
  22025. if (!this._names.has(name)) {
  22026. this._names.add(name);
  22027. }
  22028. }
  22029. this._mappings.add({
  22030. generatedLine: generated.line,
  22031. generatedColumn: generated.column,
  22032. originalLine: original != null && original.line,
  22033. originalColumn: original != null && original.column,
  22034. source: source,
  22035. name: name
  22036. });
  22037. };
  22038. /**
  22039. * Set the source content for a source file.
  22040. */
  22041. SourceMapGenerator.prototype.setSourceContent =
  22042. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  22043. var source = aSourceFile;
  22044. if (this._sourceRoot != null) {
  22045. source = util.relative(this._sourceRoot, source);
  22046. }
  22047. if (aSourceContent != null) {
  22048. // Add the source content to the _sourcesContents map.
  22049. // Create a new _sourcesContents map if the property is null.
  22050. if (!this._sourcesContents) {
  22051. this._sourcesContents = Object.create(null);
  22052. }
  22053. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  22054. } else if (this._sourcesContents) {
  22055. // Remove the source file from the _sourcesContents map.
  22056. // If the _sourcesContents map is empty, set the property to null.
  22057. delete this._sourcesContents[util.toSetString(source)];
  22058. if (Object.keys(this._sourcesContents).length === 0) {
  22059. this._sourcesContents = null;
  22060. }
  22061. }
  22062. };
  22063. /**
  22064. * Applies the mappings of a sub-source-map for a specific source file to the
  22065. * source map being generated. Each mapping to the supplied source file is
  22066. * rewritten using the supplied source map. Note: The resolution for the
  22067. * resulting mappings is the minimium of this map and the supplied map.
  22068. *
  22069. * @param aSourceMapConsumer The source map to be applied.
  22070. * @param aSourceFile Optional. The filename of the source file.
  22071. * If omitted, SourceMapConsumer's file property will be used.
  22072. * @param aSourceMapPath Optional. The dirname of the path to the source map
  22073. * to be applied. If relative, it is relative to the SourceMapConsumer.
  22074. * This parameter is needed when the two source maps aren't in the same
  22075. * directory, and the source map to be applied contains relative source
  22076. * paths. If so, those relative source paths need to be rewritten
  22077. * relative to the SourceMapGenerator.
  22078. */
  22079. SourceMapGenerator.prototype.applySourceMap =
  22080. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  22081. var sourceFile = aSourceFile;
  22082. // If aSourceFile is omitted, we will use the file property of the SourceMap
  22083. if (aSourceFile == null) {
  22084. if (aSourceMapConsumer.file == null) {
  22085. throw new Error(
  22086. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  22087. 'or the source map\'s "file" property. Both were omitted.'
  22088. );
  22089. }
  22090. sourceFile = aSourceMapConsumer.file;
  22091. }
  22092. var sourceRoot = this._sourceRoot;
  22093. // Make "sourceFile" relative if an absolute Url is passed.
  22094. if (sourceRoot != null) {
  22095. sourceFile = util.relative(sourceRoot, sourceFile);
  22096. }
  22097. // Applying the SourceMap can add and remove items from the sources and
  22098. // the names array.
  22099. var newSources = new ArraySet();
  22100. var newNames = new ArraySet();
  22101. // Find mappings for the "sourceFile"
  22102. this._mappings.unsortedForEach(function (mapping) {
  22103. if (mapping.source === sourceFile && mapping.originalLine != null) {
  22104. // Check if it can be mapped by the source map, then update the mapping.
  22105. var original = aSourceMapConsumer.originalPositionFor({
  22106. line: mapping.originalLine,
  22107. column: mapping.originalColumn
  22108. });
  22109. if (original.source != null) {
  22110. // Copy mapping
  22111. mapping.source = original.source;
  22112. if (aSourceMapPath != null) {
  22113. mapping.source = util.join(aSourceMapPath, mapping.source);
  22114. }
  22115. if (sourceRoot != null) {
  22116. mapping.source = util.relative(sourceRoot, mapping.source);
  22117. }
  22118. mapping.originalLine = original.line;
  22119. mapping.originalColumn = original.column;
  22120. if (original.name != null) {
  22121. mapping.name = original.name;
  22122. }
  22123. }
  22124. }
  22125. var source = mapping.source;
  22126. if (source != null && !newSources.has(source)) {
  22127. newSources.add(source);
  22128. }
  22129. var name = mapping.name;
  22130. if (name != null && !newNames.has(name)) {
  22131. newNames.add(name);
  22132. }
  22133. }, this);
  22134. this._sources = newSources;
  22135. this._names = newNames;
  22136. // Copy sourcesContents of applied map.
  22137. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  22138. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  22139. if (content != null) {
  22140. if (aSourceMapPath != null) {
  22141. sourceFile = util.join(aSourceMapPath, sourceFile);
  22142. }
  22143. if (sourceRoot != null) {
  22144. sourceFile = util.relative(sourceRoot, sourceFile);
  22145. }
  22146. this.setSourceContent(sourceFile, content);
  22147. }
  22148. }, this);
  22149. };
  22150. /**
  22151. * A mapping can have one of the three levels of data:
  22152. *
  22153. * 1. Just the generated position.
  22154. * 2. The Generated position, original position, and original source.
  22155. * 3. Generated and original position, original source, as well as a name
  22156. * token.
  22157. *
  22158. * To maintain consistency, we validate that any new mapping being added falls
  22159. * in to one of these categories.
  22160. */
  22161. SourceMapGenerator.prototype._validateMapping =
  22162. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  22163. aName) {
  22164. // When aOriginal is truthy but has empty values for .line and .column,
  22165. // it is most likely a programmer error. In this case we throw a very
  22166. // specific error message to try to guide them the right way.
  22167. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  22168. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  22169. var message = 'original.line and original.column are not numbers -- you probably meant to omit ' +
  22170. 'the original mapping entirely and only map the generated position. If so, pass ' +
  22171. 'null for the original mapping instead of an object with empty or null values.';
  22172. if (this._ignoreInvalidMapping) {
  22173. if (typeof console !== 'undefined' && console.warn) {
  22174. console.warn(message);
  22175. }
  22176. return false;
  22177. } else {
  22178. throw new Error(message);
  22179. }
  22180. }
  22181. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  22182. && aGenerated.line > 0 && aGenerated.column >= 0
  22183. && !aOriginal && !aSource && !aName) {
  22184. // Case 1.
  22185. return;
  22186. }
  22187. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  22188. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  22189. && aGenerated.line > 0 && aGenerated.column >= 0
  22190. && aOriginal.line > 0 && aOriginal.column >= 0
  22191. && aSource) {
  22192. // Cases 2 and 3.
  22193. return;
  22194. }
  22195. else {
  22196. var message = 'Invalid mapping: ' + JSON.stringify({
  22197. generated: aGenerated,
  22198. source: aSource,
  22199. original: aOriginal,
  22200. name: aName
  22201. });
  22202. if (this._ignoreInvalidMapping) {
  22203. if (typeof console !== 'undefined' && console.warn) {
  22204. console.warn(message);
  22205. }
  22206. return false;
  22207. } else {
  22208. throw new Error(message)
  22209. }
  22210. }
  22211. };
  22212. /**
  22213. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  22214. * specified by the source map format.
  22215. */
  22216. SourceMapGenerator.prototype._serializeMappings =
  22217. function SourceMapGenerator_serializeMappings() {
  22218. var previousGeneratedColumn = 0;
  22219. var previousGeneratedLine = 1;
  22220. var previousOriginalColumn = 0;
  22221. var previousOriginalLine = 0;
  22222. var previousName = 0;
  22223. var previousSource = 0;
  22224. var result = '';
  22225. var next;
  22226. var mapping;
  22227. var nameIdx;
  22228. var sourceIdx;
  22229. var mappings = this._mappings.toArray();
  22230. for (var i = 0, len = mappings.length; i < len; i++) {
  22231. mapping = mappings[i];
  22232. next = '';
  22233. if (mapping.generatedLine !== previousGeneratedLine) {
  22234. previousGeneratedColumn = 0;
  22235. while (mapping.generatedLine !== previousGeneratedLine) {
  22236. next += ';';
  22237. previousGeneratedLine++;
  22238. }
  22239. }
  22240. else {
  22241. if (i > 0) {
  22242. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  22243. continue;
  22244. }
  22245. next += ',';
  22246. }
  22247. }
  22248. next += base64VLQ.encode(mapping.generatedColumn
  22249. - previousGeneratedColumn);
  22250. previousGeneratedColumn = mapping.generatedColumn;
  22251. if (mapping.source != null) {
  22252. sourceIdx = this._sources.indexOf(mapping.source);
  22253. next += base64VLQ.encode(sourceIdx - previousSource);
  22254. previousSource = sourceIdx;
  22255. // lines are stored 0-based in SourceMap spec version 3
  22256. next += base64VLQ.encode(mapping.originalLine - 1
  22257. - previousOriginalLine);
  22258. previousOriginalLine = mapping.originalLine - 1;
  22259. next += base64VLQ.encode(mapping.originalColumn
  22260. - previousOriginalColumn);
  22261. previousOriginalColumn = mapping.originalColumn;
  22262. if (mapping.name != null) {
  22263. nameIdx = this._names.indexOf(mapping.name);
  22264. next += base64VLQ.encode(nameIdx - previousName);
  22265. previousName = nameIdx;
  22266. }
  22267. }
  22268. result += next;
  22269. }
  22270. return result;
  22271. };
  22272. SourceMapGenerator.prototype._generateSourcesContent =
  22273. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  22274. return aSources.map(function (source) {
  22275. if (!this._sourcesContents) {
  22276. return null;
  22277. }
  22278. if (aSourceRoot != null) {
  22279. source = util.relative(aSourceRoot, source);
  22280. }
  22281. var key = util.toSetString(source);
  22282. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  22283. ? this._sourcesContents[key]
  22284. : null;
  22285. }, this);
  22286. };
  22287. /**
  22288. * Externalize the source map.
  22289. */
  22290. SourceMapGenerator.prototype.toJSON =
  22291. function SourceMapGenerator_toJSON() {
  22292. var map = {
  22293. version: this._version,
  22294. sources: this._sources.toArray(),
  22295. names: this._names.toArray(),
  22296. mappings: this._serializeMappings()
  22297. };
  22298. if (this._file != null) {
  22299. map.file = this._file;
  22300. }
  22301. if (this._sourceRoot != null) {
  22302. map.sourceRoot = this._sourceRoot;
  22303. }
  22304. if (this._sourcesContents) {
  22305. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  22306. }
  22307. return map;
  22308. };
  22309. /**
  22310. * Render the source map being generated to a string.
  22311. */
  22312. SourceMapGenerator.prototype.toString =
  22313. function SourceMapGenerator_toString() {
  22314. return JSON.stringify(this.toJSON());
  22315. };
  22316. sourceMapGenerator$1.SourceMapGenerator = SourceMapGenerator;
  22317. return sourceMapGenerator$1;
  22318. }
  22319. var sourceMapConsumer$1 = {};
  22320. var binarySearch$1 = {};
  22321. /* -*- Mode: js; js-indent-level: 2; -*- */
  22322. var hasRequiredBinarySearch$1;
  22323. function requireBinarySearch$1 () {
  22324. if (hasRequiredBinarySearch$1) return binarySearch$1;
  22325. hasRequiredBinarySearch$1 = 1;
  22326. (function (exports) {
  22327. /*
  22328. * Copyright 2011 Mozilla Foundation and contributors
  22329. * Licensed under the New BSD license. See LICENSE or:
  22330. * http://opensource.org/licenses/BSD-3-Clause
  22331. */
  22332. exports.GREATEST_LOWER_BOUND = 1;
  22333. exports.LEAST_UPPER_BOUND = 2;
  22334. /**
  22335. * Recursive implementation of binary search.
  22336. *
  22337. * @param aLow Indices here and lower do not contain the needle.
  22338. * @param aHigh Indices here and higher do not contain the needle.
  22339. * @param aNeedle The element being searched for.
  22340. * @param aHaystack The non-empty array being searched.
  22341. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  22342. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  22343. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  22344. * closest element that is smaller than or greater than the one we are
  22345. * searching for, respectively, if the exact element cannot be found.
  22346. */
  22347. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  22348. // This function terminates when one of the following is true:
  22349. //
  22350. // 1. We find the exact element we are looking for.
  22351. //
  22352. // 2. We did not find the exact element, but we can return the index of
  22353. // the next-closest element.
  22354. //
  22355. // 3. We did not find the exact element, and there is no next-closest
  22356. // element than the one we are searching for, so we return -1.
  22357. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  22358. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  22359. if (cmp === 0) {
  22360. // Found the element we are looking for.
  22361. return mid;
  22362. }
  22363. else if (cmp > 0) {
  22364. // Our needle is greater than aHaystack[mid].
  22365. if (aHigh - mid > 1) {
  22366. // The element is in the upper half.
  22367. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  22368. }
  22369. // The exact needle element was not found in this haystack. Determine if
  22370. // we are in termination case (3) or (2) and return the appropriate thing.
  22371. if (aBias == exports.LEAST_UPPER_BOUND) {
  22372. return aHigh < aHaystack.length ? aHigh : -1;
  22373. } else {
  22374. return mid;
  22375. }
  22376. }
  22377. else {
  22378. // Our needle is less than aHaystack[mid].
  22379. if (mid - aLow > 1) {
  22380. // The element is in the lower half.
  22381. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  22382. }
  22383. // we are in termination case (3) or (2) and return the appropriate thing.
  22384. if (aBias == exports.LEAST_UPPER_BOUND) {
  22385. return mid;
  22386. } else {
  22387. return aLow < 0 ? -1 : aLow;
  22388. }
  22389. }
  22390. }
  22391. /**
  22392. * This is an implementation of binary search which will always try and return
  22393. * the index of the closest element if there is no exact hit. This is because
  22394. * mappings between original and generated line/col pairs are single points,
  22395. * and there is an implicit region between each of them, so a miss just means
  22396. * that you aren't on the very start of a region.
  22397. *
  22398. * @param aNeedle The element you are looking for.
  22399. * @param aHaystack The array that is being searched.
  22400. * @param aCompare A function which takes the needle and an element in the
  22401. * array and returns -1, 0, or 1 depending on whether the needle is less
  22402. * than, equal to, or greater than the element, respectively.
  22403. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  22404. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  22405. * closest element that is smaller than or greater than the one we are
  22406. * searching for, respectively, if the exact element cannot be found.
  22407. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  22408. */
  22409. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  22410. if (aHaystack.length === 0) {
  22411. return -1;
  22412. }
  22413. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  22414. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  22415. if (index < 0) {
  22416. return -1;
  22417. }
  22418. // We have found either the exact element, or the next-closest element than
  22419. // the one we are searching for. However, there may be more than one such
  22420. // element. Make sure we always return the smallest of these.
  22421. while (index - 1 >= 0) {
  22422. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  22423. break;
  22424. }
  22425. --index;
  22426. }
  22427. return index;
  22428. };
  22429. } (binarySearch$1));
  22430. return binarySearch$1;
  22431. }
  22432. var quickSort$1 = {};
  22433. /* -*- Mode: js; js-indent-level: 2; -*- */
  22434. var hasRequiredQuickSort$1;
  22435. function requireQuickSort$1 () {
  22436. if (hasRequiredQuickSort$1) return quickSort$1;
  22437. hasRequiredQuickSort$1 = 1;
  22438. /*
  22439. * Copyright 2011 Mozilla Foundation and contributors
  22440. * Licensed under the New BSD license. See LICENSE or:
  22441. * http://opensource.org/licenses/BSD-3-Clause
  22442. */
  22443. // It turns out that some (most?) JavaScript engines don't self-host
  22444. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  22445. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  22446. // custom comparator function, calling back and forth between the VM's C++ and
  22447. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  22448. // worse generated code for the comparator function than would be optimal. In
  22449. // fact, when sorting with a comparator, these costs outweigh the benefits of
  22450. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  22451. // a ~3500ms mean speed-up in `bench/bench.html`.
  22452. function SortTemplate(comparator) {
  22453. /**
  22454. * Swap the elements indexed by `x` and `y` in the array `ary`.
  22455. *
  22456. * @param {Array} ary
  22457. * The array.
  22458. * @param {Number} x
  22459. * The index of the first item.
  22460. * @param {Number} y
  22461. * The index of the second item.
  22462. */
  22463. function swap(ary, x, y) {
  22464. var temp = ary[x];
  22465. ary[x] = ary[y];
  22466. ary[y] = temp;
  22467. }
  22468. /**
  22469. * Returns a random integer within the range `low .. high` inclusive.
  22470. *
  22471. * @param {Number} low
  22472. * The lower bound on the range.
  22473. * @param {Number} high
  22474. * The upper bound on the range.
  22475. */
  22476. function randomIntInRange(low, high) {
  22477. return Math.round(low + (Math.random() * (high - low)));
  22478. }
  22479. /**
  22480. * The Quick Sort algorithm.
  22481. *
  22482. * @param {Array} ary
  22483. * An array to sort.
  22484. * @param {function} comparator
  22485. * Function to use to compare two items.
  22486. * @param {Number} p
  22487. * Start index of the array
  22488. * @param {Number} r
  22489. * End index of the array
  22490. */
  22491. function doQuickSort(ary, comparator, p, r) {
  22492. // If our lower bound is less than our upper bound, we (1) partition the
  22493. // array into two pieces and (2) recurse on each half. If it is not, this is
  22494. // the empty array and our base case.
  22495. if (p < r) {
  22496. // (1) Partitioning.
  22497. //
  22498. // The partitioning chooses a pivot between `p` and `r` and moves all
  22499. // elements that are less than or equal to the pivot to the before it, and
  22500. // all the elements that are greater than it after it. The effect is that
  22501. // once partition is done, the pivot is in the exact place it will be when
  22502. // the array is put in sorted order, and it will not need to be moved
  22503. // again. This runs in O(n) time.
  22504. // Always choose a random pivot so that an input array which is reverse
  22505. // sorted does not cause O(n^2) running time.
  22506. var pivotIndex = randomIntInRange(p, r);
  22507. var i = p - 1;
  22508. swap(ary, pivotIndex, r);
  22509. var pivot = ary[r];
  22510. // Immediately after `j` is incremented in this loop, the following hold
  22511. // true:
  22512. //
  22513. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  22514. //
  22515. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  22516. for (var j = p; j < r; j++) {
  22517. if (comparator(ary[j], pivot, false) <= 0) {
  22518. i += 1;
  22519. swap(ary, i, j);
  22520. }
  22521. }
  22522. swap(ary, i + 1, j);
  22523. var q = i + 1;
  22524. // (2) Recurse on each half.
  22525. doQuickSort(ary, comparator, p, q - 1);
  22526. doQuickSort(ary, comparator, q + 1, r);
  22527. }
  22528. }
  22529. return doQuickSort;
  22530. }
  22531. function cloneSort(comparator) {
  22532. let template = SortTemplate.toString();
  22533. let templateFn = new Function(`return ${template}`)();
  22534. return templateFn(comparator);
  22535. }
  22536. /**
  22537. * Sort the given array in-place with the given comparator function.
  22538. *
  22539. * @param {Array} ary
  22540. * An array to sort.
  22541. * @param {function} comparator
  22542. * Function to use to compare two items.
  22543. */
  22544. let sortCache = new WeakMap();
  22545. quickSort$1.quickSort = function (ary, comparator, start = 0) {
  22546. let doQuickSort = sortCache.get(comparator);
  22547. if (doQuickSort === void 0) {
  22548. doQuickSort = cloneSort(comparator);
  22549. sortCache.set(comparator, doQuickSort);
  22550. }
  22551. doQuickSort(ary, comparator, start, ary.length - 1);
  22552. };
  22553. return quickSort$1;
  22554. }
  22555. /* -*- Mode: js; js-indent-level: 2; -*- */
  22556. var hasRequiredSourceMapConsumer$1;
  22557. function requireSourceMapConsumer$1 () {
  22558. if (hasRequiredSourceMapConsumer$1) return sourceMapConsumer$1;
  22559. hasRequiredSourceMapConsumer$1 = 1;
  22560. /*
  22561. * Copyright 2011 Mozilla Foundation and contributors
  22562. * Licensed under the New BSD license. See LICENSE or:
  22563. * http://opensource.org/licenses/BSD-3-Clause
  22564. */
  22565. var util = /*@__PURE__*/ requireUtil$2();
  22566. var binarySearch = /*@__PURE__*/ requireBinarySearch$1();
  22567. var ArraySet = /*@__PURE__*/ requireArraySet$1().ArraySet;
  22568. var base64VLQ = /*@__PURE__*/ requireBase64Vlq$1();
  22569. var quickSort = /*@__PURE__*/ requireQuickSort$1().quickSort;
  22570. function SourceMapConsumer(aSourceMap, aSourceMapURL) {
  22571. var sourceMap = aSourceMap;
  22572. if (typeof aSourceMap === 'string') {
  22573. sourceMap = util.parseSourceMapInput(aSourceMap);
  22574. }
  22575. return sourceMap.sections != null
  22576. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  22577. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  22578. }
  22579. SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  22580. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  22581. };
  22582. /**
  22583. * The version of the source mapping spec that we are consuming.
  22584. */
  22585. SourceMapConsumer.prototype._version = 3;
  22586. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  22587. // parsed mapping coordinates from the source map's "mappings" attribute. They
  22588. // are lazily instantiated, accessed via the `_generatedMappings` and
  22589. // `_originalMappings` getters respectively, and we only parse the mappings
  22590. // and create these arrays once queried for a source location. We jump through
  22591. // these hoops because there can be many thousands of mappings, and parsing
  22592. // them is expensive, so we only want to do it if we must.
  22593. //
  22594. // Each object in the arrays is of the form:
  22595. //
  22596. // {
  22597. // generatedLine: The line number in the generated code,
  22598. // generatedColumn: The column number in the generated code,
  22599. // source: The path to the original source file that generated this
  22600. // chunk of code,
  22601. // originalLine: The line number in the original source that
  22602. // corresponds to this chunk of generated code,
  22603. // originalColumn: The column number in the original source that
  22604. // corresponds to this chunk of generated code,
  22605. // name: The name of the original symbol which generated this chunk of
  22606. // code.
  22607. // }
  22608. //
  22609. // All properties except for `generatedLine` and `generatedColumn` can be
  22610. // `null`.
  22611. //
  22612. // `_generatedMappings` is ordered by the generated positions.
  22613. //
  22614. // `_originalMappings` is ordered by the original positions.
  22615. SourceMapConsumer.prototype.__generatedMappings = null;
  22616. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  22617. configurable: true,
  22618. enumerable: true,
  22619. get: function () {
  22620. if (!this.__generatedMappings) {
  22621. this._parseMappings(this._mappings, this.sourceRoot);
  22622. }
  22623. return this.__generatedMappings;
  22624. }
  22625. });
  22626. SourceMapConsumer.prototype.__originalMappings = null;
  22627. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  22628. configurable: true,
  22629. enumerable: true,
  22630. get: function () {
  22631. if (!this.__originalMappings) {
  22632. this._parseMappings(this._mappings, this.sourceRoot);
  22633. }
  22634. return this.__originalMappings;
  22635. }
  22636. });
  22637. SourceMapConsumer.prototype._charIsMappingSeparator =
  22638. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  22639. var c = aStr.charAt(index);
  22640. return c === ";" || c === ",";
  22641. };
  22642. /**
  22643. * Parse the mappings in a string in to a data structure which we can easily
  22644. * query (the ordered arrays in the `this.__generatedMappings` and
  22645. * `this.__originalMappings` properties).
  22646. */
  22647. SourceMapConsumer.prototype._parseMappings =
  22648. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  22649. throw new Error("Subclasses must implement _parseMappings");
  22650. };
  22651. SourceMapConsumer.GENERATED_ORDER = 1;
  22652. SourceMapConsumer.ORIGINAL_ORDER = 2;
  22653. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  22654. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  22655. /**
  22656. * Iterate over each mapping between an original source/line/column and a
  22657. * generated line/column in this source map.
  22658. *
  22659. * @param Function aCallback
  22660. * The function that is called with each mapping.
  22661. * @param Object aContext
  22662. * Optional. If specified, this object will be the value of `this` every
  22663. * time that `aCallback` is called.
  22664. * @param aOrder
  22665. * Either `SourceMapConsumer.GENERATED_ORDER` or
  22666. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  22667. * iterate over the mappings sorted by the generated file's line/column
  22668. * order or the original's source/line/column order, respectively. Defaults to
  22669. * `SourceMapConsumer.GENERATED_ORDER`.
  22670. */
  22671. SourceMapConsumer.prototype.eachMapping =
  22672. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  22673. var context = aContext || null;
  22674. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  22675. var mappings;
  22676. switch (order) {
  22677. case SourceMapConsumer.GENERATED_ORDER:
  22678. mappings = this._generatedMappings;
  22679. break;
  22680. case SourceMapConsumer.ORIGINAL_ORDER:
  22681. mappings = this._originalMappings;
  22682. break;
  22683. default:
  22684. throw new Error("Unknown order of iteration.");
  22685. }
  22686. var sourceRoot = this.sourceRoot;
  22687. var boundCallback = aCallback.bind(context);
  22688. var names = this._names;
  22689. var sources = this._sources;
  22690. var sourceMapURL = this._sourceMapURL;
  22691. for (var i = 0, n = mappings.length; i < n; i++) {
  22692. var mapping = mappings[i];
  22693. var source = mapping.source === null ? null : sources.at(mapping.source);
  22694. if(source !== null) {
  22695. source = util.computeSourceURL(sourceRoot, source, sourceMapURL);
  22696. }
  22697. boundCallback({
  22698. source: source,
  22699. generatedLine: mapping.generatedLine,
  22700. generatedColumn: mapping.generatedColumn,
  22701. originalLine: mapping.originalLine,
  22702. originalColumn: mapping.originalColumn,
  22703. name: mapping.name === null ? null : names.at(mapping.name)
  22704. });
  22705. }
  22706. };
  22707. /**
  22708. * Returns all generated line and column information for the original source,
  22709. * line, and column provided. If no column is provided, returns all mappings
  22710. * corresponding to a either the line we are searching for or the next
  22711. * closest line that has any mappings. Otherwise, returns all mappings
  22712. * corresponding to the given line and either the column we are searching for
  22713. * or the next closest column that has any offsets.
  22714. *
  22715. * The only argument is an object with the following properties:
  22716. *
  22717. * - source: The filename of the original source.
  22718. * - line: The line number in the original source. The line number is 1-based.
  22719. * - column: Optional. the column number in the original source.
  22720. * The column number is 0-based.
  22721. *
  22722. * and an array of objects is returned, each with the following properties:
  22723. *
  22724. * - line: The line number in the generated source, or null. The
  22725. * line number is 1-based.
  22726. * - column: The column number in the generated source, or null.
  22727. * The column number is 0-based.
  22728. */
  22729. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  22730. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  22731. var line = util.getArg(aArgs, 'line');
  22732. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  22733. // returns the index of the closest mapping less than the needle. By
  22734. // setting needle.originalColumn to 0, we thus find the last mapping for
  22735. // the given line, provided such a mapping exists.
  22736. var needle = {
  22737. source: util.getArg(aArgs, 'source'),
  22738. originalLine: line,
  22739. originalColumn: util.getArg(aArgs, 'column', 0)
  22740. };
  22741. needle.source = this._findSourceIndex(needle.source);
  22742. if (needle.source < 0) {
  22743. return [];
  22744. }
  22745. var mappings = [];
  22746. var index = this._findMapping(needle,
  22747. this._originalMappings,
  22748. "originalLine",
  22749. "originalColumn",
  22750. util.compareByOriginalPositions,
  22751. binarySearch.LEAST_UPPER_BOUND);
  22752. if (index >= 0) {
  22753. var mapping = this._originalMappings[index];
  22754. if (aArgs.column === undefined) {
  22755. var originalLine = mapping.originalLine;
  22756. // Iterate until either we run out of mappings, or we run into
  22757. // a mapping for a different line than the one we found. Since
  22758. // mappings are sorted, this is guaranteed to find all mappings for
  22759. // the line we found.
  22760. while (mapping && mapping.originalLine === originalLine) {
  22761. mappings.push({
  22762. line: util.getArg(mapping, 'generatedLine', null),
  22763. column: util.getArg(mapping, 'generatedColumn', null),
  22764. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  22765. });
  22766. mapping = this._originalMappings[++index];
  22767. }
  22768. } else {
  22769. var originalColumn = mapping.originalColumn;
  22770. // Iterate until either we run out of mappings, or we run into
  22771. // a mapping for a different line than the one we were searching for.
  22772. // Since mappings are sorted, this is guaranteed to find all mappings for
  22773. // the line we are searching for.
  22774. while (mapping &&
  22775. mapping.originalLine === line &&
  22776. mapping.originalColumn == originalColumn) {
  22777. mappings.push({
  22778. line: util.getArg(mapping, 'generatedLine', null),
  22779. column: util.getArg(mapping, 'generatedColumn', null),
  22780. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  22781. });
  22782. mapping = this._originalMappings[++index];
  22783. }
  22784. }
  22785. }
  22786. return mappings;
  22787. };
  22788. sourceMapConsumer$1.SourceMapConsumer = SourceMapConsumer;
  22789. /**
  22790. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  22791. * query for information about the original file positions by giving it a file
  22792. * position in the generated source.
  22793. *
  22794. * The first parameter is the raw source map (either as a JSON string, or
  22795. * already parsed to an object). According to the spec, source maps have the
  22796. * following attributes:
  22797. *
  22798. * - version: Which version of the source map spec this map is following.
  22799. * - sources: An array of URLs to the original source files.
  22800. * - names: An array of identifiers which can be referrenced by individual mappings.
  22801. * - sourceRoot: Optional. The URL root from which all sources are relative.
  22802. * - sourcesContent: Optional. An array of contents of the original source files.
  22803. * - mappings: A string of base64 VLQs which contain the actual mappings.
  22804. * - file: Optional. The generated file this source map is associated with.
  22805. *
  22806. * Here is an example source map, taken from the source map spec[0]:
  22807. *
  22808. * {
  22809. * version : 3,
  22810. * file: "out.js",
  22811. * sourceRoot : "",
  22812. * sources: ["foo.js", "bar.js"],
  22813. * names: ["src", "maps", "are", "fun"],
  22814. * mappings: "AA,AB;;ABCDE;"
  22815. * }
  22816. *
  22817. * The second parameter, if given, is a string whose value is the URL
  22818. * at which the source map was found. This URL is used to compute the
  22819. * sources array.
  22820. *
  22821. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  22822. */
  22823. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  22824. var sourceMap = aSourceMap;
  22825. if (typeof aSourceMap === 'string') {
  22826. sourceMap = util.parseSourceMapInput(aSourceMap);
  22827. }
  22828. var version = util.getArg(sourceMap, 'version');
  22829. var sources = util.getArg(sourceMap, 'sources');
  22830. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  22831. // requires the array) to play nice here.
  22832. var names = util.getArg(sourceMap, 'names', []);
  22833. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  22834. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  22835. var mappings = util.getArg(sourceMap, 'mappings');
  22836. var file = util.getArg(sourceMap, 'file', null);
  22837. // Once again, Sass deviates from the spec and supplies the version as a
  22838. // string rather than a number, so we use loose equality checking here.
  22839. if (version != this._version) {
  22840. throw new Error('Unsupported version: ' + version);
  22841. }
  22842. if (sourceRoot) {
  22843. sourceRoot = util.normalize(sourceRoot);
  22844. }
  22845. sources = sources
  22846. .map(String)
  22847. // Some source maps produce relative source paths like "./foo.js" instead of
  22848. // "foo.js". Normalize these first so that future comparisons will succeed.
  22849. // See bugzil.la/1090768.
  22850. .map(util.normalize)
  22851. // Always ensure that absolute sources are internally stored relative to
  22852. // the source root, if the source root is absolute. Not doing this would
  22853. // be particularly problematic when the source root is a prefix of the
  22854. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  22855. .map(function (source) {
  22856. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  22857. ? util.relative(sourceRoot, source)
  22858. : source;
  22859. });
  22860. // Pass `true` below to allow duplicate names and sources. While source maps
  22861. // are intended to be compressed and deduplicated, the TypeScript compiler
  22862. // sometimes generates source maps with duplicates in them. See Github issue
  22863. // #72 and bugzil.la/889492.
  22864. this._names = ArraySet.fromArray(names.map(String), true);
  22865. this._sources = ArraySet.fromArray(sources, true);
  22866. this._absoluteSources = this._sources.toArray().map(function (s) {
  22867. return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
  22868. });
  22869. this.sourceRoot = sourceRoot;
  22870. this.sourcesContent = sourcesContent;
  22871. this._mappings = mappings;
  22872. this._sourceMapURL = aSourceMapURL;
  22873. this.file = file;
  22874. }
  22875. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  22876. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  22877. /**
  22878. * Utility function to find the index of a source. Returns -1 if not
  22879. * found.
  22880. */
  22881. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  22882. var relativeSource = aSource;
  22883. if (this.sourceRoot != null) {
  22884. relativeSource = util.relative(this.sourceRoot, relativeSource);
  22885. }
  22886. if (this._sources.has(relativeSource)) {
  22887. return this._sources.indexOf(relativeSource);
  22888. }
  22889. // Maybe aSource is an absolute URL as returned by |sources|. In
  22890. // this case we can't simply undo the transform.
  22891. var i;
  22892. for (i = 0; i < this._absoluteSources.length; ++i) {
  22893. if (this._absoluteSources[i] == aSource) {
  22894. return i;
  22895. }
  22896. }
  22897. return -1;
  22898. };
  22899. /**
  22900. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  22901. *
  22902. * @param SourceMapGenerator aSourceMap
  22903. * The source map that will be consumed.
  22904. * @param String aSourceMapURL
  22905. * The URL at which the source map can be found (optional)
  22906. * @returns BasicSourceMapConsumer
  22907. */
  22908. BasicSourceMapConsumer.fromSourceMap =
  22909. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  22910. var smc = Object.create(BasicSourceMapConsumer.prototype);
  22911. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  22912. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  22913. smc.sourceRoot = aSourceMap._sourceRoot;
  22914. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  22915. smc.sourceRoot);
  22916. smc.file = aSourceMap._file;
  22917. smc._sourceMapURL = aSourceMapURL;
  22918. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  22919. return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  22920. });
  22921. // Because we are modifying the entries (by converting string sources and
  22922. // names to indices into the sources and names ArraySets), we have to make
  22923. // a copy of the entry or else bad things happen. Shared mutable state
  22924. // strikes again! See github issue #191.
  22925. var generatedMappings = aSourceMap._mappings.toArray().slice();
  22926. var destGeneratedMappings = smc.__generatedMappings = [];
  22927. var destOriginalMappings = smc.__originalMappings = [];
  22928. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  22929. var srcMapping = generatedMappings[i];
  22930. var destMapping = new Mapping;
  22931. destMapping.generatedLine = srcMapping.generatedLine;
  22932. destMapping.generatedColumn = srcMapping.generatedColumn;
  22933. if (srcMapping.source) {
  22934. destMapping.source = sources.indexOf(srcMapping.source);
  22935. destMapping.originalLine = srcMapping.originalLine;
  22936. destMapping.originalColumn = srcMapping.originalColumn;
  22937. if (srcMapping.name) {
  22938. destMapping.name = names.indexOf(srcMapping.name);
  22939. }
  22940. destOriginalMappings.push(destMapping);
  22941. }
  22942. destGeneratedMappings.push(destMapping);
  22943. }
  22944. quickSort(smc.__originalMappings, util.compareByOriginalPositions);
  22945. return smc;
  22946. };
  22947. /**
  22948. * The version of the source mapping spec that we are consuming.
  22949. */
  22950. BasicSourceMapConsumer.prototype._version = 3;
  22951. /**
  22952. * The list of original sources.
  22953. */
  22954. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  22955. get: function () {
  22956. return this._absoluteSources.slice();
  22957. }
  22958. });
  22959. /**
  22960. * Provide the JIT with a nice shape / hidden class.
  22961. */
  22962. function Mapping() {
  22963. this.generatedLine = 0;
  22964. this.generatedColumn = 0;
  22965. this.source = null;
  22966. this.originalLine = null;
  22967. this.originalColumn = null;
  22968. this.name = null;
  22969. }
  22970. /**
  22971. * Parse the mappings in a string in to a data structure which we can easily
  22972. * query (the ordered arrays in the `this.__generatedMappings` and
  22973. * `this.__originalMappings` properties).
  22974. */
  22975. const compareGenerated = util.compareByGeneratedPositionsDeflatedNoLine;
  22976. function sortGenerated(array, start) {
  22977. let l = array.length;
  22978. let n = array.length - start;
  22979. if (n <= 1) {
  22980. return;
  22981. } else if (n == 2) {
  22982. let a = array[start];
  22983. let b = array[start + 1];
  22984. if (compareGenerated(a, b) > 0) {
  22985. array[start] = b;
  22986. array[start + 1] = a;
  22987. }
  22988. } else if (n < 20) {
  22989. for (let i = start; i < l; i++) {
  22990. for (let j = i; j > start; j--) {
  22991. let a = array[j - 1];
  22992. let b = array[j];
  22993. if (compareGenerated(a, b) <= 0) {
  22994. break;
  22995. }
  22996. array[j - 1] = b;
  22997. array[j] = a;
  22998. }
  22999. }
  23000. } else {
  23001. quickSort(array, compareGenerated, start);
  23002. }
  23003. }
  23004. BasicSourceMapConsumer.prototype._parseMappings =
  23005. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  23006. var generatedLine = 1;
  23007. var previousGeneratedColumn = 0;
  23008. var previousOriginalLine = 0;
  23009. var previousOriginalColumn = 0;
  23010. var previousSource = 0;
  23011. var previousName = 0;
  23012. var length = aStr.length;
  23013. var index = 0;
  23014. var temp = {};
  23015. var originalMappings = [];
  23016. var generatedMappings = [];
  23017. var mapping, segment, end, value;
  23018. let subarrayStart = 0;
  23019. while (index < length) {
  23020. if (aStr.charAt(index) === ';') {
  23021. generatedLine++;
  23022. index++;
  23023. previousGeneratedColumn = 0;
  23024. sortGenerated(generatedMappings, subarrayStart);
  23025. subarrayStart = generatedMappings.length;
  23026. }
  23027. else if (aStr.charAt(index) === ',') {
  23028. index++;
  23029. }
  23030. else {
  23031. mapping = new Mapping();
  23032. mapping.generatedLine = generatedLine;
  23033. for (end = index; end < length; end++) {
  23034. if (this._charIsMappingSeparator(aStr, end)) {
  23035. break;
  23036. }
  23037. }
  23038. aStr.slice(index, end);
  23039. segment = [];
  23040. while (index < end) {
  23041. base64VLQ.decode(aStr, index, temp);
  23042. value = temp.value;
  23043. index = temp.rest;
  23044. segment.push(value);
  23045. }
  23046. if (segment.length === 2) {
  23047. throw new Error('Found a source, but no line and column');
  23048. }
  23049. if (segment.length === 3) {
  23050. throw new Error('Found a source and line, but no column');
  23051. }
  23052. // Generated column.
  23053. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  23054. previousGeneratedColumn = mapping.generatedColumn;
  23055. if (segment.length > 1) {
  23056. // Original source.
  23057. mapping.source = previousSource + segment[1];
  23058. previousSource += segment[1];
  23059. // Original line.
  23060. mapping.originalLine = previousOriginalLine + segment[2];
  23061. previousOriginalLine = mapping.originalLine;
  23062. // Lines are stored 0-based
  23063. mapping.originalLine += 1;
  23064. // Original column.
  23065. mapping.originalColumn = previousOriginalColumn + segment[3];
  23066. previousOriginalColumn = mapping.originalColumn;
  23067. if (segment.length > 4) {
  23068. // Original name.
  23069. mapping.name = previousName + segment[4];
  23070. previousName += segment[4];
  23071. }
  23072. }
  23073. generatedMappings.push(mapping);
  23074. if (typeof mapping.originalLine === 'number') {
  23075. let currentSource = mapping.source;
  23076. while (originalMappings.length <= currentSource) {
  23077. originalMappings.push(null);
  23078. }
  23079. if (originalMappings[currentSource] === null) {
  23080. originalMappings[currentSource] = [];
  23081. }
  23082. originalMappings[currentSource].push(mapping);
  23083. }
  23084. }
  23085. }
  23086. sortGenerated(generatedMappings, subarrayStart);
  23087. this.__generatedMappings = generatedMappings;
  23088. for (var i = 0; i < originalMappings.length; i++) {
  23089. if (originalMappings[i] != null) {
  23090. quickSort(originalMappings[i], util.compareByOriginalPositionsNoSource);
  23091. }
  23092. }
  23093. this.__originalMappings = [].concat(...originalMappings);
  23094. };
  23095. /**
  23096. * Find the mapping that best matches the hypothetical "needle" mapping that
  23097. * we are searching for in the given "haystack" of mappings.
  23098. */
  23099. BasicSourceMapConsumer.prototype._findMapping =
  23100. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  23101. aColumnName, aComparator, aBias) {
  23102. // To return the position we are searching for, we must first find the
  23103. // mapping for the given position and then return the opposite position it
  23104. // points to. Because the mappings are sorted, we can use binary search to
  23105. // find the best mapping.
  23106. if (aNeedle[aLineName] <= 0) {
  23107. throw new TypeError('Line must be greater than or equal to 1, got '
  23108. + aNeedle[aLineName]);
  23109. }
  23110. if (aNeedle[aColumnName] < 0) {
  23111. throw new TypeError('Column must be greater than or equal to 0, got '
  23112. + aNeedle[aColumnName]);
  23113. }
  23114. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  23115. };
  23116. /**
  23117. * Compute the last column for each generated mapping. The last column is
  23118. * inclusive.
  23119. */
  23120. BasicSourceMapConsumer.prototype.computeColumnSpans =
  23121. function SourceMapConsumer_computeColumnSpans() {
  23122. for (var index = 0; index < this._generatedMappings.length; ++index) {
  23123. var mapping = this._generatedMappings[index];
  23124. // Mappings do not contain a field for the last generated columnt. We
  23125. // can come up with an optimistic estimate, however, by assuming that
  23126. // mappings are contiguous (i.e. given two consecutive mappings, the
  23127. // first mapping ends where the second one starts).
  23128. if (index + 1 < this._generatedMappings.length) {
  23129. var nextMapping = this._generatedMappings[index + 1];
  23130. if (mapping.generatedLine === nextMapping.generatedLine) {
  23131. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  23132. continue;
  23133. }
  23134. }
  23135. // The last mapping for each line spans the entire line.
  23136. mapping.lastGeneratedColumn = Infinity;
  23137. }
  23138. };
  23139. /**
  23140. * Returns the original source, line, and column information for the generated
  23141. * source's line and column positions provided. The only argument is an object
  23142. * with the following properties:
  23143. *
  23144. * - line: The line number in the generated source. The line number
  23145. * is 1-based.
  23146. * - column: The column number in the generated source. The column
  23147. * number is 0-based.
  23148. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  23149. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  23150. * closest element that is smaller than or greater than the one we are
  23151. * searching for, respectively, if the exact element cannot be found.
  23152. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  23153. *
  23154. * and an object is returned with the following properties:
  23155. *
  23156. * - source: The original source file, or null.
  23157. * - line: The line number in the original source, or null. The
  23158. * line number is 1-based.
  23159. * - column: The column number in the original source, or null. The
  23160. * column number is 0-based.
  23161. * - name: The original identifier, or null.
  23162. */
  23163. BasicSourceMapConsumer.prototype.originalPositionFor =
  23164. function SourceMapConsumer_originalPositionFor(aArgs) {
  23165. var needle = {
  23166. generatedLine: util.getArg(aArgs, 'line'),
  23167. generatedColumn: util.getArg(aArgs, 'column')
  23168. };
  23169. var index = this._findMapping(
  23170. needle,
  23171. this._generatedMappings,
  23172. "generatedLine",
  23173. "generatedColumn",
  23174. util.compareByGeneratedPositionsDeflated,
  23175. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  23176. );
  23177. if (index >= 0) {
  23178. var mapping = this._generatedMappings[index];
  23179. if (mapping.generatedLine === needle.generatedLine) {
  23180. var source = util.getArg(mapping, 'source', null);
  23181. if (source !== null) {
  23182. source = this._sources.at(source);
  23183. source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  23184. }
  23185. var name = util.getArg(mapping, 'name', null);
  23186. if (name !== null) {
  23187. name = this._names.at(name);
  23188. }
  23189. return {
  23190. source: source,
  23191. line: util.getArg(mapping, 'originalLine', null),
  23192. column: util.getArg(mapping, 'originalColumn', null),
  23193. name: name
  23194. };
  23195. }
  23196. }
  23197. return {
  23198. source: null,
  23199. line: null,
  23200. column: null,
  23201. name: null
  23202. };
  23203. };
  23204. /**
  23205. * Return true if we have the source content for every source in the source
  23206. * map, false otherwise.
  23207. */
  23208. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  23209. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  23210. if (!this.sourcesContent) {
  23211. return false;
  23212. }
  23213. return this.sourcesContent.length >= this._sources.size() &&
  23214. !this.sourcesContent.some(function (sc) { return sc == null; });
  23215. };
  23216. /**
  23217. * Returns the original source content. The only argument is the url of the
  23218. * original source file. Returns null if no original source content is
  23219. * available.
  23220. */
  23221. BasicSourceMapConsumer.prototype.sourceContentFor =
  23222. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  23223. if (!this.sourcesContent) {
  23224. return null;
  23225. }
  23226. var index = this._findSourceIndex(aSource);
  23227. if (index >= 0) {
  23228. return this.sourcesContent[index];
  23229. }
  23230. var relativeSource = aSource;
  23231. if (this.sourceRoot != null) {
  23232. relativeSource = util.relative(this.sourceRoot, relativeSource);
  23233. }
  23234. var url;
  23235. if (this.sourceRoot != null
  23236. && (url = util.urlParse(this.sourceRoot))) {
  23237. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  23238. // many users. We can help them out when they expect file:// URIs to
  23239. // behave like it would if they were running a local HTTP server. See
  23240. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  23241. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  23242. if (url.scheme == "file"
  23243. && this._sources.has(fileUriAbsPath)) {
  23244. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  23245. }
  23246. if ((!url.path || url.path == "/")
  23247. && this._sources.has("/" + relativeSource)) {
  23248. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  23249. }
  23250. }
  23251. // This function is used recursively from
  23252. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  23253. // don't want to throw if we can't find the source - we just want to
  23254. // return null, so we provide a flag to exit gracefully.
  23255. if (nullOnMissing) {
  23256. return null;
  23257. }
  23258. else {
  23259. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  23260. }
  23261. };
  23262. /**
  23263. * Returns the generated line and column information for the original source,
  23264. * line, and column positions provided. The only argument is an object with
  23265. * the following properties:
  23266. *
  23267. * - source: The filename of the original source.
  23268. * - line: The line number in the original source. The line number
  23269. * is 1-based.
  23270. * - column: The column number in the original source. The column
  23271. * number is 0-based.
  23272. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  23273. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  23274. * closest element that is smaller than or greater than the one we are
  23275. * searching for, respectively, if the exact element cannot be found.
  23276. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  23277. *
  23278. * and an object is returned with the following properties:
  23279. *
  23280. * - line: The line number in the generated source, or null. The
  23281. * line number is 1-based.
  23282. * - column: The column number in the generated source, or null.
  23283. * The column number is 0-based.
  23284. */
  23285. BasicSourceMapConsumer.prototype.generatedPositionFor =
  23286. function SourceMapConsumer_generatedPositionFor(aArgs) {
  23287. var source = util.getArg(aArgs, 'source');
  23288. source = this._findSourceIndex(source);
  23289. if (source < 0) {
  23290. return {
  23291. line: null,
  23292. column: null,
  23293. lastColumn: null
  23294. };
  23295. }
  23296. var needle = {
  23297. source: source,
  23298. originalLine: util.getArg(aArgs, 'line'),
  23299. originalColumn: util.getArg(aArgs, 'column')
  23300. };
  23301. var index = this._findMapping(
  23302. needle,
  23303. this._originalMappings,
  23304. "originalLine",
  23305. "originalColumn",
  23306. util.compareByOriginalPositions,
  23307. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  23308. );
  23309. if (index >= 0) {
  23310. var mapping = this._originalMappings[index];
  23311. if (mapping.source === needle.source) {
  23312. return {
  23313. line: util.getArg(mapping, 'generatedLine', null),
  23314. column: util.getArg(mapping, 'generatedColumn', null),
  23315. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  23316. };
  23317. }
  23318. }
  23319. return {
  23320. line: null,
  23321. column: null,
  23322. lastColumn: null
  23323. };
  23324. };
  23325. sourceMapConsumer$1.BasicSourceMapConsumer = BasicSourceMapConsumer;
  23326. /**
  23327. * An IndexedSourceMapConsumer instance represents a parsed source map which
  23328. * we can query for information. It differs from BasicSourceMapConsumer in
  23329. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  23330. * input.
  23331. *
  23332. * The first parameter is a raw source map (either as a JSON string, or already
  23333. * parsed to an object). According to the spec for indexed source maps, they
  23334. * have the following attributes:
  23335. *
  23336. * - version: Which version of the source map spec this map is following.
  23337. * - file: Optional. The generated file this source map is associated with.
  23338. * - sections: A list of section definitions.
  23339. *
  23340. * Each value under the "sections" field has two fields:
  23341. * - offset: The offset into the original specified at which this section
  23342. * begins to apply, defined as an object with a "line" and "column"
  23343. * field.
  23344. * - map: A source map definition. This source map could also be indexed,
  23345. * but doesn't have to be.
  23346. *
  23347. * Instead of the "map" field, it's also possible to have a "url" field
  23348. * specifying a URL to retrieve a source map from, but that's currently
  23349. * unsupported.
  23350. *
  23351. * Here's an example source map, taken from the source map spec[0], but
  23352. * modified to omit a section which uses the "url" field.
  23353. *
  23354. * {
  23355. * version : 3,
  23356. * file: "app.js",
  23357. * sections: [{
  23358. * offset: {line:100, column:10},
  23359. * map: {
  23360. * version : 3,
  23361. * file: "section.js",
  23362. * sources: ["foo.js", "bar.js"],
  23363. * names: ["src", "maps", "are", "fun"],
  23364. * mappings: "AAAA,E;;ABCDE;"
  23365. * }
  23366. * }],
  23367. * }
  23368. *
  23369. * The second parameter, if given, is a string whose value is the URL
  23370. * at which the source map was found. This URL is used to compute the
  23371. * sources array.
  23372. *
  23373. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  23374. */
  23375. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  23376. var sourceMap = aSourceMap;
  23377. if (typeof aSourceMap === 'string') {
  23378. sourceMap = util.parseSourceMapInput(aSourceMap);
  23379. }
  23380. var version = util.getArg(sourceMap, 'version');
  23381. var sections = util.getArg(sourceMap, 'sections');
  23382. if (version != this._version) {
  23383. throw new Error('Unsupported version: ' + version);
  23384. }
  23385. this._sources = new ArraySet();
  23386. this._names = new ArraySet();
  23387. var lastOffset = {
  23388. line: -1,
  23389. column: 0
  23390. };
  23391. this._sections = sections.map(function (s) {
  23392. if (s.url) {
  23393. // The url field will require support for asynchronicity.
  23394. // See https://github.com/mozilla/source-map/issues/16
  23395. throw new Error('Support for url field in sections not implemented.');
  23396. }
  23397. var offset = util.getArg(s, 'offset');
  23398. var offsetLine = util.getArg(offset, 'line');
  23399. var offsetColumn = util.getArg(offset, 'column');
  23400. if (offsetLine < lastOffset.line ||
  23401. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  23402. throw new Error('Section offsets must be ordered and non-overlapping.');
  23403. }
  23404. lastOffset = offset;
  23405. return {
  23406. generatedOffset: {
  23407. // The offset fields are 0-based, but we use 1-based indices when
  23408. // encoding/decoding from VLQ.
  23409. generatedLine: offsetLine + 1,
  23410. generatedColumn: offsetColumn + 1
  23411. },
  23412. consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
  23413. }
  23414. });
  23415. }
  23416. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  23417. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  23418. /**
  23419. * The version of the source mapping spec that we are consuming.
  23420. */
  23421. IndexedSourceMapConsumer.prototype._version = 3;
  23422. /**
  23423. * The list of original sources.
  23424. */
  23425. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  23426. get: function () {
  23427. var sources = [];
  23428. for (var i = 0; i < this._sections.length; i++) {
  23429. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  23430. sources.push(this._sections[i].consumer.sources[j]);
  23431. }
  23432. }
  23433. return sources;
  23434. }
  23435. });
  23436. /**
  23437. * Returns the original source, line, and column information for the generated
  23438. * source's line and column positions provided. The only argument is an object
  23439. * with the following properties:
  23440. *
  23441. * - line: The line number in the generated source. The line number
  23442. * is 1-based.
  23443. * - column: The column number in the generated source. The column
  23444. * number is 0-based.
  23445. *
  23446. * and an object is returned with the following properties:
  23447. *
  23448. * - source: The original source file, or null.
  23449. * - line: The line number in the original source, or null. The
  23450. * line number is 1-based.
  23451. * - column: The column number in the original source, or null. The
  23452. * column number is 0-based.
  23453. * - name: The original identifier, or null.
  23454. */
  23455. IndexedSourceMapConsumer.prototype.originalPositionFor =
  23456. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  23457. var needle = {
  23458. generatedLine: util.getArg(aArgs, 'line'),
  23459. generatedColumn: util.getArg(aArgs, 'column')
  23460. };
  23461. // Find the section containing the generated position we're trying to map
  23462. // to an original position.
  23463. var sectionIndex = binarySearch.search(needle, this._sections,
  23464. function(needle, section) {
  23465. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  23466. if (cmp) {
  23467. return cmp;
  23468. }
  23469. return (needle.generatedColumn -
  23470. section.generatedOffset.generatedColumn);
  23471. });
  23472. var section = this._sections[sectionIndex];
  23473. if (!section) {
  23474. return {
  23475. source: null,
  23476. line: null,
  23477. column: null,
  23478. name: null
  23479. };
  23480. }
  23481. return section.consumer.originalPositionFor({
  23482. line: needle.generatedLine -
  23483. (section.generatedOffset.generatedLine - 1),
  23484. column: needle.generatedColumn -
  23485. (section.generatedOffset.generatedLine === needle.generatedLine
  23486. ? section.generatedOffset.generatedColumn - 1
  23487. : 0),
  23488. bias: aArgs.bias
  23489. });
  23490. };
  23491. /**
  23492. * Return true if we have the source content for every source in the source
  23493. * map, false otherwise.
  23494. */
  23495. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  23496. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  23497. return this._sections.every(function (s) {
  23498. return s.consumer.hasContentsOfAllSources();
  23499. });
  23500. };
  23501. /**
  23502. * Returns the original source content. The only argument is the url of the
  23503. * original source file. Returns null if no original source content is
  23504. * available.
  23505. */
  23506. IndexedSourceMapConsumer.prototype.sourceContentFor =
  23507. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  23508. for (var i = 0; i < this._sections.length; i++) {
  23509. var section = this._sections[i];
  23510. var content = section.consumer.sourceContentFor(aSource, true);
  23511. if (content || content === '') {
  23512. return content;
  23513. }
  23514. }
  23515. if (nullOnMissing) {
  23516. return null;
  23517. }
  23518. else {
  23519. throw new Error('"' + aSource + '" is not in the SourceMap.');
  23520. }
  23521. };
  23522. /**
  23523. * Returns the generated line and column information for the original source,
  23524. * line, and column positions provided. The only argument is an object with
  23525. * the following properties:
  23526. *
  23527. * - source: The filename of the original source.
  23528. * - line: The line number in the original source. The line number
  23529. * is 1-based.
  23530. * - column: The column number in the original source. The column
  23531. * number is 0-based.
  23532. *
  23533. * and an object is returned with the following properties:
  23534. *
  23535. * - line: The line number in the generated source, or null. The
  23536. * line number is 1-based.
  23537. * - column: The column number in the generated source, or null.
  23538. * The column number is 0-based.
  23539. */
  23540. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  23541. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  23542. for (var i = 0; i < this._sections.length; i++) {
  23543. var section = this._sections[i];
  23544. // Only consider this section if the requested source is in the list of
  23545. // sources of the consumer.
  23546. if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
  23547. continue;
  23548. }
  23549. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  23550. if (generatedPosition) {
  23551. var ret = {
  23552. line: generatedPosition.line +
  23553. (section.generatedOffset.generatedLine - 1),
  23554. column: generatedPosition.column +
  23555. (section.generatedOffset.generatedLine === generatedPosition.line
  23556. ? section.generatedOffset.generatedColumn - 1
  23557. : 0)
  23558. };
  23559. return ret;
  23560. }
  23561. }
  23562. return {
  23563. line: null,
  23564. column: null
  23565. };
  23566. };
  23567. /**
  23568. * Parse the mappings in a string in to a data structure which we can easily
  23569. * query (the ordered arrays in the `this.__generatedMappings` and
  23570. * `this.__originalMappings` properties).
  23571. */
  23572. IndexedSourceMapConsumer.prototype._parseMappings =
  23573. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  23574. this.__generatedMappings = [];
  23575. this.__originalMappings = [];
  23576. for (var i = 0; i < this._sections.length; i++) {
  23577. var section = this._sections[i];
  23578. var sectionMappings = section.consumer._generatedMappings;
  23579. for (var j = 0; j < sectionMappings.length; j++) {
  23580. var mapping = sectionMappings[j];
  23581. var source = section.consumer._sources.at(mapping.source);
  23582. if(source !== null) {
  23583. source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  23584. }
  23585. this._sources.add(source);
  23586. source = this._sources.indexOf(source);
  23587. var name = null;
  23588. if (mapping.name) {
  23589. name = section.consumer._names.at(mapping.name);
  23590. this._names.add(name);
  23591. name = this._names.indexOf(name);
  23592. }
  23593. // The mappings coming from the consumer for the section have
  23594. // generated positions relative to the start of the section, so we
  23595. // need to offset them to be relative to the start of the concatenated
  23596. // generated file.
  23597. var adjustedMapping = {
  23598. source: source,
  23599. generatedLine: mapping.generatedLine +
  23600. (section.generatedOffset.generatedLine - 1),
  23601. generatedColumn: mapping.generatedColumn +
  23602. (section.generatedOffset.generatedLine === mapping.generatedLine
  23603. ? section.generatedOffset.generatedColumn - 1
  23604. : 0),
  23605. originalLine: mapping.originalLine,
  23606. originalColumn: mapping.originalColumn,
  23607. name: name
  23608. };
  23609. this.__generatedMappings.push(adjustedMapping);
  23610. if (typeof adjustedMapping.originalLine === 'number') {
  23611. this.__originalMappings.push(adjustedMapping);
  23612. }
  23613. }
  23614. }
  23615. quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  23616. quickSort(this.__originalMappings, util.compareByOriginalPositions);
  23617. };
  23618. sourceMapConsumer$1.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  23619. return sourceMapConsumer$1;
  23620. }
  23621. var sourceNode$1 = {};
  23622. /* -*- Mode: js; js-indent-level: 2; -*- */
  23623. var hasRequiredSourceNode$1;
  23624. function requireSourceNode$1 () {
  23625. if (hasRequiredSourceNode$1) return sourceNode$1;
  23626. hasRequiredSourceNode$1 = 1;
  23627. /*
  23628. * Copyright 2011 Mozilla Foundation and contributors
  23629. * Licensed under the New BSD license. See LICENSE or:
  23630. * http://opensource.org/licenses/BSD-3-Clause
  23631. */
  23632. var SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator$1().SourceMapGenerator;
  23633. var util = /*@__PURE__*/ requireUtil$2();
  23634. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  23635. // operating systems these days (capturing the result).
  23636. var REGEX_NEWLINE = /(\r?\n)/;
  23637. // Newline character code for charCodeAt() comparisons
  23638. var NEWLINE_CODE = 10;
  23639. // Private symbol for identifying `SourceNode`s when multiple versions of
  23640. // the source-map library are loaded. This MUST NOT CHANGE across
  23641. // versions!
  23642. var isSourceNode = "$$$isSourceNode$$$";
  23643. /**
  23644. * SourceNodes provide a way to abstract over interpolating/concatenating
  23645. * snippets of generated JavaScript source code while maintaining the line and
  23646. * column information associated with the original source code.
  23647. *
  23648. * @param aLine The original line number.
  23649. * @param aColumn The original column number.
  23650. * @param aSource The original source's filename.
  23651. * @param aChunks Optional. An array of strings which are snippets of
  23652. * generated JS, or other SourceNodes.
  23653. * @param aName The original identifier.
  23654. */
  23655. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  23656. this.children = [];
  23657. this.sourceContents = {};
  23658. this.line = aLine == null ? null : aLine;
  23659. this.column = aColumn == null ? null : aColumn;
  23660. this.source = aSource == null ? null : aSource;
  23661. this.name = aName == null ? null : aName;
  23662. this[isSourceNode] = true;
  23663. if (aChunks != null) this.add(aChunks);
  23664. }
  23665. /**
  23666. * Creates a SourceNode from generated code and a SourceMapConsumer.
  23667. *
  23668. * @param aGeneratedCode The generated code
  23669. * @param aSourceMapConsumer The SourceMap for the generated code
  23670. * @param aRelativePath Optional. The path that relative sources in the
  23671. * SourceMapConsumer should be relative to.
  23672. */
  23673. SourceNode.fromStringWithSourceMap =
  23674. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  23675. // The SourceNode we want to fill with the generated code
  23676. // and the SourceMap
  23677. var node = new SourceNode();
  23678. // All even indices of this array are one line of the generated code,
  23679. // while all odd indices are the newlines between two adjacent lines
  23680. // (since `REGEX_NEWLINE` captures its match).
  23681. // Processed fragments are accessed by calling `shiftNextLine`.
  23682. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  23683. var remainingLinesIndex = 0;
  23684. var shiftNextLine = function() {
  23685. var lineContents = getNextLine();
  23686. // The last line of a file might not have a newline.
  23687. var newLine = getNextLine() || "";
  23688. return lineContents + newLine;
  23689. function getNextLine() {
  23690. return remainingLinesIndex < remainingLines.length ?
  23691. remainingLines[remainingLinesIndex++] : undefined;
  23692. }
  23693. };
  23694. // We need to remember the position of "remainingLines"
  23695. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  23696. // The generate SourceNodes we need a code range.
  23697. // To extract it current and last mapping is used.
  23698. // Here we store the last mapping.
  23699. var lastMapping = null;
  23700. aSourceMapConsumer.eachMapping(function (mapping) {
  23701. if (lastMapping !== null) {
  23702. // We add the code from "lastMapping" to "mapping":
  23703. // First check if there is a new line in between.
  23704. if (lastGeneratedLine < mapping.generatedLine) {
  23705. // Associate first line with "lastMapping"
  23706. addMappingWithCode(lastMapping, shiftNextLine());
  23707. lastGeneratedLine++;
  23708. lastGeneratedColumn = 0;
  23709. // The remaining code is added without mapping
  23710. } else {
  23711. // There is no new line in between.
  23712. // Associate the code between "lastGeneratedColumn" and
  23713. // "mapping.generatedColumn" with "lastMapping"
  23714. var nextLine = remainingLines[remainingLinesIndex] || '';
  23715. var code = nextLine.substr(0, mapping.generatedColumn -
  23716. lastGeneratedColumn);
  23717. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  23718. lastGeneratedColumn);
  23719. lastGeneratedColumn = mapping.generatedColumn;
  23720. addMappingWithCode(lastMapping, code);
  23721. // No more remaining code, continue
  23722. lastMapping = mapping;
  23723. return;
  23724. }
  23725. }
  23726. // We add the generated code until the first mapping
  23727. // to the SourceNode without any mapping.
  23728. // Each line is added as separate string.
  23729. while (lastGeneratedLine < mapping.generatedLine) {
  23730. node.add(shiftNextLine());
  23731. lastGeneratedLine++;
  23732. }
  23733. if (lastGeneratedColumn < mapping.generatedColumn) {
  23734. var nextLine = remainingLines[remainingLinesIndex] || '';
  23735. node.add(nextLine.substr(0, mapping.generatedColumn));
  23736. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  23737. lastGeneratedColumn = mapping.generatedColumn;
  23738. }
  23739. lastMapping = mapping;
  23740. }, this);
  23741. // We have processed all mappings.
  23742. if (remainingLinesIndex < remainingLines.length) {
  23743. if (lastMapping) {
  23744. // Associate the remaining code in the current line with "lastMapping"
  23745. addMappingWithCode(lastMapping, shiftNextLine());
  23746. }
  23747. // and add the remaining lines without any mapping
  23748. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  23749. }
  23750. // Copy sourcesContent into SourceNode
  23751. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  23752. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  23753. if (content != null) {
  23754. if (aRelativePath != null) {
  23755. sourceFile = util.join(aRelativePath, sourceFile);
  23756. }
  23757. node.setSourceContent(sourceFile, content);
  23758. }
  23759. });
  23760. return node;
  23761. function addMappingWithCode(mapping, code) {
  23762. if (mapping === null || mapping.source === undefined) {
  23763. node.add(code);
  23764. } else {
  23765. var source = aRelativePath
  23766. ? util.join(aRelativePath, mapping.source)
  23767. : mapping.source;
  23768. node.add(new SourceNode(mapping.originalLine,
  23769. mapping.originalColumn,
  23770. source,
  23771. code,
  23772. mapping.name));
  23773. }
  23774. }
  23775. };
  23776. /**
  23777. * Add a chunk of generated JS to this source node.
  23778. *
  23779. * @param aChunk A string snippet of generated JS code, another instance of
  23780. * SourceNode, or an array where each member is one of those things.
  23781. */
  23782. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  23783. if (Array.isArray(aChunk)) {
  23784. aChunk.forEach(function (chunk) {
  23785. this.add(chunk);
  23786. }, this);
  23787. }
  23788. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  23789. if (aChunk) {
  23790. this.children.push(aChunk);
  23791. }
  23792. }
  23793. else {
  23794. throw new TypeError(
  23795. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  23796. );
  23797. }
  23798. return this;
  23799. };
  23800. /**
  23801. * Add a chunk of generated JS to the beginning of this source node.
  23802. *
  23803. * @param aChunk A string snippet of generated JS code, another instance of
  23804. * SourceNode, or an array where each member is one of those things.
  23805. */
  23806. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  23807. if (Array.isArray(aChunk)) {
  23808. for (var i = aChunk.length-1; i >= 0; i--) {
  23809. this.prepend(aChunk[i]);
  23810. }
  23811. }
  23812. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  23813. this.children.unshift(aChunk);
  23814. }
  23815. else {
  23816. throw new TypeError(
  23817. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  23818. );
  23819. }
  23820. return this;
  23821. };
  23822. /**
  23823. * Walk over the tree of JS snippets in this node and its children. The
  23824. * walking function is called once for each snippet of JS and is passed that
  23825. * snippet and the its original associated source's line/column location.
  23826. *
  23827. * @param aFn The traversal function.
  23828. */
  23829. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  23830. var chunk;
  23831. for (var i = 0, len = this.children.length; i < len; i++) {
  23832. chunk = this.children[i];
  23833. if (chunk[isSourceNode]) {
  23834. chunk.walk(aFn);
  23835. }
  23836. else {
  23837. if (chunk !== '') {
  23838. aFn(chunk, { source: this.source,
  23839. line: this.line,
  23840. column: this.column,
  23841. name: this.name });
  23842. }
  23843. }
  23844. }
  23845. };
  23846. /**
  23847. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  23848. * each of `this.children`.
  23849. *
  23850. * @param aSep The separator.
  23851. */
  23852. SourceNode.prototype.join = function SourceNode_join(aSep) {
  23853. var newChildren;
  23854. var i;
  23855. var len = this.children.length;
  23856. if (len > 0) {
  23857. newChildren = [];
  23858. for (i = 0; i < len-1; i++) {
  23859. newChildren.push(this.children[i]);
  23860. newChildren.push(aSep);
  23861. }
  23862. newChildren.push(this.children[i]);
  23863. this.children = newChildren;
  23864. }
  23865. return this;
  23866. };
  23867. /**
  23868. * Call String.prototype.replace on the very right-most source snippet. Useful
  23869. * for trimming whitespace from the end of a source node, etc.
  23870. *
  23871. * @param aPattern The pattern to replace.
  23872. * @param aReplacement The thing to replace the pattern with.
  23873. */
  23874. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  23875. var lastChild = this.children[this.children.length - 1];
  23876. if (lastChild[isSourceNode]) {
  23877. lastChild.replaceRight(aPattern, aReplacement);
  23878. }
  23879. else if (typeof lastChild === 'string') {
  23880. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  23881. }
  23882. else {
  23883. this.children.push(''.replace(aPattern, aReplacement));
  23884. }
  23885. return this;
  23886. };
  23887. /**
  23888. * Set the source content for a source file. This will be added to the SourceMapGenerator
  23889. * in the sourcesContent field.
  23890. *
  23891. * @param aSourceFile The filename of the source file
  23892. * @param aSourceContent The content of the source file
  23893. */
  23894. SourceNode.prototype.setSourceContent =
  23895. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  23896. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  23897. };
  23898. /**
  23899. * Walk over the tree of SourceNodes. The walking function is called for each
  23900. * source file content and is passed the filename and source content.
  23901. *
  23902. * @param aFn The traversal function.
  23903. */
  23904. SourceNode.prototype.walkSourceContents =
  23905. function SourceNode_walkSourceContents(aFn) {
  23906. for (var i = 0, len = this.children.length; i < len; i++) {
  23907. if (this.children[i][isSourceNode]) {
  23908. this.children[i].walkSourceContents(aFn);
  23909. }
  23910. }
  23911. var sources = Object.keys(this.sourceContents);
  23912. for (var i = 0, len = sources.length; i < len; i++) {
  23913. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  23914. }
  23915. };
  23916. /**
  23917. * Return the string representation of this source node. Walks over the tree
  23918. * and concatenates all the various snippets together to one string.
  23919. */
  23920. SourceNode.prototype.toString = function SourceNode_toString() {
  23921. var str = "";
  23922. this.walk(function (chunk) {
  23923. str += chunk;
  23924. });
  23925. return str;
  23926. };
  23927. /**
  23928. * Returns the string representation of this source node along with a source
  23929. * map.
  23930. */
  23931. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  23932. var generated = {
  23933. code: "",
  23934. line: 1,
  23935. column: 0
  23936. };
  23937. var map = new SourceMapGenerator(aArgs);
  23938. var sourceMappingActive = false;
  23939. var lastOriginalSource = null;
  23940. var lastOriginalLine = null;
  23941. var lastOriginalColumn = null;
  23942. var lastOriginalName = null;
  23943. this.walk(function (chunk, original) {
  23944. generated.code += chunk;
  23945. if (original.source !== null
  23946. && original.line !== null
  23947. && original.column !== null) {
  23948. if(lastOriginalSource !== original.source
  23949. || lastOriginalLine !== original.line
  23950. || lastOriginalColumn !== original.column
  23951. || lastOriginalName !== original.name) {
  23952. map.addMapping({
  23953. source: original.source,
  23954. original: {
  23955. line: original.line,
  23956. column: original.column
  23957. },
  23958. generated: {
  23959. line: generated.line,
  23960. column: generated.column
  23961. },
  23962. name: original.name
  23963. });
  23964. }
  23965. lastOriginalSource = original.source;
  23966. lastOriginalLine = original.line;
  23967. lastOriginalColumn = original.column;
  23968. lastOriginalName = original.name;
  23969. sourceMappingActive = true;
  23970. } else if (sourceMappingActive) {
  23971. map.addMapping({
  23972. generated: {
  23973. line: generated.line,
  23974. column: generated.column
  23975. }
  23976. });
  23977. lastOriginalSource = null;
  23978. sourceMappingActive = false;
  23979. }
  23980. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  23981. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  23982. generated.line++;
  23983. generated.column = 0;
  23984. // Mappings end at eol
  23985. if (idx + 1 === length) {
  23986. lastOriginalSource = null;
  23987. sourceMappingActive = false;
  23988. } else if (sourceMappingActive) {
  23989. map.addMapping({
  23990. source: original.source,
  23991. original: {
  23992. line: original.line,
  23993. column: original.column
  23994. },
  23995. generated: {
  23996. line: generated.line,
  23997. column: generated.column
  23998. },
  23999. name: original.name
  24000. });
  24001. }
  24002. } else {
  24003. generated.column++;
  24004. }
  24005. }
  24006. });
  24007. this.walkSourceContents(function (sourceFile, sourceContent) {
  24008. map.setSourceContent(sourceFile, sourceContent);
  24009. });
  24010. return { code: generated.code, map: map };
  24011. };
  24012. sourceNode$1.SourceNode = SourceNode;
  24013. return sourceNode$1;
  24014. }
  24015. /*
  24016. * Copyright 2009-2011 Mozilla Foundation and contributors
  24017. * Licensed under the New BSD license. See LICENSE.txt or:
  24018. * http://opensource.org/licenses/BSD-3-Clause
  24019. */
  24020. var hasRequiredSourceMap$1;
  24021. function requireSourceMap$1 () {
  24022. if (hasRequiredSourceMap$1) return sourceMap$1;
  24023. hasRequiredSourceMap$1 = 1;
  24024. sourceMap$1.SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator$1().SourceMapGenerator;
  24025. sourceMap$1.SourceMapConsumer = /*@__PURE__*/ requireSourceMapConsumer$1().SourceMapConsumer;
  24026. sourceMap$1.SourceNode = /*@__PURE__*/ requireSourceNode$1().SourceNode;
  24027. return sourceMap$1;
  24028. }
  24029. var sourceMapExports = /*@__PURE__*/ requireSourceMap$1();
  24030. const PURE_ANNOTATION = `/*@__PURE__*/`;
  24031. const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
  24032. function createCodegenContext(ast, {
  24033. mode = "function",
  24034. prefixIdentifiers = mode === "module",
  24035. sourceMap = false,
  24036. filename = `template.vue.html`,
  24037. scopeId = null,
  24038. optimizeImports = false,
  24039. runtimeGlobalName = `Vue`,
  24040. runtimeModuleName = `vue`,
  24041. ssrRuntimeModuleName = "vue/server-renderer",
  24042. ssr = false,
  24043. isTS = false,
  24044. inSSR = false
  24045. }) {
  24046. const context = {
  24047. mode,
  24048. prefixIdentifiers,
  24049. sourceMap,
  24050. filename,
  24051. scopeId,
  24052. optimizeImports,
  24053. runtimeGlobalName,
  24054. runtimeModuleName,
  24055. ssrRuntimeModuleName,
  24056. ssr,
  24057. isTS,
  24058. inSSR,
  24059. source: ast.source,
  24060. code: ``,
  24061. column: 1,
  24062. line: 1,
  24063. offset: 0,
  24064. indentLevel: 0,
  24065. pure: false,
  24066. map: void 0,
  24067. helper(key) {
  24068. return `_${helperNameMap[key]}`;
  24069. },
  24070. push(code, newlineIndex = -2 /* None */, node) {
  24071. context.code += code;
  24072. if (context.map) {
  24073. if (node) {
  24074. let name;
  24075. if (node.type === 4 && !node.isStatic) {
  24076. const content = node.content.replace(/^_ctx\./, "");
  24077. if (content !== node.content && isSimpleIdentifier(content)) {
  24078. name = content;
  24079. }
  24080. }
  24081. if (node.loc.source) {
  24082. addMapping(node.loc.start, name);
  24083. }
  24084. }
  24085. if (newlineIndex === -3 /* Unknown */) {
  24086. advancePositionWithMutation(context, code);
  24087. } else {
  24088. context.offset += code.length;
  24089. if (newlineIndex === -2 /* None */) {
  24090. context.column += code.length;
  24091. } else {
  24092. if (newlineIndex === -1 /* End */) {
  24093. newlineIndex = code.length - 1;
  24094. }
  24095. context.line++;
  24096. context.column = code.length - newlineIndex;
  24097. }
  24098. }
  24099. if (node && node.loc !== locStub && node.loc.source) {
  24100. addMapping(node.loc.end);
  24101. }
  24102. }
  24103. },
  24104. indent() {
  24105. newline(++context.indentLevel);
  24106. },
  24107. deindent(withoutNewLine = false) {
  24108. if (withoutNewLine) {
  24109. --context.indentLevel;
  24110. } else {
  24111. newline(--context.indentLevel);
  24112. }
  24113. },
  24114. newline() {
  24115. newline(context.indentLevel);
  24116. }
  24117. };
  24118. function newline(n) {
  24119. context.push("\n" + ` `.repeat(n), 0 /* Start */);
  24120. }
  24121. function addMapping(loc, name = null) {
  24122. const { _names, _mappings } = context.map;
  24123. if (name !== null && !_names.has(name)) _names.add(name);
  24124. _mappings.add({
  24125. originalLine: loc.line,
  24126. originalColumn: loc.column - 1,
  24127. // source-map column is 0 based
  24128. generatedLine: context.line,
  24129. generatedColumn: context.column - 1,
  24130. source: filename,
  24131. name
  24132. });
  24133. }
  24134. if (sourceMap) {
  24135. context.map = new sourceMapExports.SourceMapGenerator();
  24136. context.map.setSourceContent(filename, context.source);
  24137. context.map._sources.add(filename);
  24138. }
  24139. return context;
  24140. }
  24141. function generate(ast, options = {}) {
  24142. const context = createCodegenContext(ast, options);
  24143. if (options.onContextCreated) options.onContextCreated(context);
  24144. const {
  24145. mode,
  24146. push,
  24147. prefixIdentifiers,
  24148. indent,
  24149. deindent,
  24150. newline,
  24151. scopeId,
  24152. ssr
  24153. } = context;
  24154. const helpers = Array.from(ast.helpers);
  24155. const hasHelpers = helpers.length > 0;
  24156. const useWithBlock = !prefixIdentifiers && mode !== "module";
  24157. const genScopeId = scopeId != null && mode === "module";
  24158. const isSetupInlined = !!options.inline;
  24159. const preambleContext = isSetupInlined ? createCodegenContext(ast, options) : context;
  24160. if (mode === "module") {
  24161. genModulePreamble(ast, preambleContext, genScopeId, isSetupInlined);
  24162. } else {
  24163. genFunctionPreamble(ast, preambleContext);
  24164. }
  24165. const functionName = ssr ? `ssrRender` : `render`;
  24166. const args = ssr ? ["_ctx", "_push", "_parent", "_attrs"] : ["_ctx", "_cache"];
  24167. if (options.bindingMetadata && !options.inline) {
  24168. args.push("$props", "$setup", "$data", "$options");
  24169. }
  24170. const signature = options.isTS ? args.map((arg) => `${arg}: any`).join(",") : args.join(", ");
  24171. if (isSetupInlined) {
  24172. push(`(${signature}) => {`);
  24173. } else {
  24174. push(`function ${functionName}(${signature}) {`);
  24175. }
  24176. indent();
  24177. if (useWithBlock) {
  24178. push(`with (_ctx) {`);
  24179. indent();
  24180. if (hasHelpers) {
  24181. push(
  24182. `const { ${helpers.map(aliasHelper).join(", ")} } = _Vue
  24183. `,
  24184. -1 /* End */
  24185. );
  24186. newline();
  24187. }
  24188. }
  24189. if (ast.components.length) {
  24190. genAssets(ast.components, "component", context);
  24191. if (ast.directives.length || ast.temps > 0) {
  24192. newline();
  24193. }
  24194. }
  24195. if (ast.directives.length) {
  24196. genAssets(ast.directives, "directive", context);
  24197. if (ast.temps > 0) {
  24198. newline();
  24199. }
  24200. }
  24201. if (ast.temps > 0) {
  24202. push(`let `);
  24203. for (let i = 0; i < ast.temps; i++) {
  24204. push(`${i > 0 ? `, ` : ``}_temp${i}`);
  24205. }
  24206. }
  24207. if (ast.components.length || ast.directives.length || ast.temps) {
  24208. push(`
  24209. `, 0 /* Start */);
  24210. newline();
  24211. }
  24212. if (!ssr) {
  24213. push(`return `);
  24214. }
  24215. if (ast.codegenNode) {
  24216. genNode(ast.codegenNode, context);
  24217. } else {
  24218. push(`null`);
  24219. }
  24220. if (useWithBlock) {
  24221. deindent();
  24222. push(`}`);
  24223. }
  24224. deindent();
  24225. push(`}`);
  24226. return {
  24227. ast,
  24228. code: context.code,
  24229. preamble: isSetupInlined ? preambleContext.code : ``,
  24230. map: context.map ? context.map.toJSON() : void 0
  24231. };
  24232. }
  24233. function genFunctionPreamble(ast, context) {
  24234. const {
  24235. ssr,
  24236. prefixIdentifiers,
  24237. push,
  24238. newline,
  24239. runtimeModuleName,
  24240. runtimeGlobalName,
  24241. ssrRuntimeModuleName
  24242. } = context;
  24243. const VueBinding = ssr ? `require(${JSON.stringify(runtimeModuleName)})` : runtimeGlobalName;
  24244. const helpers = Array.from(ast.helpers);
  24245. if (helpers.length > 0) {
  24246. if (prefixIdentifiers) {
  24247. push(
  24248. `const { ${helpers.map(aliasHelper).join(", ")} } = ${VueBinding}
  24249. `,
  24250. -1 /* End */
  24251. );
  24252. } else {
  24253. push(`const _Vue = ${VueBinding}
  24254. `, -1 /* End */);
  24255. if (ast.hoists.length) {
  24256. const staticHelpers = [
  24257. CREATE_VNODE,
  24258. CREATE_ELEMENT_VNODE,
  24259. CREATE_COMMENT,
  24260. CREATE_TEXT,
  24261. CREATE_STATIC
  24262. ].filter((helper) => helpers.includes(helper)).map(aliasHelper).join(", ");
  24263. push(`const { ${staticHelpers} } = _Vue
  24264. `, -1 /* End */);
  24265. }
  24266. }
  24267. }
  24268. if (ast.ssrHelpers && ast.ssrHelpers.length) {
  24269. push(
  24270. `const { ${ast.ssrHelpers.map(aliasHelper).join(", ")} } = require("${ssrRuntimeModuleName}")
  24271. `,
  24272. -1 /* End */
  24273. );
  24274. }
  24275. genHoists(ast.hoists, context);
  24276. newline();
  24277. push(`return `);
  24278. }
  24279. function genModulePreamble(ast, context, genScopeId, inline) {
  24280. const {
  24281. push,
  24282. newline,
  24283. optimizeImports,
  24284. runtimeModuleName,
  24285. ssrRuntimeModuleName
  24286. } = context;
  24287. if (ast.helpers.size) {
  24288. const helpers = Array.from(ast.helpers);
  24289. if (optimizeImports) {
  24290. push(
  24291. `import { ${helpers.map((s) => helperNameMap[s]).join(", ")} } from ${JSON.stringify(runtimeModuleName)}
  24292. `,
  24293. -1 /* End */
  24294. );
  24295. push(
  24296. `
  24297. // Binding optimization for webpack code-split
  24298. const ${helpers.map((s) => `_${helperNameMap[s]} = ${helperNameMap[s]}`).join(", ")}
  24299. `,
  24300. -1 /* End */
  24301. );
  24302. } else {
  24303. push(
  24304. `import { ${helpers.map((s) => `${helperNameMap[s]} as _${helperNameMap[s]}`).join(", ")} } from ${JSON.stringify(runtimeModuleName)}
  24305. `,
  24306. -1 /* End */
  24307. );
  24308. }
  24309. }
  24310. if (ast.ssrHelpers && ast.ssrHelpers.length) {
  24311. push(
  24312. `import { ${ast.ssrHelpers.map((s) => `${helperNameMap[s]} as _${helperNameMap[s]}`).join(", ")} } from "${ssrRuntimeModuleName}"
  24313. `,
  24314. -1 /* End */
  24315. );
  24316. }
  24317. if (ast.imports.length) {
  24318. genImports(ast.imports, context);
  24319. newline();
  24320. }
  24321. genHoists(ast.hoists, context);
  24322. newline();
  24323. if (!inline) {
  24324. push(`export `);
  24325. }
  24326. }
  24327. function genAssets(assets, type, { helper, push, newline, isTS }) {
  24328. const resolver = helper(
  24329. type === "component" ? RESOLVE_COMPONENT : RESOLVE_DIRECTIVE
  24330. );
  24331. for (let i = 0; i < assets.length; i++) {
  24332. let id = assets[i];
  24333. const maybeSelfReference = id.endsWith("__self");
  24334. if (maybeSelfReference) {
  24335. id = id.slice(0, -6);
  24336. }
  24337. push(
  24338. `const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`
  24339. );
  24340. if (i < assets.length - 1) {
  24341. newline();
  24342. }
  24343. }
  24344. }
  24345. function genHoists(hoists, context) {
  24346. if (!hoists.length) {
  24347. return;
  24348. }
  24349. context.pure = true;
  24350. const { push, newline } = context;
  24351. newline();
  24352. for (let i = 0; i < hoists.length; i++) {
  24353. const exp = hoists[i];
  24354. if (exp) {
  24355. push(`const _hoisted_${i + 1} = `);
  24356. genNode(exp, context);
  24357. newline();
  24358. }
  24359. }
  24360. context.pure = false;
  24361. }
  24362. function genImports(importsOptions, context) {
  24363. if (!importsOptions.length) {
  24364. return;
  24365. }
  24366. importsOptions.forEach((imports) => {
  24367. context.push(`import `);
  24368. genNode(imports.exp, context);
  24369. context.push(` from '${imports.path}'`);
  24370. context.newline();
  24371. });
  24372. }
  24373. function isText(n) {
  24374. return isString$1(n) || n.type === 4 || n.type === 2 || n.type === 5 || n.type === 8;
  24375. }
  24376. function genNodeListAsArray(nodes, context) {
  24377. const multilines = nodes.length > 3 || nodes.some((n) => isArray$3(n) || !isText(n));
  24378. context.push(`[`);
  24379. multilines && context.indent();
  24380. genNodeList(nodes, context, multilines);
  24381. multilines && context.deindent();
  24382. context.push(`]`);
  24383. }
  24384. function genNodeList(nodes, context, multilines = false, comma = true) {
  24385. const { push, newline } = context;
  24386. for (let i = 0; i < nodes.length; i++) {
  24387. const node = nodes[i];
  24388. if (isString$1(node)) {
  24389. push(node, -3 /* Unknown */);
  24390. } else if (isArray$3(node)) {
  24391. genNodeListAsArray(node, context);
  24392. } else {
  24393. genNode(node, context);
  24394. }
  24395. if (i < nodes.length - 1) {
  24396. if (multilines) {
  24397. comma && push(",");
  24398. newline();
  24399. } else {
  24400. comma && push(", ");
  24401. }
  24402. }
  24403. }
  24404. }
  24405. function genNode(node, context) {
  24406. if (isString$1(node)) {
  24407. context.push(node, -3 /* Unknown */);
  24408. return;
  24409. }
  24410. if (isSymbol$1(node)) {
  24411. context.push(context.helper(node));
  24412. return;
  24413. }
  24414. switch (node.type) {
  24415. case 1:
  24416. case 9:
  24417. case 11:
  24418. assert(
  24419. node.codegenNode != null,
  24420. `Codegen node is missing for element/if/for node. Apply appropriate transforms first.`
  24421. );
  24422. genNode(node.codegenNode, context);
  24423. break;
  24424. case 2:
  24425. genText(node, context);
  24426. break;
  24427. case 4:
  24428. genExpression(node, context);
  24429. break;
  24430. case 5:
  24431. genInterpolation(node, context);
  24432. break;
  24433. case 12:
  24434. genNode(node.codegenNode, context);
  24435. break;
  24436. case 8:
  24437. genCompoundExpression(node, context);
  24438. break;
  24439. case 3:
  24440. genComment(node, context);
  24441. break;
  24442. case 13:
  24443. genVNodeCall(node, context);
  24444. break;
  24445. case 14:
  24446. genCallExpression(node, context);
  24447. break;
  24448. case 15:
  24449. genObjectExpression(node, context);
  24450. break;
  24451. case 17:
  24452. genArrayExpression(node, context);
  24453. break;
  24454. case 18:
  24455. genFunctionExpression(node, context);
  24456. break;
  24457. case 19:
  24458. genConditionalExpression(node, context);
  24459. break;
  24460. case 20:
  24461. genCacheExpression(node, context);
  24462. break;
  24463. case 21:
  24464. genNodeList(node.body, context, true, false);
  24465. break;
  24466. // SSR only types
  24467. case 22:
  24468. genTemplateLiteral(node, context);
  24469. break;
  24470. case 23:
  24471. genIfStatement(node, context);
  24472. break;
  24473. case 24:
  24474. genAssignmentExpression(node, context);
  24475. break;
  24476. case 25:
  24477. genSequenceExpression(node, context);
  24478. break;
  24479. case 26:
  24480. genReturnStatement(node, context);
  24481. break;
  24482. /* v8 ignore start */
  24483. case 10:
  24484. break;
  24485. default:
  24486. {
  24487. assert(false, `unhandled codegen node type: ${node.type}`);
  24488. const exhaustiveCheck = node;
  24489. return exhaustiveCheck;
  24490. }
  24491. }
  24492. }
  24493. function genText(node, context) {
  24494. context.push(JSON.stringify(node.content), -3 /* Unknown */, node);
  24495. }
  24496. function genExpression(node, context) {
  24497. const { content, isStatic } = node;
  24498. context.push(
  24499. isStatic ? JSON.stringify(content) : content,
  24500. -3 /* Unknown */,
  24501. node
  24502. );
  24503. }
  24504. function genInterpolation(node, context) {
  24505. const { push, helper, pure } = context;
  24506. if (pure) push(PURE_ANNOTATION);
  24507. push(`${helper(TO_DISPLAY_STRING)}(`);
  24508. genNode(node.content, context);
  24509. push(`)`);
  24510. }
  24511. function genCompoundExpression(node, context) {
  24512. for (let i = 0; i < node.children.length; i++) {
  24513. const child = node.children[i];
  24514. if (isString$1(child)) {
  24515. context.push(child, -3 /* Unknown */);
  24516. } else {
  24517. genNode(child, context);
  24518. }
  24519. }
  24520. }
  24521. function genExpressionAsPropertyKey(node, context) {
  24522. const { push } = context;
  24523. if (node.type === 8) {
  24524. push(`[`);
  24525. genCompoundExpression(node, context);
  24526. push(`]`);
  24527. } else if (node.isStatic) {
  24528. const text = isSimpleIdentifier(node.content) ? node.content : JSON.stringify(node.content);
  24529. push(text, -2 /* None */, node);
  24530. } else {
  24531. push(`[${node.content}]`, -3 /* Unknown */, node);
  24532. }
  24533. }
  24534. function genComment(node, context) {
  24535. const { push, helper, pure } = context;
  24536. if (pure) {
  24537. push(PURE_ANNOTATION);
  24538. }
  24539. push(
  24540. `${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`,
  24541. -3 /* Unknown */,
  24542. node
  24543. );
  24544. }
  24545. function genVNodeCall(node, context) {
  24546. const { push, helper, pure } = context;
  24547. const {
  24548. tag,
  24549. props,
  24550. children,
  24551. patchFlag,
  24552. dynamicProps,
  24553. directives,
  24554. isBlock,
  24555. disableTracking,
  24556. isComponent
  24557. } = node;
  24558. let patchFlagString;
  24559. if (patchFlag) {
  24560. {
  24561. if (patchFlag < 0) {
  24562. patchFlagString = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
  24563. } else {
  24564. const flagNames = Object.keys(PatchFlagNames).map(Number).filter((n) => n > 0 && patchFlag & n).map((n) => PatchFlagNames[n]).join(`, `);
  24565. patchFlagString = patchFlag + ` /* ${flagNames} */`;
  24566. }
  24567. }
  24568. }
  24569. if (directives) {
  24570. push(helper(WITH_DIRECTIVES) + `(`);
  24571. }
  24572. if (isBlock) {
  24573. push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
  24574. }
  24575. if (pure) {
  24576. push(PURE_ANNOTATION);
  24577. }
  24578. const callHelper = isBlock ? getVNodeBlockHelper(context.inSSR, isComponent) : getVNodeHelper(context.inSSR, isComponent);
  24579. push(helper(callHelper) + `(`, -2 /* None */, node);
  24580. genNodeList(
  24581. genNullableArgs([tag, props, children, patchFlagString, dynamicProps]),
  24582. context
  24583. );
  24584. push(`)`);
  24585. if (isBlock) {
  24586. push(`)`);
  24587. }
  24588. if (directives) {
  24589. push(`, `);
  24590. genNode(directives, context);
  24591. push(`)`);
  24592. }
  24593. }
  24594. function genNullableArgs(args) {
  24595. let i = args.length;
  24596. while (i--) {
  24597. if (args[i] != null) break;
  24598. }
  24599. return args.slice(0, i + 1).map((arg) => arg || `null`);
  24600. }
  24601. function genCallExpression(node, context) {
  24602. const { push, helper, pure } = context;
  24603. const callee = isString$1(node.callee) ? node.callee : helper(node.callee);
  24604. if (pure) {
  24605. push(PURE_ANNOTATION);
  24606. }
  24607. push(callee + `(`, -2 /* None */, node);
  24608. genNodeList(node.arguments, context);
  24609. push(`)`);
  24610. }
  24611. function genObjectExpression(node, context) {
  24612. const { push, indent, deindent, newline } = context;
  24613. const { properties } = node;
  24614. if (!properties.length) {
  24615. push(`{}`, -2 /* None */, node);
  24616. return;
  24617. }
  24618. const multilines = properties.length > 1 || properties.some((p) => p.value.type !== 4);
  24619. push(multilines ? `{` : `{ `);
  24620. multilines && indent();
  24621. for (let i = 0; i < properties.length; i++) {
  24622. const { key, value } = properties[i];
  24623. genExpressionAsPropertyKey(key, context);
  24624. push(`: `);
  24625. genNode(value, context);
  24626. if (i < properties.length - 1) {
  24627. push(`,`);
  24628. newline();
  24629. }
  24630. }
  24631. multilines && deindent();
  24632. push(multilines ? `}` : ` }`);
  24633. }
  24634. function genArrayExpression(node, context) {
  24635. genNodeListAsArray(node.elements, context);
  24636. }
  24637. function genFunctionExpression(node, context) {
  24638. const { push, indent, deindent } = context;
  24639. const { params, returns, body, newline, isSlot } = node;
  24640. if (isSlot) {
  24641. push(`_${helperNameMap[WITH_CTX]}(`);
  24642. }
  24643. push(`(`, -2 /* None */, node);
  24644. if (isArray$3(params)) {
  24645. genNodeList(params, context);
  24646. } else if (params) {
  24647. genNode(params, context);
  24648. }
  24649. push(`) => `);
  24650. if (newline || body) {
  24651. push(`{`);
  24652. indent();
  24653. }
  24654. if (returns) {
  24655. if (newline) {
  24656. push(`return `);
  24657. }
  24658. if (isArray$3(returns)) {
  24659. genNodeListAsArray(returns, context);
  24660. } else {
  24661. genNode(returns, context);
  24662. }
  24663. } else if (body) {
  24664. genNode(body, context);
  24665. }
  24666. if (newline || body) {
  24667. deindent();
  24668. push(`}`);
  24669. }
  24670. if (isSlot) {
  24671. push(`)`);
  24672. }
  24673. }
  24674. function genConditionalExpression(node, context) {
  24675. const { test, consequent, alternate, newline: needNewline } = node;
  24676. const { push, indent, deindent, newline } = context;
  24677. if (test.type === 4) {
  24678. const needsParens = !isSimpleIdentifier(test.content);
  24679. needsParens && push(`(`);
  24680. genExpression(test, context);
  24681. needsParens && push(`)`);
  24682. } else {
  24683. push(`(`);
  24684. genNode(test, context);
  24685. push(`)`);
  24686. }
  24687. needNewline && indent();
  24688. context.indentLevel++;
  24689. needNewline || push(` `);
  24690. push(`? `);
  24691. genNode(consequent, context);
  24692. context.indentLevel--;
  24693. needNewline && newline();
  24694. needNewline || push(` `);
  24695. push(`: `);
  24696. const isNested = alternate.type === 19;
  24697. if (!isNested) {
  24698. context.indentLevel++;
  24699. }
  24700. genNode(alternate, context);
  24701. if (!isNested) {
  24702. context.indentLevel--;
  24703. }
  24704. needNewline && deindent(
  24705. true
  24706. /* without newline */
  24707. );
  24708. }
  24709. function genCacheExpression(node, context) {
  24710. const { push, helper, indent, deindent, newline } = context;
  24711. const { needPauseTracking, needArraySpread } = node;
  24712. if (needArraySpread) {
  24713. push(`[...(`);
  24714. }
  24715. push(`_cache[${node.index}] || (`);
  24716. if (needPauseTracking) {
  24717. indent();
  24718. push(`${helper(SET_BLOCK_TRACKING)}(-1`);
  24719. if (node.inVOnce) push(`, true`);
  24720. push(`),`);
  24721. newline();
  24722. push(`(`);
  24723. }
  24724. push(`_cache[${node.index}] = `);
  24725. genNode(node.value, context);
  24726. if (needPauseTracking) {
  24727. push(`).cacheIndex = ${node.index},`);
  24728. newline();
  24729. push(`${helper(SET_BLOCK_TRACKING)}(1),`);
  24730. newline();
  24731. push(`_cache[${node.index}]`);
  24732. deindent();
  24733. }
  24734. push(`)`);
  24735. if (needArraySpread) {
  24736. push(`)]`);
  24737. }
  24738. }
  24739. function genTemplateLiteral(node, context) {
  24740. const { push, indent, deindent } = context;
  24741. push("`");
  24742. const l = node.elements.length;
  24743. const multilines = l > 3;
  24744. for (let i = 0; i < l; i++) {
  24745. const e = node.elements[i];
  24746. if (isString$1(e)) {
  24747. push(e.replace(/(`|\$|\\)/g, "\\$1"), -3 /* Unknown */);
  24748. } else {
  24749. push("${");
  24750. if (multilines) indent();
  24751. genNode(e, context);
  24752. if (multilines) deindent();
  24753. push("}");
  24754. }
  24755. }
  24756. push("`");
  24757. }
  24758. function genIfStatement(node, context) {
  24759. const { push, indent, deindent } = context;
  24760. const { test, consequent, alternate } = node;
  24761. push(`if (`);
  24762. genNode(test, context);
  24763. push(`) {`);
  24764. indent();
  24765. genNode(consequent, context);
  24766. deindent();
  24767. push(`}`);
  24768. if (alternate) {
  24769. push(` else `);
  24770. if (alternate.type === 23) {
  24771. genIfStatement(alternate, context);
  24772. } else {
  24773. push(`{`);
  24774. indent();
  24775. genNode(alternate, context);
  24776. deindent();
  24777. push(`}`);
  24778. }
  24779. }
  24780. }
  24781. function genAssignmentExpression(node, context) {
  24782. genNode(node.left, context);
  24783. context.push(` = `);
  24784. genNode(node.right, context);
  24785. }
  24786. function genSequenceExpression(node, context) {
  24787. context.push(`(`);
  24788. genNodeList(node.expressions, context);
  24789. context.push(`)`);
  24790. }
  24791. function genReturnStatement({ returns }, context) {
  24792. context.push(`return `);
  24793. if (isArray$3(returns)) {
  24794. genNodeListAsArray(returns, context);
  24795. } else {
  24796. genNode(returns, context);
  24797. }
  24798. }
  24799. const isLiteralWhitelisted = /* @__PURE__ */ makeMap("true,false,null,this");
  24800. const transformExpression = (node, context) => {
  24801. if (node.type === 5) {
  24802. node.content = processExpression(
  24803. node.content,
  24804. context
  24805. );
  24806. } else if (node.type === 1) {
  24807. const memo = findDir(node, "memo");
  24808. for (let i = 0; i < node.props.length; i++) {
  24809. const dir = node.props[i];
  24810. if (dir.type === 7 && dir.name !== "for") {
  24811. const exp = dir.exp;
  24812. const arg = dir.arg;
  24813. if (exp && exp.type === 4 && !(dir.name === "on" && arg) && // key has been processed in transformFor(vMemo + vFor)
  24814. !(memo && arg && arg.type === 4 && arg.content === "key")) {
  24815. dir.exp = processExpression(
  24816. exp,
  24817. context,
  24818. // slot args must be processed as function params
  24819. dir.name === "slot"
  24820. );
  24821. }
  24822. if (arg && arg.type === 4 && !arg.isStatic) {
  24823. dir.arg = processExpression(arg, context);
  24824. }
  24825. }
  24826. }
  24827. }
  24828. };
  24829. function processExpression(node, context, asParams = false, asRawStatements = false, localVars = Object.create(context.identifiers)) {
  24830. if (!context.prefixIdentifiers || !node.content.trim()) {
  24831. return node;
  24832. }
  24833. const { inline, bindingMetadata } = context;
  24834. const rewriteIdentifier = (raw, parent, id) => {
  24835. const type = hasOwn(bindingMetadata, raw) && bindingMetadata[raw];
  24836. if (inline) {
  24837. const isAssignmentLVal = parent && parent.type === "AssignmentExpression" && parent.left === id;
  24838. const isUpdateArg = parent && parent.type === "UpdateExpression" && parent.argument === id;
  24839. const isDestructureAssignment = parent && isInDestructureAssignment(parent, parentStack);
  24840. const isNewExpression = parent && isInNewExpression(parentStack);
  24841. const wrapWithUnref = (raw2) => {
  24842. const wrapped = `${context.helperString(UNREF)}(${raw2})`;
  24843. return isNewExpression ? `(${wrapped})` : wrapped;
  24844. };
  24845. if (isConst(type) || type === "setup-reactive-const" || localVars[raw]) {
  24846. return raw;
  24847. } else if (type === "setup-ref") {
  24848. return `${raw}.value`;
  24849. } else if (type === "setup-maybe-ref") {
  24850. return isAssignmentLVal || isUpdateArg || isDestructureAssignment ? `${raw}.value` : wrapWithUnref(raw);
  24851. } else if (type === "setup-let") {
  24852. if (isAssignmentLVal) {
  24853. const { right: rVal, operator } = parent;
  24854. const rExp = rawExp.slice(rVal.start - 1, rVal.end - 1);
  24855. const rExpString = stringifyExpression(
  24856. processExpression(
  24857. createSimpleExpression(rExp, false),
  24858. context,
  24859. false,
  24860. false,
  24861. knownIds
  24862. )
  24863. );
  24864. return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore
  24865. ` : ``} ? ${raw}.value ${operator} ${rExpString} : ${raw}`;
  24866. } else if (isUpdateArg) {
  24867. id.start = parent.start;
  24868. id.end = parent.end;
  24869. const { prefix: isPrefix, operator } = parent;
  24870. const prefix = isPrefix ? operator : ``;
  24871. const postfix = isPrefix ? `` : operator;
  24872. return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore
  24873. ` : ``} ? ${prefix}${raw}.value${postfix} : ${prefix}${raw}${postfix}`;
  24874. } else if (isDestructureAssignment) {
  24875. return raw;
  24876. } else {
  24877. return wrapWithUnref(raw);
  24878. }
  24879. } else if (type === "props") {
  24880. return genPropsAccessExp(raw);
  24881. } else if (type === "props-aliased") {
  24882. return genPropsAccessExp(bindingMetadata.__propsAliases[raw]);
  24883. }
  24884. } else {
  24885. if (type && type.startsWith("setup") || type === "literal-const") {
  24886. return `$setup.${raw}`;
  24887. } else if (type === "props-aliased") {
  24888. return `$props['${bindingMetadata.__propsAliases[raw]}']`;
  24889. } else if (type) {
  24890. return `$${type}.${raw}`;
  24891. }
  24892. }
  24893. return `_ctx.${raw}`;
  24894. };
  24895. const rawExp = node.content;
  24896. let ast = node.ast;
  24897. if (ast === false) {
  24898. return node;
  24899. }
  24900. if (ast === null || !ast && isSimpleIdentifier(rawExp)) {
  24901. const isScopeVarReference = context.identifiers[rawExp];
  24902. const isAllowedGlobal = isGloballyAllowed(rawExp);
  24903. const isLiteral = isLiteralWhitelisted(rawExp);
  24904. if (!asParams && !isScopeVarReference && !isLiteral && (!isAllowedGlobal || bindingMetadata[rawExp])) {
  24905. if (isConst(bindingMetadata[rawExp])) {
  24906. node.constType = 1;
  24907. }
  24908. node.content = rewriteIdentifier(rawExp);
  24909. } else if (!isScopeVarReference) {
  24910. if (isLiteral) {
  24911. node.constType = 3;
  24912. } else {
  24913. node.constType = 2;
  24914. }
  24915. }
  24916. return node;
  24917. }
  24918. if (!ast) {
  24919. const source = asRawStatements ? ` ${rawExp} ` : `(${rawExp})${asParams ? `=>{}` : ``}`;
  24920. try {
  24921. ast = libExports.parseExpression(source, {
  24922. sourceType: "module",
  24923. plugins: context.expressionPlugins
  24924. });
  24925. } catch (e) {
  24926. context.onError(
  24927. createCompilerError(
  24928. 46,
  24929. node.loc,
  24930. void 0,
  24931. e.message
  24932. )
  24933. );
  24934. return node;
  24935. }
  24936. }
  24937. const ids = [];
  24938. const parentStack = [];
  24939. const knownIds = Object.create(context.identifiers);
  24940. walkIdentifiers(
  24941. ast,
  24942. (node2, parent, _, isReferenced, isLocal) => {
  24943. if (isStaticPropertyKey(node2, parent)) {
  24944. return;
  24945. }
  24946. const needPrefix = isReferenced && canPrefix(node2);
  24947. if (needPrefix && !isLocal) {
  24948. if (isStaticProperty(parent) && parent.shorthand) {
  24949. node2.prefix = `${node2.name}: `;
  24950. }
  24951. node2.name = rewriteIdentifier(node2.name, parent, node2);
  24952. ids.push(node2);
  24953. } else {
  24954. if (!(needPrefix && isLocal) && (!parent || parent.type !== "CallExpression" && parent.type !== "NewExpression" && parent.type !== "MemberExpression")) {
  24955. node2.isConstant = true;
  24956. }
  24957. ids.push(node2);
  24958. }
  24959. },
  24960. true,
  24961. // invoke on ALL identifiers
  24962. parentStack,
  24963. knownIds
  24964. );
  24965. const children = [];
  24966. ids.sort((a, b) => a.start - b.start);
  24967. ids.forEach((id, i) => {
  24968. const start = id.start - 1;
  24969. const end = id.end - 1;
  24970. const last = ids[i - 1];
  24971. const leadingText = rawExp.slice(last ? last.end - 1 : 0, start);
  24972. if (leadingText.length || id.prefix) {
  24973. children.push(leadingText + (id.prefix || ``));
  24974. }
  24975. const source = rawExp.slice(start, end);
  24976. children.push(
  24977. createSimpleExpression(
  24978. id.name,
  24979. false,
  24980. {
  24981. start: advancePositionWithClone(node.loc.start, source, start),
  24982. end: advancePositionWithClone(node.loc.start, source, end),
  24983. source
  24984. },
  24985. id.isConstant ? 3 : 0
  24986. )
  24987. );
  24988. if (i === ids.length - 1 && end < rawExp.length) {
  24989. children.push(rawExp.slice(end));
  24990. }
  24991. });
  24992. let ret;
  24993. if (children.length) {
  24994. ret = createCompoundExpression(children, node.loc);
  24995. ret.ast = ast;
  24996. } else {
  24997. ret = node;
  24998. ret.constType = 3;
  24999. }
  25000. ret.identifiers = Object.keys(knownIds);
  25001. return ret;
  25002. }
  25003. function canPrefix(id) {
  25004. if (isGloballyAllowed(id.name)) {
  25005. return false;
  25006. }
  25007. if (id.name === "require") {
  25008. return false;
  25009. }
  25010. return true;
  25011. }
  25012. function stringifyExpression(exp) {
  25013. if (isString$1(exp)) {
  25014. return exp;
  25015. } else if (exp.type === 4) {
  25016. return exp.content;
  25017. } else {
  25018. return exp.children.map(stringifyExpression).join("");
  25019. }
  25020. }
  25021. function isConst(type) {
  25022. return type === "setup-const" || type === "literal-const";
  25023. }
  25024. const transformIf = createStructuralDirectiveTransform(
  25025. /^(?:if|else|else-if)$/,
  25026. (node, dir, context) => {
  25027. return processIf(node, dir, context, (ifNode, branch, isRoot) => {
  25028. const siblings = context.parent.children;
  25029. let i = siblings.indexOf(ifNode);
  25030. let key = 0;
  25031. while (i-- >= 0) {
  25032. const sibling = siblings[i];
  25033. if (sibling && sibling.type === 9) {
  25034. key += sibling.branches.length;
  25035. }
  25036. }
  25037. return () => {
  25038. if (isRoot) {
  25039. ifNode.codegenNode = createCodegenNodeForBranch(
  25040. branch,
  25041. key,
  25042. context
  25043. );
  25044. } else {
  25045. const parentCondition = getParentCondition(ifNode.codegenNode);
  25046. parentCondition.alternate = createCodegenNodeForBranch(
  25047. branch,
  25048. key + ifNode.branches.length - 1,
  25049. context
  25050. );
  25051. }
  25052. };
  25053. });
  25054. }
  25055. );
  25056. function processIf(node, dir, context, processCodegen) {
  25057. if (dir.name !== "else" && (!dir.exp || !dir.exp.content.trim())) {
  25058. const loc = dir.exp ? dir.exp.loc : node.loc;
  25059. context.onError(
  25060. createCompilerError(28, dir.loc)
  25061. );
  25062. dir.exp = createSimpleExpression(`true`, false, loc);
  25063. }
  25064. if (context.prefixIdentifiers && dir.exp) {
  25065. dir.exp = processExpression(dir.exp, context);
  25066. }
  25067. if (dir.name === "if") {
  25068. const branch = createIfBranch(node, dir);
  25069. const ifNode = {
  25070. type: 9,
  25071. loc: cloneLoc(node.loc),
  25072. branches: [branch]
  25073. };
  25074. context.replaceNode(ifNode);
  25075. if (processCodegen) {
  25076. return processCodegen(ifNode, branch, true);
  25077. }
  25078. } else {
  25079. const siblings = context.parent.children;
  25080. const comments = [];
  25081. let i = siblings.indexOf(node);
  25082. while (i-- >= -1) {
  25083. const sibling = siblings[i];
  25084. if (sibling && isCommentOrWhitespace(sibling)) {
  25085. context.removeNode(sibling);
  25086. if (sibling.type === 3) {
  25087. comments.unshift(sibling);
  25088. }
  25089. continue;
  25090. }
  25091. if (sibling && sibling.type === 9) {
  25092. if ((dir.name === "else-if" || dir.name === "else") && sibling.branches[sibling.branches.length - 1].condition === void 0) {
  25093. context.onError(
  25094. createCompilerError(30, node.loc)
  25095. );
  25096. }
  25097. context.removeNode();
  25098. const branch = createIfBranch(node, dir);
  25099. if (comments.length && // #3619 ignore comments if the v-if is direct child of <transition>
  25100. !(context.parent && context.parent.type === 1 && (context.parent.tag === "transition" || context.parent.tag === "Transition"))) {
  25101. branch.children = [...comments, ...branch.children];
  25102. }
  25103. {
  25104. const key = branch.userKey;
  25105. if (key) {
  25106. sibling.branches.forEach(({ userKey }) => {
  25107. if (isSameKey(userKey, key)) {
  25108. context.onError(
  25109. createCompilerError(
  25110. 29,
  25111. branch.userKey.loc
  25112. )
  25113. );
  25114. }
  25115. });
  25116. }
  25117. }
  25118. sibling.branches.push(branch);
  25119. const onExit = processCodegen && processCodegen(sibling, branch, false);
  25120. traverseNode(branch, context);
  25121. if (onExit) onExit();
  25122. context.currentNode = null;
  25123. } else {
  25124. context.onError(
  25125. createCompilerError(30, node.loc)
  25126. );
  25127. }
  25128. break;
  25129. }
  25130. }
  25131. }
  25132. function createIfBranch(node, dir) {
  25133. const isTemplateIf = node.tagType === 3;
  25134. return {
  25135. type: 10,
  25136. loc: node.loc,
  25137. condition: dir.name === "else" ? void 0 : dir.exp,
  25138. children: isTemplateIf && !findDir(node, "for") ? node.children : [node],
  25139. userKey: findProp(node, `key`),
  25140. isTemplateIf
  25141. };
  25142. }
  25143. function createCodegenNodeForBranch(branch, keyIndex, context) {
  25144. if (branch.condition) {
  25145. return createConditionalExpression(
  25146. branch.condition,
  25147. createChildrenCodegenNode(branch, keyIndex, context),
  25148. // make sure to pass in asBlock: true so that the comment node call
  25149. // closes the current block.
  25150. createCallExpression(context.helper(CREATE_COMMENT), [
  25151. '"v-if"' ,
  25152. "true"
  25153. ])
  25154. );
  25155. } else {
  25156. return createChildrenCodegenNode(branch, keyIndex, context);
  25157. }
  25158. }
  25159. function createChildrenCodegenNode(branch, keyIndex, context) {
  25160. const { helper } = context;
  25161. const keyProperty = createObjectProperty(
  25162. `key`,
  25163. createSimpleExpression(
  25164. `${keyIndex}`,
  25165. false,
  25166. locStub,
  25167. 2
  25168. )
  25169. );
  25170. const { children } = branch;
  25171. const firstChild = children[0];
  25172. const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1;
  25173. if (needFragmentWrapper) {
  25174. if (children.length === 1 && firstChild.type === 11) {
  25175. const vnodeCall = firstChild.codegenNode;
  25176. injectProp(vnodeCall, keyProperty, context);
  25177. return vnodeCall;
  25178. } else {
  25179. let patchFlag = 64;
  25180. if (!branch.isTemplateIf && children.filter((c) => c.type !== 3).length === 1) {
  25181. patchFlag |= 2048;
  25182. }
  25183. return createVNodeCall(
  25184. context,
  25185. helper(FRAGMENT),
  25186. createObjectExpression([keyProperty]),
  25187. children,
  25188. patchFlag,
  25189. void 0,
  25190. void 0,
  25191. true,
  25192. false,
  25193. false,
  25194. branch.loc
  25195. );
  25196. }
  25197. } else {
  25198. const ret = firstChild.codegenNode;
  25199. const vnodeCall = getMemoedVNodeCall(ret);
  25200. if (vnodeCall.type === 13) {
  25201. convertToBlock(vnodeCall, context);
  25202. }
  25203. injectProp(vnodeCall, keyProperty, context);
  25204. return ret;
  25205. }
  25206. }
  25207. function isSameKey(a, b) {
  25208. if (!a || a.type !== b.type) {
  25209. return false;
  25210. }
  25211. if (a.type === 6) {
  25212. if (a.value.content !== b.value.content) {
  25213. return false;
  25214. }
  25215. } else {
  25216. const exp = a.exp;
  25217. const branchExp = b.exp;
  25218. if (exp.type !== branchExp.type) {
  25219. return false;
  25220. }
  25221. if (exp.type !== 4 || exp.isStatic !== branchExp.isStatic || exp.content !== branchExp.content) {
  25222. return false;
  25223. }
  25224. }
  25225. return true;
  25226. }
  25227. function getParentCondition(node) {
  25228. while (true) {
  25229. if (node.type === 19) {
  25230. if (node.alternate.type === 19) {
  25231. node = node.alternate;
  25232. } else {
  25233. return node;
  25234. }
  25235. } else if (node.type === 20) {
  25236. node = node.value;
  25237. }
  25238. }
  25239. }
  25240. const transformFor = createStructuralDirectiveTransform(
  25241. "for",
  25242. (node, dir, context) => {
  25243. const { helper, removeHelper } = context;
  25244. return processFor(node, dir, context, (forNode) => {
  25245. const renderExp = createCallExpression(helper(RENDER_LIST), [
  25246. forNode.source
  25247. ]);
  25248. const isTemplate = isTemplateNode(node);
  25249. const memo = findDir(node, "memo");
  25250. const keyProp = findProp(node, `key`, false, true);
  25251. const isDirKey = keyProp && keyProp.type === 7;
  25252. let keyExp = keyProp && (keyProp.type === 6 ? keyProp.value ? createSimpleExpression(keyProp.value.content, true) : void 0 : keyProp.exp);
  25253. const keyProperty = keyExp ? createObjectProperty(`key`, keyExp) : null;
  25254. {
  25255. if (isTemplate && memo) {
  25256. memo.exp = processExpression(
  25257. memo.exp,
  25258. context
  25259. );
  25260. }
  25261. if ((isTemplate || memo) && keyProperty && isDirKey) {
  25262. keyExp = keyProp.exp = keyProperty.value = processExpression(
  25263. keyProperty.value,
  25264. context
  25265. );
  25266. }
  25267. }
  25268. const isStableFragment = forNode.source.type === 4 && forNode.source.constType > 0;
  25269. const fragmentFlag = isStableFragment ? 64 : keyProp ? 128 : 256;
  25270. forNode.codegenNode = createVNodeCall(
  25271. context,
  25272. helper(FRAGMENT),
  25273. void 0,
  25274. renderExp,
  25275. fragmentFlag,
  25276. void 0,
  25277. void 0,
  25278. true,
  25279. !isStableFragment,
  25280. false,
  25281. node.loc
  25282. );
  25283. return () => {
  25284. let childBlock;
  25285. const { children } = forNode;
  25286. if (isTemplate) {
  25287. node.children.some((c) => {
  25288. if (c.type === 1) {
  25289. const key = findProp(c, "key");
  25290. if (key) {
  25291. context.onError(
  25292. createCompilerError(
  25293. 33,
  25294. key.loc
  25295. )
  25296. );
  25297. return true;
  25298. }
  25299. }
  25300. });
  25301. }
  25302. const needFragmentWrapper = children.length !== 1 || children[0].type !== 1;
  25303. const slotOutlet = isSlotOutlet(node) ? node : isTemplate && node.children.length === 1 && isSlotOutlet(node.children[0]) ? node.children[0] : null;
  25304. if (slotOutlet) {
  25305. childBlock = slotOutlet.codegenNode;
  25306. if (isTemplate && keyProperty) {
  25307. injectProp(childBlock, keyProperty, context);
  25308. }
  25309. } else if (needFragmentWrapper) {
  25310. childBlock = createVNodeCall(
  25311. context,
  25312. helper(FRAGMENT),
  25313. keyProperty ? createObjectExpression([keyProperty]) : void 0,
  25314. node.children,
  25315. 64,
  25316. void 0,
  25317. void 0,
  25318. true,
  25319. void 0,
  25320. false
  25321. );
  25322. } else {
  25323. childBlock = children[0].codegenNode;
  25324. if (isTemplate && keyProperty) {
  25325. injectProp(childBlock, keyProperty, context);
  25326. }
  25327. if (childBlock.isBlock !== !isStableFragment) {
  25328. if (childBlock.isBlock) {
  25329. removeHelper(OPEN_BLOCK);
  25330. removeHelper(
  25331. getVNodeBlockHelper(context.inSSR, childBlock.isComponent)
  25332. );
  25333. } else {
  25334. removeHelper(
  25335. getVNodeHelper(context.inSSR, childBlock.isComponent)
  25336. );
  25337. }
  25338. }
  25339. childBlock.isBlock = !isStableFragment;
  25340. if (childBlock.isBlock) {
  25341. helper(OPEN_BLOCK);
  25342. helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  25343. } else {
  25344. helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  25345. }
  25346. }
  25347. if (memo) {
  25348. const loop = createFunctionExpression(
  25349. createForLoopParams(forNode.parseResult, [
  25350. createSimpleExpression(`_cached`)
  25351. ])
  25352. );
  25353. loop.body = createBlockStatement([
  25354. createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
  25355. createCompoundExpression([
  25356. `if (_cached && _cached.el`,
  25357. ...keyExp ? [` && _cached.key === `, keyExp] : [],
  25358. ` && ${context.helperString(
  25359. IS_MEMO_SAME
  25360. )}(_cached, _memo)) return _cached`
  25361. ]),
  25362. createCompoundExpression([`const _item = `, childBlock]),
  25363. createSimpleExpression(`_item.memo = _memo`),
  25364. createSimpleExpression(`return _item`)
  25365. ]);
  25366. renderExp.arguments.push(
  25367. loop,
  25368. createSimpleExpression(`_cache`),
  25369. createSimpleExpression(String(context.cached.length))
  25370. );
  25371. context.cached.push(null);
  25372. } else {
  25373. renderExp.arguments.push(
  25374. createFunctionExpression(
  25375. createForLoopParams(forNode.parseResult),
  25376. childBlock,
  25377. true
  25378. )
  25379. );
  25380. }
  25381. };
  25382. });
  25383. }
  25384. );
  25385. function processFor(node, dir, context, processCodegen) {
  25386. if (!dir.exp) {
  25387. context.onError(
  25388. createCompilerError(31, dir.loc)
  25389. );
  25390. return;
  25391. }
  25392. const parseResult = dir.forParseResult;
  25393. if (!parseResult) {
  25394. context.onError(
  25395. createCompilerError(32, dir.loc)
  25396. );
  25397. return;
  25398. }
  25399. finalizeForParseResult(parseResult, context);
  25400. const { addIdentifiers, removeIdentifiers, scopes } = context;
  25401. const { source, value, key, index } = parseResult;
  25402. const forNode = {
  25403. type: 11,
  25404. loc: dir.loc,
  25405. source,
  25406. valueAlias: value,
  25407. keyAlias: key,
  25408. objectIndexAlias: index,
  25409. parseResult,
  25410. children: isTemplateNode(node) ? node.children : [node]
  25411. };
  25412. context.replaceNode(forNode);
  25413. scopes.vFor++;
  25414. if (context.prefixIdentifiers) {
  25415. value && addIdentifiers(value);
  25416. key && addIdentifiers(key);
  25417. index && addIdentifiers(index);
  25418. }
  25419. const onExit = processCodegen && processCodegen(forNode);
  25420. return () => {
  25421. scopes.vFor--;
  25422. if (context.prefixIdentifiers) {
  25423. value && removeIdentifiers(value);
  25424. key && removeIdentifiers(key);
  25425. index && removeIdentifiers(index);
  25426. }
  25427. if (onExit) onExit();
  25428. };
  25429. }
  25430. function finalizeForParseResult(result, context) {
  25431. if (result.finalized) return;
  25432. if (context.prefixIdentifiers) {
  25433. result.source = processExpression(
  25434. result.source,
  25435. context
  25436. );
  25437. if (result.key) {
  25438. result.key = processExpression(
  25439. result.key,
  25440. context,
  25441. true
  25442. );
  25443. }
  25444. if (result.index) {
  25445. result.index = processExpression(
  25446. result.index,
  25447. context,
  25448. true
  25449. );
  25450. }
  25451. if (result.value) {
  25452. result.value = processExpression(
  25453. result.value,
  25454. context,
  25455. true
  25456. );
  25457. }
  25458. }
  25459. result.finalized = true;
  25460. }
  25461. function createForLoopParams({ value, key, index }, memoArgs = []) {
  25462. return createParamsList([value, key, index, ...memoArgs]);
  25463. }
  25464. function createParamsList(args) {
  25465. let i = args.length;
  25466. while (i--) {
  25467. if (args[i]) break;
  25468. }
  25469. return args.slice(0, i + 1).map((arg, i2) => arg || createSimpleExpression(`_`.repeat(i2 + 1), false));
  25470. }
  25471. const defaultFallback = createSimpleExpression(`undefined`, false);
  25472. const trackSlotScopes = (node, context) => {
  25473. if (node.type === 1 && (node.tagType === 1 || node.tagType === 3)) {
  25474. const vSlot = findDir(node, "slot");
  25475. if (vSlot) {
  25476. const slotProps = vSlot.exp;
  25477. if (context.prefixIdentifiers) {
  25478. slotProps && context.addIdentifiers(slotProps);
  25479. }
  25480. context.scopes.vSlot++;
  25481. return () => {
  25482. if (context.prefixIdentifiers) {
  25483. slotProps && context.removeIdentifiers(slotProps);
  25484. }
  25485. context.scopes.vSlot--;
  25486. };
  25487. }
  25488. }
  25489. };
  25490. const trackVForSlotScopes = (node, context) => {
  25491. let vFor;
  25492. if (isTemplateNode(node) && node.props.some(isVSlot) && (vFor = findDir(node, "for"))) {
  25493. const result = vFor.forParseResult;
  25494. if (result) {
  25495. finalizeForParseResult(result, context);
  25496. const { value, key, index } = result;
  25497. const { addIdentifiers, removeIdentifiers } = context;
  25498. value && addIdentifiers(value);
  25499. key && addIdentifiers(key);
  25500. index && addIdentifiers(index);
  25501. return () => {
  25502. value && removeIdentifiers(value);
  25503. key && removeIdentifiers(key);
  25504. index && removeIdentifiers(index);
  25505. };
  25506. }
  25507. }
  25508. };
  25509. const buildClientSlotFn = (props, _vForExp, children, loc) => createFunctionExpression(
  25510. props,
  25511. children,
  25512. false,
  25513. true,
  25514. children.length ? children[0].loc : loc
  25515. );
  25516. function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
  25517. context.helper(WITH_CTX);
  25518. const { children, loc } = node;
  25519. const slotsProperties = [];
  25520. const dynamicSlots = [];
  25521. let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
  25522. if (!context.ssr && context.prefixIdentifiers) {
  25523. hasDynamicSlots = node.props.some(
  25524. (prop) => isVSlot(prop) && (hasScopeRef(prop.arg, context.identifiers) || hasScopeRef(prop.exp, context.identifiers))
  25525. ) || children.some((child) => hasScopeRef(child, context.identifiers));
  25526. }
  25527. const onComponentSlot = findDir(node, "slot", true);
  25528. if (onComponentSlot) {
  25529. const { arg, exp } = onComponentSlot;
  25530. if (arg && !isStaticExp(arg)) {
  25531. hasDynamicSlots = true;
  25532. }
  25533. slotsProperties.push(
  25534. createObjectProperty(
  25535. arg || createSimpleExpression("default", true),
  25536. buildSlotFn(exp, void 0, children, loc)
  25537. )
  25538. );
  25539. }
  25540. let hasTemplateSlots = false;
  25541. let hasNamedDefaultSlot = false;
  25542. const implicitDefaultChildren = [];
  25543. const seenSlotNames = /* @__PURE__ */ new Set();
  25544. let conditionalBranchIndex = 0;
  25545. for (let i = 0; i < children.length; i++) {
  25546. const slotElement = children[i];
  25547. let slotDir;
  25548. if (!isTemplateNode(slotElement) || !(slotDir = findDir(slotElement, "slot", true))) {
  25549. if (slotElement.type !== 3) {
  25550. implicitDefaultChildren.push(slotElement);
  25551. }
  25552. continue;
  25553. }
  25554. if (onComponentSlot) {
  25555. context.onError(
  25556. createCompilerError(37, slotDir.loc)
  25557. );
  25558. break;
  25559. }
  25560. hasTemplateSlots = true;
  25561. const { children: slotChildren, loc: slotLoc } = slotElement;
  25562. const {
  25563. arg: slotName = createSimpleExpression(`default`, true),
  25564. exp: slotProps,
  25565. loc: dirLoc
  25566. } = slotDir;
  25567. let staticSlotName;
  25568. if (isStaticExp(slotName)) {
  25569. staticSlotName = slotName ? slotName.content : `default`;
  25570. } else {
  25571. hasDynamicSlots = true;
  25572. }
  25573. const vFor = findDir(slotElement, "for");
  25574. const slotFunction = buildSlotFn(slotProps, vFor, slotChildren, slotLoc);
  25575. let vIf;
  25576. let vElse;
  25577. if (vIf = findDir(slotElement, "if")) {
  25578. hasDynamicSlots = true;
  25579. dynamicSlots.push(
  25580. createConditionalExpression(
  25581. vIf.exp,
  25582. buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++),
  25583. defaultFallback
  25584. )
  25585. );
  25586. } else if (vElse = findDir(
  25587. slotElement,
  25588. /^else(?:-if)?$/,
  25589. true
  25590. /* allowEmpty */
  25591. )) {
  25592. let j = i;
  25593. let prev;
  25594. while (j--) {
  25595. prev = children[j];
  25596. if (!isCommentOrWhitespace(prev)) {
  25597. break;
  25598. }
  25599. }
  25600. if (prev && isTemplateNode(prev) && findDir(prev, /^(?:else-)?if$/)) {
  25601. let conditional = dynamicSlots[dynamicSlots.length - 1];
  25602. while (conditional.alternate.type === 19) {
  25603. conditional = conditional.alternate;
  25604. }
  25605. conditional.alternate = vElse.exp ? createConditionalExpression(
  25606. vElse.exp,
  25607. buildDynamicSlot(
  25608. slotName,
  25609. slotFunction,
  25610. conditionalBranchIndex++
  25611. ),
  25612. defaultFallback
  25613. ) : buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++);
  25614. } else {
  25615. context.onError(
  25616. createCompilerError(30, vElse.loc)
  25617. );
  25618. }
  25619. } else if (vFor) {
  25620. hasDynamicSlots = true;
  25621. const parseResult = vFor.forParseResult;
  25622. if (parseResult) {
  25623. finalizeForParseResult(parseResult, context);
  25624. dynamicSlots.push(
  25625. createCallExpression(context.helper(RENDER_LIST), [
  25626. parseResult.source,
  25627. createFunctionExpression(
  25628. createForLoopParams(parseResult),
  25629. buildDynamicSlot(slotName, slotFunction),
  25630. true
  25631. )
  25632. ])
  25633. );
  25634. } else {
  25635. context.onError(
  25636. createCompilerError(
  25637. 32,
  25638. vFor.loc
  25639. )
  25640. );
  25641. }
  25642. } else {
  25643. if (staticSlotName) {
  25644. if (seenSlotNames.has(staticSlotName)) {
  25645. context.onError(
  25646. createCompilerError(
  25647. 38,
  25648. dirLoc
  25649. )
  25650. );
  25651. continue;
  25652. }
  25653. seenSlotNames.add(staticSlotName);
  25654. if (staticSlotName === "default") {
  25655. hasNamedDefaultSlot = true;
  25656. }
  25657. }
  25658. slotsProperties.push(createObjectProperty(slotName, slotFunction));
  25659. }
  25660. }
  25661. if (!onComponentSlot) {
  25662. const buildDefaultSlotProperty = (props, children2) => {
  25663. const fn = buildSlotFn(props, void 0, children2, loc);
  25664. return createObjectProperty(`default`, fn);
  25665. };
  25666. if (!hasTemplateSlots) {
  25667. slotsProperties.push(buildDefaultSlotProperty(void 0, children));
  25668. } else if (implicitDefaultChildren.length && // #3766
  25669. // with whitespace: 'preserve', whitespaces between slots will end up in
  25670. // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
  25671. !implicitDefaultChildren.every(isWhitespaceText)) {
  25672. if (hasNamedDefaultSlot) {
  25673. context.onError(
  25674. createCompilerError(
  25675. 39,
  25676. implicitDefaultChildren[0].loc
  25677. )
  25678. );
  25679. } else {
  25680. slotsProperties.push(
  25681. buildDefaultSlotProperty(void 0, implicitDefaultChildren)
  25682. );
  25683. }
  25684. }
  25685. }
  25686. const slotFlag = hasDynamicSlots ? 2 : hasForwardedSlots(node.children) ? 3 : 1;
  25687. let slots = createObjectExpression(
  25688. slotsProperties.concat(
  25689. createObjectProperty(
  25690. `_`,
  25691. // 2 = compiled but dynamic = can skip normalization, but must run diff
  25692. // 1 = compiled and static = can skip normalization AND diff as optimized
  25693. createSimpleExpression(
  25694. slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ),
  25695. false
  25696. )
  25697. )
  25698. ),
  25699. loc
  25700. );
  25701. if (dynamicSlots.length) {
  25702. slots = createCallExpression(context.helper(CREATE_SLOTS), [
  25703. slots,
  25704. createArrayExpression(dynamicSlots)
  25705. ]);
  25706. }
  25707. return {
  25708. slots,
  25709. hasDynamicSlots
  25710. };
  25711. }
  25712. function buildDynamicSlot(name, fn, index) {
  25713. const props = [
  25714. createObjectProperty(`name`, name),
  25715. createObjectProperty(`fn`, fn)
  25716. ];
  25717. if (index != null) {
  25718. props.push(
  25719. createObjectProperty(`key`, createSimpleExpression(String(index), true))
  25720. );
  25721. }
  25722. return createObjectExpression(props);
  25723. }
  25724. function hasForwardedSlots(children) {
  25725. for (let i = 0; i < children.length; i++) {
  25726. const child = children[i];
  25727. switch (child.type) {
  25728. case 1:
  25729. if (child.tagType === 2 || hasForwardedSlots(child.children)) {
  25730. return true;
  25731. }
  25732. break;
  25733. case 9:
  25734. if (hasForwardedSlots(child.branches)) return true;
  25735. break;
  25736. case 10:
  25737. case 11:
  25738. if (hasForwardedSlots(child.children)) return true;
  25739. break;
  25740. }
  25741. }
  25742. return false;
  25743. }
  25744. const directiveImportMap = /* @__PURE__ */ new WeakMap();
  25745. const transformElement = (node, context) => {
  25746. return function postTransformElement() {
  25747. node = context.currentNode;
  25748. if (!(node.type === 1 && (node.tagType === 0 || node.tagType === 1))) {
  25749. return;
  25750. }
  25751. const { tag, props } = node;
  25752. const isComponent = node.tagType === 1;
  25753. let vnodeTag = isComponent ? resolveComponentType(node, context) : `"${tag}"`;
  25754. const isDynamicComponent = isObject$2(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
  25755. let vnodeProps;
  25756. let vnodeChildren;
  25757. let patchFlag = 0;
  25758. let vnodeDynamicProps;
  25759. let dynamicPropNames;
  25760. let vnodeDirectives;
  25761. let shouldUseBlock = (
  25762. // dynamic component may resolve to plain elements
  25763. isDynamicComponent || vnodeTag === TELEPORT || vnodeTag === SUSPENSE || !isComponent && // <svg> and <foreignObject> must be forced into blocks so that block
  25764. // updates inside get proper isSVG flag at runtime. (#639, #643)
  25765. // This is technically web-specific, but splitting the logic out of core
  25766. // leads to too much unnecessary complexity.
  25767. (tag === "svg" || tag === "foreignObject" || tag === "math")
  25768. );
  25769. if (props.length > 0) {
  25770. const propsBuildResult = buildProps(
  25771. node,
  25772. context,
  25773. void 0,
  25774. isComponent,
  25775. isDynamicComponent
  25776. );
  25777. vnodeProps = propsBuildResult.props;
  25778. patchFlag = propsBuildResult.patchFlag;
  25779. dynamicPropNames = propsBuildResult.dynamicPropNames;
  25780. const directives = propsBuildResult.directives;
  25781. vnodeDirectives = directives && directives.length ? createArrayExpression(
  25782. directives.map((dir) => buildDirectiveArgs(dir, context))
  25783. ) : void 0;
  25784. if (propsBuildResult.shouldUseBlock) {
  25785. shouldUseBlock = true;
  25786. }
  25787. }
  25788. if (node.children.length > 0) {
  25789. if (vnodeTag === KEEP_ALIVE) {
  25790. shouldUseBlock = true;
  25791. patchFlag |= 1024;
  25792. if (node.children.length > 1) {
  25793. context.onError(
  25794. createCompilerError(47, {
  25795. start: node.children[0].loc.start,
  25796. end: node.children[node.children.length - 1].loc.end,
  25797. source: ""
  25798. })
  25799. );
  25800. }
  25801. }
  25802. const shouldBuildAsSlots = isComponent && // Teleport is not a real component and has dedicated runtime handling
  25803. vnodeTag !== TELEPORT && // explained above.
  25804. vnodeTag !== KEEP_ALIVE;
  25805. if (shouldBuildAsSlots) {
  25806. const { slots, hasDynamicSlots } = buildSlots(node, context);
  25807. vnodeChildren = slots;
  25808. if (hasDynamicSlots) {
  25809. patchFlag |= 1024;
  25810. }
  25811. } else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
  25812. const child = node.children[0];
  25813. const type = child.type;
  25814. const hasDynamicTextChild = type === 5 || type === 8;
  25815. if (hasDynamicTextChild && getConstantType(child, context) === 0) {
  25816. patchFlag |= 1;
  25817. }
  25818. if (hasDynamicTextChild || type === 2) {
  25819. vnodeChildren = child;
  25820. } else {
  25821. vnodeChildren = node.children;
  25822. }
  25823. } else {
  25824. vnodeChildren = node.children;
  25825. }
  25826. }
  25827. if (dynamicPropNames && dynamicPropNames.length) {
  25828. vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
  25829. }
  25830. node.codegenNode = createVNodeCall(
  25831. context,
  25832. vnodeTag,
  25833. vnodeProps,
  25834. vnodeChildren,
  25835. patchFlag === 0 ? void 0 : patchFlag,
  25836. vnodeDynamicProps,
  25837. vnodeDirectives,
  25838. !!shouldUseBlock,
  25839. false,
  25840. isComponent,
  25841. node.loc
  25842. );
  25843. };
  25844. };
  25845. function resolveComponentType(node, context, ssr = false) {
  25846. let { tag } = node;
  25847. const isExplicitDynamic = isComponentTag(tag);
  25848. const isProp = findProp(
  25849. node,
  25850. "is",
  25851. false,
  25852. true
  25853. /* allow empty */
  25854. );
  25855. if (isProp) {
  25856. if (isExplicitDynamic || false) {
  25857. let exp;
  25858. if (isProp.type === 6) {
  25859. exp = isProp.value && createSimpleExpression(isProp.value.content, true);
  25860. } else {
  25861. exp = isProp.exp;
  25862. if (!exp) {
  25863. exp = createSimpleExpression(`is`, false, isProp.arg.loc);
  25864. {
  25865. exp = isProp.exp = processExpression(exp, context);
  25866. }
  25867. }
  25868. }
  25869. if (exp) {
  25870. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  25871. exp
  25872. ]);
  25873. }
  25874. } else if (isProp.type === 6 && isProp.value.content.startsWith("vue:")) {
  25875. tag = isProp.value.content.slice(4);
  25876. }
  25877. }
  25878. const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
  25879. if (builtIn) {
  25880. if (!ssr) context.helper(builtIn);
  25881. return builtIn;
  25882. }
  25883. {
  25884. const fromSetup = resolveSetupReference(tag, context);
  25885. if (fromSetup) {
  25886. return fromSetup;
  25887. }
  25888. const dotIndex = tag.indexOf(".");
  25889. if (dotIndex > 0) {
  25890. const ns = resolveSetupReference(tag.slice(0, dotIndex), context);
  25891. if (ns) {
  25892. return ns + tag.slice(dotIndex);
  25893. }
  25894. }
  25895. }
  25896. if (context.selfName && capitalize(camelize(tag)) === context.selfName) {
  25897. context.helper(RESOLVE_COMPONENT);
  25898. context.components.add(tag + `__self`);
  25899. return toValidAssetId(tag, `component`);
  25900. }
  25901. context.helper(RESOLVE_COMPONENT);
  25902. context.components.add(tag);
  25903. return toValidAssetId(tag, `component`);
  25904. }
  25905. function resolveSetupReference(name, context) {
  25906. const bindings = context.bindingMetadata;
  25907. if (!bindings || bindings.__isScriptSetup === false) {
  25908. return;
  25909. }
  25910. const camelName = camelize(name);
  25911. const PascalName = capitalize(camelName);
  25912. const checkType = (type) => {
  25913. if (bindings[name] === type) {
  25914. return name;
  25915. }
  25916. if (bindings[camelName] === type) {
  25917. return camelName;
  25918. }
  25919. if (bindings[PascalName] === type) {
  25920. return PascalName;
  25921. }
  25922. };
  25923. const fromConst = checkType("setup-const") || checkType("setup-reactive-const") || checkType("literal-const");
  25924. if (fromConst) {
  25925. return context.inline ? (
  25926. // in inline mode, const setup bindings (e.g. imports) can be used as-is
  25927. fromConst
  25928. ) : `$setup[${JSON.stringify(fromConst)}]`;
  25929. }
  25930. const fromMaybeRef = checkType("setup-let") || checkType("setup-ref") || checkType("setup-maybe-ref");
  25931. if (fromMaybeRef) {
  25932. return context.inline ? (
  25933. // setup scope bindings that may be refs need to be unrefed
  25934. `${context.helperString(UNREF)}(${fromMaybeRef})`
  25935. ) : `$setup[${JSON.stringify(fromMaybeRef)}]`;
  25936. }
  25937. const fromProps = checkType("props");
  25938. if (fromProps) {
  25939. return `${context.helperString(UNREF)}(${context.inline ? "__props" : "$props"}[${JSON.stringify(fromProps)}])`;
  25940. }
  25941. }
  25942. function buildProps(node, context, props = node.props, isComponent, isDynamicComponent, ssr = false) {
  25943. const { tag, loc: elementLoc, children } = node;
  25944. let properties = [];
  25945. const mergeArgs = [];
  25946. const runtimeDirectives = [];
  25947. const hasChildren = children.length > 0;
  25948. let shouldUseBlock = false;
  25949. let patchFlag = 0;
  25950. let hasRef = false;
  25951. let hasClassBinding = false;
  25952. let hasStyleBinding = false;
  25953. let hasHydrationEventBinding = false;
  25954. let hasDynamicKeys = false;
  25955. let hasVnodeHook = false;
  25956. const dynamicPropNames = [];
  25957. const pushMergeArg = (arg) => {
  25958. if (properties.length) {
  25959. mergeArgs.push(
  25960. createObjectExpression(dedupeProperties(properties), elementLoc)
  25961. );
  25962. properties = [];
  25963. }
  25964. if (arg) mergeArgs.push(arg);
  25965. };
  25966. const pushRefVForMarker = () => {
  25967. if (context.scopes.vFor > 0) {
  25968. properties.push(
  25969. createObjectProperty(
  25970. createSimpleExpression("ref_for", true),
  25971. createSimpleExpression("true")
  25972. )
  25973. );
  25974. }
  25975. };
  25976. const analyzePatchFlag = ({ key, value }) => {
  25977. if (isStaticExp(key)) {
  25978. const name = key.content;
  25979. const isEventHandler = isOn(name);
  25980. if (isEventHandler && (!isComponent || isDynamicComponent) && // omit the flag for click handlers because hydration gives click
  25981. // dedicated fast path.
  25982. name.toLowerCase() !== "onclick" && // omit v-model handlers
  25983. name !== "onUpdate:modelValue" && // omit onVnodeXXX hooks
  25984. !isReservedProp(name)) {
  25985. hasHydrationEventBinding = true;
  25986. }
  25987. if (isEventHandler && isReservedProp(name)) {
  25988. hasVnodeHook = true;
  25989. }
  25990. if (isEventHandler && value.type === 14) {
  25991. value = value.arguments[0];
  25992. }
  25993. if (value.type === 20 || (value.type === 4 || value.type === 8) && getConstantType(value, context) > 0) {
  25994. return;
  25995. }
  25996. if (name === "ref") {
  25997. hasRef = true;
  25998. } else if (name === "class") {
  25999. hasClassBinding = true;
  26000. } else if (name === "style") {
  26001. hasStyleBinding = true;
  26002. } else if (name !== "key" && !dynamicPropNames.includes(name)) {
  26003. dynamicPropNames.push(name);
  26004. }
  26005. if (isComponent && (name === "class" || name === "style") && !dynamicPropNames.includes(name)) {
  26006. dynamicPropNames.push(name);
  26007. }
  26008. } else {
  26009. hasDynamicKeys = true;
  26010. }
  26011. };
  26012. for (let i = 0; i < props.length; i++) {
  26013. const prop = props[i];
  26014. if (prop.type === 6) {
  26015. const { loc, name, nameLoc, value } = prop;
  26016. let isStatic = true;
  26017. if (name === "ref") {
  26018. hasRef = true;
  26019. pushRefVForMarker();
  26020. if (value && context.inline) {
  26021. const binding = context.bindingMetadata[value.content];
  26022. if (binding === "setup-let" || binding === "setup-ref" || binding === "setup-maybe-ref") {
  26023. isStatic = false;
  26024. properties.push(
  26025. createObjectProperty(
  26026. createSimpleExpression("ref_key", true),
  26027. createSimpleExpression(value.content, true, value.loc)
  26028. )
  26029. );
  26030. }
  26031. }
  26032. }
  26033. if (name === "is" && (isComponentTag(tag) || value && value.content.startsWith("vue:") || false)) {
  26034. continue;
  26035. }
  26036. properties.push(
  26037. createObjectProperty(
  26038. createSimpleExpression(name, true, nameLoc),
  26039. createSimpleExpression(
  26040. value ? value.content : "",
  26041. isStatic,
  26042. value ? value.loc : loc
  26043. )
  26044. )
  26045. );
  26046. } else {
  26047. const { name, arg, exp, loc, modifiers } = prop;
  26048. const isVBind = name === "bind";
  26049. const isVOn = name === "on";
  26050. if (name === "slot") {
  26051. if (!isComponent) {
  26052. context.onError(
  26053. createCompilerError(40, loc)
  26054. );
  26055. }
  26056. continue;
  26057. }
  26058. if (name === "once" || name === "memo") {
  26059. continue;
  26060. }
  26061. if (name === "is" || isVBind && isStaticArgOf(arg, "is") && (isComponentTag(tag) || false)) {
  26062. continue;
  26063. }
  26064. if (isVOn && ssr) {
  26065. continue;
  26066. }
  26067. if (
  26068. // #938: elements with dynamic keys should be forced into blocks
  26069. isVBind && isStaticArgOf(arg, "key") || // inline before-update hooks need to force block so that it is invoked
  26070. // before children
  26071. isVOn && hasChildren && isStaticArgOf(arg, "vue:before-update")
  26072. ) {
  26073. shouldUseBlock = true;
  26074. }
  26075. if (isVBind && isStaticArgOf(arg, "ref")) {
  26076. pushRefVForMarker();
  26077. }
  26078. if (!arg && (isVBind || isVOn)) {
  26079. hasDynamicKeys = true;
  26080. if (exp) {
  26081. if (isVBind) {
  26082. pushRefVForMarker();
  26083. pushMergeArg();
  26084. mergeArgs.push(exp);
  26085. } else {
  26086. pushMergeArg({
  26087. type: 14,
  26088. loc,
  26089. callee: context.helper(TO_HANDLERS),
  26090. arguments: isComponent ? [exp] : [exp, `true`]
  26091. });
  26092. }
  26093. } else {
  26094. context.onError(
  26095. createCompilerError(
  26096. isVBind ? 34 : 35,
  26097. loc
  26098. )
  26099. );
  26100. }
  26101. continue;
  26102. }
  26103. if (isVBind && modifiers.some((mod) => mod.content === "prop")) {
  26104. patchFlag |= 32;
  26105. }
  26106. const directiveTransform = context.directiveTransforms[name];
  26107. if (directiveTransform) {
  26108. const { props: props2, needRuntime } = directiveTransform(prop, node, context);
  26109. !ssr && props2.forEach(analyzePatchFlag);
  26110. if (isVOn && arg && !isStaticExp(arg)) {
  26111. pushMergeArg(createObjectExpression(props2, elementLoc));
  26112. } else {
  26113. properties.push(...props2);
  26114. }
  26115. if (needRuntime) {
  26116. runtimeDirectives.push(prop);
  26117. if (isSymbol$1(needRuntime)) {
  26118. directiveImportMap.set(prop, needRuntime);
  26119. }
  26120. }
  26121. } else if (!isBuiltInDirective(name)) {
  26122. runtimeDirectives.push(prop);
  26123. if (hasChildren) {
  26124. shouldUseBlock = true;
  26125. }
  26126. }
  26127. }
  26128. }
  26129. let propsExpression = void 0;
  26130. if (mergeArgs.length) {
  26131. pushMergeArg();
  26132. if (mergeArgs.length > 1) {
  26133. propsExpression = createCallExpression(
  26134. context.helper(MERGE_PROPS),
  26135. mergeArgs,
  26136. elementLoc
  26137. );
  26138. } else {
  26139. propsExpression = mergeArgs[0];
  26140. }
  26141. } else if (properties.length) {
  26142. propsExpression = createObjectExpression(
  26143. dedupeProperties(properties),
  26144. elementLoc
  26145. );
  26146. }
  26147. if (hasDynamicKeys) {
  26148. patchFlag |= 16;
  26149. } else {
  26150. if (hasClassBinding && !isComponent) {
  26151. patchFlag |= 2;
  26152. }
  26153. if (hasStyleBinding && !isComponent) {
  26154. patchFlag |= 4;
  26155. }
  26156. if (dynamicPropNames.length) {
  26157. patchFlag |= 8;
  26158. }
  26159. if (hasHydrationEventBinding) {
  26160. patchFlag |= 32;
  26161. }
  26162. }
  26163. if (!shouldUseBlock && (patchFlag === 0 || patchFlag === 32) && (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
  26164. patchFlag |= 512;
  26165. }
  26166. if (!context.inSSR && propsExpression) {
  26167. switch (propsExpression.type) {
  26168. case 15:
  26169. let classKeyIndex = -1;
  26170. let styleKeyIndex = -1;
  26171. let hasDynamicKey = false;
  26172. for (let i = 0; i < propsExpression.properties.length; i++) {
  26173. const key = propsExpression.properties[i].key;
  26174. if (isStaticExp(key)) {
  26175. if (key.content === "class") {
  26176. classKeyIndex = i;
  26177. } else if (key.content === "style") {
  26178. styleKeyIndex = i;
  26179. }
  26180. } else if (!key.isHandlerKey) {
  26181. hasDynamicKey = true;
  26182. }
  26183. }
  26184. const classProp = propsExpression.properties[classKeyIndex];
  26185. const styleProp = propsExpression.properties[styleKeyIndex];
  26186. if (!hasDynamicKey) {
  26187. if (classProp && !isStaticExp(classProp.value)) {
  26188. classProp.value = createCallExpression(
  26189. context.helper(NORMALIZE_CLASS),
  26190. [classProp.value]
  26191. );
  26192. }
  26193. if (styleProp && // the static style is compiled into an object,
  26194. // so use `hasStyleBinding` to ensure that it is a dynamic style binding
  26195. (hasStyleBinding || styleProp.value.type === 4 && styleProp.value.content.trim()[0] === `[` || // v-bind:style and style both exist,
  26196. // v-bind:style with static literal object
  26197. styleProp.value.type === 17)) {
  26198. styleProp.value = createCallExpression(
  26199. context.helper(NORMALIZE_STYLE),
  26200. [styleProp.value]
  26201. );
  26202. }
  26203. } else {
  26204. propsExpression = createCallExpression(
  26205. context.helper(NORMALIZE_PROPS),
  26206. [propsExpression]
  26207. );
  26208. }
  26209. break;
  26210. case 14:
  26211. break;
  26212. default:
  26213. propsExpression = createCallExpression(
  26214. context.helper(NORMALIZE_PROPS),
  26215. [
  26216. createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
  26217. propsExpression
  26218. ])
  26219. ]
  26220. );
  26221. break;
  26222. }
  26223. }
  26224. return {
  26225. props: propsExpression,
  26226. directives: runtimeDirectives,
  26227. patchFlag,
  26228. dynamicPropNames,
  26229. shouldUseBlock
  26230. };
  26231. }
  26232. function dedupeProperties(properties) {
  26233. const knownProps = /* @__PURE__ */ new Map();
  26234. const deduped = [];
  26235. for (let i = 0; i < properties.length; i++) {
  26236. const prop = properties[i];
  26237. if (prop.key.type === 8 || !prop.key.isStatic) {
  26238. deduped.push(prop);
  26239. continue;
  26240. }
  26241. const name = prop.key.content;
  26242. const existing = knownProps.get(name);
  26243. if (existing) {
  26244. if (name === "style" || name === "class" || isOn(name)) {
  26245. mergeAsArray(existing, prop);
  26246. }
  26247. } else {
  26248. knownProps.set(name, prop);
  26249. deduped.push(prop);
  26250. }
  26251. }
  26252. return deduped;
  26253. }
  26254. function mergeAsArray(existing, incoming) {
  26255. if (existing.value.type === 17) {
  26256. existing.value.elements.push(incoming.value);
  26257. } else {
  26258. existing.value = createArrayExpression(
  26259. [existing.value, incoming.value],
  26260. existing.loc
  26261. );
  26262. }
  26263. }
  26264. function buildDirectiveArgs(dir, context) {
  26265. const dirArgs = [];
  26266. const runtime = directiveImportMap.get(dir);
  26267. if (runtime) {
  26268. dirArgs.push(context.helperString(runtime));
  26269. } else {
  26270. const fromSetup = resolveSetupReference("v-" + dir.name, context);
  26271. if (fromSetup) {
  26272. dirArgs.push(fromSetup);
  26273. } else {
  26274. context.helper(RESOLVE_DIRECTIVE);
  26275. context.directives.add(dir.name);
  26276. dirArgs.push(toValidAssetId(dir.name, `directive`));
  26277. }
  26278. }
  26279. const { loc } = dir;
  26280. if (dir.exp) dirArgs.push(dir.exp);
  26281. if (dir.arg) {
  26282. if (!dir.exp) {
  26283. dirArgs.push(`void 0`);
  26284. }
  26285. dirArgs.push(dir.arg);
  26286. }
  26287. if (Object.keys(dir.modifiers).length) {
  26288. if (!dir.arg) {
  26289. if (!dir.exp) {
  26290. dirArgs.push(`void 0`);
  26291. }
  26292. dirArgs.push(`void 0`);
  26293. }
  26294. const trueExpression = createSimpleExpression(`true`, false, loc);
  26295. dirArgs.push(
  26296. createObjectExpression(
  26297. dir.modifiers.map(
  26298. (modifier) => createObjectProperty(modifier, trueExpression)
  26299. ),
  26300. loc
  26301. )
  26302. );
  26303. }
  26304. return createArrayExpression(dirArgs, dir.loc);
  26305. }
  26306. function stringifyDynamicPropNames(props) {
  26307. let propsNamesString = `[`;
  26308. for (let i = 0, l = props.length; i < l; i++) {
  26309. propsNamesString += JSON.stringify(props[i]);
  26310. if (i < l - 1) propsNamesString += ", ";
  26311. }
  26312. return propsNamesString + `]`;
  26313. }
  26314. function isComponentTag(tag) {
  26315. return tag === "component" || tag === "Component";
  26316. }
  26317. const transformSlotOutlet = (node, context) => {
  26318. if (isSlotOutlet(node)) {
  26319. const { children, loc } = node;
  26320. const { slotName, slotProps } = processSlotOutlet(node, context);
  26321. const slotArgs = [
  26322. context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
  26323. slotName,
  26324. "{}",
  26325. "undefined",
  26326. "true"
  26327. ];
  26328. let expectedLen = 2;
  26329. if (slotProps) {
  26330. slotArgs[2] = slotProps;
  26331. expectedLen = 3;
  26332. }
  26333. if (children.length) {
  26334. slotArgs[3] = createFunctionExpression([], children, false, false, loc);
  26335. expectedLen = 4;
  26336. }
  26337. if (context.scopeId && !context.slotted) {
  26338. expectedLen = 5;
  26339. }
  26340. slotArgs.splice(expectedLen);
  26341. node.codegenNode = createCallExpression(
  26342. context.helper(RENDER_SLOT),
  26343. slotArgs,
  26344. loc
  26345. );
  26346. }
  26347. };
  26348. function processSlotOutlet(node, context) {
  26349. let slotName = `"default"`;
  26350. let slotProps = void 0;
  26351. const nonNameProps = [];
  26352. for (let i = 0; i < node.props.length; i++) {
  26353. const p = node.props[i];
  26354. if (p.type === 6) {
  26355. if (p.value) {
  26356. if (p.name === "name") {
  26357. slotName = JSON.stringify(p.value.content);
  26358. } else {
  26359. p.name = camelize(p.name);
  26360. nonNameProps.push(p);
  26361. }
  26362. }
  26363. } else {
  26364. if (p.name === "bind" && isStaticArgOf(p.arg, "name")) {
  26365. if (p.exp) {
  26366. slotName = p.exp;
  26367. } else if (p.arg && p.arg.type === 4) {
  26368. const name = camelize(p.arg.content);
  26369. slotName = p.exp = createSimpleExpression(name, false, p.arg.loc);
  26370. {
  26371. slotName = p.exp = processExpression(p.exp, context);
  26372. }
  26373. }
  26374. } else {
  26375. if (p.name === "bind" && p.arg && isStaticExp(p.arg)) {
  26376. p.arg.content = camelize(p.arg.content);
  26377. }
  26378. nonNameProps.push(p);
  26379. }
  26380. }
  26381. }
  26382. if (nonNameProps.length > 0) {
  26383. const { props, directives } = buildProps(
  26384. node,
  26385. context,
  26386. nonNameProps,
  26387. false,
  26388. false
  26389. );
  26390. slotProps = props;
  26391. if (directives.length) {
  26392. context.onError(
  26393. createCompilerError(
  26394. 36,
  26395. directives[0].loc
  26396. )
  26397. );
  26398. }
  26399. }
  26400. return {
  26401. slotName,
  26402. slotProps
  26403. };
  26404. }
  26405. const transformOn$1 = (dir, node, context, augmentor) => {
  26406. const { loc, modifiers, arg } = dir;
  26407. if (!dir.exp && !modifiers.length) {
  26408. context.onError(createCompilerError(35, loc));
  26409. }
  26410. let eventName;
  26411. if (arg.type === 4) {
  26412. if (arg.isStatic) {
  26413. let rawName = arg.content;
  26414. if (rawName.startsWith("vnode")) {
  26415. context.onError(createCompilerError(52, arg.loc));
  26416. }
  26417. if (rawName.startsWith("vue:")) {
  26418. rawName = `vnode-${rawName.slice(4)}`;
  26419. }
  26420. const eventString = node.tagType !== 0 || rawName.startsWith("vnode") || !/[A-Z]/.test(rawName) ? (
  26421. // for non-element and vnode lifecycle event listeners, auto convert
  26422. // it to camelCase. See issue #2249
  26423. toHandlerKey(camelize(rawName))
  26424. ) : (
  26425. // preserve case for plain element listeners that have uppercase
  26426. // letters, as these may be custom elements' custom events
  26427. `on:${rawName}`
  26428. );
  26429. eventName = createSimpleExpression(eventString, true, arg.loc);
  26430. } else {
  26431. eventName = createCompoundExpression([
  26432. `${context.helperString(TO_HANDLER_KEY)}(`,
  26433. arg,
  26434. `)`
  26435. ]);
  26436. }
  26437. } else {
  26438. eventName = arg;
  26439. eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
  26440. eventName.children.push(`)`);
  26441. }
  26442. let exp = dir.exp;
  26443. if (exp && !exp.content.trim()) {
  26444. exp = void 0;
  26445. }
  26446. let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;
  26447. if (exp) {
  26448. const isMemberExp = isMemberExpression(exp, context);
  26449. const isInlineStatement = !(isMemberExp || isFnExpression(exp, context));
  26450. const hasMultipleStatements = exp.content.includes(`;`);
  26451. if (context.prefixIdentifiers) {
  26452. isInlineStatement && context.addIdentifiers(`$event`);
  26453. exp = dir.exp = processExpression(
  26454. exp,
  26455. context,
  26456. false,
  26457. hasMultipleStatements
  26458. );
  26459. isInlineStatement && context.removeIdentifiers(`$event`);
  26460. shouldCache = context.cacheHandlers && // unnecessary to cache inside v-once
  26461. !context.inVOnce && // runtime constants don't need to be cached
  26462. // (this is analyzed by compileScript in SFC <script setup>)
  26463. !(exp.type === 4 && exp.constType > 0) && // #1541 bail if this is a member exp handler passed to a component -
  26464. // we need to use the original function to preserve arity,
  26465. // e.g. <transition> relies on checking cb.length to determine
  26466. // transition end handling. Inline function is ok since its arity
  26467. // is preserved even when cached.
  26468. !(isMemberExp && node.tagType === 1) && // bail if the function references closure variables (v-for, v-slot)
  26469. // it must be passed fresh to avoid stale values.
  26470. !hasScopeRef(exp, context.identifiers);
  26471. if (shouldCache && isMemberExp) {
  26472. if (exp.type === 4) {
  26473. exp.content = `${exp.content} && ${exp.content}(...args)`;
  26474. } else {
  26475. exp.children = [...exp.children, ` && `, ...exp.children, `(...args)`];
  26476. }
  26477. }
  26478. }
  26479. if (isInlineStatement || shouldCache && isMemberExp) {
  26480. exp = createCompoundExpression([
  26481. `${isInlineStatement ? context.isTS ? `($event: any)` : `$event` : `${context.isTS ? `
  26482. //@ts-ignore
  26483. ` : ``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
  26484. exp,
  26485. hasMultipleStatements ? `}` : `)`
  26486. ]);
  26487. }
  26488. }
  26489. let ret = {
  26490. props: [
  26491. createObjectProperty(
  26492. eventName,
  26493. exp || createSimpleExpression(`() => {}`, false, loc)
  26494. )
  26495. ]
  26496. };
  26497. if (augmentor) {
  26498. ret = augmentor(ret);
  26499. }
  26500. if (shouldCache) {
  26501. ret.props[0].value = context.cache(ret.props[0].value);
  26502. }
  26503. ret.props.forEach((p) => p.key.isHandlerKey = true);
  26504. return ret;
  26505. };
  26506. const transformBind = (dir, _node, context) => {
  26507. const { modifiers, loc } = dir;
  26508. const arg = dir.arg;
  26509. let { exp } = dir;
  26510. if (exp && exp.type === 4 && !exp.content.trim()) {
  26511. {
  26512. context.onError(
  26513. createCompilerError(34, loc)
  26514. );
  26515. return {
  26516. props: [
  26517. createObjectProperty(arg, createSimpleExpression("", true, loc))
  26518. ]
  26519. };
  26520. }
  26521. }
  26522. if (arg.type !== 4) {
  26523. arg.children.unshift(`(`);
  26524. arg.children.push(`) || ""`);
  26525. } else if (!arg.isStatic) {
  26526. arg.content = arg.content ? `${arg.content} || ""` : `""`;
  26527. }
  26528. if (modifiers.some((mod) => mod.content === "camel")) {
  26529. if (arg.type === 4) {
  26530. if (arg.isStatic) {
  26531. arg.content = camelize(arg.content);
  26532. } else {
  26533. arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
  26534. }
  26535. } else {
  26536. arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
  26537. arg.children.push(`)`);
  26538. }
  26539. }
  26540. if (!context.inSSR) {
  26541. if (modifiers.some((mod) => mod.content === "prop")) {
  26542. injectPrefix(arg, ".");
  26543. }
  26544. if (modifiers.some((mod) => mod.content === "attr")) {
  26545. injectPrefix(arg, "^");
  26546. }
  26547. }
  26548. return {
  26549. props: [createObjectProperty(arg, exp)]
  26550. };
  26551. };
  26552. const injectPrefix = (arg, prefix) => {
  26553. if (arg.type === 4) {
  26554. if (arg.isStatic) {
  26555. arg.content = prefix + arg.content;
  26556. } else {
  26557. arg.content = `\`${prefix}\${${arg.content}}\``;
  26558. }
  26559. } else {
  26560. arg.children.unshift(`'${prefix}' + (`);
  26561. arg.children.push(`)`);
  26562. }
  26563. };
  26564. const transformText = (node, context) => {
  26565. if (node.type === 0 || node.type === 1 || node.type === 11 || node.type === 10) {
  26566. return () => {
  26567. const children = node.children;
  26568. let currentContainer = void 0;
  26569. let hasText = false;
  26570. for (let i = 0; i < children.length; i++) {
  26571. const child = children[i];
  26572. if (isText$1(child)) {
  26573. hasText = true;
  26574. for (let j = i + 1; j < children.length; j++) {
  26575. const next = children[j];
  26576. if (isText$1(next)) {
  26577. if (!currentContainer) {
  26578. currentContainer = children[i] = createCompoundExpression(
  26579. [child],
  26580. child.loc
  26581. );
  26582. }
  26583. currentContainer.children.push(` + `, next);
  26584. children.splice(j, 1);
  26585. j--;
  26586. } else {
  26587. currentContainer = void 0;
  26588. break;
  26589. }
  26590. }
  26591. }
  26592. }
  26593. if (!hasText || // if this is a plain element with a single text child, leave it
  26594. // as-is since the runtime has dedicated fast path for this by directly
  26595. // setting textContent of the element.
  26596. // for component root it's always normalized anyway.
  26597. children.length === 1 && (node.type === 0 || node.type === 1 && node.tagType === 0 && // #3756
  26598. // custom directives can potentially add DOM elements arbitrarily,
  26599. // we need to avoid setting textContent of the element at runtime
  26600. // to avoid accidentally overwriting the DOM elements added
  26601. // by the user through custom directives.
  26602. !node.props.find(
  26603. (p) => p.type === 7 && !context.directiveTransforms[p.name]
  26604. ) && // in compat mode, <template> tags with no special directives
  26605. // will be rendered as a fragment so its children must be
  26606. // converted into vnodes.
  26607. true)) {
  26608. return;
  26609. }
  26610. for (let i = 0; i < children.length; i++) {
  26611. const child = children[i];
  26612. if (isText$1(child) || child.type === 8) {
  26613. const callArgs = [];
  26614. if (child.type !== 2 || child.content !== " ") {
  26615. callArgs.push(child);
  26616. }
  26617. if (!context.ssr && getConstantType(child, context) === 0) {
  26618. callArgs.push(
  26619. 1 + (` /* ${PatchFlagNames[1]} */` )
  26620. );
  26621. }
  26622. children[i] = {
  26623. type: 12,
  26624. content: child,
  26625. loc: child.loc,
  26626. codegenNode: createCallExpression(
  26627. context.helper(CREATE_TEXT),
  26628. callArgs
  26629. )
  26630. };
  26631. }
  26632. }
  26633. };
  26634. }
  26635. };
  26636. const seen$1 = /* @__PURE__ */ new WeakSet();
  26637. const transformOnce = (node, context) => {
  26638. if (node.type === 1 && findDir(node, "once", true)) {
  26639. if (seen$1.has(node) || context.inVOnce || context.inSSR) {
  26640. return;
  26641. }
  26642. seen$1.add(node);
  26643. context.inVOnce = true;
  26644. context.helper(SET_BLOCK_TRACKING);
  26645. return () => {
  26646. context.inVOnce = false;
  26647. const cur = context.currentNode;
  26648. if (cur.codegenNode) {
  26649. cur.codegenNode = context.cache(
  26650. cur.codegenNode,
  26651. true,
  26652. true
  26653. );
  26654. }
  26655. };
  26656. }
  26657. };
  26658. const transformModel$1 = (dir, node, context) => {
  26659. const { exp, arg } = dir;
  26660. if (!exp) {
  26661. context.onError(
  26662. createCompilerError(41, dir.loc)
  26663. );
  26664. return createTransformProps();
  26665. }
  26666. const rawExp = exp.loc.source.trim();
  26667. const expString = exp.type === 4 ? exp.content : rawExp;
  26668. const bindingType = context.bindingMetadata[rawExp];
  26669. if (bindingType === "props" || bindingType === "props-aliased") {
  26670. context.onError(createCompilerError(44, exp.loc));
  26671. return createTransformProps();
  26672. }
  26673. if (bindingType === "literal-const" || bindingType === "setup-const") {
  26674. context.onError(createCompilerError(45, exp.loc));
  26675. return createTransformProps();
  26676. }
  26677. const maybeRef = context.inline && (bindingType === "setup-let" || bindingType === "setup-ref" || bindingType === "setup-maybe-ref");
  26678. if (!expString.trim() || !isMemberExpression(exp, context) && !maybeRef) {
  26679. context.onError(
  26680. createCompilerError(42, exp.loc)
  26681. );
  26682. return createTransformProps();
  26683. }
  26684. if (context.prefixIdentifiers && isSimpleIdentifier(expString) && context.identifiers[expString]) {
  26685. context.onError(
  26686. createCompilerError(43, exp.loc)
  26687. );
  26688. return createTransformProps();
  26689. }
  26690. const propName = arg ? arg : createSimpleExpression("modelValue", true);
  26691. const eventName = arg ? isStaticExp(arg) ? `onUpdate:${camelize(arg.content)}` : createCompoundExpression(['"onUpdate:" + ', arg]) : `onUpdate:modelValue`;
  26692. let assignmentExp;
  26693. const eventArg = context.isTS ? `($event: any)` : `$event`;
  26694. if (maybeRef) {
  26695. if (bindingType === "setup-ref") {
  26696. assignmentExp = createCompoundExpression([
  26697. `${eventArg} => ((`,
  26698. createSimpleExpression(rawExp, false, exp.loc),
  26699. `).value = $event)`
  26700. ]);
  26701. } else {
  26702. const altAssignment = bindingType === "setup-let" ? `${rawExp} = $event` : `null`;
  26703. assignmentExp = createCompoundExpression([
  26704. `${eventArg} => (${context.helperString(IS_REF)}(${rawExp}) ? (`,
  26705. createSimpleExpression(rawExp, false, exp.loc),
  26706. `).value = $event : ${altAssignment})`
  26707. ]);
  26708. }
  26709. } else {
  26710. assignmentExp = createCompoundExpression([
  26711. `${eventArg} => ((`,
  26712. exp,
  26713. `) = $event)`
  26714. ]);
  26715. }
  26716. const props = [
  26717. // modelValue: foo
  26718. createObjectProperty(propName, dir.exp),
  26719. // "onUpdate:modelValue": $event => (foo = $event)
  26720. createObjectProperty(eventName, assignmentExp)
  26721. ];
  26722. if (context.prefixIdentifiers && !context.inVOnce && context.cacheHandlers && !hasScopeRef(exp, context.identifiers)) {
  26723. props[1].value = context.cache(props[1].value);
  26724. }
  26725. if (dir.modifiers.length && node.tagType === 1) {
  26726. const modifiers = dir.modifiers.map((m) => m.content).map((m) => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`).join(`, `);
  26727. const modifiersKey = arg ? isStaticExp(arg) ? `${arg.content}Modifiers` : createCompoundExpression([arg, ' + "Modifiers"']) : `modelModifiers`;
  26728. props.push(
  26729. createObjectProperty(
  26730. modifiersKey,
  26731. createSimpleExpression(
  26732. `{ ${modifiers} }`,
  26733. false,
  26734. dir.loc,
  26735. 2
  26736. )
  26737. )
  26738. );
  26739. }
  26740. return createTransformProps(props);
  26741. };
  26742. function createTransformProps(props = []) {
  26743. return { props };
  26744. }
  26745. const seen = /* @__PURE__ */ new WeakSet();
  26746. const transformMemo = (node, context) => {
  26747. if (node.type === 1) {
  26748. const dir = findDir(node, "memo");
  26749. if (!dir || seen.has(node) || context.inSSR) {
  26750. return;
  26751. }
  26752. seen.add(node);
  26753. return () => {
  26754. const codegenNode = node.codegenNode || context.currentNode.codegenNode;
  26755. if (codegenNode && codegenNode.type === 13) {
  26756. if (node.tagType !== 1) {
  26757. convertToBlock(codegenNode, context);
  26758. }
  26759. node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
  26760. dir.exp,
  26761. createFunctionExpression(void 0, codegenNode),
  26762. `_cache`,
  26763. String(context.cached.length)
  26764. ]);
  26765. context.cached.push(null);
  26766. }
  26767. };
  26768. }
  26769. };
  26770. const transformVBindShorthand = (node, context) => {
  26771. if (node.type === 1) {
  26772. for (const prop of node.props) {
  26773. if (prop.type === 7 && prop.name === "bind" && (!prop.exp || // #13930 :foo in in-DOM templates will be parsed into :foo="" by browser
  26774. false) && prop.arg) {
  26775. const arg = prop.arg;
  26776. if (arg.type !== 4 || !arg.isStatic) {
  26777. context.onError(
  26778. createCompilerError(
  26779. 53,
  26780. arg.loc
  26781. )
  26782. );
  26783. prop.exp = createSimpleExpression("", true, arg.loc);
  26784. } else {
  26785. const propName = camelize(arg.content);
  26786. if (validFirstIdentCharRE.test(propName[0]) || // allow hyphen first char for https://github.com/vuejs/language-tools/pull/3424
  26787. propName[0] === "-") {
  26788. prop.exp = createSimpleExpression(propName, false, arg.loc);
  26789. }
  26790. }
  26791. }
  26792. }
  26793. }
  26794. };
  26795. function getBaseTransformPreset(prefixIdentifiers) {
  26796. return [
  26797. [
  26798. transformVBindShorthand,
  26799. transformOnce,
  26800. transformIf,
  26801. transformMemo,
  26802. transformFor,
  26803. ...[],
  26804. ...prefixIdentifiers ? [
  26805. // order is important
  26806. trackVForSlotScopes,
  26807. transformExpression
  26808. ] : [],
  26809. transformSlotOutlet,
  26810. transformElement,
  26811. trackSlotScopes,
  26812. transformText
  26813. ],
  26814. {
  26815. on: transformOn$1,
  26816. bind: transformBind,
  26817. model: transformModel$1
  26818. }
  26819. ];
  26820. }
  26821. function baseCompile(source, options = {}) {
  26822. const onError = options.onError || defaultOnError;
  26823. const isModuleMode = options.mode === "module";
  26824. const prefixIdentifiers = options.prefixIdentifiers === true || isModuleMode;
  26825. if (!prefixIdentifiers && options.cacheHandlers) {
  26826. onError(createCompilerError(50));
  26827. }
  26828. if (options.scopeId && !isModuleMode) {
  26829. onError(createCompilerError(51));
  26830. }
  26831. const resolvedOptions = extend({}, options, {
  26832. prefixIdentifiers
  26833. });
  26834. const ast = isString$1(source) ? baseParse(source, resolvedOptions) : source;
  26835. const [nodeTransforms, directiveTransforms] = getBaseTransformPreset(prefixIdentifiers);
  26836. if (options.isTS) {
  26837. const { expressionPlugins } = options;
  26838. if (!expressionPlugins || !expressionPlugins.includes("typescript")) {
  26839. options.expressionPlugins = [...expressionPlugins || [], "typescript"];
  26840. }
  26841. }
  26842. transform(
  26843. ast,
  26844. extend({}, resolvedOptions, {
  26845. nodeTransforms: [
  26846. ...nodeTransforms,
  26847. ...options.nodeTransforms || []
  26848. // user transforms
  26849. ],
  26850. directiveTransforms: extend(
  26851. {},
  26852. directiveTransforms,
  26853. options.directiveTransforms || {}
  26854. // user transforms
  26855. )
  26856. })
  26857. );
  26858. return generate(ast, resolvedOptions);
  26859. }
  26860. const BindingTypes = {
  26861. "DATA": "data",
  26862. "PROPS": "props",
  26863. "PROPS_ALIASED": "props-aliased",
  26864. "SETUP_LET": "setup-let",
  26865. "SETUP_CONST": "setup-const",
  26866. "SETUP_REACTIVE_CONST": "setup-reactive-const",
  26867. "SETUP_MAYBE_REF": "setup-maybe-ref",
  26868. "SETUP_REF": "setup-ref",
  26869. "OPTIONS": "options",
  26870. "LITERAL_CONST": "literal-const"
  26871. };
  26872. const noopDirectiveTransform = () => ({ props: [] });
  26873. const V_MODEL_RADIO = /* @__PURE__ */ Symbol(`vModelRadio` );
  26874. const V_MODEL_CHECKBOX = /* @__PURE__ */ Symbol(
  26875. `vModelCheckbox`
  26876. );
  26877. const V_MODEL_TEXT = /* @__PURE__ */ Symbol(`vModelText` );
  26878. const V_MODEL_SELECT = /* @__PURE__ */ Symbol(
  26879. `vModelSelect`
  26880. );
  26881. const V_MODEL_DYNAMIC = /* @__PURE__ */ Symbol(
  26882. `vModelDynamic`
  26883. );
  26884. const V_ON_WITH_MODIFIERS = /* @__PURE__ */ Symbol(
  26885. `vOnModifiersGuard`
  26886. );
  26887. const V_ON_WITH_KEYS = /* @__PURE__ */ Symbol(
  26888. `vOnKeysGuard`
  26889. );
  26890. const V_SHOW = /* @__PURE__ */ Symbol(`vShow` );
  26891. const TRANSITION = /* @__PURE__ */ Symbol(`Transition` );
  26892. const TRANSITION_GROUP = /* @__PURE__ */ Symbol(
  26893. `TransitionGroup`
  26894. );
  26895. registerRuntimeHelpers({
  26896. [V_MODEL_RADIO]: `vModelRadio`,
  26897. [V_MODEL_CHECKBOX]: `vModelCheckbox`,
  26898. [V_MODEL_TEXT]: `vModelText`,
  26899. [V_MODEL_SELECT]: `vModelSelect`,
  26900. [V_MODEL_DYNAMIC]: `vModelDynamic`,
  26901. [V_ON_WITH_MODIFIERS]: `withModifiers`,
  26902. [V_ON_WITH_KEYS]: `withKeys`,
  26903. [V_SHOW]: `vShow`,
  26904. [TRANSITION]: `Transition`,
  26905. [TRANSITION_GROUP]: `TransitionGroup`
  26906. });
  26907. const parserOptions = {
  26908. parseMode: "html",
  26909. isVoidTag,
  26910. isNativeTag: (tag) => isHTMLTag(tag) || isSVGTag(tag) || isMathMLTag(tag),
  26911. isPreTag: (tag) => tag === "pre",
  26912. isIgnoreNewlineTag: (tag) => tag === "pre" || tag === "textarea",
  26913. decodeEntities: void 0,
  26914. isBuiltInComponent: (tag) => {
  26915. if (tag === "Transition" || tag === "transition") {
  26916. return TRANSITION;
  26917. } else if (tag === "TransitionGroup" || tag === "transition-group") {
  26918. return TRANSITION_GROUP;
  26919. }
  26920. },
  26921. // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
  26922. getNamespace(tag, parent, rootNamespace) {
  26923. let ns = parent ? parent.ns : rootNamespace;
  26924. if (parent && ns === 2) {
  26925. if (parent.tag === "annotation-xml") {
  26926. if (tag === "svg") {
  26927. return 1;
  26928. }
  26929. if (parent.props.some(
  26930. (a) => a.type === 6 && a.name === "encoding" && a.value != null && (a.value.content === "text/html" || a.value.content === "application/xhtml+xml")
  26931. )) {
  26932. ns = 0;
  26933. }
  26934. } else if (/^m(?:[ions]|text)$/.test(parent.tag) && tag !== "mglyph" && tag !== "malignmark") {
  26935. ns = 0;
  26936. }
  26937. } else if (parent && ns === 1) {
  26938. if (parent.tag === "foreignObject" || parent.tag === "desc" || parent.tag === "title") {
  26939. ns = 0;
  26940. }
  26941. }
  26942. if (ns === 0) {
  26943. if (tag === "svg") {
  26944. return 1;
  26945. }
  26946. if (tag === "math") {
  26947. return 2;
  26948. }
  26949. }
  26950. return ns;
  26951. }
  26952. };
  26953. const transformStyle = (node) => {
  26954. if (node.type === 1) {
  26955. node.props.forEach((p, i) => {
  26956. if (p.type === 6 && p.name === "style" && p.value) {
  26957. node.props[i] = {
  26958. type: 7,
  26959. name: `bind`,
  26960. arg: createSimpleExpression(`style`, true, p.loc),
  26961. exp: parseInlineCSS(p.value.content, p.loc),
  26962. modifiers: [],
  26963. loc: p.loc
  26964. };
  26965. }
  26966. });
  26967. }
  26968. };
  26969. const parseInlineCSS = (cssText, loc) => {
  26970. const normalized = parseStringStyle(cssText);
  26971. return createSimpleExpression(
  26972. JSON.stringify(normalized),
  26973. false,
  26974. loc,
  26975. 3
  26976. );
  26977. };
  26978. function createDOMCompilerError(code, loc) {
  26979. return createCompilerError(
  26980. code,
  26981. loc,
  26982. DOMErrorMessages
  26983. );
  26984. }
  26985. const DOMErrorCodes = {
  26986. "X_V_HTML_NO_EXPRESSION": 54,
  26987. "54": "X_V_HTML_NO_EXPRESSION",
  26988. "X_V_HTML_WITH_CHILDREN": 55,
  26989. "55": "X_V_HTML_WITH_CHILDREN",
  26990. "X_V_TEXT_NO_EXPRESSION": 56,
  26991. "56": "X_V_TEXT_NO_EXPRESSION",
  26992. "X_V_TEXT_WITH_CHILDREN": 57,
  26993. "57": "X_V_TEXT_WITH_CHILDREN",
  26994. "X_V_MODEL_ON_INVALID_ELEMENT": 58,
  26995. "58": "X_V_MODEL_ON_INVALID_ELEMENT",
  26996. "X_V_MODEL_ARG_ON_ELEMENT": 59,
  26997. "59": "X_V_MODEL_ARG_ON_ELEMENT",
  26998. "X_V_MODEL_ON_FILE_INPUT_ELEMENT": 60,
  26999. "60": "X_V_MODEL_ON_FILE_INPUT_ELEMENT",
  27000. "X_V_MODEL_UNNECESSARY_VALUE": 61,
  27001. "61": "X_V_MODEL_UNNECESSARY_VALUE",
  27002. "X_V_SHOW_NO_EXPRESSION": 62,
  27003. "62": "X_V_SHOW_NO_EXPRESSION",
  27004. "X_TRANSITION_INVALID_CHILDREN": 63,
  27005. "63": "X_TRANSITION_INVALID_CHILDREN",
  27006. "X_IGNORED_SIDE_EFFECT_TAG": 64,
  27007. "64": "X_IGNORED_SIDE_EFFECT_TAG",
  27008. "__EXTEND_POINT__": 65,
  27009. "65": "__EXTEND_POINT__"
  27010. };
  27011. const DOMErrorMessages = {
  27012. [54]: `v-html is missing expression.`,
  27013. [55]: `v-html will override element children.`,
  27014. [56]: `v-text is missing expression.`,
  27015. [57]: `v-text will override element children.`,
  27016. [58]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
  27017. [59]: `v-model argument is not supported on plain elements.`,
  27018. [60]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`,
  27019. [61]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
  27020. [62]: `v-show is missing expression.`,
  27021. [63]: `<Transition> expects exactly one child element or component.`,
  27022. [64]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
  27023. };
  27024. const transformVHtml = (dir, node, context) => {
  27025. const { exp, loc } = dir;
  27026. if (!exp) {
  27027. context.onError(
  27028. createDOMCompilerError(54, loc)
  27029. );
  27030. }
  27031. if (node.children.length) {
  27032. context.onError(
  27033. createDOMCompilerError(55, loc)
  27034. );
  27035. node.children.length = 0;
  27036. }
  27037. return {
  27038. props: [
  27039. createObjectProperty(
  27040. createSimpleExpression(`innerHTML`, true, loc),
  27041. exp || createSimpleExpression("", true)
  27042. )
  27043. ]
  27044. };
  27045. };
  27046. const transformVText = (dir, node, context) => {
  27047. const { exp, loc } = dir;
  27048. if (!exp) {
  27049. context.onError(
  27050. createDOMCompilerError(56, loc)
  27051. );
  27052. }
  27053. if (node.children.length) {
  27054. context.onError(
  27055. createDOMCompilerError(57, loc)
  27056. );
  27057. node.children.length = 0;
  27058. }
  27059. return {
  27060. props: [
  27061. createObjectProperty(
  27062. createSimpleExpression(`textContent`, true),
  27063. exp ? getConstantType(exp, context) > 0 ? exp : createCallExpression(
  27064. context.helperString(TO_DISPLAY_STRING),
  27065. [exp],
  27066. loc
  27067. ) : createSimpleExpression("", true)
  27068. )
  27069. ]
  27070. };
  27071. };
  27072. const transformModel = (dir, node, context) => {
  27073. const baseResult = transformModel$1(dir, node, context);
  27074. if (!baseResult.props.length || node.tagType === 1) {
  27075. return baseResult;
  27076. }
  27077. if (dir.arg) {
  27078. context.onError(
  27079. createDOMCompilerError(
  27080. 59,
  27081. dir.arg.loc
  27082. )
  27083. );
  27084. }
  27085. function checkDuplicatedValue() {
  27086. const value = findDir(node, "bind");
  27087. if (value && isStaticArgOf(value.arg, "value")) {
  27088. context.onError(
  27089. createDOMCompilerError(
  27090. 61,
  27091. value.loc
  27092. )
  27093. );
  27094. }
  27095. }
  27096. const { tag } = node;
  27097. const isCustomElement = context.isCustomElement(tag);
  27098. if (tag === "input" || tag === "textarea" || tag === "select" || isCustomElement) {
  27099. let directiveToUse = V_MODEL_TEXT;
  27100. let isInvalidType = false;
  27101. if (tag === "input" || isCustomElement) {
  27102. const type = findProp(node, `type`);
  27103. if (type) {
  27104. if (type.type === 7) {
  27105. directiveToUse = V_MODEL_DYNAMIC;
  27106. } else if (type.value) {
  27107. switch (type.value.content) {
  27108. case "radio":
  27109. directiveToUse = V_MODEL_RADIO;
  27110. break;
  27111. case "checkbox":
  27112. directiveToUse = V_MODEL_CHECKBOX;
  27113. break;
  27114. case "file":
  27115. isInvalidType = true;
  27116. context.onError(
  27117. createDOMCompilerError(
  27118. 60,
  27119. dir.loc
  27120. )
  27121. );
  27122. break;
  27123. default:
  27124. checkDuplicatedValue();
  27125. break;
  27126. }
  27127. }
  27128. } else if (hasDynamicKeyVBind(node)) {
  27129. directiveToUse = V_MODEL_DYNAMIC;
  27130. } else {
  27131. checkDuplicatedValue();
  27132. }
  27133. } else if (tag === "select") {
  27134. directiveToUse = V_MODEL_SELECT;
  27135. } else {
  27136. checkDuplicatedValue();
  27137. }
  27138. if (!isInvalidType) {
  27139. baseResult.needRuntime = context.helper(directiveToUse);
  27140. }
  27141. } else {
  27142. context.onError(
  27143. createDOMCompilerError(
  27144. 58,
  27145. dir.loc
  27146. )
  27147. );
  27148. }
  27149. baseResult.props = baseResult.props.filter(
  27150. (p) => !(p.key.type === 4 && p.key.content === "modelValue")
  27151. );
  27152. return baseResult;
  27153. };
  27154. const isEventOptionModifier = /* @__PURE__ */ makeMap(`passive,once,capture`);
  27155. const isNonKeyModifier = /* @__PURE__ */ makeMap(
  27156. // event propagation management
  27157. `stop,prevent,self,ctrl,shift,alt,meta,exact,middle`
  27158. );
  27159. const maybeKeyModifier = /* @__PURE__ */ makeMap("left,right");
  27160. const isKeyboardEvent = /* @__PURE__ */ makeMap(`onkeyup,onkeydown,onkeypress`);
  27161. const resolveModifiers = (key, modifiers, context, loc) => {
  27162. const keyModifiers = [];
  27163. const nonKeyModifiers = [];
  27164. const eventOptionModifiers = [];
  27165. for (let i = 0; i < modifiers.length; i++) {
  27166. const modifier = modifiers[i].content;
  27167. if (isEventOptionModifier(modifier)) {
  27168. eventOptionModifiers.push(modifier);
  27169. } else {
  27170. if (maybeKeyModifier(modifier)) {
  27171. if (isStaticExp(key)) {
  27172. if (isKeyboardEvent(key.content.toLowerCase())) {
  27173. keyModifiers.push(modifier);
  27174. } else {
  27175. nonKeyModifiers.push(modifier);
  27176. }
  27177. } else {
  27178. keyModifiers.push(modifier);
  27179. nonKeyModifiers.push(modifier);
  27180. }
  27181. } else {
  27182. if (isNonKeyModifier(modifier)) {
  27183. nonKeyModifiers.push(modifier);
  27184. } else {
  27185. keyModifiers.push(modifier);
  27186. }
  27187. }
  27188. }
  27189. }
  27190. return {
  27191. keyModifiers,
  27192. nonKeyModifiers,
  27193. eventOptionModifiers
  27194. };
  27195. };
  27196. const transformClick = (key, event) => {
  27197. const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === "onclick";
  27198. return isStaticClick ? createSimpleExpression(event, true) : key.type !== 4 ? createCompoundExpression([
  27199. `(`,
  27200. key,
  27201. `) === "onClick" ? "${event}" : (`,
  27202. key,
  27203. `)`
  27204. ]) : key;
  27205. };
  27206. const transformOn = (dir, node, context) => {
  27207. return transformOn$1(dir, node, context, (baseResult) => {
  27208. const { modifiers } = dir;
  27209. if (!modifiers.length) return baseResult;
  27210. let { key, value: handlerExp } = baseResult.props[0];
  27211. const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
  27212. if (nonKeyModifiers.includes("right")) {
  27213. key = transformClick(key, `onContextmenu`);
  27214. }
  27215. if (nonKeyModifiers.includes("middle")) {
  27216. key = transformClick(key, `onMouseup`);
  27217. }
  27218. if (nonKeyModifiers.length) {
  27219. handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
  27220. handlerExp,
  27221. JSON.stringify(nonKeyModifiers)
  27222. ]);
  27223. }
  27224. if (keyModifiers.length && // if event name is dynamic, always wrap with keys guard
  27225. (!isStaticExp(key) || isKeyboardEvent(key.content.toLowerCase()))) {
  27226. handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
  27227. handlerExp,
  27228. JSON.stringify(keyModifiers)
  27229. ]);
  27230. }
  27231. if (eventOptionModifiers.length) {
  27232. const modifierPostfix = eventOptionModifiers.map(capitalize).join("");
  27233. key = isStaticExp(key) ? createSimpleExpression(`${key.content}${modifierPostfix}`, true) : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
  27234. }
  27235. return {
  27236. props: [createObjectProperty(key, handlerExp)]
  27237. };
  27238. });
  27239. };
  27240. const transformShow = (dir, node, context) => {
  27241. const { exp, loc } = dir;
  27242. if (!exp) {
  27243. context.onError(
  27244. createDOMCompilerError(62, loc)
  27245. );
  27246. }
  27247. return {
  27248. props: [],
  27249. needRuntime: context.helper(V_SHOW)
  27250. };
  27251. };
  27252. const transformTransition = (node, context) => {
  27253. if (node.type === 1 && node.tagType === 1) {
  27254. const component = context.isBuiltInComponent(node.tag);
  27255. if (component === TRANSITION) {
  27256. return () => {
  27257. if (!node.children.length) {
  27258. return;
  27259. }
  27260. if (hasMultipleChildren(node)) {
  27261. context.onError(
  27262. createDOMCompilerError(
  27263. 63,
  27264. {
  27265. start: node.children[0].loc.start,
  27266. end: node.children[node.children.length - 1].loc.end,
  27267. source: ""
  27268. }
  27269. )
  27270. );
  27271. }
  27272. const child = node.children[0];
  27273. if (child.type === 1) {
  27274. for (const p of child.props) {
  27275. if (p.type === 7 && p.name === "show") {
  27276. node.props.push({
  27277. type: 6,
  27278. name: "persisted",
  27279. nameLoc: node.loc,
  27280. value: void 0,
  27281. loc: node.loc
  27282. });
  27283. }
  27284. }
  27285. }
  27286. };
  27287. }
  27288. }
  27289. };
  27290. function hasMultipleChildren(node) {
  27291. const children = node.children = node.children.filter(
  27292. (c) => !isCommentOrWhitespace(c)
  27293. );
  27294. const child = children[0];
  27295. return children.length !== 1 || child.type === 11 || child.type === 9 && child.branches.some(hasMultipleChildren);
  27296. }
  27297. const expReplaceRE = /__VUE_EXP_START__(.*?)__VUE_EXP_END__/g;
  27298. const stringifyStatic = (children, context, parent) => {
  27299. if (context.scopes.vSlot > 0) {
  27300. return;
  27301. }
  27302. const isParentCached = parent.type === 1 && parent.codegenNode && parent.codegenNode.type === 13 && parent.codegenNode.children && !isArray$3(parent.codegenNode.children) && parent.codegenNode.children.type === 20;
  27303. let nc = 0;
  27304. let ec = 0;
  27305. const currentChunk = [];
  27306. const stringifyCurrentChunk = (currentIndex) => {
  27307. if (nc >= 20 || ec >= 5) {
  27308. const staticCall = createCallExpression(context.helper(CREATE_STATIC), [
  27309. JSON.stringify(
  27310. currentChunk.map((node) => stringifyNode(node, context)).join("")
  27311. ).replace(expReplaceRE, `" + $1 + "`),
  27312. // the 2nd argument indicates the number of DOM nodes this static vnode
  27313. // will insert / hydrate
  27314. String(currentChunk.length)
  27315. ]);
  27316. const deleteCount = currentChunk.length - 1;
  27317. if (isParentCached) {
  27318. children.splice(
  27319. currentIndex - currentChunk.length,
  27320. currentChunk.length,
  27321. // @ts-expect-error
  27322. staticCall
  27323. );
  27324. } else {
  27325. currentChunk[0].codegenNode.value = staticCall;
  27326. if (currentChunk.length > 1) {
  27327. children.splice(currentIndex - currentChunk.length + 1, deleteCount);
  27328. const cacheIndex = context.cached.indexOf(
  27329. currentChunk[currentChunk.length - 1].codegenNode
  27330. );
  27331. if (cacheIndex > -1) {
  27332. for (let i2 = cacheIndex; i2 < context.cached.length; i2++) {
  27333. const c = context.cached[i2];
  27334. if (c) c.index -= deleteCount;
  27335. }
  27336. context.cached.splice(cacheIndex - deleteCount + 1, deleteCount);
  27337. }
  27338. }
  27339. }
  27340. return deleteCount;
  27341. }
  27342. return 0;
  27343. };
  27344. let i = 0;
  27345. for (; i < children.length; i++) {
  27346. const child = children[i];
  27347. const isCached = isParentCached || getCachedNode(child);
  27348. if (isCached) {
  27349. const result = analyzeNode(child);
  27350. if (result) {
  27351. nc += result[0];
  27352. ec += result[1];
  27353. currentChunk.push(child);
  27354. continue;
  27355. }
  27356. }
  27357. i -= stringifyCurrentChunk(i);
  27358. nc = 0;
  27359. ec = 0;
  27360. currentChunk.length = 0;
  27361. }
  27362. stringifyCurrentChunk(i);
  27363. };
  27364. const getCachedNode = (node) => {
  27365. if ((node.type === 1 && node.tagType === 0 || node.type === 12) && node.codegenNode && node.codegenNode.type === 20) {
  27366. return node.codegenNode;
  27367. }
  27368. };
  27369. const dataAriaRE = /^(?:data|aria)-/;
  27370. const isStringifiableAttr = (name, ns) => {
  27371. return (ns === 0 ? isKnownHtmlAttr(name) : ns === 1 ? isKnownSvgAttr(name) : ns === 2 ? isKnownMathMLAttr(name) : false) || dataAriaRE.test(name);
  27372. };
  27373. const isNonStringifiable = /* @__PURE__ */ makeMap(
  27374. `caption,thead,tr,th,tbody,td,tfoot,colgroup,col`
  27375. );
  27376. function analyzeNode(node) {
  27377. if (node.type === 1 && isNonStringifiable(node.tag)) {
  27378. return false;
  27379. }
  27380. if (node.type === 1 && findDir(node, "once", true)) {
  27381. return false;
  27382. }
  27383. if (node.type === 12) {
  27384. return [1, 0];
  27385. }
  27386. let nc = 1;
  27387. let ec = node.props.length > 0 ? 1 : 0;
  27388. let bailed = false;
  27389. const bail = () => {
  27390. bailed = true;
  27391. return false;
  27392. };
  27393. function walk(node2) {
  27394. const isOptionTag = node2.tag === "option" && node2.ns === 0;
  27395. for (let i = 0; i < node2.props.length; i++) {
  27396. const p = node2.props[i];
  27397. if (p.type === 6 && !isStringifiableAttr(p.name, node2.ns)) {
  27398. return bail();
  27399. }
  27400. if (p.type === 7 && p.name === "bind") {
  27401. if (p.arg && (p.arg.type === 8 || p.arg.isStatic && !isStringifiableAttr(p.arg.content, node2.ns))) {
  27402. return bail();
  27403. }
  27404. if (p.exp && (p.exp.type === 8 || p.exp.constType < 3)) {
  27405. return bail();
  27406. }
  27407. if (isOptionTag && isStaticArgOf(p.arg, "value") && p.exp && !p.exp.isStatic) {
  27408. return bail();
  27409. }
  27410. }
  27411. }
  27412. for (let i = 0; i < node2.children.length; i++) {
  27413. nc++;
  27414. const child = node2.children[i];
  27415. if (child.type === 1) {
  27416. if (child.props.length > 0) {
  27417. ec++;
  27418. }
  27419. walk(child);
  27420. if (bailed) {
  27421. return false;
  27422. }
  27423. }
  27424. }
  27425. return true;
  27426. }
  27427. return walk(node) ? [nc, ec] : false;
  27428. }
  27429. function stringifyNode(node, context) {
  27430. if (isString$1(node)) {
  27431. return node;
  27432. }
  27433. if (isSymbol$1(node)) {
  27434. return ``;
  27435. }
  27436. switch (node.type) {
  27437. case 1:
  27438. return stringifyElement(node, context);
  27439. case 2:
  27440. return escapeHtml(node.content);
  27441. case 3:
  27442. return `<!--${escapeHtml(node.content)}-->`;
  27443. case 5:
  27444. return escapeHtml(toDisplayString(evaluateConstant(node.content)));
  27445. case 8:
  27446. return escapeHtml(evaluateConstant(node));
  27447. case 12:
  27448. return stringifyNode(node.content, context);
  27449. default:
  27450. return "";
  27451. }
  27452. }
  27453. function stringifyElement(node, context) {
  27454. let res = `<${node.tag}`;
  27455. let innerHTML = "";
  27456. for (let i = 0; i < node.props.length; i++) {
  27457. const p = node.props[i];
  27458. if (p.type === 6) {
  27459. res += ` ${p.name}`;
  27460. if (p.value) {
  27461. res += `="${escapeHtml(p.value.content)}"`;
  27462. }
  27463. } else if (p.type === 7) {
  27464. if (p.name === "bind") {
  27465. const exp = p.exp;
  27466. if (exp.content[0] === "_") {
  27467. res += ` ${p.arg.content}="__VUE_EXP_START__${exp.content}__VUE_EXP_END__"`;
  27468. continue;
  27469. }
  27470. if (isBooleanAttr(p.arg.content) && exp.content === "false") {
  27471. continue;
  27472. }
  27473. let evaluated = evaluateConstant(exp);
  27474. if (evaluated != null) {
  27475. const arg = p.arg && p.arg.content;
  27476. if (arg === "class") {
  27477. evaluated = normalizeClass(evaluated);
  27478. } else if (arg === "style") {
  27479. evaluated = stringifyStyle(normalizeStyle(evaluated));
  27480. }
  27481. res += ` ${p.arg.content}="${escapeHtml(
  27482. evaluated
  27483. )}"`;
  27484. }
  27485. } else if (p.name === "html") {
  27486. innerHTML = evaluateConstant(p.exp);
  27487. } else if (p.name === "text") {
  27488. innerHTML = escapeHtml(
  27489. toDisplayString(evaluateConstant(p.exp))
  27490. );
  27491. }
  27492. }
  27493. }
  27494. if (context.scopeId) {
  27495. res += ` ${context.scopeId}`;
  27496. }
  27497. res += `>`;
  27498. if (innerHTML) {
  27499. res += innerHTML;
  27500. } else {
  27501. for (let i = 0; i < node.children.length; i++) {
  27502. res += stringifyNode(node.children[i], context);
  27503. }
  27504. }
  27505. if (!isVoidTag(node.tag)) {
  27506. res += `</${node.tag}>`;
  27507. }
  27508. return res;
  27509. }
  27510. function evaluateConstant(exp) {
  27511. if (exp.type === 4) {
  27512. return new Function(`return (${exp.content})`)();
  27513. } else {
  27514. let res = ``;
  27515. exp.children.forEach((c) => {
  27516. if (isString$1(c) || isSymbol$1(c)) {
  27517. return;
  27518. }
  27519. if (c.type === 2) {
  27520. res += c.content;
  27521. } else if (c.type === 5) {
  27522. res += toDisplayString(evaluateConstant(c.content));
  27523. } else {
  27524. res += evaluateConstant(c);
  27525. }
  27526. });
  27527. return res;
  27528. }
  27529. }
  27530. const ignoreSideEffectTags = (node, context) => {
  27531. if (node.type === 1 && node.tagType === 0 && (node.tag === "script" || node.tag === "style")) {
  27532. context.onError(
  27533. createDOMCompilerError(
  27534. 64,
  27535. node.loc
  27536. )
  27537. );
  27538. context.removeNode();
  27539. }
  27540. };
  27541. function isValidHTMLNesting(parent, child) {
  27542. if (parent === "template") {
  27543. return true;
  27544. }
  27545. if (parent in onlyValidChildren) {
  27546. return onlyValidChildren[parent].has(child);
  27547. }
  27548. if (child in onlyValidParents) {
  27549. return onlyValidParents[child].has(parent);
  27550. }
  27551. if (parent in knownInvalidChildren) {
  27552. if (knownInvalidChildren[parent].has(child)) return false;
  27553. }
  27554. if (child in knownInvalidParents) {
  27555. if (knownInvalidParents[child].has(parent)) return false;
  27556. }
  27557. return true;
  27558. }
  27559. const headings = /* @__PURE__ */ new Set(["h1", "h2", "h3", "h4", "h5", "h6"]);
  27560. const emptySet = /* @__PURE__ */ new Set([]);
  27561. const onlyValidChildren = {
  27562. head: /* @__PURE__ */ new Set([
  27563. "base",
  27564. "basefront",
  27565. "bgsound",
  27566. "link",
  27567. "meta",
  27568. "title",
  27569. "noscript",
  27570. "noframes",
  27571. "style",
  27572. "script",
  27573. "template"
  27574. ]),
  27575. optgroup: /* @__PURE__ */ new Set(["option"]),
  27576. select: /* @__PURE__ */ new Set(["optgroup", "option", "hr"]),
  27577. // table
  27578. table: /* @__PURE__ */ new Set(["caption", "colgroup", "tbody", "tfoot", "thead"]),
  27579. tr: /* @__PURE__ */ new Set(["td", "th"]),
  27580. colgroup: /* @__PURE__ */ new Set(["col"]),
  27581. tbody: /* @__PURE__ */ new Set(["tr"]),
  27582. thead: /* @__PURE__ */ new Set(["tr"]),
  27583. tfoot: /* @__PURE__ */ new Set(["tr"]),
  27584. // these elements can not have any children elements
  27585. script: emptySet,
  27586. iframe: emptySet,
  27587. option: emptySet,
  27588. textarea: emptySet,
  27589. style: emptySet,
  27590. title: emptySet
  27591. };
  27592. const onlyValidParents = {
  27593. // sections
  27594. html: emptySet,
  27595. body: /* @__PURE__ */ new Set(["html"]),
  27596. head: /* @__PURE__ */ new Set(["html"]),
  27597. // table
  27598. td: /* @__PURE__ */ new Set(["tr"]),
  27599. colgroup: /* @__PURE__ */ new Set(["table"]),
  27600. caption: /* @__PURE__ */ new Set(["table"]),
  27601. tbody: /* @__PURE__ */ new Set(["table"]),
  27602. tfoot: /* @__PURE__ */ new Set(["table"]),
  27603. col: /* @__PURE__ */ new Set(["colgroup"]),
  27604. th: /* @__PURE__ */ new Set(["tr"]),
  27605. thead: /* @__PURE__ */ new Set(["table"]),
  27606. tr: /* @__PURE__ */ new Set(["tbody", "thead", "tfoot"]),
  27607. // data list
  27608. dd: /* @__PURE__ */ new Set(["dl", "div"]),
  27609. dt: /* @__PURE__ */ new Set(["dl", "div"]),
  27610. // other
  27611. figcaption: /* @__PURE__ */ new Set(["figure"]),
  27612. // li: new Set(["ul", "ol"]),
  27613. summary: /* @__PURE__ */ new Set(["details"]),
  27614. area: /* @__PURE__ */ new Set(["map"])
  27615. };
  27616. const knownInvalidChildren = {
  27617. p: /* @__PURE__ */ new Set([
  27618. "address",
  27619. "article",
  27620. "aside",
  27621. "blockquote",
  27622. "center",
  27623. "details",
  27624. "dialog",
  27625. "dir",
  27626. "div",
  27627. "dl",
  27628. "fieldset",
  27629. "figure",
  27630. "footer",
  27631. "form",
  27632. "h1",
  27633. "h2",
  27634. "h3",
  27635. "h4",
  27636. "h5",
  27637. "h6",
  27638. "header",
  27639. "hgroup",
  27640. "hr",
  27641. "li",
  27642. "main",
  27643. "nav",
  27644. "menu",
  27645. "ol",
  27646. "p",
  27647. "pre",
  27648. "section",
  27649. "table",
  27650. "ul"
  27651. ]),
  27652. svg: /* @__PURE__ */ new Set([
  27653. "b",
  27654. "blockquote",
  27655. "br",
  27656. "code",
  27657. "dd",
  27658. "div",
  27659. "dl",
  27660. "dt",
  27661. "em",
  27662. "embed",
  27663. "h1",
  27664. "h2",
  27665. "h3",
  27666. "h4",
  27667. "h5",
  27668. "h6",
  27669. "hr",
  27670. "i",
  27671. "img",
  27672. "li",
  27673. "menu",
  27674. "meta",
  27675. "ol",
  27676. "p",
  27677. "pre",
  27678. "ruby",
  27679. "s",
  27680. "small",
  27681. "span",
  27682. "strong",
  27683. "sub",
  27684. "sup",
  27685. "table",
  27686. "u",
  27687. "ul",
  27688. "var"
  27689. ])
  27690. };
  27691. const knownInvalidParents = {
  27692. a: /* @__PURE__ */ new Set(["a"]),
  27693. button: /* @__PURE__ */ new Set(["button"]),
  27694. dd: /* @__PURE__ */ new Set(["dd", "dt"]),
  27695. dt: /* @__PURE__ */ new Set(["dd", "dt"]),
  27696. form: /* @__PURE__ */ new Set(["form"]),
  27697. li: /* @__PURE__ */ new Set(["li"]),
  27698. h1: headings,
  27699. h2: headings,
  27700. h3: headings,
  27701. h4: headings,
  27702. h5: headings,
  27703. h6: headings
  27704. };
  27705. const validateHtmlNesting = (node, context) => {
  27706. if (node.type === 1 && node.tagType === 0 && context.parent && context.parent.type === 1 && context.parent.tagType === 0 && !isValidHTMLNesting(context.parent.tag, node.tag)) {
  27707. const error = new SyntaxError(
  27708. `<${node.tag}> cannot be child of <${context.parent.tag}>, according to HTML specifications. This can cause hydration errors or potentially disrupt future functionality.`
  27709. );
  27710. error.loc = node.loc;
  27711. context.onWarn(error);
  27712. }
  27713. };
  27714. const DOMNodeTransforms = [
  27715. transformStyle,
  27716. ...[transformTransition, validateHtmlNesting]
  27717. ];
  27718. const DOMDirectiveTransforms = {
  27719. cloak: noopDirectiveTransform,
  27720. html: transformVHtml,
  27721. text: transformVText,
  27722. model: transformModel,
  27723. // override compiler-core
  27724. on: transformOn,
  27725. // override compiler-core
  27726. show: transformShow
  27727. };
  27728. function compile$1(src, options = {}) {
  27729. return baseCompile(
  27730. src,
  27731. extend({}, parserOptions, options, {
  27732. nodeTransforms: [
  27733. // ignore <script> and <tag>
  27734. // this is not put inside DOMNodeTransforms because that list is used
  27735. // by compiler-ssr to generate vnode fallback branches
  27736. ignoreSideEffectTags,
  27737. ...DOMNodeTransforms,
  27738. ...options.nodeTransforms || []
  27739. ],
  27740. directiveTransforms: extend(
  27741. {},
  27742. DOMDirectiveTransforms,
  27743. options.directiveTransforms || {}
  27744. ),
  27745. transformHoist: stringifyStatic
  27746. })
  27747. );
  27748. }
  27749. function parse$3(template, options = {}) {
  27750. return baseParse(template, extend({}, parserOptions, options));
  27751. }
  27752. var CompilerDOM = /*#__PURE__*/Object.freeze({
  27753. __proto__: null,
  27754. BASE_TRANSITION: BASE_TRANSITION,
  27755. BindingTypes: BindingTypes,
  27756. CAMELIZE: CAMELIZE,
  27757. CAPITALIZE: CAPITALIZE,
  27758. CREATE_BLOCK: CREATE_BLOCK,
  27759. CREATE_COMMENT: CREATE_COMMENT,
  27760. CREATE_ELEMENT_BLOCK: CREATE_ELEMENT_BLOCK,
  27761. CREATE_ELEMENT_VNODE: CREATE_ELEMENT_VNODE,
  27762. CREATE_SLOTS: CREATE_SLOTS,
  27763. CREATE_STATIC: CREATE_STATIC,
  27764. CREATE_TEXT: CREATE_TEXT,
  27765. CREATE_VNODE: CREATE_VNODE,
  27766. CompilerDeprecationTypes: CompilerDeprecationTypes,
  27767. ConstantTypes: ConstantTypes,
  27768. DOMDirectiveTransforms: DOMDirectiveTransforms,
  27769. DOMErrorCodes: DOMErrorCodes,
  27770. DOMErrorMessages: DOMErrorMessages,
  27771. DOMNodeTransforms: DOMNodeTransforms,
  27772. ElementTypes: ElementTypes,
  27773. ErrorCodes: ErrorCodes,
  27774. FRAGMENT: FRAGMENT,
  27775. GUARD_REACTIVE_PROPS: GUARD_REACTIVE_PROPS,
  27776. IS_MEMO_SAME: IS_MEMO_SAME,
  27777. IS_REF: IS_REF,
  27778. KEEP_ALIVE: KEEP_ALIVE,
  27779. MERGE_PROPS: MERGE_PROPS,
  27780. NORMALIZE_CLASS: NORMALIZE_CLASS,
  27781. NORMALIZE_PROPS: NORMALIZE_PROPS,
  27782. NORMALIZE_STYLE: NORMALIZE_STYLE,
  27783. Namespaces: Namespaces,
  27784. NodeTypes: NodeTypes,
  27785. OPEN_BLOCK: OPEN_BLOCK,
  27786. POP_SCOPE_ID: POP_SCOPE_ID,
  27787. PUSH_SCOPE_ID: PUSH_SCOPE_ID,
  27788. RENDER_LIST: RENDER_LIST,
  27789. RENDER_SLOT: RENDER_SLOT,
  27790. RESOLVE_COMPONENT: RESOLVE_COMPONENT,
  27791. RESOLVE_DIRECTIVE: RESOLVE_DIRECTIVE,
  27792. RESOLVE_DYNAMIC_COMPONENT: RESOLVE_DYNAMIC_COMPONENT,
  27793. RESOLVE_FILTER: RESOLVE_FILTER,
  27794. SET_BLOCK_TRACKING: SET_BLOCK_TRACKING,
  27795. SUSPENSE: SUSPENSE,
  27796. TELEPORT: TELEPORT,
  27797. TO_DISPLAY_STRING: TO_DISPLAY_STRING,
  27798. TO_HANDLERS: TO_HANDLERS,
  27799. TO_HANDLER_KEY: TO_HANDLER_KEY,
  27800. TRANSITION: TRANSITION,
  27801. TRANSITION_GROUP: TRANSITION_GROUP,
  27802. TS_NODE_TYPES: TS_NODE_TYPES,
  27803. UNREF: UNREF,
  27804. V_MODEL_CHECKBOX: V_MODEL_CHECKBOX,
  27805. V_MODEL_DYNAMIC: V_MODEL_DYNAMIC,
  27806. V_MODEL_RADIO: V_MODEL_RADIO,
  27807. V_MODEL_SELECT: V_MODEL_SELECT,
  27808. V_MODEL_TEXT: V_MODEL_TEXT,
  27809. V_ON_WITH_KEYS: V_ON_WITH_KEYS,
  27810. V_ON_WITH_MODIFIERS: V_ON_WITH_MODIFIERS,
  27811. V_SHOW: V_SHOW,
  27812. WITH_CTX: WITH_CTX,
  27813. WITH_DIRECTIVES: WITH_DIRECTIVES,
  27814. WITH_MEMO: WITH_MEMO,
  27815. advancePositionWithClone: advancePositionWithClone,
  27816. advancePositionWithMutation: advancePositionWithMutation,
  27817. assert: assert,
  27818. baseCompile: baseCompile,
  27819. baseParse: baseParse,
  27820. buildDirectiveArgs: buildDirectiveArgs,
  27821. buildProps: buildProps,
  27822. buildSlots: buildSlots,
  27823. checkCompatEnabled: checkCompatEnabled,
  27824. compile: compile$1,
  27825. convertToBlock: convertToBlock,
  27826. createArrayExpression: createArrayExpression,
  27827. createAssignmentExpression: createAssignmentExpression,
  27828. createBlockStatement: createBlockStatement,
  27829. createCacheExpression: createCacheExpression,
  27830. createCallExpression: createCallExpression,
  27831. createCompilerError: createCompilerError,
  27832. createCompoundExpression: createCompoundExpression,
  27833. createConditionalExpression: createConditionalExpression,
  27834. createDOMCompilerError: createDOMCompilerError,
  27835. createForLoopParams: createForLoopParams,
  27836. createFunctionExpression: createFunctionExpression,
  27837. createIfStatement: createIfStatement,
  27838. createInterpolation: createInterpolation,
  27839. createObjectExpression: createObjectExpression,
  27840. createObjectProperty: createObjectProperty,
  27841. createReturnStatement: createReturnStatement,
  27842. createRoot: createRoot,
  27843. createSequenceExpression: createSequenceExpression,
  27844. createSimpleExpression: createSimpleExpression,
  27845. createStructuralDirectiveTransform: createStructuralDirectiveTransform,
  27846. createTemplateLiteral: createTemplateLiteral,
  27847. createTransformContext: createTransformContext,
  27848. createVNodeCall: createVNodeCall,
  27849. errorMessages: errorMessages$1,
  27850. extractIdentifiers: extractIdentifiers$1,
  27851. findDir: findDir,
  27852. findProp: findProp,
  27853. forAliasRE: forAliasRE,
  27854. generate: generate,
  27855. generateCodeFrame: generateCodeFrame,
  27856. getBaseTransformPreset: getBaseTransformPreset,
  27857. getConstantType: getConstantType,
  27858. getMemoedVNodeCall: getMemoedVNodeCall,
  27859. getVNodeBlockHelper: getVNodeBlockHelper,
  27860. getVNodeHelper: getVNodeHelper,
  27861. hasDynamicKeyVBind: hasDynamicKeyVBind,
  27862. hasScopeRef: hasScopeRef,
  27863. helperNameMap: helperNameMap,
  27864. injectProp: injectProp,
  27865. isAllWhitespace: isAllWhitespace,
  27866. isCommentOrWhitespace: isCommentOrWhitespace,
  27867. isCoreComponent: isCoreComponent,
  27868. isFnExpression: isFnExpression,
  27869. isFnExpressionBrowser: isFnExpressionBrowser,
  27870. isFnExpressionNode: isFnExpressionNode,
  27871. isFunctionType: isFunctionType,
  27872. isInDestructureAssignment: isInDestructureAssignment,
  27873. isInNewExpression: isInNewExpression,
  27874. isMemberExpression: isMemberExpression,
  27875. isMemberExpressionBrowser: isMemberExpressionBrowser,
  27876. isMemberExpressionNode: isMemberExpressionNode,
  27877. isReferencedIdentifier: isReferencedIdentifier,
  27878. isSimpleIdentifier: isSimpleIdentifier,
  27879. isSlotOutlet: isSlotOutlet,
  27880. isStaticArgOf: isStaticArgOf,
  27881. isStaticExp: isStaticExp,
  27882. isStaticProperty: isStaticProperty,
  27883. isStaticPropertyKey: isStaticPropertyKey,
  27884. isTemplateNode: isTemplateNode,
  27885. isText: isText$1,
  27886. isVPre: isVPre,
  27887. isVSlot: isVSlot,
  27888. isWhitespaceText: isWhitespaceText,
  27889. locStub: locStub,
  27890. noopDirectiveTransform: noopDirectiveTransform,
  27891. parse: parse$3,
  27892. parserOptions: parserOptions,
  27893. processExpression: processExpression,
  27894. processFor: processFor,
  27895. processIf: processIf,
  27896. processSlotOutlet: processSlotOutlet,
  27897. registerRuntimeHelpers: registerRuntimeHelpers,
  27898. resolveComponentType: resolveComponentType,
  27899. stringifyExpression: stringifyExpression,
  27900. toValidAssetId: toValidAssetId,
  27901. trackSlotScopes: trackSlotScopes,
  27902. trackVForSlotScopes: trackVForSlotScopes,
  27903. transform: transform,
  27904. transformBind: transformBind,
  27905. transformElement: transformElement,
  27906. transformExpression: transformExpression,
  27907. transformModel: transformModel$1,
  27908. transformOn: transformOn$1,
  27909. transformStyle: transformStyle,
  27910. transformVBindShorthand: transformVBindShorthand,
  27911. traverseNode: traverseNode,
  27912. unwrapTSNode: unwrapTSNode,
  27913. validFirstIdentCharRE: validFirstIdentCharRE,
  27914. walkBlockDeclarations: walkBlockDeclarations,
  27915. walkFunctionParams: walkFunctionParams,
  27916. walkIdentifiers: walkIdentifiers,
  27917. warnDeprecation: warnDeprecation
  27918. });
  27919. var hashSum;
  27920. var hasRequiredHashSum;
  27921. function requireHashSum () {
  27922. if (hasRequiredHashSum) return hashSum;
  27923. hasRequiredHashSum = 1;
  27924. function pad (hash, len) {
  27925. while (hash.length < len) {
  27926. hash = '0' + hash;
  27927. }
  27928. return hash;
  27929. }
  27930. function fold (hash, text) {
  27931. var i;
  27932. var chr;
  27933. var len;
  27934. if (text.length === 0) {
  27935. return hash;
  27936. }
  27937. for (i = 0, len = text.length; i < len; i++) {
  27938. chr = text.charCodeAt(i);
  27939. hash = ((hash << 5) - hash) + chr;
  27940. hash |= 0;
  27941. }
  27942. return hash < 0 ? hash * -2 : hash;
  27943. }
  27944. function foldObject (hash, o, seen) {
  27945. return Object.keys(o).sort().reduce(foldKey, hash);
  27946. function foldKey (hash, key) {
  27947. return foldValue(hash, o[key], key, seen);
  27948. }
  27949. }
  27950. function foldValue (input, value, key, seen) {
  27951. var hash = fold(fold(fold(input, key), toString(value)), typeof value);
  27952. if (value === null) {
  27953. return fold(hash, 'null');
  27954. }
  27955. if (value === undefined) {
  27956. return fold(hash, 'undefined');
  27957. }
  27958. if (typeof value === 'object' || typeof value === 'function') {
  27959. if (seen.indexOf(value) !== -1) {
  27960. return fold(hash, '[Circular]' + key);
  27961. }
  27962. seen.push(value);
  27963. var objHash = foldObject(hash, value, seen);
  27964. if (!('valueOf' in value) || typeof value.valueOf !== 'function') {
  27965. return objHash;
  27966. }
  27967. try {
  27968. return fold(objHash, String(value.valueOf()))
  27969. } catch (err) {
  27970. return fold(objHash, '[valueOf exception]' + (err.stack || err.message))
  27971. }
  27972. }
  27973. return fold(hash, value.toString());
  27974. }
  27975. function toString (o) {
  27976. return Object.prototype.toString.call(o);
  27977. }
  27978. function sum (o) {
  27979. return pad(foldValue(0, o, '', []).toString(16), 8);
  27980. }
  27981. hashSum = sum;
  27982. return hashSum;
  27983. }
  27984. var hashSumExports = /*@__PURE__*/ requireHashSum();
  27985. var hash = /*@__PURE__*/getDefaultExportFromCjs(hashSumExports);
  27986. const CSS_VARS_HELPER = `useCssVars`;
  27987. function genCssVarsFromList(vars, id, isProd, isSSR = false) {
  27988. return `{
  27989. ${vars.map(
  27990. (key) => (
  27991. // The `:` prefix here is used in `ssrRenderStyle` to distinguish whether
  27992. // a custom property comes from `ssrCssVars`. If it does, we need to reset
  27993. // its value to `initial` on the component instance to avoid unintentionally
  27994. // inheriting the same property value from a different instance of the same
  27995. // component in the outer scope.
  27996. `"${isSSR ? `:--` : ``}${genVarName(id, key, isProd, isSSR)}": (${key})`
  27997. )
  27998. ).join(",\n ")}
  27999. }`;
  28000. }
  28001. function genVarName(id, raw, isProd, isSSR = false) {
  28002. if (isProd) {
  28003. return hash(id + raw).replace(/^\d/, (r) => `v${r}`);
  28004. } else {
  28005. return `${id}-${getEscapedCssVarName(raw, isSSR)}`;
  28006. }
  28007. }
  28008. function normalizeExpression(exp) {
  28009. exp = exp.trim();
  28010. if (exp[0] === `'` && exp[exp.length - 1] === `'` || exp[0] === `"` && exp[exp.length - 1] === `"`) {
  28011. return exp.slice(1, -1);
  28012. }
  28013. return exp;
  28014. }
  28015. const vBindRE = /v-bind\s*\(/g;
  28016. function parseCssVars(sfc) {
  28017. const vars = [];
  28018. sfc.styles.forEach((style) => {
  28019. let match;
  28020. const content = style.content.replace(/\/\*([\s\S]*?)\*\/|\/\/.*/g, "");
  28021. while (match = vBindRE.exec(content)) {
  28022. const start = match.index + match[0].length;
  28023. const end = lexBinding(content, start);
  28024. if (end !== null) {
  28025. const variable = normalizeExpression(content.slice(start, end));
  28026. if (!vars.includes(variable)) {
  28027. vars.push(variable);
  28028. }
  28029. }
  28030. }
  28031. });
  28032. return vars;
  28033. }
  28034. function lexBinding(content, start) {
  28035. let state = 0 /* inParens */;
  28036. let parenDepth = 0;
  28037. for (let i = start; i < content.length; i++) {
  28038. const char = content.charAt(i);
  28039. switch (state) {
  28040. case 0 /* inParens */:
  28041. if (char === `'`) {
  28042. state = 1 /* inSingleQuoteString */;
  28043. } else if (char === `"`) {
  28044. state = 2 /* inDoubleQuoteString */;
  28045. } else if (char === `(`) {
  28046. parenDepth++;
  28047. } else if (char === `)`) {
  28048. if (parenDepth > 0) {
  28049. parenDepth--;
  28050. } else {
  28051. return i;
  28052. }
  28053. }
  28054. break;
  28055. case 1 /* inSingleQuoteString */:
  28056. if (char === `'`) {
  28057. state = 0 /* inParens */;
  28058. }
  28059. break;
  28060. case 2 /* inDoubleQuoteString */:
  28061. if (char === `"`) {
  28062. state = 0 /* inParens */;
  28063. }
  28064. break;
  28065. }
  28066. }
  28067. return null;
  28068. }
  28069. const cssVarsPlugin = (opts) => {
  28070. const { id, isProd } = opts;
  28071. return {
  28072. postcssPlugin: "vue-sfc-vars",
  28073. Declaration(decl) {
  28074. const value = decl.value;
  28075. if (vBindRE.test(value)) {
  28076. vBindRE.lastIndex = 0;
  28077. let transformed = "";
  28078. let lastIndex = 0;
  28079. let match;
  28080. while (match = vBindRE.exec(value)) {
  28081. const start = match.index + match[0].length;
  28082. const end = lexBinding(value, start);
  28083. if (end !== null) {
  28084. const variable = normalizeExpression(value.slice(start, end));
  28085. transformed += value.slice(lastIndex, match.index) + `var(--${genVarName(id, variable, isProd)})`;
  28086. lastIndex = end + 1;
  28087. }
  28088. }
  28089. decl.value = transformed + value.slice(lastIndex);
  28090. }
  28091. }
  28092. };
  28093. };
  28094. cssVarsPlugin.postcss = true;
  28095. function genCssVarsCode(vars, bindings, id, isProd) {
  28096. const varsExp = genCssVarsFromList(vars, id, isProd);
  28097. const exp = createSimpleExpression(varsExp, false);
  28098. const context = createTransformContext(createRoot([]), {
  28099. prefixIdentifiers: true,
  28100. inline: true,
  28101. bindingMetadata: bindings.__isScriptSetup === false ? void 0 : bindings
  28102. });
  28103. const transformed = processExpression(exp, context);
  28104. const transformedString = transformed.type === 4 ? transformed.content : transformed.children.map((c) => {
  28105. return typeof c === "string" ? c : c.content;
  28106. }).join("");
  28107. return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`;
  28108. }
  28109. function genNormalScriptCssVarsCode(cssVars, bindings, id, isProd, defaultVar) {
  28110. return `
  28111. import { ${CSS_VARS_HELPER} as _${CSS_VARS_HELPER} } from 'vue'
  28112. const __injectCSSVars__ = () => {
  28113. ${genCssVarsCode(
  28114. cssVars,
  28115. bindings,
  28116. id,
  28117. isProd
  28118. )}}
  28119. const __setup__ = ${defaultVar}.setup
  28120. ${defaultVar}.setup = __setup__
  28121. ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }
  28122. : __injectCSSVars__
  28123. `;
  28124. }
  28125. // shim for using process in browser
  28126. // based off https://github.com/defunctzombie/node-process/blob/master/browser.js
  28127. function defaultSetTimout() {
  28128. throw new Error('setTimeout has not been defined');
  28129. }
  28130. function defaultClearTimeout () {
  28131. throw new Error('clearTimeout has not been defined');
  28132. }
  28133. var cachedSetTimeout = defaultSetTimout;
  28134. var cachedClearTimeout = defaultClearTimeout;
  28135. if (typeof global$1.setTimeout === 'function') {
  28136. cachedSetTimeout = setTimeout;
  28137. }
  28138. if (typeof global$1.clearTimeout === 'function') {
  28139. cachedClearTimeout = clearTimeout;
  28140. }
  28141. function runTimeout(fun) {
  28142. if (cachedSetTimeout === setTimeout) {
  28143. //normal enviroments in sane situations
  28144. return setTimeout(fun, 0);
  28145. }
  28146. // if setTimeout wasn't available but was latter defined
  28147. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  28148. cachedSetTimeout = setTimeout;
  28149. return setTimeout(fun, 0);
  28150. }
  28151. try {
  28152. // when when somebody has screwed with setTimeout but no I.E. maddness
  28153. return cachedSetTimeout(fun, 0);
  28154. } catch(e){
  28155. try {
  28156. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  28157. return cachedSetTimeout.call(null, fun, 0);
  28158. } catch(e){
  28159. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  28160. return cachedSetTimeout.call(this, fun, 0);
  28161. }
  28162. }
  28163. }
  28164. function runClearTimeout(marker) {
  28165. if (cachedClearTimeout === clearTimeout) {
  28166. //normal enviroments in sane situations
  28167. return clearTimeout(marker);
  28168. }
  28169. // if clearTimeout wasn't available but was latter defined
  28170. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  28171. cachedClearTimeout = clearTimeout;
  28172. return clearTimeout(marker);
  28173. }
  28174. try {
  28175. // when when somebody has screwed with setTimeout but no I.E. maddness
  28176. return cachedClearTimeout(marker);
  28177. } catch (e){
  28178. try {
  28179. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  28180. return cachedClearTimeout.call(null, marker);
  28181. } catch (e){
  28182. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  28183. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  28184. return cachedClearTimeout.call(this, marker);
  28185. }
  28186. }
  28187. }
  28188. var queue = [];
  28189. var draining = false;
  28190. var currentQueue;
  28191. var queueIndex = -1;
  28192. function cleanUpNextTick() {
  28193. if (!draining || !currentQueue) {
  28194. return;
  28195. }
  28196. draining = false;
  28197. if (currentQueue.length) {
  28198. queue = currentQueue.concat(queue);
  28199. } else {
  28200. queueIndex = -1;
  28201. }
  28202. if (queue.length) {
  28203. drainQueue();
  28204. }
  28205. }
  28206. function drainQueue() {
  28207. if (draining) {
  28208. return;
  28209. }
  28210. var timeout = runTimeout(cleanUpNextTick);
  28211. draining = true;
  28212. var len = queue.length;
  28213. while(len) {
  28214. currentQueue = queue;
  28215. queue = [];
  28216. while (++queueIndex < len) {
  28217. if (currentQueue) {
  28218. currentQueue[queueIndex].run();
  28219. }
  28220. }
  28221. queueIndex = -1;
  28222. len = queue.length;
  28223. }
  28224. currentQueue = null;
  28225. draining = false;
  28226. runClearTimeout(timeout);
  28227. }
  28228. function nextTick(fun) {
  28229. var args = new Array(arguments.length - 1);
  28230. if (arguments.length > 1) {
  28231. for (var i = 1; i < arguments.length; i++) {
  28232. args[i - 1] = arguments[i];
  28233. }
  28234. }
  28235. queue.push(new Item(fun, args));
  28236. if (queue.length === 1 && !draining) {
  28237. runTimeout(drainQueue);
  28238. }
  28239. }
  28240. // v8 likes predictible objects
  28241. function Item(fun, array) {
  28242. this.fun = fun;
  28243. this.array = array;
  28244. }
  28245. Item.prototype.run = function () {
  28246. this.fun.apply(null, this.array);
  28247. };
  28248. var title = 'browser';
  28249. var platform = 'browser';
  28250. var browser = true;
  28251. var env = {};
  28252. var argv = [];
  28253. var version$1 = ''; // empty string to avoid regexp issues
  28254. var versions = {};
  28255. var release = {};
  28256. var config = {};
  28257. function noop() {}
  28258. var on = noop;
  28259. var addListener = noop;
  28260. var once = noop;
  28261. var off = noop;
  28262. var removeListener = noop;
  28263. var removeAllListeners = noop;
  28264. var emit = noop;
  28265. function binding(name) {
  28266. throw new Error('process.binding is not supported');
  28267. }
  28268. function cwd () { return '/' }
  28269. function chdir (dir) {
  28270. throw new Error('process.chdir is not supported');
  28271. }function umask() { return 0; }
  28272. // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
  28273. var performance = global$1.performance || {};
  28274. var performanceNow =
  28275. performance.now ||
  28276. performance.mozNow ||
  28277. performance.msNow ||
  28278. performance.oNow ||
  28279. performance.webkitNow ||
  28280. function(){ return (new Date()).getTime() };
  28281. // generate timestamp or delta
  28282. // see http://nodejs.org/api/process.html#process_process_hrtime
  28283. function hrtime(previousTimestamp){
  28284. var clocktime = performanceNow.call(performance)*1e-3;
  28285. var seconds = Math.floor(clocktime);
  28286. var nanoseconds = Math.floor((clocktime%1)*1e9);
  28287. if (previousTimestamp) {
  28288. seconds = seconds - previousTimestamp[0];
  28289. nanoseconds = nanoseconds - previousTimestamp[1];
  28290. if (nanoseconds<0) {
  28291. seconds--;
  28292. nanoseconds += 1e9;
  28293. }
  28294. }
  28295. return [seconds,nanoseconds]
  28296. }
  28297. var startTime = new Date();
  28298. function uptime() {
  28299. var currentTime = new Date();
  28300. var dif = currentTime - startTime;
  28301. return dif / 1000;
  28302. }
  28303. var browser$1 = {
  28304. nextTick: nextTick,
  28305. title: title,
  28306. browser: browser,
  28307. env: env,
  28308. argv: argv,
  28309. version: version$1,
  28310. versions: versions,
  28311. on: on,
  28312. addListener: addListener,
  28313. once: once,
  28314. off: off,
  28315. removeListener: removeListener,
  28316. removeAllListeners: removeAllListeners,
  28317. emit: emit,
  28318. binding: binding,
  28319. cwd: cwd,
  28320. chdir: chdir,
  28321. umask: umask,
  28322. hrtime: hrtime,
  28323. platform: platform,
  28324. release: release,
  28325. config: config,
  28326. uptime: uptime
  28327. };
  28328. function createCache(max = 500) {
  28329. {
  28330. return /* @__PURE__ */ new Map();
  28331. }
  28332. }
  28333. function isImportUsed(local, sfc) {
  28334. return resolveTemplateUsedIdentifiers(sfc).has(local);
  28335. }
  28336. const templateAnalysisCache = createCache();
  28337. function resolveTemplateVModelIdentifiers(sfc) {
  28338. return resolveTemplateAnalysisResult(sfc, false).vModelIds;
  28339. }
  28340. function resolveTemplateUsedIdentifiers(sfc) {
  28341. return resolveTemplateAnalysisResult(sfc).usedIds;
  28342. }
  28343. function resolveTemplateAnalysisResult(sfc, collectUsedIds = true) {
  28344. const { content, ast } = sfc.template;
  28345. const cached = templateAnalysisCache.get(content);
  28346. if (cached && (!collectUsedIds || cached.usedIds)) {
  28347. return cached;
  28348. }
  28349. const ids = collectUsedIds ? /* @__PURE__ */ new Set() : void 0;
  28350. const vModelIds = /* @__PURE__ */ new Set();
  28351. ast.children.forEach(walk);
  28352. function walk(node) {
  28353. var _a;
  28354. switch (node.type) {
  28355. case 1:
  28356. let tag = node.tag;
  28357. if (tag.includes(".")) tag = tag.split(".")[0].trim();
  28358. if (!parserOptions.isNativeTag(tag) && !parserOptions.isBuiltInComponent(tag)) {
  28359. if (ids) {
  28360. ids.add(camelize(tag));
  28361. ids.add(capitalize(camelize(tag)));
  28362. }
  28363. }
  28364. for (let i = 0; i < node.props.length; i++) {
  28365. const prop = node.props[i];
  28366. if (prop.type === 7) {
  28367. if (ids) {
  28368. if (!isBuiltInDirective(prop.name)) {
  28369. ids.add(`v${capitalize(camelize(prop.name))}`);
  28370. }
  28371. }
  28372. if (prop.name === "model") {
  28373. const exp = prop.exp;
  28374. if (exp && exp.type === 4) {
  28375. const expString = exp.content.trim();
  28376. if (isSimpleIdentifier(expString) && expString !== "undefined") {
  28377. vModelIds.add(expString);
  28378. }
  28379. }
  28380. }
  28381. if (ids && prop.arg && !prop.arg.isStatic) {
  28382. extractIdentifiers(ids, prop.arg);
  28383. }
  28384. if (ids) {
  28385. if (prop.name === "for") {
  28386. extractIdentifiers(ids, prop.forParseResult.source);
  28387. } else if (prop.exp) {
  28388. extractIdentifiers(ids, prop.exp);
  28389. } else if (prop.name === "bind" && !prop.exp) {
  28390. ids.add(camelize(prop.arg.content));
  28391. }
  28392. }
  28393. }
  28394. if (ids && prop.type === 6 && prop.name === "ref" && ((_a = prop.value) == null ? void 0 : _a.content)) {
  28395. ids.add(prop.value.content);
  28396. }
  28397. }
  28398. node.children.forEach(walk);
  28399. break;
  28400. case 5:
  28401. if (ids) extractIdentifiers(ids, node.content);
  28402. break;
  28403. }
  28404. }
  28405. const result = { usedIds: ids, vModelIds };
  28406. templateAnalysisCache.set(content, result);
  28407. return result;
  28408. }
  28409. function extractIdentifiers(ids, node) {
  28410. if (node.ast) {
  28411. walkIdentifiers(node.ast, (n) => ids.add(n.name));
  28412. } else if (node.ast === null) {
  28413. ids.add(node.content);
  28414. }
  28415. }
  28416. var __defProp$a = Object.defineProperty;
  28417. var __defProps$9 = Object.defineProperties;
  28418. var __getOwnPropDescs$9 = Object.getOwnPropertyDescriptors;
  28419. var __getOwnPropSymbols$a = Object.getOwnPropertySymbols;
  28420. var __hasOwnProp$a = Object.prototype.hasOwnProperty;
  28421. var __propIsEnum$a = Object.prototype.propertyIsEnumerable;
  28422. var __defNormalProp$a = (obj, key, value) => key in obj ? __defProp$a(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  28423. var __spreadValues$a = (a, b) => {
  28424. for (var prop in b || (b = {}))
  28425. if (__hasOwnProp$a.call(b, prop))
  28426. __defNormalProp$a(a, prop, b[prop]);
  28427. if (__getOwnPropSymbols$a)
  28428. for (var prop of __getOwnPropSymbols$a(b)) {
  28429. if (__propIsEnum$a.call(b, prop))
  28430. __defNormalProp$a(a, prop, b[prop]);
  28431. }
  28432. return a;
  28433. };
  28434. var __spreadProps$9 = (a, b) => __defProps$9(a, __getOwnPropDescs$9(b));
  28435. const DEFAULT_FILENAME = "anonymous.vue";
  28436. const parseCache$1 = createCache();
  28437. function parse$2(source, options = {}) {
  28438. var _a;
  28439. const sourceKey = genCacheKey(source, __spreadProps$9(__spreadValues$a({}, options), {
  28440. compiler: { parse: (_a = options.compiler) == null ? void 0 : _a.parse }
  28441. }));
  28442. const cache = parseCache$1.get(sourceKey);
  28443. if (cache) {
  28444. return cache;
  28445. }
  28446. const {
  28447. sourceMap = true,
  28448. filename = DEFAULT_FILENAME,
  28449. sourceRoot = "",
  28450. pad = false,
  28451. ignoreEmpty = true,
  28452. compiler = CompilerDOM,
  28453. templateParseOptions = {}
  28454. } = options;
  28455. const descriptor = {
  28456. filename,
  28457. source,
  28458. template: null,
  28459. script: null,
  28460. scriptSetup: null,
  28461. styles: [],
  28462. customBlocks: [],
  28463. cssVars: [],
  28464. slotted: false,
  28465. shouldForceReload: (prevImports) => hmrShouldReload(prevImports, descriptor)
  28466. };
  28467. const errors = [];
  28468. const ast = compiler.parse(source, __spreadProps$9(__spreadValues$a({
  28469. parseMode: "sfc",
  28470. prefixIdentifiers: true
  28471. }, templateParseOptions), {
  28472. onError: (e) => {
  28473. errors.push(e);
  28474. }
  28475. }));
  28476. ast.children.forEach((node) => {
  28477. if (node.type !== 1) {
  28478. return;
  28479. }
  28480. if (ignoreEmpty && node.tag !== "template" && isEmpty(node) && !hasSrc(node)) {
  28481. return;
  28482. }
  28483. switch (node.tag) {
  28484. case "template":
  28485. if (!descriptor.template) {
  28486. const templateBlock = descriptor.template = createBlock(
  28487. node,
  28488. source,
  28489. false
  28490. );
  28491. if (!templateBlock.attrs.src) {
  28492. templateBlock.ast = createRoot(node.children, source);
  28493. }
  28494. if (templateBlock.attrs.functional) {
  28495. const err = new SyntaxError(
  28496. `<template functional> is no longer supported in Vue 3, since functional components no longer have significant performance difference from stateful ones. Just use a normal <template> instead.`
  28497. );
  28498. err.loc = node.props.find(
  28499. (p) => p.type === 6 && p.name === "functional"
  28500. ).loc;
  28501. errors.push(err);
  28502. }
  28503. } else {
  28504. errors.push(createDuplicateBlockError(node));
  28505. }
  28506. break;
  28507. case "script":
  28508. const scriptBlock = createBlock(node, source, pad);
  28509. const isSetup = !!scriptBlock.attrs.setup;
  28510. if (isSetup && !descriptor.scriptSetup) {
  28511. descriptor.scriptSetup = scriptBlock;
  28512. break;
  28513. }
  28514. if (!isSetup && !descriptor.script) {
  28515. descriptor.script = scriptBlock;
  28516. break;
  28517. }
  28518. errors.push(createDuplicateBlockError(node, isSetup));
  28519. break;
  28520. case "style":
  28521. const styleBlock = createBlock(node, source, pad);
  28522. if (styleBlock.attrs.vars) {
  28523. errors.push(
  28524. new SyntaxError(
  28525. `<style vars> has been replaced by a new proposal: https://github.com/vuejs/rfcs/pull/231`
  28526. )
  28527. );
  28528. }
  28529. descriptor.styles.push(styleBlock);
  28530. break;
  28531. default:
  28532. descriptor.customBlocks.push(createBlock(node, source, pad));
  28533. break;
  28534. }
  28535. });
  28536. if (!descriptor.template && !descriptor.script && !descriptor.scriptSetup) {
  28537. errors.push(
  28538. new SyntaxError(
  28539. `At least one <template> or <script> is required in a single file component. ${descriptor.filename}`
  28540. )
  28541. );
  28542. }
  28543. if (descriptor.scriptSetup) {
  28544. if (descriptor.scriptSetup.src) {
  28545. errors.push(
  28546. new SyntaxError(
  28547. `<script setup> cannot use the "src" attribute because its syntax will be ambiguous outside of the component.`
  28548. )
  28549. );
  28550. descriptor.scriptSetup = null;
  28551. }
  28552. if (descriptor.script && descriptor.script.src) {
  28553. errors.push(
  28554. new SyntaxError(
  28555. `<script> cannot use the "src" attribute when <script setup> is also present because they must be processed together.`
  28556. )
  28557. );
  28558. descriptor.script = null;
  28559. }
  28560. }
  28561. let templateColumnOffset = 0;
  28562. if (descriptor.template && (descriptor.template.lang === "pug" || descriptor.template.lang === "jade")) {
  28563. [descriptor.template.content, templateColumnOffset] = dedent(
  28564. descriptor.template.content
  28565. );
  28566. }
  28567. if (sourceMap) {
  28568. const genMap = (block, columnOffset = 0) => {
  28569. if (block && !block.src) {
  28570. block.map = generateSourceMap(
  28571. filename,
  28572. source,
  28573. block.content,
  28574. sourceRoot,
  28575. !pad || block.type === "template" ? block.loc.start.line - 1 : 0,
  28576. columnOffset
  28577. );
  28578. }
  28579. };
  28580. genMap(descriptor.template, templateColumnOffset);
  28581. genMap(descriptor.script);
  28582. descriptor.styles.forEach((s) => genMap(s));
  28583. descriptor.customBlocks.forEach((s) => genMap(s));
  28584. }
  28585. descriptor.cssVars = parseCssVars(descriptor);
  28586. const slottedRE = /(?:::v-|:)slotted\(/;
  28587. descriptor.slotted = descriptor.styles.some(
  28588. (s) => s.scoped && slottedRE.test(s.content)
  28589. );
  28590. const result = {
  28591. descriptor,
  28592. errors
  28593. };
  28594. parseCache$1.set(sourceKey, result);
  28595. return result;
  28596. }
  28597. function createDuplicateBlockError(node, isScriptSetup = false) {
  28598. const err = new SyntaxError(
  28599. `Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element`
  28600. );
  28601. err.loc = node.loc;
  28602. return err;
  28603. }
  28604. function createBlock(node, source, pad) {
  28605. const type = node.tag;
  28606. const loc = node.innerLoc;
  28607. const attrs = {};
  28608. const block = {
  28609. type,
  28610. content: source.slice(loc.start.offset, loc.end.offset),
  28611. loc,
  28612. attrs
  28613. };
  28614. if (pad) {
  28615. block.content = padContent(source, block, pad) + block.content;
  28616. }
  28617. node.props.forEach((p) => {
  28618. if (p.type === 6) {
  28619. const name = p.name;
  28620. attrs[name] = p.value ? p.value.content || true : true;
  28621. if (name === "lang") {
  28622. block.lang = p.value && p.value.content;
  28623. } else if (name === "src") {
  28624. block.src = p.value && p.value.content;
  28625. } else if (type === "style") {
  28626. if (name === "scoped") {
  28627. block.scoped = true;
  28628. } else if (name === "module") {
  28629. block.module = attrs[name];
  28630. }
  28631. } else if (type === "script" && name === "setup") {
  28632. block.setup = attrs.setup;
  28633. }
  28634. }
  28635. });
  28636. return block;
  28637. }
  28638. const splitRE = /\r?\n/g;
  28639. const emptyRE = /^(?:\/\/)?\s*$/;
  28640. const replaceRE = /./g;
  28641. function generateSourceMap(filename, source, generated, sourceRoot, lineOffset, columnOffset) {
  28642. const map = new sourceMapExports.SourceMapGenerator({
  28643. file: filename.replace(/\\/g, "/"),
  28644. sourceRoot: sourceRoot.replace(/\\/g, "/")
  28645. });
  28646. map.setSourceContent(filename, source);
  28647. map._sources.add(filename);
  28648. generated.split(splitRE).forEach((line, index) => {
  28649. if (!emptyRE.test(line)) {
  28650. const originalLine = index + 1 + lineOffset;
  28651. const generatedLine = index + 1;
  28652. for (let i = 0; i < line.length; i++) {
  28653. if (!/\s/.test(line[i])) {
  28654. map._mappings.add({
  28655. originalLine,
  28656. originalColumn: i + columnOffset,
  28657. generatedLine,
  28658. generatedColumn: i,
  28659. source: filename,
  28660. name: null
  28661. });
  28662. }
  28663. }
  28664. }
  28665. });
  28666. return map.toJSON();
  28667. }
  28668. function padContent(content, block, pad) {
  28669. content = content.slice(0, block.loc.start.offset);
  28670. if (pad === "space") {
  28671. return content.replace(replaceRE, " ");
  28672. } else {
  28673. const offset = content.split(splitRE).length;
  28674. const padChar = block.type === "script" && !block.lang ? "//\n" : "\n";
  28675. return Array(offset).join(padChar);
  28676. }
  28677. }
  28678. function hasSrc(node) {
  28679. return node.props.some((p) => {
  28680. if (p.type !== 6) {
  28681. return false;
  28682. }
  28683. return p.name === "src";
  28684. });
  28685. }
  28686. function isEmpty(node) {
  28687. for (let i = 0; i < node.children.length; i++) {
  28688. const child = node.children[i];
  28689. if (child.type !== 2 || child.content.trim() !== "") {
  28690. return false;
  28691. }
  28692. }
  28693. return true;
  28694. }
  28695. function hmrShouldReload(prevImports, next) {
  28696. if (!next.scriptSetup || next.scriptSetup.lang !== "ts" && next.scriptSetup.lang !== "tsx") {
  28697. return false;
  28698. }
  28699. for (const key in prevImports) {
  28700. if (!prevImports[key].isUsedInTemplate && isImportUsed(key, next)) {
  28701. return true;
  28702. }
  28703. }
  28704. return false;
  28705. }
  28706. function dedent(s) {
  28707. const lines = s.split("\n");
  28708. const minIndent = lines.reduce(function(minIndent2, line) {
  28709. var _a, _b;
  28710. if (line.trim() === "") {
  28711. return minIndent2;
  28712. }
  28713. const indent = ((_b = (_a = line.match(/^\s*/)) == null ? void 0 : _a[0]) == null ? void 0 : _b.length) || 0;
  28714. return Math.min(indent, minIndent2);
  28715. }, Infinity);
  28716. if (minIndent === 0) {
  28717. return [s, minIndent];
  28718. }
  28719. return [
  28720. lines.map(function(line) {
  28721. return line.slice(minIndent);
  28722. }).join("\n"),
  28723. minIndent
  28724. ];
  28725. }
  28726. // Copyright Joyent, Inc. and other Node contributors.
  28727. //
  28728. // Permission is hereby granted, free of charge, to any person obtaining a
  28729. // copy of this software and associated documentation files (the
  28730. // "Software"), to deal in the Software without restriction, including
  28731. // without limitation the rights to use, copy, modify, merge, publish,
  28732. // distribute, sublicense, and/or sell copies of the Software, and to permit
  28733. // persons to whom the Software is furnished to do so, subject to the
  28734. // following conditions:
  28735. //
  28736. // The above copyright notice and this permission notice shall be included
  28737. // in all copies or substantial portions of the Software.
  28738. //
  28739. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  28740. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  28741. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  28742. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  28743. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  28744. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  28745. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  28746. // resolves . and .. elements in a path array with directory names there
  28747. // must be no slashes, empty elements, or device names (c:\) in the array
  28748. // (so also no leading and trailing slashes - it does not distinguish
  28749. // relative and absolute paths)
  28750. function normalizeArray(parts, allowAboveRoot) {
  28751. // if the path tries to go above the root, `up` ends up > 0
  28752. var up = 0;
  28753. for (var i = parts.length - 1; i >= 0; i--) {
  28754. var last = parts[i];
  28755. if (last === '.') {
  28756. parts.splice(i, 1);
  28757. } else if (last === '..') {
  28758. parts.splice(i, 1);
  28759. up++;
  28760. } else if (up) {
  28761. parts.splice(i, 1);
  28762. up--;
  28763. }
  28764. }
  28765. // if the path is allowed to go above the root, restore leading ..s
  28766. if (allowAboveRoot) {
  28767. for (; up--; up) {
  28768. parts.unshift('..');
  28769. }
  28770. }
  28771. return parts;
  28772. }
  28773. // Split a filename into [root, dir, basename, ext], unix version
  28774. // 'root' is just a slash, or nothing.
  28775. var splitPathRe =
  28776. /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
  28777. var splitPath = function(filename) {
  28778. return splitPathRe.exec(filename).slice(1);
  28779. };
  28780. // path.resolve([from ...], to)
  28781. // posix version
  28782. function resolve() {
  28783. var resolvedPath = '',
  28784. resolvedAbsolute = false;
  28785. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  28786. var path = (i >= 0) ? arguments[i] : '/';
  28787. // Skip empty and invalid entries
  28788. if (typeof path !== 'string') {
  28789. throw new TypeError('Arguments to path.resolve must be strings');
  28790. } else if (!path) {
  28791. continue;
  28792. }
  28793. resolvedPath = path + '/' + resolvedPath;
  28794. resolvedAbsolute = path.charAt(0) === '/';
  28795. }
  28796. // At this point the path should be resolved to a full absolute path, but
  28797. // handle relative paths to be safe (might happen when process.cwd() fails)
  28798. // Normalize the path
  28799. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  28800. return !!p;
  28801. }), !resolvedAbsolute).join('/');
  28802. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  28803. }
  28804. // path.normalize(path)
  28805. // posix version
  28806. function normalize$1(path) {
  28807. var isPathAbsolute = isAbsolute(path),
  28808. trailingSlash = substr(path, -1) === '/';
  28809. // Normalize the path
  28810. path = normalizeArray(filter(path.split('/'), function(p) {
  28811. return !!p;
  28812. }), !isPathAbsolute).join('/');
  28813. if (!path && !isPathAbsolute) {
  28814. path = '.';
  28815. }
  28816. if (path && trailingSlash) {
  28817. path += '/';
  28818. }
  28819. return (isPathAbsolute ? '/' : '') + path;
  28820. }
  28821. // posix version
  28822. function isAbsolute(path) {
  28823. return path.charAt(0) === '/';
  28824. }
  28825. // posix version
  28826. function join() {
  28827. var paths = Array.prototype.slice.call(arguments, 0);
  28828. return normalize$1(filter(paths, function(p, index) {
  28829. if (typeof p !== 'string') {
  28830. throw new TypeError('Arguments to path.join must be strings');
  28831. }
  28832. return p;
  28833. }).join('/'));
  28834. }
  28835. // path.relative(from, to)
  28836. // posix version
  28837. function relative(from, to) {
  28838. from = resolve(from).substr(1);
  28839. to = resolve(to).substr(1);
  28840. function trim(arr) {
  28841. var start = 0;
  28842. for (; start < arr.length; start++) {
  28843. if (arr[start] !== '') break;
  28844. }
  28845. var end = arr.length - 1;
  28846. for (; end >= 0; end--) {
  28847. if (arr[end] !== '') break;
  28848. }
  28849. if (start > end) return [];
  28850. return arr.slice(start, end - start + 1);
  28851. }
  28852. var fromParts = trim(from.split('/'));
  28853. var toParts = trim(to.split('/'));
  28854. var length = Math.min(fromParts.length, toParts.length);
  28855. var samePartsLength = length;
  28856. for (var i = 0; i < length; i++) {
  28857. if (fromParts[i] !== toParts[i]) {
  28858. samePartsLength = i;
  28859. break;
  28860. }
  28861. }
  28862. var outputParts = [];
  28863. for (var i = samePartsLength; i < fromParts.length; i++) {
  28864. outputParts.push('..');
  28865. }
  28866. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  28867. return outputParts.join('/');
  28868. }
  28869. var sep = '/';
  28870. var delimiter$1 = ':';
  28871. function dirname(path) {
  28872. var result = splitPath(path),
  28873. root = result[0],
  28874. dir = result[1];
  28875. if (!root && !dir) {
  28876. // No dirname whatsoever
  28877. return '.';
  28878. }
  28879. if (dir) {
  28880. // It has a dirname, strip trailing slash
  28881. dir = dir.substr(0, dir.length - 1);
  28882. }
  28883. return root + dir;
  28884. }
  28885. function basename(path, ext) {
  28886. var f = splitPath(path)[2];
  28887. // TODO: make this comparison case-insensitive on windows?
  28888. if (ext && f.substr(-1 * ext.length) === ext) {
  28889. f = f.substr(0, f.length - ext.length);
  28890. }
  28891. return f;
  28892. }
  28893. function extname(path) {
  28894. return splitPath(path)[3];
  28895. }
  28896. var path = {
  28897. extname: extname,
  28898. basename: basename,
  28899. dirname: dirname,
  28900. sep: sep,
  28901. delimiter: delimiter$1,
  28902. relative: relative,
  28903. join: join,
  28904. isAbsolute: isAbsolute,
  28905. normalize: normalize$1,
  28906. resolve: resolve
  28907. };
  28908. function filter (xs, f) {
  28909. if (xs.filter) return xs.filter(f);
  28910. var res = [];
  28911. for (var i = 0; i < xs.length; i++) {
  28912. if (f(xs[i], i, xs)) res.push(xs[i]);
  28913. }
  28914. return res;
  28915. }
  28916. // String.prototype.substr - negative index don't work in IE8
  28917. var substr = 'ab'.substr(-1) === 'b' ?
  28918. function (str, start, len) { return str.substr(start, len) } :
  28919. function (str, start, len) {
  28920. if (start < 0) start = str.length + start;
  28921. return str.substr(start, len);
  28922. }
  28923. ;
  28924. var _polyfillNode_path = /*#__PURE__*/Object.freeze({
  28925. __proto__: null,
  28926. basename: basename,
  28927. default: path,
  28928. delimiter: delimiter$1,
  28929. dirname: dirname,
  28930. extname: extname,
  28931. isAbsolute: isAbsolute,
  28932. join: join,
  28933. normalize: normalize$1,
  28934. relative: relative,
  28935. resolve: resolve,
  28936. sep: sep
  28937. });
  28938. /*! https://mths.be/punycode v1.4.1 by @mathias */
  28939. /** Highest positive signed 32-bit float value */
  28940. var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
  28941. /** Bootstring parameters */
  28942. var base = 36;
  28943. var tMin = 1;
  28944. var tMax = 26;
  28945. var skew = 38;
  28946. var damp = 700;
  28947. var initialBias = 72;
  28948. var initialN = 128; // 0x80
  28949. var delimiter = '-'; // '\x2D'
  28950. var regexNonASCII = /[^\x20-\x7E]/; // unprintable ASCII chars + non-ASCII chars
  28951. var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
  28952. /** Error messages */
  28953. var errors = {
  28954. 'overflow': 'Overflow: input needs wider integers to process',
  28955. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  28956. 'invalid-input': 'Invalid input'
  28957. };
  28958. /** Convenience shortcuts */
  28959. var baseMinusTMin = base - tMin;
  28960. var floor = Math.floor;
  28961. var stringFromCharCode = String.fromCharCode;
  28962. /*--------------------------------------------------------------------------*/
  28963. /**
  28964. * A generic error utility function.
  28965. * @private
  28966. * @param {String} type The error type.
  28967. * @returns {Error} Throws a `RangeError` with the applicable error message.
  28968. */
  28969. function error(type) {
  28970. throw new RangeError(errors[type]);
  28971. }
  28972. /**
  28973. * A generic `Array#map` utility function.
  28974. * @private
  28975. * @param {Array} array The array to iterate over.
  28976. * @param {Function} callback The function that gets called for every array
  28977. * item.
  28978. * @returns {Array} A new array of values returned by the callback function.
  28979. */
  28980. function map$1(array, fn) {
  28981. var length = array.length;
  28982. var result = [];
  28983. while (length--) {
  28984. result[length] = fn(array[length]);
  28985. }
  28986. return result;
  28987. }
  28988. /**
  28989. * A simple `Array#map`-like wrapper to work with domain name strings or email
  28990. * addresses.
  28991. * @private
  28992. * @param {String} domain The domain name or email address.
  28993. * @param {Function} callback The function that gets called for every
  28994. * character.
  28995. * @returns {Array} A new string of characters returned by the callback
  28996. * function.
  28997. */
  28998. function mapDomain(string, fn) {
  28999. var parts = string.split('@');
  29000. var result = '';
  29001. if (parts.length > 1) {
  29002. // In email addresses, only the domain name should be punycoded. Leave
  29003. // the local part (i.e. everything up to `@`) intact.
  29004. result = parts[0] + '@';
  29005. string = parts[1];
  29006. }
  29007. // Avoid `split(regex)` for IE8 compatibility. See #17.
  29008. string = string.replace(regexSeparators, '\x2E');
  29009. var labels = string.split('.');
  29010. var encoded = map$1(labels, fn).join('.');
  29011. return result + encoded;
  29012. }
  29013. /**
  29014. * Creates an array containing the numeric code points of each Unicode
  29015. * character in the string. While JavaScript uses UCS-2 internally,
  29016. * this function will convert a pair of surrogate halves (each of which
  29017. * UCS-2 exposes as separate characters) into a single code point,
  29018. * matching UTF-16.
  29019. * @see `punycode.ucs2.encode`
  29020. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  29021. * @memberOf punycode.ucs2
  29022. * @name decode
  29023. * @param {String} string The Unicode input string (UCS-2).
  29024. * @returns {Array} The new array of code points.
  29025. */
  29026. function ucs2decode(string) {
  29027. var output = [],
  29028. counter = 0,
  29029. length = string.length,
  29030. value,
  29031. extra;
  29032. while (counter < length) {
  29033. value = string.charCodeAt(counter++);
  29034. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  29035. // high surrogate, and there is a next character
  29036. extra = string.charCodeAt(counter++);
  29037. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  29038. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  29039. } else {
  29040. // unmatched surrogate; only append this code unit, in case the next
  29041. // code unit is the high surrogate of a surrogate pair
  29042. output.push(value);
  29043. counter--;
  29044. }
  29045. } else {
  29046. output.push(value);
  29047. }
  29048. }
  29049. return output;
  29050. }
  29051. /**
  29052. * Converts a digit/integer into a basic code point.
  29053. * @see `basicToDigit()`
  29054. * @private
  29055. * @param {Number} digit The numeric value of a basic code point.
  29056. * @returns {Number} The basic code point whose value (when used for
  29057. * representing integers) is `digit`, which needs to be in the range
  29058. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  29059. * used; else, the lowercase form is used. The behavior is undefined
  29060. * if `flag` is non-zero and `digit` has no uppercase form.
  29061. */
  29062. function digitToBasic(digit, flag) {
  29063. // 0..25 map to ASCII a..z or A..Z
  29064. // 26..35 map to ASCII 0..9
  29065. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  29066. }
  29067. /**
  29068. * Bias adaptation function as per section 3.4 of RFC 3492.
  29069. * https://tools.ietf.org/html/rfc3492#section-3.4
  29070. * @private
  29071. */
  29072. function adapt(delta, numPoints, firstTime) {
  29073. var k = 0;
  29074. delta = firstTime ? floor(delta / damp) : delta >> 1;
  29075. delta += floor(delta / numPoints);
  29076. for ( /* no initialization */ ; delta > baseMinusTMin * tMax >> 1; k += base) {
  29077. delta = floor(delta / baseMinusTMin);
  29078. }
  29079. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  29080. }
  29081. /**
  29082. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  29083. * Punycode string of ASCII-only symbols.
  29084. * @memberOf punycode
  29085. * @param {String} input The string of Unicode symbols.
  29086. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  29087. */
  29088. function encode$1(input) {
  29089. var n,
  29090. delta,
  29091. handledCPCount,
  29092. basicLength,
  29093. bias,
  29094. j,
  29095. m,
  29096. q,
  29097. k,
  29098. t,
  29099. currentValue,
  29100. output = [],
  29101. /** `inputLength` will hold the number of code points in `input`. */
  29102. inputLength,
  29103. /** Cached calculation results */
  29104. handledCPCountPlusOne,
  29105. baseMinusT,
  29106. qMinusT;
  29107. // Convert the input in UCS-2 to Unicode
  29108. input = ucs2decode(input);
  29109. // Cache the length
  29110. inputLength = input.length;
  29111. // Initialize the state
  29112. n = initialN;
  29113. delta = 0;
  29114. bias = initialBias;
  29115. // Handle the basic code points
  29116. for (j = 0; j < inputLength; ++j) {
  29117. currentValue = input[j];
  29118. if (currentValue < 0x80) {
  29119. output.push(stringFromCharCode(currentValue));
  29120. }
  29121. }
  29122. handledCPCount = basicLength = output.length;
  29123. // `handledCPCount` is the number of code points that have been handled;
  29124. // `basicLength` is the number of basic code points.
  29125. // Finish the basic string - if it is not empty - with a delimiter
  29126. if (basicLength) {
  29127. output.push(delimiter);
  29128. }
  29129. // Main encoding loop:
  29130. while (handledCPCount < inputLength) {
  29131. // All non-basic code points < n have been handled already. Find the next
  29132. // larger one:
  29133. for (m = maxInt, j = 0; j < inputLength; ++j) {
  29134. currentValue = input[j];
  29135. if (currentValue >= n && currentValue < m) {
  29136. m = currentValue;
  29137. }
  29138. }
  29139. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  29140. // but guard against overflow
  29141. handledCPCountPlusOne = handledCPCount + 1;
  29142. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  29143. error('overflow');
  29144. }
  29145. delta += (m - n) * handledCPCountPlusOne;
  29146. n = m;
  29147. for (j = 0; j < inputLength; ++j) {
  29148. currentValue = input[j];
  29149. if (currentValue < n && ++delta > maxInt) {
  29150. error('overflow');
  29151. }
  29152. if (currentValue == n) {
  29153. // Represent delta as a generalized variable-length integer
  29154. for (q = delta, k = base; /* no condition */ ; k += base) {
  29155. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  29156. if (q < t) {
  29157. break;
  29158. }
  29159. qMinusT = q - t;
  29160. baseMinusT = base - t;
  29161. output.push(
  29162. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  29163. );
  29164. q = floor(qMinusT / baseMinusT);
  29165. }
  29166. output.push(stringFromCharCode(digitToBasic(q, 0)));
  29167. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  29168. delta = 0;
  29169. ++handledCPCount;
  29170. }
  29171. }
  29172. ++delta;
  29173. ++n;
  29174. }
  29175. return output.join('');
  29176. }
  29177. /**
  29178. * Converts a Unicode string representing a domain name or an email address to
  29179. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  29180. * i.e. it doesn't matter if you call it with a domain that's already in
  29181. * ASCII.
  29182. * @memberOf punycode
  29183. * @param {String} input The domain name or email address to convert, as a
  29184. * Unicode string.
  29185. * @returns {String} The Punycode representation of the given domain name or
  29186. * email address.
  29187. */
  29188. function toASCII(input) {
  29189. return mapDomain(input, function(string) {
  29190. return regexNonASCII.test(string) ?
  29191. 'xn--' + encode$1(string) :
  29192. string;
  29193. });
  29194. }
  29195. var inherits;
  29196. if (typeof Object.create === 'function'){
  29197. inherits = function inherits(ctor, superCtor) {
  29198. // implementation from standard node.js 'util' module
  29199. ctor.super_ = superCtor;
  29200. ctor.prototype = Object.create(superCtor.prototype, {
  29201. constructor: {
  29202. value: ctor,
  29203. enumerable: false,
  29204. writable: true,
  29205. configurable: true
  29206. }
  29207. });
  29208. };
  29209. } else {
  29210. inherits = function inherits(ctor, superCtor) {
  29211. ctor.super_ = superCtor;
  29212. var TempCtor = function () {};
  29213. TempCtor.prototype = superCtor.prototype;
  29214. ctor.prototype = new TempCtor();
  29215. ctor.prototype.constructor = ctor;
  29216. };
  29217. }
  29218. var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||
  29219. function getOwnPropertyDescriptors(obj) {
  29220. var keys = Object.keys(obj);
  29221. var descriptors = {};
  29222. for (var i = 0; i < keys.length; i++) {
  29223. descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);
  29224. }
  29225. return descriptors;
  29226. };
  29227. var formatRegExp = /%[sdj%]/g;
  29228. function format$1(f) {
  29229. if (!isString(f)) {
  29230. var objects = [];
  29231. for (var i = 0; i < arguments.length; i++) {
  29232. objects.push(inspect(arguments[i]));
  29233. }
  29234. return objects.join(' ');
  29235. }
  29236. var i = 1;
  29237. var args = arguments;
  29238. var len = args.length;
  29239. var str = String(f).replace(formatRegExp, function(x) {
  29240. if (x === '%%') return '%';
  29241. if (i >= len) return x;
  29242. switch (x) {
  29243. case '%s': return String(args[i++]);
  29244. case '%d': return Number(args[i++]);
  29245. case '%j':
  29246. try {
  29247. return JSON.stringify(args[i++]);
  29248. } catch (_) {
  29249. return '[Circular]';
  29250. }
  29251. default:
  29252. return x;
  29253. }
  29254. });
  29255. for (var x = args[i]; i < len; x = args[++i]) {
  29256. if (isNull(x) || !isObject$1(x)) {
  29257. str += ' ' + x;
  29258. } else {
  29259. str += ' ' + inspect(x);
  29260. }
  29261. }
  29262. return str;
  29263. }
  29264. // Mark that a method should not be used.
  29265. // Returns a modified function which warns once by default.
  29266. // If --no-deprecation is set, then it is a no-op.
  29267. function deprecate(fn, msg) {
  29268. // Allow for deprecating things in the process of starting up.
  29269. if (isUndefined(global$1.process)) {
  29270. return function() {
  29271. return deprecate(fn, msg).apply(this, arguments);
  29272. };
  29273. }
  29274. if (browser$1.noDeprecation === true) {
  29275. return fn;
  29276. }
  29277. var warned = false;
  29278. function deprecated() {
  29279. if (!warned) {
  29280. if (browser$1.throwDeprecation) {
  29281. throw new Error(msg);
  29282. } else if (browser$1.traceDeprecation) {
  29283. console.trace(msg);
  29284. } else {
  29285. console.error(msg);
  29286. }
  29287. warned = true;
  29288. }
  29289. return fn.apply(this, arguments);
  29290. }
  29291. return deprecated;
  29292. }
  29293. var debugs = {};
  29294. var debugEnviron;
  29295. function debuglog(set) {
  29296. if (isUndefined(debugEnviron))
  29297. debugEnviron = browser$1.env.NODE_DEBUG || '';
  29298. set = set.toUpperCase();
  29299. if (!debugs[set]) {
  29300. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  29301. var pid = 0;
  29302. debugs[set] = function() {
  29303. var msg = format$1.apply(null, arguments);
  29304. console.error('%s %d: %s', set, pid, msg);
  29305. };
  29306. } else {
  29307. debugs[set] = function() {};
  29308. }
  29309. }
  29310. return debugs[set];
  29311. }
  29312. /**
  29313. * Echos the value of a value. Trys to print the value out
  29314. * in the best way possible given the different types.
  29315. *
  29316. * @param {Object} obj The object to print out.
  29317. * @param {Object} opts Optional options object that alters the output.
  29318. */
  29319. /* legacy: obj, showHidden, depth, colors*/
  29320. function inspect(obj, opts) {
  29321. // default options
  29322. var ctx = {
  29323. seen: [],
  29324. stylize: stylizeNoColor
  29325. };
  29326. // legacy...
  29327. if (arguments.length >= 3) ctx.depth = arguments[2];
  29328. if (arguments.length >= 4) ctx.colors = arguments[3];
  29329. if (isBoolean(opts)) {
  29330. // legacy...
  29331. ctx.showHidden = opts;
  29332. } else if (opts) {
  29333. // got an "options" object
  29334. _extend(ctx, opts);
  29335. }
  29336. // set default options
  29337. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  29338. if (isUndefined(ctx.depth)) ctx.depth = 2;
  29339. if (isUndefined(ctx.colors)) ctx.colors = false;
  29340. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  29341. if (ctx.colors) ctx.stylize = stylizeWithColor;
  29342. return formatValue(ctx, obj, ctx.depth);
  29343. }
  29344. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  29345. inspect.colors = {
  29346. 'bold' : [1, 22],
  29347. 'italic' : [3, 23],
  29348. 'underline' : [4, 24],
  29349. 'inverse' : [7, 27],
  29350. 'white' : [37, 39],
  29351. 'grey' : [90, 39],
  29352. 'black' : [30, 39],
  29353. 'blue' : [34, 39],
  29354. 'cyan' : [36, 39],
  29355. 'green' : [32, 39],
  29356. 'magenta' : [35, 39],
  29357. 'red' : [31, 39],
  29358. 'yellow' : [33, 39]
  29359. };
  29360. // Don't use 'blue' not visible on cmd.exe
  29361. inspect.styles = {
  29362. 'special': 'cyan',
  29363. 'number': 'yellow',
  29364. 'boolean': 'yellow',
  29365. 'undefined': 'grey',
  29366. 'null': 'bold',
  29367. 'string': 'green',
  29368. 'date': 'magenta',
  29369. // "name": intentionally not styling
  29370. 'regexp': 'red'
  29371. };
  29372. function stylizeWithColor(str, styleType) {
  29373. var style = inspect.styles[styleType];
  29374. if (style) {
  29375. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  29376. '\u001b[' + inspect.colors[style][1] + 'm';
  29377. } else {
  29378. return str;
  29379. }
  29380. }
  29381. function stylizeNoColor(str, styleType) {
  29382. return str;
  29383. }
  29384. function arrayToHash(array) {
  29385. var hash = {};
  29386. array.forEach(function(val, idx) {
  29387. hash[val] = true;
  29388. });
  29389. return hash;
  29390. }
  29391. function formatValue(ctx, value, recurseTimes) {
  29392. // Provide a hook for user-specified inspect functions.
  29393. // Check that value is an object with an inspect function on it
  29394. if (ctx.customInspect &&
  29395. value &&
  29396. isFunction(value.inspect) &&
  29397. // Filter out the util module, it's inspect function is special
  29398. value.inspect !== inspect &&
  29399. // Also filter out any prototype objects using the circular check.
  29400. !(value.constructor && value.constructor.prototype === value)) {
  29401. var ret = value.inspect(recurseTimes, ctx);
  29402. if (!isString(ret)) {
  29403. ret = formatValue(ctx, ret, recurseTimes);
  29404. }
  29405. return ret;
  29406. }
  29407. // Primitive types cannot have properties
  29408. var primitive = formatPrimitive(ctx, value);
  29409. if (primitive) {
  29410. return primitive;
  29411. }
  29412. // Look up the keys of the object.
  29413. var keys = Object.keys(value);
  29414. var visibleKeys = arrayToHash(keys);
  29415. if (ctx.showHidden) {
  29416. keys = Object.getOwnPropertyNames(value);
  29417. }
  29418. // IE doesn't make error fields non-enumerable
  29419. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  29420. if (isError(value)
  29421. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  29422. return formatError(value);
  29423. }
  29424. // Some type of object without properties can be shortcutted.
  29425. if (keys.length === 0) {
  29426. if (isFunction(value)) {
  29427. var name = value.name ? ': ' + value.name : '';
  29428. return ctx.stylize('[Function' + name + ']', 'special');
  29429. }
  29430. if (isRegExp(value)) {
  29431. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  29432. }
  29433. if (isDate(value)) {
  29434. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  29435. }
  29436. if (isError(value)) {
  29437. return formatError(value);
  29438. }
  29439. }
  29440. var base = '', array = false, braces = ['{', '}'];
  29441. // Make Array say that they are Array
  29442. if (isArray$1(value)) {
  29443. array = true;
  29444. braces = ['[', ']'];
  29445. }
  29446. // Make functions say that they are functions
  29447. if (isFunction(value)) {
  29448. var n = value.name ? ': ' + value.name : '';
  29449. base = ' [Function' + n + ']';
  29450. }
  29451. // Make RegExps say that they are RegExps
  29452. if (isRegExp(value)) {
  29453. base = ' ' + RegExp.prototype.toString.call(value);
  29454. }
  29455. // Make dates with properties first say the date
  29456. if (isDate(value)) {
  29457. base = ' ' + Date.prototype.toUTCString.call(value);
  29458. }
  29459. // Make error with message first say the error
  29460. if (isError(value)) {
  29461. base = ' ' + formatError(value);
  29462. }
  29463. if (keys.length === 0 && (!array || value.length == 0)) {
  29464. return braces[0] + base + braces[1];
  29465. }
  29466. if (recurseTimes < 0) {
  29467. if (isRegExp(value)) {
  29468. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  29469. } else {
  29470. return ctx.stylize('[Object]', 'special');
  29471. }
  29472. }
  29473. ctx.seen.push(value);
  29474. var output;
  29475. if (array) {
  29476. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  29477. } else {
  29478. output = keys.map(function(key) {
  29479. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  29480. });
  29481. }
  29482. ctx.seen.pop();
  29483. return reduceToSingleString(output, base, braces);
  29484. }
  29485. function formatPrimitive(ctx, value) {
  29486. if (isUndefined(value))
  29487. return ctx.stylize('undefined', 'undefined');
  29488. if (isString(value)) {
  29489. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  29490. .replace(/'/g, "\\'")
  29491. .replace(/\\"/g, '"') + '\'';
  29492. return ctx.stylize(simple, 'string');
  29493. }
  29494. if (isNumber(value))
  29495. return ctx.stylize('' + value, 'number');
  29496. if (isBoolean(value))
  29497. return ctx.stylize('' + value, 'boolean');
  29498. // For some reason typeof null is "object", so special case here.
  29499. if (isNull(value))
  29500. return ctx.stylize('null', 'null');
  29501. }
  29502. function formatError(value) {
  29503. return '[' + Error.prototype.toString.call(value) + ']';
  29504. }
  29505. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  29506. var output = [];
  29507. for (var i = 0, l = value.length; i < l; ++i) {
  29508. if (hasOwnProperty$2(value, String(i))) {
  29509. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  29510. String(i), true));
  29511. } else {
  29512. output.push('');
  29513. }
  29514. }
  29515. keys.forEach(function(key) {
  29516. if (!key.match(/^\d+$/)) {
  29517. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  29518. key, true));
  29519. }
  29520. });
  29521. return output;
  29522. }
  29523. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  29524. var name, str, desc;
  29525. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  29526. if (desc.get) {
  29527. if (desc.set) {
  29528. str = ctx.stylize('[Getter/Setter]', 'special');
  29529. } else {
  29530. str = ctx.stylize('[Getter]', 'special');
  29531. }
  29532. } else {
  29533. if (desc.set) {
  29534. str = ctx.stylize('[Setter]', 'special');
  29535. }
  29536. }
  29537. if (!hasOwnProperty$2(visibleKeys, key)) {
  29538. name = '[' + key + ']';
  29539. }
  29540. if (!str) {
  29541. if (ctx.seen.indexOf(desc.value) < 0) {
  29542. if (isNull(recurseTimes)) {
  29543. str = formatValue(ctx, desc.value, null);
  29544. } else {
  29545. str = formatValue(ctx, desc.value, recurseTimes - 1);
  29546. }
  29547. if (str.indexOf('\n') > -1) {
  29548. if (array) {
  29549. str = str.split('\n').map(function(line) {
  29550. return ' ' + line;
  29551. }).join('\n').substr(2);
  29552. } else {
  29553. str = '\n' + str.split('\n').map(function(line) {
  29554. return ' ' + line;
  29555. }).join('\n');
  29556. }
  29557. }
  29558. } else {
  29559. str = ctx.stylize('[Circular]', 'special');
  29560. }
  29561. }
  29562. if (isUndefined(name)) {
  29563. if (array && key.match(/^\d+$/)) {
  29564. return str;
  29565. }
  29566. name = JSON.stringify('' + key);
  29567. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  29568. name = name.substr(1, name.length - 2);
  29569. name = ctx.stylize(name, 'name');
  29570. } else {
  29571. name = name.replace(/'/g, "\\'")
  29572. .replace(/\\"/g, '"')
  29573. .replace(/(^"|"$)/g, "'");
  29574. name = ctx.stylize(name, 'string');
  29575. }
  29576. }
  29577. return name + ': ' + str;
  29578. }
  29579. function reduceToSingleString(output, base, braces) {
  29580. var length = output.reduce(function(prev, cur) {
  29581. if (cur.indexOf('\n') >= 0) ;
  29582. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  29583. }, 0);
  29584. if (length > 60) {
  29585. return braces[0] +
  29586. (base === '' ? '' : base + '\n ') +
  29587. ' ' +
  29588. output.join(',\n ') +
  29589. ' ' +
  29590. braces[1];
  29591. }
  29592. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  29593. }
  29594. // NOTE: These type checking functions intentionally don't use `instanceof`
  29595. // because it is fragile and can be easily faked with `Object.create()`.
  29596. function isArray$1(ar) {
  29597. return Array.isArray(ar);
  29598. }
  29599. function isBoolean(arg) {
  29600. return typeof arg === 'boolean';
  29601. }
  29602. function isNull(arg) {
  29603. return arg === null;
  29604. }
  29605. function isNullOrUndefined(arg) {
  29606. return arg == null;
  29607. }
  29608. function isNumber(arg) {
  29609. return typeof arg === 'number';
  29610. }
  29611. function isString(arg) {
  29612. return typeof arg === 'string';
  29613. }
  29614. function isSymbol(arg) {
  29615. return typeof arg === 'symbol';
  29616. }
  29617. function isUndefined(arg) {
  29618. return arg === void 0;
  29619. }
  29620. function isRegExp(re) {
  29621. return isObject$1(re) && objectToString(re) === '[object RegExp]';
  29622. }
  29623. function isObject$1(arg) {
  29624. return typeof arg === 'object' && arg !== null;
  29625. }
  29626. function isDate(d) {
  29627. return isObject$1(d) && objectToString(d) === '[object Date]';
  29628. }
  29629. function isError(e) {
  29630. return isObject$1(e) &&
  29631. (objectToString(e) === '[object Error]' || e instanceof Error);
  29632. }
  29633. function isFunction(arg) {
  29634. return typeof arg === 'function';
  29635. }
  29636. function isPrimitive(arg) {
  29637. return arg === null ||
  29638. typeof arg === 'boolean' ||
  29639. typeof arg === 'number' ||
  29640. typeof arg === 'string' ||
  29641. typeof arg === 'symbol' || // ES6 symbol
  29642. typeof arg === 'undefined';
  29643. }
  29644. function isBuffer(maybeBuf) {
  29645. return Buffer$1.isBuffer(maybeBuf);
  29646. }
  29647. function objectToString(o) {
  29648. return Object.prototype.toString.call(o);
  29649. }
  29650. function pad(n) {
  29651. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  29652. }
  29653. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  29654. 'Oct', 'Nov', 'Dec'];
  29655. // 26 Feb 16:19:34
  29656. function timestamp() {
  29657. var d = new Date();
  29658. var time = [pad(d.getHours()),
  29659. pad(d.getMinutes()),
  29660. pad(d.getSeconds())].join(':');
  29661. return [d.getDate(), months[d.getMonth()], time].join(' ');
  29662. }
  29663. // log is just a thin wrapper to console.log that prepends a timestamp
  29664. function log() {
  29665. console.log('%s - %s', timestamp(), format$1.apply(null, arguments));
  29666. }
  29667. function _extend(origin, add) {
  29668. // Don't do anything if add isn't an object
  29669. if (!add || !isObject$1(add)) return origin;
  29670. var keys = Object.keys(add);
  29671. var i = keys.length;
  29672. while (i--) {
  29673. origin[keys[i]] = add[keys[i]];
  29674. }
  29675. return origin;
  29676. }
  29677. function hasOwnProperty$2(obj, prop) {
  29678. return Object.prototype.hasOwnProperty.call(obj, prop);
  29679. }
  29680. var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;
  29681. function promisify(original) {
  29682. if (typeof original !== 'function')
  29683. throw new TypeError('The "original" argument must be of type Function');
  29684. if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {
  29685. var fn = original[kCustomPromisifiedSymbol];
  29686. if (typeof fn !== 'function') {
  29687. throw new TypeError('The "util.promisify.custom" argument must be of type Function');
  29688. }
  29689. Object.defineProperty(fn, kCustomPromisifiedSymbol, {
  29690. value: fn, enumerable: false, writable: false, configurable: true
  29691. });
  29692. return fn;
  29693. }
  29694. function fn() {
  29695. var promiseResolve, promiseReject;
  29696. var promise = new Promise(function (resolve, reject) {
  29697. promiseResolve = resolve;
  29698. promiseReject = reject;
  29699. });
  29700. var args = [];
  29701. for (var i = 0; i < arguments.length; i++) {
  29702. args.push(arguments[i]);
  29703. }
  29704. args.push(function (err, value) {
  29705. if (err) {
  29706. promiseReject(err);
  29707. } else {
  29708. promiseResolve(value);
  29709. }
  29710. });
  29711. try {
  29712. original.apply(this, args);
  29713. } catch (err) {
  29714. promiseReject(err);
  29715. }
  29716. return promise;
  29717. }
  29718. Object.setPrototypeOf(fn, Object.getPrototypeOf(original));
  29719. if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {
  29720. value: fn, enumerable: false, writable: false, configurable: true
  29721. });
  29722. return Object.defineProperties(
  29723. fn,
  29724. getOwnPropertyDescriptors(original)
  29725. );
  29726. }
  29727. promisify.custom = kCustomPromisifiedSymbol;
  29728. function callbackifyOnRejected(reason, cb) {
  29729. // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).
  29730. // Because `null` is a special error value in callbacks which means "no error
  29731. // occurred", we error-wrap so the callback consumer can distinguish between
  29732. // "the promise rejected with null" or "the promise fulfilled with undefined".
  29733. if (!reason) {
  29734. var newReason = new Error('Promise was rejected with a falsy value');
  29735. newReason.reason = reason;
  29736. reason = newReason;
  29737. }
  29738. return cb(reason);
  29739. }
  29740. function callbackify(original) {
  29741. if (typeof original !== 'function') {
  29742. throw new TypeError('The "original" argument must be of type Function');
  29743. }
  29744. // We DO NOT return the promise as it gives the user a false sense that
  29745. // the promise is actually somehow related to the callback's execution
  29746. // and that the callback throwing will reject the promise.
  29747. function callbackified() {
  29748. var args = [];
  29749. for (var i = 0; i < arguments.length; i++) {
  29750. args.push(arguments[i]);
  29751. }
  29752. var maybeCb = args.pop();
  29753. if (typeof maybeCb !== 'function') {
  29754. throw new TypeError('The last argument must be of type Function');
  29755. }
  29756. var self = this;
  29757. var cb = function() {
  29758. return maybeCb.apply(self, arguments);
  29759. };
  29760. // In true node style we process the callback on `nextTick` with all the
  29761. // implications (stack, `uncaughtException`, `async_hooks`)
  29762. original.apply(this, args)
  29763. .then(function(ret) { browser$1.nextTick(cb.bind(null, null, ret)); },
  29764. function(rej) { browser$1.nextTick(callbackifyOnRejected.bind(null, rej, cb)); });
  29765. }
  29766. Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));
  29767. Object.defineProperties(callbackified, getOwnPropertyDescriptors(original));
  29768. return callbackified;
  29769. }
  29770. var _polyfillNode_util = {
  29771. inherits: inherits,
  29772. _extend: _extend,
  29773. log: log,
  29774. isBuffer: isBuffer,
  29775. isPrimitive: isPrimitive,
  29776. isFunction: isFunction,
  29777. isError: isError,
  29778. isDate: isDate,
  29779. isObject: isObject$1,
  29780. isRegExp: isRegExp,
  29781. isUndefined: isUndefined,
  29782. isSymbol: isSymbol,
  29783. isString: isString,
  29784. isNumber: isNumber,
  29785. isNullOrUndefined: isNullOrUndefined,
  29786. isNull: isNull,
  29787. isBoolean: isBoolean,
  29788. isArray: isArray$1,
  29789. inspect: inspect,
  29790. deprecate: deprecate,
  29791. format: format$1,
  29792. debuglog: debuglog,
  29793. promisify: promisify,
  29794. callbackify: callbackify,
  29795. };
  29796. var _polyfillNode_util$1 = /*#__PURE__*/Object.freeze({
  29797. __proto__: null,
  29798. _extend: _extend,
  29799. callbackify: callbackify,
  29800. debuglog: debuglog,
  29801. default: _polyfillNode_util,
  29802. deprecate: deprecate,
  29803. format: format$1,
  29804. inherits: inherits,
  29805. inspect: inspect,
  29806. isArray: isArray$1,
  29807. isBoolean: isBoolean,
  29808. isBuffer: isBuffer,
  29809. isDate: isDate,
  29810. isError: isError,
  29811. isFunction: isFunction,
  29812. isNull: isNull,
  29813. isNullOrUndefined: isNullOrUndefined,
  29814. isNumber: isNumber,
  29815. isObject: isObject$1,
  29816. isPrimitive: isPrimitive,
  29817. isRegExp: isRegExp,
  29818. isString: isString,
  29819. isSymbol: isSymbol,
  29820. isUndefined: isUndefined,
  29821. log: log,
  29822. promisify: promisify
  29823. });
  29824. // Copyright Joyent, Inc. and other Node contributors.
  29825. //
  29826. // Permission is hereby granted, free of charge, to any person obtaining a
  29827. // copy of this software and associated documentation files (the
  29828. // "Software"), to deal in the Software without restriction, including
  29829. // without limitation the rights to use, copy, modify, merge, publish,
  29830. // distribute, sublicense, and/or sell copies of the Software, and to permit
  29831. // persons to whom the Software is furnished to do so, subject to the
  29832. // following conditions:
  29833. //
  29834. // The above copyright notice and this permission notice shall be included
  29835. // in all copies or substantial portions of the Software.
  29836. //
  29837. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  29838. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  29839. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  29840. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  29841. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  29842. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  29843. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  29844. // If obj.hasOwnProperty has been overridden, then calling
  29845. // obj.hasOwnProperty(prop) will break.
  29846. // See: https://github.com/joyent/node/issues/1707
  29847. function hasOwnProperty$1(obj, prop) {
  29848. return Object.prototype.hasOwnProperty.call(obj, prop);
  29849. }
  29850. var isArray = Array.isArray || function (xs) {
  29851. return Object.prototype.toString.call(xs) === '[object Array]';
  29852. };
  29853. function stringifyPrimitive(v) {
  29854. switch (typeof v) {
  29855. case 'string':
  29856. return v;
  29857. case 'boolean':
  29858. return v ? 'true' : 'false';
  29859. case 'number':
  29860. return isFinite(v) ? v : '';
  29861. default:
  29862. return '';
  29863. }
  29864. }
  29865. function stringify (obj, sep, eq, name) {
  29866. sep = sep || '&';
  29867. eq = eq || '=';
  29868. if (obj === null) {
  29869. obj = undefined;
  29870. }
  29871. if (typeof obj === 'object') {
  29872. return map(objectKeys(obj), function(k) {
  29873. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  29874. if (isArray(obj[k])) {
  29875. return map(obj[k], function(v) {
  29876. return ks + encodeURIComponent(stringifyPrimitive(v));
  29877. }).join(sep);
  29878. } else {
  29879. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  29880. }
  29881. }).join(sep);
  29882. }
  29883. if (!name) return '';
  29884. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  29885. encodeURIComponent(stringifyPrimitive(obj));
  29886. }
  29887. function map (xs, f) {
  29888. if (xs.map) return xs.map(f);
  29889. var res = [];
  29890. for (var i = 0; i < xs.length; i++) {
  29891. res.push(f(xs[i], i));
  29892. }
  29893. return res;
  29894. }
  29895. var objectKeys = Object.keys || function (obj) {
  29896. var res = [];
  29897. for (var key in obj) {
  29898. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  29899. }
  29900. return res;
  29901. };
  29902. function parse$1(qs, sep, eq, options) {
  29903. sep = sep || '&';
  29904. eq = eq || '=';
  29905. var obj = {};
  29906. if (typeof qs !== 'string' || qs.length === 0) {
  29907. return obj;
  29908. }
  29909. var regexp = /\+/g;
  29910. qs = qs.split(sep);
  29911. var maxKeys = 1000;
  29912. if (options && typeof options.maxKeys === 'number') {
  29913. maxKeys = options.maxKeys;
  29914. }
  29915. var len = qs.length;
  29916. // maxKeys <= 0 means that we should not limit keys count
  29917. if (maxKeys > 0 && len > maxKeys) {
  29918. len = maxKeys;
  29919. }
  29920. for (var i = 0; i < len; ++i) {
  29921. var x = qs[i].replace(regexp, '%20'),
  29922. idx = x.indexOf(eq),
  29923. kstr, vstr, k, v;
  29924. if (idx >= 0) {
  29925. kstr = x.substr(0, idx);
  29926. vstr = x.substr(idx + 1);
  29927. } else {
  29928. kstr = x;
  29929. vstr = '';
  29930. }
  29931. k = decodeURIComponent(kstr);
  29932. v = decodeURIComponent(vstr);
  29933. if (!hasOwnProperty$1(obj, k)) {
  29934. obj[k] = v;
  29935. } else if (isArray(obj[k])) {
  29936. obj[k].push(v);
  29937. } else {
  29938. obj[k] = [obj[k], v];
  29939. }
  29940. }
  29941. return obj;
  29942. }
  29943. // WHATWG API
  29944. const URL$1 = global$1.URL;
  29945. const URLSearchParams = global$1.URLSearchParams;
  29946. var _polyfillNode_url = {
  29947. parse: urlParse,
  29948. resolve: urlResolve,
  29949. resolveObject: urlResolveObject,
  29950. fileURLToPath: urlFileURLToPath,
  29951. format: urlFormat,
  29952. Url: Url,
  29953. // WHATWG API
  29954. URL: URL$1,
  29955. URLSearchParams,
  29956. };
  29957. function Url() {
  29958. this.protocol = null;
  29959. this.slashes = null;
  29960. this.auth = null;
  29961. this.host = null;
  29962. this.port = null;
  29963. this.hostname = null;
  29964. this.hash = null;
  29965. this.search = null;
  29966. this.query = null;
  29967. this.pathname = null;
  29968. this.path = null;
  29969. this.href = null;
  29970. }
  29971. // Reference: RFC 3986, RFC 1808, RFC 2396
  29972. // define these here so at least they only have to be
  29973. // compiled once on the first module load.
  29974. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  29975. portPattern = /:[0-9]*$/,
  29976. // Special case for a simple path URL
  29977. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  29978. // RFC 2396: characters reserved for delimiting URLs.
  29979. // We actually just auto-escape these.
  29980. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  29981. // RFC 2396: characters not allowed for various reasons.
  29982. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  29983. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  29984. autoEscape = ['\''].concat(unwise),
  29985. // Characters that are never ever allowed in a hostname.
  29986. // Note that any invalid chars are also handled, but these
  29987. // are the ones that are *expected* to be seen, so we fast-path
  29988. // them.
  29989. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  29990. hostEndingChars = ['/', '?', '#'],
  29991. hostnameMaxLen = 255,
  29992. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  29993. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  29994. // protocols that can allow "unsafe" and "unwise" chars.
  29995. unsafeProtocol = {
  29996. 'javascript': true,
  29997. 'javascript:': true
  29998. },
  29999. // protocols that never have a hostname.
  30000. hostlessProtocol = {
  30001. 'javascript': true,
  30002. 'javascript:': true
  30003. },
  30004. // protocols that always contain a // bit.
  30005. slashedProtocol = {
  30006. 'http': true,
  30007. 'https': true,
  30008. 'ftp': true,
  30009. 'gopher': true,
  30010. 'file': true,
  30011. 'http:': true,
  30012. 'https:': true,
  30013. 'ftp:': true,
  30014. 'gopher:': true,
  30015. 'file:': true
  30016. };
  30017. function urlParse(url, parseQueryString, slashesDenoteHost) {
  30018. if (url && isObject$1(url) && url instanceof Url) return url;
  30019. var u = new Url;
  30020. u.parse(url, parseQueryString, slashesDenoteHost);
  30021. return u;
  30022. }
  30023. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  30024. return parse(this, url, parseQueryString, slashesDenoteHost);
  30025. };
  30026. function parse(self, url, parseQueryString, slashesDenoteHost) {
  30027. if (!isString(url)) {
  30028. throw new TypeError('Parameter \'url\' must be a string, not ' + typeof url);
  30029. }
  30030. // Copy chrome, IE, opera backslash-handling behavior.
  30031. // Back slashes before the query string get converted to forward slashes
  30032. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  30033. var queryIndex = url.indexOf('?'),
  30034. splitter =
  30035. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  30036. uSplit = url.split(splitter),
  30037. slashRegex = /\\/g;
  30038. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  30039. url = uSplit.join(splitter);
  30040. var rest = url;
  30041. // trim before proceeding.
  30042. // This is to support parse stuff like " http://foo.com \n"
  30043. rest = rest.trim();
  30044. if (!slashesDenoteHost && url.split('#').length === 1) {
  30045. // Try fast path regexp
  30046. var simplePath = simplePathPattern.exec(rest);
  30047. if (simplePath) {
  30048. self.path = rest;
  30049. self.href = rest;
  30050. self.pathname = simplePath[1];
  30051. if (simplePath[2]) {
  30052. self.search = simplePath[2];
  30053. if (parseQueryString) {
  30054. self.query = parse$1(self.search.substr(1));
  30055. } else {
  30056. self.query = self.search.substr(1);
  30057. }
  30058. } else if (parseQueryString) {
  30059. self.search = '';
  30060. self.query = {};
  30061. }
  30062. return self;
  30063. }
  30064. }
  30065. var proto = protocolPattern.exec(rest);
  30066. if (proto) {
  30067. proto = proto[0];
  30068. var lowerProto = proto.toLowerCase();
  30069. self.protocol = lowerProto;
  30070. rest = rest.substr(proto.length);
  30071. }
  30072. // figure out if it's got a host
  30073. // user@server is *always* interpreted as a hostname, and url
  30074. // resolution will treat //foo/bar as host=foo,path=bar because that's
  30075. // how the browser resolves relative URLs.
  30076. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  30077. var slashes = rest.substr(0, 2) === '//';
  30078. if (slashes && !(proto && hostlessProtocol[proto])) {
  30079. rest = rest.substr(2);
  30080. self.slashes = true;
  30081. }
  30082. }
  30083. var i, hec, l, p;
  30084. if (!hostlessProtocol[proto] &&
  30085. (slashes || (proto && !slashedProtocol[proto]))) {
  30086. // there's a hostname.
  30087. // the first instance of /, ?, ;, or # ends the host.
  30088. //
  30089. // If there is an @ in the hostname, then non-host chars *are* allowed
  30090. // to the left of the last @ sign, unless some host-ending character
  30091. // comes *before* the @-sign.
  30092. // URLs are obnoxious.
  30093. //
  30094. // ex:
  30095. // http://a@b@c/ => user:a@b host:c
  30096. // http://a@b?@c => user:a host:c path:/?@c
  30097. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  30098. // Review our test case against browsers more comprehensively.
  30099. // find the first instance of any hostEndingChars
  30100. var hostEnd = -1;
  30101. for (i = 0; i < hostEndingChars.length; i++) {
  30102. hec = rest.indexOf(hostEndingChars[i]);
  30103. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  30104. hostEnd = hec;
  30105. }
  30106. // at this point, either we have an explicit point where the
  30107. // auth portion cannot go past, or the last @ char is the decider.
  30108. var auth, atSign;
  30109. if (hostEnd === -1) {
  30110. // atSign can be anywhere.
  30111. atSign = rest.lastIndexOf('@');
  30112. } else {
  30113. // atSign must be in auth portion.
  30114. // http://a@b/c@d => host:b auth:a path:/c@d
  30115. atSign = rest.lastIndexOf('@', hostEnd);
  30116. }
  30117. // Now we have a portion which is definitely the auth.
  30118. // Pull that off.
  30119. if (atSign !== -1) {
  30120. auth = rest.slice(0, atSign);
  30121. rest = rest.slice(atSign + 1);
  30122. self.auth = decodeURIComponent(auth);
  30123. }
  30124. // the host is the remaining to the left of the first non-host char
  30125. hostEnd = -1;
  30126. for (i = 0; i < nonHostChars.length; i++) {
  30127. hec = rest.indexOf(nonHostChars[i]);
  30128. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  30129. hostEnd = hec;
  30130. }
  30131. // if we still have not hit it, then the entire thing is a host.
  30132. if (hostEnd === -1)
  30133. hostEnd = rest.length;
  30134. self.host = rest.slice(0, hostEnd);
  30135. rest = rest.slice(hostEnd);
  30136. // pull out port.
  30137. parseHost(self);
  30138. // we've indicated that there is a hostname,
  30139. // so even if it's empty, it has to be present.
  30140. self.hostname = self.hostname || '';
  30141. // if hostname begins with [ and ends with ]
  30142. // assume that it's an IPv6 address.
  30143. var ipv6Hostname = self.hostname[0] === '[' &&
  30144. self.hostname[self.hostname.length - 1] === ']';
  30145. // validate a little.
  30146. if (!ipv6Hostname) {
  30147. var hostparts = self.hostname.split(/\./);
  30148. for (i = 0, l = hostparts.length; i < l; i++) {
  30149. var part = hostparts[i];
  30150. if (!part) continue;
  30151. if (!part.match(hostnamePartPattern)) {
  30152. var newpart = '';
  30153. for (var j = 0, k = part.length; j < k; j++) {
  30154. if (part.charCodeAt(j) > 127) {
  30155. // we replace non-ASCII char with a temporary placeholder
  30156. // we need this to make sure size of hostname is not
  30157. // broken by replacing non-ASCII by nothing
  30158. newpart += 'x';
  30159. } else {
  30160. newpart += part[j];
  30161. }
  30162. }
  30163. // we test again with ASCII char only
  30164. if (!newpart.match(hostnamePartPattern)) {
  30165. var validParts = hostparts.slice(0, i);
  30166. var notHost = hostparts.slice(i + 1);
  30167. var bit = part.match(hostnamePartStart);
  30168. if (bit) {
  30169. validParts.push(bit[1]);
  30170. notHost.unshift(bit[2]);
  30171. }
  30172. if (notHost.length) {
  30173. rest = '/' + notHost.join('.') + rest;
  30174. }
  30175. self.hostname = validParts.join('.');
  30176. break;
  30177. }
  30178. }
  30179. }
  30180. }
  30181. if (self.hostname.length > hostnameMaxLen) {
  30182. self.hostname = '';
  30183. } else {
  30184. // hostnames are always lower case.
  30185. self.hostname = self.hostname.toLowerCase();
  30186. }
  30187. if (!ipv6Hostname) {
  30188. // IDNA Support: Returns a punycoded representation of "domain".
  30189. // It only converts parts of the domain name that
  30190. // have non-ASCII characters, i.e. it doesn't matter if
  30191. // you call it with a domain that already is ASCII-only.
  30192. self.hostname = toASCII(self.hostname);
  30193. }
  30194. p = self.port ? ':' + self.port : '';
  30195. var h = self.hostname || '';
  30196. self.host = h + p;
  30197. self.href += self.host;
  30198. // strip [ and ] from the hostname
  30199. // the host field still retains them, though
  30200. if (ipv6Hostname) {
  30201. self.hostname = self.hostname.substr(1, self.hostname.length - 2);
  30202. if (rest[0] !== '/') {
  30203. rest = '/' + rest;
  30204. }
  30205. }
  30206. }
  30207. // now rest is set to the post-host stuff.
  30208. // chop off any delim chars.
  30209. if (!unsafeProtocol[lowerProto]) {
  30210. // First, make 100% sure that any "autoEscape" chars get
  30211. // escaped, even if encodeURIComponent doesn't think they
  30212. // need to be.
  30213. for (i = 0, l = autoEscape.length; i < l; i++) {
  30214. var ae = autoEscape[i];
  30215. if (rest.indexOf(ae) === -1)
  30216. continue;
  30217. var esc = encodeURIComponent(ae);
  30218. if (esc === ae) {
  30219. esc = escape(ae);
  30220. }
  30221. rest = rest.split(ae).join(esc);
  30222. }
  30223. }
  30224. // chop off from the tail first.
  30225. var hash = rest.indexOf('#');
  30226. if (hash !== -1) {
  30227. // got a fragment string.
  30228. self.hash = rest.substr(hash);
  30229. rest = rest.slice(0, hash);
  30230. }
  30231. var qm = rest.indexOf('?');
  30232. if (qm !== -1) {
  30233. self.search = rest.substr(qm);
  30234. self.query = rest.substr(qm + 1);
  30235. if (parseQueryString) {
  30236. self.query = parse$1(self.query);
  30237. }
  30238. rest = rest.slice(0, qm);
  30239. } else if (parseQueryString) {
  30240. // no query string, but parseQueryString still requested
  30241. self.search = '';
  30242. self.query = {};
  30243. }
  30244. if (rest) self.pathname = rest;
  30245. if (slashedProtocol[lowerProto] &&
  30246. self.hostname && !self.pathname) {
  30247. self.pathname = '/';
  30248. }
  30249. //to support http.request
  30250. if (self.pathname || self.search) {
  30251. p = self.pathname || '';
  30252. var s = self.search || '';
  30253. self.path = p + s;
  30254. }
  30255. // finally, reconstruct the href based on what has been validated.
  30256. self.href = format(self);
  30257. return self;
  30258. }
  30259. function urlFileURLToPath(path) {
  30260. if (typeof path === 'string')
  30261. path = new Url().parse(path);
  30262. else if (!(path instanceof Url))
  30263. throw new TypeError('The "path" argument must be of type string or an instance of URL. Received type ' + (typeof path) + String(path));
  30264. if (path.protocol !== 'file:')
  30265. throw new TypeError('The URL must be of scheme file');
  30266. return getPathFromURLPosix(path);
  30267. }
  30268. function getPathFromURLPosix(url) {
  30269. const pathname = url.pathname;
  30270. for (let n = 0; n < pathname.length; n++) {
  30271. if (pathname[n] === '%') {
  30272. const third = pathname.codePointAt(n + 2) | 0x20;
  30273. if (pathname[n + 1] === '2' && third === 102) {
  30274. throw new TypeError(
  30275. 'must not include encoded / characters'
  30276. );
  30277. }
  30278. }
  30279. }
  30280. return decodeURIComponent(pathname);
  30281. }
  30282. // format a parsed object into a url string
  30283. function urlFormat(obj) {
  30284. // ensure it's an object, and not a string url.
  30285. // If it's an obj, this is a no-op.
  30286. // this way, you can call url_format() on strings
  30287. // to clean up potentially wonky urls.
  30288. if (isString(obj)) obj = parse({}, obj);
  30289. return format(obj);
  30290. }
  30291. function format(self) {
  30292. var auth = self.auth || '';
  30293. if (auth) {
  30294. auth = encodeURIComponent(auth);
  30295. auth = auth.replace(/%3A/i, ':');
  30296. auth += '@';
  30297. }
  30298. var protocol = self.protocol || '',
  30299. pathname = self.pathname || '',
  30300. hash = self.hash || '',
  30301. host = false,
  30302. query = '';
  30303. if (self.host) {
  30304. host = auth + self.host;
  30305. } else if (self.hostname) {
  30306. host = auth + (self.hostname.indexOf(':') === -1 ?
  30307. self.hostname :
  30308. '[' + this.hostname + ']');
  30309. if (self.port) {
  30310. host += ':' + self.port;
  30311. }
  30312. }
  30313. if (self.query &&
  30314. isObject$1(self.query) &&
  30315. Object.keys(self.query).length) {
  30316. query = stringify(self.query);
  30317. }
  30318. var search = self.search || (query && ('?' + query)) || '';
  30319. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  30320. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  30321. // unless they had them to begin with.
  30322. if (self.slashes ||
  30323. (!protocol || slashedProtocol[protocol]) && host !== false) {
  30324. host = '//' + (host || '');
  30325. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  30326. } else if (!host) {
  30327. host = '';
  30328. }
  30329. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  30330. if (search && search.charAt(0) !== '?') search = '?' + search;
  30331. pathname = pathname.replace(/[?#]/g, function(match) {
  30332. return encodeURIComponent(match);
  30333. });
  30334. search = search.replace('#', '%23');
  30335. return protocol + host + pathname + search + hash;
  30336. }
  30337. Url.prototype.format = function() {
  30338. return format(this);
  30339. };
  30340. function urlResolve(source, relative) {
  30341. return urlParse(source, false, true).resolve(relative);
  30342. }
  30343. Url.prototype.resolve = function(relative) {
  30344. return this.resolveObject(urlParse(relative, false, true)).format();
  30345. };
  30346. function urlResolveObject(source, relative) {
  30347. if (!source) return relative;
  30348. return urlParse(source, false, true).resolveObject(relative);
  30349. }
  30350. Url.prototype.resolveObject = function(relative) {
  30351. if (isString(relative)) {
  30352. var rel = new Url();
  30353. rel.parse(relative, false, true);
  30354. relative = rel;
  30355. }
  30356. var result = new Url();
  30357. var tkeys = Object.keys(this);
  30358. for (var tk = 0; tk < tkeys.length; tk++) {
  30359. var tkey = tkeys[tk];
  30360. result[tkey] = this[tkey];
  30361. }
  30362. // hash is always overridden, no matter what.
  30363. // even href="" will remove it.
  30364. result.hash = relative.hash;
  30365. // if the relative url is empty, then there's nothing left to do here.
  30366. if (relative.href === '') {
  30367. result.href = result.format();
  30368. return result;
  30369. }
  30370. // hrefs like //foo/bar always cut to the protocol.
  30371. if (relative.slashes && !relative.protocol) {
  30372. // take everything except the protocol from relative
  30373. var rkeys = Object.keys(relative);
  30374. for (var rk = 0; rk < rkeys.length; rk++) {
  30375. var rkey = rkeys[rk];
  30376. if (rkey !== 'protocol')
  30377. result[rkey] = relative[rkey];
  30378. }
  30379. //urlParse appends trailing / to urls like http://www.example.com
  30380. if (slashedProtocol[result.protocol] &&
  30381. result.hostname && !result.pathname) {
  30382. result.path = result.pathname = '/';
  30383. }
  30384. result.href = result.format();
  30385. return result;
  30386. }
  30387. var relPath;
  30388. if (relative.protocol && relative.protocol !== result.protocol) {
  30389. // if it's a known url protocol, then changing
  30390. // the protocol does weird things
  30391. // first, if it's not file:, then we MUST have a host,
  30392. // and if there was a path
  30393. // to begin with, then we MUST have a path.
  30394. // if it is file:, then the host is dropped,
  30395. // because that's known to be hostless.
  30396. // anything else is assumed to be absolute.
  30397. if (!slashedProtocol[relative.protocol]) {
  30398. var keys = Object.keys(relative);
  30399. for (var v = 0; v < keys.length; v++) {
  30400. var k = keys[v];
  30401. result[k] = relative[k];
  30402. }
  30403. result.href = result.format();
  30404. return result;
  30405. }
  30406. result.protocol = relative.protocol;
  30407. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  30408. relPath = (relative.pathname || '').split('/');
  30409. while (relPath.length && !(relative.host = relPath.shift()));
  30410. if (!relative.host) relative.host = '';
  30411. if (!relative.hostname) relative.hostname = '';
  30412. if (relPath[0] !== '') relPath.unshift('');
  30413. if (relPath.length < 2) relPath.unshift('');
  30414. result.pathname = relPath.join('/');
  30415. } else {
  30416. result.pathname = relative.pathname;
  30417. }
  30418. result.search = relative.search;
  30419. result.query = relative.query;
  30420. result.host = relative.host || '';
  30421. result.auth = relative.auth;
  30422. result.hostname = relative.hostname || relative.host;
  30423. result.port = relative.port;
  30424. // to support http.request
  30425. if (result.pathname || result.search) {
  30426. var p = result.pathname || '';
  30427. var s = result.search || '';
  30428. result.path = p + s;
  30429. }
  30430. result.slashes = result.slashes || relative.slashes;
  30431. result.href = result.format();
  30432. return result;
  30433. }
  30434. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  30435. isRelAbs = (
  30436. relative.host ||
  30437. relative.pathname && relative.pathname.charAt(0) === '/'
  30438. ),
  30439. mustEndAbs = (isRelAbs || isSourceAbs ||
  30440. (result.host && relative.pathname)),
  30441. removeAllDots = mustEndAbs,
  30442. srcPath = result.pathname && result.pathname.split('/') || [],
  30443. psychotic = result.protocol && !slashedProtocol[result.protocol];
  30444. relPath = relative.pathname && relative.pathname.split('/') || [];
  30445. // if the url is a non-slashed url, then relative
  30446. // links like ../.. should be able
  30447. // to crawl up to the hostname, as well. This is strange.
  30448. // result.protocol has already been set by now.
  30449. // Later on, put the first path part into the host field.
  30450. if (psychotic) {
  30451. result.hostname = '';
  30452. result.port = null;
  30453. if (result.host) {
  30454. if (srcPath[0] === '') srcPath[0] = result.host;
  30455. else srcPath.unshift(result.host);
  30456. }
  30457. result.host = '';
  30458. if (relative.protocol) {
  30459. relative.hostname = null;
  30460. relative.port = null;
  30461. if (relative.host) {
  30462. if (relPath[0] === '') relPath[0] = relative.host;
  30463. else relPath.unshift(relative.host);
  30464. }
  30465. relative.host = null;
  30466. }
  30467. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  30468. }
  30469. var authInHost;
  30470. if (isRelAbs) {
  30471. // it's absolute.
  30472. result.host = (relative.host || relative.host === '') ?
  30473. relative.host : result.host;
  30474. result.hostname = (relative.hostname || relative.hostname === '') ?
  30475. relative.hostname : result.hostname;
  30476. result.search = relative.search;
  30477. result.query = relative.query;
  30478. srcPath = relPath;
  30479. // fall through to the dot-handling below.
  30480. } else if (relPath.length) {
  30481. // it's relative
  30482. // throw away the existing file, and take the new path instead.
  30483. if (!srcPath) srcPath = [];
  30484. srcPath.pop();
  30485. srcPath = srcPath.concat(relPath);
  30486. result.search = relative.search;
  30487. result.query = relative.query;
  30488. } else if (!isNullOrUndefined(relative.search)) {
  30489. // just pull out the search.
  30490. // like href='?foo'.
  30491. // Put this after the other two cases because it simplifies the booleans
  30492. if (psychotic) {
  30493. result.hostname = result.host = srcPath.shift();
  30494. //occationaly the auth can get stuck only in host
  30495. //this especially happens in cases like
  30496. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  30497. authInHost = result.host && result.host.indexOf('@') > 0 ?
  30498. result.host.split('@') : false;
  30499. if (authInHost) {
  30500. result.auth = authInHost.shift();
  30501. result.host = result.hostname = authInHost.shift();
  30502. }
  30503. }
  30504. result.search = relative.search;
  30505. result.query = relative.query;
  30506. //to support http.request
  30507. if (!isNull(result.pathname) || !isNull(result.search)) {
  30508. result.path = (result.pathname ? result.pathname : '') +
  30509. (result.search ? result.search : '');
  30510. }
  30511. result.href = result.format();
  30512. return result;
  30513. }
  30514. if (!srcPath.length) {
  30515. // no path at all. easy.
  30516. // we've already handled the other stuff above.
  30517. result.pathname = null;
  30518. //to support http.request
  30519. if (result.search) {
  30520. result.path = '/' + result.search;
  30521. } else {
  30522. result.path = null;
  30523. }
  30524. result.href = result.format();
  30525. return result;
  30526. }
  30527. // if a url ENDs in . or .., then it must get a trailing slash.
  30528. // however, if it ends in anything else non-slashy,
  30529. // then it must NOT get a trailing slash.
  30530. var last = srcPath.slice(-1)[0];
  30531. var hasTrailingSlash = (
  30532. (result.host || relative.host || srcPath.length > 1) &&
  30533. (last === '.' || last === '..') || last === '');
  30534. // strip single dots, resolve double dots to parent dir
  30535. // if the path tries to go above the root, `up` ends up > 0
  30536. var up = 0;
  30537. for (var i = srcPath.length; i >= 0; i--) {
  30538. last = srcPath[i];
  30539. if (last === '.') {
  30540. srcPath.splice(i, 1);
  30541. } else if (last === '..') {
  30542. srcPath.splice(i, 1);
  30543. up++;
  30544. } else if (up) {
  30545. srcPath.splice(i, 1);
  30546. up--;
  30547. }
  30548. }
  30549. // if the path is allowed to go above the root, restore leading ..s
  30550. if (!mustEndAbs && !removeAllDots) {
  30551. for (; up--; up) {
  30552. srcPath.unshift('..');
  30553. }
  30554. }
  30555. if (mustEndAbs && srcPath[0] !== '' &&
  30556. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  30557. srcPath.unshift('');
  30558. }
  30559. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  30560. srcPath.push('');
  30561. }
  30562. var isAbsolute = srcPath[0] === '' ||
  30563. (srcPath[0] && srcPath[0].charAt(0) === '/');
  30564. // put the host back
  30565. if (psychotic) {
  30566. result.hostname = result.host = isAbsolute ? '' :
  30567. srcPath.length ? srcPath.shift() : '';
  30568. //occationaly the auth can get stuck only in host
  30569. //this especially happens in cases like
  30570. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  30571. authInHost = result.host && result.host.indexOf('@') > 0 ?
  30572. result.host.split('@') : false;
  30573. if (authInHost) {
  30574. result.auth = authInHost.shift();
  30575. result.host = result.hostname = authInHost.shift();
  30576. }
  30577. }
  30578. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  30579. if (mustEndAbs && !isAbsolute) {
  30580. srcPath.unshift('');
  30581. }
  30582. if (!srcPath.length) {
  30583. result.pathname = null;
  30584. result.path = null;
  30585. } else {
  30586. result.pathname = srcPath.join('/');
  30587. }
  30588. //to support request.http
  30589. if (!isNull(result.pathname) || !isNull(result.search)) {
  30590. result.path = (result.pathname ? result.pathname : '') +
  30591. (result.search ? result.search : '');
  30592. }
  30593. result.auth = relative.auth || result.auth;
  30594. result.slashes = result.slashes || relative.slashes;
  30595. result.href = result.format();
  30596. return result;
  30597. };
  30598. Url.prototype.parseHost = function() {
  30599. return parseHost(this);
  30600. };
  30601. function parseHost(self) {
  30602. var host = self.host;
  30603. var port = portPattern.exec(host);
  30604. if (port) {
  30605. port = port[0];
  30606. if (port !== ':') {
  30607. self.port = port.substr(1);
  30608. }
  30609. host = host.substr(0, host.length - port.length);
  30610. }
  30611. if (host) self.hostname = host;
  30612. }
  30613. var _polyfillNode_url$1 = /*#__PURE__*/Object.freeze({
  30614. __proto__: null,
  30615. URL: URL$1,
  30616. URLSearchParams: URLSearchParams,
  30617. Url: Url,
  30618. default: _polyfillNode_url,
  30619. fileURLToPath: urlFileURLToPath,
  30620. format: urlFormat,
  30621. parse: urlParse,
  30622. resolve: urlResolve,
  30623. resolveObject: urlResolveObject
  30624. });
  30625. function isRelativeUrl(url) {
  30626. const firstChar = url.charAt(0);
  30627. return firstChar === "." || firstChar === "~" || firstChar === "@" || firstChar === "#";
  30628. }
  30629. const externalRE = /^(?:https?:)?\/\//;
  30630. function isExternalUrl(url) {
  30631. return externalRE.test(url);
  30632. }
  30633. const dataUrlRE = /^\s*data:/i;
  30634. function isDataUrl(url) {
  30635. return dataUrlRE.test(url);
  30636. }
  30637. function normalizeDecodedImportPath(source) {
  30638. try {
  30639. return decodeURIComponent(source);
  30640. } catch (e) {
  30641. return source;
  30642. }
  30643. }
  30644. function parseUrl(url) {
  30645. const firstChar = url.charAt(0);
  30646. if (firstChar === "~") {
  30647. const secondChar = url.charAt(1);
  30648. url = url.slice(secondChar === "/" ? 2 : 1);
  30649. }
  30650. return parseUriParts(url);
  30651. }
  30652. function parseUriParts(urlString) {
  30653. return urlParse(isString$1(urlString) ? urlString : "", false, true);
  30654. }
  30655. var __defProp$9 = Object.defineProperty;
  30656. var __defProps$8 = Object.defineProperties;
  30657. var __getOwnPropDescs$8 = Object.getOwnPropertyDescriptors;
  30658. var __getOwnPropSymbols$9 = Object.getOwnPropertySymbols;
  30659. var __hasOwnProp$9 = Object.prototype.hasOwnProperty;
  30660. var __propIsEnum$9 = Object.prototype.propertyIsEnumerable;
  30661. var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  30662. var __spreadValues$9 = (a, b) => {
  30663. for (var prop in b || (b = {}))
  30664. if (__hasOwnProp$9.call(b, prop))
  30665. __defNormalProp$9(a, prop, b[prop]);
  30666. if (__getOwnPropSymbols$9)
  30667. for (var prop of __getOwnPropSymbols$9(b)) {
  30668. if (__propIsEnum$9.call(b, prop))
  30669. __defNormalProp$9(a, prop, b[prop]);
  30670. }
  30671. return a;
  30672. };
  30673. var __spreadProps$8 = (a, b) => __defProps$8(a, __getOwnPropDescs$8(b));
  30674. const resourceUrlTagConfig = {
  30675. video: ["src", "poster"],
  30676. source: ["src"],
  30677. img: ["src"]
  30678. };
  30679. const defaultAssetUrlOptions = {
  30680. base: null,
  30681. includeAbsolute: false,
  30682. tags: __spreadProps$8(__spreadValues$9({}, resourceUrlTagConfig), {
  30683. image: ["xlink:href", "href"],
  30684. use: ["xlink:href", "href"]
  30685. })
  30686. };
  30687. const normalizeOptions = (options) => {
  30688. if (Object.keys(options).some((key) => isArray$3(options[key]))) {
  30689. return __spreadProps$8(__spreadValues$9({}, defaultAssetUrlOptions), {
  30690. tags: options
  30691. });
  30692. }
  30693. return __spreadValues$9(__spreadValues$9({}, defaultAssetUrlOptions), options);
  30694. };
  30695. const createAssetUrlTransformWithOptions = (options) => {
  30696. return (node, context) => transformAssetUrl(node, context, options);
  30697. };
  30698. function canTransformHashImport(tag, attrName) {
  30699. var _a;
  30700. return !!((_a = resourceUrlTagConfig[tag]) == null ? void 0 : _a.includes(attrName));
  30701. }
  30702. const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
  30703. if (node.type === 1) {
  30704. if (!node.props.length) {
  30705. return;
  30706. }
  30707. const tags = options.tags || defaultAssetUrlOptions.tags;
  30708. const attrs = tags[node.tag];
  30709. const wildCardAttrs = tags["*"];
  30710. if (!attrs && !wildCardAttrs) {
  30711. return;
  30712. }
  30713. const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
  30714. node.props.forEach((attr, index) => {
  30715. if (attr.type !== 6 || !assetAttrs.includes(attr.name) || !attr.value) {
  30716. return;
  30717. }
  30718. const urlValue = attr.value.content;
  30719. const isHashOnlyValue = urlValue[0] === "#";
  30720. if (isExternalUrl(urlValue) || isDataUrl(urlValue) || // a bare `#` is never a valid import specifier
  30721. urlValue === "#" || isHashOnlyValue && !canTransformHashImport(node.tag, attr.name) || !options.includeAbsolute && !isRelativeUrl(urlValue)) {
  30722. return;
  30723. }
  30724. const url = parseUrl(urlValue);
  30725. if (options.base && urlValue[0] === ".") {
  30726. const base = parseUrl(options.base);
  30727. const protocol = base.protocol || "";
  30728. const host = base.host ? protocol + "//" + base.host : "";
  30729. const basePath = base.path || "/";
  30730. attr.value.content = host + (path.posix || path).join(basePath, url.path + (url.hash || ""));
  30731. return;
  30732. }
  30733. const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
  30734. node.props[index] = {
  30735. type: 7,
  30736. name: "bind",
  30737. arg: createSimpleExpression(attr.name, true, attr.loc),
  30738. exp,
  30739. modifiers: [],
  30740. loc: attr.loc
  30741. };
  30742. });
  30743. }
  30744. };
  30745. function resolveOrRegisterImport(source, loc, context) {
  30746. const normalizedSource = normalizeDecodedImportPath(source);
  30747. const existingIndex = context.imports.findIndex(
  30748. (i) => i.path === normalizedSource
  30749. );
  30750. if (existingIndex > -1) {
  30751. return {
  30752. name: `_imports_${existingIndex}`,
  30753. exp: context.imports[existingIndex].exp
  30754. };
  30755. }
  30756. const name = `_imports_${context.imports.length}`;
  30757. const exp = createSimpleExpression(
  30758. name,
  30759. false,
  30760. loc,
  30761. 3
  30762. );
  30763. context.imports.push({
  30764. exp,
  30765. path: normalizedSource
  30766. });
  30767. return { name, exp };
  30768. }
  30769. function getImportsExpressionExp(path2, hash, loc, context) {
  30770. if (!path2 && !hash) {
  30771. return createSimpleExpression(`''`, false, loc, 3);
  30772. }
  30773. if (!path2 && hash) {
  30774. const { exp } = resolveOrRegisterImport(hash, loc, context);
  30775. return exp;
  30776. }
  30777. if (path2 && !hash) {
  30778. const { exp } = resolveOrRegisterImport(path2, loc, context);
  30779. return exp;
  30780. }
  30781. const { name } = resolveOrRegisterImport(path2, loc, context);
  30782. const hashExp = `${name} + '${hash}'`;
  30783. const finalExp = createSimpleExpression(
  30784. hashExp,
  30785. false,
  30786. loc,
  30787. 3
  30788. );
  30789. if (!context.hoistStatic) {
  30790. return finalExp;
  30791. }
  30792. const existingHoistIndex = context.hoists.findIndex((h) => {
  30793. return h && h.type === 4 && !h.isStatic && h.content === hashExp;
  30794. });
  30795. if (existingHoistIndex > -1) {
  30796. return createSimpleExpression(
  30797. `_hoisted_${existingHoistIndex + 1}`,
  30798. false,
  30799. loc,
  30800. 3
  30801. );
  30802. }
  30803. return context.hoist(finalExp);
  30804. }
  30805. const srcsetTags = ["img", "source"];
  30806. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  30807. const createSrcsetTransformWithOptions = (options) => {
  30808. return (node, context) => transformSrcset(node, context, options);
  30809. };
  30810. const transformSrcset = (node, context, options = defaultAssetUrlOptions) => {
  30811. if (node.type === 1) {
  30812. if (srcsetTags.includes(node.tag) && node.props.length) {
  30813. node.props.forEach((attr, index) => {
  30814. if (attr.name === "srcset" && attr.type === 6) {
  30815. if (!attr.value) return;
  30816. const value = attr.value.content;
  30817. if (!value) return;
  30818. const imageCandidates = value.split(",").map((s) => {
  30819. const [url, descriptor] = s.replace(escapedSpaceCharacters, " ").trim().split(" ", 2);
  30820. return { url, descriptor };
  30821. });
  30822. for (let i = 0; i < imageCandidates.length; i++) {
  30823. const { url } = imageCandidates[i];
  30824. if (isDataUrl(url)) {
  30825. imageCandidates[i + 1].url = url + "," + imageCandidates[i + 1].url;
  30826. imageCandidates.splice(i, 1);
  30827. }
  30828. }
  30829. const shouldProcessUrl = (url) => {
  30830. return url && !isExternalUrl(url) && !isDataUrl(url) && (options.includeAbsolute || isRelativeUrl(url));
  30831. };
  30832. if (!imageCandidates.some(({ url }) => shouldProcessUrl(url))) {
  30833. return;
  30834. }
  30835. if (options.base) {
  30836. const base = options.base;
  30837. const set = [];
  30838. let needImportTransform = false;
  30839. imageCandidates.forEach((candidate) => {
  30840. let { url, descriptor } = candidate;
  30841. descriptor = descriptor ? ` ${descriptor}` : ``;
  30842. if (url[0] === ".") {
  30843. candidate.url = (path.posix || path).join(base, url);
  30844. set.push(candidate.url + descriptor);
  30845. } else if (shouldProcessUrl(url)) {
  30846. needImportTransform = true;
  30847. } else {
  30848. set.push(url + descriptor);
  30849. }
  30850. });
  30851. if (!needImportTransform) {
  30852. attr.value.content = set.join(", ");
  30853. return;
  30854. }
  30855. }
  30856. const compoundExpression = createCompoundExpression([], attr.loc);
  30857. imageCandidates.forEach(({ url, descriptor }, index2) => {
  30858. if (shouldProcessUrl(url)) {
  30859. const { path: path2, hash } = parseUrl(url);
  30860. const source = path2 ? path2 : hash;
  30861. if (source) {
  30862. const normalizedSource = normalizeDecodedImportPath(source);
  30863. const existingImportsIndex = context.imports.findIndex(
  30864. (i) => i.path === normalizedSource
  30865. );
  30866. let exp2;
  30867. if (existingImportsIndex > -1) {
  30868. exp2 = createSimpleExpression(
  30869. `_imports_${existingImportsIndex}`,
  30870. false,
  30871. attr.loc,
  30872. 3
  30873. );
  30874. } else {
  30875. exp2 = createSimpleExpression(
  30876. `_imports_${context.imports.length}`,
  30877. false,
  30878. attr.loc,
  30879. 3
  30880. );
  30881. context.imports.push({ exp: exp2, path: normalizedSource });
  30882. }
  30883. if (path2 && hash) {
  30884. exp2 = createSimpleExpression(
  30885. `${exp2.content} + '${hash}'`,
  30886. false,
  30887. attr.loc,
  30888. 3
  30889. );
  30890. }
  30891. compoundExpression.children.push(exp2);
  30892. }
  30893. } else {
  30894. const exp2 = createSimpleExpression(
  30895. `"${url}"`,
  30896. false,
  30897. attr.loc,
  30898. 3
  30899. );
  30900. compoundExpression.children.push(exp2);
  30901. }
  30902. const isNotLast = imageCandidates.length - 1 > index2;
  30903. if (descriptor && isNotLast) {
  30904. compoundExpression.children.push(` + ' ${descriptor}, ' + `);
  30905. } else if (descriptor) {
  30906. compoundExpression.children.push(` + ' ${descriptor}'`);
  30907. } else if (isNotLast) {
  30908. compoundExpression.children.push(` + ', ' + `);
  30909. }
  30910. });
  30911. let exp = compoundExpression;
  30912. if (context.hoistStatic) {
  30913. exp = context.hoist(compoundExpression);
  30914. exp.constType = 3;
  30915. }
  30916. node.props[index] = {
  30917. type: 7,
  30918. name: "bind",
  30919. arg: createSimpleExpression("srcset", true, attr.loc),
  30920. exp,
  30921. modifiers: [],
  30922. loc: attr.loc
  30923. };
  30924. }
  30925. });
  30926. }
  30927. }
  30928. };
  30929. const SSR_INTERPOLATE = /* @__PURE__ */ Symbol(`ssrInterpolate`);
  30930. const SSR_RENDER_VNODE = /* @__PURE__ */ Symbol(`ssrRenderVNode`);
  30931. const SSR_RENDER_COMPONENT = /* @__PURE__ */ Symbol(`ssrRenderComponent`);
  30932. const SSR_RENDER_SLOT = /* @__PURE__ */ Symbol(`ssrRenderSlot`);
  30933. const SSR_RENDER_SLOT_INNER = /* @__PURE__ */ Symbol(`ssrRenderSlotInner`);
  30934. const SSR_RENDER_CLASS = /* @__PURE__ */ Symbol(`ssrRenderClass`);
  30935. const SSR_RENDER_STYLE = /* @__PURE__ */ Symbol(`ssrRenderStyle`);
  30936. const SSR_RENDER_ATTRS = /* @__PURE__ */ Symbol(`ssrRenderAttrs`);
  30937. const SSR_RENDER_ATTR = /* @__PURE__ */ Symbol(`ssrRenderAttr`);
  30938. const SSR_RENDER_DYNAMIC_ATTR = /* @__PURE__ */ Symbol(`ssrRenderDynamicAttr`);
  30939. const SSR_RENDER_LIST = /* @__PURE__ */ Symbol(`ssrRenderList`);
  30940. const SSR_INCLUDE_BOOLEAN_ATTR = /* @__PURE__ */ Symbol(
  30941. `ssrIncludeBooleanAttr`
  30942. );
  30943. const SSR_LOOSE_EQUAL = /* @__PURE__ */ Symbol(`ssrLooseEqual`);
  30944. const SSR_LOOSE_CONTAIN = /* @__PURE__ */ Symbol(`ssrLooseContain`);
  30945. const SSR_RENDER_DYNAMIC_MODEL = /* @__PURE__ */ Symbol(
  30946. `ssrRenderDynamicModel`
  30947. );
  30948. const SSR_GET_DYNAMIC_MODEL_PROPS = /* @__PURE__ */ Symbol(
  30949. `ssrGetDynamicModelProps`
  30950. );
  30951. const SSR_RENDER_TELEPORT = /* @__PURE__ */ Symbol(`ssrRenderTeleport`);
  30952. const SSR_RENDER_SUSPENSE = /* @__PURE__ */ Symbol(`ssrRenderSuspense`);
  30953. const SSR_GET_DIRECTIVE_PROPS = /* @__PURE__ */ Symbol(`ssrGetDirectiveProps`);
  30954. const ssrHelpers = {
  30955. [SSR_INTERPOLATE]: `ssrInterpolate`,
  30956. [SSR_RENDER_VNODE]: `ssrRenderVNode`,
  30957. [SSR_RENDER_COMPONENT]: `ssrRenderComponent`,
  30958. [SSR_RENDER_SLOT]: `ssrRenderSlot`,
  30959. [SSR_RENDER_SLOT_INNER]: `ssrRenderSlotInner`,
  30960. [SSR_RENDER_CLASS]: `ssrRenderClass`,
  30961. [SSR_RENDER_STYLE]: `ssrRenderStyle`,
  30962. [SSR_RENDER_ATTRS]: `ssrRenderAttrs`,
  30963. [SSR_RENDER_ATTR]: `ssrRenderAttr`,
  30964. [SSR_RENDER_DYNAMIC_ATTR]: `ssrRenderDynamicAttr`,
  30965. [SSR_RENDER_LIST]: `ssrRenderList`,
  30966. [SSR_INCLUDE_BOOLEAN_ATTR]: `ssrIncludeBooleanAttr`,
  30967. [SSR_LOOSE_EQUAL]: `ssrLooseEqual`,
  30968. [SSR_LOOSE_CONTAIN]: `ssrLooseContain`,
  30969. [SSR_RENDER_DYNAMIC_MODEL]: `ssrRenderDynamicModel`,
  30970. [SSR_GET_DYNAMIC_MODEL_PROPS]: `ssrGetDynamicModelProps`,
  30971. [SSR_RENDER_TELEPORT]: `ssrRenderTeleport`,
  30972. [SSR_RENDER_SUSPENSE]: `ssrRenderSuspense`,
  30973. [SSR_GET_DIRECTIVE_PROPS]: `ssrGetDirectiveProps`
  30974. };
  30975. registerRuntimeHelpers(ssrHelpers);
  30976. const ssrTransformIf = createStructuralDirectiveTransform(
  30977. /^(?:if|else|else-if)$/,
  30978. processIf
  30979. );
  30980. function ssrProcessIf(node, context, disableNestedFragments = false, disableComment = false) {
  30981. const [rootBranch] = node.branches;
  30982. const ifStatement = createIfStatement(
  30983. rootBranch.condition,
  30984. processIfBranch(rootBranch, context, disableNestedFragments)
  30985. );
  30986. context.pushStatement(ifStatement);
  30987. let currentIf = ifStatement;
  30988. for (let i = 1; i < node.branches.length; i++) {
  30989. const branch = node.branches[i];
  30990. const branchBlockStatement = processIfBranch(
  30991. branch,
  30992. context,
  30993. disableNestedFragments
  30994. );
  30995. if (branch.condition) {
  30996. currentIf = currentIf.alternate = createIfStatement(
  30997. branch.condition,
  30998. branchBlockStatement
  30999. );
  31000. } else {
  31001. currentIf.alternate = branchBlockStatement;
  31002. }
  31003. }
  31004. if (!currentIf.alternate && !disableComment) {
  31005. currentIf.alternate = createBlockStatement([
  31006. createCallExpression(`_push`, ["`<!---->`"])
  31007. ]);
  31008. }
  31009. }
  31010. function processIfBranch(branch, context, disableNestedFragments = false) {
  31011. const { children } = branch;
  31012. const needFragmentWrapper = !disableNestedFragments && (children.length !== 1 || children[0].type !== 1) && // optimize away nested fragments when the only child is a ForNode
  31013. !(children.length === 1 && children[0].type === 11);
  31014. return processChildrenAsStatement(branch, context, needFragmentWrapper);
  31015. }
  31016. const ssrTransformFor = createStructuralDirectiveTransform("for", processFor);
  31017. function ssrProcessFor(node, context, disableNestedFragments = false) {
  31018. const needFragmentWrapper = !disableNestedFragments && (node.children.length !== 1 || node.children[0].type !== 1);
  31019. const renderLoop = createFunctionExpression(
  31020. createForLoopParams(node.parseResult)
  31021. );
  31022. renderLoop.body = processChildrenAsStatement(
  31023. node,
  31024. context,
  31025. needFragmentWrapper
  31026. );
  31027. if (!disableNestedFragments) {
  31028. context.pushStringPart(`<!--[-->`);
  31029. }
  31030. context.pushStatement(
  31031. createCallExpression(context.helper(SSR_RENDER_LIST), [
  31032. node.source,
  31033. renderLoop
  31034. ])
  31035. );
  31036. if (!disableNestedFragments) {
  31037. context.pushStringPart(`<!--]-->`);
  31038. }
  31039. }
  31040. const ssrTransformSlotOutlet = (node, context) => {
  31041. if (isSlotOutlet(node)) {
  31042. const { slotName, slotProps } = processSlotOutlet(node, context);
  31043. const args = [
  31044. `_ctx.$slots`,
  31045. slotName,
  31046. slotProps || `{}`,
  31047. // fallback content placeholder. will be replaced in the process phase
  31048. `null`,
  31049. `_push`,
  31050. `_parent`
  31051. ];
  31052. if (context.scopeId && context.slotted !== false) {
  31053. args.push(`"${context.scopeId}-s"`);
  31054. }
  31055. let method = SSR_RENDER_SLOT;
  31056. let parent = context.parent;
  31057. if (parent) {
  31058. const children = parent.children;
  31059. if (parent.type === 10) {
  31060. parent = context.grandParent;
  31061. }
  31062. let componentType;
  31063. if (parent.type === 1 && parent.tagType === 1 && ((componentType = resolveComponentType(parent, context, true)) === TRANSITION || componentType === TRANSITION_GROUP) && children.filter((c) => c.type === 1).length === 1) {
  31064. method = SSR_RENDER_SLOT_INNER;
  31065. if (!(context.scopeId && context.slotted !== false)) {
  31066. args.push("null");
  31067. }
  31068. args.push("true");
  31069. }
  31070. }
  31071. node.ssrCodegenNode = createCallExpression(context.helper(method), args);
  31072. }
  31073. };
  31074. function ssrProcessSlotOutlet(node, context) {
  31075. const renderCall = node.ssrCodegenNode;
  31076. if (node.children.length) {
  31077. const fallbackRenderFn = createFunctionExpression([]);
  31078. fallbackRenderFn.body = processChildrenAsStatement(node, context);
  31079. renderCall.arguments[3] = fallbackRenderFn;
  31080. }
  31081. if (context.withSlotScopeId) {
  31082. const slotScopeId = renderCall.arguments[6];
  31083. renderCall.arguments[6] = slotScopeId ? `${slotScopeId} + _scopeId` : `_scopeId`;
  31084. }
  31085. context.pushStatement(node.ssrCodegenNode);
  31086. }
  31087. function createSSRCompilerError(code, loc) {
  31088. return createCompilerError(code, loc, SSRErrorMessages);
  31089. }
  31090. const SSRErrorMessages = {
  31091. [65]: `Unsafe attribute name for SSR.`,
  31092. [66]: `Missing the 'to' prop on teleport element.`,
  31093. [67]: `Invalid AST node during SSR transform.`
  31094. };
  31095. function ssrProcessTeleport(node, context) {
  31096. const targetProp = findProp(node, "to");
  31097. if (!targetProp) {
  31098. context.onError(
  31099. createSSRCompilerError(66, node.loc)
  31100. );
  31101. return;
  31102. }
  31103. let target;
  31104. if (targetProp.type === 6) {
  31105. target = targetProp.value && createSimpleExpression(targetProp.value.content, true);
  31106. } else {
  31107. target = targetProp.exp;
  31108. }
  31109. if (!target) {
  31110. context.onError(
  31111. createSSRCompilerError(
  31112. 66,
  31113. targetProp.loc
  31114. )
  31115. );
  31116. return;
  31117. }
  31118. const disabledProp = findProp(
  31119. node,
  31120. "disabled",
  31121. false,
  31122. true
  31123. /* allow empty */
  31124. );
  31125. const disabled = disabledProp ? disabledProp.type === 6 ? `true` : disabledProp.exp || `false` : `false`;
  31126. const contentRenderFn = createFunctionExpression(
  31127. [`_push`],
  31128. void 0,
  31129. // Body is added later
  31130. true,
  31131. // newline
  31132. false,
  31133. // isSlot
  31134. node.loc
  31135. );
  31136. contentRenderFn.body = processChildrenAsStatement(node, context);
  31137. context.pushStatement(
  31138. createCallExpression(context.helper(SSR_RENDER_TELEPORT), [
  31139. `_push`,
  31140. contentRenderFn,
  31141. target,
  31142. disabled,
  31143. `_parent`
  31144. ])
  31145. );
  31146. }
  31147. const wipMap$3 = /* @__PURE__ */ new WeakMap();
  31148. function ssrTransformSuspense(node, context) {
  31149. return () => {
  31150. if (node.children.length) {
  31151. const wipEntry = {
  31152. slotsExp: null,
  31153. // to be immediately set
  31154. wipSlots: []
  31155. };
  31156. wipMap$3.set(node, wipEntry);
  31157. wipEntry.slotsExp = buildSlots(
  31158. node,
  31159. context,
  31160. (_props, _vForExp, children, loc) => {
  31161. const fn = createFunctionExpression(
  31162. [],
  31163. void 0,
  31164. // no return, assign body later
  31165. true,
  31166. // newline
  31167. false,
  31168. // suspense slots are not treated as normal slots
  31169. loc
  31170. );
  31171. wipEntry.wipSlots.push({
  31172. fn,
  31173. children
  31174. });
  31175. return fn;
  31176. }
  31177. ).slots;
  31178. }
  31179. };
  31180. }
  31181. function ssrProcessSuspense(node, context) {
  31182. const wipEntry = wipMap$3.get(node);
  31183. if (!wipEntry) {
  31184. return;
  31185. }
  31186. const { slotsExp, wipSlots } = wipEntry;
  31187. for (let i = 0; i < wipSlots.length; i++) {
  31188. const slot = wipSlots[i];
  31189. slot.fn.body = processChildrenAsStatement(slot, context);
  31190. }
  31191. context.pushStatement(
  31192. createCallExpression(context.helper(SSR_RENDER_SUSPENSE), [
  31193. `_push`,
  31194. slotsExp
  31195. ])
  31196. );
  31197. }
  31198. const rawChildrenMap = /* @__PURE__ */ new WeakMap();
  31199. const ssrTransformElement = (node, context) => {
  31200. if (node.type !== 1 || node.tagType !== 0) {
  31201. return;
  31202. }
  31203. return function ssrPostTransformElement() {
  31204. const openTag = [`<${node.tag}`];
  31205. const needTagForRuntime = node.tag === "textarea" || node.tag.indexOf("-") > 0;
  31206. const hasDynamicVBind = hasDynamicKeyVBind(node);
  31207. const hasCustomDir = node.props.some(
  31208. (p) => p.type === 7 && !isBuiltInDirective(p.name)
  31209. );
  31210. const vShowPropIndex = node.props.findIndex(
  31211. (i) => i.type === 7 && i.name === "show"
  31212. );
  31213. if (vShowPropIndex !== -1) {
  31214. const vShowProp = node.props[vShowPropIndex];
  31215. node.props.splice(vShowPropIndex, 1);
  31216. node.props.push(vShowProp);
  31217. }
  31218. const needMergeProps = hasDynamicVBind || hasCustomDir;
  31219. if (needMergeProps) {
  31220. const { props, directives } = buildProps(
  31221. node,
  31222. context,
  31223. node.props,
  31224. false,
  31225. false,
  31226. true
  31227. );
  31228. if (props || directives.length) {
  31229. const mergedProps = buildSSRProps(props, directives, context);
  31230. const propsExp = createCallExpression(
  31231. context.helper(SSR_RENDER_ATTRS),
  31232. [mergedProps]
  31233. );
  31234. if (node.tag === "textarea") {
  31235. const existingText = node.children[0];
  31236. if (!hasContentOverrideDirective(node) && (!existingText || existingText.type !== 5)) {
  31237. const tempId = `_temp${context.temps++}`;
  31238. propsExp.arguments = [
  31239. createAssignmentExpression(
  31240. createSimpleExpression(tempId, false),
  31241. mergedProps
  31242. )
  31243. ];
  31244. rawChildrenMap.set(
  31245. node,
  31246. createCallExpression(context.helper(SSR_INTERPOLATE), [
  31247. createConditionalExpression(
  31248. createSimpleExpression(`"value" in ${tempId}`, false),
  31249. createSimpleExpression(`${tempId}.value`, false),
  31250. createSimpleExpression(
  31251. existingText ? existingText.content : ``,
  31252. true
  31253. ),
  31254. false
  31255. )
  31256. ])
  31257. );
  31258. }
  31259. } else if (node.tag === "input") {
  31260. const vModel = findVModel(node);
  31261. if (vModel) {
  31262. const tempId = `_temp${context.temps++}`;
  31263. const tempExp = createSimpleExpression(tempId, false);
  31264. propsExp.arguments = [
  31265. createSequenceExpression([
  31266. createAssignmentExpression(tempExp, mergedProps),
  31267. createCallExpression(context.helper(MERGE_PROPS), [
  31268. tempExp,
  31269. createCallExpression(
  31270. context.helper(SSR_GET_DYNAMIC_MODEL_PROPS),
  31271. [
  31272. tempExp,
  31273. // existing props
  31274. vModel.exp
  31275. // model
  31276. ]
  31277. )
  31278. ])
  31279. ])
  31280. ];
  31281. }
  31282. } else if (directives.length && !node.children.length) {
  31283. if (!hasContentOverrideDirective(node)) {
  31284. const tempId = `_temp${context.temps++}`;
  31285. propsExp.arguments = [
  31286. createAssignmentExpression(
  31287. createSimpleExpression(tempId, false),
  31288. mergedProps
  31289. )
  31290. ];
  31291. rawChildrenMap.set(
  31292. node,
  31293. createConditionalExpression(
  31294. createSimpleExpression(`"textContent" in ${tempId}`, false),
  31295. createCallExpression(context.helper(SSR_INTERPOLATE), [
  31296. createSimpleExpression(`${tempId}.textContent`, false)
  31297. ]),
  31298. createSimpleExpression(`${tempId}.innerHTML ?? ''`, false),
  31299. false
  31300. )
  31301. );
  31302. }
  31303. }
  31304. if (needTagForRuntime) {
  31305. propsExp.arguments.push(`"${node.tag}"`);
  31306. }
  31307. openTag.push(propsExp);
  31308. }
  31309. }
  31310. let dynamicClassBinding = void 0;
  31311. let staticClassBinding = void 0;
  31312. let dynamicStyleBinding = void 0;
  31313. for (let i = 0; i < node.props.length; i++) {
  31314. const prop = node.props[i];
  31315. if (node.tag === "input" && isTrueFalseValue(prop)) {
  31316. continue;
  31317. }
  31318. if (prop.type === 7) {
  31319. if (prop.name === "html" && prop.exp) {
  31320. rawChildrenMap.set(
  31321. node,
  31322. createCompoundExpression([`(`, prop.exp, `) ?? ''`])
  31323. );
  31324. } else if (prop.name === "text" && prop.exp) {
  31325. node.children = [createInterpolation(prop.exp, prop.loc)];
  31326. } else if (prop.name === "slot") {
  31327. context.onError(
  31328. createCompilerError(40, prop.loc)
  31329. );
  31330. } else if (isTextareaWithValue(node, prop) && prop.exp) {
  31331. if (!needMergeProps) {
  31332. node.children = [createInterpolation(prop.exp, prop.loc)];
  31333. }
  31334. } else if (!needMergeProps && prop.name !== "on") {
  31335. const directiveTransform = context.directiveTransforms[prop.name];
  31336. if (directiveTransform) {
  31337. const { props, ssrTagParts } = directiveTransform(
  31338. prop,
  31339. node,
  31340. context
  31341. );
  31342. if (ssrTagParts) {
  31343. openTag.push(...ssrTagParts);
  31344. }
  31345. for (let j = 0; j < props.length; j++) {
  31346. const { key, value } = props[j];
  31347. if (isStaticExp(key)) {
  31348. let attrName = key.content;
  31349. if (attrName === "key" || attrName === "ref") {
  31350. continue;
  31351. }
  31352. if (attrName === "class") {
  31353. openTag.push(
  31354. ` class="`,
  31355. dynamicClassBinding = createCallExpression(
  31356. context.helper(SSR_RENDER_CLASS),
  31357. [value]
  31358. ),
  31359. `"`
  31360. );
  31361. } else if (attrName === "style") {
  31362. if (dynamicStyleBinding) {
  31363. mergeCall(dynamicStyleBinding, value);
  31364. } else {
  31365. openTag.push(
  31366. ` style="`,
  31367. dynamicStyleBinding = createCallExpression(
  31368. context.helper(SSR_RENDER_STYLE),
  31369. [value]
  31370. ),
  31371. `"`
  31372. );
  31373. }
  31374. } else {
  31375. attrName = node.tag.indexOf("-") > 0 ? attrName : propsToAttrMap[attrName] || attrName.toLowerCase();
  31376. if (isBooleanAttr(attrName)) {
  31377. openTag.push(
  31378. createConditionalExpression(
  31379. createCallExpression(
  31380. context.helper(SSR_INCLUDE_BOOLEAN_ATTR),
  31381. [value]
  31382. ),
  31383. createSimpleExpression(" " + attrName, true),
  31384. createSimpleExpression("", true),
  31385. false
  31386. )
  31387. );
  31388. } else if (isSSRSafeAttrName(attrName)) {
  31389. openTag.push(
  31390. createCallExpression(context.helper(SSR_RENDER_ATTR), [
  31391. key,
  31392. value
  31393. ])
  31394. );
  31395. } else {
  31396. context.onError(
  31397. createSSRCompilerError(
  31398. 65,
  31399. key.loc
  31400. )
  31401. );
  31402. }
  31403. }
  31404. } else {
  31405. const args = [key, value];
  31406. if (needTagForRuntime) {
  31407. args.push(`"${node.tag}"`);
  31408. }
  31409. openTag.push(
  31410. createCallExpression(
  31411. context.helper(SSR_RENDER_DYNAMIC_ATTR),
  31412. args
  31413. )
  31414. );
  31415. }
  31416. }
  31417. }
  31418. }
  31419. } else {
  31420. const name = prop.name;
  31421. if (node.tag === "textarea" && name === "value" && prop.value) {
  31422. rawChildrenMap.set(node, escapeHtml(prop.value.content));
  31423. } else if (!needMergeProps) {
  31424. if (name === "key" || name === "ref") {
  31425. continue;
  31426. }
  31427. if (name === "class" && prop.value) {
  31428. staticClassBinding = JSON.stringify(prop.value.content);
  31429. }
  31430. openTag.push(
  31431. ` ${prop.name}` + (prop.value ? `="${escapeHtml(prop.value.content)}"` : ``)
  31432. );
  31433. }
  31434. }
  31435. }
  31436. if (dynamicClassBinding && staticClassBinding) {
  31437. mergeCall(dynamicClassBinding, staticClassBinding);
  31438. removeStaticBinding(openTag, "class");
  31439. }
  31440. if (context.scopeId) {
  31441. openTag.push(` ${context.scopeId}`);
  31442. }
  31443. node.ssrCodegenNode = createTemplateLiteral(openTag);
  31444. };
  31445. };
  31446. function buildSSRProps(props, directives, context) {
  31447. let mergePropsArgs = [];
  31448. if (props) {
  31449. if (props.type === 14) {
  31450. mergePropsArgs = props.arguments;
  31451. } else {
  31452. mergePropsArgs.push(props);
  31453. }
  31454. }
  31455. if (directives.length) {
  31456. for (const dir of directives) {
  31457. mergePropsArgs.push(
  31458. createCallExpression(context.helper(SSR_GET_DIRECTIVE_PROPS), [
  31459. `_ctx`,
  31460. ...buildDirectiveArgs(dir, context).elements
  31461. ])
  31462. );
  31463. }
  31464. }
  31465. return mergePropsArgs.length > 1 ? createCallExpression(context.helper(MERGE_PROPS), mergePropsArgs) : mergePropsArgs[0];
  31466. }
  31467. function isTrueFalseValue(prop) {
  31468. if (prop.type === 7) {
  31469. return prop.name === "bind" && prop.arg && isStaticExp(prop.arg) && (prop.arg.content === "true-value" || prop.arg.content === "false-value");
  31470. } else {
  31471. return prop.name === "true-value" || prop.name === "false-value";
  31472. }
  31473. }
  31474. function isTextareaWithValue(node, prop) {
  31475. return !!(node.tag === "textarea" && prop.name === "bind" && isStaticArgOf(prop.arg, "value"));
  31476. }
  31477. function mergeCall(call, arg) {
  31478. const existing = call.arguments[0];
  31479. if (existing.type === 17) {
  31480. existing.elements.push(arg);
  31481. } else {
  31482. call.arguments[0] = createArrayExpression([existing, arg]);
  31483. }
  31484. }
  31485. function removeStaticBinding(tag, binding) {
  31486. const regExp = new RegExp(`^ ${binding}=".+"$`);
  31487. const i = tag.findIndex((e) => typeof e === "string" && regExp.test(e));
  31488. if (i > -1) {
  31489. tag.splice(i, 1);
  31490. }
  31491. }
  31492. function findVModel(node) {
  31493. return node.props.find(
  31494. (p) => p.type === 7 && p.name === "model" && p.exp
  31495. );
  31496. }
  31497. function hasContentOverrideDirective(node) {
  31498. return !!findDir(node, "text") || !!findDir(node, "html");
  31499. }
  31500. function ssrProcessElement(node, context) {
  31501. const isVoidTag = context.options.isVoidTag || NO;
  31502. const elementsToAdd = node.ssrCodegenNode.elements;
  31503. for (let j = 0; j < elementsToAdd.length; j++) {
  31504. context.pushStringPart(elementsToAdd[j]);
  31505. }
  31506. if (context.withSlotScopeId) {
  31507. context.pushStringPart(createSimpleExpression(`_scopeId`, false));
  31508. }
  31509. context.pushStringPart(`>`);
  31510. const rawChildren = rawChildrenMap.get(node);
  31511. if (rawChildren) {
  31512. context.pushStringPart(rawChildren);
  31513. } else if (node.children.length) {
  31514. processChildren(node, context);
  31515. }
  31516. if (!isVoidTag(node.tag)) {
  31517. context.pushStringPart(`</${node.tag}>`);
  31518. }
  31519. }
  31520. const wipMap$2 = /* @__PURE__ */ new WeakMap();
  31521. function ssrTransformTransitionGroup(node, context) {
  31522. return () => {
  31523. const tag = findProp(node, "tag");
  31524. if (tag) {
  31525. const otherProps = node.props.filter((p) => p !== tag);
  31526. const { props, directives } = buildProps(
  31527. node,
  31528. context,
  31529. otherProps,
  31530. true,
  31531. false,
  31532. true
  31533. );
  31534. let propsExp = null;
  31535. if (props || directives.length) {
  31536. propsExp = createCallExpression(context.helper(SSR_RENDER_ATTRS), [
  31537. buildSSRProps(props, directives, context)
  31538. ]);
  31539. }
  31540. wipMap$2.set(node, {
  31541. tag,
  31542. propsExp,
  31543. scopeId: context.scopeId || null
  31544. });
  31545. }
  31546. };
  31547. }
  31548. function ssrProcessTransitionGroup(node, context) {
  31549. const entry = wipMap$2.get(node);
  31550. if (entry) {
  31551. const { tag, propsExp, scopeId } = entry;
  31552. if (tag.type === 7) {
  31553. context.pushStringPart(`<`);
  31554. context.pushStringPart(tag.exp);
  31555. if (propsExp) {
  31556. context.pushStringPart(propsExp);
  31557. }
  31558. if (scopeId) {
  31559. context.pushStringPart(` ${scopeId}`);
  31560. }
  31561. context.pushStringPart(`>`);
  31562. processChildren(
  31563. node,
  31564. context,
  31565. false,
  31566. /**
  31567. * TransitionGroup has the special runtime behavior of flattening and
  31568. * concatenating all children into a single fragment (in order for them to
  31569. * be patched using the same key map) so we need to account for that here
  31570. * by disabling nested fragment wrappers from being generated.
  31571. */
  31572. true,
  31573. /**
  31574. * TransitionGroup filters out comment children at runtime and thus
  31575. * doesn't expect comments to be present during hydration. We need to
  31576. * account for that by disabling the empty comment that is otherwise
  31577. * rendered for a falsy v-if that has no v-else specified. (#6715)
  31578. */
  31579. true
  31580. );
  31581. context.pushStringPart(`</`);
  31582. context.pushStringPart(tag.exp);
  31583. context.pushStringPart(`>`);
  31584. } else {
  31585. context.pushStringPart(`<${tag.value.content}`);
  31586. if (propsExp) {
  31587. context.pushStringPart(propsExp);
  31588. }
  31589. if (scopeId) {
  31590. context.pushStringPart(` ${scopeId}`);
  31591. }
  31592. context.pushStringPart(`>`);
  31593. processChildren(node, context, false, true, true);
  31594. context.pushStringPart(`</${tag.value.content}>`);
  31595. }
  31596. } else {
  31597. processChildren(node, context, true, true, true);
  31598. }
  31599. }
  31600. const wipMap$1 = /* @__PURE__ */ new WeakMap();
  31601. function ssrTransformTransition(node, context) {
  31602. return () => {
  31603. const appear = findProp(node, "appear", false, true);
  31604. wipMap$1.set(node, !!appear);
  31605. };
  31606. }
  31607. function ssrProcessTransition(node, context) {
  31608. node.children = node.children.filter((c) => c.type !== 3);
  31609. const appear = wipMap$1.get(node);
  31610. if (appear) {
  31611. context.pushStringPart(`<template>`);
  31612. processChildren(node, context, false, true);
  31613. context.pushStringPart(`</template>`);
  31614. } else {
  31615. processChildren(node, context, false, true);
  31616. }
  31617. }
  31618. var __defProp$8 = Object.defineProperty;
  31619. var __defProps$7 = Object.defineProperties;
  31620. var __getOwnPropDescs$7 = Object.getOwnPropertyDescriptors;
  31621. var __getOwnPropSymbols$8 = Object.getOwnPropertySymbols;
  31622. var __hasOwnProp$8 = Object.prototype.hasOwnProperty;
  31623. var __propIsEnum$8 = Object.prototype.propertyIsEnumerable;
  31624. var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  31625. var __spreadValues$8 = (a, b) => {
  31626. for (var prop in b || (b = {}))
  31627. if (__hasOwnProp$8.call(b, prop))
  31628. __defNormalProp$8(a, prop, b[prop]);
  31629. if (__getOwnPropSymbols$8)
  31630. for (var prop of __getOwnPropSymbols$8(b)) {
  31631. if (__propIsEnum$8.call(b, prop))
  31632. __defNormalProp$8(a, prop, b[prop]);
  31633. }
  31634. return a;
  31635. };
  31636. var __spreadProps$7 = (a, b) => __defProps$7(a, __getOwnPropDescs$7(b));
  31637. const wipMap = /* @__PURE__ */ new WeakMap();
  31638. const WIP_SLOT = /* @__PURE__ */ Symbol();
  31639. const componentTypeMap = /* @__PURE__ */ new WeakMap();
  31640. const ssrTransformComponent = (node, context) => {
  31641. if (node.type !== 1 || node.tagType !== 1) {
  31642. return;
  31643. }
  31644. const component = resolveComponentType(
  31645. node,
  31646. context,
  31647. true
  31648. /* ssr */
  31649. );
  31650. const isDynamicComponent = isObject$2(component) && component.callee === RESOLVE_DYNAMIC_COMPONENT;
  31651. componentTypeMap.set(node, component);
  31652. if (isSymbol$1(component)) {
  31653. if (component === SUSPENSE) {
  31654. return ssrTransformSuspense(node, context);
  31655. } else if (component === TRANSITION_GROUP) {
  31656. return ssrTransformTransitionGroup(node, context);
  31657. } else if (component === TRANSITION) {
  31658. return ssrTransformTransition(node);
  31659. }
  31660. return;
  31661. }
  31662. const vnodeBranches = [];
  31663. const clonedNode = clone(node);
  31664. return function ssrPostTransformComponent() {
  31665. if (clonedNode.children.length) {
  31666. buildSlots(clonedNode, context, (props, vFor, children) => {
  31667. vnodeBranches.push(
  31668. createVNodeSlotBranch(props, vFor, children, context)
  31669. );
  31670. return createFunctionExpression(void 0);
  31671. });
  31672. }
  31673. let propsExp = `null`;
  31674. if (node.props.length) {
  31675. const { props, directives } = buildProps(
  31676. node,
  31677. context,
  31678. void 0,
  31679. true,
  31680. isDynamicComponent
  31681. );
  31682. if (props || directives.length) {
  31683. propsExp = buildSSRProps(props, directives, context);
  31684. }
  31685. }
  31686. const wipEntries = [];
  31687. wipMap.set(node, wipEntries);
  31688. const buildSSRSlotFn = (props, _vForExp, children, loc) => {
  31689. const param0 = props && stringifyExpression(props) || `_`;
  31690. const fn = createFunctionExpression(
  31691. [param0, `_push`, `_parent`, `_scopeId`],
  31692. void 0,
  31693. // no return, assign body later
  31694. true,
  31695. // newline
  31696. true,
  31697. // isSlot
  31698. loc
  31699. );
  31700. wipEntries.push({
  31701. type: WIP_SLOT,
  31702. fn,
  31703. children,
  31704. // also collect the corresponding vnode branch built earlier
  31705. vnodeBranch: vnodeBranches[wipEntries.length]
  31706. });
  31707. return fn;
  31708. };
  31709. const slots = node.children.length ? buildSlots(node, context, buildSSRSlotFn).slots : `null`;
  31710. if (typeof component !== "string") {
  31711. node.ssrCodegenNode = createCallExpression(
  31712. context.helper(SSR_RENDER_VNODE),
  31713. [
  31714. `_push`,
  31715. createCallExpression(context.helper(CREATE_VNODE), [
  31716. component,
  31717. propsExp,
  31718. slots
  31719. ]),
  31720. `_parent`
  31721. ]
  31722. );
  31723. } else {
  31724. node.ssrCodegenNode = createCallExpression(
  31725. context.helper(SSR_RENDER_COMPONENT),
  31726. [component, propsExp, slots, `_parent`]
  31727. );
  31728. }
  31729. };
  31730. };
  31731. function ssrProcessComponent(node, context, parent) {
  31732. const component = componentTypeMap.get(node);
  31733. if (!node.ssrCodegenNode) {
  31734. if (component === TELEPORT) {
  31735. return ssrProcessTeleport(node, context);
  31736. } else if (component === SUSPENSE) {
  31737. return ssrProcessSuspense(node, context);
  31738. } else if (component === TRANSITION_GROUP) {
  31739. return ssrProcessTransitionGroup(node, context);
  31740. } else {
  31741. if (parent.type === WIP_SLOT) {
  31742. context.pushStringPart(``);
  31743. }
  31744. if (component === TRANSITION) {
  31745. return ssrProcessTransition(node, context);
  31746. }
  31747. processChildren(node, context);
  31748. }
  31749. } else {
  31750. const wipEntries = wipMap.get(node) || [];
  31751. for (let i = 0; i < wipEntries.length; i++) {
  31752. const { fn, vnodeBranch } = wipEntries[i];
  31753. fn.body = createIfStatement(
  31754. createSimpleExpression(`_push`, false),
  31755. processChildrenAsStatement(
  31756. wipEntries[i],
  31757. context,
  31758. false,
  31759. true
  31760. ),
  31761. vnodeBranch
  31762. );
  31763. }
  31764. if (context.withSlotScopeId) {
  31765. node.ssrCodegenNode.arguments.push(`_scopeId`);
  31766. }
  31767. if (typeof component === "string") {
  31768. context.pushStatement(
  31769. createCallExpression(`_push`, [node.ssrCodegenNode])
  31770. );
  31771. } else {
  31772. context.pushStatement(node.ssrCodegenNode);
  31773. }
  31774. }
  31775. }
  31776. const rawOptionsMap = /* @__PURE__ */ new WeakMap();
  31777. const [baseNodeTransforms, baseDirectiveTransforms] = getBaseTransformPreset(true);
  31778. const vnodeNodeTransforms = [...baseNodeTransforms, ...DOMNodeTransforms];
  31779. const vnodeDirectiveTransforms = __spreadValues$8(__spreadValues$8({}, baseDirectiveTransforms), DOMDirectiveTransforms);
  31780. function createVNodeSlotBranch(slotProps, vFor, children, parentContext) {
  31781. const rawOptions = rawOptionsMap.get(parentContext.root);
  31782. const subOptions = __spreadProps$7(__spreadValues$8({}, rawOptions), {
  31783. // overwrite with vnode-based transforms
  31784. nodeTransforms: [
  31785. ...vnodeNodeTransforms,
  31786. ...rawOptions.nodeTransforms || []
  31787. ],
  31788. directiveTransforms: __spreadValues$8(__spreadValues$8({}, vnodeDirectiveTransforms), rawOptions.directiveTransforms || {})
  31789. });
  31790. const wrapperProps = [];
  31791. if (slotProps) {
  31792. wrapperProps.push({
  31793. type: 7,
  31794. name: "slot",
  31795. exp: slotProps,
  31796. arg: void 0,
  31797. modifiers: [],
  31798. loc: locStub
  31799. });
  31800. }
  31801. if (vFor) {
  31802. wrapperProps.push(extend({}, vFor));
  31803. }
  31804. const wrapperNode = {
  31805. type: 1,
  31806. ns: 0,
  31807. tag: "template",
  31808. tagType: 3,
  31809. props: wrapperProps,
  31810. children,
  31811. loc: locStub,
  31812. codegenNode: void 0
  31813. };
  31814. subTransform(wrapperNode, subOptions, parentContext);
  31815. return createReturnStatement(children);
  31816. }
  31817. function subTransform(node, options, parentContext) {
  31818. const childRoot = createRoot([node]);
  31819. const childContext = createTransformContext(childRoot, options);
  31820. childContext.ssr = false;
  31821. childContext.scopes = __spreadValues$8({}, parentContext.scopes);
  31822. childContext.identifiers = __spreadValues$8({}, parentContext.identifiers);
  31823. childContext.imports = parentContext.imports;
  31824. traverseNode(childRoot, childContext);
  31825. ["helpers", "components", "directives"].forEach((key) => {
  31826. childContext[key].forEach((value, helperKey) => {
  31827. if (key === "helpers") {
  31828. const parentCount = parentContext.helpers.get(helperKey);
  31829. if (parentCount === void 0) {
  31830. parentContext.helpers.set(helperKey, value);
  31831. } else {
  31832. parentContext.helpers.set(helperKey, value + parentCount);
  31833. }
  31834. } else {
  31835. parentContext[key].add(value);
  31836. }
  31837. });
  31838. });
  31839. }
  31840. function clone(v) {
  31841. if (isArray$3(v)) {
  31842. return v.map(clone);
  31843. } else if (isPlainObject(v)) {
  31844. const res = {};
  31845. for (const key in v) {
  31846. res[key] = clone(v[key]);
  31847. }
  31848. return res;
  31849. } else {
  31850. return v;
  31851. }
  31852. }
  31853. function ssrCodegenTransform(ast, options) {
  31854. const context = createSSRTransformContext(ast, options);
  31855. if (options.ssrCssVars) {
  31856. const cssContext = createTransformContext(createRoot([]), options);
  31857. const varsExp = processExpression(
  31858. createSimpleExpression(options.ssrCssVars, false),
  31859. cssContext
  31860. );
  31861. context.body.push(
  31862. createCompoundExpression([`const _cssVars = { style: `, varsExp, `}`])
  31863. );
  31864. Array.from(cssContext.helpers.keys()).forEach((helper) => {
  31865. ast.helpers.add(helper);
  31866. });
  31867. }
  31868. const isFragment = ast.children.length > 1 && ast.children.some((c) => !isText$1(c));
  31869. processChildren(ast, context, isFragment);
  31870. ast.codegenNode = createBlockStatement(context.body);
  31871. ast.ssrHelpers = Array.from(
  31872. /* @__PURE__ */ new Set([
  31873. ...Array.from(ast.helpers).filter((h) => h in ssrHelpers),
  31874. ...context.helpers
  31875. ])
  31876. );
  31877. ast.helpers = new Set(Array.from(ast.helpers).filter((h) => !(h in ssrHelpers)));
  31878. }
  31879. function createSSRTransformContext(root, options, helpers = /* @__PURE__ */ new Set(), withSlotScopeId = false) {
  31880. const body = [];
  31881. let currentString = null;
  31882. return {
  31883. root,
  31884. options,
  31885. body,
  31886. helpers,
  31887. withSlotScopeId,
  31888. onError: options.onError || ((e) => {
  31889. throw e;
  31890. }),
  31891. helper(name) {
  31892. helpers.add(name);
  31893. return name;
  31894. },
  31895. pushStringPart(part) {
  31896. if (!currentString) {
  31897. const currentCall = createCallExpression(`_push`);
  31898. body.push(currentCall);
  31899. currentString = createTemplateLiteral([]);
  31900. currentCall.arguments.push(currentString);
  31901. }
  31902. const bufferedElements = currentString.elements;
  31903. const lastItem = bufferedElements[bufferedElements.length - 1];
  31904. if (isString$1(part) && isString$1(lastItem)) {
  31905. bufferedElements[bufferedElements.length - 1] += part;
  31906. } else {
  31907. bufferedElements.push(part);
  31908. }
  31909. },
  31910. pushStatement(statement) {
  31911. currentString = null;
  31912. body.push(statement);
  31913. }
  31914. };
  31915. }
  31916. function createChildContext(parent, withSlotScopeId = parent.withSlotScopeId) {
  31917. return createSSRTransformContext(
  31918. parent.root,
  31919. parent.options,
  31920. parent.helpers,
  31921. withSlotScopeId
  31922. );
  31923. }
  31924. function processChildren(parent, context, asFragment = false, disableNestedFragments = false, disableComment = false) {
  31925. if (asFragment) {
  31926. context.pushStringPart(`<!--[-->`);
  31927. }
  31928. const { children } = parent;
  31929. for (let i = 0; i < children.length; i++) {
  31930. const child = children[i];
  31931. switch (child.type) {
  31932. case 1:
  31933. switch (child.tagType) {
  31934. case 0:
  31935. ssrProcessElement(child, context);
  31936. break;
  31937. case 1:
  31938. ssrProcessComponent(child, context, parent);
  31939. break;
  31940. case 2:
  31941. ssrProcessSlotOutlet(child, context);
  31942. break;
  31943. case 3:
  31944. break;
  31945. default:
  31946. context.onError(
  31947. createSSRCompilerError(
  31948. 67,
  31949. child.loc
  31950. )
  31951. );
  31952. const exhaustiveCheck2 = child;
  31953. return exhaustiveCheck2;
  31954. }
  31955. break;
  31956. case 2:
  31957. context.pushStringPart(escapeHtml(child.content));
  31958. break;
  31959. case 3:
  31960. if (!disableComment) {
  31961. context.pushStringPart(`<!--${child.content}-->`);
  31962. }
  31963. break;
  31964. case 5:
  31965. context.pushStringPart(
  31966. createCallExpression(context.helper(SSR_INTERPOLATE), [
  31967. child.content
  31968. ])
  31969. );
  31970. break;
  31971. case 9:
  31972. ssrProcessIf(child, context, disableNestedFragments, disableComment);
  31973. break;
  31974. case 11:
  31975. ssrProcessFor(child, context, disableNestedFragments);
  31976. break;
  31977. case 10:
  31978. break;
  31979. case 12:
  31980. case 8:
  31981. break;
  31982. default:
  31983. context.onError(
  31984. createSSRCompilerError(
  31985. 67,
  31986. child.loc
  31987. )
  31988. );
  31989. const exhaustiveCheck = child;
  31990. return exhaustiveCheck;
  31991. }
  31992. }
  31993. if (asFragment) {
  31994. context.pushStringPart(`<!--]-->`);
  31995. }
  31996. }
  31997. function processChildrenAsStatement(parent, parentContext, asFragment = false, withSlotScopeId = parentContext.withSlotScopeId) {
  31998. const childContext = createChildContext(parentContext, withSlotScopeId);
  31999. processChildren(parent, childContext, asFragment);
  32000. return createBlockStatement(childContext.body);
  32001. }
  32002. const ssrTransformModel = (dir, node, context) => {
  32003. const model = dir.exp;
  32004. function checkDuplicatedValue() {
  32005. const value = findProp(node, "value");
  32006. if (value) {
  32007. context.onError(
  32008. createDOMCompilerError(
  32009. 61,
  32010. value.loc
  32011. )
  32012. );
  32013. }
  32014. }
  32015. const processSelectChildren = (children) => {
  32016. children.forEach((child) => {
  32017. if (child.type === 1) {
  32018. processOption(child);
  32019. } else if (child.type === 11) {
  32020. processSelectChildren(child.children);
  32021. } else if (child.type === 9) {
  32022. child.branches.forEach((b) => processSelectChildren(b.children));
  32023. }
  32024. });
  32025. };
  32026. function processOption(plainNode) {
  32027. if (plainNode.tag === "option") {
  32028. if (plainNode.props.findIndex((p) => p.name === "selected") === -1) {
  32029. const value = findValueBinding(plainNode);
  32030. plainNode.ssrCodegenNode.elements.push(
  32031. createConditionalExpression(
  32032. createCallExpression(context.helper(SSR_INCLUDE_BOOLEAN_ATTR), [
  32033. createConditionalExpression(
  32034. createCallExpression(`Array.isArray`, [model]),
  32035. createCallExpression(context.helper(SSR_LOOSE_CONTAIN), [
  32036. model,
  32037. value
  32038. ]),
  32039. createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
  32040. model,
  32041. value
  32042. ])
  32043. )
  32044. ]),
  32045. createSimpleExpression(" selected", true),
  32046. createSimpleExpression("", true),
  32047. false
  32048. )
  32049. );
  32050. }
  32051. } else if (plainNode.tag === "optgroup") {
  32052. processSelectChildren(plainNode.children);
  32053. }
  32054. }
  32055. if (node.tagType === 0) {
  32056. const res = { props: [] };
  32057. if (node.tag === "input") {
  32058. const defaultProps = [
  32059. // default value binding for text type inputs
  32060. createObjectProperty(`value`, model)
  32061. ];
  32062. const type = findProp(node, "type");
  32063. if (type) {
  32064. const value = findValueBinding(node);
  32065. if (type.type === 7) {
  32066. res.ssrTagParts = [
  32067. createCallExpression(context.helper(SSR_RENDER_DYNAMIC_MODEL), [
  32068. type.exp,
  32069. model,
  32070. value
  32071. ])
  32072. ];
  32073. } else if (type.value) {
  32074. switch (type.value.content) {
  32075. case "radio":
  32076. res.props = [
  32077. createObjectProperty(
  32078. `checked`,
  32079. createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
  32080. model,
  32081. value
  32082. ])
  32083. )
  32084. ];
  32085. break;
  32086. case "checkbox":
  32087. const trueValueBinding = findProp(node, "true-value");
  32088. if (trueValueBinding) {
  32089. const trueValue = trueValueBinding.type === 6 ? JSON.stringify(trueValueBinding.value.content) : trueValueBinding.exp;
  32090. res.props = [
  32091. createObjectProperty(
  32092. `checked`,
  32093. createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
  32094. model,
  32095. trueValue
  32096. ])
  32097. )
  32098. ];
  32099. } else {
  32100. res.props = [
  32101. createObjectProperty(
  32102. `checked`,
  32103. createConditionalExpression(
  32104. createCallExpression(`Array.isArray`, [model]),
  32105. createCallExpression(context.helper(SSR_LOOSE_CONTAIN), [
  32106. model,
  32107. value
  32108. ]),
  32109. model
  32110. )
  32111. )
  32112. ];
  32113. }
  32114. break;
  32115. case "file":
  32116. context.onError(
  32117. createDOMCompilerError(
  32118. 60,
  32119. dir.loc
  32120. )
  32121. );
  32122. break;
  32123. default:
  32124. checkDuplicatedValue();
  32125. res.props = defaultProps;
  32126. break;
  32127. }
  32128. }
  32129. } else if (hasDynamicKeyVBind(node)) ; else {
  32130. checkDuplicatedValue();
  32131. res.props = defaultProps;
  32132. }
  32133. } else if (node.tag === "textarea") {
  32134. checkDuplicatedValue();
  32135. node.children = [createInterpolation(model, model.loc)];
  32136. } else if (node.tag === "select") {
  32137. processSelectChildren(node.children);
  32138. } else {
  32139. context.onError(
  32140. createDOMCompilerError(
  32141. 58,
  32142. dir.loc
  32143. )
  32144. );
  32145. }
  32146. return res;
  32147. } else {
  32148. return transformModel$1(dir, node, context);
  32149. }
  32150. };
  32151. function findValueBinding(node) {
  32152. const valueBinding = findProp(node, "value");
  32153. return valueBinding ? valueBinding.type === 7 ? valueBinding.exp : createSimpleExpression(valueBinding.value.content, true) : createSimpleExpression(`null`, false);
  32154. }
  32155. const ssrTransformShow = (dir, node, context) => {
  32156. if (!dir.exp) {
  32157. context.onError(
  32158. createDOMCompilerError(62)
  32159. );
  32160. }
  32161. return {
  32162. props: [
  32163. createObjectProperty(
  32164. `style`,
  32165. createConditionalExpression(
  32166. dir.exp,
  32167. createSimpleExpression(`null`, false),
  32168. createObjectExpression([
  32169. createObjectProperty(
  32170. `display`,
  32171. createSimpleExpression(`none`, true)
  32172. )
  32173. ]),
  32174. false
  32175. )
  32176. )
  32177. ]
  32178. };
  32179. };
  32180. const filterChild = (node) => node.children.filter((n) => !isCommentOrWhitespace(n));
  32181. const hasSingleChild = (node) => filterChild(node).length === 1;
  32182. const ssrInjectFallthroughAttrs = (node, context) => {
  32183. if (node.type === 0) {
  32184. context.identifiers._attrs = 1;
  32185. }
  32186. if (node.type === 1 && node.tagType === 1 && (node.tag === "transition" || node.tag === "Transition" || node.tag === "KeepAlive" || node.tag === "keep-alive")) {
  32187. const rootChildren = filterChild(context.root);
  32188. if (rootChildren.length === 1 && rootChildren[0] === node) {
  32189. if (hasSingleChild(node)) {
  32190. injectFallthroughAttrs(node.children[0]);
  32191. }
  32192. return;
  32193. }
  32194. }
  32195. const parent = context.parent;
  32196. if (!parent || parent.type !== 0) {
  32197. return;
  32198. }
  32199. if (node.type === 10 && hasSingleChild(node)) {
  32200. let hasEncounteredIf = false;
  32201. for (const c of filterChild(parent)) {
  32202. if (c.type === 9 || c.type === 1 && findDir(c, "if")) {
  32203. if (hasEncounteredIf) return;
  32204. hasEncounteredIf = true;
  32205. } else if (
  32206. // node before v-if
  32207. !hasEncounteredIf || // non else nodes
  32208. !(c.type === 1 && findDir(c, /else/, true))
  32209. ) {
  32210. return;
  32211. }
  32212. }
  32213. injectFallthroughAttrs(node.children[0]);
  32214. } else if (hasSingleChild(parent)) {
  32215. injectFallthroughAttrs(node);
  32216. }
  32217. };
  32218. function injectFallthroughAttrs(node) {
  32219. if (node.type === 1 && (node.tagType === 0 || node.tagType === 1) && !findDir(node, "for")) {
  32220. node.props.push({
  32221. type: 7,
  32222. name: "bind",
  32223. arg: void 0,
  32224. exp: createSimpleExpression(`_attrs`, false),
  32225. modifiers: [],
  32226. loc: locStub
  32227. });
  32228. }
  32229. }
  32230. const ssrInjectCssVars = (node, context) => {
  32231. if (!context.ssrCssVars) {
  32232. return;
  32233. }
  32234. if (node.type === 0) {
  32235. context.identifiers._cssVars = 1;
  32236. }
  32237. const parent = context.parent;
  32238. if (!parent || parent.type !== 0) {
  32239. return;
  32240. }
  32241. if (node.type === 10) {
  32242. for (const child of node.children) {
  32243. injectCssVars(child);
  32244. }
  32245. } else {
  32246. injectCssVars(node);
  32247. }
  32248. };
  32249. function injectCssVars(node) {
  32250. if (node.type === 1 && (node.tagType === 0 || node.tagType === 1) && !findDir(node, "for")) {
  32251. if (node.tag === "suspense" || node.tag === "Suspense") {
  32252. for (const child of node.children) {
  32253. if (child.type === 1 && child.tagType === 3) {
  32254. child.children.forEach(injectCssVars);
  32255. } else {
  32256. injectCssVars(child);
  32257. }
  32258. }
  32259. } else {
  32260. node.props.push({
  32261. type: 7,
  32262. name: "bind",
  32263. arg: void 0,
  32264. exp: createSimpleExpression(`_cssVars`, false),
  32265. modifiers: [],
  32266. loc: locStub
  32267. });
  32268. }
  32269. }
  32270. }
  32271. var __defProp$7 = Object.defineProperty;
  32272. var __defProps$6 = Object.defineProperties;
  32273. var __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors;
  32274. var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
  32275. var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
  32276. var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
  32277. var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  32278. var __spreadValues$7 = (a, b) => {
  32279. for (var prop in b || (b = {}))
  32280. if (__hasOwnProp$7.call(b, prop))
  32281. __defNormalProp$7(a, prop, b[prop]);
  32282. if (__getOwnPropSymbols$7)
  32283. for (var prop of __getOwnPropSymbols$7(b)) {
  32284. if (__propIsEnum$7.call(b, prop))
  32285. __defNormalProp$7(a, prop, b[prop]);
  32286. }
  32287. return a;
  32288. };
  32289. var __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b));
  32290. function compile(source, options = {}) {
  32291. options = __spreadProps$6(__spreadValues$7(__spreadValues$7({}, options), parserOptions), {
  32292. ssr: true,
  32293. inSSR: true,
  32294. scopeId: options.mode === "function" ? null : options.scopeId,
  32295. // always prefix since compiler-ssr doesn't have size concern
  32296. prefixIdentifiers: true,
  32297. // disable optimizations that are unnecessary for ssr
  32298. cacheHandlers: false,
  32299. hoistStatic: false
  32300. });
  32301. const ast = typeof source === "string" ? baseParse(source, options) : source;
  32302. rawOptionsMap.set(ast, options);
  32303. transform(ast, __spreadProps$6(__spreadValues$7({}, options), {
  32304. hoistStatic: false,
  32305. nodeTransforms: [
  32306. transformVBindShorthand,
  32307. ssrTransformIf,
  32308. ssrTransformFor,
  32309. trackVForSlotScopes,
  32310. transformExpression,
  32311. ssrTransformSlotOutlet,
  32312. ssrInjectFallthroughAttrs,
  32313. ssrInjectCssVars,
  32314. ssrTransformElement,
  32315. ssrTransformComponent,
  32316. trackSlotScopes,
  32317. transformStyle,
  32318. ...options.nodeTransforms || []
  32319. // user transforms
  32320. ],
  32321. directiveTransforms: __spreadValues$7({
  32322. // reusing core v-bind
  32323. bind: transformBind,
  32324. on: transformOn$1,
  32325. // model and show have dedicated SSR handling
  32326. model: ssrTransformModel,
  32327. show: ssrTransformShow,
  32328. // the following are ignored during SSR
  32329. // on: noopDirectiveTransform,
  32330. cloak: noopDirectiveTransform,
  32331. once: noopDirectiveTransform,
  32332. memo: noopDirectiveTransform
  32333. }, options.directiveTransforms || {})
  32334. }));
  32335. ssrCodegenTransform(ast, options);
  32336. return generate(ast, options);
  32337. }
  32338. var CompilerSSR = /*#__PURE__*/Object.freeze({
  32339. __proto__: null,
  32340. compile: compile
  32341. });
  32342. var _polyfillNode_fs = {};
  32343. var _polyfillNode_fs$1 = /*#__PURE__*/Object.freeze({
  32344. __proto__: null,
  32345. default: _polyfillNode_fs
  32346. });
  32347. var require$$0$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_fs$1);
  32348. var require$$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_path);
  32349. var require$$0 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_util$1);
  32350. const hasWarned = {};
  32351. function warnOnce$1(msg) {
  32352. const isNodeProd = typeof process !== "undefined" && process.env.NODE_ENV === "production";
  32353. if (!isNodeProd && true && !hasWarned[msg]) {
  32354. hasWarned[msg] = true;
  32355. warn(msg);
  32356. }
  32357. }
  32358. function warn(msg) {
  32359. console.warn(
  32360. `\x1B[1m\x1B[33m[@vue/compiler-sfc]\x1B[0m\x1B[33m ${msg}\x1B[0m
  32361. `
  32362. );
  32363. }
  32364. var __defProp$6 = Object.defineProperty;
  32365. var __defProps$5 = Object.defineProperties;
  32366. var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
  32367. var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
  32368. var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
  32369. var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
  32370. var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  32371. var __spreadValues$6 = (a, b) => {
  32372. for (var prop in b || (b = {}))
  32373. if (__hasOwnProp$6.call(b, prop))
  32374. __defNormalProp$6(a, prop, b[prop]);
  32375. if (__getOwnPropSymbols$6)
  32376. for (var prop of __getOwnPropSymbols$6(b)) {
  32377. if (__propIsEnum$6.call(b, prop))
  32378. __defNormalProp$6(a, prop, b[prop]);
  32379. }
  32380. return a;
  32381. };
  32382. var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
  32383. function preprocess$1({ source, filename, preprocessOptions }, preprocessor) {
  32384. let res = "";
  32385. let err = null;
  32386. preprocessor.render(
  32387. source,
  32388. __spreadValues$6({ filename }, preprocessOptions),
  32389. (_err, _res) => {
  32390. if (_err) err = _err;
  32391. res = _res;
  32392. }
  32393. );
  32394. if (err) throw err;
  32395. return res;
  32396. }
  32397. function compileTemplate(options) {
  32398. const { preprocessLang, preprocessCustomRequire } = options;
  32399. if (preprocessLang && !preprocessCustomRequire) {
  32400. throw new Error(
  32401. `[@vue/compiler-sfc] Template preprocessing in the browser build must provide the \`preprocessCustomRequire\` option to return the in-browser version of the preprocessor in the shape of { render(): string }.`
  32402. );
  32403. }
  32404. const preprocessor = preprocessLang ? preprocessCustomRequire ? preprocessCustomRequire(preprocessLang) : void 0 : false;
  32405. if (preprocessor) {
  32406. try {
  32407. return doCompileTemplate(__spreadProps$5(__spreadValues$6({}, options), {
  32408. source: preprocess$1(options, preprocessor),
  32409. ast: void 0
  32410. // invalidate AST if template goes through preprocessor
  32411. }));
  32412. } catch (e) {
  32413. return {
  32414. code: `export default function render() {}`,
  32415. source: options.source,
  32416. tips: [],
  32417. errors: [e]
  32418. };
  32419. }
  32420. } else if (preprocessLang) {
  32421. return {
  32422. code: `export default function render() {}`,
  32423. source: options.source,
  32424. tips: [
  32425. `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
  32426. ],
  32427. errors: [
  32428. `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
  32429. ]
  32430. };
  32431. } else {
  32432. return doCompileTemplate(options);
  32433. }
  32434. }
  32435. function doCompileTemplate({
  32436. filename,
  32437. id,
  32438. scoped,
  32439. slotted,
  32440. inMap,
  32441. source,
  32442. ast: inAST,
  32443. ssr = false,
  32444. ssrCssVars,
  32445. isProd = false,
  32446. compiler,
  32447. compilerOptions = {},
  32448. transformAssetUrls
  32449. }) {
  32450. const errors = [];
  32451. const warnings = [];
  32452. let nodeTransforms = [];
  32453. if (isObject$2(transformAssetUrls)) {
  32454. const assetOptions = normalizeOptions(transformAssetUrls);
  32455. nodeTransforms = [
  32456. createAssetUrlTransformWithOptions(assetOptions),
  32457. createSrcsetTransformWithOptions(assetOptions)
  32458. ];
  32459. } else if (transformAssetUrls !== false) {
  32460. nodeTransforms = [transformAssetUrl, transformSrcset];
  32461. }
  32462. if (ssr && !ssrCssVars) {
  32463. warnOnce$1(
  32464. `compileTemplate is called with \`ssr: true\` but no corresponding \`cssVars\` option.`
  32465. );
  32466. }
  32467. if (!id) {
  32468. warnOnce$1(`compileTemplate now requires the \`id\` option.`);
  32469. id = "";
  32470. }
  32471. const shortId = id.replace(/^data-v-/, "");
  32472. const longId = `data-v-${shortId}`;
  32473. const defaultCompiler = ssr ? CompilerSSR : CompilerDOM;
  32474. compiler = compiler || defaultCompiler;
  32475. if (compiler !== defaultCompiler) {
  32476. inAST = void 0;
  32477. }
  32478. if (inAST == null ? void 0 : inAST.transformed) {
  32479. const newAST = (ssr ? CompilerDOM : compiler).parse(inAST.source, __spreadProps$5(__spreadValues$6({
  32480. prefixIdentifiers: true
  32481. }, compilerOptions), {
  32482. parseMode: "sfc",
  32483. onError: (e) => errors.push(e)
  32484. }));
  32485. const template = newAST.children.find(
  32486. (node) => node.type === 1 && node.tag === "template"
  32487. );
  32488. inAST = createRoot(template.children, inAST.source);
  32489. }
  32490. let { code, ast, preamble, map } = compiler.compile(inAST || source, __spreadProps$5(__spreadValues$6({
  32491. mode: "module",
  32492. prefixIdentifiers: true,
  32493. hoistStatic: true,
  32494. cacheHandlers: true,
  32495. ssrCssVars: ssr && ssrCssVars && ssrCssVars.length ? genCssVarsFromList(ssrCssVars, shortId, isProd, true) : "",
  32496. scopeId: scoped ? longId : void 0,
  32497. slotted,
  32498. sourceMap: true
  32499. }, compilerOptions), {
  32500. hmr: !isProd,
  32501. nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []),
  32502. filename,
  32503. onError: (e) => errors.push(e),
  32504. onWarn: (w) => warnings.push(w)
  32505. }));
  32506. if (inMap && !inAST) {
  32507. if (map) {
  32508. map = mapLines(inMap, map);
  32509. }
  32510. if (errors.length) {
  32511. patchErrors(errors, source, inMap);
  32512. }
  32513. }
  32514. const tips = warnings.map((w) => {
  32515. let msg = w.message;
  32516. if (w.loc) {
  32517. msg += `
  32518. ${generateCodeFrame(
  32519. (inAST == null ? void 0 : inAST.source) || source,
  32520. w.loc.start.offset,
  32521. w.loc.end.offset
  32522. )}`;
  32523. }
  32524. return msg;
  32525. });
  32526. return { code, ast, preamble, source, errors, tips, map };
  32527. }
  32528. function mapLines(oldMap, newMap) {
  32529. if (!oldMap) return newMap;
  32530. if (!newMap) return oldMap;
  32531. const oldMapConsumer = new sourceMapExports.SourceMapConsumer(oldMap);
  32532. const newMapConsumer = new sourceMapExports.SourceMapConsumer(newMap);
  32533. const mergedMapGenerator = new sourceMapExports.SourceMapGenerator();
  32534. newMapConsumer.eachMapping((m) => {
  32535. if (m.originalLine == null) {
  32536. return;
  32537. }
  32538. const origPosInOldMap = oldMapConsumer.originalPositionFor({
  32539. line: m.originalLine,
  32540. column: m.originalColumn
  32541. });
  32542. if (origPosInOldMap.source == null) {
  32543. return;
  32544. }
  32545. mergedMapGenerator.addMapping({
  32546. generated: {
  32547. line: m.generatedLine,
  32548. column: m.generatedColumn
  32549. },
  32550. original: {
  32551. line: origPosInOldMap.line,
  32552. // map line
  32553. // use current column, since the oldMap produced by @vue/compiler-sfc
  32554. // does not
  32555. column: m.originalColumn
  32556. },
  32557. source: origPosInOldMap.source,
  32558. name: origPosInOldMap.name
  32559. });
  32560. });
  32561. const generator = mergedMapGenerator;
  32562. oldMapConsumer.sources.forEach((sourceFile) => {
  32563. generator._sources.add(sourceFile);
  32564. const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
  32565. if (sourceContent != null) {
  32566. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  32567. }
  32568. });
  32569. generator._sourceRoot = oldMap.sourceRoot;
  32570. generator._file = oldMap.file;
  32571. return generator.toJSON();
  32572. }
  32573. function patchErrors(errors, source, inMap) {
  32574. const originalSource = inMap.sourcesContent[0];
  32575. const offset = originalSource.indexOf(source);
  32576. const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
  32577. errors.forEach((err) => {
  32578. if (err.loc) {
  32579. err.loc.start.line += lineOffset;
  32580. err.loc.start.offset += offset;
  32581. if (err.loc.end !== err.loc.start) {
  32582. err.loc.end.line += lineOffset;
  32583. err.loc.end.offset += offset;
  32584. }
  32585. }
  32586. });
  32587. }
  32588. var picocolors = {exports: {}};
  32589. var hasRequiredPicocolors;
  32590. function requirePicocolors () {
  32591. if (hasRequiredPicocolors) return picocolors.exports;
  32592. hasRequiredPicocolors = 1;
  32593. let p = browser$1 || {}, argv = p.argv || [], env = p.env || {};
  32594. let isColorSupported =
  32595. !(!!env.NO_COLOR || argv.includes("--no-color")) &&
  32596. (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI);
  32597. let formatter = (open, close, replace = open) =>
  32598. input => {
  32599. let string = "" + input, index = string.indexOf(close, open.length);
  32600. return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close
  32601. };
  32602. let replaceClose = (string, close, replace, index) => {
  32603. let result = "", cursor = 0;
  32604. do {
  32605. result += string.substring(cursor, index) + replace;
  32606. cursor = index + close.length;
  32607. index = string.indexOf(close, cursor);
  32608. } while (~index)
  32609. return result + string.substring(cursor)
  32610. };
  32611. let createColors = (enabled = isColorSupported) => {
  32612. let f = enabled ? formatter : () => String;
  32613. return {
  32614. isColorSupported: enabled,
  32615. reset: f("\x1b[0m", "\x1b[0m"),
  32616. bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
  32617. dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
  32618. italic: f("\x1b[3m", "\x1b[23m"),
  32619. underline: f("\x1b[4m", "\x1b[24m"),
  32620. inverse: f("\x1b[7m", "\x1b[27m"),
  32621. hidden: f("\x1b[8m", "\x1b[28m"),
  32622. strikethrough: f("\x1b[9m", "\x1b[29m"),
  32623. black: f("\x1b[30m", "\x1b[39m"),
  32624. red: f("\x1b[31m", "\x1b[39m"),
  32625. green: f("\x1b[32m", "\x1b[39m"),
  32626. yellow: f("\x1b[33m", "\x1b[39m"),
  32627. blue: f("\x1b[34m", "\x1b[39m"),
  32628. magenta: f("\x1b[35m", "\x1b[39m"),
  32629. cyan: f("\x1b[36m", "\x1b[39m"),
  32630. white: f("\x1b[37m", "\x1b[39m"),
  32631. gray: f("\x1b[90m", "\x1b[39m"),
  32632. bgBlack: f("\x1b[40m", "\x1b[49m"),
  32633. bgRed: f("\x1b[41m", "\x1b[49m"),
  32634. bgGreen: f("\x1b[42m", "\x1b[49m"),
  32635. bgYellow: f("\x1b[43m", "\x1b[49m"),
  32636. bgBlue: f("\x1b[44m", "\x1b[49m"),
  32637. bgMagenta: f("\x1b[45m", "\x1b[49m"),
  32638. bgCyan: f("\x1b[46m", "\x1b[49m"),
  32639. bgWhite: f("\x1b[47m", "\x1b[49m"),
  32640. blackBright: f("\x1b[90m", "\x1b[39m"),
  32641. redBright: f("\x1b[91m", "\x1b[39m"),
  32642. greenBright: f("\x1b[92m", "\x1b[39m"),
  32643. yellowBright: f("\x1b[93m", "\x1b[39m"),
  32644. blueBright: f("\x1b[94m", "\x1b[39m"),
  32645. magentaBright: f("\x1b[95m", "\x1b[39m"),
  32646. cyanBright: f("\x1b[96m", "\x1b[39m"),
  32647. whiteBright: f("\x1b[97m", "\x1b[39m"),
  32648. bgBlackBright: f("\x1b[100m", "\x1b[49m"),
  32649. bgRedBright: f("\x1b[101m", "\x1b[49m"),
  32650. bgGreenBright: f("\x1b[102m", "\x1b[49m"),
  32651. bgYellowBright: f("\x1b[103m", "\x1b[49m"),
  32652. bgBlueBright: f("\x1b[104m", "\x1b[49m"),
  32653. bgMagentaBright: f("\x1b[105m", "\x1b[49m"),
  32654. bgCyanBright: f("\x1b[106m", "\x1b[49m"),
  32655. bgWhiteBright: f("\x1b[107m", "\x1b[49m"),
  32656. }
  32657. };
  32658. picocolors.exports = createColors();
  32659. picocolors.exports.createColors = createColors;
  32660. return picocolors.exports;
  32661. }
  32662. var tokenize$1;
  32663. var hasRequiredTokenize$1;
  32664. function requireTokenize$1 () {
  32665. if (hasRequiredTokenize$1) return tokenize$1;
  32666. hasRequiredTokenize$1 = 1;
  32667. const SINGLE_QUOTE = "'".charCodeAt(0);
  32668. const DOUBLE_QUOTE = '"'.charCodeAt(0);
  32669. const BACKSLASH = '\\'.charCodeAt(0);
  32670. const SLASH = '/'.charCodeAt(0);
  32671. const NEWLINE = '\n'.charCodeAt(0);
  32672. const SPACE = ' '.charCodeAt(0);
  32673. const FEED = '\f'.charCodeAt(0);
  32674. const TAB = '\t'.charCodeAt(0);
  32675. const CR = '\r'.charCodeAt(0);
  32676. const OPEN_SQUARE = '['.charCodeAt(0);
  32677. const CLOSE_SQUARE = ']'.charCodeAt(0);
  32678. const OPEN_PARENTHESES = '('.charCodeAt(0);
  32679. const CLOSE_PARENTHESES = ')'.charCodeAt(0);
  32680. const OPEN_CURLY = '{'.charCodeAt(0);
  32681. const CLOSE_CURLY = '}'.charCodeAt(0);
  32682. const SEMICOLON = ';'.charCodeAt(0);
  32683. const ASTERISK = '*'.charCodeAt(0);
  32684. const COLON = ':'.charCodeAt(0);
  32685. const AT = '@'.charCodeAt(0);
  32686. const RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g;
  32687. const RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g;
  32688. const RE_BAD_BRACKET = /.[\r\n"'(/\\]/;
  32689. const RE_HEX_ESCAPE = /[\da-f]/i;
  32690. tokenize$1 = function tokenizer(input, options = {}) {
  32691. let css = input.css.valueOf();
  32692. let ignore = options.ignoreErrors;
  32693. let code, content, escape, next, quote;
  32694. let currentToken, escaped, escapePos, n, prev;
  32695. let length = css.length;
  32696. let pos = 0;
  32697. let buffer = [];
  32698. let returned = [];
  32699. let lastBadParen = -1;
  32700. function position() {
  32701. return pos
  32702. }
  32703. function unclosed(what) {
  32704. throw input.error('Unclosed ' + what, pos)
  32705. }
  32706. function endOfFile() {
  32707. return returned.length === 0 && pos >= length
  32708. }
  32709. function nextToken(opts) {
  32710. if (returned.length) return returned.pop()
  32711. if (pos >= length) return
  32712. let ignoreUnclosed = opts ? opts.ignoreUnclosed : false;
  32713. code = css.charCodeAt(pos);
  32714. switch (code) {
  32715. case NEWLINE:
  32716. case SPACE:
  32717. case TAB:
  32718. case CR:
  32719. case FEED: {
  32720. next = pos;
  32721. do {
  32722. next += 1;
  32723. code = css.charCodeAt(next);
  32724. } while (
  32725. code === SPACE ||
  32726. code === NEWLINE ||
  32727. code === TAB ||
  32728. code === CR ||
  32729. code === FEED
  32730. )
  32731. currentToken = ['space', css.slice(pos, next)];
  32732. pos = next - 1;
  32733. break
  32734. }
  32735. case OPEN_SQUARE:
  32736. case CLOSE_SQUARE:
  32737. case OPEN_CURLY:
  32738. case CLOSE_CURLY:
  32739. case COLON:
  32740. case SEMICOLON:
  32741. case CLOSE_PARENTHESES: {
  32742. let controlChar = String.fromCharCode(code);
  32743. currentToken = [controlChar, controlChar, pos];
  32744. break
  32745. }
  32746. case OPEN_PARENTHESES: {
  32747. prev = buffer.length ? buffer.pop()[1] : '';
  32748. n = css.charCodeAt(pos + 1);
  32749. if (
  32750. prev === 'url' &&
  32751. n !== SINGLE_QUOTE &&
  32752. n !== DOUBLE_QUOTE &&
  32753. n !== SPACE &&
  32754. n !== NEWLINE &&
  32755. n !== TAB &&
  32756. n !== FEED &&
  32757. n !== CR
  32758. ) {
  32759. next = pos;
  32760. do {
  32761. escaped = false;
  32762. next = css.indexOf(')', next + 1);
  32763. if (next === -1) {
  32764. if (ignore || ignoreUnclosed) {
  32765. next = pos;
  32766. break
  32767. } else {
  32768. unclosed('bracket');
  32769. }
  32770. }
  32771. escapePos = next;
  32772. while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
  32773. escapePos -= 1;
  32774. escaped = !escaped;
  32775. }
  32776. } while (escaped)
  32777. currentToken = ['brackets', css.slice(pos, next + 1), pos, next];
  32778. pos = next;
  32779. } else if (pos <= lastBadParen) {
  32780. currentToken = ['(', '(', pos];
  32781. } else {
  32782. next = css.indexOf(')', pos + 1);
  32783. content = css.slice(pos, next + 1);
  32784. if (next === -1 || RE_BAD_BRACKET.test(content)) {
  32785. lastBadParen = next === -1 ? length : next;
  32786. currentToken = ['(', '(', pos];
  32787. } else {
  32788. currentToken = ['brackets', content, pos, next];
  32789. pos = next;
  32790. }
  32791. }
  32792. break
  32793. }
  32794. case SINGLE_QUOTE:
  32795. case DOUBLE_QUOTE: {
  32796. quote = code === SINGLE_QUOTE ? "'" : '"';
  32797. next = pos;
  32798. do {
  32799. escaped = false;
  32800. next = css.indexOf(quote, next + 1);
  32801. if (next === -1) {
  32802. if (ignore || ignoreUnclosed) {
  32803. next = pos + 1;
  32804. break
  32805. } else {
  32806. unclosed('string');
  32807. }
  32808. }
  32809. escapePos = next;
  32810. while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
  32811. escapePos -= 1;
  32812. escaped = !escaped;
  32813. }
  32814. } while (escaped)
  32815. currentToken = ['string', css.slice(pos, next + 1), pos, next];
  32816. pos = next;
  32817. break
  32818. }
  32819. case AT: {
  32820. RE_AT_END.lastIndex = pos + 1;
  32821. RE_AT_END.test(css);
  32822. if (RE_AT_END.lastIndex === 0) {
  32823. next = css.length - 1;
  32824. } else {
  32825. next = RE_AT_END.lastIndex - 2;
  32826. }
  32827. currentToken = ['at-word', css.slice(pos, next + 1), pos, next];
  32828. pos = next;
  32829. break
  32830. }
  32831. case BACKSLASH: {
  32832. next = pos;
  32833. escape = true;
  32834. while (css.charCodeAt(next + 1) === BACKSLASH) {
  32835. next += 1;
  32836. escape = !escape;
  32837. }
  32838. code = css.charCodeAt(next + 1);
  32839. if (
  32840. escape &&
  32841. code !== SLASH &&
  32842. code !== SPACE &&
  32843. code !== NEWLINE &&
  32844. code !== TAB &&
  32845. code !== CR &&
  32846. code !== FEED
  32847. ) {
  32848. next += 1;
  32849. if (RE_HEX_ESCAPE.test(css.charAt(next))) {
  32850. while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) {
  32851. next += 1;
  32852. }
  32853. if (css.charCodeAt(next + 1) === SPACE) {
  32854. next += 1;
  32855. }
  32856. }
  32857. }
  32858. currentToken = ['word', css.slice(pos, next + 1), pos, next];
  32859. pos = next;
  32860. break
  32861. }
  32862. default: {
  32863. if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
  32864. next = css.indexOf('*/', pos + 2) + 1;
  32865. if (next === 0) {
  32866. if (ignore || ignoreUnclosed) {
  32867. next = css.length;
  32868. } else {
  32869. unclosed('comment');
  32870. }
  32871. }
  32872. currentToken = ['comment', css.slice(pos, next + 1), pos, next];
  32873. pos = next;
  32874. } else {
  32875. RE_WORD_END.lastIndex = pos + 1;
  32876. RE_WORD_END.test(css);
  32877. if (RE_WORD_END.lastIndex === 0) {
  32878. next = css.length - 1;
  32879. } else {
  32880. next = RE_WORD_END.lastIndex - 2;
  32881. }
  32882. currentToken = ['word', css.slice(pos, next + 1), pos, next];
  32883. buffer.push(currentToken);
  32884. pos = next;
  32885. }
  32886. break
  32887. }
  32888. }
  32889. pos++;
  32890. return currentToken
  32891. }
  32892. function back(token) {
  32893. returned.push(token);
  32894. }
  32895. return {
  32896. back,
  32897. endOfFile,
  32898. nextToken,
  32899. position
  32900. }
  32901. };
  32902. return tokenize$1;
  32903. }
  32904. var terminalHighlight_1;
  32905. var hasRequiredTerminalHighlight;
  32906. function requireTerminalHighlight () {
  32907. if (hasRequiredTerminalHighlight) return terminalHighlight_1;
  32908. hasRequiredTerminalHighlight = 1;
  32909. let pico = /*@__PURE__*/ requirePicocolors();
  32910. let tokenizer = /*@__PURE__*/ requireTokenize$1();
  32911. let Input;
  32912. function registerInput(dependant) {
  32913. Input = dependant;
  32914. }
  32915. const HIGHLIGHT_THEME = {
  32916. ';': pico.yellow,
  32917. ':': pico.yellow,
  32918. '(': pico.cyan,
  32919. ')': pico.cyan,
  32920. '[': pico.yellow,
  32921. ']': pico.yellow,
  32922. '{': pico.yellow,
  32923. '}': pico.yellow,
  32924. 'at-word': pico.cyan,
  32925. 'brackets': pico.cyan,
  32926. 'call': pico.cyan,
  32927. 'class': pico.yellow,
  32928. 'comment': pico.gray,
  32929. 'hash': pico.magenta,
  32930. 'string': pico.green
  32931. };
  32932. function getTokenType([type, value], processor) {
  32933. if (type === 'word') {
  32934. if (value[0] === '.') {
  32935. return 'class'
  32936. }
  32937. if (value[0] === '#') {
  32938. return 'hash'
  32939. }
  32940. }
  32941. if (!processor.endOfFile()) {
  32942. let next = processor.nextToken();
  32943. processor.back(next);
  32944. if (next[0] === 'brackets' || next[0] === '(') return 'call'
  32945. }
  32946. return type
  32947. }
  32948. function terminalHighlight(css) {
  32949. let processor = tokenizer(new Input(css), { ignoreErrors: true });
  32950. let result = '';
  32951. while (!processor.endOfFile()) {
  32952. let token = processor.nextToken();
  32953. let color = HIGHLIGHT_THEME[getTokenType(token, processor)];
  32954. if (color) {
  32955. result += token[1]
  32956. .split(/\r?\n/)
  32957. .map(i => color(i))
  32958. .join('\n');
  32959. } else {
  32960. result += token[1];
  32961. }
  32962. }
  32963. return result
  32964. }
  32965. terminalHighlight.registerInput = registerInput;
  32966. terminalHighlight_1 = terminalHighlight;
  32967. return terminalHighlight_1;
  32968. }
  32969. var cssSyntaxError;
  32970. var hasRequiredCssSyntaxError;
  32971. function requireCssSyntaxError () {
  32972. if (hasRequiredCssSyntaxError) return cssSyntaxError;
  32973. hasRequiredCssSyntaxError = 1;
  32974. let pico = /*@__PURE__*/ requirePicocolors();
  32975. let terminalHighlight = /*@__PURE__*/ requireTerminalHighlight();
  32976. class CssSyntaxError extends Error {
  32977. constructor(message, line, column, source, file, plugin) {
  32978. super(message);
  32979. this.name = 'CssSyntaxError';
  32980. this.reason = message;
  32981. if (file) {
  32982. this.file = file;
  32983. }
  32984. if (source) {
  32985. this.source = source;
  32986. }
  32987. if (plugin) {
  32988. this.plugin = plugin;
  32989. }
  32990. if (typeof line !== 'undefined' && typeof column !== 'undefined') {
  32991. if (typeof line === 'number') {
  32992. this.line = line;
  32993. this.column = column;
  32994. } else {
  32995. this.line = line.line;
  32996. this.column = line.column;
  32997. this.endLine = column.line;
  32998. this.endColumn = column.column;
  32999. }
  33000. }
  33001. this.setMessage();
  33002. if (Error.captureStackTrace) {
  33003. Error.captureStackTrace(this, CssSyntaxError);
  33004. }
  33005. }
  33006. setMessage() {
  33007. this.message = this.plugin ? this.plugin + ': ' : '';
  33008. this.message += this.file ? this.file : '<css input>';
  33009. if (typeof this.line !== 'undefined') {
  33010. this.message += ':' + this.line + ':' + this.column;
  33011. }
  33012. this.message += ': ' + this.reason;
  33013. }
  33014. showSourceCode(color) {
  33015. if (!this.source) return ''
  33016. let css = this.source;
  33017. if (color == null) color = pico.isColorSupported;
  33018. let aside = text => text;
  33019. let mark = text => text;
  33020. let highlight = text => text;
  33021. if (color) {
  33022. let { bold, gray, red } = pico.createColors(true);
  33023. mark = text => bold(red(text));
  33024. aside = text => gray(text);
  33025. if (terminalHighlight) {
  33026. highlight = text => terminalHighlight(text);
  33027. }
  33028. }
  33029. let lines = css.split(/\r?\n/);
  33030. let start = Math.max(this.line - 3, 0);
  33031. let end = Math.min(this.line + 2, lines.length);
  33032. let maxWidth = String(end).length;
  33033. return lines
  33034. .slice(start, end)
  33035. .map((line, index) => {
  33036. let number = start + 1 + index;
  33037. let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | ';
  33038. if (number === this.line) {
  33039. if (line.length > 160) {
  33040. let padding = 20;
  33041. let subLineStart = Math.max(0, this.column - padding);
  33042. let subLineEnd = Math.max(
  33043. this.column + padding,
  33044. this.endColumn + padding
  33045. );
  33046. let subLine = line.slice(subLineStart, subLineEnd);
  33047. let spacing =
  33048. aside(gutter.replace(/\d/g, ' ')) +
  33049. line
  33050. .slice(0, Math.min(this.column - 1, padding - 1))
  33051. .replace(/[^\t]/g, ' ');
  33052. return (
  33053. mark('>') +
  33054. aside(gutter) +
  33055. highlight(subLine) +
  33056. '\n ' +
  33057. spacing +
  33058. mark('^')
  33059. )
  33060. }
  33061. let spacing =
  33062. aside(gutter.replace(/\d/g, ' ')) +
  33063. line.slice(0, this.column - 1).replace(/[^\t]/g, ' ');
  33064. return (
  33065. mark('>') +
  33066. aside(gutter) +
  33067. highlight(line) +
  33068. '\n ' +
  33069. spacing +
  33070. mark('^')
  33071. )
  33072. }
  33073. return ' ' + aside(gutter) + highlight(line)
  33074. })
  33075. .join('\n')
  33076. }
  33077. toString() {
  33078. let code = this.showSourceCode();
  33079. if (code) {
  33080. code = '\n\n' + code + '\n';
  33081. }
  33082. return this.name + ': ' + this.message + code
  33083. }
  33084. }
  33085. cssSyntaxError = CssSyntaxError;
  33086. CssSyntaxError.default = CssSyntaxError;
  33087. return cssSyntaxError;
  33088. }
  33089. var stringifier;
  33090. var hasRequiredStringifier;
  33091. function requireStringifier () {
  33092. if (hasRequiredStringifier) return stringifier;
  33093. hasRequiredStringifier = 1;
  33094. // Escapes sequences that could break out of an HTML <style> context.
  33095. // Uses CSS unicode escaping (\3c = '<') which is valid CSS and parsed
  33096. // correctly by all compliant CSS consumers.
  33097. const STYLE_TAG = /(<)(\/?style\b)/gi;
  33098. const COMMENT_OPEN = /(<)(!--)/g;
  33099. function escapeHTMLInCSS(str) {
  33100. if (typeof str !== 'string') return str
  33101. if (!str.includes('<')) return str
  33102. return str.replace(STYLE_TAG, '\\3c $2').replace(COMMENT_OPEN, '\\3c $2')
  33103. }
  33104. const DEFAULT_RAW = {
  33105. after: '\n',
  33106. beforeClose: '\n',
  33107. beforeComment: '\n',
  33108. beforeDecl: '\n',
  33109. beforeOpen: ' ',
  33110. beforeRule: '\n',
  33111. colon: ': ',
  33112. commentLeft: ' ',
  33113. commentRight: ' ',
  33114. emptyBody: '',
  33115. indent: ' ',
  33116. semicolon: false
  33117. };
  33118. function capitalize(str) {
  33119. return str[0].toUpperCase() + str.slice(1)
  33120. }
  33121. class Stringifier {
  33122. constructor(builder) {
  33123. this.builder = builder;
  33124. }
  33125. atrule(node, semicolon) {
  33126. let raws = node.raws;
  33127. let name = '@' + node.name;
  33128. let params = node.params ? this.rawValue(node, 'params') : '';
  33129. if (typeof raws.afterName !== 'undefined') {
  33130. name += raws.afterName;
  33131. } else if (params) {
  33132. name += ' ';
  33133. }
  33134. if (node.nodes) {
  33135. this.block(node, name + params);
  33136. } else {
  33137. let end = (raws.between || '') + (semicolon ? ';' : '');
  33138. this.builder(escapeHTMLInCSS(name + params + end), node);
  33139. }
  33140. }
  33141. beforeAfter(node, detect) {
  33142. let value;
  33143. if (node.type === 'decl') {
  33144. value = this.raw(node, null, 'beforeDecl');
  33145. } else if (node.type === 'comment') {
  33146. value = this.raw(node, null, 'beforeComment');
  33147. } else if (detect === 'before') {
  33148. value = this.raw(node, null, 'beforeRule');
  33149. } else {
  33150. value = this.raw(node, null, 'beforeClose');
  33151. }
  33152. let buf = node.parent;
  33153. let depth = 0;
  33154. while (buf && buf.type !== 'root') {
  33155. depth += 1;
  33156. buf = buf.parent;
  33157. }
  33158. if (value.includes('\n')) {
  33159. let indent = this.raw(node, null, 'indent');
  33160. if (indent.length) {
  33161. for (let step = 0; step < depth; step++) value += indent;
  33162. }
  33163. }
  33164. return value
  33165. }
  33166. block(node, start) {
  33167. let between = this.raw(node, 'between', 'beforeOpen');
  33168. this.builder(escapeHTMLInCSS(start + between) + '{', node, 'start');
  33169. let after;
  33170. if (node.nodes && node.nodes.length) {
  33171. this.body(node);
  33172. after = this.raw(node, 'after');
  33173. } else {
  33174. after = this.raw(node, 'after', 'emptyBody');
  33175. }
  33176. if (after) this.builder(escapeHTMLInCSS(after));
  33177. this.builder('}', node, 'end');
  33178. }
  33179. body(node) {
  33180. let nodes = node.nodes;
  33181. let last = nodes.length - 1;
  33182. while (last > 0) {
  33183. if (nodes[last].type !== 'comment') break
  33184. last -= 1;
  33185. }
  33186. let semicolon = this.raw(node, 'semicolon');
  33187. let isDocument = node.type === 'document';
  33188. for (let i = 0; i < nodes.length; i++) {
  33189. let child = nodes[i];
  33190. let before = this.raw(child, 'before');
  33191. if (before) this.builder(isDocument ? before : escapeHTMLInCSS(before));
  33192. this.stringify(child, last !== i || semicolon);
  33193. }
  33194. }
  33195. comment(node) {
  33196. let left = this.raw(node, 'left', 'commentLeft');
  33197. let right = this.raw(node, 'right', 'commentRight');
  33198. this.builder(escapeHTMLInCSS('/*' + left + node.text + right + '*/'), node);
  33199. }
  33200. decl(node, semicolon) {
  33201. let raws = node.raws;
  33202. let between = this.raw(node, 'between', 'colon');
  33203. let string = node.prop + between + this.rawValue(node, 'value');
  33204. if (node.important) {
  33205. string += raws.important || ' !important';
  33206. }
  33207. if (semicolon) string += ';';
  33208. this.builder(escapeHTMLInCSS(string), node);
  33209. }
  33210. document(node) {
  33211. this.body(node);
  33212. }
  33213. raw(node, own, detect) {
  33214. let value;
  33215. if (!detect) detect = own;
  33216. // Already had
  33217. if (own) {
  33218. value = node.raws[own];
  33219. if (typeof value !== 'undefined') return value
  33220. }
  33221. let parent = node.parent;
  33222. if (detect === 'before') {
  33223. // Hack for first rule in CSS
  33224. if (!parent || (parent.type === 'root' && parent.first === node)) {
  33225. return ''
  33226. }
  33227. // `root` nodes in `document` should use only their own raws
  33228. if (parent && parent.type === 'document') {
  33229. return ''
  33230. }
  33231. }
  33232. // Floating child without parent
  33233. if (!parent) return DEFAULT_RAW[detect]
  33234. // Detect style by other nodes
  33235. let root = node.root();
  33236. let cache = root.rawCache || (root.rawCache = {});
  33237. if (typeof cache[detect] !== 'undefined') {
  33238. return cache[detect]
  33239. }
  33240. if (detect === 'before' || detect === 'after') {
  33241. return this.beforeAfter(node, detect)
  33242. } else {
  33243. let method = 'raw' + capitalize(detect);
  33244. if (this[method]) {
  33245. value = this[method](root, node);
  33246. } else {
  33247. root.walk(i => {
  33248. value = i.raws[own];
  33249. if (typeof value !== 'undefined') return false
  33250. });
  33251. }
  33252. }
  33253. if (typeof value === 'undefined') value = DEFAULT_RAW[detect];
  33254. cache[detect] = value;
  33255. return value
  33256. }
  33257. rawBeforeClose(root) {
  33258. let value;
  33259. root.walk(i => {
  33260. if (i.nodes && i.nodes.length > 0) {
  33261. if (typeof i.raws.after !== 'undefined') {
  33262. value = i.raws.after;
  33263. if (value.includes('\n')) {
  33264. value = value.replace(/[^\n]+$/, '');
  33265. }
  33266. return false
  33267. }
  33268. }
  33269. });
  33270. if (value) value = value.replace(/\S/g, '');
  33271. return value
  33272. }
  33273. rawBeforeComment(root, node) {
  33274. let value;
  33275. root.walkComments(i => {
  33276. if (typeof i.raws.before !== 'undefined') {
  33277. value = i.raws.before;
  33278. if (value.includes('\n')) {
  33279. value = value.replace(/[^\n]+$/, '');
  33280. }
  33281. return false
  33282. }
  33283. });
  33284. if (typeof value === 'undefined') {
  33285. value = this.raw(node, null, 'beforeDecl');
  33286. } else if (value) {
  33287. value = value.replace(/\S/g, '');
  33288. }
  33289. return value
  33290. }
  33291. rawBeforeDecl(root, node) {
  33292. let value;
  33293. root.walkDecls(i => {
  33294. if (typeof i.raws.before !== 'undefined') {
  33295. value = i.raws.before;
  33296. if (value.includes('\n')) {
  33297. value = value.replace(/[^\n]+$/, '');
  33298. }
  33299. return false
  33300. }
  33301. });
  33302. if (typeof value === 'undefined') {
  33303. value = this.raw(node, null, 'beforeRule');
  33304. } else if (value) {
  33305. value = value.replace(/\S/g, '');
  33306. }
  33307. return value
  33308. }
  33309. rawBeforeOpen(root) {
  33310. let value;
  33311. root.walk(i => {
  33312. if (i.type !== 'decl') {
  33313. value = i.raws.between;
  33314. if (typeof value !== 'undefined') return false
  33315. }
  33316. });
  33317. return value
  33318. }
  33319. rawBeforeRule(root) {
  33320. let value;
  33321. root.walk(i => {
  33322. if (i.nodes && (i.parent !== root || root.first !== i)) {
  33323. if (typeof i.raws.before !== 'undefined') {
  33324. value = i.raws.before;
  33325. if (value.includes('\n')) {
  33326. value = value.replace(/[^\n]+$/, '');
  33327. }
  33328. return false
  33329. }
  33330. }
  33331. });
  33332. if (value) value = value.replace(/\S/g, '');
  33333. return value
  33334. }
  33335. rawColon(root) {
  33336. let value;
  33337. root.walkDecls(i => {
  33338. if (typeof i.raws.between !== 'undefined') {
  33339. value = i.raws.between.replace(/[^\s:]/g, '');
  33340. return false
  33341. }
  33342. });
  33343. return value
  33344. }
  33345. rawEmptyBody(root) {
  33346. let value;
  33347. root.walk(i => {
  33348. if (i.nodes && i.nodes.length === 0) {
  33349. value = i.raws.after;
  33350. if (typeof value !== 'undefined') return false
  33351. }
  33352. });
  33353. return value
  33354. }
  33355. rawIndent(root) {
  33356. if (root.raws.indent) return root.raws.indent
  33357. let value;
  33358. root.walk(i => {
  33359. let p = i.parent;
  33360. if (p && p !== root && p.parent && p.parent === root) {
  33361. if (typeof i.raws.before !== 'undefined') {
  33362. let parts = i.raws.before.split('\n');
  33363. value = parts[parts.length - 1];
  33364. value = value.replace(/\S/g, '');
  33365. return false
  33366. }
  33367. }
  33368. });
  33369. return value
  33370. }
  33371. rawSemicolon(root) {
  33372. let value;
  33373. root.walk(i => {
  33374. if (i.nodes && i.nodes.length && i.last.type === 'decl') {
  33375. value = i.raws.semicolon;
  33376. if (typeof value !== 'undefined') return false
  33377. }
  33378. });
  33379. return value
  33380. }
  33381. rawValue(node, prop) {
  33382. let value = node[prop];
  33383. let raw = node.raws[prop];
  33384. if (raw && raw.value === value) {
  33385. return raw.raw
  33386. }
  33387. return value
  33388. }
  33389. root(node) {
  33390. this.body(node);
  33391. if (node.raws.after) {
  33392. let after = node.raws.after;
  33393. let isDocument = node.parent && node.parent.type === 'document';
  33394. this.builder(isDocument ? after : escapeHTMLInCSS(after));
  33395. }
  33396. }
  33397. rule(node) {
  33398. this.block(node, this.rawValue(node, 'selector'));
  33399. if (node.raws.ownSemicolon) {
  33400. this.builder(escapeHTMLInCSS(node.raws.ownSemicolon), node, 'end');
  33401. }
  33402. }
  33403. stringify(node, semicolon) {
  33404. /* c8 ignore start */
  33405. if (!this[node.type]) {
  33406. throw new Error(
  33407. 'Unknown AST node type ' +
  33408. node.type +
  33409. '. ' +
  33410. 'Maybe you need to change PostCSS stringifier.'
  33411. )
  33412. }
  33413. /* c8 ignore stop */
  33414. this[node.type](node, semicolon);
  33415. }
  33416. }
  33417. stringifier = Stringifier;
  33418. Stringifier.default = Stringifier;
  33419. return stringifier;
  33420. }
  33421. var stringify_1;
  33422. var hasRequiredStringify;
  33423. function requireStringify () {
  33424. if (hasRequiredStringify) return stringify_1;
  33425. hasRequiredStringify = 1;
  33426. let Stringifier = /*@__PURE__*/ requireStringifier();
  33427. function stringify(node, builder) {
  33428. let str = new Stringifier(builder);
  33429. str.stringify(node);
  33430. }
  33431. stringify_1 = stringify;
  33432. stringify.default = stringify;
  33433. return stringify_1;
  33434. }
  33435. var symbols = {};
  33436. var hasRequiredSymbols;
  33437. function requireSymbols () {
  33438. if (hasRequiredSymbols) return symbols;
  33439. hasRequiredSymbols = 1;
  33440. symbols.isClean = Symbol('isClean');
  33441. symbols.my = Symbol('my');
  33442. return symbols;
  33443. }
  33444. var node$2;
  33445. var hasRequiredNode$2;
  33446. function requireNode$2 () {
  33447. if (hasRequiredNode$2) return node$2;
  33448. hasRequiredNode$2 = 1;
  33449. let CssSyntaxError = /*@__PURE__*/ requireCssSyntaxError();
  33450. let Stringifier = /*@__PURE__*/ requireStringifier();
  33451. let stringify = /*@__PURE__*/ requireStringify();
  33452. let { isClean, my } = /*@__PURE__*/ requireSymbols();
  33453. function cloneNode(obj, parent) {
  33454. let cloned = new obj.constructor();
  33455. for (let i in obj) {
  33456. if (!Object.prototype.hasOwnProperty.call(obj, i)) {
  33457. /* c8 ignore next 2 */
  33458. continue
  33459. }
  33460. if (i === 'proxyCache') continue
  33461. let value = obj[i];
  33462. let type = typeof value;
  33463. if (i === 'parent' && type === 'object') {
  33464. if (parent) cloned[i] = parent;
  33465. } else if (i === 'source') {
  33466. cloned[i] = value;
  33467. } else if (Array.isArray(value)) {
  33468. cloned[i] = value.map(j => cloneNode(j, cloned));
  33469. } else {
  33470. if (type === 'object' && value !== null) value = cloneNode(value);
  33471. cloned[i] = value;
  33472. }
  33473. }
  33474. return cloned
  33475. }
  33476. function sourceOffset(inputCSS, position) {
  33477. // Not all custom syntaxes support `offset` in `source.start` and `source.end`
  33478. if (position && typeof position.offset !== 'undefined') {
  33479. return position.offset
  33480. }
  33481. let column = 1;
  33482. let line = 1;
  33483. let offset = 0;
  33484. for (let i = 0; i < inputCSS.length; i++) {
  33485. if (line === position.line && column === position.column) {
  33486. offset = i;
  33487. break
  33488. }
  33489. if (inputCSS[i] === '\n') {
  33490. column = 1;
  33491. line += 1;
  33492. } else {
  33493. column += 1;
  33494. }
  33495. }
  33496. return offset
  33497. }
  33498. class Node {
  33499. get proxyOf() {
  33500. return this
  33501. }
  33502. constructor(defaults = {}) {
  33503. this.raws = {};
  33504. this[isClean] = false;
  33505. this[my] = true;
  33506. for (let name in defaults) {
  33507. if (name === 'nodes') {
  33508. this.nodes = [];
  33509. for (let node of defaults[name]) {
  33510. if (typeof node.clone === 'function') {
  33511. this.append(node.clone());
  33512. } else {
  33513. this.append(node);
  33514. }
  33515. }
  33516. } else {
  33517. this[name] = defaults[name];
  33518. }
  33519. }
  33520. }
  33521. addToError(error) {
  33522. error.postcssNode = this;
  33523. if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
  33524. let s = this.source;
  33525. error.stack = error.stack.replace(
  33526. /\n\s{4}at /,
  33527. `$&${s.input.from}:${s.start.line}:${s.start.column}$&`
  33528. );
  33529. }
  33530. return error
  33531. }
  33532. after(add) {
  33533. this.parent.insertAfter(this, add);
  33534. return this
  33535. }
  33536. assign(overrides = {}) {
  33537. for (let name in overrides) {
  33538. this[name] = overrides[name];
  33539. }
  33540. return this
  33541. }
  33542. before(add) {
  33543. this.parent.insertBefore(this, add);
  33544. return this
  33545. }
  33546. cleanRaws(keepBetween) {
  33547. delete this.raws.before;
  33548. delete this.raws.after;
  33549. if (!keepBetween) delete this.raws.between;
  33550. }
  33551. clone(overrides = {}) {
  33552. let cloned = cloneNode(this);
  33553. for (let name in overrides) {
  33554. cloned[name] = overrides[name];
  33555. }
  33556. return cloned
  33557. }
  33558. cloneAfter(overrides = {}) {
  33559. let cloned = this.clone(overrides);
  33560. this.parent.insertAfter(this, cloned);
  33561. return cloned
  33562. }
  33563. cloneBefore(overrides = {}) {
  33564. let cloned = this.clone(overrides);
  33565. this.parent.insertBefore(this, cloned);
  33566. return cloned
  33567. }
  33568. error(message, opts = {}) {
  33569. if (this.source) {
  33570. let { end, start } = this.rangeBy(opts);
  33571. return this.source.input.error(
  33572. message,
  33573. { column: start.column, line: start.line },
  33574. { column: end.column, line: end.line },
  33575. opts
  33576. )
  33577. }
  33578. return new CssSyntaxError(message)
  33579. }
  33580. getProxyProcessor() {
  33581. return {
  33582. get(node, prop) {
  33583. if (prop === 'proxyOf') {
  33584. return node
  33585. } else if (prop === 'root') {
  33586. return () => node.root().toProxy()
  33587. } else {
  33588. return node[prop]
  33589. }
  33590. },
  33591. set(node, prop, value) {
  33592. if (node[prop] === value) return true
  33593. node[prop] = value;
  33594. if (
  33595. prop === 'prop' ||
  33596. prop === 'value' ||
  33597. prop === 'name' ||
  33598. prop === 'params' ||
  33599. prop === 'important' ||
  33600. /* c8 ignore next */
  33601. prop === 'text'
  33602. ) {
  33603. node.markDirty();
  33604. }
  33605. return true
  33606. }
  33607. }
  33608. }
  33609. /* c8 ignore next 3 */
  33610. markClean() {
  33611. this[isClean] = true;
  33612. }
  33613. markDirty() {
  33614. if (this[isClean]) {
  33615. this[isClean] = false;
  33616. let next = this;
  33617. while ((next = next.parent)) {
  33618. next[isClean] = false;
  33619. }
  33620. }
  33621. }
  33622. next() {
  33623. if (!this.parent) return undefined
  33624. let index = this.parent.index(this);
  33625. return this.parent.nodes[index + 1]
  33626. }
  33627. positionBy(opts = {}) {
  33628. let pos = this.source.start;
  33629. if (opts.index) {
  33630. pos = this.positionInside(opts.index);
  33631. } else if (opts.word) {
  33632. let inputString =
  33633. 'document' in this.source.input
  33634. ? this.source.input.document
  33635. : this.source.input.css;
  33636. let stringRepresentation = inputString.slice(
  33637. sourceOffset(inputString, this.source.start),
  33638. sourceOffset(inputString, this.source.end)
  33639. );
  33640. let index = stringRepresentation.indexOf(opts.word);
  33641. if (index !== -1) pos = this.positionInside(index);
  33642. }
  33643. return pos
  33644. }
  33645. positionInside(index) {
  33646. let column = this.source.start.column;
  33647. let line = this.source.start.line;
  33648. let inputString =
  33649. 'document' in this.source.input
  33650. ? this.source.input.document
  33651. : this.source.input.css;
  33652. let offset = sourceOffset(inputString, this.source.start);
  33653. let end = offset + index;
  33654. for (let i = offset; i < end; i++) {
  33655. if (inputString[i] === '\n') {
  33656. column = 1;
  33657. line += 1;
  33658. } else {
  33659. column += 1;
  33660. }
  33661. }
  33662. return { column, line, offset: end }
  33663. }
  33664. prev() {
  33665. if (!this.parent) return undefined
  33666. let index = this.parent.index(this);
  33667. return this.parent.nodes[index - 1]
  33668. }
  33669. rangeBy(opts = {}) {
  33670. let inputString =
  33671. 'document' in this.source.input
  33672. ? this.source.input.document
  33673. : this.source.input.css;
  33674. let start = {
  33675. column: this.source.start.column,
  33676. line: this.source.start.line,
  33677. offset: sourceOffset(inputString, this.source.start)
  33678. };
  33679. let end = this.source.end
  33680. ? {
  33681. column: this.source.end.column + 1,
  33682. line: this.source.end.line,
  33683. offset:
  33684. typeof this.source.end.offset === 'number'
  33685. ? // `source.end.offset` is exclusive, so we don't need to add 1
  33686. this.source.end.offset
  33687. : // Since line/column in this.source.end is inclusive,
  33688. // the `sourceOffset(... , this.source.end)` returns an inclusive offset.
  33689. // So, we add 1 to convert it to exclusive.
  33690. sourceOffset(inputString, this.source.end) + 1
  33691. }
  33692. : {
  33693. column: start.column + 1,
  33694. line: start.line,
  33695. offset: start.offset + 1
  33696. };
  33697. if (opts.word) {
  33698. let stringRepresentation = inputString.slice(
  33699. sourceOffset(inputString, this.source.start),
  33700. sourceOffset(inputString, this.source.end)
  33701. );
  33702. let index = stringRepresentation.indexOf(opts.word);
  33703. if (index !== -1) {
  33704. start = this.positionInside(index);
  33705. end = this.positionInside(index + opts.word.length);
  33706. }
  33707. } else {
  33708. if (opts.start) {
  33709. start = {
  33710. column: opts.start.column,
  33711. line: opts.start.line,
  33712. offset: sourceOffset(inputString, opts.start)
  33713. };
  33714. } else if (opts.index) {
  33715. start = this.positionInside(opts.index);
  33716. }
  33717. if (opts.end) {
  33718. end = {
  33719. column: opts.end.column,
  33720. line: opts.end.line,
  33721. offset: sourceOffset(inputString, opts.end)
  33722. };
  33723. } else if (typeof opts.endIndex === 'number') {
  33724. end = this.positionInside(opts.endIndex);
  33725. } else if (opts.index) {
  33726. end = this.positionInside(opts.index + 1);
  33727. }
  33728. }
  33729. if (
  33730. end.line < start.line ||
  33731. (end.line === start.line && end.column <= start.column)
  33732. ) {
  33733. end = {
  33734. column: start.column + 1,
  33735. line: start.line,
  33736. offset: start.offset + 1
  33737. };
  33738. }
  33739. return { end, start }
  33740. }
  33741. raw(prop, defaultType) {
  33742. let str = new Stringifier();
  33743. return str.raw(this, prop, defaultType)
  33744. }
  33745. remove() {
  33746. if (this.parent) {
  33747. this.parent.removeChild(this);
  33748. }
  33749. this.parent = undefined;
  33750. return this
  33751. }
  33752. replaceWith(...nodes) {
  33753. if (this.parent) {
  33754. let bookmark = this;
  33755. let foundSelf = false;
  33756. for (let node of nodes) {
  33757. if (node === this) {
  33758. foundSelf = true;
  33759. } else if (foundSelf) {
  33760. this.parent.insertAfter(bookmark, node);
  33761. bookmark = node;
  33762. } else {
  33763. this.parent.insertBefore(bookmark, node);
  33764. }
  33765. }
  33766. if (!foundSelf) {
  33767. this.remove();
  33768. }
  33769. }
  33770. return this
  33771. }
  33772. root() {
  33773. let result = this;
  33774. while (result.parent && result.parent.type !== 'document') {
  33775. result = result.parent;
  33776. }
  33777. return result
  33778. }
  33779. toJSON(_, inputs) {
  33780. let fixed = {};
  33781. let emitInputs = inputs == null;
  33782. inputs = inputs || new Map();
  33783. let inputsNextIndex = 0;
  33784. for (let name in this) {
  33785. if (!Object.prototype.hasOwnProperty.call(this, name)) {
  33786. /* c8 ignore next 2 */
  33787. continue
  33788. }
  33789. if (name === 'parent' || name === 'proxyCache') continue
  33790. let value = this[name];
  33791. if (Array.isArray(value)) {
  33792. fixed[name] = value.map(i => {
  33793. if (typeof i === 'object' && i.toJSON) {
  33794. return i.toJSON(null, inputs)
  33795. } else {
  33796. return i
  33797. }
  33798. });
  33799. } else if (typeof value === 'object' && value.toJSON) {
  33800. fixed[name] = value.toJSON(null, inputs);
  33801. } else if (name === 'source') {
  33802. if (value == null) continue
  33803. let inputId = inputs.get(value.input);
  33804. if (inputId == null) {
  33805. inputId = inputsNextIndex;
  33806. inputs.set(value.input, inputsNextIndex);
  33807. inputsNextIndex++;
  33808. }
  33809. fixed[name] = {
  33810. end: value.end,
  33811. inputId,
  33812. start: value.start
  33813. };
  33814. } else {
  33815. fixed[name] = value;
  33816. }
  33817. }
  33818. if (emitInputs) {
  33819. fixed.inputs = [...inputs.keys()].map(input => input.toJSON());
  33820. }
  33821. return fixed
  33822. }
  33823. toProxy() {
  33824. if (!this.proxyCache) {
  33825. this.proxyCache = new Proxy(this, this.getProxyProcessor());
  33826. }
  33827. return this.proxyCache
  33828. }
  33829. toString(stringifier = stringify) {
  33830. if (stringifier.stringify) stringifier = stringifier.stringify;
  33831. let result = '';
  33832. stringifier(this, i => {
  33833. result += i;
  33834. });
  33835. return result
  33836. }
  33837. warn(result, text, opts = {}) {
  33838. let data = { node: this };
  33839. for (let i in opts) data[i] = opts[i];
  33840. return result.warn(text, data)
  33841. }
  33842. }
  33843. node$2 = Node;
  33844. Node.default = Node;
  33845. return node$2;
  33846. }
  33847. var comment$1;
  33848. var hasRequiredComment$1;
  33849. function requireComment$1 () {
  33850. if (hasRequiredComment$1) return comment$1;
  33851. hasRequiredComment$1 = 1;
  33852. let Node = /*@__PURE__*/ requireNode$2();
  33853. class Comment extends Node {
  33854. constructor(defaults) {
  33855. super(defaults);
  33856. this.type = 'comment';
  33857. }
  33858. }
  33859. comment$1 = Comment;
  33860. Comment.default = Comment;
  33861. return comment$1;
  33862. }
  33863. var declaration;
  33864. var hasRequiredDeclaration;
  33865. function requireDeclaration () {
  33866. if (hasRequiredDeclaration) return declaration;
  33867. hasRequiredDeclaration = 1;
  33868. let Node = /*@__PURE__*/ requireNode$2();
  33869. class Declaration extends Node {
  33870. get variable() {
  33871. return this.prop.startsWith('--') || this.prop[0] === '$'
  33872. }
  33873. constructor(defaults) {
  33874. if (
  33875. defaults &&
  33876. typeof defaults.value !== 'undefined' &&
  33877. typeof defaults.value !== 'string'
  33878. ) {
  33879. defaults = { ...defaults, value: String(defaults.value) };
  33880. }
  33881. super(defaults);
  33882. this.type = 'decl';
  33883. }
  33884. }
  33885. declaration = Declaration;
  33886. Declaration.default = Declaration;
  33887. return declaration;
  33888. }
  33889. var container$1;
  33890. var hasRequiredContainer$1;
  33891. function requireContainer$1 () {
  33892. if (hasRequiredContainer$1) return container$1;
  33893. hasRequiredContainer$1 = 1;
  33894. let Comment = /*@__PURE__*/ requireComment$1();
  33895. let Declaration = /*@__PURE__*/ requireDeclaration();
  33896. let Node = /*@__PURE__*/ requireNode$2();
  33897. let { isClean, my } = /*@__PURE__*/ requireSymbols();
  33898. let AtRule, parse, Root, Rule;
  33899. function cleanSource(nodes) {
  33900. return nodes.map(i => {
  33901. if (i.nodes) i.nodes = cleanSource(i.nodes);
  33902. delete i.source;
  33903. return i
  33904. })
  33905. }
  33906. function markTreeDirty(node) {
  33907. node[isClean] = false;
  33908. if (node.proxyOf.nodes) {
  33909. for (let i of node.proxyOf.nodes) {
  33910. markTreeDirty(i);
  33911. }
  33912. }
  33913. }
  33914. class Container extends Node {
  33915. get first() {
  33916. if (!this.proxyOf.nodes) return undefined
  33917. return this.proxyOf.nodes[0]
  33918. }
  33919. get last() {
  33920. if (!this.proxyOf.nodes) return undefined
  33921. return this.proxyOf.nodes[this.proxyOf.nodes.length - 1]
  33922. }
  33923. append(...children) {
  33924. for (let child of children) {
  33925. let nodes = this.normalize(child, this.last);
  33926. for (let node of nodes) this.proxyOf.nodes.push(node);
  33927. }
  33928. this.markDirty();
  33929. return this
  33930. }
  33931. cleanRaws(keepBetween) {
  33932. super.cleanRaws(keepBetween);
  33933. if (this.nodes) {
  33934. for (let node of this.nodes) node.cleanRaws(keepBetween);
  33935. }
  33936. }
  33937. each(callback) {
  33938. if (!this.proxyOf.nodes) return undefined
  33939. let iterator = this.getIterator();
  33940. let index, result;
  33941. while (this.indexes[iterator] < this.proxyOf.nodes.length) {
  33942. index = this.indexes[iterator];
  33943. result = callback(this.proxyOf.nodes[index], index);
  33944. if (result === false) break
  33945. this.indexes[iterator] += 1;
  33946. }
  33947. delete this.indexes[iterator];
  33948. return result
  33949. }
  33950. every(condition) {
  33951. return this.nodes.every(condition)
  33952. }
  33953. getIterator() {
  33954. if (!this.lastEach) this.lastEach = 0;
  33955. if (!this.indexes) this.indexes = {};
  33956. this.lastEach += 1;
  33957. let iterator = this.lastEach;
  33958. this.indexes[iterator] = 0;
  33959. return iterator
  33960. }
  33961. getProxyProcessor() {
  33962. return {
  33963. get(node, prop) {
  33964. if (prop === 'proxyOf') {
  33965. return node
  33966. } else if (!node[prop]) {
  33967. return node[prop]
  33968. } else if (
  33969. prop === 'each' ||
  33970. (typeof prop === 'string' && prop.startsWith('walk'))
  33971. ) {
  33972. return (...args) => {
  33973. return node[prop](
  33974. ...args.map(i => {
  33975. if (typeof i === 'function') {
  33976. return (child, index) => i(child.toProxy(), index)
  33977. } else {
  33978. return i
  33979. }
  33980. })
  33981. )
  33982. }
  33983. } else if (prop === 'every' || prop === 'some') {
  33984. return cb => {
  33985. return node[prop]((child, ...other) =>
  33986. cb(child.toProxy(), ...other)
  33987. )
  33988. }
  33989. } else if (prop === 'root') {
  33990. return () => node.root().toProxy()
  33991. } else if (prop === 'nodes') {
  33992. return node.nodes.map(i => i.toProxy())
  33993. } else if (prop === 'first' || prop === 'last') {
  33994. return node[prop].toProxy()
  33995. } else {
  33996. return node[prop]
  33997. }
  33998. },
  33999. set(node, prop, value) {
  34000. if (node[prop] === value) return true
  34001. node[prop] = value;
  34002. if (prop === 'name' || prop === 'params' || prop === 'selector') {
  34003. node.markDirty();
  34004. }
  34005. return true
  34006. }
  34007. }
  34008. }
  34009. index(child) {
  34010. if (typeof child === 'number') return child
  34011. if (child.proxyOf) child = child.proxyOf;
  34012. return this.proxyOf.nodes.indexOf(child)
  34013. }
  34014. insertAfter(exist, add) {
  34015. let existIndex = this.index(exist);
  34016. let nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse();
  34017. existIndex = this.index(exist);
  34018. for (let node of nodes) this.proxyOf.nodes.splice(existIndex + 1, 0, node);
  34019. let index;
  34020. for (let id in this.indexes) {
  34021. index = this.indexes[id];
  34022. if (existIndex < index) {
  34023. this.indexes[id] = index + nodes.length;
  34024. }
  34025. }
  34026. this.markDirty();
  34027. return this
  34028. }
  34029. insertBefore(exist, add) {
  34030. let existIndex = this.index(exist);
  34031. let type = existIndex === 0 ? 'prepend' : false;
  34032. let nodes = this.normalize(
  34033. add,
  34034. this.proxyOf.nodes[existIndex],
  34035. type
  34036. ).reverse();
  34037. existIndex = this.index(exist);
  34038. for (let node of nodes) this.proxyOf.nodes.splice(existIndex, 0, node);
  34039. let index;
  34040. for (let id in this.indexes) {
  34041. index = this.indexes[id];
  34042. if (existIndex <= index) {
  34043. this.indexes[id] = index + nodes.length;
  34044. }
  34045. }
  34046. this.markDirty();
  34047. return this
  34048. }
  34049. normalize(nodes, sample) {
  34050. if (typeof nodes === 'string') {
  34051. nodes = cleanSource(parse(nodes).nodes);
  34052. } else if (typeof nodes === 'undefined') {
  34053. nodes = [];
  34054. } else if (Array.isArray(nodes)) {
  34055. nodes = nodes.slice(0);
  34056. for (let i of nodes) {
  34057. if (i.parent) i.parent.removeChild(i, 'ignore');
  34058. }
  34059. } else if (nodes.type === 'root' && this.type !== 'document') {
  34060. nodes = nodes.nodes.slice(0);
  34061. for (let i of nodes) {
  34062. if (i.parent) i.parent.removeChild(i, 'ignore');
  34063. }
  34064. } else if (nodes.type) {
  34065. nodes = [nodes];
  34066. } else if (nodes.prop) {
  34067. if (typeof nodes.value === 'undefined') {
  34068. throw new Error('Value field is missed in node creation')
  34069. } else if (typeof nodes.value !== 'string') {
  34070. nodes.value = String(nodes.value);
  34071. }
  34072. nodes = [new Declaration(nodes)];
  34073. } else if (nodes.selector || nodes.selectors) {
  34074. nodes = [new Rule(nodes)];
  34075. } else if (nodes.name) {
  34076. nodes = [new AtRule(nodes)];
  34077. } else if (nodes.text) {
  34078. nodes = [new Comment(nodes)];
  34079. } else {
  34080. throw new Error('Unknown node type in node creation')
  34081. }
  34082. let processed = nodes.map(i => {
  34083. /* c8 ignore next */
  34084. if (!i[my]) Container.rebuild(i);
  34085. i = i.proxyOf;
  34086. if (i.parent) i.parent.removeChild(i);
  34087. if (i[isClean]) markTreeDirty(i);
  34088. if (!i.raws) i.raws = {};
  34089. if (typeof i.raws.before === 'undefined') {
  34090. if (sample && typeof sample.raws.before !== 'undefined') {
  34091. i.raws.before = sample.raws.before.replace(/\S/g, '');
  34092. }
  34093. }
  34094. i.parent = this.proxyOf;
  34095. return i
  34096. });
  34097. return processed
  34098. }
  34099. prepend(...children) {
  34100. children = children.reverse();
  34101. for (let child of children) {
  34102. let nodes = this.normalize(child, this.first, 'prepend').reverse();
  34103. for (let node of nodes) this.proxyOf.nodes.unshift(node);
  34104. for (let id in this.indexes) {
  34105. this.indexes[id] = this.indexes[id] + nodes.length;
  34106. }
  34107. }
  34108. this.markDirty();
  34109. return this
  34110. }
  34111. push(child) {
  34112. child.parent = this;
  34113. this.proxyOf.nodes.push(child);
  34114. return this
  34115. }
  34116. removeAll() {
  34117. for (let node of this.proxyOf.nodes) node.parent = undefined;
  34118. this.proxyOf.nodes = [];
  34119. this.markDirty();
  34120. return this
  34121. }
  34122. removeChild(child) {
  34123. child = this.index(child);
  34124. this.proxyOf.nodes[child].parent = undefined;
  34125. this.proxyOf.nodes.splice(child, 1);
  34126. let index;
  34127. for (let id in this.indexes) {
  34128. index = this.indexes[id];
  34129. if (index >= child) {
  34130. this.indexes[id] = index - 1;
  34131. }
  34132. }
  34133. this.markDirty();
  34134. return this
  34135. }
  34136. replaceValues(pattern, opts, callback) {
  34137. if (!callback) {
  34138. callback = opts;
  34139. opts = {};
  34140. }
  34141. this.walkDecls(decl => {
  34142. if (opts.props && !opts.props.includes(decl.prop)) return
  34143. if (opts.fast && !decl.value.includes(opts.fast)) return
  34144. decl.value = decl.value.replace(pattern, callback);
  34145. });
  34146. this.markDirty();
  34147. return this
  34148. }
  34149. some(condition) {
  34150. return this.nodes.some(condition)
  34151. }
  34152. walk(callback) {
  34153. return this.each((child, i) => {
  34154. let result;
  34155. try {
  34156. result = callback(child, i);
  34157. } catch (e) {
  34158. throw child.addToError(e)
  34159. }
  34160. if (result !== false && child.walk) {
  34161. result = child.walk(callback);
  34162. }
  34163. return result
  34164. })
  34165. }
  34166. walkAtRules(name, callback) {
  34167. if (!callback) {
  34168. callback = name;
  34169. return this.walk((child, i) => {
  34170. if (child.type === 'atrule') {
  34171. return callback(child, i)
  34172. }
  34173. })
  34174. }
  34175. if (name instanceof RegExp) {
  34176. return this.walk((child, i) => {
  34177. if (child.type === 'atrule' && name.test(child.name)) {
  34178. return callback(child, i)
  34179. }
  34180. })
  34181. }
  34182. return this.walk((child, i) => {
  34183. if (child.type === 'atrule' && child.name === name) {
  34184. return callback(child, i)
  34185. }
  34186. })
  34187. }
  34188. walkComments(callback) {
  34189. return this.walk((child, i) => {
  34190. if (child.type === 'comment') {
  34191. return callback(child, i)
  34192. }
  34193. })
  34194. }
  34195. walkDecls(prop, callback) {
  34196. if (!callback) {
  34197. callback = prop;
  34198. return this.walk((child, i) => {
  34199. if (child.type === 'decl') {
  34200. return callback(child, i)
  34201. }
  34202. })
  34203. }
  34204. if (prop instanceof RegExp) {
  34205. return this.walk((child, i) => {
  34206. if (child.type === 'decl' && prop.test(child.prop)) {
  34207. return callback(child, i)
  34208. }
  34209. })
  34210. }
  34211. return this.walk((child, i) => {
  34212. if (child.type === 'decl' && child.prop === prop) {
  34213. return callback(child, i)
  34214. }
  34215. })
  34216. }
  34217. walkRules(selector, callback) {
  34218. if (!callback) {
  34219. callback = selector;
  34220. return this.walk((child, i) => {
  34221. if (child.type === 'rule') {
  34222. return callback(child, i)
  34223. }
  34224. })
  34225. }
  34226. if (selector instanceof RegExp) {
  34227. return this.walk((child, i) => {
  34228. if (child.type === 'rule' && selector.test(child.selector)) {
  34229. return callback(child, i)
  34230. }
  34231. })
  34232. }
  34233. return this.walk((child, i) => {
  34234. if (child.type === 'rule' && child.selector === selector) {
  34235. return callback(child, i)
  34236. }
  34237. })
  34238. }
  34239. }
  34240. Container.registerParse = dependant => {
  34241. parse = dependant;
  34242. };
  34243. Container.registerRule = dependant => {
  34244. Rule = dependant;
  34245. };
  34246. Container.registerAtRule = dependant => {
  34247. AtRule = dependant;
  34248. };
  34249. Container.registerRoot = dependant => {
  34250. Root = dependant;
  34251. };
  34252. container$1 = Container;
  34253. Container.default = Container;
  34254. /* c8 ignore start */
  34255. Container.rebuild = node => {
  34256. if (node.type === 'atrule') {
  34257. Object.setPrototypeOf(node, AtRule.prototype);
  34258. } else if (node.type === 'rule') {
  34259. Object.setPrototypeOf(node, Rule.prototype);
  34260. } else if (node.type === 'decl') {
  34261. Object.setPrototypeOf(node, Declaration.prototype);
  34262. } else if (node.type === 'comment') {
  34263. Object.setPrototypeOf(node, Comment.prototype);
  34264. } else if (node.type === 'root') {
  34265. Object.setPrototypeOf(node, Root.prototype);
  34266. }
  34267. node[my] = true;
  34268. if (node.nodes) {
  34269. node.nodes.forEach(child => {
  34270. Container.rebuild(child);
  34271. });
  34272. }
  34273. };
  34274. /* c8 ignore stop */
  34275. return container$1;
  34276. }
  34277. var atRule;
  34278. var hasRequiredAtRule;
  34279. function requireAtRule () {
  34280. if (hasRequiredAtRule) return atRule;
  34281. hasRequiredAtRule = 1;
  34282. let Container = /*@__PURE__*/ requireContainer$1();
  34283. class AtRule extends Container {
  34284. constructor(defaults) {
  34285. super(defaults);
  34286. this.type = 'atrule';
  34287. }
  34288. append(...children) {
  34289. if (!this.proxyOf.nodes) this.nodes = [];
  34290. return super.append(...children)
  34291. }
  34292. prepend(...children) {
  34293. if (!this.proxyOf.nodes) this.nodes = [];
  34294. return super.prepend(...children)
  34295. }
  34296. }
  34297. atRule = AtRule;
  34298. AtRule.default = AtRule;
  34299. Container.registerAtRule(AtRule);
  34300. return atRule;
  34301. }
  34302. var document;
  34303. var hasRequiredDocument;
  34304. function requireDocument () {
  34305. if (hasRequiredDocument) return document;
  34306. hasRequiredDocument = 1;
  34307. let Container = /*@__PURE__*/ requireContainer$1();
  34308. let LazyResult, Processor;
  34309. class Document extends Container {
  34310. constructor(defaults) {
  34311. // type needs to be passed to super, otherwise child roots won't be normalized correctly
  34312. super({ type: 'document', ...defaults });
  34313. if (!this.nodes) {
  34314. this.nodes = [];
  34315. }
  34316. }
  34317. toResult(opts = {}) {
  34318. let lazy = new LazyResult(new Processor(), this, opts);
  34319. return lazy.stringify()
  34320. }
  34321. }
  34322. Document.registerLazyResult = dependant => {
  34323. LazyResult = dependant;
  34324. };
  34325. Document.registerProcessor = dependant => {
  34326. Processor = dependant;
  34327. };
  34328. document = Document;
  34329. Document.default = Document;
  34330. return document;
  34331. }
  34332. var nonSecure;
  34333. var hasRequiredNonSecure;
  34334. function requireNonSecure () {
  34335. if (hasRequiredNonSecure) return nonSecure;
  34336. hasRequiredNonSecure = 1;
  34337. // This alphabet uses `A-Za-z0-9_-` symbols.
  34338. // The order of characters is optimized for better gzip and brotli compression.
  34339. // References to the same file (works both for gzip and brotli):
  34340. // `'use`, `andom`, and `rict'`
  34341. // References to the brotli default dictionary:
  34342. // `-26T`, `1983`, `40px`, `75px`, `bush`, `jack`, `mind`, `very`, and `wolf`
  34343. let urlAlphabet =
  34344. 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
  34345. let customAlphabet = (alphabet, defaultSize = 21) => {
  34346. return (size = defaultSize) => {
  34347. let id = '';
  34348. // A compact alternative for `for (var i = 0; i < step; i++)`.
  34349. let i = size | 0;
  34350. while (i--) {
  34351. // `| 0` is more compact and faster than `Math.floor()`.
  34352. id += alphabet[(Math.random() * alphabet.length) | 0];
  34353. }
  34354. return id
  34355. }
  34356. };
  34357. let nanoid = (size = 21) => {
  34358. let id = '';
  34359. // A compact alternative for `for (var i = 0; i < step; i++)`.
  34360. let i = size | 0;
  34361. while (i--) {
  34362. // `| 0` is more compact and faster than `Math.floor()`.
  34363. id += urlAlphabet[(Math.random() * 64) | 0];
  34364. }
  34365. return id
  34366. };
  34367. nonSecure = { nanoid, customAlphabet };
  34368. return nonSecure;
  34369. }
  34370. var require$$2 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_url$1);
  34371. var previousMap;
  34372. var hasRequiredPreviousMap;
  34373. function requirePreviousMap () {
  34374. if (hasRequiredPreviousMap) return previousMap;
  34375. hasRequiredPreviousMap = 1;
  34376. let { existsSync, readFileSync } = require$$0$1;
  34377. let { dirname, join } = require$$1;
  34378. let { SourceMapConsumer, SourceMapGenerator } = /*@__PURE__*/ requireSourceMap$1();
  34379. function fromBase64(str) {
  34380. if (Buffer$1) {
  34381. return Buffer$1.from(str, 'base64').toString()
  34382. } else {
  34383. /* c8 ignore next 2 */
  34384. return window.atob(str)
  34385. }
  34386. }
  34387. class PreviousMap {
  34388. constructor(css, opts) {
  34389. if (opts.map === false) return
  34390. if (opts.unsafeMap) this.unsafeMap = true;
  34391. this.loadAnnotation(css);
  34392. this.inline = this.startWith(this.annotation, 'data:');
  34393. let prev = opts.map ? opts.map.prev : undefined;
  34394. let text = this.loadMap(opts.from, prev);
  34395. if (!this.mapFile && opts.from) {
  34396. this.mapFile = opts.from;
  34397. }
  34398. if (this.mapFile) this.root = dirname(this.mapFile);
  34399. if (text) this.text = text;
  34400. }
  34401. consumer() {
  34402. if (!this.consumerCache) {
  34403. this.consumerCache = new SourceMapConsumer(this.json || this.text);
  34404. }
  34405. return this.consumerCache
  34406. }
  34407. decodeInline(text) {
  34408. let baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/;
  34409. let baseUri = /^data:application\/json;base64,/;
  34410. let charsetUri = /^data:application\/json;charset=utf-?8,/;
  34411. let uri = /^data:application\/json,/;
  34412. let uriMatch = text.match(charsetUri) || text.match(uri);
  34413. if (uriMatch) {
  34414. return decodeURIComponent(text.substr(uriMatch[0].length))
  34415. }
  34416. let baseUriMatch = text.match(baseCharsetUri) || text.match(baseUri);
  34417. if (baseUriMatch) {
  34418. return fromBase64(text.substr(baseUriMatch[0].length))
  34419. }
  34420. let encoding = text.slice('data:application/json;'.length);
  34421. encoding = encoding.slice(0, encoding.indexOf(','));
  34422. throw new Error('Unsupported source map encoding ' + encoding)
  34423. }
  34424. getAnnotationURL(sourceMapString) {
  34425. return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, '').trim()
  34426. }
  34427. isMap(map) {
  34428. if (typeof map !== 'object') return false
  34429. return (
  34430. typeof map.mappings === 'string' ||
  34431. typeof map._mappings === 'string' ||
  34432. Array.isArray(map.sections)
  34433. )
  34434. }
  34435. loadAnnotation(css) {
  34436. let comments = css.match(/\/\*\s*# sourceMappingURL=/g);
  34437. if (!comments) return
  34438. // sourceMappingURLs from comments, strings, etc.
  34439. let start = css.lastIndexOf(comments.pop());
  34440. let end = css.indexOf('*/', start);
  34441. if (start > -1 && end > -1) {
  34442. // Locate the last sourceMappingURL to avoid pickin
  34443. this.annotation = this.getAnnotationURL(css.substring(start, end));
  34444. }
  34445. }
  34446. loadFile(path, cssFile, trusted) {
  34447. /* c8 ignore next 5 */
  34448. if (!trusted && !this.unsafeMap) {
  34449. if (!/\.map$/i.test(path)) {
  34450. return undefined
  34451. }
  34452. }
  34453. this.root = dirname(path);
  34454. if (existsSync(path)) {
  34455. this.mapFile = path;
  34456. return readFileSync(path, 'utf-8').toString().trim()
  34457. }
  34458. }
  34459. loadMap(file, prev) {
  34460. if (prev === false) return false
  34461. if (prev) {
  34462. if (typeof prev === 'string') {
  34463. return prev
  34464. } else if (typeof prev === 'function') {
  34465. let prevPath = prev(file);
  34466. if (prevPath) {
  34467. let map = this.loadFile(prevPath, file, true);
  34468. if (!map) {
  34469. throw new Error(
  34470. 'Unable to load previous source map: ' + prevPath.toString()
  34471. )
  34472. }
  34473. return map
  34474. }
  34475. } else if (prev instanceof SourceMapConsumer) {
  34476. return SourceMapGenerator.fromSourceMap(prev).toString()
  34477. } else if (prev instanceof SourceMapGenerator) {
  34478. return prev.toString()
  34479. } else if (this.isMap(prev)) {
  34480. return JSON.stringify(prev)
  34481. } else {
  34482. throw new Error(
  34483. 'Unsupported previous source map format: ' + prev.toString()
  34484. )
  34485. }
  34486. } else if (this.inline) {
  34487. return this.decodeInline(this.annotation)
  34488. } else if (this.annotation) {
  34489. let map = this.annotation;
  34490. if (file) map = join(dirname(file), map);
  34491. let unknown = this.loadFile(map, file, false);
  34492. if (unknown) {
  34493. try {
  34494. /* c8 ignore next 4 */
  34495. this.json = JSON.parse(unknown.replace(/^\)]}'[^\n]*\n/, ''));
  34496. } catch {
  34497. return undefined
  34498. }
  34499. }
  34500. return unknown
  34501. }
  34502. }
  34503. startWith(string, start) {
  34504. if (!string) return false
  34505. return string.substr(0, start.length) === start
  34506. }
  34507. withContent() {
  34508. return !!(
  34509. this.consumer().sourcesContent &&
  34510. this.consumer().sourcesContent.length > 0
  34511. )
  34512. }
  34513. }
  34514. previousMap = PreviousMap;
  34515. PreviousMap.default = PreviousMap;
  34516. return previousMap;
  34517. }
  34518. var input;
  34519. var hasRequiredInput;
  34520. function requireInput () {
  34521. if (hasRequiredInput) return input;
  34522. hasRequiredInput = 1;
  34523. let { nanoid } = /*@__PURE__*/ requireNonSecure();
  34524. let { isAbsolute, resolve } = require$$1;
  34525. let { SourceMapConsumer, SourceMapGenerator } = /*@__PURE__*/ requireSourceMap$1();
  34526. let { fileURLToPath, pathToFileURL } = require$$2;
  34527. let CssSyntaxError = /*@__PURE__*/ requireCssSyntaxError();
  34528. let PreviousMap = /*@__PURE__*/ requirePreviousMap();
  34529. let terminalHighlight = /*@__PURE__*/ requireTerminalHighlight();
  34530. let lineToIndexCache = Symbol('lineToIndexCache');
  34531. let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator);
  34532. let pathAvailable = Boolean(resolve && isAbsolute);
  34533. function getLineToIndex(input) {
  34534. if (input[lineToIndexCache]) return input[lineToIndexCache]
  34535. let lines = input.css.split('\n');
  34536. let lineToIndex = new Array(lines.length);
  34537. let prevIndex = 0;
  34538. for (let i = 0, l = lines.length; i < l; i++) {
  34539. lineToIndex[i] = prevIndex;
  34540. prevIndex += lines[i].length + 1;
  34541. }
  34542. input[lineToIndexCache] = lineToIndex;
  34543. return lineToIndex
  34544. }
  34545. class Input {
  34546. get from() {
  34547. return this.file || this.id
  34548. }
  34549. constructor(css, opts = {}) {
  34550. if (
  34551. css === null ||
  34552. typeof css === 'undefined' ||
  34553. (typeof css === 'object' && !css.toString)
  34554. ) {
  34555. throw new Error(`PostCSS received ${css} instead of CSS string`)
  34556. }
  34557. this.css = css.toString();
  34558. if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') {
  34559. this.hasBOM = true;
  34560. this.css = this.css.slice(1);
  34561. } else {
  34562. this.hasBOM = false;
  34563. }
  34564. this.document = this.css;
  34565. if (opts.document) this.document = opts.document.toString();
  34566. if (opts.from) {
  34567. if (
  34568. !pathAvailable ||
  34569. /^\w+:\/\//.test(opts.from) ||
  34570. isAbsolute(opts.from)
  34571. ) {
  34572. this.file = opts.from;
  34573. } else {
  34574. this.file = resolve(opts.from);
  34575. }
  34576. }
  34577. if (pathAvailable && sourceMapAvailable) {
  34578. let map = new PreviousMap(this.css, opts);
  34579. if (map.text) {
  34580. this.map = map;
  34581. let file = map.consumer().file;
  34582. if (!this.file && file) this.file = this.mapResolve(file);
  34583. }
  34584. }
  34585. if (!this.file) {
  34586. this.id = '<input css ' + nanoid(6) + '>';
  34587. }
  34588. if (this.map) this.map.file = this.from;
  34589. }
  34590. error(message, line, column, opts = {}) {
  34591. let endColumn, endLine, endOffset, offset, result;
  34592. if (line && typeof line === 'object') {
  34593. let start = line;
  34594. let end = column;
  34595. if (typeof start.offset === 'number') {
  34596. offset = start.offset;
  34597. let pos = this.fromOffset(offset);
  34598. line = pos.line;
  34599. column = pos.col;
  34600. } else {
  34601. line = start.line;
  34602. column = start.column;
  34603. offset = this.fromLineAndColumn(line, column);
  34604. }
  34605. if (typeof end.offset === 'number') {
  34606. endOffset = end.offset;
  34607. let pos = this.fromOffset(endOffset);
  34608. endLine = pos.line;
  34609. endColumn = pos.col;
  34610. } else {
  34611. endLine = end.line;
  34612. endColumn = end.column;
  34613. endOffset = this.fromLineAndColumn(end.line, end.column);
  34614. }
  34615. } else if (!column) {
  34616. offset = line;
  34617. let pos = this.fromOffset(offset);
  34618. line = pos.line;
  34619. column = pos.col;
  34620. } else {
  34621. offset = this.fromLineAndColumn(line, column);
  34622. }
  34623. let origin = this.origin(line, column, endLine, endColumn);
  34624. if (origin) {
  34625. result = new CssSyntaxError(
  34626. message,
  34627. origin.endLine === undefined
  34628. ? origin.line
  34629. : { column: origin.column, line: origin.line },
  34630. origin.endLine === undefined
  34631. ? origin.column
  34632. : { column: origin.endColumn, line: origin.endLine },
  34633. origin.source,
  34634. origin.file,
  34635. opts.plugin
  34636. );
  34637. } else {
  34638. result = new CssSyntaxError(
  34639. message,
  34640. endLine === undefined ? line : { column, line },
  34641. endLine === undefined ? column : { column: endColumn, line: endLine },
  34642. this.css,
  34643. this.file,
  34644. opts.plugin
  34645. );
  34646. }
  34647. result.input = {
  34648. column,
  34649. endColumn,
  34650. endLine,
  34651. endOffset,
  34652. line,
  34653. offset,
  34654. source: this.css
  34655. };
  34656. if (this.file) {
  34657. if (pathToFileURL) {
  34658. result.input.url = pathToFileURL(this.file).toString();
  34659. }
  34660. result.input.file = this.file;
  34661. }
  34662. return result
  34663. }
  34664. fromLineAndColumn(line, column) {
  34665. let lineToIndex = getLineToIndex(this);
  34666. let index = lineToIndex[line - 1];
  34667. return index + column - 1
  34668. }
  34669. fromOffset(offset) {
  34670. let lineToIndex = getLineToIndex(this);
  34671. let lastLine = lineToIndex[lineToIndex.length - 1];
  34672. let min = 0;
  34673. if (offset >= lastLine) {
  34674. min = lineToIndex.length - 1;
  34675. } else {
  34676. let max = lineToIndex.length - 2;
  34677. let mid;
  34678. while (min < max) {
  34679. mid = min + ((max - min) >> 1);
  34680. if (offset < lineToIndex[mid]) {
  34681. max = mid - 1;
  34682. } else if (offset >= lineToIndex[mid + 1]) {
  34683. min = mid + 1;
  34684. } else {
  34685. min = mid;
  34686. break
  34687. }
  34688. }
  34689. }
  34690. return {
  34691. col: offset - lineToIndex[min] + 1,
  34692. line: min + 1
  34693. }
  34694. }
  34695. mapResolve(file) {
  34696. if (/^\w+:\/\//.test(file)) {
  34697. return file
  34698. }
  34699. return resolve(this.map.consumer().sourceRoot || this.map.root || '.', file)
  34700. }
  34701. origin(line, column, endLine, endColumn) {
  34702. if (!this.map) return false
  34703. let consumer = this.map.consumer();
  34704. let from = consumer.originalPositionFor({ column, line });
  34705. if (!from.source) return false
  34706. let to;
  34707. if (typeof endLine === 'number') {
  34708. to = consumer.originalPositionFor({ column: endColumn, line: endLine });
  34709. }
  34710. let fromUrl;
  34711. if (isAbsolute(from.source)) {
  34712. fromUrl = pathToFileURL(from.source);
  34713. } else {
  34714. fromUrl = new URL(
  34715. from.source,
  34716. this.map.consumer().sourceRoot || pathToFileURL(this.map.mapFile)
  34717. );
  34718. }
  34719. let result = {
  34720. column: from.column,
  34721. endColumn: to && to.column,
  34722. endLine: to && to.line,
  34723. line: from.line,
  34724. url: fromUrl.toString()
  34725. };
  34726. if (fromUrl.protocol === 'file:') {
  34727. if (fileURLToPath) {
  34728. result.file = fileURLToPath(fromUrl);
  34729. } else {
  34730. /* c8 ignore next 2 */
  34731. throw new Error(`file: protocol is not available in this PostCSS build`)
  34732. }
  34733. }
  34734. let source = consumer.sourceContentFor(from.source);
  34735. if (source) result.source = source;
  34736. return result
  34737. }
  34738. toJSON() {
  34739. let json = {};
  34740. for (let name of ['hasBOM', 'css', 'file', 'id']) {
  34741. if (this[name] != null) {
  34742. json[name] = this[name];
  34743. }
  34744. }
  34745. if (this.map) {
  34746. json.map = { ...this.map };
  34747. if (json.map.consumerCache) {
  34748. json.map.consumerCache = undefined;
  34749. }
  34750. }
  34751. return json
  34752. }
  34753. }
  34754. input = Input;
  34755. Input.default = Input;
  34756. if (terminalHighlight && terminalHighlight.registerInput) {
  34757. terminalHighlight.registerInput(Input);
  34758. }
  34759. return input;
  34760. }
  34761. var root$1;
  34762. var hasRequiredRoot$1;
  34763. function requireRoot$1 () {
  34764. if (hasRequiredRoot$1) return root$1;
  34765. hasRequiredRoot$1 = 1;
  34766. let Container = /*@__PURE__*/ requireContainer$1();
  34767. let LazyResult, Processor;
  34768. class Root extends Container {
  34769. constructor(defaults) {
  34770. super(defaults);
  34771. this.type = 'root';
  34772. if (!this.nodes) this.nodes = [];
  34773. }
  34774. normalize(child, sample, type) {
  34775. let nodes = super.normalize(child);
  34776. if (sample) {
  34777. if (type === 'prepend') {
  34778. if (this.nodes.length > 1) {
  34779. sample.raws.before = this.nodes[1].raws.before;
  34780. } else {
  34781. delete sample.raws.before;
  34782. }
  34783. } else if (this.first !== sample) {
  34784. for (let node of nodes) {
  34785. node.raws.before = sample.raws.before;
  34786. }
  34787. }
  34788. }
  34789. return nodes
  34790. }
  34791. removeChild(child, ignore) {
  34792. let index = this.index(child);
  34793. if (!ignore && index === 0 && this.nodes.length > 1) {
  34794. this.nodes[1].raws.before = this.nodes[index].raws.before;
  34795. }
  34796. return super.removeChild(child)
  34797. }
  34798. toResult(opts = {}) {
  34799. let lazy = new LazyResult(new Processor(), this, opts);
  34800. return lazy.stringify()
  34801. }
  34802. }
  34803. Root.registerLazyResult = dependant => {
  34804. LazyResult = dependant;
  34805. };
  34806. Root.registerProcessor = dependant => {
  34807. Processor = dependant;
  34808. };
  34809. root$1 = Root;
  34810. Root.default = Root;
  34811. Container.registerRoot(Root);
  34812. return root$1;
  34813. }
  34814. var list_1;
  34815. var hasRequiredList;
  34816. function requireList () {
  34817. if (hasRequiredList) return list_1;
  34818. hasRequiredList = 1;
  34819. let list = {
  34820. comma(string) {
  34821. return list.split(string, [','], true)
  34822. },
  34823. space(string) {
  34824. let spaces = [' ', '\n', '\t'];
  34825. return list.split(string, spaces)
  34826. },
  34827. split(string, separators, last) {
  34828. let array = [];
  34829. let current = '';
  34830. let split = false;
  34831. let func = 0;
  34832. let inQuote = false;
  34833. let prevQuote = '';
  34834. let escape = false;
  34835. for (let letter of string) {
  34836. if (escape) {
  34837. escape = false;
  34838. } else if (letter === '\\') {
  34839. escape = true;
  34840. } else if (inQuote) {
  34841. if (letter === prevQuote) {
  34842. inQuote = false;
  34843. }
  34844. } else if (letter === '"' || letter === "'") {
  34845. inQuote = true;
  34846. prevQuote = letter;
  34847. } else if (letter === '(') {
  34848. func += 1;
  34849. } else if (letter === ')') {
  34850. if (func > 0) func -= 1;
  34851. } else if (func === 0) {
  34852. if (separators.includes(letter)) split = true;
  34853. }
  34854. if (split) {
  34855. if (current !== '') array.push(current.trim());
  34856. current = '';
  34857. split = false;
  34858. } else {
  34859. current += letter;
  34860. }
  34861. }
  34862. if (last || current !== '') array.push(current.trim());
  34863. return array
  34864. }
  34865. };
  34866. list_1 = list;
  34867. list.default = list;
  34868. return list_1;
  34869. }
  34870. var rule;
  34871. var hasRequiredRule;
  34872. function requireRule () {
  34873. if (hasRequiredRule) return rule;
  34874. hasRequiredRule = 1;
  34875. let Container = /*@__PURE__*/ requireContainer$1();
  34876. let list = /*@__PURE__*/ requireList();
  34877. class Rule extends Container {
  34878. get selectors() {
  34879. return list.comma(this.selector)
  34880. }
  34881. set selectors(values) {
  34882. let match = this.selector ? this.selector.match(/,\s*/) : null;
  34883. let sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen');
  34884. this.selector = values.join(sep);
  34885. }
  34886. constructor(defaults) {
  34887. super(defaults);
  34888. this.type = 'rule';
  34889. if (!this.nodes) this.nodes = [];
  34890. }
  34891. }
  34892. rule = Rule;
  34893. Rule.default = Rule;
  34894. Container.registerRule(Rule);
  34895. return rule;
  34896. }
  34897. var fromJSON_1;
  34898. var hasRequiredFromJSON;
  34899. function requireFromJSON () {
  34900. if (hasRequiredFromJSON) return fromJSON_1;
  34901. hasRequiredFromJSON = 1;
  34902. let AtRule = /*@__PURE__*/ requireAtRule();
  34903. let Comment = /*@__PURE__*/ requireComment$1();
  34904. let Declaration = /*@__PURE__*/ requireDeclaration();
  34905. let Input = /*@__PURE__*/ requireInput();
  34906. let PreviousMap = /*@__PURE__*/ requirePreviousMap();
  34907. let Root = /*@__PURE__*/ requireRoot$1();
  34908. let Rule = /*@__PURE__*/ requireRule();
  34909. function fromJSON(json, inputs) {
  34910. if (Array.isArray(json)) return json.map(n => fromJSON(n))
  34911. let { inputs: ownInputs, ...defaults } = json;
  34912. if (ownInputs) {
  34913. inputs = [];
  34914. for (let input of ownInputs) {
  34915. let inputHydrated = { ...input, __proto__: Input.prototype };
  34916. if (inputHydrated.map) {
  34917. inputHydrated.map = {
  34918. ...inputHydrated.map,
  34919. __proto__: PreviousMap.prototype
  34920. };
  34921. }
  34922. inputs.push(inputHydrated);
  34923. }
  34924. }
  34925. if (defaults.nodes) {
  34926. defaults.nodes = json.nodes.map(n => fromJSON(n, inputs));
  34927. }
  34928. if (defaults.source) {
  34929. let { inputId, ...source } = defaults.source;
  34930. defaults.source = source;
  34931. if (inputId != null) {
  34932. defaults.source.input = inputs[inputId];
  34933. }
  34934. }
  34935. if (defaults.type === 'root') {
  34936. return new Root(defaults)
  34937. } else if (defaults.type === 'decl') {
  34938. return new Declaration(defaults)
  34939. } else if (defaults.type === 'rule') {
  34940. return new Rule(defaults)
  34941. } else if (defaults.type === 'comment') {
  34942. return new Comment(defaults)
  34943. } else if (defaults.type === 'atrule') {
  34944. return new AtRule(defaults)
  34945. } else {
  34946. throw new Error('Unknown node type: ' + json.type)
  34947. }
  34948. }
  34949. fromJSON_1 = fromJSON;
  34950. fromJSON.default = fromJSON;
  34951. return fromJSON_1;
  34952. }
  34953. var mapGenerator;
  34954. var hasRequiredMapGenerator;
  34955. function requireMapGenerator () {
  34956. if (hasRequiredMapGenerator) return mapGenerator;
  34957. hasRequiredMapGenerator = 1;
  34958. let { dirname, relative, resolve, sep } = require$$1;
  34959. let { SourceMapConsumer, SourceMapGenerator } = /*@__PURE__*/ requireSourceMap$1();
  34960. let { pathToFileURL } = require$$2;
  34961. let Input = /*@__PURE__*/ requireInput();
  34962. let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator);
  34963. let pathAvailable = Boolean(dirname && resolve && relative && sep);
  34964. class MapGenerator {
  34965. constructor(stringify, root, opts, cssString) {
  34966. this.stringify = stringify;
  34967. this.mapOpts = opts.map || {};
  34968. this.root = root;
  34969. this.opts = opts;
  34970. this.css = cssString;
  34971. this.originalCSS = cssString;
  34972. this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute;
  34973. this.memoizedFileURLs = new Map();
  34974. this.memoizedPaths = new Map();
  34975. this.memoizedURLs = new Map();
  34976. }
  34977. addAnnotation() {
  34978. let content;
  34979. if (this.isInline()) {
  34980. content =
  34981. 'data:application/json;base64,' + this.toBase64(this.map.toString());
  34982. } else if (typeof this.mapOpts.annotation === 'string') {
  34983. content = this.mapOpts.annotation;
  34984. } else if (typeof this.mapOpts.annotation === 'function') {
  34985. content = this.mapOpts.annotation(this.opts.to, this.root);
  34986. } else {
  34987. content = this.outputFile() + '.map';
  34988. }
  34989. let eol = '\n';
  34990. if (this.css.includes('\r\n')) eol = '\r\n';
  34991. this.css += eol + '/*# sourceMappingURL=' + content + ' */';
  34992. }
  34993. applyPrevMaps() {
  34994. for (let prev of this.previous()) {
  34995. let from = this.toUrl(this.path(prev.file));
  34996. let root = prev.root || dirname(prev.file);
  34997. let map;
  34998. if (this.mapOpts.sourcesContent === false) {
  34999. map = new SourceMapConsumer(prev.text);
  35000. if (map.sourcesContent) {
  35001. map.sourcesContent = null;
  35002. }
  35003. } else {
  35004. map = prev.consumer();
  35005. }
  35006. this.map.applySourceMap(map, from, this.toUrl(this.path(root)));
  35007. }
  35008. }
  35009. clearAnnotation() {
  35010. if (this.mapOpts.annotation === false) return
  35011. if (this.root) {
  35012. let node;
  35013. for (let i = this.root.nodes.length - 1; i >= 0; i--) {
  35014. node = this.root.nodes[i];
  35015. if (node.type !== 'comment') continue
  35016. if (node.text.startsWith('# sourceMappingURL=')) {
  35017. this.root.removeChild(i);
  35018. }
  35019. }
  35020. } else if (this.css) {
  35021. let startIndex;
  35022. while ((startIndex = this.css.lastIndexOf('/*#')) !== -1) {
  35023. let endIndex = this.css.indexOf('*/', startIndex + 3);
  35024. if (endIndex === -1) break
  35025. while (startIndex > 0 && this.css[startIndex - 1] === '\n') {
  35026. startIndex--;
  35027. }
  35028. this.css = this.css.slice(0, startIndex) + this.css.slice(endIndex + 2);
  35029. }
  35030. }
  35031. }
  35032. generate() {
  35033. this.clearAnnotation();
  35034. if (pathAvailable && sourceMapAvailable && this.isMap()) {
  35035. return this.generateMap()
  35036. } else {
  35037. let result = '';
  35038. this.stringify(this.root, i => {
  35039. result += i;
  35040. });
  35041. return [result]
  35042. }
  35043. }
  35044. generateMap() {
  35045. if (this.root) {
  35046. this.generateString();
  35047. } else if (this.previous().length === 1) {
  35048. let prev = this.previous()[0].consumer();
  35049. prev.file = this.outputFile();
  35050. this.map = SourceMapGenerator.fromSourceMap(prev, {
  35051. ignoreInvalidMapping: true
  35052. });
  35053. } else {
  35054. this.map = new SourceMapGenerator({
  35055. file: this.outputFile(),
  35056. ignoreInvalidMapping: true
  35057. });
  35058. this.map.addMapping({
  35059. generated: { column: 0, line: 1 },
  35060. original: { column: 0, line: 1 },
  35061. source: this.opts.from
  35062. ? this.toUrl(this.path(this.opts.from))
  35063. : '<no source>'
  35064. });
  35065. }
  35066. if (this.isSourcesContent()) this.setSourcesContent();
  35067. if (this.root && this.previous().length > 0) this.applyPrevMaps();
  35068. if (this.isAnnotation()) this.addAnnotation();
  35069. if (this.isInline()) {
  35070. return [this.css]
  35071. } else {
  35072. return [this.css, this.map]
  35073. }
  35074. }
  35075. generateString() {
  35076. this.css = '';
  35077. this.map = new SourceMapGenerator({
  35078. file: this.outputFile(),
  35079. ignoreInvalidMapping: true
  35080. });
  35081. let line = 1;
  35082. let column = 1;
  35083. let noSource = '<no source>';
  35084. let mapping = {
  35085. generated: { column: 0, line: 0 },
  35086. original: { column: 0, line: 0 },
  35087. source: ''
  35088. };
  35089. let last, lines;
  35090. this.stringify(this.root, (str, node, type) => {
  35091. this.css += str;
  35092. if (node && type !== 'end') {
  35093. mapping.generated.line = line;
  35094. mapping.generated.column = column - 1;
  35095. if (node.source && node.source.start) {
  35096. mapping.source = this.sourcePath(node);
  35097. mapping.original.line = node.source.start.line;
  35098. mapping.original.column = node.source.start.column - 1;
  35099. this.map.addMapping(mapping);
  35100. } else {
  35101. mapping.source = noSource;
  35102. mapping.original.line = 1;
  35103. mapping.original.column = 0;
  35104. this.map.addMapping(mapping);
  35105. }
  35106. }
  35107. lines = str.match(/\n/g);
  35108. if (lines) {
  35109. line += lines.length;
  35110. last = str.lastIndexOf('\n');
  35111. column = str.length - last;
  35112. } else {
  35113. column += str.length;
  35114. }
  35115. if (node && type !== 'start') {
  35116. let p = node.parent || { raws: {} };
  35117. let childless =
  35118. node.type === 'decl' || (node.type === 'atrule' && !node.nodes);
  35119. if (!childless || node !== p.last || p.raws.semicolon) {
  35120. if (node.source && node.source.end) {
  35121. mapping.source = this.sourcePath(node);
  35122. mapping.original.line = node.source.end.line;
  35123. mapping.original.column = node.source.end.column - 1;
  35124. mapping.generated.line = line;
  35125. mapping.generated.column = column - 2;
  35126. this.map.addMapping(mapping);
  35127. } else {
  35128. mapping.source = noSource;
  35129. mapping.original.line = 1;
  35130. mapping.original.column = 0;
  35131. mapping.generated.line = line;
  35132. mapping.generated.column = column - 1;
  35133. this.map.addMapping(mapping);
  35134. }
  35135. }
  35136. }
  35137. });
  35138. }
  35139. isAnnotation() {
  35140. if (this.isInline()) {
  35141. return true
  35142. }
  35143. if (typeof this.mapOpts.annotation !== 'undefined') {
  35144. return this.mapOpts.annotation
  35145. }
  35146. if (this.previous().length) {
  35147. return this.previous().some(i => i.annotation)
  35148. }
  35149. return true
  35150. }
  35151. isInline() {
  35152. if (typeof this.mapOpts.inline !== 'undefined') {
  35153. return this.mapOpts.inline
  35154. }
  35155. let annotation = this.mapOpts.annotation;
  35156. if (typeof annotation !== 'undefined' && annotation !== true) {
  35157. return false
  35158. }
  35159. if (this.previous().length) {
  35160. return this.previous().some(i => i.inline)
  35161. }
  35162. return true
  35163. }
  35164. isMap() {
  35165. if (typeof this.opts.map !== 'undefined') {
  35166. return !!this.opts.map
  35167. }
  35168. return this.previous().length > 0
  35169. }
  35170. isSourcesContent() {
  35171. if (typeof this.mapOpts.sourcesContent !== 'undefined') {
  35172. return this.mapOpts.sourcesContent
  35173. }
  35174. if (this.previous().length) {
  35175. return this.previous().some(i => i.withContent())
  35176. }
  35177. return true
  35178. }
  35179. outputFile() {
  35180. if (this.opts.to) {
  35181. return this.path(this.opts.to)
  35182. } else if (this.opts.from) {
  35183. return this.path(this.opts.from)
  35184. } else {
  35185. return 'to.css'
  35186. }
  35187. }
  35188. path(file) {
  35189. if (this.mapOpts.absolute) return file
  35190. if (file.charCodeAt(0) === 60 /* `<` */) return file
  35191. if (/^\w+:\/\//.test(file)) return file
  35192. let cached = this.memoizedPaths.get(file);
  35193. if (cached) return cached
  35194. let from = this.opts.to ? dirname(this.opts.to) : '.';
  35195. if (typeof this.mapOpts.annotation === 'string') {
  35196. from = dirname(resolve(from, this.mapOpts.annotation));
  35197. }
  35198. let path = relative(from, file);
  35199. this.memoizedPaths.set(file, path);
  35200. return path
  35201. }
  35202. previous() {
  35203. if (!this.previousMaps) {
  35204. this.previousMaps = [];
  35205. if (this.root) {
  35206. this.root.walk(node => {
  35207. if (node.source && node.source.input.map) {
  35208. let map = node.source.input.map;
  35209. if (!this.previousMaps.includes(map)) {
  35210. this.previousMaps.push(map);
  35211. }
  35212. }
  35213. });
  35214. } else {
  35215. let input = new Input(this.originalCSS, this.opts);
  35216. if (input.map) this.previousMaps.push(input.map);
  35217. }
  35218. }
  35219. return this.previousMaps
  35220. }
  35221. setSourcesContent() {
  35222. let already = {};
  35223. if (this.root) {
  35224. this.root.walk(node => {
  35225. if (node.source) {
  35226. let from = node.source.input.from;
  35227. if (from && !already[from]) {
  35228. already[from] = true;
  35229. let fromUrl = this.usesFileUrls
  35230. ? this.toFileUrl(from)
  35231. : this.toUrl(this.path(from));
  35232. this.map.setSourceContent(fromUrl, node.source.input.css);
  35233. }
  35234. }
  35235. });
  35236. } else if (this.css) {
  35237. let from = this.opts.from
  35238. ? this.toUrl(this.path(this.opts.from))
  35239. : '<no source>';
  35240. this.map.setSourceContent(from, this.css);
  35241. }
  35242. }
  35243. sourcePath(node) {
  35244. if (this.mapOpts.from) {
  35245. return this.toUrl(this.mapOpts.from)
  35246. } else if (this.usesFileUrls) {
  35247. return this.toFileUrl(node.source.input.from)
  35248. } else {
  35249. return this.toUrl(this.path(node.source.input.from))
  35250. }
  35251. }
  35252. toBase64(str) {
  35253. if (Buffer$1) {
  35254. return Buffer$1.from(str).toString('base64')
  35255. } else {
  35256. return window.btoa(unescape(encodeURIComponent(str)))
  35257. }
  35258. }
  35259. toFileUrl(path) {
  35260. let cached = this.memoizedFileURLs.get(path);
  35261. if (cached) return cached
  35262. if (pathToFileURL) {
  35263. let fileURL = pathToFileURL(path).toString();
  35264. this.memoizedFileURLs.set(path, fileURL);
  35265. return fileURL
  35266. } else {
  35267. throw new Error(
  35268. '`map.absolute` option is not available in this PostCSS build'
  35269. )
  35270. }
  35271. }
  35272. toUrl(path) {
  35273. let cached = this.memoizedURLs.get(path);
  35274. if (cached) return cached
  35275. if (sep === '\\') {
  35276. path = path.replace(/\\/g, '/');
  35277. }
  35278. let url = encodeURI(path).replace(/[#?]/g, encodeURIComponent);
  35279. this.memoizedURLs.set(path, url);
  35280. return url
  35281. }
  35282. }
  35283. mapGenerator = MapGenerator;
  35284. return mapGenerator;
  35285. }
  35286. var parser$1;
  35287. var hasRequiredParser$1;
  35288. function requireParser$1 () {
  35289. if (hasRequiredParser$1) return parser$1;
  35290. hasRequiredParser$1 = 1;
  35291. let AtRule = /*@__PURE__*/ requireAtRule();
  35292. let Comment = /*@__PURE__*/ requireComment$1();
  35293. let Declaration = /*@__PURE__*/ requireDeclaration();
  35294. let Root = /*@__PURE__*/ requireRoot$1();
  35295. let Rule = /*@__PURE__*/ requireRule();
  35296. let tokenizer = /*@__PURE__*/ requireTokenize$1();
  35297. const SAFE_COMMENT_NEIGHBOR = {
  35298. empty: true,
  35299. space: true
  35300. };
  35301. function findLastWithPosition(tokens) {
  35302. for (let i = tokens.length - 1; i >= 0; i--) {
  35303. let token = tokens[i];
  35304. let pos = token[3] || token[2];
  35305. if (pos) return pos
  35306. }
  35307. }
  35308. function tokensToString(tokens, from, to) {
  35309. let result = '';
  35310. for (let i = from; i < to; i++) result += tokens[i][1];
  35311. return result
  35312. }
  35313. class Parser {
  35314. constructor(input) {
  35315. this.input = input;
  35316. this.root = new Root();
  35317. this.current = this.root;
  35318. this.spaces = '';
  35319. this.semicolon = false;
  35320. this.createTokenizer();
  35321. this.root.source = { input, start: { column: 1, line: 1, offset: 0 } };
  35322. }
  35323. atrule(token) {
  35324. let node = new AtRule();
  35325. node.name = token[1].slice(1);
  35326. if (node.name === '') {
  35327. this.unnamedAtrule(node, token);
  35328. }
  35329. this.init(node, token[2]);
  35330. let type;
  35331. let prev;
  35332. let shift;
  35333. let last = false;
  35334. let open = false;
  35335. let params = [];
  35336. let brackets = [];
  35337. while (!this.tokenizer.endOfFile()) {
  35338. token = this.tokenizer.nextToken();
  35339. type = token[0];
  35340. if (type === '(' || type === '[') {
  35341. brackets.push(type === '(' ? ')' : ']');
  35342. } else if (type === '{' && brackets.length > 0) {
  35343. brackets.push('}');
  35344. } else if (type === brackets[brackets.length - 1]) {
  35345. brackets.pop();
  35346. }
  35347. if (brackets.length === 0) {
  35348. if (type === ';') {
  35349. node.source.end = this.getPosition(token[2]);
  35350. node.source.end.offset++;
  35351. this.semicolon = true;
  35352. break
  35353. } else if (type === '{') {
  35354. open = true;
  35355. break
  35356. } else if (type === '}') {
  35357. if (params.length > 0) {
  35358. shift = params.length - 1;
  35359. prev = params[shift];
  35360. while (prev && prev[0] === 'space') {
  35361. prev = params[--shift];
  35362. }
  35363. if (prev) {
  35364. node.source.end = this.getPosition(prev[3] || prev[2]);
  35365. node.source.end.offset++;
  35366. }
  35367. }
  35368. this.end(token);
  35369. break
  35370. } else {
  35371. params.push(token);
  35372. }
  35373. } else {
  35374. params.push(token);
  35375. }
  35376. if (this.tokenizer.endOfFile()) {
  35377. last = true;
  35378. break
  35379. }
  35380. }
  35381. node.raws.between = this.spacesAndCommentsFromEnd(params);
  35382. if (params.length) {
  35383. node.raws.afterName = this.spacesAndCommentsFromStart(params);
  35384. this.raw(node, 'params', params);
  35385. if (last) {
  35386. token = params[params.length - 1];
  35387. node.source.end = this.getPosition(token[3] || token[2]);
  35388. node.source.end.offset++;
  35389. this.spaces = node.raws.between;
  35390. node.raws.between = '';
  35391. }
  35392. } else {
  35393. node.raws.afterName = '';
  35394. node.params = '';
  35395. }
  35396. if (open) {
  35397. node.nodes = [];
  35398. this.current = node;
  35399. }
  35400. }
  35401. checkMissedSemicolon(tokens) {
  35402. let colon = this.colon(tokens);
  35403. if (colon === false) return
  35404. let founded = 0;
  35405. let token;
  35406. for (let j = colon - 1; j >= 0; j--) {
  35407. token = tokens[j];
  35408. if (token[0] !== 'space') {
  35409. founded += 1;
  35410. if (founded === 2) break
  35411. }
  35412. }
  35413. // If the token is a word, e.g. `!important`, `red` or any other valid
  35414. // property's value. Then we need to return the colon after that word
  35415. // token. [3] is the "end" colon of that word. And because we need it
  35416. // after that one we do +1 to get the next one.
  35417. throw this.input.error(
  35418. 'Missed semicolon',
  35419. token[0] === 'word' ? token[3] + 1 : token[2]
  35420. )
  35421. }
  35422. colon(tokens) {
  35423. let brackets = 0;
  35424. let prev, token, type;
  35425. for (let [i, element] of tokens.entries()) {
  35426. token = element;
  35427. type = token[0];
  35428. if (type === '(') {
  35429. brackets += 1;
  35430. }
  35431. if (type === ')') {
  35432. brackets -= 1;
  35433. }
  35434. if (brackets === 0 && type === ':') {
  35435. if (!prev) {
  35436. this.doubleColon(token);
  35437. } else if (prev[0] === 'word' && prev[1] === 'progid') {
  35438. continue
  35439. } else {
  35440. return i
  35441. }
  35442. }
  35443. prev = token;
  35444. }
  35445. return false
  35446. }
  35447. comment(token) {
  35448. let node = new Comment();
  35449. this.init(node, token[2]);
  35450. node.source.end = this.getPosition(token[3] || token[2]);
  35451. node.source.end.offset++;
  35452. let text = token[1].slice(2, -2);
  35453. if (!text.trim()) {
  35454. node.text = '';
  35455. node.raws.left = text;
  35456. node.raws.right = '';
  35457. } else {
  35458. let match = text.match(/^(\s*)([^]*\S)(\s*)$/);
  35459. node.text = match[2];
  35460. node.raws.left = match[1];
  35461. node.raws.right = match[3];
  35462. }
  35463. }
  35464. createTokenizer() {
  35465. this.tokenizer = tokenizer(this.input);
  35466. }
  35467. decl(tokens, customProperty) {
  35468. let node = new Declaration();
  35469. this.init(node, tokens[0][2]);
  35470. let last = tokens[tokens.length - 1];
  35471. if (last[0] === ';') {
  35472. this.semicolon = true;
  35473. tokens.pop();
  35474. }
  35475. node.source.end = this.getPosition(
  35476. last[3] || last[2] || findLastWithPosition(tokens)
  35477. );
  35478. node.source.end.offset++;
  35479. let start = 0;
  35480. while (tokens[start][0] !== 'word') {
  35481. if (start === tokens.length - 1) this.unknownWord([tokens[start]]);
  35482. start++;
  35483. }
  35484. node.raws.before += tokensToString(tokens, 0, start);
  35485. node.source.start = this.getPosition(tokens[start][2]);
  35486. let propStart = start;
  35487. while (start < tokens.length) {
  35488. let type = tokens[start][0];
  35489. if (type === ':' || type === 'space' || type === 'comment') {
  35490. break
  35491. }
  35492. start++;
  35493. }
  35494. node.prop = tokensToString(tokens, propStart, start);
  35495. let betweenStart = start;
  35496. let token;
  35497. while (start < tokens.length) {
  35498. token = tokens[start];
  35499. start++;
  35500. if (token[0] === ':') break
  35501. if (token[0] === 'word' && /\w/.test(token[1])) {
  35502. this.unknownWord([token]);
  35503. }
  35504. }
  35505. node.raws.between = tokensToString(tokens, betweenStart, start);
  35506. if (node.prop[0] === '_' || node.prop[0] === '*') {
  35507. node.raws.before += node.prop[0];
  35508. node.prop = node.prop.slice(1);
  35509. }
  35510. let firstSpacesStart = start;
  35511. while (start < tokens.length) {
  35512. let next = tokens[start][0];
  35513. if (next !== 'space' && next !== 'comment') break
  35514. start++;
  35515. }
  35516. let firstSpaces = tokens.slice(firstSpacesStart, start);
  35517. tokens = tokens.slice(start);
  35518. this.precheckMissedSemicolon(tokens);
  35519. for (let i = tokens.length - 1; i >= 0; i--) {
  35520. token = tokens[i];
  35521. if (token[1].toLowerCase() === '!important') {
  35522. node.important = true;
  35523. let string = this.stringFrom(tokens, i);
  35524. string = this.spacesFromEnd(tokens) + string;
  35525. if (string !== ' !important') node.raws.important = string;
  35526. break
  35527. } else if (token[1].toLowerCase() === 'important') {
  35528. let cache = tokens.slice(0);
  35529. let str = '';
  35530. for (let j = i; j > 0; j--) {
  35531. let type = cache[j][0];
  35532. if (str.trim().startsWith('!') && type !== 'space') {
  35533. break
  35534. }
  35535. str = cache.pop()[1] + str;
  35536. }
  35537. if (str.trim().startsWith('!')) {
  35538. node.important = true;
  35539. node.raws.important = str;
  35540. tokens = cache;
  35541. }
  35542. }
  35543. if (token[0] !== 'space' && token[0] !== 'comment') {
  35544. break
  35545. }
  35546. }
  35547. let hasWord = tokens.some(i => i[0] !== 'space' && i[0] !== 'comment');
  35548. if (hasWord) {
  35549. node.raws.between += firstSpaces.map(i => i[1]).join('');
  35550. firstSpaces = [];
  35551. }
  35552. this.raw(node, 'value', firstSpaces.concat(tokens), customProperty);
  35553. if (node.value.includes(':') && !customProperty) {
  35554. this.checkMissedSemicolon(tokens);
  35555. }
  35556. }
  35557. doubleColon(token) {
  35558. throw this.input.error(
  35559. 'Double colon',
  35560. { offset: token[2] },
  35561. { offset: token[2] + token[1].length }
  35562. )
  35563. }
  35564. emptyRule(token) {
  35565. let node = new Rule();
  35566. this.init(node, token[2]);
  35567. node.selector = '';
  35568. node.raws.between = '';
  35569. this.current = node;
  35570. }
  35571. end(token) {
  35572. if (this.current.nodes && this.current.nodes.length) {
  35573. this.current.raws.semicolon = this.semicolon;
  35574. }
  35575. this.semicolon = false;
  35576. this.current.raws.after = (this.current.raws.after || '') + this.spaces;
  35577. this.spaces = '';
  35578. if (this.current.parent) {
  35579. this.current.source.end = this.getPosition(token[2]);
  35580. this.current.source.end.offset++;
  35581. this.current = this.current.parent;
  35582. } else {
  35583. this.unexpectedClose(token);
  35584. }
  35585. }
  35586. endFile() {
  35587. if (this.current.parent) this.unclosedBlock();
  35588. if (this.current.nodes && this.current.nodes.length) {
  35589. this.current.raws.semicolon = this.semicolon;
  35590. }
  35591. this.current.raws.after = (this.current.raws.after || '') + this.spaces;
  35592. this.root.source.end = this.getPosition(this.tokenizer.position());
  35593. }
  35594. freeSemicolon(token) {
  35595. this.spaces += token[1];
  35596. if (this.current.nodes) {
  35597. let prev = this.current.nodes[this.current.nodes.length - 1];
  35598. if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) {
  35599. prev.raws.ownSemicolon = this.spaces;
  35600. this.spaces = '';
  35601. prev.source.end = this.getPosition(token[2]);
  35602. prev.source.end.offset += prev.raws.ownSemicolon.length;
  35603. }
  35604. }
  35605. }
  35606. // Helpers
  35607. getPosition(offset) {
  35608. let pos = this.input.fromOffset(offset);
  35609. return {
  35610. column: pos.col,
  35611. line: pos.line,
  35612. offset
  35613. }
  35614. }
  35615. init(node, offset) {
  35616. this.current.push(node);
  35617. node.source = {
  35618. input: this.input,
  35619. start: this.getPosition(offset)
  35620. };
  35621. node.raws.before = this.spaces;
  35622. this.spaces = '';
  35623. if (node.type !== 'comment') this.semicolon = false;
  35624. }
  35625. other(start) {
  35626. let end = false;
  35627. let type = null;
  35628. let colon = false;
  35629. let bracket = null;
  35630. let brackets = [];
  35631. let customProperty = start[1].startsWith('--');
  35632. let tokens = [];
  35633. let token = start;
  35634. while (token) {
  35635. type = token[0];
  35636. tokens.push(token);
  35637. if (type === '(' || type === '[') {
  35638. if (!bracket) bracket = token;
  35639. brackets.push(type === '(' ? ')' : ']');
  35640. } else if (customProperty && colon && type === '{') {
  35641. if (!bracket) bracket = token;
  35642. brackets.push('}');
  35643. } else if (brackets.length === 0) {
  35644. if (type === ';') {
  35645. if (colon) {
  35646. this.decl(tokens, customProperty);
  35647. return
  35648. } else {
  35649. break
  35650. }
  35651. } else if (type === '{') {
  35652. this.rule(tokens);
  35653. return
  35654. } else if (type === '}') {
  35655. this.tokenizer.back(tokens.pop());
  35656. end = true;
  35657. break
  35658. } else if (type === ':') {
  35659. colon = true;
  35660. }
  35661. } else if (type === brackets[brackets.length - 1]) {
  35662. brackets.pop();
  35663. if (brackets.length === 0) bracket = null;
  35664. }
  35665. token = this.tokenizer.nextToken();
  35666. }
  35667. if (this.tokenizer.endOfFile()) end = true;
  35668. if (brackets.length > 0) this.unclosedBracket(bracket);
  35669. if (end && colon) {
  35670. if (!customProperty) {
  35671. while (tokens.length) {
  35672. token = tokens[tokens.length - 1][0];
  35673. if (token !== 'space' && token !== 'comment') break
  35674. this.tokenizer.back(tokens.pop());
  35675. }
  35676. }
  35677. this.decl(tokens, customProperty);
  35678. } else {
  35679. this.unknownWord(tokens);
  35680. }
  35681. }
  35682. parse() {
  35683. let token;
  35684. while (!this.tokenizer.endOfFile()) {
  35685. token = this.tokenizer.nextToken();
  35686. switch (token[0]) {
  35687. case 'space':
  35688. this.spaces += token[1];
  35689. break
  35690. case ';':
  35691. this.freeSemicolon(token);
  35692. break
  35693. case '}':
  35694. this.end(token);
  35695. break
  35696. case 'comment':
  35697. this.comment(token);
  35698. break
  35699. case 'at-word':
  35700. this.atrule(token);
  35701. break
  35702. case '{':
  35703. this.emptyRule(token);
  35704. break
  35705. default:
  35706. this.other(token);
  35707. break
  35708. }
  35709. }
  35710. this.endFile();
  35711. }
  35712. precheckMissedSemicolon(/* tokens */) {
  35713. // Hook for Safe Parser
  35714. }
  35715. raw(node, prop, tokens, customProperty) {
  35716. let token, type;
  35717. let length = tokens.length;
  35718. let value = '';
  35719. let clean = true;
  35720. let next, prev;
  35721. for (let i = 0; i < length; i += 1) {
  35722. token = tokens[i];
  35723. type = token[0];
  35724. if (type === 'space' && i === length - 1 && !customProperty) {
  35725. clean = false;
  35726. } else if (type === 'comment') {
  35727. prev = tokens[i - 1] ? tokens[i - 1][0] : 'empty';
  35728. next = tokens[i + 1] ? tokens[i + 1][0] : 'empty';
  35729. if (!SAFE_COMMENT_NEIGHBOR[prev] && !SAFE_COMMENT_NEIGHBOR[next]) {
  35730. if (value.slice(-1) === ',') {
  35731. clean = false;
  35732. } else {
  35733. value += token[1];
  35734. }
  35735. } else {
  35736. clean = false;
  35737. }
  35738. } else {
  35739. value += token[1];
  35740. }
  35741. }
  35742. if (!clean) {
  35743. let raw = tokens.reduce((all, i) => all + i[1], '');
  35744. node.raws[prop] = { raw, value };
  35745. }
  35746. node[prop] = value;
  35747. }
  35748. rule(tokens) {
  35749. tokens.pop();
  35750. let node = new Rule();
  35751. this.init(node, tokens[0][2]);
  35752. node.raws.between = this.spacesAndCommentsFromEnd(tokens);
  35753. this.raw(node, 'selector', tokens);
  35754. this.current = node;
  35755. }
  35756. spacesAndCommentsFromEnd(tokens) {
  35757. let lastTokenType;
  35758. let spaces = '';
  35759. while (tokens.length) {
  35760. lastTokenType = tokens[tokens.length - 1][0];
  35761. if (lastTokenType !== 'space' && lastTokenType !== 'comment') break
  35762. spaces = tokens.pop()[1] + spaces;
  35763. }
  35764. return spaces
  35765. }
  35766. // Errors
  35767. spacesAndCommentsFromStart(tokens) {
  35768. let next;
  35769. let spaces = '';
  35770. while (tokens.length) {
  35771. next = tokens[0][0];
  35772. if (next !== 'space' && next !== 'comment') break
  35773. spaces += tokens.shift()[1];
  35774. }
  35775. return spaces
  35776. }
  35777. spacesFromEnd(tokens) {
  35778. let lastTokenType;
  35779. let spaces = '';
  35780. while (tokens.length) {
  35781. lastTokenType = tokens[tokens.length - 1][0];
  35782. if (lastTokenType !== 'space') break
  35783. spaces = tokens.pop()[1] + spaces;
  35784. }
  35785. return spaces
  35786. }
  35787. stringFrom(tokens, from) {
  35788. let result = '';
  35789. for (let i = from; i < tokens.length; i++) {
  35790. result += tokens[i][1];
  35791. }
  35792. tokens.splice(from, tokens.length - from);
  35793. return result
  35794. }
  35795. unclosedBlock() {
  35796. let pos = this.current.source.start;
  35797. throw this.input.error('Unclosed block', pos.line, pos.column)
  35798. }
  35799. unclosedBracket(bracket) {
  35800. throw this.input.error(
  35801. 'Unclosed bracket',
  35802. { offset: bracket[2] },
  35803. { offset: bracket[2] + 1 }
  35804. )
  35805. }
  35806. unexpectedClose(token) {
  35807. throw this.input.error(
  35808. 'Unexpected }',
  35809. { offset: token[2] },
  35810. { offset: token[2] + 1 }
  35811. )
  35812. }
  35813. unknownWord(tokens) {
  35814. throw this.input.error(
  35815. 'Unknown word ' + tokens[0][1],
  35816. { offset: tokens[0][2] },
  35817. { offset: tokens[0][2] + tokens[0][1].length }
  35818. )
  35819. }
  35820. unnamedAtrule(node, token) {
  35821. throw this.input.error(
  35822. 'At-rule without name',
  35823. { offset: token[2] },
  35824. { offset: token[2] + token[1].length }
  35825. )
  35826. }
  35827. }
  35828. parser$1 = Parser;
  35829. return parser$1;
  35830. }
  35831. var parse_1;
  35832. var hasRequiredParse;
  35833. function requireParse () {
  35834. if (hasRequiredParse) return parse_1;
  35835. hasRequiredParse = 1;
  35836. let Container = /*@__PURE__*/ requireContainer$1();
  35837. let Input = /*@__PURE__*/ requireInput();
  35838. let Parser = /*@__PURE__*/ requireParser$1();
  35839. function parse(css, opts) {
  35840. let input = new Input(css, opts);
  35841. let parser = new Parser(input);
  35842. try {
  35843. parser.parse();
  35844. } catch (e) {
  35845. if (browser$1.env.NODE_ENV !== 'production') {
  35846. if (e.name === 'CssSyntaxError' && opts && opts.from) {
  35847. if (/\.scss$/i.test(opts.from)) {
  35848. e.message +=
  35849. '\nYou tried to parse SCSS with ' +
  35850. 'the standard CSS parser; ' +
  35851. 'try again with the postcss-scss parser';
  35852. } else if (/\.sass/i.test(opts.from)) {
  35853. e.message +=
  35854. '\nYou tried to parse Sass with ' +
  35855. 'the standard CSS parser; ' +
  35856. 'try again with the postcss-sass parser';
  35857. } else if (/\.less$/i.test(opts.from)) {
  35858. e.message +=
  35859. '\nYou tried to parse Less with ' +
  35860. 'the standard CSS parser; ' +
  35861. 'try again with the postcss-less parser';
  35862. }
  35863. }
  35864. }
  35865. throw e
  35866. }
  35867. return parser.root
  35868. }
  35869. parse_1 = parse;
  35870. parse.default = parse;
  35871. Container.registerParse(parse);
  35872. return parse_1;
  35873. }
  35874. var warning;
  35875. var hasRequiredWarning;
  35876. function requireWarning () {
  35877. if (hasRequiredWarning) return warning;
  35878. hasRequiredWarning = 1;
  35879. class Warning {
  35880. constructor(text, opts = {}) {
  35881. this.type = 'warning';
  35882. this.text = text;
  35883. if (opts.node && opts.node.source) {
  35884. let range = opts.node.rangeBy(opts);
  35885. this.line = range.start.line;
  35886. this.column = range.start.column;
  35887. this.endLine = range.end.line;
  35888. this.endColumn = range.end.column;
  35889. }
  35890. for (let opt in opts) this[opt] = opts[opt];
  35891. }
  35892. toString() {
  35893. if (this.node) {
  35894. return this.node.error(this.text, {
  35895. index: this.index,
  35896. plugin: this.plugin,
  35897. word: this.word
  35898. }).message
  35899. }
  35900. if (this.plugin) {
  35901. return this.plugin + ': ' + this.text
  35902. }
  35903. return this.text
  35904. }
  35905. }
  35906. warning = Warning;
  35907. Warning.default = Warning;
  35908. return warning;
  35909. }
  35910. var result;
  35911. var hasRequiredResult;
  35912. function requireResult () {
  35913. if (hasRequiredResult) return result;
  35914. hasRequiredResult = 1;
  35915. let Warning = /*@__PURE__*/ requireWarning();
  35916. class Result {
  35917. get content() {
  35918. return this.css
  35919. }
  35920. constructor(processor, root, opts) {
  35921. this.processor = processor;
  35922. this.messages = [];
  35923. this.root = root;
  35924. this.opts = opts;
  35925. this.css = '';
  35926. this.map = undefined;
  35927. }
  35928. toString() {
  35929. return this.css
  35930. }
  35931. warn(text, opts = {}) {
  35932. if (!opts.plugin) {
  35933. if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
  35934. opts.plugin = this.lastPlugin.postcssPlugin;
  35935. }
  35936. }
  35937. let warning = new Warning(text, opts);
  35938. this.messages.push(warning);
  35939. return warning
  35940. }
  35941. warnings() {
  35942. return this.messages.filter(i => i.type === 'warning')
  35943. }
  35944. }
  35945. result = Result;
  35946. Result.default = Result;
  35947. return result;
  35948. }
  35949. /* eslint-disable no-console */
  35950. var warnOnce;
  35951. var hasRequiredWarnOnce;
  35952. function requireWarnOnce () {
  35953. if (hasRequiredWarnOnce) return warnOnce;
  35954. hasRequiredWarnOnce = 1;
  35955. let printed = {};
  35956. warnOnce = function warnOnce(message) {
  35957. if (printed[message]) return
  35958. printed[message] = true;
  35959. if (typeof console !== 'undefined' && console.warn) {
  35960. console.warn(message);
  35961. }
  35962. };
  35963. return warnOnce;
  35964. }
  35965. var lazyResult;
  35966. var hasRequiredLazyResult;
  35967. function requireLazyResult () {
  35968. if (hasRequiredLazyResult) return lazyResult;
  35969. hasRequiredLazyResult = 1;
  35970. let Container = /*@__PURE__*/ requireContainer$1();
  35971. let Document = /*@__PURE__*/ requireDocument();
  35972. let MapGenerator = /*@__PURE__*/ requireMapGenerator();
  35973. let parse = /*@__PURE__*/ requireParse();
  35974. let Result = /*@__PURE__*/ requireResult();
  35975. let Root = /*@__PURE__*/ requireRoot$1();
  35976. let stringify = /*@__PURE__*/ requireStringify();
  35977. let { isClean, my } = /*@__PURE__*/ requireSymbols();
  35978. let warnOnce = /*@__PURE__*/ requireWarnOnce();
  35979. const TYPE_TO_CLASS_NAME = {
  35980. atrule: 'AtRule',
  35981. comment: 'Comment',
  35982. decl: 'Declaration',
  35983. document: 'Document',
  35984. root: 'Root',
  35985. rule: 'Rule'
  35986. };
  35987. const PLUGIN_PROPS = {
  35988. AtRule: true,
  35989. AtRuleExit: true,
  35990. Comment: true,
  35991. CommentExit: true,
  35992. Declaration: true,
  35993. DeclarationExit: true,
  35994. Document: true,
  35995. DocumentExit: true,
  35996. Once: true,
  35997. OnceExit: true,
  35998. postcssPlugin: true,
  35999. prepare: true,
  36000. Root: true,
  36001. RootExit: true,
  36002. Rule: true,
  36003. RuleExit: true
  36004. };
  36005. const NOT_VISITORS = {
  36006. Once: true,
  36007. postcssPlugin: true,
  36008. prepare: true
  36009. };
  36010. const CHILDREN = 0;
  36011. function isPromise(obj) {
  36012. return typeof obj === 'object' && typeof obj.then === 'function'
  36013. }
  36014. function getEvents(node) {
  36015. let key = false;
  36016. let type = TYPE_TO_CLASS_NAME[node.type];
  36017. if (node.type === 'decl') {
  36018. key = node.prop.toLowerCase();
  36019. } else if (node.type === 'atrule') {
  36020. key = node.name.toLowerCase();
  36021. }
  36022. if (key && node.append) {
  36023. return [
  36024. type,
  36025. type + '-' + key,
  36026. CHILDREN,
  36027. type + 'Exit',
  36028. type + 'Exit-' + key
  36029. ]
  36030. } else if (key) {
  36031. return [type, type + '-' + key, type + 'Exit', type + 'Exit-' + key]
  36032. } else if (node.append) {
  36033. return [type, CHILDREN, type + 'Exit']
  36034. } else {
  36035. return [type, type + 'Exit']
  36036. }
  36037. }
  36038. function toStack(node) {
  36039. let events;
  36040. if (node.type === 'document') {
  36041. events = ['Document', CHILDREN, 'DocumentExit'];
  36042. } else if (node.type === 'root') {
  36043. events = ['Root', CHILDREN, 'RootExit'];
  36044. } else {
  36045. events = getEvents(node);
  36046. }
  36047. return {
  36048. eventIndex: 0,
  36049. events,
  36050. iterator: 0,
  36051. node,
  36052. visitorIndex: 0,
  36053. visitors: []
  36054. }
  36055. }
  36056. function cleanMarks(node) {
  36057. node[isClean] = false;
  36058. if (node.nodes) node.nodes.forEach(i => cleanMarks(i));
  36059. return node
  36060. }
  36061. let postcss = {};
  36062. class LazyResult {
  36063. get content() {
  36064. return this.stringify().content
  36065. }
  36066. get css() {
  36067. return this.stringify().css
  36068. }
  36069. get map() {
  36070. return this.stringify().map
  36071. }
  36072. get messages() {
  36073. return this.sync().messages
  36074. }
  36075. get opts() {
  36076. return this.result.opts
  36077. }
  36078. get processor() {
  36079. return this.result.processor
  36080. }
  36081. get root() {
  36082. return this.sync().root
  36083. }
  36084. get [Symbol.toStringTag]() {
  36085. return 'LazyResult'
  36086. }
  36087. constructor(processor, css, opts) {
  36088. this.stringified = false;
  36089. this.processed = false;
  36090. let root;
  36091. if (
  36092. typeof css === 'object' &&
  36093. css !== null &&
  36094. (css.type === 'root' || css.type === 'document')
  36095. ) {
  36096. root = cleanMarks(css);
  36097. } else if (css instanceof LazyResult || css instanceof Result) {
  36098. root = cleanMarks(css.root);
  36099. if (css.map) {
  36100. if (typeof opts.map === 'undefined') opts.map = {};
  36101. if (!opts.map.inline) opts.map.inline = false;
  36102. opts.map.prev = css.map;
  36103. }
  36104. } else {
  36105. let parser = parse;
  36106. if (opts.syntax) parser = opts.syntax.parse;
  36107. if (opts.parser) parser = opts.parser;
  36108. if (parser.parse) parser = parser.parse;
  36109. try {
  36110. root = parser(css, opts);
  36111. } catch (error) {
  36112. this.processed = true;
  36113. this.error = error;
  36114. }
  36115. if (root && !root[my]) {
  36116. /* c8 ignore next 2 */
  36117. Container.rebuild(root);
  36118. }
  36119. }
  36120. this.result = new Result(processor, root, opts);
  36121. this.helpers = { ...postcss, postcss, result: this.result };
  36122. this.plugins = this.processor.plugins.map(plugin => {
  36123. if (typeof plugin === 'object' && plugin.prepare) {
  36124. return { ...plugin, ...plugin.prepare(this.result) }
  36125. } else {
  36126. return plugin
  36127. }
  36128. });
  36129. }
  36130. async() {
  36131. if (this.error) return Promise.reject(this.error)
  36132. if (this.processed) return Promise.resolve(this.result)
  36133. if (!this.processing) {
  36134. this.processing = this.runAsync();
  36135. }
  36136. return this.processing
  36137. }
  36138. catch(onRejected) {
  36139. return this.async().catch(onRejected)
  36140. }
  36141. finally(onFinally) {
  36142. return this.async().then(onFinally, onFinally)
  36143. }
  36144. getAsyncError() {
  36145. throw new Error('Use process(css).then(cb) to work with async plugins')
  36146. }
  36147. handleError(error, node) {
  36148. let plugin = this.result.lastPlugin;
  36149. try {
  36150. if (node) node.addToError(error);
  36151. this.error = error;
  36152. if (error.name === 'CssSyntaxError' && !error.plugin) {
  36153. error.plugin = plugin.postcssPlugin;
  36154. error.setMessage();
  36155. } else if (plugin.postcssVersion) {
  36156. if (browser$1.env.NODE_ENV !== 'production') {
  36157. let pluginName = plugin.postcssPlugin;
  36158. let pluginVer = plugin.postcssVersion;
  36159. let runtimeVer = this.result.processor.version;
  36160. let a = pluginVer.split('.');
  36161. let b = runtimeVer.split('.');
  36162. if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) {
  36163. // eslint-disable-next-line no-console
  36164. console.error(
  36165. 'Unknown error from PostCSS plugin. Your current PostCSS ' +
  36166. 'version is ' +
  36167. runtimeVer +
  36168. ', but ' +
  36169. pluginName +
  36170. ' uses ' +
  36171. pluginVer +
  36172. '. Perhaps this is the source of the error below.'
  36173. );
  36174. }
  36175. }
  36176. }
  36177. } catch (err) {
  36178. /* c8 ignore next 3 */
  36179. // eslint-disable-next-line no-console
  36180. if (console && console.error) console.error(err);
  36181. }
  36182. return error
  36183. }
  36184. prepareVisitors() {
  36185. this.listeners = {};
  36186. let add = (plugin, type, cb) => {
  36187. if (!this.listeners[type]) this.listeners[type] = [];
  36188. this.listeners[type].push([plugin, cb]);
  36189. };
  36190. for (let plugin of this.plugins) {
  36191. if (typeof plugin === 'object') {
  36192. for (let event in plugin) {
  36193. if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) {
  36194. throw new Error(
  36195. `Unknown event ${event} in ${plugin.postcssPlugin}. ` +
  36196. `Try to update PostCSS (${this.processor.version} now).`
  36197. )
  36198. }
  36199. if (!NOT_VISITORS[event]) {
  36200. if (typeof plugin[event] === 'object') {
  36201. for (let filter in plugin[event]) {
  36202. if (filter === '*') {
  36203. add(plugin, event, plugin[event][filter]);
  36204. } else {
  36205. add(
  36206. plugin,
  36207. event + '-' + filter.toLowerCase(),
  36208. plugin[event][filter]
  36209. );
  36210. }
  36211. }
  36212. } else if (typeof plugin[event] === 'function') {
  36213. add(plugin, event, plugin[event]);
  36214. }
  36215. }
  36216. }
  36217. }
  36218. }
  36219. this.hasListener = Object.keys(this.listeners).length > 0;
  36220. }
  36221. async runAsync() {
  36222. this.plugin = 0;
  36223. for (let i = 0; i < this.plugins.length; i++) {
  36224. let plugin = this.plugins[i];
  36225. let promise = this.runOnRoot(plugin);
  36226. if (isPromise(promise)) {
  36227. try {
  36228. await promise;
  36229. } catch (error) {
  36230. throw this.handleError(error)
  36231. }
  36232. }
  36233. }
  36234. this.prepareVisitors();
  36235. if (this.hasListener) {
  36236. let root = this.result.root;
  36237. while (!root[isClean]) {
  36238. root[isClean] = true;
  36239. let stack = [toStack(root)];
  36240. while (stack.length > 0) {
  36241. let promise = this.visitTick(stack);
  36242. if (isPromise(promise)) {
  36243. try {
  36244. await promise;
  36245. } catch (e) {
  36246. let node = stack[stack.length - 1].node;
  36247. throw this.handleError(e, node)
  36248. }
  36249. }
  36250. }
  36251. }
  36252. if (this.listeners.OnceExit) {
  36253. for (let [plugin, visitor] of this.listeners.OnceExit) {
  36254. this.result.lastPlugin = plugin;
  36255. try {
  36256. if (root.type === 'document') {
  36257. let roots = root.nodes.map(subRoot =>
  36258. visitor(subRoot, this.helpers)
  36259. );
  36260. await Promise.all(roots);
  36261. } else {
  36262. await visitor(root, this.helpers);
  36263. }
  36264. } catch (e) {
  36265. throw this.handleError(e)
  36266. }
  36267. }
  36268. }
  36269. }
  36270. this.processed = true;
  36271. return this.stringify()
  36272. }
  36273. runOnRoot(plugin) {
  36274. this.result.lastPlugin = plugin;
  36275. try {
  36276. if (typeof plugin === 'object' && plugin.Once) {
  36277. if (this.result.root.type === 'document') {
  36278. let roots = this.result.root.nodes.map(root =>
  36279. plugin.Once(root, this.helpers)
  36280. );
  36281. if (isPromise(roots[0])) {
  36282. return Promise.all(roots)
  36283. }
  36284. return roots
  36285. }
  36286. return plugin.Once(this.result.root, this.helpers)
  36287. } else if (typeof plugin === 'function') {
  36288. return plugin(this.result.root, this.result)
  36289. }
  36290. } catch (error) {
  36291. throw this.handleError(error)
  36292. }
  36293. }
  36294. stringify() {
  36295. if (this.error) throw this.error
  36296. if (this.stringified) return this.result
  36297. this.stringified = true;
  36298. this.sync();
  36299. let opts = this.result.opts;
  36300. let str = stringify;
  36301. if (opts.syntax) str = opts.syntax.stringify;
  36302. if (opts.stringifier) str = opts.stringifier;
  36303. if (str.stringify) str = str.stringify;
  36304. let rootSource = this.result.root.source;
  36305. if (
  36306. opts.map === undefined &&
  36307. !(rootSource && rootSource.input && rootSource.input.map)
  36308. ) {
  36309. let result = '';
  36310. str(this.result.root, i => {
  36311. result += i;
  36312. });
  36313. this.result.css = result;
  36314. return this.result
  36315. }
  36316. let map = new MapGenerator(str, this.result.root, this.result.opts);
  36317. let data = map.generate();
  36318. this.result.css = data[0];
  36319. this.result.map = data[1];
  36320. return this.result
  36321. }
  36322. sync() {
  36323. if (this.error) throw this.error
  36324. if (this.processed) return this.result
  36325. this.processed = true;
  36326. if (this.processing) {
  36327. throw this.getAsyncError()
  36328. }
  36329. for (let plugin of this.plugins) {
  36330. let promise = this.runOnRoot(plugin);
  36331. if (isPromise(promise)) {
  36332. throw this.getAsyncError()
  36333. }
  36334. }
  36335. this.prepareVisitors();
  36336. if (this.hasListener) {
  36337. let root = this.result.root;
  36338. while (!root[isClean]) {
  36339. root[isClean] = true;
  36340. this.walkSync(root);
  36341. }
  36342. if (this.listeners.OnceExit) {
  36343. if (root.type === 'document') {
  36344. for (let subRoot of root.nodes) {
  36345. this.visitSync(this.listeners.OnceExit, subRoot);
  36346. }
  36347. } else {
  36348. this.visitSync(this.listeners.OnceExit, root);
  36349. }
  36350. }
  36351. }
  36352. return this.result
  36353. }
  36354. then(onFulfilled, onRejected) {
  36355. if (browser$1.env.NODE_ENV !== 'production') {
  36356. if (!('from' in this.opts)) {
  36357. warnOnce(
  36358. 'Without `from` option PostCSS could generate wrong source map ' +
  36359. 'and will not find Browserslist config. Set it to CSS file path ' +
  36360. 'or to `undefined` to prevent this warning.'
  36361. );
  36362. }
  36363. }
  36364. return this.async().then(onFulfilled, onRejected)
  36365. }
  36366. toString() {
  36367. return this.css
  36368. }
  36369. visitSync(visitors, node) {
  36370. for (let [plugin, visitor] of visitors) {
  36371. this.result.lastPlugin = plugin;
  36372. let promise;
  36373. try {
  36374. promise = visitor(node, this.helpers);
  36375. } catch (e) {
  36376. throw this.handleError(e, node.proxyOf)
  36377. }
  36378. if (node.type !== 'root' && node.type !== 'document' && !node.parent) {
  36379. return true
  36380. }
  36381. if (isPromise(promise)) {
  36382. throw this.getAsyncError()
  36383. }
  36384. }
  36385. }
  36386. visitTick(stack) {
  36387. let visit = stack[stack.length - 1];
  36388. let { node, visitors } = visit;
  36389. if (node.type !== 'root' && node.type !== 'document' && !node.parent) {
  36390. stack.pop();
  36391. return
  36392. }
  36393. if (visitors.length > 0 && visit.visitorIndex < visitors.length) {
  36394. let [plugin, visitor] = visitors[visit.visitorIndex];
  36395. visit.visitorIndex += 1;
  36396. if (visit.visitorIndex === visitors.length) {
  36397. visit.visitors = [];
  36398. visit.visitorIndex = 0;
  36399. }
  36400. this.result.lastPlugin = plugin;
  36401. try {
  36402. return visitor(node.toProxy(), this.helpers)
  36403. } catch (e) {
  36404. throw this.handleError(e, node)
  36405. }
  36406. }
  36407. if (visit.iterator !== 0) {
  36408. let iterator = visit.iterator;
  36409. let child;
  36410. while ((child = node.nodes[node.indexes[iterator]])) {
  36411. node.indexes[iterator] += 1;
  36412. if (!child[isClean]) {
  36413. child[isClean] = true;
  36414. stack.push(toStack(child));
  36415. return
  36416. }
  36417. }
  36418. visit.iterator = 0;
  36419. delete node.indexes[iterator];
  36420. }
  36421. let events = visit.events;
  36422. while (visit.eventIndex < events.length) {
  36423. let event = events[visit.eventIndex];
  36424. visit.eventIndex += 1;
  36425. if (event === CHILDREN) {
  36426. if (node.nodes && node.nodes.length) {
  36427. node[isClean] = true;
  36428. visit.iterator = node.getIterator();
  36429. }
  36430. return
  36431. } else if (this.listeners[event]) {
  36432. visit.visitors = this.listeners[event];
  36433. return
  36434. }
  36435. }
  36436. stack.pop();
  36437. }
  36438. walkSync(node) {
  36439. node[isClean] = true;
  36440. let events = getEvents(node);
  36441. for (let event of events) {
  36442. if (event === CHILDREN) {
  36443. if (node.nodes) {
  36444. node.each(child => {
  36445. if (!child[isClean]) this.walkSync(child);
  36446. });
  36447. }
  36448. } else {
  36449. let visitors = this.listeners[event];
  36450. if (visitors) {
  36451. if (this.visitSync(visitors, node.toProxy())) return
  36452. }
  36453. }
  36454. }
  36455. }
  36456. warnings() {
  36457. return this.sync().warnings()
  36458. }
  36459. }
  36460. LazyResult.registerPostcss = dependant => {
  36461. postcss = dependant;
  36462. };
  36463. lazyResult = LazyResult;
  36464. LazyResult.default = LazyResult;
  36465. Root.registerLazyResult(LazyResult);
  36466. Document.registerLazyResult(LazyResult);
  36467. return lazyResult;
  36468. }
  36469. var noWorkResult;
  36470. var hasRequiredNoWorkResult;
  36471. function requireNoWorkResult () {
  36472. if (hasRequiredNoWorkResult) return noWorkResult;
  36473. hasRequiredNoWorkResult = 1;
  36474. let MapGenerator = /*@__PURE__*/ requireMapGenerator();
  36475. let parse = /*@__PURE__*/ requireParse();
  36476. let Result = /*@__PURE__*/ requireResult();
  36477. let stringify = /*@__PURE__*/ requireStringify();
  36478. let warnOnce = /*@__PURE__*/ requireWarnOnce();
  36479. class NoWorkResult {
  36480. get content() {
  36481. return this.result.css
  36482. }
  36483. get css() {
  36484. return this.result.css
  36485. }
  36486. get map() {
  36487. return this.result.map
  36488. }
  36489. get messages() {
  36490. return []
  36491. }
  36492. get opts() {
  36493. return this.result.opts
  36494. }
  36495. get processor() {
  36496. return this.result.processor
  36497. }
  36498. get root() {
  36499. if (this._root) {
  36500. return this._root
  36501. }
  36502. let root;
  36503. let parser = parse;
  36504. try {
  36505. root = parser(this._css, this._opts);
  36506. } catch (error) {
  36507. this.error = error;
  36508. }
  36509. if (this.error) {
  36510. throw this.error
  36511. } else {
  36512. this._root = root;
  36513. return root
  36514. }
  36515. }
  36516. get [Symbol.toStringTag]() {
  36517. return 'NoWorkResult'
  36518. }
  36519. constructor(processor, css, opts) {
  36520. css = css.toString();
  36521. this.stringified = false;
  36522. this._processor = processor;
  36523. this._css = css;
  36524. this._opts = opts;
  36525. this._map = undefined;
  36526. let str = stringify;
  36527. this.result = new Result(this._processor, undefined, this._opts);
  36528. this.result.css = css;
  36529. let self = this;
  36530. Object.defineProperty(this.result, 'root', {
  36531. get() {
  36532. return self.root
  36533. }
  36534. });
  36535. let map = new MapGenerator(str, undefined, this._opts, css);
  36536. if (map.isMap()) {
  36537. let [generatedCSS, generatedMap] = map.generate();
  36538. if (generatedCSS) {
  36539. this.result.css = generatedCSS;
  36540. }
  36541. if (generatedMap) {
  36542. this.result.map = generatedMap;
  36543. }
  36544. } else {
  36545. map.clearAnnotation();
  36546. this.result.css = map.css;
  36547. }
  36548. }
  36549. async() {
  36550. if (this.error) return Promise.reject(this.error)
  36551. return Promise.resolve(this.result)
  36552. }
  36553. catch(onRejected) {
  36554. return this.async().catch(onRejected)
  36555. }
  36556. finally(onFinally) {
  36557. return this.async().then(onFinally, onFinally)
  36558. }
  36559. sync() {
  36560. if (this.error) throw this.error
  36561. return this.result
  36562. }
  36563. then(onFulfilled, onRejected) {
  36564. if (browser$1.env.NODE_ENV !== 'production') {
  36565. if (!('from' in this._opts)) {
  36566. warnOnce(
  36567. 'Without `from` option PostCSS could generate wrong source map ' +
  36568. 'and will not find Browserslist config. Set it to CSS file path ' +
  36569. 'or to `undefined` to prevent this warning.'
  36570. );
  36571. }
  36572. }
  36573. return this.async().then(onFulfilled, onRejected)
  36574. }
  36575. toString() {
  36576. return this._css
  36577. }
  36578. warnings() {
  36579. return []
  36580. }
  36581. }
  36582. noWorkResult = NoWorkResult;
  36583. NoWorkResult.default = NoWorkResult;
  36584. return noWorkResult;
  36585. }
  36586. var processor$1;
  36587. var hasRequiredProcessor$1;
  36588. function requireProcessor$1 () {
  36589. if (hasRequiredProcessor$1) return processor$1;
  36590. hasRequiredProcessor$1 = 1;
  36591. let Document = /*@__PURE__*/ requireDocument();
  36592. let LazyResult = /*@__PURE__*/ requireLazyResult();
  36593. let NoWorkResult = /*@__PURE__*/ requireNoWorkResult();
  36594. let Root = /*@__PURE__*/ requireRoot$1();
  36595. class Processor {
  36596. constructor(plugins = []) {
  36597. this.version = '8.5.15';
  36598. this.plugins = this.normalize(plugins);
  36599. }
  36600. normalize(plugins) {
  36601. let normalized = [];
  36602. for (let i of plugins) {
  36603. if (i.postcss === true) {
  36604. i = i();
  36605. } else if (i.postcss) {
  36606. i = i.postcss;
  36607. }
  36608. if (typeof i === 'object' && Array.isArray(i.plugins)) {
  36609. normalized = normalized.concat(i.plugins);
  36610. } else if (typeof i === 'object' && i.postcssPlugin) {
  36611. normalized.push(i);
  36612. } else if (typeof i === 'function') {
  36613. normalized.push(i);
  36614. } else if (typeof i === 'object' && (i.parse || i.stringify)) {
  36615. if (browser$1.env.NODE_ENV !== 'production') {
  36616. throw new Error(
  36617. 'PostCSS syntaxes cannot be used as plugins. Instead, please use ' +
  36618. 'one of the syntax/parser/stringifier options as outlined ' +
  36619. 'in your PostCSS runner documentation.'
  36620. )
  36621. }
  36622. } else {
  36623. throw new Error(i + ' is not a PostCSS plugin')
  36624. }
  36625. }
  36626. return normalized
  36627. }
  36628. process(css, opts = {}) {
  36629. if (
  36630. !this.plugins.length &&
  36631. !opts.parser &&
  36632. !opts.stringifier &&
  36633. !opts.syntax
  36634. ) {
  36635. return new NoWorkResult(this, css, opts)
  36636. } else {
  36637. return new LazyResult(this, css, opts)
  36638. }
  36639. }
  36640. use(plugin) {
  36641. this.plugins = this.plugins.concat(this.normalize([plugin]));
  36642. return this
  36643. }
  36644. }
  36645. processor$1 = Processor;
  36646. Processor.default = Processor;
  36647. Root.registerProcessor(Processor);
  36648. Document.registerProcessor(Processor);
  36649. return processor$1;
  36650. }
  36651. var postcss_1;
  36652. var hasRequiredPostcss;
  36653. function requirePostcss () {
  36654. if (hasRequiredPostcss) return postcss_1;
  36655. hasRequiredPostcss = 1;
  36656. let AtRule = /*@__PURE__*/ requireAtRule();
  36657. let Comment = /*@__PURE__*/ requireComment$1();
  36658. let Container = /*@__PURE__*/ requireContainer$1();
  36659. let CssSyntaxError = /*@__PURE__*/ requireCssSyntaxError();
  36660. let Declaration = /*@__PURE__*/ requireDeclaration();
  36661. let Document = /*@__PURE__*/ requireDocument();
  36662. let fromJSON = /*@__PURE__*/ requireFromJSON();
  36663. let Input = /*@__PURE__*/ requireInput();
  36664. let LazyResult = /*@__PURE__*/ requireLazyResult();
  36665. let list = /*@__PURE__*/ requireList();
  36666. let Node = /*@__PURE__*/ requireNode$2();
  36667. let parse = /*@__PURE__*/ requireParse();
  36668. let Processor = /*@__PURE__*/ requireProcessor$1();
  36669. let Result = /*@__PURE__*/ requireResult();
  36670. let Root = /*@__PURE__*/ requireRoot$1();
  36671. let Rule = /*@__PURE__*/ requireRule();
  36672. let stringify = /*@__PURE__*/ requireStringify();
  36673. let Warning = /*@__PURE__*/ requireWarning();
  36674. function postcss(...plugins) {
  36675. if (plugins.length === 1 && Array.isArray(plugins[0])) {
  36676. plugins = plugins[0];
  36677. }
  36678. return new Processor(plugins)
  36679. }
  36680. postcss.plugin = function plugin(name, initializer) {
  36681. let warningPrinted = false;
  36682. function creator(...args) {
  36683. // eslint-disable-next-line no-console
  36684. if (console && console.warn && !warningPrinted) {
  36685. warningPrinted = true;
  36686. // eslint-disable-next-line no-console
  36687. console.warn(
  36688. name +
  36689. ': postcss.plugin was deprecated. Migration guide:\n' +
  36690. 'https://evilmartians.com/chronicles/postcss-8-plugin-migration'
  36691. );
  36692. if (browser$1.env.LANG && browser$1.env.LANG.startsWith('cn')) {
  36693. /* c8 ignore next 7 */
  36694. // eslint-disable-next-line no-console
  36695. console.warn(
  36696. name +
  36697. ': 里面 postcss.plugin 被弃用. 迁移指南:\n' +
  36698. 'https://www.w3ctech.com/topic/2226'
  36699. );
  36700. }
  36701. }
  36702. let transformer = initializer(...args);
  36703. transformer.postcssPlugin = name;
  36704. transformer.postcssVersion = new Processor().version;
  36705. return transformer
  36706. }
  36707. let cache;
  36708. Object.defineProperty(creator, 'postcss', {
  36709. get() {
  36710. if (!cache) cache = creator();
  36711. return cache
  36712. }
  36713. });
  36714. creator.process = function (css, processOpts, pluginOpts) {
  36715. return postcss([creator(pluginOpts)]).process(css, processOpts)
  36716. };
  36717. return creator
  36718. };
  36719. postcss.stringify = stringify;
  36720. postcss.parse = parse;
  36721. postcss.fromJSON = fromJSON;
  36722. postcss.list = list;
  36723. postcss.comment = defaults => new Comment(defaults);
  36724. postcss.atRule = defaults => new AtRule(defaults);
  36725. postcss.decl = defaults => new Declaration(defaults);
  36726. postcss.rule = defaults => new Rule(defaults);
  36727. postcss.root = defaults => new Root(defaults);
  36728. postcss.document = defaults => new Document(defaults);
  36729. postcss.CssSyntaxError = CssSyntaxError;
  36730. postcss.Declaration = Declaration;
  36731. postcss.Container = Container;
  36732. postcss.Processor = Processor;
  36733. postcss.Document = Document;
  36734. postcss.Comment = Comment;
  36735. postcss.Warning = Warning;
  36736. postcss.AtRule = AtRule;
  36737. postcss.Result = Result;
  36738. postcss.Input = Input;
  36739. postcss.Rule = Rule;
  36740. postcss.Root = Root;
  36741. postcss.Node = Node;
  36742. LazyResult.registerPostcss(postcss);
  36743. postcss_1 = postcss;
  36744. postcss.default = postcss;
  36745. return postcss_1;
  36746. }
  36747. var postcssExports = /*@__PURE__*/ requirePostcss();
  36748. var postcss = /*@__PURE__*/getDefaultExportFromCjs(postcssExports);
  36749. postcss.stringify;
  36750. postcss.fromJSON;
  36751. postcss.plugin;
  36752. postcss.parse;
  36753. postcss.list;
  36754. postcss.document;
  36755. postcss.comment;
  36756. postcss.atRule;
  36757. postcss.rule;
  36758. postcss.decl;
  36759. postcss.root;
  36760. postcss.CssSyntaxError;
  36761. postcss.Declaration;
  36762. postcss.Container;
  36763. postcss.Processor;
  36764. postcss.Document;
  36765. postcss.Comment;
  36766. postcss.Warning;
  36767. postcss.AtRule;
  36768. postcss.Result;
  36769. postcss.Input;
  36770. const Rule = postcss.Rule;
  36771. postcss.Root;
  36772. postcss.Node;
  36773. const trimPlugin = () => {
  36774. return {
  36775. postcssPlugin: "vue-sfc-trim",
  36776. Once(root) {
  36777. root.walk(({ type, raws }) => {
  36778. if (type === "rule" || type === "atrule") {
  36779. if (raws.before) raws.before = "\n";
  36780. if ("after" in raws && raws.after) raws.after = "\n";
  36781. }
  36782. });
  36783. }
  36784. };
  36785. };
  36786. trimPlugin.postcss = true;
  36787. var dist = {exports: {}};
  36788. var processor = {exports: {}};
  36789. var parser = {exports: {}};
  36790. var root = {exports: {}};
  36791. var container = {exports: {}};
  36792. var node$1 = {exports: {}};
  36793. var util$1 = {};
  36794. var unesc = {exports: {}};
  36795. var hasRequiredUnesc;
  36796. function requireUnesc () {
  36797. if (hasRequiredUnesc) return unesc.exports;
  36798. hasRequiredUnesc = 1;
  36799. (function (module, exports) {
  36800. exports.__esModule = true;
  36801. exports["default"] = unesc;
  36802. // Many thanks for this post which made this migration much easier.
  36803. // https://mathiasbynens.be/notes/css-escapes
  36804. /**
  36805. *
  36806. * @param {string} str
  36807. * @returns {[string, number]|undefined}
  36808. */
  36809. function gobbleHex(str) {
  36810. var lower = str.toLowerCase();
  36811. var hex = '';
  36812. var spaceTerminated = false;
  36813. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  36814. var code = lower.charCodeAt(i);
  36815. // check to see if we are dealing with a valid hex char [a-f|0-9]
  36816. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
  36817. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  36818. spaceTerminated = code === 32;
  36819. if (!valid) {
  36820. break;
  36821. }
  36822. hex += lower[i];
  36823. }
  36824. if (hex.length === 0) {
  36825. return undefined;
  36826. }
  36827. var codePoint = parseInt(hex, 16);
  36828. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
  36829. // Add special case for
  36830. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  36831. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  36832. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  36833. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  36834. }
  36835. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  36836. }
  36837. var CONTAINS_ESCAPE = /\\/;
  36838. function unesc(str) {
  36839. var needToProcess = CONTAINS_ESCAPE.test(str);
  36840. if (!needToProcess) {
  36841. return str;
  36842. }
  36843. var ret = "";
  36844. for (var i = 0; i < str.length; i++) {
  36845. if (str[i] === "\\") {
  36846. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  36847. if (gobbled !== undefined) {
  36848. ret += gobbled[0];
  36849. i += gobbled[1];
  36850. continue;
  36851. }
  36852. // Retain a pair of \\ if double escaped `\\\\`
  36853. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  36854. if (str[i + 1] === "\\") {
  36855. ret += "\\";
  36856. i++;
  36857. continue;
  36858. }
  36859. // if \\ is at the end of the string retain it
  36860. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  36861. if (str.length === i + 1) {
  36862. ret += str[i];
  36863. }
  36864. continue;
  36865. }
  36866. ret += str[i];
  36867. }
  36868. return ret;
  36869. }
  36870. module.exports = exports.default;
  36871. } (unesc, unesc.exports));
  36872. return unesc.exports;
  36873. }
  36874. var getProp = {exports: {}};
  36875. var hasRequiredGetProp;
  36876. function requireGetProp () {
  36877. if (hasRequiredGetProp) return getProp.exports;
  36878. hasRequiredGetProp = 1;
  36879. (function (module, exports) {
  36880. exports.__esModule = true;
  36881. exports["default"] = getProp;
  36882. function getProp(obj) {
  36883. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  36884. props[_key - 1] = arguments[_key];
  36885. }
  36886. while (props.length > 0) {
  36887. var prop = props.shift();
  36888. if (!obj[prop]) {
  36889. return undefined;
  36890. }
  36891. obj = obj[prop];
  36892. }
  36893. return obj;
  36894. }
  36895. module.exports = exports.default;
  36896. } (getProp, getProp.exports));
  36897. return getProp.exports;
  36898. }
  36899. var ensureObject = {exports: {}};
  36900. var hasRequiredEnsureObject;
  36901. function requireEnsureObject () {
  36902. if (hasRequiredEnsureObject) return ensureObject.exports;
  36903. hasRequiredEnsureObject = 1;
  36904. (function (module, exports) {
  36905. exports.__esModule = true;
  36906. exports["default"] = ensureObject;
  36907. function ensureObject(obj) {
  36908. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  36909. props[_key - 1] = arguments[_key];
  36910. }
  36911. while (props.length > 0) {
  36912. var prop = props.shift();
  36913. if (!obj[prop]) {
  36914. obj[prop] = {};
  36915. }
  36916. obj = obj[prop];
  36917. }
  36918. }
  36919. module.exports = exports.default;
  36920. } (ensureObject, ensureObject.exports));
  36921. return ensureObject.exports;
  36922. }
  36923. var stripComments = {exports: {}};
  36924. var hasRequiredStripComments;
  36925. function requireStripComments () {
  36926. if (hasRequiredStripComments) return stripComments.exports;
  36927. hasRequiredStripComments = 1;
  36928. (function (module, exports) {
  36929. exports.__esModule = true;
  36930. exports["default"] = stripComments;
  36931. function stripComments(str) {
  36932. var s = "";
  36933. var commentStart = str.indexOf("/*");
  36934. var lastEnd = 0;
  36935. while (commentStart >= 0) {
  36936. s = s + str.slice(lastEnd, commentStart);
  36937. var commentEnd = str.indexOf("*/", commentStart + 2);
  36938. if (commentEnd < 0) {
  36939. return s;
  36940. }
  36941. lastEnd = commentEnd + 2;
  36942. commentStart = str.indexOf("/*", lastEnd);
  36943. }
  36944. s = s + str.slice(lastEnd);
  36945. return s;
  36946. }
  36947. module.exports = exports.default;
  36948. } (stripComments, stripComments.exports));
  36949. return stripComments.exports;
  36950. }
  36951. var hasRequiredUtil$1;
  36952. function requireUtil$1 () {
  36953. if (hasRequiredUtil$1) return util$1;
  36954. hasRequiredUtil$1 = 1;
  36955. util$1.__esModule = true;
  36956. util$1.unesc = util$1.stripComments = util$1.getProp = util$1.ensureObject = void 0;
  36957. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc());
  36958. util$1.unesc = _unesc["default"];
  36959. var _getProp = _interopRequireDefault(/*@__PURE__*/ requireGetProp());
  36960. util$1.getProp = _getProp["default"];
  36961. var _ensureObject = _interopRequireDefault(/*@__PURE__*/ requireEnsureObject());
  36962. util$1.ensureObject = _ensureObject["default"];
  36963. var _stripComments = _interopRequireDefault(/*@__PURE__*/ requireStripComments());
  36964. util$1.stripComments = _stripComments["default"];
  36965. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  36966. return util$1;
  36967. }
  36968. var hasRequiredNode$1;
  36969. function requireNode$1 () {
  36970. if (hasRequiredNode$1) return node$1.exports;
  36971. hasRequiredNode$1 = 1;
  36972. (function (module, exports) {
  36973. exports.__esModule = true;
  36974. exports["default"] = void 0;
  36975. var _util = /*@__PURE__*/ requireUtil$1();
  36976. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  36977. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  36978. var cloneNode = function cloneNode(obj, parent) {
  36979. if (typeof obj !== 'object' || obj === null) {
  36980. return obj;
  36981. }
  36982. var cloned = new obj.constructor();
  36983. for (var i in obj) {
  36984. if (!obj.hasOwnProperty(i)) {
  36985. continue;
  36986. }
  36987. var value = obj[i];
  36988. var type = typeof value;
  36989. if (i === 'parent' && type === 'object') {
  36990. if (parent) {
  36991. cloned[i] = parent;
  36992. }
  36993. } else if (value instanceof Array) {
  36994. cloned[i] = value.map(function (j) {
  36995. return cloneNode(j, cloned);
  36996. });
  36997. } else {
  36998. cloned[i] = cloneNode(value, cloned);
  36999. }
  37000. }
  37001. return cloned;
  37002. };
  37003. var Node = /*#__PURE__*/function () {
  37004. function Node(opts) {
  37005. if (opts === void 0) {
  37006. opts = {};
  37007. }
  37008. Object.assign(this, opts);
  37009. this.spaces = this.spaces || {};
  37010. this.spaces.before = this.spaces.before || '';
  37011. this.spaces.after = this.spaces.after || '';
  37012. }
  37013. var _proto = Node.prototype;
  37014. _proto.remove = function remove() {
  37015. if (this.parent) {
  37016. this.parent.removeChild(this);
  37017. }
  37018. this.parent = undefined;
  37019. return this;
  37020. };
  37021. _proto.replaceWith = function replaceWith() {
  37022. if (this.parent) {
  37023. for (var index in arguments) {
  37024. this.parent.insertBefore(this, arguments[index]);
  37025. }
  37026. this.remove();
  37027. }
  37028. return this;
  37029. };
  37030. _proto.next = function next() {
  37031. return this.parent.at(this.parent.index(this) + 1);
  37032. };
  37033. _proto.prev = function prev() {
  37034. return this.parent.at(this.parent.index(this) - 1);
  37035. };
  37036. _proto.clone = function clone(overrides) {
  37037. if (overrides === void 0) {
  37038. overrides = {};
  37039. }
  37040. var cloned = cloneNode(this);
  37041. for (var name in overrides) {
  37042. cloned[name] = overrides[name];
  37043. }
  37044. return cloned;
  37045. }
  37046. /**
  37047. * Some non-standard syntax doesn't follow normal escaping rules for css.
  37048. * This allows non standard syntax to be appended to an existing property
  37049. * by specifying the escaped value. By specifying the escaped value,
  37050. * illegal characters are allowed to be directly inserted into css output.
  37051. * @param {string} name the property to set
  37052. * @param {any} value the unescaped value of the property
  37053. * @param {string} valueEscaped optional. the escaped value of the property.
  37054. */;
  37055. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  37056. if (!this.raws) {
  37057. this.raws = {};
  37058. }
  37059. var originalValue = this[name];
  37060. var originalEscaped = this.raws[name];
  37061. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  37062. if (originalEscaped || valueEscaped !== value) {
  37063. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  37064. } else {
  37065. delete this.raws[name]; // delete any escaped value that was created by the setter.
  37066. }
  37067. }
  37068. /**
  37069. * Some non-standard syntax doesn't follow normal escaping rules for css.
  37070. * This allows the escaped value to be specified directly, allowing illegal
  37071. * characters to be directly inserted into css output.
  37072. * @param {string} name the property to set
  37073. * @param {any} value the unescaped value of the property
  37074. * @param {string} valueEscaped the escaped value of the property.
  37075. */;
  37076. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  37077. if (!this.raws) {
  37078. this.raws = {};
  37079. }
  37080. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  37081. this.raws[name] = valueEscaped;
  37082. }
  37083. /**
  37084. * When you want a value to passed through to CSS directly. This method
  37085. * deletes the corresponding raw value causing the stringifier to fallback
  37086. * to the unescaped value.
  37087. * @param {string} name the property to set.
  37088. * @param {any} value The value that is both escaped and unescaped.
  37089. */;
  37090. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  37091. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  37092. if (this.raws) {
  37093. delete this.raws[name];
  37094. }
  37095. }
  37096. /**
  37097. *
  37098. * @param {number} line The number (starting with 1)
  37099. * @param {number} column The column number (starting with 1)
  37100. */;
  37101. _proto.isAtPosition = function isAtPosition(line, column) {
  37102. if (this.source && this.source.start && this.source.end) {
  37103. if (this.source.start.line > line) {
  37104. return false;
  37105. }
  37106. if (this.source.end.line < line) {
  37107. return false;
  37108. }
  37109. if (this.source.start.line === line && this.source.start.column > column) {
  37110. return false;
  37111. }
  37112. if (this.source.end.line === line && this.source.end.column < column) {
  37113. return false;
  37114. }
  37115. return true;
  37116. }
  37117. return undefined;
  37118. };
  37119. _proto.stringifyProperty = function stringifyProperty(name) {
  37120. return this.raws && this.raws[name] || this[name];
  37121. };
  37122. _proto.valueToString = function valueToString() {
  37123. return String(this.stringifyProperty("value"));
  37124. };
  37125. _proto.toString = function toString() {
  37126. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  37127. };
  37128. _createClass(Node, [{
  37129. key: "rawSpaceBefore",
  37130. get: function get() {
  37131. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  37132. if (rawSpace === undefined) {
  37133. rawSpace = this.spaces && this.spaces.before;
  37134. }
  37135. return rawSpace || "";
  37136. },
  37137. set: function set(raw) {
  37138. (0, _util.ensureObject)(this, "raws", "spaces");
  37139. this.raws.spaces.before = raw;
  37140. }
  37141. }, {
  37142. key: "rawSpaceAfter",
  37143. get: function get() {
  37144. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  37145. if (rawSpace === undefined) {
  37146. rawSpace = this.spaces.after;
  37147. }
  37148. return rawSpace || "";
  37149. },
  37150. set: function set(raw) {
  37151. (0, _util.ensureObject)(this, "raws", "spaces");
  37152. this.raws.spaces.after = raw;
  37153. }
  37154. }]);
  37155. return Node;
  37156. }();
  37157. exports["default"] = Node;
  37158. module.exports = exports.default;
  37159. } (node$1, node$1.exports));
  37160. return node$1.exports;
  37161. }
  37162. var types = {};
  37163. var hasRequiredTypes;
  37164. function requireTypes () {
  37165. if (hasRequiredTypes) return types;
  37166. hasRequiredTypes = 1;
  37167. types.__esModule = true;
  37168. types.UNIVERSAL = types.TAG = types.STRING = types.SELECTOR = types.ROOT = types.PSEUDO = types.NESTING = types.ID = types.COMMENT = types.COMBINATOR = types.CLASS = types.ATTRIBUTE = void 0;
  37169. var TAG = 'tag';
  37170. types.TAG = TAG;
  37171. var STRING = 'string';
  37172. types.STRING = STRING;
  37173. var SELECTOR = 'selector';
  37174. types.SELECTOR = SELECTOR;
  37175. var ROOT = 'root';
  37176. types.ROOT = ROOT;
  37177. var PSEUDO = 'pseudo';
  37178. types.PSEUDO = PSEUDO;
  37179. var NESTING = 'nesting';
  37180. types.NESTING = NESTING;
  37181. var ID = 'id';
  37182. types.ID = ID;
  37183. var COMMENT = 'comment';
  37184. types.COMMENT = COMMENT;
  37185. var COMBINATOR = 'combinator';
  37186. types.COMBINATOR = COMBINATOR;
  37187. var CLASS = 'class';
  37188. types.CLASS = CLASS;
  37189. var ATTRIBUTE = 'attribute';
  37190. types.ATTRIBUTE = ATTRIBUTE;
  37191. var UNIVERSAL = 'universal';
  37192. types.UNIVERSAL = UNIVERSAL;
  37193. return types;
  37194. }
  37195. var hasRequiredContainer;
  37196. function requireContainer () {
  37197. if (hasRequiredContainer) return container.exports;
  37198. hasRequiredContainer = 1;
  37199. (function (module, exports) {
  37200. exports.__esModule = true;
  37201. exports["default"] = void 0;
  37202. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$1());
  37203. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes());
  37204. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  37205. function _interopRequireWildcard(obj, nodeInterop) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  37206. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  37207. function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike) { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
  37208. function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  37209. function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
  37210. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  37211. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  37212. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  37213. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  37214. var Container = /*#__PURE__*/function (_Node) {
  37215. _inheritsLoose(Container, _Node);
  37216. function Container(opts) {
  37217. var _this;
  37218. _this = _Node.call(this, opts) || this;
  37219. if (!_this.nodes) {
  37220. _this.nodes = [];
  37221. }
  37222. return _this;
  37223. }
  37224. var _proto = Container.prototype;
  37225. _proto.append = function append(selector) {
  37226. selector.parent = this;
  37227. this.nodes.push(selector);
  37228. return this;
  37229. };
  37230. _proto.prepend = function prepend(selector) {
  37231. selector.parent = this;
  37232. this.nodes.unshift(selector);
  37233. for (var id in this.indexes) {
  37234. this.indexes[id]++;
  37235. }
  37236. return this;
  37237. };
  37238. _proto.at = function at(index) {
  37239. return this.nodes[index];
  37240. };
  37241. _proto.index = function index(child) {
  37242. if (typeof child === 'number') {
  37243. return child;
  37244. }
  37245. return this.nodes.indexOf(child);
  37246. };
  37247. _proto.removeChild = function removeChild(child) {
  37248. child = this.index(child);
  37249. this.at(child).parent = undefined;
  37250. this.nodes.splice(child, 1);
  37251. var index;
  37252. for (var id in this.indexes) {
  37253. index = this.indexes[id];
  37254. if (index >= child) {
  37255. this.indexes[id] = index - 1;
  37256. }
  37257. }
  37258. return this;
  37259. };
  37260. _proto.removeAll = function removeAll() {
  37261. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  37262. var node = _step.value;
  37263. node.parent = undefined;
  37264. }
  37265. this.nodes = [];
  37266. return this;
  37267. };
  37268. _proto.empty = function empty() {
  37269. return this.removeAll();
  37270. };
  37271. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  37272. var _this$nodes;
  37273. newNode.parent = this;
  37274. var oldIndex = this.index(oldNode);
  37275. var resetNode = [];
  37276. for (var i = 2; i < arguments.length; i++) {
  37277. resetNode.push(arguments[i]);
  37278. }
  37279. (_this$nodes = this.nodes).splice.apply(_this$nodes, [oldIndex + 1, 0, newNode].concat(resetNode));
  37280. newNode.parent = this;
  37281. var index;
  37282. for (var id in this.indexes) {
  37283. index = this.indexes[id];
  37284. if (oldIndex < index) {
  37285. this.indexes[id] = index + arguments.length - 1;
  37286. }
  37287. }
  37288. return this;
  37289. };
  37290. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  37291. var _this$nodes2;
  37292. newNode.parent = this;
  37293. var oldIndex = this.index(oldNode);
  37294. var resetNode = [];
  37295. for (var i = 2; i < arguments.length; i++) {
  37296. resetNode.push(arguments[i]);
  37297. }
  37298. (_this$nodes2 = this.nodes).splice.apply(_this$nodes2, [oldIndex, 0, newNode].concat(resetNode));
  37299. newNode.parent = this;
  37300. var index;
  37301. for (var id in this.indexes) {
  37302. index = this.indexes[id];
  37303. if (index >= oldIndex) {
  37304. this.indexes[id] = index + arguments.length - 1;
  37305. }
  37306. }
  37307. return this;
  37308. };
  37309. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  37310. var found = undefined;
  37311. this.each(function (node) {
  37312. if (node.atPosition) {
  37313. var foundChild = node.atPosition(line, col);
  37314. if (foundChild) {
  37315. found = foundChild;
  37316. return false;
  37317. }
  37318. } else if (node.isAtPosition(line, col)) {
  37319. found = node;
  37320. return false;
  37321. }
  37322. });
  37323. return found;
  37324. }
  37325. /**
  37326. * Return the most specific node at the line and column number given.
  37327. * The source location is based on the original parsed location, locations aren't
  37328. * updated as selector nodes are mutated.
  37329. *
  37330. * Note that this location is relative to the location of the first character
  37331. * of the selector, and not the location of the selector in the overall document
  37332. * when used in conjunction with postcss.
  37333. *
  37334. * If not found, returns undefined.
  37335. * @param {number} line The line number of the node to find. (1-based index)
  37336. * @param {number} col The column number of the node to find. (1-based index)
  37337. */;
  37338. _proto.atPosition = function atPosition(line, col) {
  37339. if (this.isAtPosition(line, col)) {
  37340. return this._findChildAtPosition(line, col) || this;
  37341. } else {
  37342. return undefined;
  37343. }
  37344. };
  37345. _proto._inferEndPosition = function _inferEndPosition() {
  37346. if (this.last && this.last.source && this.last.source.end) {
  37347. this.source = this.source || {};
  37348. this.source.end = this.source.end || {};
  37349. Object.assign(this.source.end, this.last.source.end);
  37350. }
  37351. };
  37352. _proto.each = function each(callback) {
  37353. if (!this.lastEach) {
  37354. this.lastEach = 0;
  37355. }
  37356. if (!this.indexes) {
  37357. this.indexes = {};
  37358. }
  37359. this.lastEach++;
  37360. var id = this.lastEach;
  37361. this.indexes[id] = 0;
  37362. if (!this.length) {
  37363. return undefined;
  37364. }
  37365. var index, result;
  37366. while (this.indexes[id] < this.length) {
  37367. index = this.indexes[id];
  37368. result = callback(this.at(index), index);
  37369. if (result === false) {
  37370. break;
  37371. }
  37372. this.indexes[id] += 1;
  37373. }
  37374. delete this.indexes[id];
  37375. if (result === false) {
  37376. return false;
  37377. }
  37378. };
  37379. _proto.walk = function walk(callback) {
  37380. return this.each(function (node, i) {
  37381. var result = callback(node, i);
  37382. if (result !== false && node.length) {
  37383. result = node.walk(callback);
  37384. }
  37385. if (result === false) {
  37386. return false;
  37387. }
  37388. });
  37389. };
  37390. _proto.walkAttributes = function walkAttributes(callback) {
  37391. var _this2 = this;
  37392. return this.walk(function (selector) {
  37393. if (selector.type === types.ATTRIBUTE) {
  37394. return callback.call(_this2, selector);
  37395. }
  37396. });
  37397. };
  37398. _proto.walkClasses = function walkClasses(callback) {
  37399. var _this3 = this;
  37400. return this.walk(function (selector) {
  37401. if (selector.type === types.CLASS) {
  37402. return callback.call(_this3, selector);
  37403. }
  37404. });
  37405. };
  37406. _proto.walkCombinators = function walkCombinators(callback) {
  37407. var _this4 = this;
  37408. return this.walk(function (selector) {
  37409. if (selector.type === types.COMBINATOR) {
  37410. return callback.call(_this4, selector);
  37411. }
  37412. });
  37413. };
  37414. _proto.walkComments = function walkComments(callback) {
  37415. var _this5 = this;
  37416. return this.walk(function (selector) {
  37417. if (selector.type === types.COMMENT) {
  37418. return callback.call(_this5, selector);
  37419. }
  37420. });
  37421. };
  37422. _proto.walkIds = function walkIds(callback) {
  37423. var _this6 = this;
  37424. return this.walk(function (selector) {
  37425. if (selector.type === types.ID) {
  37426. return callback.call(_this6, selector);
  37427. }
  37428. });
  37429. };
  37430. _proto.walkNesting = function walkNesting(callback) {
  37431. var _this7 = this;
  37432. return this.walk(function (selector) {
  37433. if (selector.type === types.NESTING) {
  37434. return callback.call(_this7, selector);
  37435. }
  37436. });
  37437. };
  37438. _proto.walkPseudos = function walkPseudos(callback) {
  37439. var _this8 = this;
  37440. return this.walk(function (selector) {
  37441. if (selector.type === types.PSEUDO) {
  37442. return callback.call(_this8, selector);
  37443. }
  37444. });
  37445. };
  37446. _proto.walkTags = function walkTags(callback) {
  37447. var _this9 = this;
  37448. return this.walk(function (selector) {
  37449. if (selector.type === types.TAG) {
  37450. return callback.call(_this9, selector);
  37451. }
  37452. });
  37453. };
  37454. _proto.walkUniversals = function walkUniversals(callback) {
  37455. var _this10 = this;
  37456. return this.walk(function (selector) {
  37457. if (selector.type === types.UNIVERSAL) {
  37458. return callback.call(_this10, selector);
  37459. }
  37460. });
  37461. };
  37462. _proto.split = function split(callback) {
  37463. var _this11 = this;
  37464. var current = [];
  37465. return this.reduce(function (memo, node, index) {
  37466. var split = callback.call(_this11, node);
  37467. current.push(node);
  37468. if (split) {
  37469. memo.push(current);
  37470. current = [];
  37471. } else if (index === _this11.length - 1) {
  37472. memo.push(current);
  37473. }
  37474. return memo;
  37475. }, []);
  37476. };
  37477. _proto.map = function map(callback) {
  37478. return this.nodes.map(callback);
  37479. };
  37480. _proto.reduce = function reduce(callback, memo) {
  37481. return this.nodes.reduce(callback, memo);
  37482. };
  37483. _proto.every = function every(callback) {
  37484. return this.nodes.every(callback);
  37485. };
  37486. _proto.some = function some(callback) {
  37487. return this.nodes.some(callback);
  37488. };
  37489. _proto.filter = function filter(callback) {
  37490. return this.nodes.filter(callback);
  37491. };
  37492. _proto.sort = function sort(callback) {
  37493. return this.nodes.sort(callback);
  37494. };
  37495. _proto.toString = function toString() {
  37496. return this.map(String).join('');
  37497. };
  37498. _createClass(Container, [{
  37499. key: "first",
  37500. get: function get() {
  37501. return this.at(0);
  37502. }
  37503. }, {
  37504. key: "last",
  37505. get: function get() {
  37506. return this.at(this.length - 1);
  37507. }
  37508. }, {
  37509. key: "length",
  37510. get: function get() {
  37511. return this.nodes.length;
  37512. }
  37513. }]);
  37514. return Container;
  37515. }(_node["default"]);
  37516. exports["default"] = Container;
  37517. module.exports = exports.default;
  37518. } (container, container.exports));
  37519. return container.exports;
  37520. }
  37521. var hasRequiredRoot;
  37522. function requireRoot () {
  37523. if (hasRequiredRoot) return root.exports;
  37524. hasRequiredRoot = 1;
  37525. (function (module, exports) {
  37526. exports.__esModule = true;
  37527. exports["default"] = void 0;
  37528. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  37529. var _types = /*@__PURE__*/ requireTypes();
  37530. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  37531. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  37532. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  37533. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  37534. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  37535. var Root = /*#__PURE__*/function (_Container) {
  37536. _inheritsLoose(Root, _Container);
  37537. function Root(opts) {
  37538. var _this;
  37539. _this = _Container.call(this, opts) || this;
  37540. _this.type = _types.ROOT;
  37541. return _this;
  37542. }
  37543. var _proto = Root.prototype;
  37544. _proto.toString = function toString() {
  37545. var str = this.reduce(function (memo, selector) {
  37546. memo.push(String(selector));
  37547. return memo;
  37548. }, []).join(',');
  37549. return this.trailingComma ? str + ',' : str;
  37550. };
  37551. _proto.error = function error(message, options) {
  37552. if (this._error) {
  37553. return this._error(message, options);
  37554. } else {
  37555. return new Error(message);
  37556. }
  37557. };
  37558. _createClass(Root, [{
  37559. key: "errorGenerator",
  37560. set: function set(handler) {
  37561. this._error = handler;
  37562. }
  37563. }]);
  37564. return Root;
  37565. }(_container["default"]);
  37566. exports["default"] = Root;
  37567. module.exports = exports.default;
  37568. } (root, root.exports));
  37569. return root.exports;
  37570. }
  37571. var selector = {exports: {}};
  37572. var hasRequiredSelector;
  37573. function requireSelector () {
  37574. if (hasRequiredSelector) return selector.exports;
  37575. hasRequiredSelector = 1;
  37576. (function (module, exports) {
  37577. exports.__esModule = true;
  37578. exports["default"] = void 0;
  37579. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  37580. var _types = /*@__PURE__*/ requireTypes();
  37581. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  37582. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  37583. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  37584. var Selector = /*#__PURE__*/function (_Container) {
  37585. _inheritsLoose(Selector, _Container);
  37586. function Selector(opts) {
  37587. var _this;
  37588. _this = _Container.call(this, opts) || this;
  37589. _this.type = _types.SELECTOR;
  37590. return _this;
  37591. }
  37592. return Selector;
  37593. }(_container["default"]);
  37594. exports["default"] = Selector;
  37595. module.exports = exports.default;
  37596. } (selector, selector.exports));
  37597. return selector.exports;
  37598. }
  37599. var className = {exports: {}};
  37600. /*! https://mths.be/cssesc v3.0.0 by @mathias */
  37601. var cssesc_1;
  37602. var hasRequiredCssesc;
  37603. function requireCssesc () {
  37604. if (hasRequiredCssesc) return cssesc_1;
  37605. hasRequiredCssesc = 1;
  37606. var object = {};
  37607. var hasOwnProperty = object.hasOwnProperty;
  37608. var merge = function merge(options, defaults) {
  37609. if (!options) {
  37610. return defaults;
  37611. }
  37612. var result = {};
  37613. for (var key in defaults) {
  37614. // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
  37615. // only recognized option names are used.
  37616. result[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key];
  37617. }
  37618. return result;
  37619. };
  37620. var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
  37621. var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
  37622. var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  37623. // https://mathiasbynens.be/notes/css-escapes#css
  37624. var cssesc = function cssesc(string, options) {
  37625. options = merge(options, cssesc.options);
  37626. if (options.quotes != 'single' && options.quotes != 'double') {
  37627. options.quotes = 'single';
  37628. }
  37629. var quote = options.quotes == 'double' ? '"' : '\'';
  37630. var isIdentifier = options.isIdentifier;
  37631. var firstChar = string.charAt(0);
  37632. var output = '';
  37633. var counter = 0;
  37634. var length = string.length;
  37635. while (counter < length) {
  37636. var character = string.charAt(counter++);
  37637. var codePoint = character.charCodeAt();
  37638. var value = void 0;
  37639. // If it’s not a printable ASCII character…
  37640. if (codePoint < 0x20 || codePoint > 0x7E) {
  37641. if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
  37642. // It’s a high surrogate, and there is a next character.
  37643. var extra = string.charCodeAt(counter++);
  37644. if ((extra & 0xFC00) == 0xDC00) {
  37645. // next character is low surrogate
  37646. codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
  37647. } else {
  37648. // It’s an unmatched surrogate; only append this code unit, in case
  37649. // the next code unit is the high surrogate of a surrogate pair.
  37650. counter--;
  37651. }
  37652. }
  37653. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  37654. } else {
  37655. if (options.escapeEverything) {
  37656. if (regexAnySingleEscape.test(character)) {
  37657. value = '\\' + character;
  37658. } else {
  37659. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  37660. }
  37661. } else if (/[\t\n\f\r\x0B]/.test(character)) {
  37662. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  37663. } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
  37664. value = '\\' + character;
  37665. } else {
  37666. value = character;
  37667. }
  37668. }
  37669. output += value;
  37670. }
  37671. if (isIdentifier) {
  37672. if (/^-[-\d]/.test(output)) {
  37673. output = '\\-' + output.slice(1);
  37674. } else if (/\d/.test(firstChar)) {
  37675. output = '\\3' + firstChar + ' ' + output.slice(1);
  37676. }
  37677. }
  37678. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  37679. // since they’re redundant. Note that this is only possible if the escape
  37680. // sequence isn’t preceded by an odd number of backslashes.
  37681. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
  37682. if ($1 && $1.length % 2) {
  37683. // It’s not safe to remove the space, so don’t.
  37684. return $0;
  37685. }
  37686. // Strip the space.
  37687. return ($1 || '') + $2;
  37688. });
  37689. if (!isIdentifier && options.wrap) {
  37690. return quote + output + quote;
  37691. }
  37692. return output;
  37693. };
  37694. // Expose default options (so they can be overridden globally).
  37695. cssesc.options = {
  37696. 'escapeEverything': false,
  37697. 'isIdentifier': false,
  37698. 'quotes': 'single',
  37699. 'wrap': false
  37700. };
  37701. cssesc.version = '3.0.0';
  37702. cssesc_1 = cssesc;
  37703. return cssesc_1;
  37704. }
  37705. var hasRequiredClassName;
  37706. function requireClassName () {
  37707. if (hasRequiredClassName) return className.exports;
  37708. hasRequiredClassName = 1;
  37709. (function (module, exports) {
  37710. exports.__esModule = true;
  37711. exports["default"] = void 0;
  37712. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  37713. var _util = /*@__PURE__*/ requireUtil$1();
  37714. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$1());
  37715. var _types = /*@__PURE__*/ requireTypes();
  37716. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  37717. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  37718. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  37719. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  37720. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  37721. var ClassName = /*#__PURE__*/function (_Node) {
  37722. _inheritsLoose(ClassName, _Node);
  37723. function ClassName(opts) {
  37724. var _this;
  37725. _this = _Node.call(this, opts) || this;
  37726. _this.type = _types.CLASS;
  37727. _this._constructed = true;
  37728. return _this;
  37729. }
  37730. var _proto = ClassName.prototype;
  37731. _proto.valueToString = function valueToString() {
  37732. return '.' + _Node.prototype.valueToString.call(this);
  37733. };
  37734. _createClass(ClassName, [{
  37735. key: "value",
  37736. get: function get() {
  37737. return this._value;
  37738. },
  37739. set: function set(v) {
  37740. if (this._constructed) {
  37741. var escaped = (0, _cssesc["default"])(v, {
  37742. isIdentifier: true
  37743. });
  37744. if (escaped !== v) {
  37745. (0, _util.ensureObject)(this, "raws");
  37746. this.raws.value = escaped;
  37747. } else if (this.raws) {
  37748. delete this.raws.value;
  37749. }
  37750. }
  37751. this._value = v;
  37752. }
  37753. }]);
  37754. return ClassName;
  37755. }(_node["default"]);
  37756. exports["default"] = ClassName;
  37757. module.exports = exports.default;
  37758. } (className, className.exports));
  37759. return className.exports;
  37760. }
  37761. var comment = {exports: {}};
  37762. var hasRequiredComment;
  37763. function requireComment () {
  37764. if (hasRequiredComment) return comment.exports;
  37765. hasRequiredComment = 1;
  37766. (function (module, exports) {
  37767. exports.__esModule = true;
  37768. exports["default"] = void 0;
  37769. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$1());
  37770. var _types = /*@__PURE__*/ requireTypes();
  37771. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  37772. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  37773. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  37774. var Comment = /*#__PURE__*/function (_Node) {
  37775. _inheritsLoose(Comment, _Node);
  37776. function Comment(opts) {
  37777. var _this;
  37778. _this = _Node.call(this, opts) || this;
  37779. _this.type = _types.COMMENT;
  37780. return _this;
  37781. }
  37782. return Comment;
  37783. }(_node["default"]);
  37784. exports["default"] = Comment;
  37785. module.exports = exports.default;
  37786. } (comment, comment.exports));
  37787. return comment.exports;
  37788. }
  37789. var id = {exports: {}};
  37790. var hasRequiredId;
  37791. function requireId () {
  37792. if (hasRequiredId) return id.exports;
  37793. hasRequiredId = 1;
  37794. (function (module, exports) {
  37795. exports.__esModule = true;
  37796. exports["default"] = void 0;
  37797. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$1());
  37798. var _types = /*@__PURE__*/ requireTypes();
  37799. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  37800. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  37801. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  37802. var ID = /*#__PURE__*/function (_Node) {
  37803. _inheritsLoose(ID, _Node);
  37804. function ID(opts) {
  37805. var _this;
  37806. _this = _Node.call(this, opts) || this;
  37807. _this.type = _types.ID;
  37808. return _this;
  37809. }
  37810. var _proto = ID.prototype;
  37811. _proto.valueToString = function valueToString() {
  37812. return '#' + _Node.prototype.valueToString.call(this);
  37813. };
  37814. return ID;
  37815. }(_node["default"]);
  37816. exports["default"] = ID;
  37817. module.exports = exports.default;
  37818. } (id, id.exports));
  37819. return id.exports;
  37820. }
  37821. var tag = {exports: {}};
  37822. var namespace = {exports: {}};
  37823. var hasRequiredNamespace;
  37824. function requireNamespace () {
  37825. if (hasRequiredNamespace) return namespace.exports;
  37826. hasRequiredNamespace = 1;
  37827. (function (module, exports) {
  37828. exports.__esModule = true;
  37829. exports["default"] = void 0;
  37830. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  37831. var _util = /*@__PURE__*/ requireUtil$1();
  37832. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$1());
  37833. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  37834. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  37835. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  37836. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  37837. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  37838. var Namespace = /*#__PURE__*/function (_Node) {
  37839. _inheritsLoose(Namespace, _Node);
  37840. function Namespace() {
  37841. return _Node.apply(this, arguments) || this;
  37842. }
  37843. var _proto = Namespace.prototype;
  37844. _proto.qualifiedName = function qualifiedName(value) {
  37845. if (this.namespace) {
  37846. return this.namespaceString + "|" + value;
  37847. } else {
  37848. return value;
  37849. }
  37850. };
  37851. _proto.valueToString = function valueToString() {
  37852. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  37853. };
  37854. _createClass(Namespace, [{
  37855. key: "namespace",
  37856. get: function get() {
  37857. return this._namespace;
  37858. },
  37859. set: function set(namespace) {
  37860. if (namespace === true || namespace === "*" || namespace === "&") {
  37861. this._namespace = namespace;
  37862. if (this.raws) {
  37863. delete this.raws.namespace;
  37864. }
  37865. return;
  37866. }
  37867. var escaped = (0, _cssesc["default"])(namespace, {
  37868. isIdentifier: true
  37869. });
  37870. this._namespace = namespace;
  37871. if (escaped !== namespace) {
  37872. (0, _util.ensureObject)(this, "raws");
  37873. this.raws.namespace = escaped;
  37874. } else if (this.raws) {
  37875. delete this.raws.namespace;
  37876. }
  37877. }
  37878. }, {
  37879. key: "ns",
  37880. get: function get() {
  37881. return this._namespace;
  37882. },
  37883. set: function set(namespace) {
  37884. this.namespace = namespace;
  37885. }
  37886. }, {
  37887. key: "namespaceString",
  37888. get: function get() {
  37889. if (this.namespace) {
  37890. var ns = this.stringifyProperty("namespace");
  37891. if (ns === true) {
  37892. return '';
  37893. } else {
  37894. return ns;
  37895. }
  37896. } else {
  37897. return '';
  37898. }
  37899. }
  37900. }]);
  37901. return Namespace;
  37902. }(_node["default"]);
  37903. exports["default"] = Namespace;
  37904. module.exports = exports.default;
  37905. } (namespace, namespace.exports));
  37906. return namespace.exports;
  37907. }
  37908. var hasRequiredTag;
  37909. function requireTag () {
  37910. if (hasRequiredTag) return tag.exports;
  37911. hasRequiredTag = 1;
  37912. (function (module, exports) {
  37913. exports.__esModule = true;
  37914. exports["default"] = void 0;
  37915. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  37916. var _types = /*@__PURE__*/ requireTypes();
  37917. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  37918. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  37919. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  37920. var Tag = /*#__PURE__*/function (_Namespace) {
  37921. _inheritsLoose(Tag, _Namespace);
  37922. function Tag(opts) {
  37923. var _this;
  37924. _this = _Namespace.call(this, opts) || this;
  37925. _this.type = _types.TAG;
  37926. return _this;
  37927. }
  37928. return Tag;
  37929. }(_namespace["default"]);
  37930. exports["default"] = Tag;
  37931. module.exports = exports.default;
  37932. } (tag, tag.exports));
  37933. return tag.exports;
  37934. }
  37935. var string = {exports: {}};
  37936. var hasRequiredString;
  37937. function requireString () {
  37938. if (hasRequiredString) return string.exports;
  37939. hasRequiredString = 1;
  37940. (function (module, exports) {
  37941. exports.__esModule = true;
  37942. exports["default"] = void 0;
  37943. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$1());
  37944. var _types = /*@__PURE__*/ requireTypes();
  37945. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  37946. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  37947. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  37948. var String = /*#__PURE__*/function (_Node) {
  37949. _inheritsLoose(String, _Node);
  37950. function String(opts) {
  37951. var _this;
  37952. _this = _Node.call(this, opts) || this;
  37953. _this.type = _types.STRING;
  37954. return _this;
  37955. }
  37956. return String;
  37957. }(_node["default"]);
  37958. exports["default"] = String;
  37959. module.exports = exports.default;
  37960. } (string, string.exports));
  37961. return string.exports;
  37962. }
  37963. var pseudo = {exports: {}};
  37964. var hasRequiredPseudo;
  37965. function requirePseudo () {
  37966. if (hasRequiredPseudo) return pseudo.exports;
  37967. hasRequiredPseudo = 1;
  37968. (function (module, exports) {
  37969. exports.__esModule = true;
  37970. exports["default"] = void 0;
  37971. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  37972. var _types = /*@__PURE__*/ requireTypes();
  37973. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  37974. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  37975. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  37976. var Pseudo = /*#__PURE__*/function (_Container) {
  37977. _inheritsLoose(Pseudo, _Container);
  37978. function Pseudo(opts) {
  37979. var _this;
  37980. _this = _Container.call(this, opts) || this;
  37981. _this.type = _types.PSEUDO;
  37982. return _this;
  37983. }
  37984. var _proto = Pseudo.prototype;
  37985. _proto.toString = function toString() {
  37986. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  37987. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  37988. };
  37989. return Pseudo;
  37990. }(_container["default"]);
  37991. exports["default"] = Pseudo;
  37992. module.exports = exports.default;
  37993. } (pseudo, pseudo.exports));
  37994. return pseudo.exports;
  37995. }
  37996. var attribute = {};
  37997. var node;
  37998. var hasRequiredNode;
  37999. function requireNode () {
  38000. if (hasRequiredNode) return node;
  38001. hasRequiredNode = 1;
  38002. /**
  38003. * For Node.js, simply re-export the core `util.deprecate` function.
  38004. */
  38005. node = require$$0.deprecate;
  38006. return node;
  38007. }
  38008. var hasRequiredAttribute;
  38009. function requireAttribute () {
  38010. if (hasRequiredAttribute) return attribute;
  38011. hasRequiredAttribute = 1;
  38012. (function (exports) {
  38013. exports.__esModule = true;
  38014. exports["default"] = void 0;
  38015. exports.unescapeValue = unescapeValue;
  38016. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  38017. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc());
  38018. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  38019. var _types = /*@__PURE__*/ requireTypes();
  38020. var _CSSESC_QUOTE_OPTIONS;
  38021. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  38022. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  38023. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  38024. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  38025. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  38026. var deprecate = /*@__PURE__*/ requireNode();
  38027. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  38028. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  38029. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  38030. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  38031. function unescapeValue(value) {
  38032. var deprecatedUsage = false;
  38033. var quoteMark = null;
  38034. var unescaped = value;
  38035. var m = unescaped.match(WRAPPED_IN_QUOTES);
  38036. if (m) {
  38037. quoteMark = m[1];
  38038. unescaped = m[2];
  38039. }
  38040. unescaped = (0, _unesc["default"])(unescaped);
  38041. if (unescaped !== value) {
  38042. deprecatedUsage = true;
  38043. }
  38044. return {
  38045. deprecatedUsage: deprecatedUsage,
  38046. unescaped: unescaped,
  38047. quoteMark: quoteMark
  38048. };
  38049. }
  38050. function handleDeprecatedContructorOpts(opts) {
  38051. if (opts.quoteMark !== undefined) {
  38052. return opts;
  38053. }
  38054. if (opts.value === undefined) {
  38055. return opts;
  38056. }
  38057. warnOfDeprecatedConstructor();
  38058. var _unescapeValue = unescapeValue(opts.value),
  38059. quoteMark = _unescapeValue.quoteMark,
  38060. unescaped = _unescapeValue.unescaped;
  38061. if (!opts.raws) {
  38062. opts.raws = {};
  38063. }
  38064. if (opts.raws.value === undefined) {
  38065. opts.raws.value = opts.value;
  38066. }
  38067. opts.value = unescaped;
  38068. opts.quoteMark = quoteMark;
  38069. return opts;
  38070. }
  38071. var Attribute = /*#__PURE__*/function (_Namespace) {
  38072. _inheritsLoose(Attribute, _Namespace);
  38073. function Attribute(opts) {
  38074. var _this;
  38075. if (opts === void 0) {
  38076. opts = {};
  38077. }
  38078. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  38079. _this.type = _types.ATTRIBUTE;
  38080. _this.raws = _this.raws || {};
  38081. Object.defineProperty(_this.raws, 'unquoted', {
  38082. get: deprecate(function () {
  38083. return _this.value;
  38084. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  38085. set: deprecate(function () {
  38086. return _this.value;
  38087. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  38088. });
  38089. _this._constructed = true;
  38090. return _this;
  38091. }
  38092. /**
  38093. * Returns the Attribute's value quoted such that it would be legal to use
  38094. * in the value of a css file. The original value's quotation setting
  38095. * used for stringification is left unchanged. See `setValue(value, options)`
  38096. * if you want to control the quote settings of a new value for the attribute.
  38097. *
  38098. * You can also change the quotation used for the current value by setting quoteMark.
  38099. *
  38100. * Options:
  38101. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  38102. * option is not set, the original value for quoteMark will be used. If
  38103. * indeterminate, a double quote is used. The legal values are:
  38104. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  38105. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  38106. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  38107. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  38108. * over the quoteMark option value.
  38109. * * smart {boolean} - if true, will select a quote mark based on the value
  38110. * and the other options specified here. See the `smartQuoteMark()`
  38111. * method.
  38112. **/
  38113. var _proto = Attribute.prototype;
  38114. _proto.getQuotedValue = function getQuotedValue(options) {
  38115. if (options === void 0) {
  38116. options = {};
  38117. }
  38118. var quoteMark = this._determineQuoteMark(options);
  38119. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  38120. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  38121. return escaped;
  38122. };
  38123. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  38124. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  38125. }
  38126. /**
  38127. * Set the unescaped value with the specified quotation options. The value
  38128. * provided must not include any wrapping quote marks -- those quotes will
  38129. * be interpreted as part of the value and escaped accordingly.
  38130. */;
  38131. _proto.setValue = function setValue(value, options) {
  38132. if (options === void 0) {
  38133. options = {};
  38134. }
  38135. this._value = value;
  38136. this._quoteMark = this._determineQuoteMark(options);
  38137. this._syncRawValue();
  38138. }
  38139. /**
  38140. * Intelligently select a quoteMark value based on the value's contents. If
  38141. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  38142. * mark will be picked that minimizes the number of escapes.
  38143. *
  38144. * If there's no clear winner, the quote mark from these options is used,
  38145. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  38146. * true). If the quoteMark is unspecified, a double quote is used.
  38147. *
  38148. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  38149. * from the quoteValue method.
  38150. */;
  38151. _proto.smartQuoteMark = function smartQuoteMark(options) {
  38152. var v = this.value;
  38153. var numSingleQuotes = v.replace(/[^']/g, '').length;
  38154. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  38155. if (numSingleQuotes + numDoubleQuotes === 0) {
  38156. var escaped = (0, _cssesc["default"])(v, {
  38157. isIdentifier: true
  38158. });
  38159. if (escaped === v) {
  38160. return Attribute.NO_QUOTE;
  38161. } else {
  38162. var pref = this.preferredQuoteMark(options);
  38163. if (pref === Attribute.NO_QUOTE) {
  38164. // pick a quote mark that isn't none and see if it's smaller
  38165. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  38166. var opts = CSSESC_QUOTE_OPTIONS[quote];
  38167. var quoteValue = (0, _cssesc["default"])(v, opts);
  38168. if (quoteValue.length < escaped.length) {
  38169. return quote;
  38170. }
  38171. }
  38172. return pref;
  38173. }
  38174. } else if (numDoubleQuotes === numSingleQuotes) {
  38175. return this.preferredQuoteMark(options);
  38176. } else if (numDoubleQuotes < numSingleQuotes) {
  38177. return Attribute.DOUBLE_QUOTE;
  38178. } else {
  38179. return Attribute.SINGLE_QUOTE;
  38180. }
  38181. }
  38182. /**
  38183. * Selects the preferred quote mark based on the options and the current quote mark value.
  38184. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  38185. * instead.
  38186. */;
  38187. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  38188. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  38189. if (quoteMark === undefined) {
  38190. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  38191. }
  38192. if (quoteMark === undefined) {
  38193. quoteMark = Attribute.DOUBLE_QUOTE;
  38194. }
  38195. return quoteMark;
  38196. };
  38197. _proto._syncRawValue = function _syncRawValue() {
  38198. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  38199. if (rawValue === this._value) {
  38200. if (this.raws) {
  38201. delete this.raws.value;
  38202. }
  38203. } else {
  38204. this.raws.value = rawValue;
  38205. }
  38206. };
  38207. _proto._handleEscapes = function _handleEscapes(prop, value) {
  38208. if (this._constructed) {
  38209. var escaped = (0, _cssesc["default"])(value, {
  38210. isIdentifier: true
  38211. });
  38212. if (escaped !== value) {
  38213. this.raws[prop] = escaped;
  38214. } else {
  38215. delete this.raws[prop];
  38216. }
  38217. }
  38218. };
  38219. _proto._spacesFor = function _spacesFor(name) {
  38220. var attrSpaces = {
  38221. before: '',
  38222. after: ''
  38223. };
  38224. var spaces = this.spaces[name] || {};
  38225. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  38226. return Object.assign(attrSpaces, spaces, rawSpaces);
  38227. };
  38228. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  38229. if (spaceName === void 0) {
  38230. spaceName = name;
  38231. }
  38232. if (concat === void 0) {
  38233. concat = defaultAttrConcat;
  38234. }
  38235. var attrSpaces = this._spacesFor(spaceName);
  38236. return concat(this.stringifyProperty(name), attrSpaces);
  38237. }
  38238. /**
  38239. * returns the offset of the attribute part specified relative to the
  38240. * start of the node of the output string.
  38241. *
  38242. * * "ns" - alias for "namespace"
  38243. * * "namespace" - the namespace if it exists.
  38244. * * "attribute" - the attribute name
  38245. * * "attributeNS" - the start of the attribute or its namespace
  38246. * * "operator" - the match operator of the attribute
  38247. * * "value" - The value (string or identifier)
  38248. * * "insensitive" - the case insensitivity flag;
  38249. * @param part One of the possible values inside an attribute.
  38250. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  38251. */;
  38252. _proto.offsetOf = function offsetOf(name) {
  38253. var count = 1;
  38254. var attributeSpaces = this._spacesFor("attribute");
  38255. count += attributeSpaces.before.length;
  38256. if (name === "namespace" || name === "ns") {
  38257. return this.namespace ? count : -1;
  38258. }
  38259. if (name === "attributeNS") {
  38260. return count;
  38261. }
  38262. count += this.namespaceString.length;
  38263. if (this.namespace) {
  38264. count += 1;
  38265. }
  38266. if (name === "attribute") {
  38267. return count;
  38268. }
  38269. count += this.stringifyProperty("attribute").length;
  38270. count += attributeSpaces.after.length;
  38271. var operatorSpaces = this._spacesFor("operator");
  38272. count += operatorSpaces.before.length;
  38273. var operator = this.stringifyProperty("operator");
  38274. if (name === "operator") {
  38275. return operator ? count : -1;
  38276. }
  38277. count += operator.length;
  38278. count += operatorSpaces.after.length;
  38279. var valueSpaces = this._spacesFor("value");
  38280. count += valueSpaces.before.length;
  38281. var value = this.stringifyProperty("value");
  38282. if (name === "value") {
  38283. return value ? count : -1;
  38284. }
  38285. count += value.length;
  38286. count += valueSpaces.after.length;
  38287. var insensitiveSpaces = this._spacesFor("insensitive");
  38288. count += insensitiveSpaces.before.length;
  38289. if (name === "insensitive") {
  38290. return this.insensitive ? count : -1;
  38291. }
  38292. return -1;
  38293. };
  38294. _proto.toString = function toString() {
  38295. var _this2 = this;
  38296. var selector = [this.rawSpaceBefore, '['];
  38297. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  38298. if (this.operator && (this.value || this.value === '')) {
  38299. selector.push(this._stringFor('operator'));
  38300. selector.push(this._stringFor('value'));
  38301. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  38302. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  38303. attrSpaces.before = " ";
  38304. }
  38305. return defaultAttrConcat(attrValue, attrSpaces);
  38306. }));
  38307. }
  38308. selector.push(']');
  38309. selector.push(this.rawSpaceAfter);
  38310. return selector.join('');
  38311. };
  38312. _createClass(Attribute, [{
  38313. key: "quoted",
  38314. get: function get() {
  38315. var qm = this.quoteMark;
  38316. return qm === "'" || qm === '"';
  38317. },
  38318. set: function set(value) {
  38319. warnOfDeprecatedQuotedAssignment();
  38320. }
  38321. /**
  38322. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  38323. * returns `null` if the value is not quoted.
  38324. * returns `undefined` if the quotation state is unknown (this can happen when
  38325. * the attribute is constructed without specifying a quote mark.)
  38326. */
  38327. }, {
  38328. key: "quoteMark",
  38329. get: function get() {
  38330. return this._quoteMark;
  38331. }
  38332. /**
  38333. * Set the quote mark to be used by this attribute's value.
  38334. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  38335. * value is updated accordingly.
  38336. *
  38337. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  38338. */,
  38339. set: function set(quoteMark) {
  38340. if (!this._constructed) {
  38341. this._quoteMark = quoteMark;
  38342. return;
  38343. }
  38344. if (this._quoteMark !== quoteMark) {
  38345. this._quoteMark = quoteMark;
  38346. this._syncRawValue();
  38347. }
  38348. }
  38349. }, {
  38350. key: "qualifiedAttribute",
  38351. get: function get() {
  38352. return this.qualifiedName(this.raws.attribute || this.attribute);
  38353. }
  38354. }, {
  38355. key: "insensitiveFlag",
  38356. get: function get() {
  38357. return this.insensitive ? 'i' : '';
  38358. }
  38359. }, {
  38360. key: "value",
  38361. get: function get() {
  38362. return this._value;
  38363. },
  38364. set:
  38365. /**
  38366. * Before 3.0, the value had to be set to an escaped value including any wrapped
  38367. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  38368. * is unescaped during parsing and any quote marks are removed.
  38369. *
  38370. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  38371. * a deprecation warning is raised when the new value contains any characters that would
  38372. * require escaping (including if it contains wrapped quotes).
  38373. *
  38374. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  38375. * how the new value is quoted.
  38376. */
  38377. function set(v) {
  38378. if (this._constructed) {
  38379. var _unescapeValue2 = unescapeValue(v),
  38380. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  38381. unescaped = _unescapeValue2.unescaped,
  38382. quoteMark = _unescapeValue2.quoteMark;
  38383. if (deprecatedUsage) {
  38384. warnOfDeprecatedValueAssignment();
  38385. }
  38386. if (unescaped === this._value && quoteMark === this._quoteMark) {
  38387. return;
  38388. }
  38389. this._value = unescaped;
  38390. this._quoteMark = quoteMark;
  38391. this._syncRawValue();
  38392. } else {
  38393. this._value = v;
  38394. }
  38395. }
  38396. }, {
  38397. key: "insensitive",
  38398. get: function get() {
  38399. return this._insensitive;
  38400. }
  38401. /**
  38402. * Set the case insensitive flag.
  38403. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  38404. * of the attribute is updated accordingly.
  38405. *
  38406. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  38407. */,
  38408. set: function set(insensitive) {
  38409. if (!insensitive) {
  38410. this._insensitive = false;
  38411. // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  38412. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  38413. if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
  38414. this.raws.insensitiveFlag = undefined;
  38415. }
  38416. }
  38417. this._insensitive = insensitive;
  38418. }
  38419. }, {
  38420. key: "attribute",
  38421. get: function get() {
  38422. return this._attribute;
  38423. },
  38424. set: function set(name) {
  38425. this._handleEscapes("attribute", name);
  38426. this._attribute = name;
  38427. }
  38428. }]);
  38429. return Attribute;
  38430. }(_namespace["default"]);
  38431. exports["default"] = Attribute;
  38432. Attribute.NO_QUOTE = null;
  38433. Attribute.SINGLE_QUOTE = "'";
  38434. Attribute.DOUBLE_QUOTE = '"';
  38435. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  38436. "'": {
  38437. quotes: 'single',
  38438. wrap: true
  38439. },
  38440. '"': {
  38441. quotes: 'double',
  38442. wrap: true
  38443. }
  38444. }, _CSSESC_QUOTE_OPTIONS[null] = {
  38445. isIdentifier: true
  38446. }, _CSSESC_QUOTE_OPTIONS);
  38447. function defaultAttrConcat(attrValue, attrSpaces) {
  38448. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  38449. }
  38450. } (attribute));
  38451. return attribute;
  38452. }
  38453. var universal = {exports: {}};
  38454. var hasRequiredUniversal;
  38455. function requireUniversal () {
  38456. if (hasRequiredUniversal) return universal.exports;
  38457. hasRequiredUniversal = 1;
  38458. (function (module, exports) {
  38459. exports.__esModule = true;
  38460. exports["default"] = void 0;
  38461. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  38462. var _types = /*@__PURE__*/ requireTypes();
  38463. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  38464. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  38465. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  38466. var Universal = /*#__PURE__*/function (_Namespace) {
  38467. _inheritsLoose(Universal, _Namespace);
  38468. function Universal(opts) {
  38469. var _this;
  38470. _this = _Namespace.call(this, opts) || this;
  38471. _this.type = _types.UNIVERSAL;
  38472. _this.value = '*';
  38473. return _this;
  38474. }
  38475. return Universal;
  38476. }(_namespace["default"]);
  38477. exports["default"] = Universal;
  38478. module.exports = exports.default;
  38479. } (universal, universal.exports));
  38480. return universal.exports;
  38481. }
  38482. var combinator = {exports: {}};
  38483. var hasRequiredCombinator;
  38484. function requireCombinator () {
  38485. if (hasRequiredCombinator) return combinator.exports;
  38486. hasRequiredCombinator = 1;
  38487. (function (module, exports) {
  38488. exports.__esModule = true;
  38489. exports["default"] = void 0;
  38490. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$1());
  38491. var _types = /*@__PURE__*/ requireTypes();
  38492. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  38493. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  38494. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  38495. var Combinator = /*#__PURE__*/function (_Node) {
  38496. _inheritsLoose(Combinator, _Node);
  38497. function Combinator(opts) {
  38498. var _this;
  38499. _this = _Node.call(this, opts) || this;
  38500. _this.type = _types.COMBINATOR;
  38501. return _this;
  38502. }
  38503. return Combinator;
  38504. }(_node["default"]);
  38505. exports["default"] = Combinator;
  38506. module.exports = exports.default;
  38507. } (combinator, combinator.exports));
  38508. return combinator.exports;
  38509. }
  38510. var nesting = {exports: {}};
  38511. var hasRequiredNesting;
  38512. function requireNesting () {
  38513. if (hasRequiredNesting) return nesting.exports;
  38514. hasRequiredNesting = 1;
  38515. (function (module, exports) {
  38516. exports.__esModule = true;
  38517. exports["default"] = void 0;
  38518. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$1());
  38519. var _types = /*@__PURE__*/ requireTypes();
  38520. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  38521. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  38522. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  38523. var Nesting = /*#__PURE__*/function (_Node) {
  38524. _inheritsLoose(Nesting, _Node);
  38525. function Nesting(opts) {
  38526. var _this;
  38527. _this = _Node.call(this, opts) || this;
  38528. _this.type = _types.NESTING;
  38529. _this.value = '&';
  38530. return _this;
  38531. }
  38532. return Nesting;
  38533. }(_node["default"]);
  38534. exports["default"] = Nesting;
  38535. module.exports = exports.default;
  38536. } (nesting, nesting.exports));
  38537. return nesting.exports;
  38538. }
  38539. var sortAscending = {exports: {}};
  38540. var hasRequiredSortAscending;
  38541. function requireSortAscending () {
  38542. if (hasRequiredSortAscending) return sortAscending.exports;
  38543. hasRequiredSortAscending = 1;
  38544. (function (module, exports) {
  38545. exports.__esModule = true;
  38546. exports["default"] = sortAscending;
  38547. function sortAscending(list) {
  38548. return list.sort(function (a, b) {
  38549. return a - b;
  38550. });
  38551. }
  38552. module.exports = exports.default;
  38553. } (sortAscending, sortAscending.exports));
  38554. return sortAscending.exports;
  38555. }
  38556. var tokenize = {};
  38557. var tokenTypes = {};
  38558. var hasRequiredTokenTypes;
  38559. function requireTokenTypes () {
  38560. if (hasRequiredTokenTypes) return tokenTypes;
  38561. hasRequiredTokenTypes = 1;
  38562. tokenTypes.__esModule = true;
  38563. tokenTypes.word = tokenTypes.tilde = tokenTypes.tab = tokenTypes.str = tokenTypes.space = tokenTypes.slash = tokenTypes.singleQuote = tokenTypes.semicolon = tokenTypes.plus = tokenTypes.pipe = tokenTypes.openSquare = tokenTypes.openParenthesis = tokenTypes.newline = tokenTypes.greaterThan = tokenTypes.feed = tokenTypes.equals = tokenTypes.doubleQuote = tokenTypes.dollar = tokenTypes.cr = tokenTypes.comment = tokenTypes.comma = tokenTypes.combinator = tokenTypes.colon = tokenTypes.closeSquare = tokenTypes.closeParenthesis = tokenTypes.caret = tokenTypes.bang = tokenTypes.backslash = tokenTypes.at = tokenTypes.asterisk = tokenTypes.ampersand = void 0;
  38564. var ampersand = 38; // `&`.charCodeAt(0);
  38565. tokenTypes.ampersand = ampersand;
  38566. var asterisk = 42; // `*`.charCodeAt(0);
  38567. tokenTypes.asterisk = asterisk;
  38568. var at = 64; // `@`.charCodeAt(0);
  38569. tokenTypes.at = at;
  38570. var comma = 44; // `,`.charCodeAt(0);
  38571. tokenTypes.comma = comma;
  38572. var colon = 58; // `:`.charCodeAt(0);
  38573. tokenTypes.colon = colon;
  38574. var semicolon = 59; // `;`.charCodeAt(0);
  38575. tokenTypes.semicolon = semicolon;
  38576. var openParenthesis = 40; // `(`.charCodeAt(0);
  38577. tokenTypes.openParenthesis = openParenthesis;
  38578. var closeParenthesis = 41; // `)`.charCodeAt(0);
  38579. tokenTypes.closeParenthesis = closeParenthesis;
  38580. var openSquare = 91; // `[`.charCodeAt(0);
  38581. tokenTypes.openSquare = openSquare;
  38582. var closeSquare = 93; // `]`.charCodeAt(0);
  38583. tokenTypes.closeSquare = closeSquare;
  38584. var dollar = 36; // `$`.charCodeAt(0);
  38585. tokenTypes.dollar = dollar;
  38586. var tilde = 126; // `~`.charCodeAt(0);
  38587. tokenTypes.tilde = tilde;
  38588. var caret = 94; // `^`.charCodeAt(0);
  38589. tokenTypes.caret = caret;
  38590. var plus = 43; // `+`.charCodeAt(0);
  38591. tokenTypes.plus = plus;
  38592. var equals = 61; // `=`.charCodeAt(0);
  38593. tokenTypes.equals = equals;
  38594. var pipe = 124; // `|`.charCodeAt(0);
  38595. tokenTypes.pipe = pipe;
  38596. var greaterThan = 62; // `>`.charCodeAt(0);
  38597. tokenTypes.greaterThan = greaterThan;
  38598. var space = 32; // ` `.charCodeAt(0);
  38599. tokenTypes.space = space;
  38600. var singleQuote = 39; // `'`.charCodeAt(0);
  38601. tokenTypes.singleQuote = singleQuote;
  38602. var doubleQuote = 34; // `"`.charCodeAt(0);
  38603. tokenTypes.doubleQuote = doubleQuote;
  38604. var slash = 47; // `/`.charCodeAt(0);
  38605. tokenTypes.slash = slash;
  38606. var bang = 33; // `!`.charCodeAt(0);
  38607. tokenTypes.bang = bang;
  38608. var backslash = 92; // '\\'.charCodeAt(0);
  38609. tokenTypes.backslash = backslash;
  38610. var cr = 13; // '\r'.charCodeAt(0);
  38611. tokenTypes.cr = cr;
  38612. var feed = 12; // '\f'.charCodeAt(0);
  38613. tokenTypes.feed = feed;
  38614. var newline = 10; // '\n'.charCodeAt(0);
  38615. tokenTypes.newline = newline;
  38616. var tab = 9; // '\t'.charCodeAt(0);
  38617. // Expose aliases primarily for readability.
  38618. tokenTypes.tab = tab;
  38619. var str = singleQuote;
  38620. // No good single character representation!
  38621. tokenTypes.str = str;
  38622. var comment = -1;
  38623. tokenTypes.comment = comment;
  38624. var word = -2;
  38625. tokenTypes.word = word;
  38626. var combinator = -3;
  38627. tokenTypes.combinator = combinator;
  38628. return tokenTypes;
  38629. }
  38630. var hasRequiredTokenize;
  38631. function requireTokenize () {
  38632. if (hasRequiredTokenize) return tokenize;
  38633. hasRequiredTokenize = 1;
  38634. (function (exports) {
  38635. exports.__esModule = true;
  38636. exports.FIELDS = void 0;
  38637. exports["default"] = tokenize;
  38638. var t = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes());
  38639. var _unescapable, _wordDelimiters;
  38640. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  38641. function _interopRequireWildcard(obj, nodeInterop) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  38642. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  38643. var wordDelimiters = (_wordDelimiters = {}, _wordDelimiters[t.space] = true, _wordDelimiters[t.tab] = true, _wordDelimiters[t.newline] = true, _wordDelimiters[t.cr] = true, _wordDelimiters[t.feed] = true, _wordDelimiters[t.ampersand] = true, _wordDelimiters[t.asterisk] = true, _wordDelimiters[t.bang] = true, _wordDelimiters[t.comma] = true, _wordDelimiters[t.colon] = true, _wordDelimiters[t.semicolon] = true, _wordDelimiters[t.openParenthesis] = true, _wordDelimiters[t.closeParenthesis] = true, _wordDelimiters[t.openSquare] = true, _wordDelimiters[t.closeSquare] = true, _wordDelimiters[t.singleQuote] = true, _wordDelimiters[t.doubleQuote] = true, _wordDelimiters[t.plus] = true, _wordDelimiters[t.pipe] = true, _wordDelimiters[t.tilde] = true, _wordDelimiters[t.greaterThan] = true, _wordDelimiters[t.equals] = true, _wordDelimiters[t.dollar] = true, _wordDelimiters[t.caret] = true, _wordDelimiters[t.slash] = true, _wordDelimiters);
  38644. var hex = {};
  38645. var hexChars = "0123456789abcdefABCDEF";
  38646. for (var i = 0; i < hexChars.length; i++) {
  38647. hex[hexChars.charCodeAt(i)] = true;
  38648. }
  38649. /**
  38650. * Returns the last index of the bar css word
  38651. * @param {string} css The string in which the word begins
  38652. * @param {number} start The index into the string where word's first letter occurs
  38653. */
  38654. function consumeWord(css, start) {
  38655. var next = start;
  38656. var code;
  38657. do {
  38658. code = css.charCodeAt(next);
  38659. if (wordDelimiters[code]) {
  38660. return next - 1;
  38661. } else if (code === t.backslash) {
  38662. next = consumeEscape(css, next) + 1;
  38663. } else {
  38664. // All other characters are part of the word
  38665. next++;
  38666. }
  38667. } while (next < css.length);
  38668. return next - 1;
  38669. }
  38670. /**
  38671. * Returns the last index of the escape sequence
  38672. * @param {string} css The string in which the sequence begins
  38673. * @param {number} start The index into the string where escape character (`\`) occurs.
  38674. */
  38675. function consumeEscape(css, start) {
  38676. var next = start;
  38677. var code = css.charCodeAt(next + 1);
  38678. if (unescapable[code]) ; else if (hex[code]) {
  38679. var hexDigits = 0;
  38680. // consume up to 6 hex chars
  38681. do {
  38682. next++;
  38683. hexDigits++;
  38684. code = css.charCodeAt(next + 1);
  38685. } while (hex[code] && hexDigits < 6);
  38686. // if fewer than 6 hex chars, a trailing space ends the escape
  38687. if (hexDigits < 6 && code === t.space) {
  38688. next++;
  38689. }
  38690. } else {
  38691. // the next char is part of the current word
  38692. next++;
  38693. }
  38694. return next;
  38695. }
  38696. var FIELDS = {
  38697. TYPE: 0,
  38698. START_LINE: 1,
  38699. START_COL: 2,
  38700. END_LINE: 3,
  38701. END_COL: 4,
  38702. START_POS: 5,
  38703. END_POS: 6
  38704. };
  38705. exports.FIELDS = FIELDS;
  38706. function tokenize(input) {
  38707. var tokens = [];
  38708. var css = input.css.valueOf();
  38709. var _css = css,
  38710. length = _css.length;
  38711. var offset = -1;
  38712. var line = 1;
  38713. var start = 0;
  38714. var end = 0;
  38715. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  38716. function unclosed(what, fix) {
  38717. if (input.safe) {
  38718. // fyi: this is never set to true.
  38719. css += fix;
  38720. next = css.length - 1;
  38721. } else {
  38722. throw input.error('Unclosed ' + what, line, start - offset, start);
  38723. }
  38724. }
  38725. while (start < length) {
  38726. code = css.charCodeAt(start);
  38727. if (code === t.newline) {
  38728. offset = start;
  38729. line += 1;
  38730. }
  38731. switch (code) {
  38732. case t.space:
  38733. case t.tab:
  38734. case t.newline:
  38735. case t.cr:
  38736. case t.feed:
  38737. next = start;
  38738. do {
  38739. next += 1;
  38740. code = css.charCodeAt(next);
  38741. if (code === t.newline) {
  38742. offset = next;
  38743. line += 1;
  38744. }
  38745. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  38746. tokenType = t.space;
  38747. endLine = line;
  38748. endColumn = next - offset - 1;
  38749. end = next;
  38750. break;
  38751. case t.plus:
  38752. case t.greaterThan:
  38753. case t.tilde:
  38754. case t.pipe:
  38755. next = start;
  38756. do {
  38757. next += 1;
  38758. code = css.charCodeAt(next);
  38759. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  38760. tokenType = t.combinator;
  38761. endLine = line;
  38762. endColumn = start - offset;
  38763. end = next;
  38764. break;
  38765. // Consume these characters as single tokens.
  38766. case t.asterisk:
  38767. case t.ampersand:
  38768. case t.bang:
  38769. case t.comma:
  38770. case t.equals:
  38771. case t.dollar:
  38772. case t.caret:
  38773. case t.openSquare:
  38774. case t.closeSquare:
  38775. case t.colon:
  38776. case t.semicolon:
  38777. case t.openParenthesis:
  38778. case t.closeParenthesis:
  38779. next = start;
  38780. tokenType = code;
  38781. endLine = line;
  38782. endColumn = start - offset;
  38783. end = next + 1;
  38784. break;
  38785. case t.singleQuote:
  38786. case t.doubleQuote:
  38787. quote = code === t.singleQuote ? "'" : '"';
  38788. next = start;
  38789. do {
  38790. escaped = false;
  38791. next = css.indexOf(quote, next + 1);
  38792. if (next === -1) {
  38793. unclosed('quote', quote);
  38794. }
  38795. escapePos = next;
  38796. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  38797. escapePos -= 1;
  38798. escaped = !escaped;
  38799. }
  38800. } while (escaped);
  38801. tokenType = t.str;
  38802. endLine = line;
  38803. endColumn = start - offset;
  38804. end = next + 1;
  38805. break;
  38806. default:
  38807. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  38808. next = css.indexOf('*/', start + 2) + 1;
  38809. if (next === 0) {
  38810. unclosed('comment', '*/');
  38811. }
  38812. content = css.slice(start, next + 1);
  38813. lines = content.split('\n');
  38814. last = lines.length - 1;
  38815. if (last > 0) {
  38816. nextLine = line + last;
  38817. nextOffset = next - lines[last].length;
  38818. } else {
  38819. nextLine = line;
  38820. nextOffset = offset;
  38821. }
  38822. tokenType = t.comment;
  38823. line = nextLine;
  38824. endLine = nextLine;
  38825. endColumn = next - nextOffset;
  38826. } else if (code === t.slash) {
  38827. next = start;
  38828. tokenType = code;
  38829. endLine = line;
  38830. endColumn = start - offset;
  38831. end = next + 1;
  38832. } else {
  38833. next = consumeWord(css, start);
  38834. tokenType = t.word;
  38835. endLine = line;
  38836. endColumn = next - offset;
  38837. }
  38838. end = next + 1;
  38839. break;
  38840. }
  38841. // Ensure that the token structure remains consistent
  38842. tokens.push([tokenType,
  38843. // [0] Token type
  38844. line,
  38845. // [1] Starting line
  38846. start - offset,
  38847. // [2] Starting column
  38848. endLine,
  38849. // [3] Ending line
  38850. endColumn,
  38851. // [4] Ending column
  38852. start,
  38853. // [5] Start position / Source index
  38854. end // [6] End position
  38855. ]);
  38856. // Reset offset for the next token
  38857. if (nextOffset) {
  38858. offset = nextOffset;
  38859. nextOffset = null;
  38860. }
  38861. start = end;
  38862. }
  38863. return tokens;
  38864. }
  38865. } (tokenize));
  38866. return tokenize;
  38867. }
  38868. var hasRequiredParser;
  38869. function requireParser () {
  38870. if (hasRequiredParser) return parser.exports;
  38871. hasRequiredParser = 1;
  38872. (function (module, exports) {
  38873. exports.__esModule = true;
  38874. exports["default"] = void 0;
  38875. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot());
  38876. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector());
  38877. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName());
  38878. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment());
  38879. var _id = _interopRequireDefault(/*@__PURE__*/ requireId());
  38880. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag());
  38881. var _string = _interopRequireDefault(/*@__PURE__*/ requireString());
  38882. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo());
  38883. var _attribute = _interopRequireWildcard(/*@__PURE__*/ requireAttribute());
  38884. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal());
  38885. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator());
  38886. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting());
  38887. var _sortAscending = _interopRequireDefault(/*@__PURE__*/ requireSortAscending());
  38888. var _tokenize = _interopRequireWildcard(/*@__PURE__*/ requireTokenize());
  38889. var tokens = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes());
  38890. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes());
  38891. var _util = /*@__PURE__*/ requireUtil$1();
  38892. var _WHITESPACE_TOKENS, _Object$assign;
  38893. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  38894. function _interopRequireWildcard(obj, nodeInterop) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  38895. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  38896. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  38897. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  38898. var WHITESPACE_TOKENS = (_WHITESPACE_TOKENS = {}, _WHITESPACE_TOKENS[tokens.space] = true, _WHITESPACE_TOKENS[tokens.cr] = true, _WHITESPACE_TOKENS[tokens.feed] = true, _WHITESPACE_TOKENS[tokens.newline] = true, _WHITESPACE_TOKENS[tokens.tab] = true, _WHITESPACE_TOKENS);
  38899. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  38900. function tokenStart(token) {
  38901. return {
  38902. line: token[_tokenize.FIELDS.START_LINE],
  38903. column: token[_tokenize.FIELDS.START_COL]
  38904. };
  38905. }
  38906. function tokenEnd(token) {
  38907. return {
  38908. line: token[_tokenize.FIELDS.END_LINE],
  38909. column: token[_tokenize.FIELDS.END_COL]
  38910. };
  38911. }
  38912. function getSource(startLine, startColumn, endLine, endColumn) {
  38913. return {
  38914. start: {
  38915. line: startLine,
  38916. column: startColumn
  38917. },
  38918. end: {
  38919. line: endLine,
  38920. column: endColumn
  38921. }
  38922. };
  38923. }
  38924. function getTokenSource(token) {
  38925. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  38926. }
  38927. function getTokenSourceSpan(startToken, endToken) {
  38928. if (!startToken) {
  38929. return undefined;
  38930. }
  38931. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  38932. }
  38933. function unescapeProp(node, prop) {
  38934. var value = node[prop];
  38935. if (typeof value !== "string") {
  38936. return;
  38937. }
  38938. if (value.indexOf("\\") !== -1) {
  38939. (0, _util.ensureObject)(node, 'raws');
  38940. node[prop] = (0, _util.unesc)(value);
  38941. if (node.raws[prop] === undefined) {
  38942. node.raws[prop] = value;
  38943. }
  38944. }
  38945. return node;
  38946. }
  38947. function indexesOf(array, item) {
  38948. var i = -1;
  38949. var indexes = [];
  38950. while ((i = array.indexOf(item, i + 1)) !== -1) {
  38951. indexes.push(i);
  38952. }
  38953. return indexes;
  38954. }
  38955. function uniqs() {
  38956. var list = Array.prototype.concat.apply([], arguments);
  38957. return list.filter(function (item, i) {
  38958. return i === list.indexOf(item);
  38959. });
  38960. }
  38961. var Parser = /*#__PURE__*/function () {
  38962. function Parser(rule, options) {
  38963. if (options === void 0) {
  38964. options = {};
  38965. }
  38966. this.rule = rule;
  38967. this.options = Object.assign({
  38968. lossy: false,
  38969. safe: false
  38970. }, options);
  38971. this.position = 0;
  38972. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  38973. this.tokens = (0, _tokenize["default"])({
  38974. css: this.css,
  38975. error: this._errorGenerator(),
  38976. safe: this.options.safe
  38977. });
  38978. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  38979. this.root = new _root["default"]({
  38980. source: rootSource
  38981. });
  38982. this.root.errorGenerator = this._errorGenerator();
  38983. var selector = new _selector["default"]({
  38984. source: {
  38985. start: {
  38986. line: 1,
  38987. column: 1
  38988. }
  38989. },
  38990. sourceIndex: 0
  38991. });
  38992. this.root.append(selector);
  38993. this.current = selector;
  38994. this.loop();
  38995. }
  38996. var _proto = Parser.prototype;
  38997. _proto._errorGenerator = function _errorGenerator() {
  38998. var _this = this;
  38999. return function (message, errorOptions) {
  39000. if (typeof _this.rule === 'string') {
  39001. return new Error(message);
  39002. }
  39003. return _this.rule.error(message, errorOptions);
  39004. };
  39005. };
  39006. _proto.attribute = function attribute() {
  39007. var attr = [];
  39008. var startingToken = this.currToken;
  39009. this.position++;
  39010. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  39011. attr.push(this.currToken);
  39012. this.position++;
  39013. }
  39014. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  39015. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  39016. }
  39017. var len = attr.length;
  39018. var node = {
  39019. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  39020. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  39021. };
  39022. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  39023. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  39024. }
  39025. var pos = 0;
  39026. var spaceBefore = '';
  39027. var commentBefore = '';
  39028. var lastAdded = null;
  39029. var spaceAfterMeaningfulToken = false;
  39030. while (pos < len) {
  39031. var token = attr[pos];
  39032. var content = this.content(token);
  39033. var next = attr[pos + 1];
  39034. switch (token[_tokenize.FIELDS.TYPE]) {
  39035. case tokens.space:
  39036. // if (
  39037. // len === 1 ||
  39038. // pos === 0 && this.content(next) === '|'
  39039. // ) {
  39040. // return this.expected('attribute', token[TOKEN.START_POS], content);
  39041. // }
  39042. spaceAfterMeaningfulToken = true;
  39043. if (this.options.lossy) {
  39044. break;
  39045. }
  39046. if (lastAdded) {
  39047. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  39048. var prevContent = node.spaces[lastAdded].after || '';
  39049. node.spaces[lastAdded].after = prevContent + content;
  39050. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  39051. if (existingComment) {
  39052. node.raws.spaces[lastAdded].after = existingComment + content;
  39053. }
  39054. } else {
  39055. spaceBefore = spaceBefore + content;
  39056. commentBefore = commentBefore + content;
  39057. }
  39058. break;
  39059. case tokens.asterisk:
  39060. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  39061. node.operator = content;
  39062. lastAdded = 'operator';
  39063. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  39064. if (spaceBefore) {
  39065. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  39066. node.spaces.attribute.before = spaceBefore;
  39067. spaceBefore = '';
  39068. }
  39069. if (commentBefore) {
  39070. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  39071. node.raws.spaces.attribute.before = spaceBefore;
  39072. commentBefore = '';
  39073. }
  39074. node.namespace = (node.namespace || "") + content;
  39075. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  39076. if (rawValue) {
  39077. node.raws.namespace += content;
  39078. }
  39079. lastAdded = 'namespace';
  39080. }
  39081. spaceAfterMeaningfulToken = false;
  39082. break;
  39083. case tokens.dollar:
  39084. if (lastAdded === "value") {
  39085. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  39086. node.value += "$";
  39087. if (oldRawValue) {
  39088. node.raws.value = oldRawValue + "$";
  39089. }
  39090. break;
  39091. }
  39092. // Falls through
  39093. case tokens.caret:
  39094. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  39095. node.operator = content;
  39096. lastAdded = 'operator';
  39097. }
  39098. spaceAfterMeaningfulToken = false;
  39099. break;
  39100. case tokens.combinator:
  39101. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  39102. node.operator = content;
  39103. lastAdded = 'operator';
  39104. }
  39105. if (content !== '|') {
  39106. spaceAfterMeaningfulToken = false;
  39107. break;
  39108. }
  39109. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  39110. node.operator = content;
  39111. lastAdded = 'operator';
  39112. } else if (!node.namespace && !node.attribute) {
  39113. node.namespace = true;
  39114. }
  39115. spaceAfterMeaningfulToken = false;
  39116. break;
  39117. case tokens.word:
  39118. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
  39119. // this look-ahead probably fails with comment nodes involved.
  39120. !node.operator && !node.namespace) {
  39121. node.namespace = content;
  39122. lastAdded = 'namespace';
  39123. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  39124. if (spaceBefore) {
  39125. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  39126. node.spaces.attribute.before = spaceBefore;
  39127. spaceBefore = '';
  39128. }
  39129. if (commentBefore) {
  39130. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  39131. node.raws.spaces.attribute.before = commentBefore;
  39132. commentBefore = '';
  39133. }
  39134. node.attribute = (node.attribute || "") + content;
  39135. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  39136. if (_rawValue) {
  39137. node.raws.attribute += content;
  39138. }
  39139. lastAdded = 'attribute';
  39140. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  39141. var _unescaped = (0, _util.unesc)(content);
  39142. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  39143. var oldValue = node.value || '';
  39144. node.value = oldValue + _unescaped;
  39145. node.quoteMark = null;
  39146. if (_unescaped !== content || _oldRawValue) {
  39147. (0, _util.ensureObject)(node, 'raws');
  39148. node.raws.value = (_oldRawValue || oldValue) + content;
  39149. }
  39150. lastAdded = 'value';
  39151. } else {
  39152. var insensitive = content === 'i' || content === "I";
  39153. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  39154. node.insensitive = insensitive;
  39155. if (!insensitive || content === "I") {
  39156. (0, _util.ensureObject)(node, 'raws');
  39157. node.raws.insensitiveFlag = content;
  39158. }
  39159. lastAdded = 'insensitive';
  39160. if (spaceBefore) {
  39161. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  39162. node.spaces.insensitive.before = spaceBefore;
  39163. spaceBefore = '';
  39164. }
  39165. if (commentBefore) {
  39166. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  39167. node.raws.spaces.insensitive.before = commentBefore;
  39168. commentBefore = '';
  39169. }
  39170. } else if (node.value || node.value === '') {
  39171. lastAdded = 'value';
  39172. node.value += content;
  39173. if (node.raws.value) {
  39174. node.raws.value += content;
  39175. }
  39176. }
  39177. }
  39178. spaceAfterMeaningfulToken = false;
  39179. break;
  39180. case tokens.str:
  39181. if (!node.attribute || !node.operator) {
  39182. return this.error("Expected an attribute followed by an operator preceding the string.", {
  39183. index: token[_tokenize.FIELDS.START_POS]
  39184. });
  39185. }
  39186. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  39187. unescaped = _unescapeValue.unescaped,
  39188. quoteMark = _unescapeValue.quoteMark;
  39189. node.value = unescaped;
  39190. node.quoteMark = quoteMark;
  39191. lastAdded = 'value';
  39192. (0, _util.ensureObject)(node, 'raws');
  39193. node.raws.value = content;
  39194. spaceAfterMeaningfulToken = false;
  39195. break;
  39196. case tokens.equals:
  39197. if (!node.attribute) {
  39198. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  39199. }
  39200. if (node.value) {
  39201. return this.error('Unexpected "=" found; an operator was already defined.', {
  39202. index: token[_tokenize.FIELDS.START_POS]
  39203. });
  39204. }
  39205. node.operator = node.operator ? node.operator + content : content;
  39206. lastAdded = 'operator';
  39207. spaceAfterMeaningfulToken = false;
  39208. break;
  39209. case tokens.comment:
  39210. if (lastAdded) {
  39211. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  39212. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  39213. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  39214. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  39215. node.raws.spaces[lastAdded].after = rawLastComment + content;
  39216. } else {
  39217. var lastValue = node[lastAdded] || '';
  39218. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  39219. (0, _util.ensureObject)(node, 'raws');
  39220. node.raws[lastAdded] = rawLastValue + content;
  39221. }
  39222. } else {
  39223. commentBefore = commentBefore + content;
  39224. }
  39225. break;
  39226. default:
  39227. return this.error("Unexpected \"" + content + "\" found.", {
  39228. index: token[_tokenize.FIELDS.START_POS]
  39229. });
  39230. }
  39231. pos++;
  39232. }
  39233. unescapeProp(node, "attribute");
  39234. unescapeProp(node, "namespace");
  39235. this.newNode(new _attribute["default"](node));
  39236. this.position++;
  39237. }
  39238. /**
  39239. * return a node containing meaningless garbage up to (but not including) the specified token position.
  39240. * if the token position is negative, all remaining tokens are consumed.
  39241. *
  39242. * This returns an array containing a single string node if all whitespace,
  39243. * otherwise an array of comment nodes with space before and after.
  39244. *
  39245. * These tokens are not added to the current selector, the caller can add them or use them to amend
  39246. * a previous node's space metadata.
  39247. *
  39248. * In lossy mode, this returns only comments.
  39249. */;
  39250. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  39251. if (stopPosition < 0) {
  39252. stopPosition = this.tokens.length;
  39253. }
  39254. var startPosition = this.position;
  39255. var nodes = [];
  39256. var space = "";
  39257. var lastComment = undefined;
  39258. do {
  39259. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  39260. if (!this.options.lossy) {
  39261. space += this.content();
  39262. }
  39263. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  39264. var spaces = {};
  39265. if (space) {
  39266. spaces.before = space;
  39267. space = "";
  39268. }
  39269. lastComment = new _comment["default"]({
  39270. value: this.content(),
  39271. source: getTokenSource(this.currToken),
  39272. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  39273. spaces: spaces
  39274. });
  39275. nodes.push(lastComment);
  39276. }
  39277. } while (++this.position < stopPosition);
  39278. if (space) {
  39279. if (lastComment) {
  39280. lastComment.spaces.after = space;
  39281. } else if (!this.options.lossy) {
  39282. var firstToken = this.tokens[startPosition];
  39283. var lastToken = this.tokens[this.position - 1];
  39284. nodes.push(new _string["default"]({
  39285. value: '',
  39286. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  39287. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  39288. spaces: {
  39289. before: space,
  39290. after: ''
  39291. }
  39292. }));
  39293. }
  39294. }
  39295. return nodes;
  39296. }
  39297. /**
  39298. *
  39299. * @param {*} nodes
  39300. */;
  39301. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  39302. var _this2 = this;
  39303. if (requiredSpace === void 0) {
  39304. requiredSpace = false;
  39305. }
  39306. var space = "";
  39307. var rawSpace = "";
  39308. nodes.forEach(function (n) {
  39309. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  39310. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  39311. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  39312. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  39313. });
  39314. if (rawSpace === space) {
  39315. rawSpace = undefined;
  39316. }
  39317. var result = {
  39318. space: space,
  39319. rawSpace: rawSpace
  39320. };
  39321. return result;
  39322. };
  39323. _proto.isNamedCombinator = function isNamedCombinator(position) {
  39324. if (position === void 0) {
  39325. position = this.position;
  39326. }
  39327. return this.tokens[position + 0] && this.tokens[position + 0][_tokenize.FIELDS.TYPE] === tokens.slash && this.tokens[position + 1] && this.tokens[position + 1][_tokenize.FIELDS.TYPE] === tokens.word && this.tokens[position + 2] && this.tokens[position + 2][_tokenize.FIELDS.TYPE] === tokens.slash;
  39328. };
  39329. _proto.namedCombinator = function namedCombinator() {
  39330. if (this.isNamedCombinator()) {
  39331. var nameRaw = this.content(this.tokens[this.position + 1]);
  39332. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  39333. var raws = {};
  39334. if (name !== nameRaw) {
  39335. raws.value = "/" + nameRaw + "/";
  39336. }
  39337. var node = new _combinator["default"]({
  39338. value: "/" + name + "/",
  39339. source: getSource(this.currToken[_tokenize.FIELDS.START_LINE], this.currToken[_tokenize.FIELDS.START_COL], this.tokens[this.position + 2][_tokenize.FIELDS.END_LINE], this.tokens[this.position + 2][_tokenize.FIELDS.END_COL]),
  39340. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  39341. raws: raws
  39342. });
  39343. this.position = this.position + 3;
  39344. return node;
  39345. } else {
  39346. this.unexpected();
  39347. }
  39348. };
  39349. _proto.combinator = function combinator() {
  39350. var _this3 = this;
  39351. if (this.content() === '|') {
  39352. return this.namespace();
  39353. }
  39354. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  39355. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  39356. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  39357. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  39358. if (nodes.length > 0) {
  39359. var last = this.current.last;
  39360. if (last) {
  39361. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  39362. space = _this$convertWhitespa.space,
  39363. rawSpace = _this$convertWhitespa.rawSpace;
  39364. if (rawSpace !== undefined) {
  39365. last.rawSpaceAfter += rawSpace;
  39366. }
  39367. last.spaces.after += space;
  39368. } else {
  39369. nodes.forEach(function (n) {
  39370. return _this3.newNode(n);
  39371. });
  39372. }
  39373. }
  39374. return;
  39375. }
  39376. var firstToken = this.currToken;
  39377. var spaceOrDescendantSelectorNodes = undefined;
  39378. if (nextSigTokenPos > this.position) {
  39379. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  39380. }
  39381. var node;
  39382. if (this.isNamedCombinator()) {
  39383. node = this.namedCombinator();
  39384. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  39385. node = new _combinator["default"]({
  39386. value: this.content(),
  39387. source: getTokenSource(this.currToken),
  39388. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  39389. });
  39390. this.position++;
  39391. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  39392. this.unexpected();
  39393. }
  39394. if (node) {
  39395. if (spaceOrDescendantSelectorNodes) {
  39396. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  39397. _space = _this$convertWhitespa2.space,
  39398. _rawSpace = _this$convertWhitespa2.rawSpace;
  39399. node.spaces.before = _space;
  39400. node.rawSpaceBefore = _rawSpace;
  39401. }
  39402. } else {
  39403. // descendant combinator
  39404. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  39405. _space2 = _this$convertWhitespa3.space,
  39406. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  39407. if (!_rawSpace2) {
  39408. _rawSpace2 = _space2;
  39409. }
  39410. var spaces = {};
  39411. var raws = {
  39412. spaces: {}
  39413. };
  39414. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  39415. spaces.before = _space2.slice(0, _space2.length - 1);
  39416. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  39417. } else if (_space2[0] === ' ' && _rawSpace2[0] === ' ') {
  39418. spaces.after = _space2.slice(1);
  39419. raws.spaces.after = _rawSpace2.slice(1);
  39420. } else {
  39421. raws.value = _rawSpace2;
  39422. }
  39423. node = new _combinator["default"]({
  39424. value: ' ',
  39425. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  39426. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  39427. spaces: spaces,
  39428. raws: raws
  39429. });
  39430. }
  39431. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  39432. node.spaces.after = this.optionalSpace(this.content());
  39433. this.position++;
  39434. }
  39435. return this.newNode(node);
  39436. };
  39437. _proto.comma = function comma() {
  39438. if (this.position === this.tokens.length - 1) {
  39439. this.root.trailingComma = true;
  39440. this.position++;
  39441. return;
  39442. }
  39443. this.current._inferEndPosition();
  39444. var selector = new _selector["default"]({
  39445. source: {
  39446. start: tokenStart(this.tokens[this.position + 1])
  39447. },
  39448. sourceIndex: this.tokens[this.position + 1][_tokenize.FIELDS.START_POS]
  39449. });
  39450. this.current.parent.append(selector);
  39451. this.current = selector;
  39452. this.position++;
  39453. };
  39454. _proto.comment = function comment() {
  39455. var current = this.currToken;
  39456. this.newNode(new _comment["default"]({
  39457. value: this.content(),
  39458. source: getTokenSource(current),
  39459. sourceIndex: current[_tokenize.FIELDS.START_POS]
  39460. }));
  39461. this.position++;
  39462. };
  39463. _proto.error = function error(message, opts) {
  39464. throw this.root.error(message, opts);
  39465. };
  39466. _proto.missingBackslash = function missingBackslash() {
  39467. return this.error('Expected a backslash preceding the semicolon.', {
  39468. index: this.currToken[_tokenize.FIELDS.START_POS]
  39469. });
  39470. };
  39471. _proto.missingParenthesis = function missingParenthesis() {
  39472. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  39473. };
  39474. _proto.missingSquareBracket = function missingSquareBracket() {
  39475. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  39476. };
  39477. _proto.unexpected = function unexpected() {
  39478. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  39479. };
  39480. _proto.unexpectedPipe = function unexpectedPipe() {
  39481. return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  39482. };
  39483. _proto.namespace = function namespace() {
  39484. var before = this.prevToken && this.content(this.prevToken) || true;
  39485. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  39486. this.position++;
  39487. return this.word(before);
  39488. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  39489. this.position++;
  39490. return this.universal(before);
  39491. }
  39492. this.unexpectedPipe();
  39493. };
  39494. _proto.nesting = function nesting() {
  39495. if (this.nextToken) {
  39496. var nextContent = this.content(this.nextToken);
  39497. if (nextContent === "|") {
  39498. this.position++;
  39499. return;
  39500. }
  39501. }
  39502. var current = this.currToken;
  39503. this.newNode(new _nesting["default"]({
  39504. value: this.content(),
  39505. source: getTokenSource(current),
  39506. sourceIndex: current[_tokenize.FIELDS.START_POS]
  39507. }));
  39508. this.position++;
  39509. };
  39510. _proto.parentheses = function parentheses() {
  39511. var last = this.current.last;
  39512. var unbalanced = 1;
  39513. this.position++;
  39514. if (last && last.type === types.PSEUDO) {
  39515. var selector = new _selector["default"]({
  39516. source: {
  39517. start: tokenStart(this.tokens[this.position])
  39518. },
  39519. sourceIndex: this.tokens[this.position][_tokenize.FIELDS.START_POS]
  39520. });
  39521. var cache = this.current;
  39522. last.append(selector);
  39523. this.current = selector;
  39524. while (this.position < this.tokens.length && unbalanced) {
  39525. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  39526. unbalanced++;
  39527. }
  39528. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  39529. unbalanced--;
  39530. }
  39531. if (unbalanced) {
  39532. this.parse();
  39533. } else {
  39534. this.current.source.end = tokenEnd(this.currToken);
  39535. this.current.parent.source.end = tokenEnd(this.currToken);
  39536. this.position++;
  39537. }
  39538. }
  39539. this.current = cache;
  39540. } else {
  39541. // I think this case should be an error. It's used to implement a basic parse of media queries
  39542. // but I don't think it's a good idea.
  39543. var parenStart = this.currToken;
  39544. var parenValue = "(";
  39545. var parenEnd;
  39546. while (this.position < this.tokens.length && unbalanced) {
  39547. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  39548. unbalanced++;
  39549. }
  39550. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  39551. unbalanced--;
  39552. }
  39553. parenEnd = this.currToken;
  39554. parenValue += this.parseParenthesisToken(this.currToken);
  39555. this.position++;
  39556. }
  39557. if (last) {
  39558. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  39559. } else {
  39560. this.newNode(new _string["default"]({
  39561. value: parenValue,
  39562. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  39563. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  39564. }));
  39565. }
  39566. }
  39567. if (unbalanced) {
  39568. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  39569. }
  39570. };
  39571. _proto.pseudo = function pseudo() {
  39572. var _this4 = this;
  39573. var pseudoStr = '';
  39574. var startingToken = this.currToken;
  39575. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  39576. pseudoStr += this.content();
  39577. this.position++;
  39578. }
  39579. if (!this.currToken) {
  39580. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  39581. }
  39582. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  39583. this.splitWord(false, function (first, length) {
  39584. pseudoStr += first;
  39585. _this4.newNode(new _pseudo["default"]({
  39586. value: pseudoStr,
  39587. source: getTokenSourceSpan(startingToken, _this4.currToken),
  39588. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  39589. }));
  39590. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  39591. _this4.error('Misplaced parenthesis.', {
  39592. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  39593. });
  39594. }
  39595. });
  39596. } else {
  39597. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  39598. }
  39599. };
  39600. _proto.space = function space() {
  39601. var content = this.content();
  39602. // Handle space before and after the selector
  39603. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  39604. return node.type === 'comment';
  39605. })) {
  39606. this.spaces = this.optionalSpace(content);
  39607. this.position++;
  39608. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  39609. this.current.last.spaces.after = this.optionalSpace(content);
  39610. this.position++;
  39611. } else {
  39612. this.combinator();
  39613. }
  39614. };
  39615. _proto.string = function string() {
  39616. var current = this.currToken;
  39617. this.newNode(new _string["default"]({
  39618. value: this.content(),
  39619. source: getTokenSource(current),
  39620. sourceIndex: current[_tokenize.FIELDS.START_POS]
  39621. }));
  39622. this.position++;
  39623. };
  39624. _proto.universal = function universal(namespace) {
  39625. var nextToken = this.nextToken;
  39626. if (nextToken && this.content(nextToken) === '|') {
  39627. this.position++;
  39628. return this.namespace();
  39629. }
  39630. var current = this.currToken;
  39631. this.newNode(new _universal["default"]({
  39632. value: this.content(),
  39633. source: getTokenSource(current),
  39634. sourceIndex: current[_tokenize.FIELDS.START_POS]
  39635. }), namespace);
  39636. this.position++;
  39637. };
  39638. _proto.splitWord = function splitWord(namespace, firstCallback) {
  39639. var _this5 = this;
  39640. var nextToken = this.nextToken;
  39641. var word = this.content();
  39642. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  39643. this.position++;
  39644. var current = this.content();
  39645. word += current;
  39646. if (current.lastIndexOf('\\') === current.length - 1) {
  39647. var next = this.nextToken;
  39648. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  39649. word += this.requiredSpace(this.content(next));
  39650. this.position++;
  39651. }
  39652. }
  39653. nextToken = this.nextToken;
  39654. }
  39655. var hasClass = indexesOf(word, '.').filter(function (i) {
  39656. // Allow escaped dot within class name
  39657. var escapedDot = word[i - 1] === '\\';
  39658. // Allow decimal numbers percent in @keyframes
  39659. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  39660. return !escapedDot && !isKeyframesPercent;
  39661. });
  39662. var hasId = indexesOf(word, '#').filter(function (i) {
  39663. return word[i - 1] !== '\\';
  39664. });
  39665. // Eliminate Sass interpolations from the list of id indexes
  39666. var interpolations = indexesOf(word, '#{');
  39667. if (interpolations.length) {
  39668. hasId = hasId.filter(function (hashIndex) {
  39669. return !~interpolations.indexOf(hashIndex);
  39670. });
  39671. }
  39672. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  39673. indices.forEach(function (ind, i) {
  39674. var index = indices[i + 1] || word.length;
  39675. var value = word.slice(ind, index);
  39676. if (i === 0 && firstCallback) {
  39677. return firstCallback.call(_this5, value, indices.length);
  39678. }
  39679. var node;
  39680. var current = _this5.currToken;
  39681. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  39682. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  39683. if (~hasClass.indexOf(ind)) {
  39684. var classNameOpts = {
  39685. value: value.slice(1),
  39686. source: source,
  39687. sourceIndex: sourceIndex
  39688. };
  39689. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  39690. } else if (~hasId.indexOf(ind)) {
  39691. var idOpts = {
  39692. value: value.slice(1),
  39693. source: source,
  39694. sourceIndex: sourceIndex
  39695. };
  39696. node = new _id["default"](unescapeProp(idOpts, "value"));
  39697. } else {
  39698. var tagOpts = {
  39699. value: value,
  39700. source: source,
  39701. sourceIndex: sourceIndex
  39702. };
  39703. unescapeProp(tagOpts, "value");
  39704. node = new _tag["default"](tagOpts);
  39705. }
  39706. _this5.newNode(node, namespace);
  39707. // Ensure that the namespace is used only once
  39708. namespace = null;
  39709. });
  39710. this.position++;
  39711. };
  39712. _proto.word = function word(namespace) {
  39713. var nextToken = this.nextToken;
  39714. if (nextToken && this.content(nextToken) === '|') {
  39715. this.position++;
  39716. return this.namespace();
  39717. }
  39718. return this.splitWord(namespace);
  39719. };
  39720. _proto.loop = function loop() {
  39721. while (this.position < this.tokens.length) {
  39722. this.parse(true);
  39723. }
  39724. this.current._inferEndPosition();
  39725. return this.root;
  39726. };
  39727. _proto.parse = function parse(throwOnParenthesis) {
  39728. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  39729. case tokens.space:
  39730. this.space();
  39731. break;
  39732. case tokens.comment:
  39733. this.comment();
  39734. break;
  39735. case tokens.openParenthesis:
  39736. this.parentheses();
  39737. break;
  39738. case tokens.closeParenthesis:
  39739. if (throwOnParenthesis) {
  39740. this.missingParenthesis();
  39741. }
  39742. break;
  39743. case tokens.openSquare:
  39744. this.attribute();
  39745. break;
  39746. case tokens.dollar:
  39747. case tokens.caret:
  39748. case tokens.equals:
  39749. case tokens.word:
  39750. this.word();
  39751. break;
  39752. case tokens.colon:
  39753. this.pseudo();
  39754. break;
  39755. case tokens.comma:
  39756. this.comma();
  39757. break;
  39758. case tokens.asterisk:
  39759. this.universal();
  39760. break;
  39761. case tokens.ampersand:
  39762. this.nesting();
  39763. break;
  39764. case tokens.slash:
  39765. case tokens.combinator:
  39766. this.combinator();
  39767. break;
  39768. case tokens.str:
  39769. this.string();
  39770. break;
  39771. // These cases throw; no break needed.
  39772. case tokens.closeSquare:
  39773. this.missingSquareBracket();
  39774. case tokens.semicolon:
  39775. this.missingBackslash();
  39776. default:
  39777. this.unexpected();
  39778. }
  39779. }
  39780. /**
  39781. * Helpers
  39782. */;
  39783. _proto.expected = function expected(description, index, found) {
  39784. if (Array.isArray(description)) {
  39785. var last = description.pop();
  39786. description = description.join(', ') + " or " + last;
  39787. }
  39788. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  39789. if (!found) {
  39790. return this.error("Expected " + an + " " + description + ".", {
  39791. index: index
  39792. });
  39793. }
  39794. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  39795. index: index
  39796. });
  39797. };
  39798. _proto.requiredSpace = function requiredSpace(space) {
  39799. return this.options.lossy ? ' ' : space;
  39800. };
  39801. _proto.optionalSpace = function optionalSpace(space) {
  39802. return this.options.lossy ? '' : space;
  39803. };
  39804. _proto.lossySpace = function lossySpace(space, required) {
  39805. if (this.options.lossy) {
  39806. return required ? ' ' : '';
  39807. } else {
  39808. return space;
  39809. }
  39810. };
  39811. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  39812. var content = this.content(token);
  39813. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  39814. return this.requiredSpace(content);
  39815. } else {
  39816. return content;
  39817. }
  39818. };
  39819. _proto.newNode = function newNode(node, namespace) {
  39820. if (namespace) {
  39821. if (/^ +$/.test(namespace)) {
  39822. if (!this.options.lossy) {
  39823. this.spaces = (this.spaces || '') + namespace;
  39824. }
  39825. namespace = true;
  39826. }
  39827. node.namespace = namespace;
  39828. unescapeProp(node, "namespace");
  39829. }
  39830. if (this.spaces) {
  39831. node.spaces.before = this.spaces;
  39832. this.spaces = '';
  39833. }
  39834. return this.current.append(node);
  39835. };
  39836. _proto.content = function content(token) {
  39837. if (token === void 0) {
  39838. token = this.currToken;
  39839. }
  39840. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  39841. };
  39842. /**
  39843. * returns the index of the next non-whitespace, non-comment token.
  39844. * returns -1 if no meaningful token is found.
  39845. */
  39846. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  39847. if (startPosition === void 0) {
  39848. startPosition = this.position + 1;
  39849. }
  39850. var searchPosition = startPosition;
  39851. while (searchPosition < this.tokens.length) {
  39852. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  39853. searchPosition++;
  39854. continue;
  39855. } else {
  39856. return searchPosition;
  39857. }
  39858. }
  39859. return -1;
  39860. };
  39861. _createClass(Parser, [{
  39862. key: "currToken",
  39863. get: function get() {
  39864. return this.tokens[this.position];
  39865. }
  39866. }, {
  39867. key: "nextToken",
  39868. get: function get() {
  39869. return this.tokens[this.position + 1];
  39870. }
  39871. }, {
  39872. key: "prevToken",
  39873. get: function get() {
  39874. return this.tokens[this.position - 1];
  39875. }
  39876. }]);
  39877. return Parser;
  39878. }();
  39879. exports["default"] = Parser;
  39880. module.exports = exports.default;
  39881. } (parser, parser.exports));
  39882. return parser.exports;
  39883. }
  39884. var hasRequiredProcessor;
  39885. function requireProcessor () {
  39886. if (hasRequiredProcessor) return processor.exports;
  39887. hasRequiredProcessor = 1;
  39888. (function (module, exports) {
  39889. exports.__esModule = true;
  39890. exports["default"] = void 0;
  39891. var _parser = _interopRequireDefault(/*@__PURE__*/ requireParser());
  39892. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  39893. var Processor = /*#__PURE__*/function () {
  39894. function Processor(func, options) {
  39895. this.func = func || function noop() {};
  39896. this.funcRes = null;
  39897. this.options = options;
  39898. }
  39899. var _proto = Processor.prototype;
  39900. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  39901. if (options === void 0) {
  39902. options = {};
  39903. }
  39904. var merged = Object.assign({}, this.options, options);
  39905. if (merged.updateSelector === false) {
  39906. return false;
  39907. } else {
  39908. return typeof rule !== "string";
  39909. }
  39910. };
  39911. _proto._isLossy = function _isLossy(options) {
  39912. if (options === void 0) {
  39913. options = {};
  39914. }
  39915. var merged = Object.assign({}, this.options, options);
  39916. if (merged.lossless === false) {
  39917. return true;
  39918. } else {
  39919. return false;
  39920. }
  39921. };
  39922. _proto._root = function _root(rule, options) {
  39923. if (options === void 0) {
  39924. options = {};
  39925. }
  39926. var parser = new _parser["default"](rule, this._parseOptions(options));
  39927. return parser.root;
  39928. };
  39929. _proto._parseOptions = function _parseOptions(options) {
  39930. return {
  39931. lossy: this._isLossy(options)
  39932. };
  39933. };
  39934. _proto._run = function _run(rule, options) {
  39935. var _this = this;
  39936. if (options === void 0) {
  39937. options = {};
  39938. }
  39939. return new Promise(function (resolve, reject) {
  39940. try {
  39941. var root = _this._root(rule, options);
  39942. Promise.resolve(_this.func(root)).then(function (transform) {
  39943. var string = undefined;
  39944. if (_this._shouldUpdateSelector(rule, options)) {
  39945. string = root.toString();
  39946. rule.selector = string;
  39947. }
  39948. return {
  39949. transform: transform,
  39950. root: root,
  39951. string: string
  39952. };
  39953. }).then(resolve, reject);
  39954. } catch (e) {
  39955. reject(e);
  39956. return;
  39957. }
  39958. });
  39959. };
  39960. _proto._runSync = function _runSync(rule, options) {
  39961. if (options === void 0) {
  39962. options = {};
  39963. }
  39964. var root = this._root(rule, options);
  39965. var transform = this.func(root);
  39966. if (transform && typeof transform.then === "function") {
  39967. throw new Error("Selector processor returned a promise to a synchronous call.");
  39968. }
  39969. var string = undefined;
  39970. if (options.updateSelector && typeof rule !== "string") {
  39971. string = root.toString();
  39972. rule.selector = string;
  39973. }
  39974. return {
  39975. transform: transform,
  39976. root: root,
  39977. string: string
  39978. };
  39979. }
  39980. /**
  39981. * Process rule into a selector AST.
  39982. *
  39983. * @param rule {postcss.Rule | string} The css selector to be processed
  39984. * @param options The options for processing
  39985. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  39986. */;
  39987. _proto.ast = function ast(rule, options) {
  39988. return this._run(rule, options).then(function (result) {
  39989. return result.root;
  39990. });
  39991. }
  39992. /**
  39993. * Process rule into a selector AST synchronously.
  39994. *
  39995. * @param rule {postcss.Rule | string} The css selector to be processed
  39996. * @param options The options for processing
  39997. * @returns {parser.Root} The AST of the selector after processing it.
  39998. */;
  39999. _proto.astSync = function astSync(rule, options) {
  40000. return this._runSync(rule, options).root;
  40001. }
  40002. /**
  40003. * Process a selector into a transformed value asynchronously
  40004. *
  40005. * @param rule {postcss.Rule | string} The css selector to be processed
  40006. * @param options The options for processing
  40007. * @returns {Promise<any>} The value returned by the processor.
  40008. */;
  40009. _proto.transform = function transform(rule, options) {
  40010. return this._run(rule, options).then(function (result) {
  40011. return result.transform;
  40012. });
  40013. }
  40014. /**
  40015. * Process a selector into a transformed value synchronously.
  40016. *
  40017. * @param rule {postcss.Rule | string} The css selector to be processed
  40018. * @param options The options for processing
  40019. * @returns {any} The value returned by the processor.
  40020. */;
  40021. _proto.transformSync = function transformSync(rule, options) {
  40022. return this._runSync(rule, options).transform;
  40023. }
  40024. /**
  40025. * Process a selector into a new selector string asynchronously.
  40026. *
  40027. * @param rule {postcss.Rule | string} The css selector to be processed
  40028. * @param options The options for processing
  40029. * @returns {string} the selector after processing.
  40030. */;
  40031. _proto.process = function process(rule, options) {
  40032. return this._run(rule, options).then(function (result) {
  40033. return result.string || result.root.toString();
  40034. });
  40035. }
  40036. /**
  40037. * Process a selector into a new selector string synchronously.
  40038. *
  40039. * @param rule {postcss.Rule | string} The css selector to be processed
  40040. * @param options The options for processing
  40041. * @returns {string} the selector after processing.
  40042. */;
  40043. _proto.processSync = function processSync(rule, options) {
  40044. var result = this._runSync(rule, options);
  40045. return result.string || result.root.toString();
  40046. };
  40047. return Processor;
  40048. }();
  40049. exports["default"] = Processor;
  40050. module.exports = exports.default;
  40051. } (processor, processor.exports));
  40052. return processor.exports;
  40053. }
  40054. var selectors = {};
  40055. var constructors = {};
  40056. var hasRequiredConstructors;
  40057. function requireConstructors () {
  40058. if (hasRequiredConstructors) return constructors;
  40059. hasRequiredConstructors = 1;
  40060. constructors.__esModule = true;
  40061. constructors.universal = constructors.tag = constructors.string = constructors.selector = constructors.root = constructors.pseudo = constructors.nesting = constructors.id = constructors.comment = constructors.combinator = constructors.className = constructors.attribute = void 0;
  40062. var _attribute = _interopRequireDefault(/*@__PURE__*/ requireAttribute());
  40063. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName());
  40064. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator());
  40065. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment());
  40066. var _id = _interopRequireDefault(/*@__PURE__*/ requireId());
  40067. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting());
  40068. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo());
  40069. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot());
  40070. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector());
  40071. var _string = _interopRequireDefault(/*@__PURE__*/ requireString());
  40072. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag());
  40073. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal());
  40074. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40075. var attribute = function attribute(opts) {
  40076. return new _attribute["default"](opts);
  40077. };
  40078. constructors.attribute = attribute;
  40079. var className = function className(opts) {
  40080. return new _className["default"](opts);
  40081. };
  40082. constructors.className = className;
  40083. var combinator = function combinator(opts) {
  40084. return new _combinator["default"](opts);
  40085. };
  40086. constructors.combinator = combinator;
  40087. var comment = function comment(opts) {
  40088. return new _comment["default"](opts);
  40089. };
  40090. constructors.comment = comment;
  40091. var id = function id(opts) {
  40092. return new _id["default"](opts);
  40093. };
  40094. constructors.id = id;
  40095. var nesting = function nesting(opts) {
  40096. return new _nesting["default"](opts);
  40097. };
  40098. constructors.nesting = nesting;
  40099. var pseudo = function pseudo(opts) {
  40100. return new _pseudo["default"](opts);
  40101. };
  40102. constructors.pseudo = pseudo;
  40103. var root = function root(opts) {
  40104. return new _root["default"](opts);
  40105. };
  40106. constructors.root = root;
  40107. var selector = function selector(opts) {
  40108. return new _selector["default"](opts);
  40109. };
  40110. constructors.selector = selector;
  40111. var string = function string(opts) {
  40112. return new _string["default"](opts);
  40113. };
  40114. constructors.string = string;
  40115. var tag = function tag(opts) {
  40116. return new _tag["default"](opts);
  40117. };
  40118. constructors.tag = tag;
  40119. var universal = function universal(opts) {
  40120. return new _universal["default"](opts);
  40121. };
  40122. constructors.universal = universal;
  40123. return constructors;
  40124. }
  40125. var guards = {};
  40126. var hasRequiredGuards;
  40127. function requireGuards () {
  40128. if (hasRequiredGuards) return guards;
  40129. hasRequiredGuards = 1;
  40130. guards.__esModule = true;
  40131. guards.isComment = guards.isCombinator = guards.isClassName = guards.isAttribute = void 0;
  40132. guards.isContainer = isContainer;
  40133. guards.isIdentifier = void 0;
  40134. guards.isNamespace = isNamespace;
  40135. guards.isNesting = void 0;
  40136. guards.isNode = isNode;
  40137. guards.isPseudo = void 0;
  40138. guards.isPseudoClass = isPseudoClass;
  40139. guards.isPseudoElement = isPseudoElement;
  40140. guards.isUniversal = guards.isTag = guards.isString = guards.isSelector = guards.isRoot = void 0;
  40141. var _types = /*@__PURE__*/ requireTypes();
  40142. var _IS_TYPE;
  40143. var IS_TYPE = (_IS_TYPE = {}, _IS_TYPE[_types.ATTRIBUTE] = true, _IS_TYPE[_types.CLASS] = true, _IS_TYPE[_types.COMBINATOR] = true, _IS_TYPE[_types.COMMENT] = true, _IS_TYPE[_types.ID] = true, _IS_TYPE[_types.NESTING] = true, _IS_TYPE[_types.PSEUDO] = true, _IS_TYPE[_types.ROOT] = true, _IS_TYPE[_types.SELECTOR] = true, _IS_TYPE[_types.STRING] = true, _IS_TYPE[_types.TAG] = true, _IS_TYPE[_types.UNIVERSAL] = true, _IS_TYPE);
  40144. function isNode(node) {
  40145. return typeof node === "object" && IS_TYPE[node.type];
  40146. }
  40147. function isNodeType(type, node) {
  40148. return isNode(node) && node.type === type;
  40149. }
  40150. var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  40151. guards.isAttribute = isAttribute;
  40152. var isClassName = isNodeType.bind(null, _types.CLASS);
  40153. guards.isClassName = isClassName;
  40154. var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  40155. guards.isCombinator = isCombinator;
  40156. var isComment = isNodeType.bind(null, _types.COMMENT);
  40157. guards.isComment = isComment;
  40158. var isIdentifier = isNodeType.bind(null, _types.ID);
  40159. guards.isIdentifier = isIdentifier;
  40160. var isNesting = isNodeType.bind(null, _types.NESTING);
  40161. guards.isNesting = isNesting;
  40162. var isPseudo = isNodeType.bind(null, _types.PSEUDO);
  40163. guards.isPseudo = isPseudo;
  40164. var isRoot = isNodeType.bind(null, _types.ROOT);
  40165. guards.isRoot = isRoot;
  40166. var isSelector = isNodeType.bind(null, _types.SELECTOR);
  40167. guards.isSelector = isSelector;
  40168. var isString = isNodeType.bind(null, _types.STRING);
  40169. guards.isString = isString;
  40170. var isTag = isNodeType.bind(null, _types.TAG);
  40171. guards.isTag = isTag;
  40172. var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  40173. guards.isUniversal = isUniversal;
  40174. function isPseudoElement(node) {
  40175. return isPseudo(node) && node.value && (node.value.startsWith("::") || node.value.toLowerCase() === ":before" || node.value.toLowerCase() === ":after" || node.value.toLowerCase() === ":first-letter" || node.value.toLowerCase() === ":first-line");
  40176. }
  40177. function isPseudoClass(node) {
  40178. return isPseudo(node) && !isPseudoElement(node);
  40179. }
  40180. function isContainer(node) {
  40181. return !!(isNode(node) && node.walk);
  40182. }
  40183. function isNamespace(node) {
  40184. return isAttribute(node) || isTag(node);
  40185. }
  40186. return guards;
  40187. }
  40188. var hasRequiredSelectors;
  40189. function requireSelectors () {
  40190. if (hasRequiredSelectors) return selectors;
  40191. hasRequiredSelectors = 1;
  40192. (function (exports) {
  40193. exports.__esModule = true;
  40194. var _types = /*@__PURE__*/ requireTypes();
  40195. Object.keys(_types).forEach(function (key) {
  40196. if (key === "default" || key === "__esModule") return;
  40197. if (key in exports && exports[key] === _types[key]) return;
  40198. exports[key] = _types[key];
  40199. });
  40200. var _constructors = /*@__PURE__*/ requireConstructors();
  40201. Object.keys(_constructors).forEach(function (key) {
  40202. if (key === "default" || key === "__esModule") return;
  40203. if (key in exports && exports[key] === _constructors[key]) return;
  40204. exports[key] = _constructors[key];
  40205. });
  40206. var _guards = /*@__PURE__*/ requireGuards();
  40207. Object.keys(_guards).forEach(function (key) {
  40208. if (key === "default" || key === "__esModule") return;
  40209. if (key in exports && exports[key] === _guards[key]) return;
  40210. exports[key] = _guards[key];
  40211. });
  40212. } (selectors));
  40213. return selectors;
  40214. }
  40215. var hasRequiredDist;
  40216. function requireDist () {
  40217. if (hasRequiredDist) return dist.exports;
  40218. hasRequiredDist = 1;
  40219. (function (module, exports) {
  40220. exports.__esModule = true;
  40221. exports["default"] = void 0;
  40222. var _processor = _interopRequireDefault(/*@__PURE__*/ requireProcessor());
  40223. var selectors = _interopRequireWildcard(/*@__PURE__*/ requireSelectors());
  40224. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  40225. function _interopRequireWildcard(obj, nodeInterop) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  40226. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  40227. var parser = function parser(processor) {
  40228. return new _processor["default"](processor);
  40229. };
  40230. Object.assign(parser, selectors);
  40231. delete parser.__esModule;
  40232. var _default = parser;
  40233. exports["default"] = _default;
  40234. module.exports = exports.default;
  40235. } (dist, dist.exports));
  40236. return dist.exports;
  40237. }
  40238. var distExports = /*@__PURE__*/ requireDist();
  40239. var selectorParser = /*@__PURE__*/getDefaultExportFromCjs(distExports);
  40240. const animationNameRE = /^(?:-\w+-)?animation-name$/;
  40241. const animationRE = /^(?:-\w+-)?animation$/;
  40242. const keyframesRE = /^(?:-\w+-)?keyframes$/;
  40243. const scopedPlugin = (id = "") => {
  40244. const keyframes = /* @__PURE__ */ Object.create(null);
  40245. const shortId = id.replace(/^data-v-/, "");
  40246. return {
  40247. postcssPlugin: "vue-sfc-scoped",
  40248. Rule(rule) {
  40249. processRule(id, rule);
  40250. },
  40251. AtRule(node) {
  40252. if (keyframesRE.test(node.name) && !node.params.endsWith(`-${shortId}`)) {
  40253. keyframes[node.params] = node.params = node.params + "-" + shortId;
  40254. }
  40255. },
  40256. OnceExit(root) {
  40257. if (Object.keys(keyframes).length) {
  40258. root.walkDecls((decl) => {
  40259. if (animationNameRE.test(decl.prop)) {
  40260. decl.value = decl.value.split(",").map((v) => keyframes[v.trim()] || v.trim()).join(",");
  40261. }
  40262. if (animationRE.test(decl.prop)) {
  40263. decl.value = decl.value.split(",").map((v) => {
  40264. const vals = v.trim().split(/\s+/);
  40265. const i = vals.findIndex((val) => keyframes[val]);
  40266. if (i !== -1) {
  40267. vals.splice(i, 1, keyframes[vals[i]]);
  40268. return vals.join(" ");
  40269. } else {
  40270. return v;
  40271. }
  40272. }).join(",");
  40273. }
  40274. });
  40275. }
  40276. }
  40277. };
  40278. };
  40279. const processedRules = /* @__PURE__ */ new WeakSet();
  40280. function processRule(id, rule) {
  40281. if (processedRules.has(rule) || rule.parent && rule.parent.type === "atrule" && keyframesRE.test(rule.parent.name)) {
  40282. return;
  40283. }
  40284. processedRules.add(rule);
  40285. let deep = false;
  40286. let parent = rule.parent;
  40287. while (parent && parent.type !== "root") {
  40288. if (parent.__deep) {
  40289. deep = true;
  40290. break;
  40291. }
  40292. parent = parent.parent;
  40293. }
  40294. rule.selector = selectorParser((selectorRoot) => {
  40295. selectorRoot.each((selector) => {
  40296. rewriteSelector(id, rule, selector, selectorRoot, deep);
  40297. });
  40298. }).processSync(rule.selector);
  40299. }
  40300. function rewriteSelector(id, rule, selector, selectorRoot, deep, slotted = false) {
  40301. let node = null;
  40302. let shouldInject = !deep;
  40303. let hasNestedDeep = false;
  40304. let splitForNestedDeep = false;
  40305. selector.each((n) => {
  40306. if (n.type === "combinator" && (n.value === ">>>" || n.value === "/deep/")) {
  40307. n.value = " ";
  40308. n.spaces.before = n.spaces.after = "";
  40309. warn(
  40310. `the >>> and /deep/ combinators have been deprecated. Use :deep() instead.`
  40311. );
  40312. return false;
  40313. }
  40314. if (n.type === "pseudo") {
  40315. const { value } = n;
  40316. if (isDeepContainerPseudo(n)) {
  40317. const hasDeepSelectors = n.nodes.some(
  40318. (selector2) => selector2.some(isDeepSelector)
  40319. );
  40320. if (hasDeepSelectors) {
  40321. const hasScopeAnchor = !!node;
  40322. const hasMixedSelectors = n.nodes.some(
  40323. (selector2) => !selector2.some(isDeepSelector)
  40324. );
  40325. const hasTrailingNodes = selector.index(n) < selector.length - 1;
  40326. if (canSplitDeepContainerPseudo(n) && !deep && !hasScopeAnchor && hasMixedSelectors && hasTrailingNodes) {
  40327. splitSelectorForNestedDeep(
  40328. id,
  40329. rule,
  40330. selector,
  40331. selectorRoot,
  40332. n,
  40333. deep,
  40334. slotted
  40335. );
  40336. splitForNestedDeep = true;
  40337. return false;
  40338. }
  40339. if (value === ":not" && !deep && !hasScopeAnchor && hasMixedSelectors && hasTrailingNodes) {
  40340. return;
  40341. }
  40342. n.nodes.forEach(
  40343. (selector2) => rewriteSelector(
  40344. id,
  40345. rule,
  40346. selector2,
  40347. selectorRoot,
  40348. deep || hasScopeAnchor,
  40349. slotted
  40350. )
  40351. );
  40352. if (!hasScopeAnchor) {
  40353. node = n;
  40354. shouldInject = false;
  40355. }
  40356. hasNestedDeep = true;
  40357. }
  40358. }
  40359. if (value === ":deep" || value === "::v-deep") {
  40360. rule.__deep = true;
  40361. if (n.nodes.length) {
  40362. let last = n;
  40363. n.nodes[0].each((ss) => {
  40364. selector.insertAfter(last, ss);
  40365. last = ss;
  40366. });
  40367. const prev = selector.at(selector.index(n) - 1);
  40368. if (!prev || !isSpaceCombinator(prev)) {
  40369. selector.insertAfter(
  40370. n,
  40371. selectorParser.combinator({
  40372. value: " "
  40373. })
  40374. );
  40375. }
  40376. selector.removeChild(n);
  40377. } else {
  40378. warn(
  40379. `${value} usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead of ${value} <inner-selector>.`
  40380. );
  40381. const prev = selector.at(selector.index(n) - 1);
  40382. if (prev && isSpaceCombinator(prev)) {
  40383. selector.removeChild(prev);
  40384. }
  40385. selector.removeChild(n);
  40386. }
  40387. return false;
  40388. }
  40389. if (value === ":slotted" || value === "::v-slotted") {
  40390. rewriteSelector(
  40391. id,
  40392. rule,
  40393. n.nodes[0],
  40394. selectorRoot,
  40395. deep,
  40396. true
  40397. );
  40398. let last = n;
  40399. n.nodes[0].each((ss) => {
  40400. selector.insertAfter(last, ss);
  40401. last = ss;
  40402. });
  40403. selector.removeChild(n);
  40404. shouldInject = false;
  40405. return false;
  40406. }
  40407. if (value === ":global" || value === "::v-global") {
  40408. selector.replaceWith(n.nodes[0]);
  40409. return false;
  40410. }
  40411. }
  40412. if (n.type === "universal") {
  40413. const prev = selector.at(selector.index(n) - 1);
  40414. const next = selector.at(selector.index(n) + 1);
  40415. if (!prev) {
  40416. if (next) {
  40417. if (next.type === "combinator" && next.value === " ") {
  40418. selector.removeChild(next);
  40419. }
  40420. selector.removeChild(n);
  40421. return;
  40422. } else {
  40423. node = selectorParser.combinator({
  40424. value: ""
  40425. });
  40426. selector.insertBefore(n, node);
  40427. selector.removeChild(n);
  40428. return false;
  40429. }
  40430. }
  40431. if (node) return;
  40432. }
  40433. if (!hasNestedDeep && (n.type !== "pseudo" && n.type !== "combinator" || n.type === "pseudo" && (n.value === ":is" || n.value === ":where") && !node)) {
  40434. node = n;
  40435. }
  40436. });
  40437. if (splitForNestedDeep) {
  40438. return;
  40439. }
  40440. if (rule.nodes.some((node2) => node2.type === "rule")) {
  40441. const deep2 = rule.__deep;
  40442. if (!deep2) {
  40443. extractAndWrapNodes(rule);
  40444. const atruleNodes = rule.nodes.filter((node2) => node2.type === "atrule");
  40445. for (const atnode of atruleNodes) {
  40446. extractAndWrapNodes(atnode);
  40447. }
  40448. }
  40449. shouldInject = deep2;
  40450. }
  40451. if (node && !hasNestedDeep) {
  40452. const { type, value } = node;
  40453. if (type === "pseudo" && (value === ":is" || value === ":where")) {
  40454. node.nodes.forEach(
  40455. (value2) => rewriteSelector(id, rule, value2, selectorRoot, deep, slotted)
  40456. );
  40457. shouldInject = false;
  40458. }
  40459. }
  40460. if (node) {
  40461. node.spaces.after = "";
  40462. } else {
  40463. selector.first.spaces.before = "";
  40464. }
  40465. if (shouldInject) {
  40466. const idToAdd = slotted ? id + "-s" : id;
  40467. selector.insertAfter(
  40468. // If node is null it means we need to inject [id] at the start
  40469. // insertAfter can handle `null` here
  40470. node,
  40471. selectorParser.attribute({
  40472. attribute: idToAdd,
  40473. value: idToAdd,
  40474. raws: {},
  40475. quoteMark: `"`
  40476. })
  40477. );
  40478. }
  40479. }
  40480. function isSpaceCombinator(node) {
  40481. return node.type === "combinator" && /^\s+$/.test(node.value);
  40482. }
  40483. function isDeepSelector(node) {
  40484. var _a;
  40485. if (node.type === "pseudo" && (node.value === ":deep" || node.value === "::v-deep")) {
  40486. return true;
  40487. }
  40488. return !!((_a = node.nodes) == null ? void 0 : _a.some((child) => isDeepSelector(child)));
  40489. }
  40490. function isDeepContainerPseudo(node) {
  40491. return node.type === "pseudo" && (node.value === ":is" || node.value === ":where" || node.value === ":has" || node.value === ":not");
  40492. }
  40493. function canSplitDeepContainerPseudo(node) {
  40494. return node.value === ":is" || node.value === ":where" || node.value === ":has";
  40495. }
  40496. function splitSelectorForNestedDeep(id, rule, selector, selectorRoot, pseudo, deep, slotted) {
  40497. const pseudoIndex = selector.index(pseudo);
  40498. const selectors = pseudo.nodes.map((branch, index) => {
  40499. const branchSelector = selector.clone();
  40500. if (branchSelector.first) {
  40501. branchSelector.first.spaces.before = index === 0 ? selector.first.spaces.before : " ";
  40502. }
  40503. const branchPseudo = branchSelector.at(pseudoIndex);
  40504. const branchClone = branch.clone();
  40505. if (branchClone.first) {
  40506. branchClone.first.spaces.before = "";
  40507. }
  40508. branchPseudo.removeAll();
  40509. branchPseudo.append(branchClone);
  40510. rewriteSelector(id, rule, branchSelector, selectorRoot, deep, slotted);
  40511. return branchSelector;
  40512. });
  40513. selector.replaceWith(...selectors);
  40514. }
  40515. function extractAndWrapNodes(parentNode) {
  40516. if (!parentNode.nodes) return;
  40517. const nodes = parentNode.nodes.filter(
  40518. (node) => node.type === "decl" || node.type === "comment"
  40519. );
  40520. if (nodes.length) {
  40521. for (const node of nodes) {
  40522. parentNode.removeChild(node);
  40523. }
  40524. const wrappedRule = new Rule({
  40525. nodes,
  40526. selector: "&"
  40527. });
  40528. parentNode.prepend(wrappedRule);
  40529. }
  40530. }
  40531. scopedPlugin.postcss = true;
  40532. var sourceMap = {};
  40533. var sourceMapGenerator = {};
  40534. var base64Vlq = {};
  40535. var base64 = {};
  40536. /* -*- Mode: js; js-indent-level: 2; -*- */
  40537. var hasRequiredBase64;
  40538. function requireBase64 () {
  40539. if (hasRequiredBase64) return base64;
  40540. hasRequiredBase64 = 1;
  40541. /*
  40542. * Copyright 2011 Mozilla Foundation and contributors
  40543. * Licensed under the New BSD license. See LICENSE or:
  40544. * http://opensource.org/licenses/BSD-3-Clause
  40545. */
  40546. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  40547. /**
  40548. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  40549. */
  40550. base64.encode = function (number) {
  40551. if (0 <= number && number < intToCharMap.length) {
  40552. return intToCharMap[number];
  40553. }
  40554. throw new TypeError("Must be between 0 and 63: " + number);
  40555. };
  40556. /**
  40557. * Decode a single base 64 character code digit to an integer. Returns -1 on
  40558. * failure.
  40559. */
  40560. base64.decode = function (charCode) {
  40561. var bigA = 65; // 'A'
  40562. var bigZ = 90; // 'Z'
  40563. var littleA = 97; // 'a'
  40564. var littleZ = 122; // 'z'
  40565. var zero = 48; // '0'
  40566. var nine = 57; // '9'
  40567. var plus = 43; // '+'
  40568. var slash = 47; // '/'
  40569. var littleOffset = 26;
  40570. var numberOffset = 52;
  40571. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  40572. if (bigA <= charCode && charCode <= bigZ) {
  40573. return (charCode - bigA);
  40574. }
  40575. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  40576. if (littleA <= charCode && charCode <= littleZ) {
  40577. return (charCode - littleA + littleOffset);
  40578. }
  40579. // 52 - 61: 0123456789
  40580. if (zero <= charCode && charCode <= nine) {
  40581. return (charCode - zero + numberOffset);
  40582. }
  40583. // 62: +
  40584. if (charCode == plus) {
  40585. return 62;
  40586. }
  40587. // 63: /
  40588. if (charCode == slash) {
  40589. return 63;
  40590. }
  40591. // Invalid base64 digit.
  40592. return -1;
  40593. };
  40594. return base64;
  40595. }
  40596. /* -*- Mode: js; js-indent-level: 2; -*- */
  40597. var hasRequiredBase64Vlq;
  40598. function requireBase64Vlq () {
  40599. if (hasRequiredBase64Vlq) return base64Vlq;
  40600. hasRequiredBase64Vlq = 1;
  40601. /*
  40602. * Copyright 2011 Mozilla Foundation and contributors
  40603. * Licensed under the New BSD license. See LICENSE or:
  40604. * http://opensource.org/licenses/BSD-3-Clause
  40605. *
  40606. * Based on the Base 64 VLQ implementation in Closure Compiler:
  40607. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  40608. *
  40609. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  40610. * Redistribution and use in source and binary forms, with or without
  40611. * modification, are permitted provided that the following conditions are
  40612. * met:
  40613. *
  40614. * * Redistributions of source code must retain the above copyright
  40615. * notice, this list of conditions and the following disclaimer.
  40616. * * Redistributions in binary form must reproduce the above
  40617. * copyright notice, this list of conditions and the following
  40618. * disclaimer in the documentation and/or other materials provided
  40619. * with the distribution.
  40620. * * Neither the name of Google Inc. nor the names of its
  40621. * contributors may be used to endorse or promote products derived
  40622. * from this software without specific prior written permission.
  40623. *
  40624. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  40625. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  40626. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  40627. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  40628. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40629. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  40630. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  40631. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  40632. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  40633. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  40634. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  40635. */
  40636. var base64 = /*@__PURE__*/ requireBase64();
  40637. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  40638. // length quantities we use in the source map spec, the first bit is the sign,
  40639. // the next four bits are the actual value, and the 6th bit is the
  40640. // continuation bit. The continuation bit tells us whether there are more
  40641. // digits in this value following this digit.
  40642. //
  40643. // Continuation
  40644. // | Sign
  40645. // | |
  40646. // V V
  40647. // 101011
  40648. var VLQ_BASE_SHIFT = 5;
  40649. // binary: 100000
  40650. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  40651. // binary: 011111
  40652. var VLQ_BASE_MASK = VLQ_BASE - 1;
  40653. // binary: 100000
  40654. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  40655. /**
  40656. * Converts from a two-complement value to a value where the sign bit is
  40657. * placed in the least significant bit. For example, as decimals:
  40658. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  40659. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  40660. */
  40661. function toVLQSigned(aValue) {
  40662. return aValue < 0
  40663. ? ((-aValue) << 1) + 1
  40664. : (aValue << 1) + 0;
  40665. }
  40666. /**
  40667. * Converts to a two-complement value from a value where the sign bit is
  40668. * placed in the least significant bit. For example, as decimals:
  40669. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  40670. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  40671. */
  40672. function fromVLQSigned(aValue) {
  40673. var isNegative = (aValue & 1) === 1;
  40674. var shifted = aValue >> 1;
  40675. return isNegative
  40676. ? -shifted
  40677. : shifted;
  40678. }
  40679. /**
  40680. * Returns the base 64 VLQ encoded value.
  40681. */
  40682. base64Vlq.encode = function base64VLQ_encode(aValue) {
  40683. var encoded = "";
  40684. var digit;
  40685. var vlq = toVLQSigned(aValue);
  40686. do {
  40687. digit = vlq & VLQ_BASE_MASK;
  40688. vlq >>>= VLQ_BASE_SHIFT;
  40689. if (vlq > 0) {
  40690. // There are still more digits in this value, so we must make sure the
  40691. // continuation bit is marked.
  40692. digit |= VLQ_CONTINUATION_BIT;
  40693. }
  40694. encoded += base64.encode(digit);
  40695. } while (vlq > 0);
  40696. return encoded;
  40697. };
  40698. /**
  40699. * Decodes the next base 64 VLQ value from the given string and returns the
  40700. * value and the rest of the string via the out parameter.
  40701. */
  40702. base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  40703. var strLen = aStr.length;
  40704. var result = 0;
  40705. var shift = 0;
  40706. var continuation, digit;
  40707. do {
  40708. if (aIndex >= strLen) {
  40709. throw new Error("Expected more digits in base 64 VLQ value.");
  40710. }
  40711. digit = base64.decode(aStr.charCodeAt(aIndex++));
  40712. if (digit === -1) {
  40713. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  40714. }
  40715. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  40716. digit &= VLQ_BASE_MASK;
  40717. result = result + (digit << shift);
  40718. shift += VLQ_BASE_SHIFT;
  40719. } while (continuation);
  40720. aOutParam.value = fromVLQSigned(result);
  40721. aOutParam.rest = aIndex;
  40722. };
  40723. return base64Vlq;
  40724. }
  40725. var util = {};
  40726. /* -*- Mode: js; js-indent-level: 2; -*- */
  40727. var hasRequiredUtil;
  40728. function requireUtil () {
  40729. if (hasRequiredUtil) return util;
  40730. hasRequiredUtil = 1;
  40731. (function (exports) {
  40732. /*
  40733. * Copyright 2011 Mozilla Foundation and contributors
  40734. * Licensed under the New BSD license. See LICENSE or:
  40735. * http://opensource.org/licenses/BSD-3-Clause
  40736. */
  40737. /**
  40738. * This is a helper function for getting values from parameter/options
  40739. * objects.
  40740. *
  40741. * @param args The object we are extracting values from
  40742. * @param name The name of the property we are getting.
  40743. * @param defaultValue An optional value to return if the property is missing
  40744. * from the object. If this is not specified and the property is missing, an
  40745. * error will be thrown.
  40746. */
  40747. function getArg(aArgs, aName, aDefaultValue) {
  40748. if (aName in aArgs) {
  40749. return aArgs[aName];
  40750. } else if (arguments.length === 3) {
  40751. return aDefaultValue;
  40752. } else {
  40753. throw new Error('"' + aName + '" is a required argument.');
  40754. }
  40755. }
  40756. exports.getArg = getArg;
  40757. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  40758. var dataUrlRegexp = /^data:.+\,.+$/;
  40759. function urlParse(aUrl) {
  40760. var match = aUrl.match(urlRegexp);
  40761. if (!match) {
  40762. return null;
  40763. }
  40764. return {
  40765. scheme: match[1],
  40766. auth: match[2],
  40767. host: match[3],
  40768. port: match[4],
  40769. path: match[5]
  40770. };
  40771. }
  40772. exports.urlParse = urlParse;
  40773. function urlGenerate(aParsedUrl) {
  40774. var url = '';
  40775. if (aParsedUrl.scheme) {
  40776. url += aParsedUrl.scheme + ':';
  40777. }
  40778. url += '//';
  40779. if (aParsedUrl.auth) {
  40780. url += aParsedUrl.auth + '@';
  40781. }
  40782. if (aParsedUrl.host) {
  40783. url += aParsedUrl.host;
  40784. }
  40785. if (aParsedUrl.port) {
  40786. url += ":" + aParsedUrl.port;
  40787. }
  40788. if (aParsedUrl.path) {
  40789. url += aParsedUrl.path;
  40790. }
  40791. return url;
  40792. }
  40793. exports.urlGenerate = urlGenerate;
  40794. /**
  40795. * Normalizes a path, or the path portion of a URL:
  40796. *
  40797. * - Replaces consecutive slashes with one slash.
  40798. * - Removes unnecessary '.' parts.
  40799. * - Removes unnecessary '<dir>/..' parts.
  40800. *
  40801. * Based on code in the Node.js 'path' core module.
  40802. *
  40803. * @param aPath The path or url to normalize.
  40804. */
  40805. function normalize(aPath) {
  40806. var path = aPath;
  40807. var url = urlParse(aPath);
  40808. if (url) {
  40809. if (!url.path) {
  40810. return aPath;
  40811. }
  40812. path = url.path;
  40813. }
  40814. var isAbsolute = exports.isAbsolute(path);
  40815. var parts = path.split(/\/+/);
  40816. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  40817. part = parts[i];
  40818. if (part === '.') {
  40819. parts.splice(i, 1);
  40820. } else if (part === '..') {
  40821. up++;
  40822. } else if (up > 0) {
  40823. if (part === '') {
  40824. // The first part is blank if the path is absolute. Trying to go
  40825. // above the root is a no-op. Therefore we can remove all '..' parts
  40826. // directly after the root.
  40827. parts.splice(i + 1, up);
  40828. up = 0;
  40829. } else {
  40830. parts.splice(i, 2);
  40831. up--;
  40832. }
  40833. }
  40834. }
  40835. path = parts.join('/');
  40836. if (path === '') {
  40837. path = isAbsolute ? '/' : '.';
  40838. }
  40839. if (url) {
  40840. url.path = path;
  40841. return urlGenerate(url);
  40842. }
  40843. return path;
  40844. }
  40845. exports.normalize = normalize;
  40846. /**
  40847. * Joins two paths/URLs.
  40848. *
  40849. * @param aRoot The root path or URL.
  40850. * @param aPath The path or URL to be joined with the root.
  40851. *
  40852. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  40853. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  40854. * first.
  40855. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  40856. * is updated with the result and aRoot is returned. Otherwise the result
  40857. * is returned.
  40858. * - If aPath is absolute, the result is aPath.
  40859. * - Otherwise the two paths are joined with a slash.
  40860. * - Joining for example 'http://' and 'www.example.com' is also supported.
  40861. */
  40862. function join(aRoot, aPath) {
  40863. if (aRoot === "") {
  40864. aRoot = ".";
  40865. }
  40866. if (aPath === "") {
  40867. aPath = ".";
  40868. }
  40869. var aPathUrl = urlParse(aPath);
  40870. var aRootUrl = urlParse(aRoot);
  40871. if (aRootUrl) {
  40872. aRoot = aRootUrl.path || '/';
  40873. }
  40874. // `join(foo, '//www.example.org')`
  40875. if (aPathUrl && !aPathUrl.scheme) {
  40876. if (aRootUrl) {
  40877. aPathUrl.scheme = aRootUrl.scheme;
  40878. }
  40879. return urlGenerate(aPathUrl);
  40880. }
  40881. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  40882. return aPath;
  40883. }
  40884. // `join('http://', 'www.example.com')`
  40885. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  40886. aRootUrl.host = aPath;
  40887. return urlGenerate(aRootUrl);
  40888. }
  40889. var joined = aPath.charAt(0) === '/'
  40890. ? aPath
  40891. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  40892. if (aRootUrl) {
  40893. aRootUrl.path = joined;
  40894. return urlGenerate(aRootUrl);
  40895. }
  40896. return joined;
  40897. }
  40898. exports.join = join;
  40899. exports.isAbsolute = function (aPath) {
  40900. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  40901. };
  40902. /**
  40903. * Make a path relative to a URL or another path.
  40904. *
  40905. * @param aRoot The root path or URL.
  40906. * @param aPath The path or URL to be made relative to aRoot.
  40907. */
  40908. function relative(aRoot, aPath) {
  40909. if (aRoot === "") {
  40910. aRoot = ".";
  40911. }
  40912. aRoot = aRoot.replace(/\/$/, '');
  40913. // It is possible for the path to be above the root. In this case, simply
  40914. // checking whether the root is a prefix of the path won't work. Instead, we
  40915. // need to remove components from the root one by one, until either we find
  40916. // a prefix that fits, or we run out of components to remove.
  40917. var level = 0;
  40918. while (aPath.indexOf(aRoot + '/') !== 0) {
  40919. var index = aRoot.lastIndexOf("/");
  40920. if (index < 0) {
  40921. return aPath;
  40922. }
  40923. // If the only part of the root that is left is the scheme (i.e. http://,
  40924. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  40925. // have exhausted all components, so the path is not relative to the root.
  40926. aRoot = aRoot.slice(0, index);
  40927. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  40928. return aPath;
  40929. }
  40930. ++level;
  40931. }
  40932. // Make sure we add a "../" for each component we removed from the root.
  40933. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  40934. }
  40935. exports.relative = relative;
  40936. var supportsNullProto = (function () {
  40937. var obj = Object.create(null);
  40938. return !('__proto__' in obj);
  40939. }());
  40940. function identity (s) {
  40941. return s;
  40942. }
  40943. /**
  40944. * Because behavior goes wacky when you set `__proto__` on objects, we
  40945. * have to prefix all the strings in our set with an arbitrary character.
  40946. *
  40947. * See https://github.com/mozilla/source-map/pull/31 and
  40948. * https://github.com/mozilla/source-map/issues/30
  40949. *
  40950. * @param String aStr
  40951. */
  40952. function toSetString(aStr) {
  40953. if (isProtoString(aStr)) {
  40954. return '$' + aStr;
  40955. }
  40956. return aStr;
  40957. }
  40958. exports.toSetString = supportsNullProto ? identity : toSetString;
  40959. function fromSetString(aStr) {
  40960. if (isProtoString(aStr)) {
  40961. return aStr.slice(1);
  40962. }
  40963. return aStr;
  40964. }
  40965. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  40966. function isProtoString(s) {
  40967. if (!s) {
  40968. return false;
  40969. }
  40970. var length = s.length;
  40971. if (length < 9 /* "__proto__".length */) {
  40972. return false;
  40973. }
  40974. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  40975. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  40976. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  40977. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  40978. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  40979. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  40980. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  40981. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  40982. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  40983. return false;
  40984. }
  40985. for (var i = length - 10; i >= 0; i--) {
  40986. if (s.charCodeAt(i) !== 36 /* '$' */) {
  40987. return false;
  40988. }
  40989. }
  40990. return true;
  40991. }
  40992. /**
  40993. * Comparator between two mappings where the original positions are compared.
  40994. *
  40995. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  40996. * mappings with the same original source/line/column, but different generated
  40997. * line and column the same. Useful when searching for a mapping with a
  40998. * stubbed out mapping.
  40999. */
  41000. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  41001. var cmp = strcmp(mappingA.source, mappingB.source);
  41002. if (cmp !== 0) {
  41003. return cmp;
  41004. }
  41005. cmp = mappingA.originalLine - mappingB.originalLine;
  41006. if (cmp !== 0) {
  41007. return cmp;
  41008. }
  41009. cmp = mappingA.originalColumn - mappingB.originalColumn;
  41010. if (cmp !== 0 || onlyCompareOriginal) {
  41011. return cmp;
  41012. }
  41013. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  41014. if (cmp !== 0) {
  41015. return cmp;
  41016. }
  41017. cmp = mappingA.generatedLine - mappingB.generatedLine;
  41018. if (cmp !== 0) {
  41019. return cmp;
  41020. }
  41021. return strcmp(mappingA.name, mappingB.name);
  41022. }
  41023. exports.compareByOriginalPositions = compareByOriginalPositions;
  41024. /**
  41025. * Comparator between two mappings with deflated source and name indices where
  41026. * the generated positions are compared.
  41027. *
  41028. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  41029. * mappings with the same generated line and column, but different
  41030. * source/name/original line and column the same. Useful when searching for a
  41031. * mapping with a stubbed out mapping.
  41032. */
  41033. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  41034. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  41035. if (cmp !== 0) {
  41036. return cmp;
  41037. }
  41038. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  41039. if (cmp !== 0 || onlyCompareGenerated) {
  41040. return cmp;
  41041. }
  41042. cmp = strcmp(mappingA.source, mappingB.source);
  41043. if (cmp !== 0) {
  41044. return cmp;
  41045. }
  41046. cmp = mappingA.originalLine - mappingB.originalLine;
  41047. if (cmp !== 0) {
  41048. return cmp;
  41049. }
  41050. cmp = mappingA.originalColumn - mappingB.originalColumn;
  41051. if (cmp !== 0) {
  41052. return cmp;
  41053. }
  41054. return strcmp(mappingA.name, mappingB.name);
  41055. }
  41056. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  41057. function strcmp(aStr1, aStr2) {
  41058. if (aStr1 === aStr2) {
  41059. return 0;
  41060. }
  41061. if (aStr1 === null) {
  41062. return 1; // aStr2 !== null
  41063. }
  41064. if (aStr2 === null) {
  41065. return -1; // aStr1 !== null
  41066. }
  41067. if (aStr1 > aStr2) {
  41068. return 1;
  41069. }
  41070. return -1;
  41071. }
  41072. /**
  41073. * Comparator between two mappings with inflated source and name strings where
  41074. * the generated positions are compared.
  41075. */
  41076. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  41077. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  41078. if (cmp !== 0) {
  41079. return cmp;
  41080. }
  41081. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  41082. if (cmp !== 0) {
  41083. return cmp;
  41084. }
  41085. cmp = strcmp(mappingA.source, mappingB.source);
  41086. if (cmp !== 0) {
  41087. return cmp;
  41088. }
  41089. cmp = mappingA.originalLine - mappingB.originalLine;
  41090. if (cmp !== 0) {
  41091. return cmp;
  41092. }
  41093. cmp = mappingA.originalColumn - mappingB.originalColumn;
  41094. if (cmp !== 0) {
  41095. return cmp;
  41096. }
  41097. return strcmp(mappingA.name, mappingB.name);
  41098. }
  41099. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  41100. /**
  41101. * Strip any JSON XSSI avoidance prefix from the string (as documented
  41102. * in the source maps specification), and then parse the string as
  41103. * JSON.
  41104. */
  41105. function parseSourceMapInput(str) {
  41106. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  41107. }
  41108. exports.parseSourceMapInput = parseSourceMapInput;
  41109. /**
  41110. * Compute the URL of a source given the the source root, the source's
  41111. * URL, and the source map's URL.
  41112. */
  41113. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  41114. sourceURL = sourceURL || '';
  41115. if (sourceRoot) {
  41116. // This follows what Chrome does.
  41117. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  41118. sourceRoot += '/';
  41119. }
  41120. // The spec says:
  41121. // Line 4: An optional source root, useful for relocating source
  41122. // files on a server or removing repeated values in the
  41123. // “sources” entry. This value is prepended to the individual
  41124. // entries in the “source” field.
  41125. sourceURL = sourceRoot + sourceURL;
  41126. }
  41127. // Historically, SourceMapConsumer did not take the sourceMapURL as
  41128. // a parameter. This mode is still somewhat supported, which is why
  41129. // this code block is conditional. However, it's preferable to pass
  41130. // the source map URL to SourceMapConsumer, so that this function
  41131. // can implement the source URL resolution algorithm as outlined in
  41132. // the spec. This block is basically the equivalent of:
  41133. // new URL(sourceURL, sourceMapURL).toString()
  41134. // ... except it avoids using URL, which wasn't available in the
  41135. // older releases of node still supported by this library.
  41136. //
  41137. // The spec says:
  41138. // If the sources are not absolute URLs after prepending of the
  41139. // “sourceRoot”, the sources are resolved relative to the
  41140. // SourceMap (like resolving script src in a html document).
  41141. if (sourceMapURL) {
  41142. var parsed = urlParse(sourceMapURL);
  41143. if (!parsed) {
  41144. throw new Error("sourceMapURL could not be parsed");
  41145. }
  41146. if (parsed.path) {
  41147. // Strip the last path component, but keep the "/".
  41148. var index = parsed.path.lastIndexOf('/');
  41149. if (index >= 0) {
  41150. parsed.path = parsed.path.substring(0, index + 1);
  41151. }
  41152. }
  41153. sourceURL = join(urlGenerate(parsed), sourceURL);
  41154. }
  41155. return normalize(sourceURL);
  41156. }
  41157. exports.computeSourceURL = computeSourceURL;
  41158. } (util));
  41159. return util;
  41160. }
  41161. var arraySet = {};
  41162. /* -*- Mode: js; js-indent-level: 2; -*- */
  41163. var hasRequiredArraySet;
  41164. function requireArraySet () {
  41165. if (hasRequiredArraySet) return arraySet;
  41166. hasRequiredArraySet = 1;
  41167. /*
  41168. * Copyright 2011 Mozilla Foundation and contributors
  41169. * Licensed under the New BSD license. See LICENSE or:
  41170. * http://opensource.org/licenses/BSD-3-Clause
  41171. */
  41172. var util = /*@__PURE__*/ requireUtil();
  41173. var has = Object.prototype.hasOwnProperty;
  41174. var hasNativeMap = typeof Map !== "undefined";
  41175. /**
  41176. * A data structure which is a combination of an array and a set. Adding a new
  41177. * member is O(1), testing for membership is O(1), and finding the index of an
  41178. * element is O(1). Removing elements from the set is not supported. Only
  41179. * strings are supported for membership.
  41180. */
  41181. function ArraySet() {
  41182. this._array = [];
  41183. this._set = hasNativeMap ? new Map() : Object.create(null);
  41184. }
  41185. /**
  41186. * Static method for creating ArraySet instances from an existing array.
  41187. */
  41188. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  41189. var set = new ArraySet();
  41190. for (var i = 0, len = aArray.length; i < len; i++) {
  41191. set.add(aArray[i], aAllowDuplicates);
  41192. }
  41193. return set;
  41194. };
  41195. /**
  41196. * Return how many unique items are in this ArraySet. If duplicates have been
  41197. * added, than those do not count towards the size.
  41198. *
  41199. * @returns Number
  41200. */
  41201. ArraySet.prototype.size = function ArraySet_size() {
  41202. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  41203. };
  41204. /**
  41205. * Add the given string to this set.
  41206. *
  41207. * @param String aStr
  41208. */
  41209. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  41210. var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
  41211. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  41212. var idx = this._array.length;
  41213. if (!isDuplicate || aAllowDuplicates) {
  41214. this._array.push(aStr);
  41215. }
  41216. if (!isDuplicate) {
  41217. if (hasNativeMap) {
  41218. this._set.set(aStr, idx);
  41219. } else {
  41220. this._set[sStr] = idx;
  41221. }
  41222. }
  41223. };
  41224. /**
  41225. * Is the given string a member of this set?
  41226. *
  41227. * @param String aStr
  41228. */
  41229. ArraySet.prototype.has = function ArraySet_has(aStr) {
  41230. if (hasNativeMap) {
  41231. return this._set.has(aStr);
  41232. } else {
  41233. var sStr = util.toSetString(aStr);
  41234. return has.call(this._set, sStr);
  41235. }
  41236. };
  41237. /**
  41238. * What is the index of the given string in the array?
  41239. *
  41240. * @param String aStr
  41241. */
  41242. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  41243. if (hasNativeMap) {
  41244. var idx = this._set.get(aStr);
  41245. if (idx >= 0) {
  41246. return idx;
  41247. }
  41248. } else {
  41249. var sStr = util.toSetString(aStr);
  41250. if (has.call(this._set, sStr)) {
  41251. return this._set[sStr];
  41252. }
  41253. }
  41254. throw new Error('"' + aStr + '" is not in the set.');
  41255. };
  41256. /**
  41257. * What is the element at the given index?
  41258. *
  41259. * @param Number aIdx
  41260. */
  41261. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  41262. if (aIdx >= 0 && aIdx < this._array.length) {
  41263. return this._array[aIdx];
  41264. }
  41265. throw new Error('No element indexed by ' + aIdx);
  41266. };
  41267. /**
  41268. * Returns the array representation of this set (which has the proper indices
  41269. * indicated by indexOf). Note that this is a copy of the internal array used
  41270. * for storing the members so that no one can mess with internal state.
  41271. */
  41272. ArraySet.prototype.toArray = function ArraySet_toArray() {
  41273. return this._array.slice();
  41274. };
  41275. arraySet.ArraySet = ArraySet;
  41276. return arraySet;
  41277. }
  41278. var mappingList = {};
  41279. /* -*- Mode: js; js-indent-level: 2; -*- */
  41280. var hasRequiredMappingList;
  41281. function requireMappingList () {
  41282. if (hasRequiredMappingList) return mappingList;
  41283. hasRequiredMappingList = 1;
  41284. /*
  41285. * Copyright 2014 Mozilla Foundation and contributors
  41286. * Licensed under the New BSD license. See LICENSE or:
  41287. * http://opensource.org/licenses/BSD-3-Clause
  41288. */
  41289. var util = /*@__PURE__*/ requireUtil();
  41290. /**
  41291. * Determine whether mappingB is after mappingA with respect to generated
  41292. * position.
  41293. */
  41294. function generatedPositionAfter(mappingA, mappingB) {
  41295. // Optimized for most common case
  41296. var lineA = mappingA.generatedLine;
  41297. var lineB = mappingB.generatedLine;
  41298. var columnA = mappingA.generatedColumn;
  41299. var columnB = mappingB.generatedColumn;
  41300. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  41301. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  41302. }
  41303. /**
  41304. * A data structure to provide a sorted view of accumulated mappings in a
  41305. * performance conscious manner. It trades a neglibable overhead in general
  41306. * case for a large speedup in case of mappings being added in order.
  41307. */
  41308. function MappingList() {
  41309. this._array = [];
  41310. this._sorted = true;
  41311. // Serves as infimum
  41312. this._last = {generatedLine: -1, generatedColumn: 0};
  41313. }
  41314. /**
  41315. * Iterate through internal items. This method takes the same arguments that
  41316. * `Array.prototype.forEach` takes.
  41317. *
  41318. * NOTE: The order of the mappings is NOT guaranteed.
  41319. */
  41320. MappingList.prototype.unsortedForEach =
  41321. function MappingList_forEach(aCallback, aThisArg) {
  41322. this._array.forEach(aCallback, aThisArg);
  41323. };
  41324. /**
  41325. * Add the given source mapping.
  41326. *
  41327. * @param Object aMapping
  41328. */
  41329. MappingList.prototype.add = function MappingList_add(aMapping) {
  41330. if (generatedPositionAfter(this._last, aMapping)) {
  41331. this._last = aMapping;
  41332. this._array.push(aMapping);
  41333. } else {
  41334. this._sorted = false;
  41335. this._array.push(aMapping);
  41336. }
  41337. };
  41338. /**
  41339. * Returns the flat, sorted array of mappings. The mappings are sorted by
  41340. * generated position.
  41341. *
  41342. * WARNING: This method returns internal data without copying, for
  41343. * performance. The return value must NOT be mutated, and should be treated as
  41344. * an immutable borrow. If you want to take ownership, you must make your own
  41345. * copy.
  41346. */
  41347. MappingList.prototype.toArray = function MappingList_toArray() {
  41348. if (!this._sorted) {
  41349. this._array.sort(util.compareByGeneratedPositionsInflated);
  41350. this._sorted = true;
  41351. }
  41352. return this._array;
  41353. };
  41354. mappingList.MappingList = MappingList;
  41355. return mappingList;
  41356. }
  41357. /* -*- Mode: js; js-indent-level: 2; -*- */
  41358. var hasRequiredSourceMapGenerator;
  41359. function requireSourceMapGenerator () {
  41360. if (hasRequiredSourceMapGenerator) return sourceMapGenerator;
  41361. hasRequiredSourceMapGenerator = 1;
  41362. /*
  41363. * Copyright 2011 Mozilla Foundation and contributors
  41364. * Licensed under the New BSD license. See LICENSE or:
  41365. * http://opensource.org/licenses/BSD-3-Clause
  41366. */
  41367. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  41368. var util = /*@__PURE__*/ requireUtil();
  41369. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  41370. var MappingList = /*@__PURE__*/ requireMappingList().MappingList;
  41371. /**
  41372. * An instance of the SourceMapGenerator represents a source map which is
  41373. * being built incrementally. You may pass an object with the following
  41374. * properties:
  41375. *
  41376. * - file: The filename of the generated source.
  41377. * - sourceRoot: A root for all relative URLs in this source map.
  41378. */
  41379. function SourceMapGenerator(aArgs) {
  41380. if (!aArgs) {
  41381. aArgs = {};
  41382. }
  41383. this._file = util.getArg(aArgs, 'file', null);
  41384. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  41385. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  41386. this._sources = new ArraySet();
  41387. this._names = new ArraySet();
  41388. this._mappings = new MappingList();
  41389. this._sourcesContents = null;
  41390. }
  41391. SourceMapGenerator.prototype._version = 3;
  41392. /**
  41393. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  41394. *
  41395. * @param aSourceMapConsumer The SourceMap.
  41396. */
  41397. SourceMapGenerator.fromSourceMap =
  41398. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  41399. var sourceRoot = aSourceMapConsumer.sourceRoot;
  41400. var generator = new SourceMapGenerator({
  41401. file: aSourceMapConsumer.file,
  41402. sourceRoot: sourceRoot
  41403. });
  41404. aSourceMapConsumer.eachMapping(function (mapping) {
  41405. var newMapping = {
  41406. generated: {
  41407. line: mapping.generatedLine,
  41408. column: mapping.generatedColumn
  41409. }
  41410. };
  41411. if (mapping.source != null) {
  41412. newMapping.source = mapping.source;
  41413. if (sourceRoot != null) {
  41414. newMapping.source = util.relative(sourceRoot, newMapping.source);
  41415. }
  41416. newMapping.original = {
  41417. line: mapping.originalLine,
  41418. column: mapping.originalColumn
  41419. };
  41420. if (mapping.name != null) {
  41421. newMapping.name = mapping.name;
  41422. }
  41423. }
  41424. generator.addMapping(newMapping);
  41425. });
  41426. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  41427. var sourceRelative = sourceFile;
  41428. if (sourceRoot !== null) {
  41429. sourceRelative = util.relative(sourceRoot, sourceFile);
  41430. }
  41431. if (!generator._sources.has(sourceRelative)) {
  41432. generator._sources.add(sourceRelative);
  41433. }
  41434. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  41435. if (content != null) {
  41436. generator.setSourceContent(sourceFile, content);
  41437. }
  41438. });
  41439. return generator;
  41440. };
  41441. /**
  41442. * Add a single mapping from original source line and column to the generated
  41443. * source's line and column for this source map being created. The mapping
  41444. * object should have the following properties:
  41445. *
  41446. * - generated: An object with the generated line and column positions.
  41447. * - original: An object with the original line and column positions.
  41448. * - source: The original source file (relative to the sourceRoot).
  41449. * - name: An optional original token name for this mapping.
  41450. */
  41451. SourceMapGenerator.prototype.addMapping =
  41452. function SourceMapGenerator_addMapping(aArgs) {
  41453. var generated = util.getArg(aArgs, 'generated');
  41454. var original = util.getArg(aArgs, 'original', null);
  41455. var source = util.getArg(aArgs, 'source', null);
  41456. var name = util.getArg(aArgs, 'name', null);
  41457. if (!this._skipValidation) {
  41458. this._validateMapping(generated, original, source, name);
  41459. }
  41460. if (source != null) {
  41461. source = String(source);
  41462. if (!this._sources.has(source)) {
  41463. this._sources.add(source);
  41464. }
  41465. }
  41466. if (name != null) {
  41467. name = String(name);
  41468. if (!this._names.has(name)) {
  41469. this._names.add(name);
  41470. }
  41471. }
  41472. this._mappings.add({
  41473. generatedLine: generated.line,
  41474. generatedColumn: generated.column,
  41475. originalLine: original != null && original.line,
  41476. originalColumn: original != null && original.column,
  41477. source: source,
  41478. name: name
  41479. });
  41480. };
  41481. /**
  41482. * Set the source content for a source file.
  41483. */
  41484. SourceMapGenerator.prototype.setSourceContent =
  41485. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  41486. var source = aSourceFile;
  41487. if (this._sourceRoot != null) {
  41488. source = util.relative(this._sourceRoot, source);
  41489. }
  41490. if (aSourceContent != null) {
  41491. // Add the source content to the _sourcesContents map.
  41492. // Create a new _sourcesContents map if the property is null.
  41493. if (!this._sourcesContents) {
  41494. this._sourcesContents = Object.create(null);
  41495. }
  41496. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  41497. } else if (this._sourcesContents) {
  41498. // Remove the source file from the _sourcesContents map.
  41499. // If the _sourcesContents map is empty, set the property to null.
  41500. delete this._sourcesContents[util.toSetString(source)];
  41501. if (Object.keys(this._sourcesContents).length === 0) {
  41502. this._sourcesContents = null;
  41503. }
  41504. }
  41505. };
  41506. /**
  41507. * Applies the mappings of a sub-source-map for a specific source file to the
  41508. * source map being generated. Each mapping to the supplied source file is
  41509. * rewritten using the supplied source map. Note: The resolution for the
  41510. * resulting mappings is the minimium of this map and the supplied map.
  41511. *
  41512. * @param aSourceMapConsumer The source map to be applied.
  41513. * @param aSourceFile Optional. The filename of the source file.
  41514. * If omitted, SourceMapConsumer's file property will be used.
  41515. * @param aSourceMapPath Optional. The dirname of the path to the source map
  41516. * to be applied. If relative, it is relative to the SourceMapConsumer.
  41517. * This parameter is needed when the two source maps aren't in the same
  41518. * directory, and the source map to be applied contains relative source
  41519. * paths. If so, those relative source paths need to be rewritten
  41520. * relative to the SourceMapGenerator.
  41521. */
  41522. SourceMapGenerator.prototype.applySourceMap =
  41523. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  41524. var sourceFile = aSourceFile;
  41525. // If aSourceFile is omitted, we will use the file property of the SourceMap
  41526. if (aSourceFile == null) {
  41527. if (aSourceMapConsumer.file == null) {
  41528. throw new Error(
  41529. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  41530. 'or the source map\'s "file" property. Both were omitted.'
  41531. );
  41532. }
  41533. sourceFile = aSourceMapConsumer.file;
  41534. }
  41535. var sourceRoot = this._sourceRoot;
  41536. // Make "sourceFile" relative if an absolute Url is passed.
  41537. if (sourceRoot != null) {
  41538. sourceFile = util.relative(sourceRoot, sourceFile);
  41539. }
  41540. // Applying the SourceMap can add and remove items from the sources and
  41541. // the names array.
  41542. var newSources = new ArraySet();
  41543. var newNames = new ArraySet();
  41544. // Find mappings for the "sourceFile"
  41545. this._mappings.unsortedForEach(function (mapping) {
  41546. if (mapping.source === sourceFile && mapping.originalLine != null) {
  41547. // Check if it can be mapped by the source map, then update the mapping.
  41548. var original = aSourceMapConsumer.originalPositionFor({
  41549. line: mapping.originalLine,
  41550. column: mapping.originalColumn
  41551. });
  41552. if (original.source != null) {
  41553. // Copy mapping
  41554. mapping.source = original.source;
  41555. if (aSourceMapPath != null) {
  41556. mapping.source = util.join(aSourceMapPath, mapping.source);
  41557. }
  41558. if (sourceRoot != null) {
  41559. mapping.source = util.relative(sourceRoot, mapping.source);
  41560. }
  41561. mapping.originalLine = original.line;
  41562. mapping.originalColumn = original.column;
  41563. if (original.name != null) {
  41564. mapping.name = original.name;
  41565. }
  41566. }
  41567. }
  41568. var source = mapping.source;
  41569. if (source != null && !newSources.has(source)) {
  41570. newSources.add(source);
  41571. }
  41572. var name = mapping.name;
  41573. if (name != null && !newNames.has(name)) {
  41574. newNames.add(name);
  41575. }
  41576. }, this);
  41577. this._sources = newSources;
  41578. this._names = newNames;
  41579. // Copy sourcesContents of applied map.
  41580. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  41581. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  41582. if (content != null) {
  41583. if (aSourceMapPath != null) {
  41584. sourceFile = util.join(aSourceMapPath, sourceFile);
  41585. }
  41586. if (sourceRoot != null) {
  41587. sourceFile = util.relative(sourceRoot, sourceFile);
  41588. }
  41589. this.setSourceContent(sourceFile, content);
  41590. }
  41591. }, this);
  41592. };
  41593. /**
  41594. * A mapping can have one of the three levels of data:
  41595. *
  41596. * 1. Just the generated position.
  41597. * 2. The Generated position, original position, and original source.
  41598. * 3. Generated and original position, original source, as well as a name
  41599. * token.
  41600. *
  41601. * To maintain consistency, we validate that any new mapping being added falls
  41602. * in to one of these categories.
  41603. */
  41604. SourceMapGenerator.prototype._validateMapping =
  41605. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  41606. aName) {
  41607. // When aOriginal is truthy but has empty values for .line and .column,
  41608. // it is most likely a programmer error. In this case we throw a very
  41609. // specific error message to try to guide them the right way.
  41610. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  41611. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  41612. throw new Error(
  41613. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  41614. 'the original mapping entirely and only map the generated position. If so, pass ' +
  41615. 'null for the original mapping instead of an object with empty or null values.'
  41616. );
  41617. }
  41618. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  41619. && aGenerated.line > 0 && aGenerated.column >= 0
  41620. && !aOriginal && !aSource && !aName) {
  41621. // Case 1.
  41622. return;
  41623. }
  41624. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  41625. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  41626. && aGenerated.line > 0 && aGenerated.column >= 0
  41627. && aOriginal.line > 0 && aOriginal.column >= 0
  41628. && aSource) {
  41629. // Cases 2 and 3.
  41630. return;
  41631. }
  41632. else {
  41633. throw new Error('Invalid mapping: ' + JSON.stringify({
  41634. generated: aGenerated,
  41635. source: aSource,
  41636. original: aOriginal,
  41637. name: aName
  41638. }));
  41639. }
  41640. };
  41641. /**
  41642. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  41643. * specified by the source map format.
  41644. */
  41645. SourceMapGenerator.prototype._serializeMappings =
  41646. function SourceMapGenerator_serializeMappings() {
  41647. var previousGeneratedColumn = 0;
  41648. var previousGeneratedLine = 1;
  41649. var previousOriginalColumn = 0;
  41650. var previousOriginalLine = 0;
  41651. var previousName = 0;
  41652. var previousSource = 0;
  41653. var result = '';
  41654. var next;
  41655. var mapping;
  41656. var nameIdx;
  41657. var sourceIdx;
  41658. var mappings = this._mappings.toArray();
  41659. for (var i = 0, len = mappings.length; i < len; i++) {
  41660. mapping = mappings[i];
  41661. next = '';
  41662. if (mapping.generatedLine !== previousGeneratedLine) {
  41663. previousGeneratedColumn = 0;
  41664. while (mapping.generatedLine !== previousGeneratedLine) {
  41665. next += ';';
  41666. previousGeneratedLine++;
  41667. }
  41668. }
  41669. else {
  41670. if (i > 0) {
  41671. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  41672. continue;
  41673. }
  41674. next += ',';
  41675. }
  41676. }
  41677. next += base64VLQ.encode(mapping.generatedColumn
  41678. - previousGeneratedColumn);
  41679. previousGeneratedColumn = mapping.generatedColumn;
  41680. if (mapping.source != null) {
  41681. sourceIdx = this._sources.indexOf(mapping.source);
  41682. next += base64VLQ.encode(sourceIdx - previousSource);
  41683. previousSource = sourceIdx;
  41684. // lines are stored 0-based in SourceMap spec version 3
  41685. next += base64VLQ.encode(mapping.originalLine - 1
  41686. - previousOriginalLine);
  41687. previousOriginalLine = mapping.originalLine - 1;
  41688. next += base64VLQ.encode(mapping.originalColumn
  41689. - previousOriginalColumn);
  41690. previousOriginalColumn = mapping.originalColumn;
  41691. if (mapping.name != null) {
  41692. nameIdx = this._names.indexOf(mapping.name);
  41693. next += base64VLQ.encode(nameIdx - previousName);
  41694. previousName = nameIdx;
  41695. }
  41696. }
  41697. result += next;
  41698. }
  41699. return result;
  41700. };
  41701. SourceMapGenerator.prototype._generateSourcesContent =
  41702. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  41703. return aSources.map(function (source) {
  41704. if (!this._sourcesContents) {
  41705. return null;
  41706. }
  41707. if (aSourceRoot != null) {
  41708. source = util.relative(aSourceRoot, source);
  41709. }
  41710. var key = util.toSetString(source);
  41711. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  41712. ? this._sourcesContents[key]
  41713. : null;
  41714. }, this);
  41715. };
  41716. /**
  41717. * Externalize the source map.
  41718. */
  41719. SourceMapGenerator.prototype.toJSON =
  41720. function SourceMapGenerator_toJSON() {
  41721. var map = {
  41722. version: this._version,
  41723. sources: this._sources.toArray(),
  41724. names: this._names.toArray(),
  41725. mappings: this._serializeMappings()
  41726. };
  41727. if (this._file != null) {
  41728. map.file = this._file;
  41729. }
  41730. if (this._sourceRoot != null) {
  41731. map.sourceRoot = this._sourceRoot;
  41732. }
  41733. if (this._sourcesContents) {
  41734. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  41735. }
  41736. return map;
  41737. };
  41738. /**
  41739. * Render the source map being generated to a string.
  41740. */
  41741. SourceMapGenerator.prototype.toString =
  41742. function SourceMapGenerator_toString() {
  41743. return JSON.stringify(this.toJSON());
  41744. };
  41745. sourceMapGenerator.SourceMapGenerator = SourceMapGenerator;
  41746. return sourceMapGenerator;
  41747. }
  41748. var sourceMapConsumer = {};
  41749. var binarySearch = {};
  41750. /* -*- Mode: js; js-indent-level: 2; -*- */
  41751. var hasRequiredBinarySearch;
  41752. function requireBinarySearch () {
  41753. if (hasRequiredBinarySearch) return binarySearch;
  41754. hasRequiredBinarySearch = 1;
  41755. (function (exports) {
  41756. /*
  41757. * Copyright 2011 Mozilla Foundation and contributors
  41758. * Licensed under the New BSD license. See LICENSE or:
  41759. * http://opensource.org/licenses/BSD-3-Clause
  41760. */
  41761. exports.GREATEST_LOWER_BOUND = 1;
  41762. exports.LEAST_UPPER_BOUND = 2;
  41763. /**
  41764. * Recursive implementation of binary search.
  41765. *
  41766. * @param aLow Indices here and lower do not contain the needle.
  41767. * @param aHigh Indices here and higher do not contain the needle.
  41768. * @param aNeedle The element being searched for.
  41769. * @param aHaystack The non-empty array being searched.
  41770. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  41771. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  41772. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  41773. * closest element that is smaller than or greater than the one we are
  41774. * searching for, respectively, if the exact element cannot be found.
  41775. */
  41776. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  41777. // This function terminates when one of the following is true:
  41778. //
  41779. // 1. We find the exact element we are looking for.
  41780. //
  41781. // 2. We did not find the exact element, but we can return the index of
  41782. // the next-closest element.
  41783. //
  41784. // 3. We did not find the exact element, and there is no next-closest
  41785. // element than the one we are searching for, so we return -1.
  41786. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  41787. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  41788. if (cmp === 0) {
  41789. // Found the element we are looking for.
  41790. return mid;
  41791. }
  41792. else if (cmp > 0) {
  41793. // Our needle is greater than aHaystack[mid].
  41794. if (aHigh - mid > 1) {
  41795. // The element is in the upper half.
  41796. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  41797. }
  41798. // The exact needle element was not found in this haystack. Determine if
  41799. // we are in termination case (3) or (2) and return the appropriate thing.
  41800. if (aBias == exports.LEAST_UPPER_BOUND) {
  41801. return aHigh < aHaystack.length ? aHigh : -1;
  41802. } else {
  41803. return mid;
  41804. }
  41805. }
  41806. else {
  41807. // Our needle is less than aHaystack[mid].
  41808. if (mid - aLow > 1) {
  41809. // The element is in the lower half.
  41810. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  41811. }
  41812. // we are in termination case (3) or (2) and return the appropriate thing.
  41813. if (aBias == exports.LEAST_UPPER_BOUND) {
  41814. return mid;
  41815. } else {
  41816. return aLow < 0 ? -1 : aLow;
  41817. }
  41818. }
  41819. }
  41820. /**
  41821. * This is an implementation of binary search which will always try and return
  41822. * the index of the closest element if there is no exact hit. This is because
  41823. * mappings between original and generated line/col pairs are single points,
  41824. * and there is an implicit region between each of them, so a miss just means
  41825. * that you aren't on the very start of a region.
  41826. *
  41827. * @param aNeedle The element you are looking for.
  41828. * @param aHaystack The array that is being searched.
  41829. * @param aCompare A function which takes the needle and an element in the
  41830. * array and returns -1, 0, or 1 depending on whether the needle is less
  41831. * than, equal to, or greater than the element, respectively.
  41832. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  41833. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  41834. * closest element that is smaller than or greater than the one we are
  41835. * searching for, respectively, if the exact element cannot be found.
  41836. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  41837. */
  41838. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  41839. if (aHaystack.length === 0) {
  41840. return -1;
  41841. }
  41842. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  41843. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  41844. if (index < 0) {
  41845. return -1;
  41846. }
  41847. // We have found either the exact element, or the next-closest element than
  41848. // the one we are searching for. However, there may be more than one such
  41849. // element. Make sure we always return the smallest of these.
  41850. while (index - 1 >= 0) {
  41851. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  41852. break;
  41853. }
  41854. --index;
  41855. }
  41856. return index;
  41857. };
  41858. } (binarySearch));
  41859. return binarySearch;
  41860. }
  41861. var quickSort = {};
  41862. /* -*- Mode: js; js-indent-level: 2; -*- */
  41863. var hasRequiredQuickSort;
  41864. function requireQuickSort () {
  41865. if (hasRequiredQuickSort) return quickSort;
  41866. hasRequiredQuickSort = 1;
  41867. /*
  41868. * Copyright 2011 Mozilla Foundation and contributors
  41869. * Licensed under the New BSD license. See LICENSE or:
  41870. * http://opensource.org/licenses/BSD-3-Clause
  41871. */
  41872. // It turns out that some (most?) JavaScript engines don't self-host
  41873. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  41874. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  41875. // custom comparator function, calling back and forth between the VM's C++ and
  41876. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  41877. // worse generated code for the comparator function than would be optimal. In
  41878. // fact, when sorting with a comparator, these costs outweigh the benefits of
  41879. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  41880. // a ~3500ms mean speed-up in `bench/bench.html`.
  41881. /**
  41882. * Swap the elements indexed by `x` and `y` in the array `ary`.
  41883. *
  41884. * @param {Array} ary
  41885. * The array.
  41886. * @param {Number} x
  41887. * The index of the first item.
  41888. * @param {Number} y
  41889. * The index of the second item.
  41890. */
  41891. function swap(ary, x, y) {
  41892. var temp = ary[x];
  41893. ary[x] = ary[y];
  41894. ary[y] = temp;
  41895. }
  41896. /**
  41897. * Returns a random integer within the range `low .. high` inclusive.
  41898. *
  41899. * @param {Number} low
  41900. * The lower bound on the range.
  41901. * @param {Number} high
  41902. * The upper bound on the range.
  41903. */
  41904. function randomIntInRange(low, high) {
  41905. return Math.round(low + (Math.random() * (high - low)));
  41906. }
  41907. /**
  41908. * The Quick Sort algorithm.
  41909. *
  41910. * @param {Array} ary
  41911. * An array to sort.
  41912. * @param {function} comparator
  41913. * Function to use to compare two items.
  41914. * @param {Number} p
  41915. * Start index of the array
  41916. * @param {Number} r
  41917. * End index of the array
  41918. */
  41919. function doQuickSort(ary, comparator, p, r) {
  41920. // If our lower bound is less than our upper bound, we (1) partition the
  41921. // array into two pieces and (2) recurse on each half. If it is not, this is
  41922. // the empty array and our base case.
  41923. if (p < r) {
  41924. // (1) Partitioning.
  41925. //
  41926. // The partitioning chooses a pivot between `p` and `r` and moves all
  41927. // elements that are less than or equal to the pivot to the before it, and
  41928. // all the elements that are greater than it after it. The effect is that
  41929. // once partition is done, the pivot is in the exact place it will be when
  41930. // the array is put in sorted order, and it will not need to be moved
  41931. // again. This runs in O(n) time.
  41932. // Always choose a random pivot so that an input array which is reverse
  41933. // sorted does not cause O(n^2) running time.
  41934. var pivotIndex = randomIntInRange(p, r);
  41935. var i = p - 1;
  41936. swap(ary, pivotIndex, r);
  41937. var pivot = ary[r];
  41938. // Immediately after `j` is incremented in this loop, the following hold
  41939. // true:
  41940. //
  41941. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  41942. //
  41943. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  41944. for (var j = p; j < r; j++) {
  41945. if (comparator(ary[j], pivot) <= 0) {
  41946. i += 1;
  41947. swap(ary, i, j);
  41948. }
  41949. }
  41950. swap(ary, i + 1, j);
  41951. var q = i + 1;
  41952. // (2) Recurse on each half.
  41953. doQuickSort(ary, comparator, p, q - 1);
  41954. doQuickSort(ary, comparator, q + 1, r);
  41955. }
  41956. }
  41957. /**
  41958. * Sort the given array in-place with the given comparator function.
  41959. *
  41960. * @param {Array} ary
  41961. * An array to sort.
  41962. * @param {function} comparator
  41963. * Function to use to compare two items.
  41964. */
  41965. quickSort.quickSort = function (ary, comparator) {
  41966. doQuickSort(ary, comparator, 0, ary.length - 1);
  41967. };
  41968. return quickSort;
  41969. }
  41970. /* -*- Mode: js; js-indent-level: 2; -*- */
  41971. var hasRequiredSourceMapConsumer;
  41972. function requireSourceMapConsumer () {
  41973. if (hasRequiredSourceMapConsumer) return sourceMapConsumer;
  41974. hasRequiredSourceMapConsumer = 1;
  41975. /*
  41976. * Copyright 2011 Mozilla Foundation and contributors
  41977. * Licensed under the New BSD license. See LICENSE or:
  41978. * http://opensource.org/licenses/BSD-3-Clause
  41979. */
  41980. var util = /*@__PURE__*/ requireUtil();
  41981. var binarySearch = /*@__PURE__*/ requireBinarySearch();
  41982. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  41983. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  41984. var quickSort = /*@__PURE__*/ requireQuickSort().quickSort;
  41985. function SourceMapConsumer(aSourceMap, aSourceMapURL) {
  41986. var sourceMap = aSourceMap;
  41987. if (typeof aSourceMap === 'string') {
  41988. sourceMap = util.parseSourceMapInput(aSourceMap);
  41989. }
  41990. return sourceMap.sections != null
  41991. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  41992. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  41993. }
  41994. SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  41995. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  41996. };
  41997. /**
  41998. * The version of the source mapping spec that we are consuming.
  41999. */
  42000. SourceMapConsumer.prototype._version = 3;
  42001. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  42002. // parsed mapping coordinates from the source map's "mappings" attribute. They
  42003. // are lazily instantiated, accessed via the `_generatedMappings` and
  42004. // `_originalMappings` getters respectively, and we only parse the mappings
  42005. // and create these arrays once queried for a source location. We jump through
  42006. // these hoops because there can be many thousands of mappings, and parsing
  42007. // them is expensive, so we only want to do it if we must.
  42008. //
  42009. // Each object in the arrays is of the form:
  42010. //
  42011. // {
  42012. // generatedLine: The line number in the generated code,
  42013. // generatedColumn: The column number in the generated code,
  42014. // source: The path to the original source file that generated this
  42015. // chunk of code,
  42016. // originalLine: The line number in the original source that
  42017. // corresponds to this chunk of generated code,
  42018. // originalColumn: The column number in the original source that
  42019. // corresponds to this chunk of generated code,
  42020. // name: The name of the original symbol which generated this chunk of
  42021. // code.
  42022. // }
  42023. //
  42024. // All properties except for `generatedLine` and `generatedColumn` can be
  42025. // `null`.
  42026. //
  42027. // `_generatedMappings` is ordered by the generated positions.
  42028. //
  42029. // `_originalMappings` is ordered by the original positions.
  42030. SourceMapConsumer.prototype.__generatedMappings = null;
  42031. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  42032. configurable: true,
  42033. enumerable: true,
  42034. get: function () {
  42035. if (!this.__generatedMappings) {
  42036. this._parseMappings(this._mappings, this.sourceRoot);
  42037. }
  42038. return this.__generatedMappings;
  42039. }
  42040. });
  42041. SourceMapConsumer.prototype.__originalMappings = null;
  42042. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  42043. configurable: true,
  42044. enumerable: true,
  42045. get: function () {
  42046. if (!this.__originalMappings) {
  42047. this._parseMappings(this._mappings, this.sourceRoot);
  42048. }
  42049. return this.__originalMappings;
  42050. }
  42051. });
  42052. SourceMapConsumer.prototype._charIsMappingSeparator =
  42053. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  42054. var c = aStr.charAt(index);
  42055. return c === ";" || c === ",";
  42056. };
  42057. /**
  42058. * Parse the mappings in a string in to a data structure which we can easily
  42059. * query (the ordered arrays in the `this.__generatedMappings` and
  42060. * `this.__originalMappings` properties).
  42061. */
  42062. SourceMapConsumer.prototype._parseMappings =
  42063. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  42064. throw new Error("Subclasses must implement _parseMappings");
  42065. };
  42066. SourceMapConsumer.GENERATED_ORDER = 1;
  42067. SourceMapConsumer.ORIGINAL_ORDER = 2;
  42068. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  42069. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  42070. /**
  42071. * Iterate over each mapping between an original source/line/column and a
  42072. * generated line/column in this source map.
  42073. *
  42074. * @param Function aCallback
  42075. * The function that is called with each mapping.
  42076. * @param Object aContext
  42077. * Optional. If specified, this object will be the value of `this` every
  42078. * time that `aCallback` is called.
  42079. * @param aOrder
  42080. * Either `SourceMapConsumer.GENERATED_ORDER` or
  42081. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  42082. * iterate over the mappings sorted by the generated file's line/column
  42083. * order or the original's source/line/column order, respectively. Defaults to
  42084. * `SourceMapConsumer.GENERATED_ORDER`.
  42085. */
  42086. SourceMapConsumer.prototype.eachMapping =
  42087. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  42088. var context = aContext || null;
  42089. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  42090. var mappings;
  42091. switch (order) {
  42092. case SourceMapConsumer.GENERATED_ORDER:
  42093. mappings = this._generatedMappings;
  42094. break;
  42095. case SourceMapConsumer.ORIGINAL_ORDER:
  42096. mappings = this._originalMappings;
  42097. break;
  42098. default:
  42099. throw new Error("Unknown order of iteration.");
  42100. }
  42101. var sourceRoot = this.sourceRoot;
  42102. mappings.map(function (mapping) {
  42103. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  42104. source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  42105. return {
  42106. source: source,
  42107. generatedLine: mapping.generatedLine,
  42108. generatedColumn: mapping.generatedColumn,
  42109. originalLine: mapping.originalLine,
  42110. originalColumn: mapping.originalColumn,
  42111. name: mapping.name === null ? null : this._names.at(mapping.name)
  42112. };
  42113. }, this).forEach(aCallback, context);
  42114. };
  42115. /**
  42116. * Returns all generated line and column information for the original source,
  42117. * line, and column provided. If no column is provided, returns all mappings
  42118. * corresponding to a either the line we are searching for or the next
  42119. * closest line that has any mappings. Otherwise, returns all mappings
  42120. * corresponding to the given line and either the column we are searching for
  42121. * or the next closest column that has any offsets.
  42122. *
  42123. * The only argument is an object with the following properties:
  42124. *
  42125. * - source: The filename of the original source.
  42126. * - line: The line number in the original source. The line number is 1-based.
  42127. * - column: Optional. the column number in the original source.
  42128. * The column number is 0-based.
  42129. *
  42130. * and an array of objects is returned, each with the following properties:
  42131. *
  42132. * - line: The line number in the generated source, or null. The
  42133. * line number is 1-based.
  42134. * - column: The column number in the generated source, or null.
  42135. * The column number is 0-based.
  42136. */
  42137. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  42138. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  42139. var line = util.getArg(aArgs, 'line');
  42140. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  42141. // returns the index of the closest mapping less than the needle. By
  42142. // setting needle.originalColumn to 0, we thus find the last mapping for
  42143. // the given line, provided such a mapping exists.
  42144. var needle = {
  42145. source: util.getArg(aArgs, 'source'),
  42146. originalLine: line,
  42147. originalColumn: util.getArg(aArgs, 'column', 0)
  42148. };
  42149. needle.source = this._findSourceIndex(needle.source);
  42150. if (needle.source < 0) {
  42151. return [];
  42152. }
  42153. var mappings = [];
  42154. var index = this._findMapping(needle,
  42155. this._originalMappings,
  42156. "originalLine",
  42157. "originalColumn",
  42158. util.compareByOriginalPositions,
  42159. binarySearch.LEAST_UPPER_BOUND);
  42160. if (index >= 0) {
  42161. var mapping = this._originalMappings[index];
  42162. if (aArgs.column === undefined) {
  42163. var originalLine = mapping.originalLine;
  42164. // Iterate until either we run out of mappings, or we run into
  42165. // a mapping for a different line than the one we found. Since
  42166. // mappings are sorted, this is guaranteed to find all mappings for
  42167. // the line we found.
  42168. while (mapping && mapping.originalLine === originalLine) {
  42169. mappings.push({
  42170. line: util.getArg(mapping, 'generatedLine', null),
  42171. column: util.getArg(mapping, 'generatedColumn', null),
  42172. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  42173. });
  42174. mapping = this._originalMappings[++index];
  42175. }
  42176. } else {
  42177. var originalColumn = mapping.originalColumn;
  42178. // Iterate until either we run out of mappings, or we run into
  42179. // a mapping for a different line than the one we were searching for.
  42180. // Since mappings are sorted, this is guaranteed to find all mappings for
  42181. // the line we are searching for.
  42182. while (mapping &&
  42183. mapping.originalLine === line &&
  42184. mapping.originalColumn == originalColumn) {
  42185. mappings.push({
  42186. line: util.getArg(mapping, 'generatedLine', null),
  42187. column: util.getArg(mapping, 'generatedColumn', null),
  42188. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  42189. });
  42190. mapping = this._originalMappings[++index];
  42191. }
  42192. }
  42193. }
  42194. return mappings;
  42195. };
  42196. sourceMapConsumer.SourceMapConsumer = SourceMapConsumer;
  42197. /**
  42198. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  42199. * query for information about the original file positions by giving it a file
  42200. * position in the generated source.
  42201. *
  42202. * The first parameter is the raw source map (either as a JSON string, or
  42203. * already parsed to an object). According to the spec, source maps have the
  42204. * following attributes:
  42205. *
  42206. * - version: Which version of the source map spec this map is following.
  42207. * - sources: An array of URLs to the original source files.
  42208. * - names: An array of identifiers which can be referrenced by individual mappings.
  42209. * - sourceRoot: Optional. The URL root from which all sources are relative.
  42210. * - sourcesContent: Optional. An array of contents of the original source files.
  42211. * - mappings: A string of base64 VLQs which contain the actual mappings.
  42212. * - file: Optional. The generated file this source map is associated with.
  42213. *
  42214. * Here is an example source map, taken from the source map spec[0]:
  42215. *
  42216. * {
  42217. * version : 3,
  42218. * file: "out.js",
  42219. * sourceRoot : "",
  42220. * sources: ["foo.js", "bar.js"],
  42221. * names: ["src", "maps", "are", "fun"],
  42222. * mappings: "AA,AB;;ABCDE;"
  42223. * }
  42224. *
  42225. * The second parameter, if given, is a string whose value is the URL
  42226. * at which the source map was found. This URL is used to compute the
  42227. * sources array.
  42228. *
  42229. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  42230. */
  42231. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  42232. var sourceMap = aSourceMap;
  42233. if (typeof aSourceMap === 'string') {
  42234. sourceMap = util.parseSourceMapInput(aSourceMap);
  42235. }
  42236. var version = util.getArg(sourceMap, 'version');
  42237. var sources = util.getArg(sourceMap, 'sources');
  42238. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  42239. // requires the array) to play nice here.
  42240. var names = util.getArg(sourceMap, 'names', []);
  42241. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  42242. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  42243. var mappings = util.getArg(sourceMap, 'mappings');
  42244. var file = util.getArg(sourceMap, 'file', null);
  42245. // Once again, Sass deviates from the spec and supplies the version as a
  42246. // string rather than a number, so we use loose equality checking here.
  42247. if (version != this._version) {
  42248. throw new Error('Unsupported version: ' + version);
  42249. }
  42250. if (sourceRoot) {
  42251. sourceRoot = util.normalize(sourceRoot);
  42252. }
  42253. sources = sources
  42254. .map(String)
  42255. // Some source maps produce relative source paths like "./foo.js" instead of
  42256. // "foo.js". Normalize these first so that future comparisons will succeed.
  42257. // See bugzil.la/1090768.
  42258. .map(util.normalize)
  42259. // Always ensure that absolute sources are internally stored relative to
  42260. // the source root, if the source root is absolute. Not doing this would
  42261. // be particularly problematic when the source root is a prefix of the
  42262. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  42263. .map(function (source) {
  42264. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  42265. ? util.relative(sourceRoot, source)
  42266. : source;
  42267. });
  42268. // Pass `true` below to allow duplicate names and sources. While source maps
  42269. // are intended to be compressed and deduplicated, the TypeScript compiler
  42270. // sometimes generates source maps with duplicates in them. See Github issue
  42271. // #72 and bugzil.la/889492.
  42272. this._names = ArraySet.fromArray(names.map(String), true);
  42273. this._sources = ArraySet.fromArray(sources, true);
  42274. this._absoluteSources = this._sources.toArray().map(function (s) {
  42275. return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
  42276. });
  42277. this.sourceRoot = sourceRoot;
  42278. this.sourcesContent = sourcesContent;
  42279. this._mappings = mappings;
  42280. this._sourceMapURL = aSourceMapURL;
  42281. this.file = file;
  42282. }
  42283. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  42284. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  42285. /**
  42286. * Utility function to find the index of a source. Returns -1 if not
  42287. * found.
  42288. */
  42289. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  42290. var relativeSource = aSource;
  42291. if (this.sourceRoot != null) {
  42292. relativeSource = util.relative(this.sourceRoot, relativeSource);
  42293. }
  42294. if (this._sources.has(relativeSource)) {
  42295. return this._sources.indexOf(relativeSource);
  42296. }
  42297. // Maybe aSource is an absolute URL as returned by |sources|. In
  42298. // this case we can't simply undo the transform.
  42299. var i;
  42300. for (i = 0; i < this._absoluteSources.length; ++i) {
  42301. if (this._absoluteSources[i] == aSource) {
  42302. return i;
  42303. }
  42304. }
  42305. return -1;
  42306. };
  42307. /**
  42308. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  42309. *
  42310. * @param SourceMapGenerator aSourceMap
  42311. * The source map that will be consumed.
  42312. * @param String aSourceMapURL
  42313. * The URL at which the source map can be found (optional)
  42314. * @returns BasicSourceMapConsumer
  42315. */
  42316. BasicSourceMapConsumer.fromSourceMap =
  42317. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  42318. var smc = Object.create(BasicSourceMapConsumer.prototype);
  42319. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  42320. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  42321. smc.sourceRoot = aSourceMap._sourceRoot;
  42322. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  42323. smc.sourceRoot);
  42324. smc.file = aSourceMap._file;
  42325. smc._sourceMapURL = aSourceMapURL;
  42326. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  42327. return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  42328. });
  42329. // Because we are modifying the entries (by converting string sources and
  42330. // names to indices into the sources and names ArraySets), we have to make
  42331. // a copy of the entry or else bad things happen. Shared mutable state
  42332. // strikes again! See github issue #191.
  42333. var generatedMappings = aSourceMap._mappings.toArray().slice();
  42334. var destGeneratedMappings = smc.__generatedMappings = [];
  42335. var destOriginalMappings = smc.__originalMappings = [];
  42336. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  42337. var srcMapping = generatedMappings[i];
  42338. var destMapping = new Mapping;
  42339. destMapping.generatedLine = srcMapping.generatedLine;
  42340. destMapping.generatedColumn = srcMapping.generatedColumn;
  42341. if (srcMapping.source) {
  42342. destMapping.source = sources.indexOf(srcMapping.source);
  42343. destMapping.originalLine = srcMapping.originalLine;
  42344. destMapping.originalColumn = srcMapping.originalColumn;
  42345. if (srcMapping.name) {
  42346. destMapping.name = names.indexOf(srcMapping.name);
  42347. }
  42348. destOriginalMappings.push(destMapping);
  42349. }
  42350. destGeneratedMappings.push(destMapping);
  42351. }
  42352. quickSort(smc.__originalMappings, util.compareByOriginalPositions);
  42353. return smc;
  42354. };
  42355. /**
  42356. * The version of the source mapping spec that we are consuming.
  42357. */
  42358. BasicSourceMapConsumer.prototype._version = 3;
  42359. /**
  42360. * The list of original sources.
  42361. */
  42362. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  42363. get: function () {
  42364. return this._absoluteSources.slice();
  42365. }
  42366. });
  42367. /**
  42368. * Provide the JIT with a nice shape / hidden class.
  42369. */
  42370. function Mapping() {
  42371. this.generatedLine = 0;
  42372. this.generatedColumn = 0;
  42373. this.source = null;
  42374. this.originalLine = null;
  42375. this.originalColumn = null;
  42376. this.name = null;
  42377. }
  42378. /**
  42379. * Parse the mappings in a string in to a data structure which we can easily
  42380. * query (the ordered arrays in the `this.__generatedMappings` and
  42381. * `this.__originalMappings` properties).
  42382. */
  42383. BasicSourceMapConsumer.prototype._parseMappings =
  42384. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  42385. var generatedLine = 1;
  42386. var previousGeneratedColumn = 0;
  42387. var previousOriginalLine = 0;
  42388. var previousOriginalColumn = 0;
  42389. var previousSource = 0;
  42390. var previousName = 0;
  42391. var length = aStr.length;
  42392. var index = 0;
  42393. var cachedSegments = {};
  42394. var temp = {};
  42395. var originalMappings = [];
  42396. var generatedMappings = [];
  42397. var mapping, str, segment, end, value;
  42398. while (index < length) {
  42399. if (aStr.charAt(index) === ';') {
  42400. generatedLine++;
  42401. index++;
  42402. previousGeneratedColumn = 0;
  42403. }
  42404. else if (aStr.charAt(index) === ',') {
  42405. index++;
  42406. }
  42407. else {
  42408. mapping = new Mapping();
  42409. mapping.generatedLine = generatedLine;
  42410. // Because each offset is encoded relative to the previous one,
  42411. // many segments often have the same encoding. We can exploit this
  42412. // fact by caching the parsed variable length fields of each segment,
  42413. // allowing us to avoid a second parse if we encounter the same
  42414. // segment again.
  42415. for (end = index; end < length; end++) {
  42416. if (this._charIsMappingSeparator(aStr, end)) {
  42417. break;
  42418. }
  42419. }
  42420. str = aStr.slice(index, end);
  42421. segment = cachedSegments[str];
  42422. if (segment) {
  42423. index += str.length;
  42424. } else {
  42425. segment = [];
  42426. while (index < end) {
  42427. base64VLQ.decode(aStr, index, temp);
  42428. value = temp.value;
  42429. index = temp.rest;
  42430. segment.push(value);
  42431. }
  42432. if (segment.length === 2) {
  42433. throw new Error('Found a source, but no line and column');
  42434. }
  42435. if (segment.length === 3) {
  42436. throw new Error('Found a source and line, but no column');
  42437. }
  42438. cachedSegments[str] = segment;
  42439. }
  42440. // Generated column.
  42441. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  42442. previousGeneratedColumn = mapping.generatedColumn;
  42443. if (segment.length > 1) {
  42444. // Original source.
  42445. mapping.source = previousSource + segment[1];
  42446. previousSource += segment[1];
  42447. // Original line.
  42448. mapping.originalLine = previousOriginalLine + segment[2];
  42449. previousOriginalLine = mapping.originalLine;
  42450. // Lines are stored 0-based
  42451. mapping.originalLine += 1;
  42452. // Original column.
  42453. mapping.originalColumn = previousOriginalColumn + segment[3];
  42454. previousOriginalColumn = mapping.originalColumn;
  42455. if (segment.length > 4) {
  42456. // Original name.
  42457. mapping.name = previousName + segment[4];
  42458. previousName += segment[4];
  42459. }
  42460. }
  42461. generatedMappings.push(mapping);
  42462. if (typeof mapping.originalLine === 'number') {
  42463. originalMappings.push(mapping);
  42464. }
  42465. }
  42466. }
  42467. quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
  42468. this.__generatedMappings = generatedMappings;
  42469. quickSort(originalMappings, util.compareByOriginalPositions);
  42470. this.__originalMappings = originalMappings;
  42471. };
  42472. /**
  42473. * Find the mapping that best matches the hypothetical "needle" mapping that
  42474. * we are searching for in the given "haystack" of mappings.
  42475. */
  42476. BasicSourceMapConsumer.prototype._findMapping =
  42477. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  42478. aColumnName, aComparator, aBias) {
  42479. // To return the position we are searching for, we must first find the
  42480. // mapping for the given position and then return the opposite position it
  42481. // points to. Because the mappings are sorted, we can use binary search to
  42482. // find the best mapping.
  42483. if (aNeedle[aLineName] <= 0) {
  42484. throw new TypeError('Line must be greater than or equal to 1, got '
  42485. + aNeedle[aLineName]);
  42486. }
  42487. if (aNeedle[aColumnName] < 0) {
  42488. throw new TypeError('Column must be greater than or equal to 0, got '
  42489. + aNeedle[aColumnName]);
  42490. }
  42491. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  42492. };
  42493. /**
  42494. * Compute the last column for each generated mapping. The last column is
  42495. * inclusive.
  42496. */
  42497. BasicSourceMapConsumer.prototype.computeColumnSpans =
  42498. function SourceMapConsumer_computeColumnSpans() {
  42499. for (var index = 0; index < this._generatedMappings.length; ++index) {
  42500. var mapping = this._generatedMappings[index];
  42501. // Mappings do not contain a field for the last generated columnt. We
  42502. // can come up with an optimistic estimate, however, by assuming that
  42503. // mappings are contiguous (i.e. given two consecutive mappings, the
  42504. // first mapping ends where the second one starts).
  42505. if (index + 1 < this._generatedMappings.length) {
  42506. var nextMapping = this._generatedMappings[index + 1];
  42507. if (mapping.generatedLine === nextMapping.generatedLine) {
  42508. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  42509. continue;
  42510. }
  42511. }
  42512. // The last mapping for each line spans the entire line.
  42513. mapping.lastGeneratedColumn = Infinity;
  42514. }
  42515. };
  42516. /**
  42517. * Returns the original source, line, and column information for the generated
  42518. * source's line and column positions provided. The only argument is an object
  42519. * with the following properties:
  42520. *
  42521. * - line: The line number in the generated source. The line number
  42522. * is 1-based.
  42523. * - column: The column number in the generated source. The column
  42524. * number is 0-based.
  42525. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  42526. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  42527. * closest element that is smaller than or greater than the one we are
  42528. * searching for, respectively, if the exact element cannot be found.
  42529. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  42530. *
  42531. * and an object is returned with the following properties:
  42532. *
  42533. * - source: The original source file, or null.
  42534. * - line: The line number in the original source, or null. The
  42535. * line number is 1-based.
  42536. * - column: The column number in the original source, or null. The
  42537. * column number is 0-based.
  42538. * - name: The original identifier, or null.
  42539. */
  42540. BasicSourceMapConsumer.prototype.originalPositionFor =
  42541. function SourceMapConsumer_originalPositionFor(aArgs) {
  42542. var needle = {
  42543. generatedLine: util.getArg(aArgs, 'line'),
  42544. generatedColumn: util.getArg(aArgs, 'column')
  42545. };
  42546. var index = this._findMapping(
  42547. needle,
  42548. this._generatedMappings,
  42549. "generatedLine",
  42550. "generatedColumn",
  42551. util.compareByGeneratedPositionsDeflated,
  42552. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  42553. );
  42554. if (index >= 0) {
  42555. var mapping = this._generatedMappings[index];
  42556. if (mapping.generatedLine === needle.generatedLine) {
  42557. var source = util.getArg(mapping, 'source', null);
  42558. if (source !== null) {
  42559. source = this._sources.at(source);
  42560. source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  42561. }
  42562. var name = util.getArg(mapping, 'name', null);
  42563. if (name !== null) {
  42564. name = this._names.at(name);
  42565. }
  42566. return {
  42567. source: source,
  42568. line: util.getArg(mapping, 'originalLine', null),
  42569. column: util.getArg(mapping, 'originalColumn', null),
  42570. name: name
  42571. };
  42572. }
  42573. }
  42574. return {
  42575. source: null,
  42576. line: null,
  42577. column: null,
  42578. name: null
  42579. };
  42580. };
  42581. /**
  42582. * Return true if we have the source content for every source in the source
  42583. * map, false otherwise.
  42584. */
  42585. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  42586. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  42587. if (!this.sourcesContent) {
  42588. return false;
  42589. }
  42590. return this.sourcesContent.length >= this._sources.size() &&
  42591. !this.sourcesContent.some(function (sc) { return sc == null; });
  42592. };
  42593. /**
  42594. * Returns the original source content. The only argument is the url of the
  42595. * original source file. Returns null if no original source content is
  42596. * available.
  42597. */
  42598. BasicSourceMapConsumer.prototype.sourceContentFor =
  42599. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  42600. if (!this.sourcesContent) {
  42601. return null;
  42602. }
  42603. var index = this._findSourceIndex(aSource);
  42604. if (index >= 0) {
  42605. return this.sourcesContent[index];
  42606. }
  42607. var relativeSource = aSource;
  42608. if (this.sourceRoot != null) {
  42609. relativeSource = util.relative(this.sourceRoot, relativeSource);
  42610. }
  42611. var url;
  42612. if (this.sourceRoot != null
  42613. && (url = util.urlParse(this.sourceRoot))) {
  42614. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  42615. // many users. We can help them out when they expect file:// URIs to
  42616. // behave like it would if they were running a local HTTP server. See
  42617. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  42618. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  42619. if (url.scheme == "file"
  42620. && this._sources.has(fileUriAbsPath)) {
  42621. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  42622. }
  42623. if ((!url.path || url.path == "/")
  42624. && this._sources.has("/" + relativeSource)) {
  42625. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  42626. }
  42627. }
  42628. // This function is used recursively from
  42629. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  42630. // don't want to throw if we can't find the source - we just want to
  42631. // return null, so we provide a flag to exit gracefully.
  42632. if (nullOnMissing) {
  42633. return null;
  42634. }
  42635. else {
  42636. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  42637. }
  42638. };
  42639. /**
  42640. * Returns the generated line and column information for the original source,
  42641. * line, and column positions provided. The only argument is an object with
  42642. * the following properties:
  42643. *
  42644. * - source: The filename of the original source.
  42645. * - line: The line number in the original source. The line number
  42646. * is 1-based.
  42647. * - column: The column number in the original source. The column
  42648. * number is 0-based.
  42649. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  42650. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  42651. * closest element that is smaller than or greater than the one we are
  42652. * searching for, respectively, if the exact element cannot be found.
  42653. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  42654. *
  42655. * and an object is returned with the following properties:
  42656. *
  42657. * - line: The line number in the generated source, or null. The
  42658. * line number is 1-based.
  42659. * - column: The column number in the generated source, or null.
  42660. * The column number is 0-based.
  42661. */
  42662. BasicSourceMapConsumer.prototype.generatedPositionFor =
  42663. function SourceMapConsumer_generatedPositionFor(aArgs) {
  42664. var source = util.getArg(aArgs, 'source');
  42665. source = this._findSourceIndex(source);
  42666. if (source < 0) {
  42667. return {
  42668. line: null,
  42669. column: null,
  42670. lastColumn: null
  42671. };
  42672. }
  42673. var needle = {
  42674. source: source,
  42675. originalLine: util.getArg(aArgs, 'line'),
  42676. originalColumn: util.getArg(aArgs, 'column')
  42677. };
  42678. var index = this._findMapping(
  42679. needle,
  42680. this._originalMappings,
  42681. "originalLine",
  42682. "originalColumn",
  42683. util.compareByOriginalPositions,
  42684. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  42685. );
  42686. if (index >= 0) {
  42687. var mapping = this._originalMappings[index];
  42688. if (mapping.source === needle.source) {
  42689. return {
  42690. line: util.getArg(mapping, 'generatedLine', null),
  42691. column: util.getArg(mapping, 'generatedColumn', null),
  42692. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  42693. };
  42694. }
  42695. }
  42696. return {
  42697. line: null,
  42698. column: null,
  42699. lastColumn: null
  42700. };
  42701. };
  42702. sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer;
  42703. /**
  42704. * An IndexedSourceMapConsumer instance represents a parsed source map which
  42705. * we can query for information. It differs from BasicSourceMapConsumer in
  42706. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  42707. * input.
  42708. *
  42709. * The first parameter is a raw source map (either as a JSON string, or already
  42710. * parsed to an object). According to the spec for indexed source maps, they
  42711. * have the following attributes:
  42712. *
  42713. * - version: Which version of the source map spec this map is following.
  42714. * - file: Optional. The generated file this source map is associated with.
  42715. * - sections: A list of section definitions.
  42716. *
  42717. * Each value under the "sections" field has two fields:
  42718. * - offset: The offset into the original specified at which this section
  42719. * begins to apply, defined as an object with a "line" and "column"
  42720. * field.
  42721. * - map: A source map definition. This source map could also be indexed,
  42722. * but doesn't have to be.
  42723. *
  42724. * Instead of the "map" field, it's also possible to have a "url" field
  42725. * specifying a URL to retrieve a source map from, but that's currently
  42726. * unsupported.
  42727. *
  42728. * Here's an example source map, taken from the source map spec[0], but
  42729. * modified to omit a section which uses the "url" field.
  42730. *
  42731. * {
  42732. * version : 3,
  42733. * file: "app.js",
  42734. * sections: [{
  42735. * offset: {line:100, column:10},
  42736. * map: {
  42737. * version : 3,
  42738. * file: "section.js",
  42739. * sources: ["foo.js", "bar.js"],
  42740. * names: ["src", "maps", "are", "fun"],
  42741. * mappings: "AAAA,E;;ABCDE;"
  42742. * }
  42743. * }],
  42744. * }
  42745. *
  42746. * The second parameter, if given, is a string whose value is the URL
  42747. * at which the source map was found. This URL is used to compute the
  42748. * sources array.
  42749. *
  42750. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  42751. */
  42752. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  42753. var sourceMap = aSourceMap;
  42754. if (typeof aSourceMap === 'string') {
  42755. sourceMap = util.parseSourceMapInput(aSourceMap);
  42756. }
  42757. var version = util.getArg(sourceMap, 'version');
  42758. var sections = util.getArg(sourceMap, 'sections');
  42759. if (version != this._version) {
  42760. throw new Error('Unsupported version: ' + version);
  42761. }
  42762. this._sources = new ArraySet();
  42763. this._names = new ArraySet();
  42764. var lastOffset = {
  42765. line: -1,
  42766. column: 0
  42767. };
  42768. this._sections = sections.map(function (s) {
  42769. if (s.url) {
  42770. // The url field will require support for asynchronicity.
  42771. // See https://github.com/mozilla/source-map/issues/16
  42772. throw new Error('Support for url field in sections not implemented.');
  42773. }
  42774. var offset = util.getArg(s, 'offset');
  42775. var offsetLine = util.getArg(offset, 'line');
  42776. var offsetColumn = util.getArg(offset, 'column');
  42777. if (offsetLine < lastOffset.line ||
  42778. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  42779. throw new Error('Section offsets must be ordered and non-overlapping.');
  42780. }
  42781. lastOffset = offset;
  42782. return {
  42783. generatedOffset: {
  42784. // The offset fields are 0-based, but we use 1-based indices when
  42785. // encoding/decoding from VLQ.
  42786. generatedLine: offsetLine + 1,
  42787. generatedColumn: offsetColumn + 1
  42788. },
  42789. consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
  42790. }
  42791. });
  42792. }
  42793. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  42794. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  42795. /**
  42796. * The version of the source mapping spec that we are consuming.
  42797. */
  42798. IndexedSourceMapConsumer.prototype._version = 3;
  42799. /**
  42800. * The list of original sources.
  42801. */
  42802. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  42803. get: function () {
  42804. var sources = [];
  42805. for (var i = 0; i < this._sections.length; i++) {
  42806. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  42807. sources.push(this._sections[i].consumer.sources[j]);
  42808. }
  42809. }
  42810. return sources;
  42811. }
  42812. });
  42813. /**
  42814. * Returns the original source, line, and column information for the generated
  42815. * source's line and column positions provided. The only argument is an object
  42816. * with the following properties:
  42817. *
  42818. * - line: The line number in the generated source. The line number
  42819. * is 1-based.
  42820. * - column: The column number in the generated source. The column
  42821. * number is 0-based.
  42822. *
  42823. * and an object is returned with the following properties:
  42824. *
  42825. * - source: The original source file, or null.
  42826. * - line: The line number in the original source, or null. The
  42827. * line number is 1-based.
  42828. * - column: The column number in the original source, or null. The
  42829. * column number is 0-based.
  42830. * - name: The original identifier, or null.
  42831. */
  42832. IndexedSourceMapConsumer.prototype.originalPositionFor =
  42833. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  42834. var needle = {
  42835. generatedLine: util.getArg(aArgs, 'line'),
  42836. generatedColumn: util.getArg(aArgs, 'column')
  42837. };
  42838. // Find the section containing the generated position we're trying to map
  42839. // to an original position.
  42840. var sectionIndex = binarySearch.search(needle, this._sections,
  42841. function(needle, section) {
  42842. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  42843. if (cmp) {
  42844. return cmp;
  42845. }
  42846. return (needle.generatedColumn -
  42847. section.generatedOffset.generatedColumn);
  42848. });
  42849. var section = this._sections[sectionIndex];
  42850. if (!section) {
  42851. return {
  42852. source: null,
  42853. line: null,
  42854. column: null,
  42855. name: null
  42856. };
  42857. }
  42858. return section.consumer.originalPositionFor({
  42859. line: needle.generatedLine -
  42860. (section.generatedOffset.generatedLine - 1),
  42861. column: needle.generatedColumn -
  42862. (section.generatedOffset.generatedLine === needle.generatedLine
  42863. ? section.generatedOffset.generatedColumn - 1
  42864. : 0),
  42865. bias: aArgs.bias
  42866. });
  42867. };
  42868. /**
  42869. * Return true if we have the source content for every source in the source
  42870. * map, false otherwise.
  42871. */
  42872. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  42873. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  42874. return this._sections.every(function (s) {
  42875. return s.consumer.hasContentsOfAllSources();
  42876. });
  42877. };
  42878. /**
  42879. * Returns the original source content. The only argument is the url of the
  42880. * original source file. Returns null if no original source content is
  42881. * available.
  42882. */
  42883. IndexedSourceMapConsumer.prototype.sourceContentFor =
  42884. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  42885. for (var i = 0; i < this._sections.length; i++) {
  42886. var section = this._sections[i];
  42887. var content = section.consumer.sourceContentFor(aSource, true);
  42888. if (content) {
  42889. return content;
  42890. }
  42891. }
  42892. if (nullOnMissing) {
  42893. return null;
  42894. }
  42895. else {
  42896. throw new Error('"' + aSource + '" is not in the SourceMap.');
  42897. }
  42898. };
  42899. /**
  42900. * Returns the generated line and column information for the original source,
  42901. * line, and column positions provided. The only argument is an object with
  42902. * the following properties:
  42903. *
  42904. * - source: The filename of the original source.
  42905. * - line: The line number in the original source. The line number
  42906. * is 1-based.
  42907. * - column: The column number in the original source. The column
  42908. * number is 0-based.
  42909. *
  42910. * and an object is returned with the following properties:
  42911. *
  42912. * - line: The line number in the generated source, or null. The
  42913. * line number is 1-based.
  42914. * - column: The column number in the generated source, or null.
  42915. * The column number is 0-based.
  42916. */
  42917. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  42918. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  42919. for (var i = 0; i < this._sections.length; i++) {
  42920. var section = this._sections[i];
  42921. // Only consider this section if the requested source is in the list of
  42922. // sources of the consumer.
  42923. if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
  42924. continue;
  42925. }
  42926. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  42927. if (generatedPosition) {
  42928. var ret = {
  42929. line: generatedPosition.line +
  42930. (section.generatedOffset.generatedLine - 1),
  42931. column: generatedPosition.column +
  42932. (section.generatedOffset.generatedLine === generatedPosition.line
  42933. ? section.generatedOffset.generatedColumn - 1
  42934. : 0)
  42935. };
  42936. return ret;
  42937. }
  42938. }
  42939. return {
  42940. line: null,
  42941. column: null
  42942. };
  42943. };
  42944. /**
  42945. * Parse the mappings in a string in to a data structure which we can easily
  42946. * query (the ordered arrays in the `this.__generatedMappings` and
  42947. * `this.__originalMappings` properties).
  42948. */
  42949. IndexedSourceMapConsumer.prototype._parseMappings =
  42950. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  42951. this.__generatedMappings = [];
  42952. this.__originalMappings = [];
  42953. for (var i = 0; i < this._sections.length; i++) {
  42954. var section = this._sections[i];
  42955. var sectionMappings = section.consumer._generatedMappings;
  42956. for (var j = 0; j < sectionMappings.length; j++) {
  42957. var mapping = sectionMappings[j];
  42958. var source = section.consumer._sources.at(mapping.source);
  42959. source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  42960. this._sources.add(source);
  42961. source = this._sources.indexOf(source);
  42962. var name = null;
  42963. if (mapping.name) {
  42964. name = section.consumer._names.at(mapping.name);
  42965. this._names.add(name);
  42966. name = this._names.indexOf(name);
  42967. }
  42968. // The mappings coming from the consumer for the section have
  42969. // generated positions relative to the start of the section, so we
  42970. // need to offset them to be relative to the start of the concatenated
  42971. // generated file.
  42972. var adjustedMapping = {
  42973. source: source,
  42974. generatedLine: mapping.generatedLine +
  42975. (section.generatedOffset.generatedLine - 1),
  42976. generatedColumn: mapping.generatedColumn +
  42977. (section.generatedOffset.generatedLine === mapping.generatedLine
  42978. ? section.generatedOffset.generatedColumn - 1
  42979. : 0),
  42980. originalLine: mapping.originalLine,
  42981. originalColumn: mapping.originalColumn,
  42982. name: name
  42983. };
  42984. this.__generatedMappings.push(adjustedMapping);
  42985. if (typeof adjustedMapping.originalLine === 'number') {
  42986. this.__originalMappings.push(adjustedMapping);
  42987. }
  42988. }
  42989. }
  42990. quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  42991. quickSort(this.__originalMappings, util.compareByOriginalPositions);
  42992. };
  42993. sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  42994. return sourceMapConsumer;
  42995. }
  42996. var sourceNode = {};
  42997. /* -*- Mode: js; js-indent-level: 2; -*- */
  42998. var hasRequiredSourceNode;
  42999. function requireSourceNode () {
  43000. if (hasRequiredSourceNode) return sourceNode;
  43001. hasRequiredSourceNode = 1;
  43002. /*
  43003. * Copyright 2011 Mozilla Foundation and contributors
  43004. * Licensed under the New BSD license. See LICENSE or:
  43005. * http://opensource.org/licenses/BSD-3-Clause
  43006. */
  43007. var SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  43008. var util = /*@__PURE__*/ requireUtil();
  43009. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  43010. // operating systems these days (capturing the result).
  43011. var REGEX_NEWLINE = /(\r?\n)/;
  43012. // Newline character code for charCodeAt() comparisons
  43013. var NEWLINE_CODE = 10;
  43014. // Private symbol for identifying `SourceNode`s when multiple versions of
  43015. // the source-map library are loaded. This MUST NOT CHANGE across
  43016. // versions!
  43017. var isSourceNode = "$$$isSourceNode$$$";
  43018. /**
  43019. * SourceNodes provide a way to abstract over interpolating/concatenating
  43020. * snippets of generated JavaScript source code while maintaining the line and
  43021. * column information associated with the original source code.
  43022. *
  43023. * @param aLine The original line number.
  43024. * @param aColumn The original column number.
  43025. * @param aSource The original source's filename.
  43026. * @param aChunks Optional. An array of strings which are snippets of
  43027. * generated JS, or other SourceNodes.
  43028. * @param aName The original identifier.
  43029. */
  43030. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  43031. this.children = [];
  43032. this.sourceContents = {};
  43033. this.line = aLine == null ? null : aLine;
  43034. this.column = aColumn == null ? null : aColumn;
  43035. this.source = aSource == null ? null : aSource;
  43036. this.name = aName == null ? null : aName;
  43037. this[isSourceNode] = true;
  43038. if (aChunks != null) this.add(aChunks);
  43039. }
  43040. /**
  43041. * Creates a SourceNode from generated code and a SourceMapConsumer.
  43042. *
  43043. * @param aGeneratedCode The generated code
  43044. * @param aSourceMapConsumer The SourceMap for the generated code
  43045. * @param aRelativePath Optional. The path that relative sources in the
  43046. * SourceMapConsumer should be relative to.
  43047. */
  43048. SourceNode.fromStringWithSourceMap =
  43049. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  43050. // The SourceNode we want to fill with the generated code
  43051. // and the SourceMap
  43052. var node = new SourceNode();
  43053. // All even indices of this array are one line of the generated code,
  43054. // while all odd indices are the newlines between two adjacent lines
  43055. // (since `REGEX_NEWLINE` captures its match).
  43056. // Processed fragments are accessed by calling `shiftNextLine`.
  43057. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  43058. var remainingLinesIndex = 0;
  43059. var shiftNextLine = function() {
  43060. var lineContents = getNextLine();
  43061. // The last line of a file might not have a newline.
  43062. var newLine = getNextLine() || "";
  43063. return lineContents + newLine;
  43064. function getNextLine() {
  43065. return remainingLinesIndex < remainingLines.length ?
  43066. remainingLines[remainingLinesIndex++] : undefined;
  43067. }
  43068. };
  43069. // We need to remember the position of "remainingLines"
  43070. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  43071. // The generate SourceNodes we need a code range.
  43072. // To extract it current and last mapping is used.
  43073. // Here we store the last mapping.
  43074. var lastMapping = null;
  43075. aSourceMapConsumer.eachMapping(function (mapping) {
  43076. if (lastMapping !== null) {
  43077. // We add the code from "lastMapping" to "mapping":
  43078. // First check if there is a new line in between.
  43079. if (lastGeneratedLine < mapping.generatedLine) {
  43080. // Associate first line with "lastMapping"
  43081. addMappingWithCode(lastMapping, shiftNextLine());
  43082. lastGeneratedLine++;
  43083. lastGeneratedColumn = 0;
  43084. // The remaining code is added without mapping
  43085. } else {
  43086. // There is no new line in between.
  43087. // Associate the code between "lastGeneratedColumn" and
  43088. // "mapping.generatedColumn" with "lastMapping"
  43089. var nextLine = remainingLines[remainingLinesIndex] || '';
  43090. var code = nextLine.substr(0, mapping.generatedColumn -
  43091. lastGeneratedColumn);
  43092. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  43093. lastGeneratedColumn);
  43094. lastGeneratedColumn = mapping.generatedColumn;
  43095. addMappingWithCode(lastMapping, code);
  43096. // No more remaining code, continue
  43097. lastMapping = mapping;
  43098. return;
  43099. }
  43100. }
  43101. // We add the generated code until the first mapping
  43102. // to the SourceNode without any mapping.
  43103. // Each line is added as separate string.
  43104. while (lastGeneratedLine < mapping.generatedLine) {
  43105. node.add(shiftNextLine());
  43106. lastGeneratedLine++;
  43107. }
  43108. if (lastGeneratedColumn < mapping.generatedColumn) {
  43109. var nextLine = remainingLines[remainingLinesIndex] || '';
  43110. node.add(nextLine.substr(0, mapping.generatedColumn));
  43111. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  43112. lastGeneratedColumn = mapping.generatedColumn;
  43113. }
  43114. lastMapping = mapping;
  43115. }, this);
  43116. // We have processed all mappings.
  43117. if (remainingLinesIndex < remainingLines.length) {
  43118. if (lastMapping) {
  43119. // Associate the remaining code in the current line with "lastMapping"
  43120. addMappingWithCode(lastMapping, shiftNextLine());
  43121. }
  43122. // and add the remaining lines without any mapping
  43123. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  43124. }
  43125. // Copy sourcesContent into SourceNode
  43126. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  43127. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  43128. if (content != null) {
  43129. if (aRelativePath != null) {
  43130. sourceFile = util.join(aRelativePath, sourceFile);
  43131. }
  43132. node.setSourceContent(sourceFile, content);
  43133. }
  43134. });
  43135. return node;
  43136. function addMappingWithCode(mapping, code) {
  43137. if (mapping === null || mapping.source === undefined) {
  43138. node.add(code);
  43139. } else {
  43140. var source = aRelativePath
  43141. ? util.join(aRelativePath, mapping.source)
  43142. : mapping.source;
  43143. node.add(new SourceNode(mapping.originalLine,
  43144. mapping.originalColumn,
  43145. source,
  43146. code,
  43147. mapping.name));
  43148. }
  43149. }
  43150. };
  43151. /**
  43152. * Add a chunk of generated JS to this source node.
  43153. *
  43154. * @param aChunk A string snippet of generated JS code, another instance of
  43155. * SourceNode, or an array where each member is one of those things.
  43156. */
  43157. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  43158. if (Array.isArray(aChunk)) {
  43159. aChunk.forEach(function (chunk) {
  43160. this.add(chunk);
  43161. }, this);
  43162. }
  43163. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  43164. if (aChunk) {
  43165. this.children.push(aChunk);
  43166. }
  43167. }
  43168. else {
  43169. throw new TypeError(
  43170. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  43171. );
  43172. }
  43173. return this;
  43174. };
  43175. /**
  43176. * Add a chunk of generated JS to the beginning of this source node.
  43177. *
  43178. * @param aChunk A string snippet of generated JS code, another instance of
  43179. * SourceNode, or an array where each member is one of those things.
  43180. */
  43181. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  43182. if (Array.isArray(aChunk)) {
  43183. for (var i = aChunk.length-1; i >= 0; i--) {
  43184. this.prepend(aChunk[i]);
  43185. }
  43186. }
  43187. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  43188. this.children.unshift(aChunk);
  43189. }
  43190. else {
  43191. throw new TypeError(
  43192. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  43193. );
  43194. }
  43195. return this;
  43196. };
  43197. /**
  43198. * Walk over the tree of JS snippets in this node and its children. The
  43199. * walking function is called once for each snippet of JS and is passed that
  43200. * snippet and the its original associated source's line/column location.
  43201. *
  43202. * @param aFn The traversal function.
  43203. */
  43204. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  43205. var chunk;
  43206. for (var i = 0, len = this.children.length; i < len; i++) {
  43207. chunk = this.children[i];
  43208. if (chunk[isSourceNode]) {
  43209. chunk.walk(aFn);
  43210. }
  43211. else {
  43212. if (chunk !== '') {
  43213. aFn(chunk, { source: this.source,
  43214. line: this.line,
  43215. column: this.column,
  43216. name: this.name });
  43217. }
  43218. }
  43219. }
  43220. };
  43221. /**
  43222. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  43223. * each of `this.children`.
  43224. *
  43225. * @param aSep The separator.
  43226. */
  43227. SourceNode.prototype.join = function SourceNode_join(aSep) {
  43228. var newChildren;
  43229. var i;
  43230. var len = this.children.length;
  43231. if (len > 0) {
  43232. newChildren = [];
  43233. for (i = 0; i < len-1; i++) {
  43234. newChildren.push(this.children[i]);
  43235. newChildren.push(aSep);
  43236. }
  43237. newChildren.push(this.children[i]);
  43238. this.children = newChildren;
  43239. }
  43240. return this;
  43241. };
  43242. /**
  43243. * Call String.prototype.replace on the very right-most source snippet. Useful
  43244. * for trimming whitespace from the end of a source node, etc.
  43245. *
  43246. * @param aPattern The pattern to replace.
  43247. * @param aReplacement The thing to replace the pattern with.
  43248. */
  43249. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  43250. var lastChild = this.children[this.children.length - 1];
  43251. if (lastChild[isSourceNode]) {
  43252. lastChild.replaceRight(aPattern, aReplacement);
  43253. }
  43254. else if (typeof lastChild === 'string') {
  43255. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  43256. }
  43257. else {
  43258. this.children.push(''.replace(aPattern, aReplacement));
  43259. }
  43260. return this;
  43261. };
  43262. /**
  43263. * Set the source content for a source file. This will be added to the SourceMapGenerator
  43264. * in the sourcesContent field.
  43265. *
  43266. * @param aSourceFile The filename of the source file
  43267. * @param aSourceContent The content of the source file
  43268. */
  43269. SourceNode.prototype.setSourceContent =
  43270. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  43271. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  43272. };
  43273. /**
  43274. * Walk over the tree of SourceNodes. The walking function is called for each
  43275. * source file content and is passed the filename and source content.
  43276. *
  43277. * @param aFn The traversal function.
  43278. */
  43279. SourceNode.prototype.walkSourceContents =
  43280. function SourceNode_walkSourceContents(aFn) {
  43281. for (var i = 0, len = this.children.length; i < len; i++) {
  43282. if (this.children[i][isSourceNode]) {
  43283. this.children[i].walkSourceContents(aFn);
  43284. }
  43285. }
  43286. var sources = Object.keys(this.sourceContents);
  43287. for (var i = 0, len = sources.length; i < len; i++) {
  43288. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  43289. }
  43290. };
  43291. /**
  43292. * Return the string representation of this source node. Walks over the tree
  43293. * and concatenates all the various snippets together to one string.
  43294. */
  43295. SourceNode.prototype.toString = function SourceNode_toString() {
  43296. var str = "";
  43297. this.walk(function (chunk) {
  43298. str += chunk;
  43299. });
  43300. return str;
  43301. };
  43302. /**
  43303. * Returns the string representation of this source node along with a source
  43304. * map.
  43305. */
  43306. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  43307. var generated = {
  43308. code: "",
  43309. line: 1,
  43310. column: 0
  43311. };
  43312. var map = new SourceMapGenerator(aArgs);
  43313. var sourceMappingActive = false;
  43314. var lastOriginalSource = null;
  43315. var lastOriginalLine = null;
  43316. var lastOriginalColumn = null;
  43317. var lastOriginalName = null;
  43318. this.walk(function (chunk, original) {
  43319. generated.code += chunk;
  43320. if (original.source !== null
  43321. && original.line !== null
  43322. && original.column !== null) {
  43323. if(lastOriginalSource !== original.source
  43324. || lastOriginalLine !== original.line
  43325. || lastOriginalColumn !== original.column
  43326. || lastOriginalName !== original.name) {
  43327. map.addMapping({
  43328. source: original.source,
  43329. original: {
  43330. line: original.line,
  43331. column: original.column
  43332. },
  43333. generated: {
  43334. line: generated.line,
  43335. column: generated.column
  43336. },
  43337. name: original.name
  43338. });
  43339. }
  43340. lastOriginalSource = original.source;
  43341. lastOriginalLine = original.line;
  43342. lastOriginalColumn = original.column;
  43343. lastOriginalName = original.name;
  43344. sourceMappingActive = true;
  43345. } else if (sourceMappingActive) {
  43346. map.addMapping({
  43347. generated: {
  43348. line: generated.line,
  43349. column: generated.column
  43350. }
  43351. });
  43352. lastOriginalSource = null;
  43353. sourceMappingActive = false;
  43354. }
  43355. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  43356. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  43357. generated.line++;
  43358. generated.column = 0;
  43359. // Mappings end at eol
  43360. if (idx + 1 === length) {
  43361. lastOriginalSource = null;
  43362. sourceMappingActive = false;
  43363. } else if (sourceMappingActive) {
  43364. map.addMapping({
  43365. source: original.source,
  43366. original: {
  43367. line: original.line,
  43368. column: original.column
  43369. },
  43370. generated: {
  43371. line: generated.line,
  43372. column: generated.column
  43373. },
  43374. name: original.name
  43375. });
  43376. }
  43377. } else {
  43378. generated.column++;
  43379. }
  43380. }
  43381. });
  43382. this.walkSourceContents(function (sourceFile, sourceContent) {
  43383. map.setSourceContent(sourceFile, sourceContent);
  43384. });
  43385. return { code: generated.code, map: map };
  43386. };
  43387. sourceNode.SourceNode = SourceNode;
  43388. return sourceNode;
  43389. }
  43390. /*
  43391. * Copyright 2009-2011 Mozilla Foundation and contributors
  43392. * Licensed under the New BSD license. See LICENSE.txt or:
  43393. * http://opensource.org/licenses/BSD-3-Clause
  43394. */
  43395. var hasRequiredSourceMap;
  43396. function requireSourceMap () {
  43397. if (hasRequiredSourceMap) return sourceMap;
  43398. hasRequiredSourceMap = 1;
  43399. sourceMap.SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  43400. sourceMap.SourceMapConsumer = /*@__PURE__*/ requireSourceMapConsumer().SourceMapConsumer;
  43401. sourceMap.SourceNode = /*@__PURE__*/ requireSourceNode().SourceNode;
  43402. return sourceMap;
  43403. }
  43404. var mergeSourceMap;
  43405. var hasRequiredMergeSourceMap;
  43406. function requireMergeSourceMap () {
  43407. if (hasRequiredMergeSourceMap) return mergeSourceMap;
  43408. hasRequiredMergeSourceMap = 1;
  43409. var sourceMap = /*@__PURE__*/ requireSourceMap();
  43410. var SourceMapConsumer = sourceMap.SourceMapConsumer;
  43411. var SourceMapGenerator = sourceMap.SourceMapGenerator;
  43412. mergeSourceMap = merge;
  43413. /**
  43414. * Merge old source map and new source map and return merged.
  43415. * If old or new source map value is falsy, return another one as it is.
  43416. *
  43417. * @param {object|string} [oldMap] old source map object
  43418. * @param {object|string} [newmap] new source map object
  43419. * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
  43420. */
  43421. function merge(oldMap, newMap) {
  43422. if (!oldMap) return newMap
  43423. if (!newMap) return oldMap
  43424. var oldMapConsumer = new SourceMapConsumer(oldMap);
  43425. var newMapConsumer = new SourceMapConsumer(newMap);
  43426. var mergedMapGenerator = new SourceMapGenerator();
  43427. // iterate on new map and overwrite original position of new map with one of old map
  43428. newMapConsumer.eachMapping(function(m) {
  43429. // pass when `originalLine` is null.
  43430. // It occurs in case that the node does not have origin in original code.
  43431. if (m.originalLine == null) return
  43432. var origPosInOldMap = oldMapConsumer.originalPositionFor({
  43433. line: m.originalLine,
  43434. column: m.originalColumn
  43435. });
  43436. if (origPosInOldMap.source == null) return
  43437. mergedMapGenerator.addMapping({
  43438. original: {
  43439. line: origPosInOldMap.line,
  43440. column: origPosInOldMap.column
  43441. },
  43442. generated: {
  43443. line: m.generatedLine,
  43444. column: m.generatedColumn
  43445. },
  43446. source: origPosInOldMap.source,
  43447. name: origPosInOldMap.name
  43448. });
  43449. });
  43450. var consumers = [oldMapConsumer, newMapConsumer];
  43451. consumers.forEach(function(consumer) {
  43452. consumer.sources.forEach(function(sourceFile) {
  43453. mergedMapGenerator._sources.add(sourceFile);
  43454. var sourceContent = consumer.sourceContentFor(sourceFile);
  43455. if (sourceContent != null) {
  43456. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  43457. }
  43458. });
  43459. });
  43460. mergedMapGenerator._sourceRoot = oldMap.sourceRoot;
  43461. mergedMapGenerator._file = oldMap.file;
  43462. return JSON.parse(mergedMapGenerator.toString())
  43463. }
  43464. return mergeSourceMap;
  43465. }
  43466. var mergeSourceMapExports = /*@__PURE__*/ requireMergeSourceMap();
  43467. var merge = /*@__PURE__*/getDefaultExportFromCjs(mergeSourceMapExports);
  43468. var __defProp$5 = Object.defineProperty;
  43469. var __defProps$4 = Object.defineProperties;
  43470. var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
  43471. var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
  43472. var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
  43473. var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
  43474. var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  43475. var __spreadValues$5 = (a, b) => {
  43476. for (var prop in b || (b = {}))
  43477. if (__hasOwnProp$5.call(b, prop))
  43478. __defNormalProp$5(a, prop, b[prop]);
  43479. if (__getOwnPropSymbols$5)
  43480. for (var prop of __getOwnPropSymbols$5(b)) {
  43481. if (__propIsEnum$5.call(b, prop))
  43482. __defNormalProp$5(a, prop, b[prop]);
  43483. }
  43484. return a;
  43485. };
  43486. var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
  43487. const scss = (source, map, options, load = require) => {
  43488. const nodeSass = load("sass");
  43489. const { compileString, renderSync } = nodeSass;
  43490. const data = getSource(source, options.filename, options.additionalData);
  43491. let css;
  43492. let dependencies;
  43493. let sourceMap;
  43494. try {
  43495. if (compileString) {
  43496. const { pathToFileURL, fileURLToPath } = load("url");
  43497. const result = compileString(data, __spreadProps$4(__spreadValues$5({}, options), {
  43498. url: pathToFileURL(options.filename),
  43499. sourceMap: !!map
  43500. }));
  43501. css = result.css;
  43502. dependencies = result.loadedUrls.map((url) => fileURLToPath(url));
  43503. sourceMap = map ? result.sourceMap : void 0;
  43504. } else {
  43505. const result = renderSync(__spreadProps$4(__spreadValues$5({}, options), {
  43506. data,
  43507. file: options.filename,
  43508. outFile: options.filename,
  43509. sourceMap: !!map
  43510. }));
  43511. css = result.css.toString();
  43512. dependencies = result.stats.includedFiles;
  43513. sourceMap = map ? JSON.parse(result.map.toString()) : void 0;
  43514. }
  43515. if (map) {
  43516. return {
  43517. code: css,
  43518. errors: [],
  43519. dependencies,
  43520. map: merge(map, sourceMap)
  43521. };
  43522. }
  43523. return { code: css, errors: [], dependencies };
  43524. } catch (e) {
  43525. return { code: "", errors: [e], dependencies: [] };
  43526. }
  43527. };
  43528. const sass = (source, map, options, load) => scss(
  43529. source,
  43530. map,
  43531. __spreadProps$4(__spreadValues$5({}, options), {
  43532. indentedSyntax: true
  43533. }),
  43534. load
  43535. );
  43536. const less = (source, map, options, load = require) => {
  43537. const nodeLess = load("less");
  43538. let result;
  43539. let error = null;
  43540. nodeLess.render(
  43541. getSource(source, options.filename, options.additionalData),
  43542. __spreadProps$4(__spreadValues$5({}, options), { syncImport: true }),
  43543. (err, output) => {
  43544. error = err;
  43545. result = output;
  43546. }
  43547. );
  43548. if (error) return { code: "", errors: [error], dependencies: [] };
  43549. const dependencies = result.imports;
  43550. if (map) {
  43551. return {
  43552. code: result.css.toString(),
  43553. map: merge(map, result.map),
  43554. errors: [],
  43555. dependencies
  43556. };
  43557. }
  43558. return {
  43559. code: result.css.toString(),
  43560. errors: [],
  43561. dependencies
  43562. };
  43563. };
  43564. const styl = (source, map, options, load = require) => {
  43565. const nodeStylus = load("stylus");
  43566. try {
  43567. const ref = nodeStylus(source, options);
  43568. if (map) ref.set("sourcemap", { inline: false, comment: false });
  43569. const result = ref.render();
  43570. const dependencies = ref.deps();
  43571. if (map) {
  43572. return {
  43573. code: result,
  43574. map: merge(map, ref.sourcemap),
  43575. errors: [],
  43576. dependencies
  43577. };
  43578. }
  43579. return { code: result, errors: [], dependencies };
  43580. } catch (e) {
  43581. return { code: "", errors: [e], dependencies: [] };
  43582. }
  43583. };
  43584. function getSource(source, filename, additionalData) {
  43585. if (!additionalData) return source;
  43586. if (isFunction$1(additionalData)) {
  43587. return additionalData(source, filename);
  43588. }
  43589. return additionalData + source;
  43590. }
  43591. const processors = {
  43592. less,
  43593. sass,
  43594. scss,
  43595. styl,
  43596. stylus: styl
  43597. };
  43598. var __defProp$4 = Object.defineProperty;
  43599. var __defProps$3 = Object.defineProperties;
  43600. var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
  43601. var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
  43602. var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
  43603. var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
  43604. var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  43605. var __spreadValues$4 = (a, b) => {
  43606. for (var prop in b || (b = {}))
  43607. if (__hasOwnProp$4.call(b, prop))
  43608. __defNormalProp$4(a, prop, b[prop]);
  43609. if (__getOwnPropSymbols$4)
  43610. for (var prop of __getOwnPropSymbols$4(b)) {
  43611. if (__propIsEnum$4.call(b, prop))
  43612. __defNormalProp$4(a, prop, b[prop]);
  43613. }
  43614. return a;
  43615. };
  43616. var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
  43617. function compileStyle(options) {
  43618. return doCompileStyle(__spreadProps$3(__spreadValues$4({}, options), {
  43619. isAsync: false
  43620. }));
  43621. }
  43622. function compileStyleAsync(options) {
  43623. return doCompileStyle(__spreadProps$3(__spreadValues$4({}, options), {
  43624. isAsync: true
  43625. }));
  43626. }
  43627. function doCompileStyle(options) {
  43628. const {
  43629. filename,
  43630. id,
  43631. scoped = false,
  43632. trim = true,
  43633. isProd = false,
  43634. modules = false,
  43635. modulesOptions = {},
  43636. preprocessLang,
  43637. postcssOptions,
  43638. postcssPlugins
  43639. } = options;
  43640. const preprocessor = preprocessLang && processors[preprocessLang];
  43641. const preProcessedSource = preprocessor && preprocess(options, preprocessor);
  43642. const map = preProcessedSource ? preProcessedSource.map : options.inMap || options.map;
  43643. const source = preProcessedSource ? preProcessedSource.code : options.source;
  43644. const shortId = id.replace(/^data-v-/, "");
  43645. const longId = `data-v-${shortId}`;
  43646. const plugins = (postcssPlugins || []).slice();
  43647. plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
  43648. if (trim) {
  43649. plugins.push(trimPlugin());
  43650. }
  43651. if (scoped) {
  43652. plugins.push(scopedPlugin(longId));
  43653. }
  43654. let cssModules;
  43655. if (modules) {
  43656. {
  43657. throw new Error(
  43658. "[@vue/compiler-sfc] `modules` option is not supported in the browser build."
  43659. );
  43660. }
  43661. }
  43662. const postCSSOptions = __spreadProps$3(__spreadValues$4({}, postcssOptions), {
  43663. to: filename,
  43664. from: filename
  43665. });
  43666. if (map) {
  43667. postCSSOptions.map = {
  43668. inline: false,
  43669. annotation: false,
  43670. prev: map
  43671. };
  43672. }
  43673. let result;
  43674. let code;
  43675. let outMap;
  43676. const dependencies = new Set(
  43677. preProcessedSource ? preProcessedSource.dependencies : []
  43678. );
  43679. dependencies.delete(filename);
  43680. const errors = [];
  43681. if (preProcessedSource && preProcessedSource.errors.length) {
  43682. errors.push(...preProcessedSource.errors);
  43683. }
  43684. const recordPlainCssDependencies = (messages) => {
  43685. messages.forEach((msg) => {
  43686. if (msg.type === "dependency") {
  43687. dependencies.add(msg.file);
  43688. }
  43689. });
  43690. return dependencies;
  43691. };
  43692. try {
  43693. result = postcss(plugins).process(source, postCSSOptions);
  43694. if (options.isAsync) {
  43695. return result.then((result2) => ({
  43696. code: result2.css || "",
  43697. map: result2.map && result2.map.toJSON(),
  43698. errors,
  43699. modules: cssModules,
  43700. rawResult: result2,
  43701. dependencies: recordPlainCssDependencies(result2.messages)
  43702. })).catch((error) => ({
  43703. code: "",
  43704. map: void 0,
  43705. errors: [...errors, error],
  43706. rawResult: void 0,
  43707. dependencies
  43708. }));
  43709. }
  43710. recordPlainCssDependencies(result.messages);
  43711. code = result.css;
  43712. outMap = result.map;
  43713. } catch (e) {
  43714. errors.push(e);
  43715. }
  43716. return {
  43717. code: code || ``,
  43718. map: outMap && outMap.toJSON(),
  43719. errors,
  43720. rawResult: result,
  43721. dependencies
  43722. };
  43723. }
  43724. function preprocess(options, preprocessor) {
  43725. if (!options.preprocessCustomRequire) {
  43726. throw new Error(
  43727. `[@vue/compiler-sfc] Style preprocessing in the browser build must provide the \`preprocessCustomRequire\` option to return the in-browser version of the preprocessor.`
  43728. );
  43729. }
  43730. return preprocessor(
  43731. options.source,
  43732. options.inMap || options.map,
  43733. __spreadValues$4({
  43734. filename: options.filename
  43735. }, options.preprocessOptions),
  43736. options.preprocessCustomRequire
  43737. );
  43738. }
  43739. const UNKNOWN_TYPE = "Unknown";
  43740. function resolveObjectKey(node, computed) {
  43741. switch (node.type) {
  43742. case "StringLiteral":
  43743. case "NumericLiteral":
  43744. return String(node.value);
  43745. case "Identifier":
  43746. if (!computed) return node.name;
  43747. }
  43748. return void 0;
  43749. }
  43750. function concatStrings(strs) {
  43751. return strs.filter((s) => !!s).join(", ");
  43752. }
  43753. function isLiteralNode(node) {
  43754. return node.type.endsWith("Literal");
  43755. }
  43756. function isCallOf(node, test) {
  43757. return !!(node && test && node.type === "CallExpression" && node.callee.type === "Identifier" && (typeof test === "string" ? node.callee.name === test : test(node.callee.name)));
  43758. }
  43759. function toRuntimeTypeString(types) {
  43760. return types.length > 1 ? `[${types.join(", ")}]` : types[0];
  43761. }
  43762. function getImportedName(specifier) {
  43763. if (specifier.type === "ImportSpecifier")
  43764. return specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
  43765. else if (specifier.type === "ImportNamespaceSpecifier") return "*";
  43766. return "default";
  43767. }
  43768. function getId(node) {
  43769. return node.type === "Identifier" ? node.name : node.type === "StringLiteral" ? node.value : null;
  43770. }
  43771. function getStringLiteralKey(node) {
  43772. return node.computed ? node.key.type === "TemplateLiteral" && !node.key.expressions.length ? node.key.quasis.map((q) => q.value.cooked).join("") : null : node.key.type === "Identifier" ? node.key.name : node.key.type === "StringLiteral" ? node.key.value : node.key.type === "NumericLiteral" ? String(node.key.value) : null;
  43773. }
  43774. const normalize = (path.posix || path).normalize;
  43775. const windowsSlashRE = /\\/g;
  43776. function normalizePath(p) {
  43777. return normalize(p.replace(windowsSlashRE, "/"));
  43778. }
  43779. const joinPaths = (path.posix || path).join;
  43780. const propNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~\-]/;
  43781. function getEscapedPropName(key) {
  43782. return propNameEscapeSymbolsRE.test(key) ? JSON.stringify(key) : key;
  43783. }
  43784. const isJS = (...langs) => langs.some((lang) => lang === "js" || lang === "jsx");
  43785. const isTS = (...langs) => langs.some((lang) => lang === "ts" || lang === "tsx");
  43786. function analyzeScriptBindings(ast) {
  43787. for (const node of ast) {
  43788. if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "ObjectExpression") {
  43789. return analyzeBindingsFromOptions(node.declaration);
  43790. }
  43791. }
  43792. return {};
  43793. }
  43794. function analyzeBindingsFromOptions(node) {
  43795. const bindings = {};
  43796. Object.defineProperty(bindings, "__isScriptSetup", {
  43797. enumerable: false,
  43798. value: false
  43799. });
  43800. for (const property of node.properties) {
  43801. if (property.type === "ObjectProperty" && !property.computed && property.key.type === "Identifier") {
  43802. if (property.key.name === "props") {
  43803. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  43804. bindings[key] = "props";
  43805. }
  43806. } else if (property.key.name === "inject") {
  43807. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  43808. bindings[key] = "options";
  43809. }
  43810. } else if (property.value.type === "ObjectExpression" && (property.key.name === "computed" || property.key.name === "methods")) {
  43811. for (const key of getObjectExpressionKeys(property.value)) {
  43812. bindings[key] = "options";
  43813. }
  43814. }
  43815. } else if (property.type === "ObjectMethod" && property.key.type === "Identifier" && (property.key.name === "setup" || property.key.name === "data")) {
  43816. for (const bodyItem of property.body.body) {
  43817. if (bodyItem.type === "ReturnStatement" && bodyItem.argument && bodyItem.argument.type === "ObjectExpression") {
  43818. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  43819. bindings[key] = property.key.name === "setup" ? "setup-maybe-ref" : "data";
  43820. }
  43821. }
  43822. }
  43823. }
  43824. }
  43825. return bindings;
  43826. }
  43827. function getObjectExpressionKeys(node) {
  43828. const keys = [];
  43829. for (const prop of node.properties) {
  43830. if (prop.type === "SpreadElement") continue;
  43831. const key = resolveObjectKey(prop.key, prop.computed);
  43832. if (key) keys.push(String(key));
  43833. }
  43834. return keys;
  43835. }
  43836. function getArrayExpressionKeys(node) {
  43837. const keys = [];
  43838. for (const element of node.elements) {
  43839. if (element && element.type === "StringLiteral") {
  43840. keys.push(element.value);
  43841. }
  43842. }
  43843. return keys;
  43844. }
  43845. function getObjectOrArrayExpressionKeys(value) {
  43846. if (value.type === "ArrayExpression") {
  43847. return getArrayExpressionKeys(value);
  43848. }
  43849. if (value.type === "ObjectExpression") {
  43850. return getObjectExpressionKeys(value);
  43851. }
  43852. return [];
  43853. }
  43854. // src/vlq.ts
  43855. var comma = ",".charCodeAt(0);
  43856. var semicolon = ";".charCodeAt(0);
  43857. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  43858. var intToChar = new Uint8Array(64);
  43859. var charToInt = new Uint8Array(128);
  43860. for (let i = 0; i < chars.length; i++) {
  43861. const c = chars.charCodeAt(i);
  43862. intToChar[i] = c;
  43863. charToInt[c] = i;
  43864. }
  43865. function encodeInteger(builder, num, relative) {
  43866. let delta = num - relative;
  43867. delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
  43868. do {
  43869. let clamped = delta & 31;
  43870. delta >>>= 5;
  43871. if (delta > 0) clamped |= 32;
  43872. builder.write(intToChar[clamped]);
  43873. } while (delta > 0);
  43874. return num;
  43875. }
  43876. // src/strings.ts
  43877. var bufLength = 1024 * 16;
  43878. var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
  43879. decode(buf) {
  43880. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  43881. return out.toString();
  43882. }
  43883. } : {
  43884. decode(buf) {
  43885. let out = "";
  43886. for (let i = 0; i < buf.length; i++) {
  43887. out += String.fromCharCode(buf[i]);
  43888. }
  43889. return out;
  43890. }
  43891. };
  43892. var StringWriter = class {
  43893. constructor() {
  43894. this.pos = 0;
  43895. this.out = "";
  43896. this.buffer = new Uint8Array(bufLength);
  43897. }
  43898. write(v) {
  43899. const { buffer } = this;
  43900. buffer[this.pos++] = v;
  43901. if (this.pos === bufLength) {
  43902. this.out += td.decode(buffer);
  43903. this.pos = 0;
  43904. }
  43905. }
  43906. flush() {
  43907. const { buffer, out, pos } = this;
  43908. return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
  43909. }
  43910. };
  43911. function encode(decoded) {
  43912. const writer = new StringWriter();
  43913. let sourcesIndex = 0;
  43914. let sourceLine = 0;
  43915. let sourceColumn = 0;
  43916. let namesIndex = 0;
  43917. for (let i = 0; i < decoded.length; i++) {
  43918. const line = decoded[i];
  43919. if (i > 0) writer.write(semicolon);
  43920. if (line.length === 0) continue;
  43921. let genColumn = 0;
  43922. for (let j = 0; j < line.length; j++) {
  43923. const segment = line[j];
  43924. if (j > 0) writer.write(comma);
  43925. genColumn = encodeInteger(writer, segment[0], genColumn);
  43926. if (segment.length === 1) continue;
  43927. sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
  43928. sourceLine = encodeInteger(writer, segment[2], sourceLine);
  43929. sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
  43930. if (segment.length === 4) continue;
  43931. namesIndex = encodeInteger(writer, segment[4], namesIndex);
  43932. }
  43933. }
  43934. return writer.flush();
  43935. }
  43936. class BitSet {
  43937. constructor(arg) {
  43938. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  43939. }
  43940. add(n) {
  43941. this.bits[n >> 5] |= 1 << (n & 31);
  43942. }
  43943. has(n) {
  43944. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  43945. }
  43946. }
  43947. class Chunk {
  43948. constructor(start, end, content) {
  43949. this.start = start;
  43950. this.end = end;
  43951. this.original = content;
  43952. this.intro = '';
  43953. this.outro = '';
  43954. this.content = content;
  43955. this.storeName = false;
  43956. this.edited = false;
  43957. {
  43958. this.previous = null;
  43959. this.next = null;
  43960. }
  43961. }
  43962. appendLeft(content) {
  43963. this.outro += content;
  43964. }
  43965. appendRight(content) {
  43966. this.intro = this.intro + content;
  43967. }
  43968. clone() {
  43969. const chunk = new Chunk(this.start, this.end, this.original);
  43970. chunk.intro = this.intro;
  43971. chunk.outro = this.outro;
  43972. chunk.content = this.content;
  43973. chunk.storeName = this.storeName;
  43974. chunk.edited = this.edited;
  43975. return chunk;
  43976. }
  43977. contains(index) {
  43978. return this.start < index && index < this.end;
  43979. }
  43980. eachNext(fn) {
  43981. let chunk = this;
  43982. while (chunk) {
  43983. fn(chunk);
  43984. chunk = chunk.next;
  43985. }
  43986. }
  43987. eachPrevious(fn) {
  43988. let chunk = this;
  43989. while (chunk) {
  43990. fn(chunk);
  43991. chunk = chunk.previous;
  43992. }
  43993. }
  43994. edit(content, storeName, contentOnly) {
  43995. this.content = content;
  43996. if (!contentOnly) {
  43997. this.intro = '';
  43998. this.outro = '';
  43999. }
  44000. this.storeName = storeName;
  44001. this.edited = true;
  44002. return this;
  44003. }
  44004. prependLeft(content) {
  44005. this.outro = content + this.outro;
  44006. }
  44007. prependRight(content) {
  44008. this.intro = content + this.intro;
  44009. }
  44010. reset() {
  44011. this.intro = '';
  44012. this.outro = '';
  44013. if (this.edited) {
  44014. this.content = this.original;
  44015. this.storeName = false;
  44016. this.edited = false;
  44017. }
  44018. }
  44019. split(index) {
  44020. const sliceIndex = index - this.start;
  44021. const originalBefore = this.original.slice(0, sliceIndex);
  44022. const originalAfter = this.original.slice(sliceIndex);
  44023. this.original = originalBefore;
  44024. const newChunk = new Chunk(index, this.end, originalAfter);
  44025. newChunk.outro = this.outro;
  44026. this.outro = '';
  44027. this.end = index;
  44028. if (this.edited) {
  44029. // after split we should save the edit content record into the correct chunk
  44030. // to make sure sourcemap correct
  44031. // For example:
  44032. // ' test'.trim()
  44033. // split -> ' ' + 'test'
  44034. // ✔️ edit -> '' + 'test'
  44035. // ✖️ edit -> 'test' + ''
  44036. // TODO is this block necessary?...
  44037. newChunk.edit('', false);
  44038. this.content = '';
  44039. } else {
  44040. this.content = originalBefore;
  44041. }
  44042. newChunk.next = this.next;
  44043. if (newChunk.next) newChunk.next.previous = newChunk;
  44044. newChunk.previous = this;
  44045. this.next = newChunk;
  44046. return newChunk;
  44047. }
  44048. toString() {
  44049. return this.intro + this.content + this.outro;
  44050. }
  44051. trimEnd(rx) {
  44052. this.outro = this.outro.replace(rx, '');
  44053. if (this.outro.length) return true;
  44054. const trimmed = this.content.replace(rx, '');
  44055. if (trimmed.length) {
  44056. if (trimmed !== this.content) {
  44057. this.split(this.start + trimmed.length).edit('', undefined, true);
  44058. if (this.edited) {
  44059. // save the change, if it has been edited
  44060. this.edit(trimmed, this.storeName, true);
  44061. }
  44062. }
  44063. return true;
  44064. } else {
  44065. this.edit('', undefined, true);
  44066. this.intro = this.intro.replace(rx, '');
  44067. if (this.intro.length) return true;
  44068. }
  44069. }
  44070. trimStart(rx) {
  44071. this.intro = this.intro.replace(rx, '');
  44072. if (this.intro.length) return true;
  44073. const trimmed = this.content.replace(rx, '');
  44074. if (trimmed.length) {
  44075. if (trimmed !== this.content) {
  44076. const newChunk = this.split(this.end - trimmed.length);
  44077. if (this.edited) {
  44078. // save the change, if it has been edited
  44079. newChunk.edit(trimmed, this.storeName, true);
  44080. }
  44081. this.edit('', undefined, true);
  44082. }
  44083. return true;
  44084. } else {
  44085. this.edit('', undefined, true);
  44086. this.outro = this.outro.replace(rx, '');
  44087. if (this.outro.length) return true;
  44088. }
  44089. }
  44090. }
  44091. function getBtoa() {
  44092. if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {
  44093. return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
  44094. } else if (typeof Buffer === 'function') {
  44095. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  44096. } else {
  44097. return () => {
  44098. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  44099. };
  44100. }
  44101. }
  44102. const btoa = /*#__PURE__*/ getBtoa();
  44103. class SourceMap {
  44104. constructor(properties) {
  44105. this.version = 3;
  44106. this.file = properties.file;
  44107. this.sources = properties.sources;
  44108. this.sourcesContent = properties.sourcesContent;
  44109. this.names = properties.names;
  44110. this.mappings = encode(properties.mappings);
  44111. if (typeof properties.x_google_ignoreList !== 'undefined') {
  44112. this.x_google_ignoreList = properties.x_google_ignoreList;
  44113. }
  44114. if (typeof properties.debugId !== 'undefined') {
  44115. this.debugId = properties.debugId;
  44116. }
  44117. }
  44118. toString() {
  44119. return JSON.stringify(this);
  44120. }
  44121. toUrl() {
  44122. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  44123. }
  44124. }
  44125. function guessIndent(code) {
  44126. const lines = code.split('\n');
  44127. const tabbed = lines.filter((line) => /^\t+/.test(line));
  44128. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  44129. if (tabbed.length === 0 && spaced.length === 0) {
  44130. return null;
  44131. }
  44132. // More lines tabbed than spaced? Assume tabs, and
  44133. // default to tabs in the case of a tie (or nothing
  44134. // to go on)
  44135. if (tabbed.length >= spaced.length) {
  44136. return '\t';
  44137. }
  44138. // Otherwise, we need to guess the multiple
  44139. const min = spaced.reduce((previous, current) => {
  44140. const numSpaces = /^ +/.exec(current)[0].length;
  44141. return Math.min(numSpaces, previous);
  44142. }, Infinity);
  44143. return new Array(min + 1).join(' ');
  44144. }
  44145. function getRelativePath(from, to) {
  44146. const fromParts = from.split(/[/\\]/);
  44147. const toParts = to.split(/[/\\]/);
  44148. fromParts.pop(); // get dirname
  44149. while (fromParts[0] === toParts[0]) {
  44150. fromParts.shift();
  44151. toParts.shift();
  44152. }
  44153. if (fromParts.length) {
  44154. let i = fromParts.length;
  44155. while (i--) fromParts[i] = '..';
  44156. }
  44157. return fromParts.concat(toParts).join('/');
  44158. }
  44159. const toString = Object.prototype.toString;
  44160. function isObject(thing) {
  44161. return toString.call(thing) === '[object Object]';
  44162. }
  44163. function getLocator(source) {
  44164. const originalLines = source.split('\n');
  44165. const lineOffsets = [];
  44166. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  44167. lineOffsets.push(pos);
  44168. pos += originalLines[i].length + 1;
  44169. }
  44170. return function locate(index) {
  44171. let i = 0;
  44172. let j = lineOffsets.length;
  44173. while (i < j) {
  44174. const m = (i + j) >> 1;
  44175. if (index < lineOffsets[m]) {
  44176. j = m;
  44177. } else {
  44178. i = m + 1;
  44179. }
  44180. }
  44181. const line = i - 1;
  44182. const column = index - lineOffsets[line];
  44183. return { line, column };
  44184. };
  44185. }
  44186. const wordRegex = /\w/;
  44187. class Mappings {
  44188. constructor(hires) {
  44189. this.hires = hires;
  44190. this.generatedCodeLine = 0;
  44191. this.generatedCodeColumn = 0;
  44192. this.raw = [];
  44193. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  44194. this.pending = null;
  44195. }
  44196. addEdit(sourceIndex, content, loc, nameIndex) {
  44197. if (content.length) {
  44198. const contentLengthMinusOne = content.length - 1;
  44199. let contentLineEnd = content.indexOf('\n', 0);
  44200. let previousContentLineEnd = -1;
  44201. // Loop through each line in the content and add a segment, but stop if the last line is empty,
  44202. // else code afterwards would fill one line too many
  44203. while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
  44204. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  44205. if (nameIndex >= 0) {
  44206. segment.push(nameIndex);
  44207. }
  44208. this.rawSegments.push(segment);
  44209. this.generatedCodeLine += 1;
  44210. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  44211. this.generatedCodeColumn = 0;
  44212. previousContentLineEnd = contentLineEnd;
  44213. contentLineEnd = content.indexOf('\n', contentLineEnd + 1);
  44214. }
  44215. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  44216. if (nameIndex >= 0) {
  44217. segment.push(nameIndex);
  44218. }
  44219. this.rawSegments.push(segment);
  44220. this.advance(content.slice(previousContentLineEnd + 1));
  44221. } else if (this.pending) {
  44222. this.rawSegments.push(this.pending);
  44223. this.advance(content);
  44224. }
  44225. this.pending = null;
  44226. }
  44227. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  44228. let originalCharIndex = chunk.start;
  44229. let first = true;
  44230. // when iterating each char, check if it's in a word boundary
  44231. let charInHiresBoundary = false;
  44232. while (originalCharIndex < chunk.end) {
  44233. if (original[originalCharIndex] === '\n') {
  44234. loc.line += 1;
  44235. loc.column = 0;
  44236. this.generatedCodeLine += 1;
  44237. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  44238. this.generatedCodeColumn = 0;
  44239. first = true;
  44240. charInHiresBoundary = false;
  44241. } else {
  44242. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  44243. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  44244. if (this.hires === 'boundary') {
  44245. // in hires "boundary", group segments per word boundary than per char
  44246. if (wordRegex.test(original[originalCharIndex])) {
  44247. // for first char in the boundary found, start the boundary by pushing a segment
  44248. if (!charInHiresBoundary) {
  44249. this.rawSegments.push(segment);
  44250. charInHiresBoundary = true;
  44251. }
  44252. } else {
  44253. // for non-word char, end the boundary by pushing a segment
  44254. this.rawSegments.push(segment);
  44255. charInHiresBoundary = false;
  44256. }
  44257. } else {
  44258. this.rawSegments.push(segment);
  44259. }
  44260. }
  44261. loc.column += 1;
  44262. this.generatedCodeColumn += 1;
  44263. first = false;
  44264. }
  44265. originalCharIndex += 1;
  44266. }
  44267. this.pending = null;
  44268. }
  44269. advance(str) {
  44270. if (!str) return;
  44271. const lines = str.split('\n');
  44272. if (lines.length > 1) {
  44273. for (let i = 0; i < lines.length - 1; i++) {
  44274. this.generatedCodeLine++;
  44275. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  44276. }
  44277. this.generatedCodeColumn = 0;
  44278. }
  44279. this.generatedCodeColumn += lines[lines.length - 1].length;
  44280. }
  44281. }
  44282. const n = '\n';
  44283. const warned = {
  44284. insertLeft: false,
  44285. insertRight: false,
  44286. storeName: false,
  44287. };
  44288. class MagicString {
  44289. constructor(string, options = {}) {
  44290. const chunk = new Chunk(0, string.length, string);
  44291. Object.defineProperties(this, {
  44292. original: { writable: true, value: string },
  44293. outro: { writable: true, value: '' },
  44294. intro: { writable: true, value: '' },
  44295. firstChunk: { writable: true, value: chunk },
  44296. lastChunk: { writable: true, value: chunk },
  44297. lastSearchedChunk: { writable: true, value: chunk },
  44298. byStart: { writable: true, value: {} },
  44299. byEnd: { writable: true, value: {} },
  44300. filename: { writable: true, value: options.filename },
  44301. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  44302. sourcemapLocations: { writable: true, value: new BitSet() },
  44303. storedNames: { writable: true, value: {} },
  44304. indentStr: { writable: true, value: undefined },
  44305. ignoreList: { writable: true, value: options.ignoreList },
  44306. offset: { writable: true, value: options.offset || 0 },
  44307. });
  44308. this.byStart[0] = chunk;
  44309. this.byEnd[string.length] = chunk;
  44310. }
  44311. addSourcemapLocation(char) {
  44312. this.sourcemapLocations.add(char);
  44313. }
  44314. append(content) {
  44315. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  44316. this.outro += content;
  44317. return this;
  44318. }
  44319. appendLeft(index, content) {
  44320. index = index + this.offset;
  44321. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  44322. this._split(index);
  44323. const chunk = this.byEnd[index];
  44324. if (chunk) {
  44325. chunk.appendLeft(content);
  44326. } else {
  44327. this.intro += content;
  44328. }
  44329. return this;
  44330. }
  44331. appendRight(index, content) {
  44332. index = index + this.offset;
  44333. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  44334. this._split(index);
  44335. const chunk = this.byStart[index];
  44336. if (chunk) {
  44337. chunk.appendRight(content);
  44338. } else {
  44339. this.outro += content;
  44340. }
  44341. return this;
  44342. }
  44343. clone() {
  44344. const cloned = new MagicString(this.original, { filename: this.filename, offset: this.offset });
  44345. let originalChunk = this.firstChunk;
  44346. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  44347. while (originalChunk) {
  44348. cloned.byStart[clonedChunk.start] = clonedChunk;
  44349. cloned.byEnd[clonedChunk.end] = clonedChunk;
  44350. const nextOriginalChunk = originalChunk.next;
  44351. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  44352. if (nextClonedChunk) {
  44353. clonedChunk.next = nextClonedChunk;
  44354. nextClonedChunk.previous = clonedChunk;
  44355. clonedChunk = nextClonedChunk;
  44356. }
  44357. originalChunk = nextOriginalChunk;
  44358. }
  44359. cloned.lastChunk = clonedChunk;
  44360. if (this.indentExclusionRanges) {
  44361. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  44362. }
  44363. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  44364. cloned.intro = this.intro;
  44365. cloned.outro = this.outro;
  44366. return cloned;
  44367. }
  44368. generateDecodedMap(options) {
  44369. options = options || {};
  44370. const sourceIndex = 0;
  44371. const names = Object.keys(this.storedNames);
  44372. const mappings = new Mappings(options.hires);
  44373. const locate = getLocator(this.original);
  44374. if (this.intro) {
  44375. mappings.advance(this.intro);
  44376. }
  44377. this.firstChunk.eachNext((chunk) => {
  44378. const loc = locate(chunk.start);
  44379. if (chunk.intro.length) mappings.advance(chunk.intro);
  44380. if (chunk.edited) {
  44381. mappings.addEdit(
  44382. sourceIndex,
  44383. chunk.content,
  44384. loc,
  44385. chunk.storeName ? names.indexOf(chunk.original) : -1,
  44386. );
  44387. } else {
  44388. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  44389. }
  44390. if (chunk.outro.length) mappings.advance(chunk.outro);
  44391. });
  44392. if (this.outro) {
  44393. mappings.advance(this.outro);
  44394. }
  44395. return {
  44396. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  44397. sources: [
  44398. options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
  44399. ],
  44400. sourcesContent: options.includeContent ? [this.original] : undefined,
  44401. names,
  44402. mappings: mappings.raw,
  44403. x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
  44404. };
  44405. }
  44406. generateMap(options) {
  44407. return new SourceMap(this.generateDecodedMap(options));
  44408. }
  44409. _ensureindentStr() {
  44410. if (this.indentStr === undefined) {
  44411. this.indentStr = guessIndent(this.original);
  44412. }
  44413. }
  44414. _getRawIndentString() {
  44415. this._ensureindentStr();
  44416. return this.indentStr;
  44417. }
  44418. getIndentString() {
  44419. this._ensureindentStr();
  44420. return this.indentStr === null ? '\t' : this.indentStr;
  44421. }
  44422. indent(indentStr, options) {
  44423. const pattern = /^[^\r\n]/gm;
  44424. if (isObject(indentStr)) {
  44425. options = indentStr;
  44426. indentStr = undefined;
  44427. }
  44428. if (indentStr === undefined) {
  44429. this._ensureindentStr();
  44430. indentStr = this.indentStr || '\t';
  44431. }
  44432. if (indentStr === '') return this; // noop
  44433. options = options || {};
  44434. // Process exclusion ranges
  44435. const isExcluded = {};
  44436. if (options.exclude) {
  44437. const exclusions =
  44438. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  44439. exclusions.forEach((exclusion) => {
  44440. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  44441. isExcluded[i] = true;
  44442. }
  44443. });
  44444. }
  44445. let shouldIndentNextCharacter = options.indentStart !== false;
  44446. const replacer = (match) => {
  44447. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  44448. shouldIndentNextCharacter = true;
  44449. return match;
  44450. };
  44451. this.intro = this.intro.replace(pattern, replacer);
  44452. let charIndex = 0;
  44453. let chunk = this.firstChunk;
  44454. while (chunk) {
  44455. const end = chunk.end;
  44456. if (chunk.edited) {
  44457. if (!isExcluded[charIndex]) {
  44458. chunk.content = chunk.content.replace(pattern, replacer);
  44459. if (chunk.content.length) {
  44460. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  44461. }
  44462. }
  44463. } else {
  44464. charIndex = chunk.start;
  44465. while (charIndex < end) {
  44466. if (!isExcluded[charIndex]) {
  44467. const char = this.original[charIndex];
  44468. if (char === '\n') {
  44469. shouldIndentNextCharacter = true;
  44470. } else if (char !== '\r' && shouldIndentNextCharacter) {
  44471. shouldIndentNextCharacter = false;
  44472. if (charIndex === chunk.start) {
  44473. chunk.prependRight(indentStr);
  44474. } else {
  44475. this._splitChunk(chunk, charIndex);
  44476. chunk = chunk.next;
  44477. chunk.prependRight(indentStr);
  44478. }
  44479. }
  44480. }
  44481. charIndex += 1;
  44482. }
  44483. }
  44484. charIndex = chunk.end;
  44485. chunk = chunk.next;
  44486. }
  44487. this.outro = this.outro.replace(pattern, replacer);
  44488. return this;
  44489. }
  44490. insert() {
  44491. throw new Error(
  44492. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
  44493. );
  44494. }
  44495. insertLeft(index, content) {
  44496. if (!warned.insertLeft) {
  44497. console.warn(
  44498. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
  44499. );
  44500. warned.insertLeft = true;
  44501. }
  44502. return this.appendLeft(index, content);
  44503. }
  44504. insertRight(index, content) {
  44505. if (!warned.insertRight) {
  44506. console.warn(
  44507. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
  44508. );
  44509. warned.insertRight = true;
  44510. }
  44511. return this.prependRight(index, content);
  44512. }
  44513. move(start, end, index) {
  44514. start = start + this.offset;
  44515. end = end + this.offset;
  44516. index = index + this.offset;
  44517. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  44518. this._split(start);
  44519. this._split(end);
  44520. this._split(index);
  44521. const first = this.byStart[start];
  44522. const last = this.byEnd[end];
  44523. const oldLeft = first.previous;
  44524. const oldRight = last.next;
  44525. const newRight = this.byStart[index];
  44526. if (!newRight && last === this.lastChunk) return this;
  44527. const newLeft = newRight ? newRight.previous : this.lastChunk;
  44528. if (oldLeft) oldLeft.next = oldRight;
  44529. if (oldRight) oldRight.previous = oldLeft;
  44530. if (newLeft) newLeft.next = first;
  44531. if (newRight) newRight.previous = last;
  44532. if (!first.previous) this.firstChunk = last.next;
  44533. if (!last.next) {
  44534. this.lastChunk = first.previous;
  44535. this.lastChunk.next = null;
  44536. }
  44537. first.previous = newLeft;
  44538. last.next = newRight || null;
  44539. if (!newLeft) this.firstChunk = first;
  44540. if (!newRight) this.lastChunk = last;
  44541. return this;
  44542. }
  44543. overwrite(start, end, content, options) {
  44544. options = options || {};
  44545. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  44546. }
  44547. update(start, end, content, options) {
  44548. start = start + this.offset;
  44549. end = end + this.offset;
  44550. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  44551. if (this.original.length !== 0) {
  44552. while (start < 0) start += this.original.length;
  44553. while (end < 0) end += this.original.length;
  44554. }
  44555. if (end > this.original.length) throw new Error('end is out of bounds');
  44556. if (start === end)
  44557. throw new Error(
  44558. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
  44559. );
  44560. this._split(start);
  44561. this._split(end);
  44562. if (options === true) {
  44563. if (!warned.storeName) {
  44564. console.warn(
  44565. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
  44566. );
  44567. warned.storeName = true;
  44568. }
  44569. options = { storeName: true };
  44570. }
  44571. const storeName = options !== undefined ? options.storeName : false;
  44572. const overwrite = options !== undefined ? options.overwrite : false;
  44573. if (storeName) {
  44574. const original = this.original.slice(start, end);
  44575. Object.defineProperty(this.storedNames, original, {
  44576. writable: true,
  44577. value: true,
  44578. enumerable: true,
  44579. });
  44580. }
  44581. const first = this.byStart[start];
  44582. const last = this.byEnd[end];
  44583. if (first) {
  44584. let chunk = first;
  44585. while (chunk !== last) {
  44586. if (chunk.next !== this.byStart[chunk.end]) {
  44587. throw new Error('Cannot overwrite across a split point');
  44588. }
  44589. chunk = chunk.next;
  44590. chunk.edit('', false);
  44591. }
  44592. first.edit(content, storeName, !overwrite);
  44593. } else {
  44594. // must be inserting at the end
  44595. const newChunk = new Chunk(start, end, '').edit(content, storeName);
  44596. // TODO last chunk in the array may not be the last chunk, if it's moved...
  44597. last.next = newChunk;
  44598. newChunk.previous = last;
  44599. }
  44600. return this;
  44601. }
  44602. prepend(content) {
  44603. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  44604. this.intro = content + this.intro;
  44605. return this;
  44606. }
  44607. prependLeft(index, content) {
  44608. index = index + this.offset;
  44609. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  44610. this._split(index);
  44611. const chunk = this.byEnd[index];
  44612. if (chunk) {
  44613. chunk.prependLeft(content);
  44614. } else {
  44615. this.intro = content + this.intro;
  44616. }
  44617. return this;
  44618. }
  44619. prependRight(index, content) {
  44620. index = index + this.offset;
  44621. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  44622. this._split(index);
  44623. const chunk = this.byStart[index];
  44624. if (chunk) {
  44625. chunk.prependRight(content);
  44626. } else {
  44627. this.outro = content + this.outro;
  44628. }
  44629. return this;
  44630. }
  44631. remove(start, end) {
  44632. start = start + this.offset;
  44633. end = end + this.offset;
  44634. if (this.original.length !== 0) {
  44635. while (start < 0) start += this.original.length;
  44636. while (end < 0) end += this.original.length;
  44637. }
  44638. if (start === end) return this;
  44639. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  44640. if (start > end) throw new Error('end must be greater than start');
  44641. this._split(start);
  44642. this._split(end);
  44643. let chunk = this.byStart[start];
  44644. while (chunk) {
  44645. chunk.intro = '';
  44646. chunk.outro = '';
  44647. chunk.edit('');
  44648. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  44649. }
  44650. return this;
  44651. }
  44652. reset(start, end) {
  44653. start = start + this.offset;
  44654. end = end + this.offset;
  44655. if (this.original.length !== 0) {
  44656. while (start < 0) start += this.original.length;
  44657. while (end < 0) end += this.original.length;
  44658. }
  44659. if (start === end) return this;
  44660. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  44661. if (start > end) throw new Error('end must be greater than start');
  44662. this._split(start);
  44663. this._split(end);
  44664. let chunk = this.byStart[start];
  44665. while (chunk) {
  44666. chunk.reset();
  44667. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  44668. }
  44669. return this;
  44670. }
  44671. lastChar() {
  44672. if (this.outro.length) return this.outro[this.outro.length - 1];
  44673. let chunk = this.lastChunk;
  44674. do {
  44675. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  44676. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  44677. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  44678. } while ((chunk = chunk.previous));
  44679. if (this.intro.length) return this.intro[this.intro.length - 1];
  44680. return '';
  44681. }
  44682. lastLine() {
  44683. let lineIndex = this.outro.lastIndexOf(n);
  44684. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  44685. let lineStr = this.outro;
  44686. let chunk = this.lastChunk;
  44687. do {
  44688. if (chunk.outro.length > 0) {
  44689. lineIndex = chunk.outro.lastIndexOf(n);
  44690. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  44691. lineStr = chunk.outro + lineStr;
  44692. }
  44693. if (chunk.content.length > 0) {
  44694. lineIndex = chunk.content.lastIndexOf(n);
  44695. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  44696. lineStr = chunk.content + lineStr;
  44697. }
  44698. if (chunk.intro.length > 0) {
  44699. lineIndex = chunk.intro.lastIndexOf(n);
  44700. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  44701. lineStr = chunk.intro + lineStr;
  44702. }
  44703. } while ((chunk = chunk.previous));
  44704. lineIndex = this.intro.lastIndexOf(n);
  44705. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  44706. return this.intro + lineStr;
  44707. }
  44708. slice(start = 0, end = this.original.length - this.offset) {
  44709. start = start + this.offset;
  44710. end = end + this.offset;
  44711. if (this.original.length !== 0) {
  44712. while (start < 0) start += this.original.length;
  44713. while (end < 0) end += this.original.length;
  44714. }
  44715. let result = '';
  44716. // find start chunk
  44717. let chunk = this.firstChunk;
  44718. while (chunk && (chunk.start > start || chunk.end <= start)) {
  44719. // found end chunk before start
  44720. if (chunk.start < end && chunk.end >= end) {
  44721. return result;
  44722. }
  44723. chunk = chunk.next;
  44724. }
  44725. if (chunk && chunk.edited && chunk.start !== start)
  44726. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  44727. const startChunk = chunk;
  44728. while (chunk) {
  44729. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  44730. result += chunk.intro;
  44731. }
  44732. const containsEnd = chunk.start < end && chunk.end >= end;
  44733. if (containsEnd && chunk.edited && chunk.end !== end)
  44734. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  44735. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  44736. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  44737. result += chunk.content.slice(sliceStart, sliceEnd);
  44738. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  44739. result += chunk.outro;
  44740. }
  44741. if (containsEnd) {
  44742. break;
  44743. }
  44744. chunk = chunk.next;
  44745. }
  44746. return result;
  44747. }
  44748. // TODO deprecate this? not really very useful
  44749. snip(start, end) {
  44750. const clone = this.clone();
  44751. clone.remove(0, start);
  44752. clone.remove(end, clone.original.length);
  44753. return clone;
  44754. }
  44755. _split(index) {
  44756. if (this.byStart[index] || this.byEnd[index]) return;
  44757. let chunk = this.lastSearchedChunk;
  44758. let previousChunk = chunk;
  44759. const searchForward = index > chunk.end;
  44760. while (chunk) {
  44761. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  44762. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  44763. // Prevent infinite loop (e.g. via empty chunks, where start === end)
  44764. if (chunk === previousChunk) return;
  44765. previousChunk = chunk;
  44766. }
  44767. }
  44768. _splitChunk(chunk, index) {
  44769. if (chunk.edited && chunk.content.length) {
  44770. // zero-length edited chunks are a special case (overlapping replacements)
  44771. const loc = getLocator(this.original)(index);
  44772. throw new Error(
  44773. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
  44774. );
  44775. }
  44776. const newChunk = chunk.split(index);
  44777. this.byEnd[index] = chunk;
  44778. this.byStart[index] = newChunk;
  44779. this.byEnd[newChunk.end] = newChunk;
  44780. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  44781. this.lastSearchedChunk = chunk;
  44782. return true;
  44783. }
  44784. toString() {
  44785. let str = this.intro;
  44786. let chunk = this.firstChunk;
  44787. while (chunk) {
  44788. str += chunk.toString();
  44789. chunk = chunk.next;
  44790. }
  44791. return str + this.outro;
  44792. }
  44793. isEmpty() {
  44794. let chunk = this.firstChunk;
  44795. do {
  44796. if (
  44797. (chunk.intro.length && chunk.intro.trim()) ||
  44798. (chunk.content.length && chunk.content.trim()) ||
  44799. (chunk.outro.length && chunk.outro.trim())
  44800. )
  44801. return false;
  44802. } while ((chunk = chunk.next));
  44803. return true;
  44804. }
  44805. length() {
  44806. let chunk = this.firstChunk;
  44807. let length = 0;
  44808. do {
  44809. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  44810. } while ((chunk = chunk.next));
  44811. return length;
  44812. }
  44813. trimLines() {
  44814. return this.trim('[\\r\\n]');
  44815. }
  44816. trim(charType) {
  44817. return this.trimStart(charType).trimEnd(charType);
  44818. }
  44819. trimEndAborted(charType) {
  44820. const rx = new RegExp((charType || '\\s') + '+$');
  44821. this.outro = this.outro.replace(rx, '');
  44822. if (this.outro.length) return true;
  44823. let chunk = this.lastChunk;
  44824. do {
  44825. const end = chunk.end;
  44826. const aborted = chunk.trimEnd(rx);
  44827. // if chunk was trimmed, we have a new lastChunk
  44828. if (chunk.end !== end) {
  44829. if (this.lastChunk === chunk) {
  44830. this.lastChunk = chunk.next;
  44831. }
  44832. this.byEnd[chunk.end] = chunk;
  44833. this.byStart[chunk.next.start] = chunk.next;
  44834. this.byEnd[chunk.next.end] = chunk.next;
  44835. }
  44836. if (aborted) return true;
  44837. chunk = chunk.previous;
  44838. } while (chunk);
  44839. return false;
  44840. }
  44841. trimEnd(charType) {
  44842. this.trimEndAborted(charType);
  44843. return this;
  44844. }
  44845. trimStartAborted(charType) {
  44846. const rx = new RegExp('^' + (charType || '\\s') + '+');
  44847. this.intro = this.intro.replace(rx, '');
  44848. if (this.intro.length) return true;
  44849. let chunk = this.firstChunk;
  44850. do {
  44851. const end = chunk.end;
  44852. const aborted = chunk.trimStart(rx);
  44853. if (chunk.end !== end) {
  44854. // special case...
  44855. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  44856. this.byEnd[chunk.end] = chunk;
  44857. this.byStart[chunk.next.start] = chunk.next;
  44858. this.byEnd[chunk.next.end] = chunk.next;
  44859. }
  44860. if (aborted) return true;
  44861. chunk = chunk.next;
  44862. } while (chunk);
  44863. return false;
  44864. }
  44865. trimStart(charType) {
  44866. this.trimStartAborted(charType);
  44867. return this;
  44868. }
  44869. hasChanged() {
  44870. return this.original !== this.toString();
  44871. }
  44872. _replaceRegexp(searchValue, replacement) {
  44873. function getReplacement(match, str) {
  44874. if (typeof replacement === 'string') {
  44875. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  44876. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  44877. if (i === '$') return '$';
  44878. if (i === '&') return match[0];
  44879. const num = +i;
  44880. if (num < match.length) return match[+i];
  44881. return `$${i}`;
  44882. });
  44883. } else {
  44884. return replacement(...match, match.index, str, match.groups);
  44885. }
  44886. }
  44887. function matchAll(re, str) {
  44888. let match;
  44889. const matches = [];
  44890. while ((match = re.exec(str))) {
  44891. matches.push(match);
  44892. }
  44893. return matches;
  44894. }
  44895. if (searchValue.global) {
  44896. const matches = matchAll(searchValue, this.original);
  44897. matches.forEach((match) => {
  44898. if (match.index != null) {
  44899. const replacement = getReplacement(match, this.original);
  44900. if (replacement !== match[0]) {
  44901. this.overwrite(match.index, match.index + match[0].length, replacement);
  44902. }
  44903. }
  44904. });
  44905. } else {
  44906. const match = this.original.match(searchValue);
  44907. if (match && match.index != null) {
  44908. const replacement = getReplacement(match, this.original);
  44909. if (replacement !== match[0]) {
  44910. this.overwrite(match.index, match.index + match[0].length, replacement);
  44911. }
  44912. }
  44913. }
  44914. return this;
  44915. }
  44916. _replaceString(string, replacement) {
  44917. const { original } = this;
  44918. const index = original.indexOf(string);
  44919. if (index !== -1) {
  44920. if (typeof replacement === 'function') {
  44921. replacement = replacement(string, index, original);
  44922. }
  44923. if (string !== replacement) {
  44924. this.overwrite(index, index + string.length, replacement);
  44925. }
  44926. }
  44927. return this;
  44928. }
  44929. replace(searchValue, replacement) {
  44930. if (typeof searchValue === 'string') {
  44931. return this._replaceString(searchValue, replacement);
  44932. }
  44933. return this._replaceRegexp(searchValue, replacement);
  44934. }
  44935. _replaceAllString(string, replacement) {
  44936. const { original } = this;
  44937. const stringLength = string.length;
  44938. for (
  44939. let index = original.indexOf(string);
  44940. index !== -1;
  44941. index = original.indexOf(string, index + stringLength)
  44942. ) {
  44943. const previous = original.slice(index, index + stringLength);
  44944. let _replacement = replacement;
  44945. if (typeof replacement === 'function') {
  44946. _replacement = replacement(previous, index, original);
  44947. }
  44948. if (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement);
  44949. }
  44950. return this;
  44951. }
  44952. replaceAll(searchValue, replacement) {
  44953. if (typeof searchValue === 'string') {
  44954. return this._replaceAllString(searchValue, replacement);
  44955. }
  44956. if (!searchValue.global) {
  44957. throw new TypeError(
  44958. 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
  44959. );
  44960. }
  44961. return this._replaceRegexp(searchValue, replacement);
  44962. }
  44963. }
  44964. var _a, _b;
  44965. class ScriptCompileContext {
  44966. constructor(descriptor, options) {
  44967. this.descriptor = descriptor;
  44968. this.options = options;
  44969. this.isCE = false;
  44970. this.source = this.descriptor.source;
  44971. this.filename = this.descriptor.filename;
  44972. this.s = new MagicString(this.source);
  44973. this.startOffset = (_a = this.descriptor.scriptSetup) == null ? void 0 : _a.loc.start.offset;
  44974. this.endOffset = (_b = this.descriptor.scriptSetup) == null ? void 0 : _b.loc.end.offset;
  44975. this.userImports = /* @__PURE__ */ Object.create(null);
  44976. // macros presence check
  44977. this.hasDefinePropsCall = false;
  44978. this.hasDefineEmitCall = false;
  44979. this.hasDefineExposeCall = false;
  44980. this.hasDefaultExportName = false;
  44981. this.hasDefaultExportRender = false;
  44982. this.hasDefineOptionsCall = false;
  44983. this.hasDefineSlotsCall = false;
  44984. this.hasDefineModelCall = false;
  44985. this.propsDestructuredBindings = /* @__PURE__ */ Object.create(null);
  44986. // defineModel
  44987. this.modelDecls = /* @__PURE__ */ Object.create(null);
  44988. // codegen
  44989. this.bindingMetadata = {};
  44990. this.helperImports = /* @__PURE__ */ new Set();
  44991. const { script, scriptSetup } = descriptor;
  44992. const scriptLang = script && script.lang;
  44993. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  44994. this.isJS = isJS(scriptLang, scriptSetupLang);
  44995. this.isTS = isTS(scriptLang, scriptSetupLang);
  44996. const customElement = options.customElement;
  44997. const filename = this.descriptor.filename;
  44998. if (customElement) {
  44999. this.isCE = typeof customElement === "boolean" ? customElement : customElement(filename);
  45000. }
  45001. const plugins = resolveParserPlugins(
  45002. scriptLang || scriptSetupLang,
  45003. options.babelParserPlugins
  45004. );
  45005. function parse(input, offset) {
  45006. try {
  45007. return libExports.parse(input, {
  45008. plugins,
  45009. sourceType: "module"
  45010. }).program;
  45011. } catch (e) {
  45012. e.message = `[vue/compiler-sfc] ${e.message}
  45013. ${descriptor.filename}
  45014. ${generateCodeFrame(
  45015. descriptor.source,
  45016. e.pos + offset,
  45017. e.pos + offset + 1
  45018. )}`;
  45019. throw e;
  45020. }
  45021. }
  45022. this.scriptAst = descriptor.script && parse(descriptor.script.content, descriptor.script.loc.start.offset);
  45023. this.scriptSetupAst = descriptor.scriptSetup && parse(descriptor.scriptSetup.content, this.startOffset);
  45024. }
  45025. helper(key) {
  45026. this.helperImports.add(key);
  45027. return `_${key}`;
  45028. }
  45029. getString(node, scriptSetup = true) {
  45030. const block = scriptSetup ? this.descriptor.scriptSetup : this.descriptor.script;
  45031. return block.content.slice(node.start, node.end);
  45032. }
  45033. warn(msg, node, scope) {
  45034. warn(generateError(msg, node, this, scope));
  45035. }
  45036. error(msg, node, scope) {
  45037. throw new Error(
  45038. `[@vue/compiler-sfc] ${generateError(msg, node, this, scope)}`
  45039. );
  45040. }
  45041. }
  45042. function generateError(msg, node, ctx, scope) {
  45043. const offset = scope ? scope.offset : ctx.startOffset;
  45044. return `${msg}
  45045. ${(scope || ctx.descriptor).filename}
  45046. ${generateCodeFrame(
  45047. (scope || ctx.descriptor).source,
  45048. node.start + offset,
  45049. node.end + offset
  45050. )}`;
  45051. }
  45052. function resolveParserPlugins(lang, userPlugins, dts = false) {
  45053. const plugins = [];
  45054. if (!userPlugins || !userPlugins.some(
  45055. (p) => p === "importAssertions" || p === "importAttributes" || isArray$3(p) && p[0] === "importAttributes"
  45056. )) {
  45057. plugins.push("importAttributes");
  45058. }
  45059. if (lang === "jsx" || lang === "tsx" || lang === "mtsx") {
  45060. plugins.push("jsx");
  45061. } else if (userPlugins) {
  45062. userPlugins = userPlugins.filter((p) => p !== "jsx");
  45063. }
  45064. if (lang === "ts" || lang === "mts" || lang === "tsx" || lang === "cts" || lang === "mtsx") {
  45065. plugins.push(["typescript", { dts }], "explicitResourceManagement");
  45066. if (!userPlugins || !userPlugins.includes("decorators")) {
  45067. plugins.push("decorators-legacy");
  45068. }
  45069. }
  45070. if (userPlugins) {
  45071. plugins.push(...userPlugins);
  45072. }
  45073. return plugins;
  45074. }
  45075. function rewriteDefault(input, as, parserPlugins) {
  45076. const ast = libExports.parse(input, {
  45077. sourceType: "module",
  45078. plugins: resolveParserPlugins("js", parserPlugins)
  45079. }).program.body;
  45080. const s = new MagicString(input);
  45081. rewriteDefaultAST(ast, s, as);
  45082. return s.toString();
  45083. }
  45084. function rewriteDefaultAST(ast, s, as) {
  45085. if (!hasDefaultExport(ast)) {
  45086. s.append(`
  45087. const ${as} = {}`);
  45088. return;
  45089. }
  45090. ast.forEach((node) => {
  45091. if (node.type === "ExportDefaultDeclaration") {
  45092. if (node.declaration.type === "ClassDeclaration" && node.declaration.id) {
  45093. const start = node.declaration.decorators && node.declaration.decorators.length > 0 ? node.declaration.decorators[node.declaration.decorators.length - 1].end : node.start;
  45094. s.overwrite(start, node.declaration.id.start, ` class `);
  45095. s.append(`
  45096. const ${as} = ${node.declaration.id.name}`);
  45097. } else {
  45098. s.overwrite(node.start, node.declaration.start, `const ${as} = `);
  45099. }
  45100. } else if (node.type === "ExportNamedDeclaration") {
  45101. for (const specifier of node.specifiers) {
  45102. if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier" && specifier.exported.name === "default") {
  45103. if (node.source) {
  45104. if (specifier.local.name === "default") {
  45105. s.prepend(
  45106. `import { default as __VUE_DEFAULT__ } from '${node.source.value}'
  45107. `
  45108. );
  45109. const end2 = specifierEnd(s, specifier.local.end, node.end);
  45110. s.remove(specifier.start, end2);
  45111. s.append(`
  45112. const ${as} = __VUE_DEFAULT__`);
  45113. continue;
  45114. } else {
  45115. s.prepend(
  45116. `import { ${s.slice(
  45117. specifier.local.start,
  45118. specifier.local.end
  45119. )} as __VUE_DEFAULT__ } from '${node.source.value}'
  45120. `
  45121. );
  45122. const end2 = specifierEnd(s, specifier.exported.end, node.end);
  45123. s.remove(specifier.start, end2);
  45124. s.append(`
  45125. const ${as} = __VUE_DEFAULT__`);
  45126. continue;
  45127. }
  45128. }
  45129. const end = specifierEnd(s, specifier.end, node.end);
  45130. s.remove(specifier.start, end);
  45131. s.append(`
  45132. const ${as} = ${specifier.local.name}`);
  45133. }
  45134. }
  45135. }
  45136. });
  45137. }
  45138. function hasDefaultExport(ast) {
  45139. for (const stmt of ast) {
  45140. if (stmt.type === "ExportDefaultDeclaration") {
  45141. return true;
  45142. } else if (stmt.type === "ExportNamedDeclaration" && stmt.specifiers.some(
  45143. (spec) => spec.exported.name === "default"
  45144. )) {
  45145. return true;
  45146. }
  45147. }
  45148. return false;
  45149. }
  45150. function specifierEnd(s, end, nodeEnd) {
  45151. let hasCommas = false;
  45152. let oldEnd = end;
  45153. while (end < nodeEnd) {
  45154. if (/\s/.test(s.slice(end, end + 1))) {
  45155. end++;
  45156. } else if (s.slice(end, end + 1) === ",") {
  45157. end++;
  45158. hasCommas = true;
  45159. break;
  45160. } else if (s.slice(end, end + 1) === "}") {
  45161. break;
  45162. }
  45163. }
  45164. return hasCommas ? end : oldEnd;
  45165. }
  45166. var __defProp$3 = Object.defineProperty;
  45167. var __defProps$2 = Object.defineProperties;
  45168. var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
  45169. var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
  45170. var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
  45171. var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
  45172. var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  45173. var __spreadValues$3 = (a, b) => {
  45174. for (var prop in b || (b = {}))
  45175. if (__hasOwnProp$3.call(b, prop))
  45176. __defNormalProp$3(a, prop, b[prop]);
  45177. if (__getOwnPropSymbols$3)
  45178. for (var prop of __getOwnPropSymbols$3(b)) {
  45179. if (__propIsEnum$3.call(b, prop))
  45180. __defNormalProp$3(a, prop, b[prop]);
  45181. }
  45182. return a;
  45183. };
  45184. var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
  45185. const normalScriptDefaultVar = `__default__`;
  45186. function processNormalScript(ctx, scopeId) {
  45187. var _a;
  45188. const script = ctx.descriptor.script;
  45189. try {
  45190. let content = script.content;
  45191. let map = script.map;
  45192. const scriptAst = ctx.scriptAst;
  45193. const bindings = analyzeScriptBindings(scriptAst.body);
  45194. const { cssVars } = ctx.descriptor;
  45195. const { genDefaultAs, isProd } = ctx.options;
  45196. if (cssVars.length || genDefaultAs) {
  45197. const defaultVar = genDefaultAs || normalScriptDefaultVar;
  45198. const s = new MagicString(content);
  45199. rewriteDefaultAST(scriptAst.body, s, defaultVar);
  45200. content = s.toString();
  45201. if (cssVars.length && !((_a = ctx.options.templateOptions) == null ? void 0 : _a.ssr)) {
  45202. content += genNormalScriptCssVarsCode(
  45203. cssVars,
  45204. bindings,
  45205. scopeId,
  45206. !!isProd,
  45207. defaultVar
  45208. );
  45209. }
  45210. if (!genDefaultAs) {
  45211. content += `
  45212. export default ${defaultVar}`;
  45213. }
  45214. }
  45215. return __spreadProps$2(__spreadValues$3({}, script), {
  45216. content,
  45217. map,
  45218. bindings,
  45219. scriptAst: scriptAst.body
  45220. });
  45221. } catch (e) {
  45222. return script;
  45223. }
  45224. }
  45225. var __defProp$2 = Object.defineProperty;
  45226. var __defProps$1 = Object.defineProperties;
  45227. var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
  45228. var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
  45229. var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
  45230. var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
  45231. var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  45232. var __spreadValues$2 = (a, b) => {
  45233. for (var prop in b || (b = {}))
  45234. if (__hasOwnProp$2.call(b, prop))
  45235. __defNormalProp$2(a, prop, b[prop]);
  45236. if (__getOwnPropSymbols$2)
  45237. for (var prop of __getOwnPropSymbols$2(b)) {
  45238. if (__propIsEnum$2.call(b, prop))
  45239. __defNormalProp$2(a, prop, b[prop]);
  45240. }
  45241. return a;
  45242. };
  45243. var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
  45244. class TypeScope {
  45245. constructor(filename, source, offset = 0, imports = /* @__PURE__ */ Object.create(null), types = /* @__PURE__ */ Object.create(null), declares = /* @__PURE__ */ Object.create(null)) {
  45246. this.filename = filename;
  45247. this.source = source;
  45248. this.offset = offset;
  45249. this.imports = imports;
  45250. this.types = types;
  45251. this.declares = declares;
  45252. this.isGenericScope = false;
  45253. this.resolvedImportSources = /* @__PURE__ */ Object.create(null);
  45254. this.exportedTypes = /* @__PURE__ */ Object.create(null);
  45255. this.exportedDeclares = /* @__PURE__ */ Object.create(null);
  45256. }
  45257. }
  45258. function recordScopeDep(ctx, scope) {
  45259. if (scope && scope.filename !== ctx.filename) {
  45260. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(scope.filename);
  45261. }
  45262. }
  45263. function recordResolvedElementDeps(ctx, { props }) {
  45264. for (const key in props) {
  45265. recordScopeDep(ctx, props[key]._ownerScope);
  45266. }
  45267. }
  45268. function resolveTypeElements(ctx, node, scope, typeParameters) {
  45269. const canCache = !typeParameters;
  45270. if (canCache && node._resolvedElements) {
  45271. recordResolvedElementDeps(ctx, node._resolvedElements);
  45272. return node._resolvedElements;
  45273. }
  45274. const resolved = innerResolveTypeElements(
  45275. ctx,
  45276. node,
  45277. node._ownerScope || scope || ctxToScope(ctx),
  45278. typeParameters
  45279. );
  45280. return canCache ? node._resolvedElements = resolved : resolved;
  45281. }
  45282. function innerResolveTypeElements(ctx, node, scope, typeParameters) {
  45283. var _a, _b;
  45284. if (node.leadingComments && node.leadingComments.some((c) => c.value.includes("@vue-ignore"))) {
  45285. return { props: {} };
  45286. }
  45287. switch (node.type) {
  45288. case "TSTypeLiteral":
  45289. return typeElementsToMap(ctx, node.members, scope, typeParameters);
  45290. case "TSInterfaceDeclaration":
  45291. return resolveInterfaceMembers(ctx, node, scope, typeParameters);
  45292. case "TSTypeAliasDeclaration":
  45293. case "TSTypeAnnotation":
  45294. case "TSParenthesizedType":
  45295. return resolveTypeElements(
  45296. ctx,
  45297. node.typeAnnotation,
  45298. scope,
  45299. typeParameters
  45300. );
  45301. case "TSFunctionType": {
  45302. return { props: {}, calls: [node] };
  45303. }
  45304. case "TSUnionType":
  45305. case "TSIntersectionType":
  45306. return mergeElements(
  45307. node.types.map((t) => resolveTypeElements(ctx, t, scope, typeParameters)),
  45308. node.type
  45309. );
  45310. case "TSMappedType":
  45311. return resolveMappedType(ctx, node, scope, typeParameters);
  45312. case "TSIndexedAccessType": {
  45313. const types = resolveIndexType(ctx, node, scope);
  45314. return mergeElements(
  45315. types.map((t) => resolveTypeElements(ctx, t, t._ownerScope)),
  45316. "TSUnionType"
  45317. );
  45318. }
  45319. case "TSExpressionWithTypeArguments":
  45320. // referenced by interface extends
  45321. case "TSTypeReference": {
  45322. const typeName = getReferenceName(node);
  45323. if ((typeName === "ExtractPropTypes" || typeName === "ExtractPublicPropTypes") && node.typeParameters && ((_a = scope.imports[typeName]) == null ? void 0 : _a.source) === "vue") {
  45324. return resolveExtractPropTypes(
  45325. resolveTypeElements(
  45326. ctx,
  45327. node.typeParameters.params[0],
  45328. scope,
  45329. typeParameters
  45330. ),
  45331. scope
  45332. );
  45333. }
  45334. const resolved = resolveTypeReference(ctx, node, scope);
  45335. if (resolved) {
  45336. let typeParams;
  45337. if ((resolved.type === "TSTypeAliasDeclaration" || resolved.type === "TSInterfaceDeclaration") && resolved.typeParameters && node.typeParameters) {
  45338. typeParams = /* @__PURE__ */ Object.create(null);
  45339. resolved.typeParameters.params.forEach((p, i) => {
  45340. let param = typeParameters && typeParameters[p.name];
  45341. if (!param) param = node.typeParameters.params[i];
  45342. typeParams[p.name] = param;
  45343. });
  45344. }
  45345. return resolveTypeElements(
  45346. ctx,
  45347. resolved,
  45348. resolved._ownerScope,
  45349. typeParams
  45350. );
  45351. } else {
  45352. if (typeof typeName === "string") {
  45353. if (typeParameters && typeParameters[typeName]) {
  45354. return resolveTypeElements(
  45355. ctx,
  45356. typeParameters[typeName],
  45357. scope,
  45358. typeParameters
  45359. );
  45360. }
  45361. if (
  45362. // @ts-expect-error
  45363. SupportedBuiltinsSet.has(typeName)
  45364. ) {
  45365. return resolveBuiltin(
  45366. ctx,
  45367. node,
  45368. typeName,
  45369. scope,
  45370. typeParameters
  45371. );
  45372. } else if (typeName === "ReturnType" && node.typeParameters) {
  45373. const ret = resolveReturnType(
  45374. ctx,
  45375. node.typeParameters.params[0],
  45376. scope
  45377. );
  45378. if (ret) {
  45379. return resolveTypeElements(ctx, ret, scope);
  45380. }
  45381. }
  45382. }
  45383. return ctx.error(
  45384. `Unresolvable type reference or unsupported built-in utility type`,
  45385. node,
  45386. scope
  45387. );
  45388. }
  45389. }
  45390. case "TSImportType": {
  45391. if (getId(node.argument) === "vue" && ((_b = node.qualifier) == null ? void 0 : _b.type) === "Identifier" && node.qualifier.name === "ExtractPropTypes" && node.typeParameters) {
  45392. return resolveExtractPropTypes(
  45393. resolveTypeElements(ctx, node.typeParameters.params[0], scope),
  45394. scope
  45395. );
  45396. }
  45397. const sourceScope = importSourceToScope(
  45398. ctx,
  45399. node.argument,
  45400. scope,
  45401. node.argument.value
  45402. );
  45403. const resolved = resolveTypeReference(ctx, node, sourceScope);
  45404. if (resolved) {
  45405. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  45406. }
  45407. break;
  45408. }
  45409. case "TSTypeQuery":
  45410. {
  45411. const resolved = resolveTypeReference(ctx, node, scope);
  45412. if (resolved) {
  45413. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  45414. }
  45415. }
  45416. break;
  45417. }
  45418. return ctx.error(`Unresolvable type: ${node.type}`, node, scope);
  45419. }
  45420. function typeElementsToMap(ctx, elements, scope = ctxToScope(ctx), typeParameters) {
  45421. const res = { props: {} };
  45422. for (const e of elements) {
  45423. if (e.type === "TSPropertySignature" || e.type === "TSMethodSignature") {
  45424. if (typeParameters) {
  45425. scope = createChildScope(scope);
  45426. scope.isGenericScope = true;
  45427. Object.assign(scope.types, typeParameters);
  45428. }
  45429. e._ownerScope = scope;
  45430. const name = getStringLiteralKey(e);
  45431. if (name !== null) {
  45432. res.props[name] = e;
  45433. } else {
  45434. ctx.error(
  45435. `Unsupported computed key in type referenced by a macro`,
  45436. e.key,
  45437. scope
  45438. );
  45439. }
  45440. } else if (e.type === "TSCallSignatureDeclaration") {
  45441. (res.calls || (res.calls = [])).push(e);
  45442. }
  45443. }
  45444. return res;
  45445. }
  45446. function mergeElements(maps, type) {
  45447. if (maps.length === 1) return maps[0];
  45448. const res = { props: {} };
  45449. const { props: baseProps } = res;
  45450. for (const { props, calls } of maps) {
  45451. for (const key in props) {
  45452. if (!hasOwn(baseProps, key)) {
  45453. baseProps[key] = props[key];
  45454. } else {
  45455. baseProps[key] = createProperty(
  45456. baseProps[key].key,
  45457. {
  45458. type,
  45459. // @ts-expect-error
  45460. types: [baseProps[key], props[key]]
  45461. },
  45462. baseProps[key]._ownerScope,
  45463. baseProps[key].optional || props[key].optional
  45464. );
  45465. }
  45466. }
  45467. if (calls) {
  45468. (res.calls || (res.calls = [])).push(...calls);
  45469. }
  45470. }
  45471. return res;
  45472. }
  45473. function createProperty(key, typeAnnotation, scope, optional) {
  45474. return {
  45475. type: "TSPropertySignature",
  45476. key,
  45477. kind: "get",
  45478. optional,
  45479. typeAnnotation: {
  45480. type: "TSTypeAnnotation",
  45481. typeAnnotation
  45482. },
  45483. _ownerScope: scope
  45484. };
  45485. }
  45486. function resolveInterfaceMembers(ctx, node, scope, typeParameters) {
  45487. const base = typeElementsToMap(
  45488. ctx,
  45489. node.body.body,
  45490. node._ownerScope,
  45491. typeParameters
  45492. );
  45493. if (node.extends) {
  45494. for (const ext of node.extends) {
  45495. try {
  45496. const { props, calls } = resolveTypeElements(ctx, ext, scope);
  45497. for (const key in props) {
  45498. if (!hasOwn(base.props, key)) {
  45499. base.props[key] = props[key];
  45500. }
  45501. }
  45502. if (calls) {
  45503. ;
  45504. (base.calls || (base.calls = [])).push(...calls);
  45505. }
  45506. } catch (e) {
  45507. if (!ctx.silentOnExtendsFailure) {
  45508. ctx.error(
  45509. `Failed to resolve extends base type.
  45510. If this previously worked in 3.2, you can instruct the compiler to ignore this extend by adding /* @vue-ignore */ before it, for example:
  45511. interface Props extends /* @vue-ignore */ Base {}
  45512. Note: both in 3.2 or with the ignore, the properties in the base type are treated as fallthrough attrs at runtime.`,
  45513. ext,
  45514. scope
  45515. );
  45516. }
  45517. }
  45518. }
  45519. }
  45520. return base;
  45521. }
  45522. function resolveMappedType(ctx, node, scope, typeParameters) {
  45523. const res = { props: {} };
  45524. let keys;
  45525. if (node.nameType) {
  45526. const { name, constraint } = node.typeParameter;
  45527. scope = createChildScope(scope);
  45528. Object.assign(scope.types, __spreadProps$1(__spreadValues$2({}, typeParameters), { [name]: constraint }));
  45529. keys = resolveStringType(ctx, node.nameType, scope);
  45530. } else {
  45531. keys = resolveStringType(ctx, node.typeParameter.constraint, scope);
  45532. }
  45533. for (const key of keys) {
  45534. res.props[key] = createProperty(
  45535. {
  45536. type: "Identifier",
  45537. name: key
  45538. },
  45539. node.typeAnnotation,
  45540. scope,
  45541. !!node.optional
  45542. );
  45543. }
  45544. return res;
  45545. }
  45546. function resolveIndexType(ctx, node, scope) {
  45547. var _a, _b;
  45548. if (node.indexType.type === "TSNumberKeyword") {
  45549. return resolveArrayElementType(ctx, node.objectType, scope);
  45550. }
  45551. const { indexType, objectType } = node;
  45552. const types = [];
  45553. let keys;
  45554. let resolved;
  45555. if (indexType.type === "TSStringKeyword") {
  45556. resolved = resolveTypeElements(ctx, objectType, scope);
  45557. keys = Object.keys(resolved.props);
  45558. } else {
  45559. keys = resolveStringType(ctx, indexType, scope);
  45560. resolved = resolveTypeElements(ctx, objectType, scope);
  45561. }
  45562. for (const key of keys) {
  45563. const targetType = (_b = (_a = resolved.props[key]) == null ? void 0 : _a.typeAnnotation) == null ? void 0 : _b.typeAnnotation;
  45564. if (targetType) {
  45565. targetType._ownerScope = resolved.props[key]._ownerScope;
  45566. types.push(targetType);
  45567. }
  45568. }
  45569. return types;
  45570. }
  45571. function resolveArrayElementType(ctx, node, scope) {
  45572. if (node.type === "TSArrayType") {
  45573. return [node.elementType];
  45574. }
  45575. if (node.type === "TSTupleType") {
  45576. return node.elementTypes.map(
  45577. (t) => t.type === "TSNamedTupleMember" ? t.elementType : t
  45578. );
  45579. }
  45580. if (node.type === "TSTypeReference") {
  45581. if (getReferenceName(node) === "Array" && node.typeParameters) {
  45582. return node.typeParameters.params;
  45583. } else {
  45584. const resolved = resolveTypeReference(ctx, node, scope);
  45585. if (resolved) {
  45586. return resolveArrayElementType(ctx, resolved, scope);
  45587. }
  45588. }
  45589. }
  45590. return ctx.error(
  45591. "Failed to resolve element type from target type",
  45592. node,
  45593. scope
  45594. );
  45595. }
  45596. function resolveStringType(ctx, node, scope, typeParameters) {
  45597. switch (node.type) {
  45598. case "StringLiteral":
  45599. return [node.value];
  45600. case "TSLiteralType":
  45601. return resolveStringType(ctx, node.literal, scope, typeParameters);
  45602. case "TSUnionType":
  45603. return node.types.map((t) => resolveStringType(ctx, t, scope, typeParameters)).flat();
  45604. case "TemplateLiteral": {
  45605. return resolveTemplateKeys(ctx, node, scope);
  45606. }
  45607. case "TSTypeReference": {
  45608. const resolved = resolveTypeReference(ctx, node, scope);
  45609. if (resolved) {
  45610. return resolveStringType(ctx, resolved, scope, typeParameters);
  45611. }
  45612. if (node.typeName.type === "Identifier") {
  45613. const name = node.typeName.name;
  45614. if (typeParameters && typeParameters[name]) {
  45615. return resolveStringType(
  45616. ctx,
  45617. typeParameters[name],
  45618. scope,
  45619. typeParameters
  45620. );
  45621. }
  45622. const getParam = (index = 0) => resolveStringType(
  45623. ctx,
  45624. node.typeParameters.params[index],
  45625. scope,
  45626. typeParameters
  45627. );
  45628. switch (name) {
  45629. case "Extract":
  45630. return getParam(1);
  45631. case "Exclude": {
  45632. const excluded = getParam(1);
  45633. return getParam().filter((s) => !excluded.includes(s));
  45634. }
  45635. case "Uppercase":
  45636. return getParam().map((s) => s.toUpperCase());
  45637. case "Lowercase":
  45638. return getParam().map((s) => s.toLowerCase());
  45639. case "Capitalize":
  45640. return getParam().map(capitalize);
  45641. case "Uncapitalize":
  45642. return getParam().map((s) => s[0].toLowerCase() + s.slice(1));
  45643. default:
  45644. ctx.error(
  45645. "Unsupported type when resolving index type",
  45646. node.typeName,
  45647. scope
  45648. );
  45649. }
  45650. }
  45651. }
  45652. }
  45653. return ctx.error("Failed to resolve index type into finite keys", node, scope);
  45654. }
  45655. function resolveTemplateKeys(ctx, node, scope) {
  45656. if (!node.expressions.length) {
  45657. return [node.quasis[0].value.raw];
  45658. }
  45659. const res = [];
  45660. const e = node.expressions[0];
  45661. const q = node.quasis[0];
  45662. const leading = q ? q.value.raw : ``;
  45663. const resolved = resolveStringType(ctx, e, scope);
  45664. const restResolved = resolveTemplateKeys(
  45665. ctx,
  45666. __spreadProps$1(__spreadValues$2({}, node), {
  45667. expressions: node.expressions.slice(1),
  45668. quasis: q ? node.quasis.slice(1) : node.quasis
  45669. }),
  45670. scope
  45671. );
  45672. for (const r of resolved) {
  45673. for (const rr of restResolved) {
  45674. res.push(leading + r + rr);
  45675. }
  45676. }
  45677. return res;
  45678. }
  45679. const SupportedBuiltinsSet = /* @__PURE__ */ new Set([
  45680. "Partial",
  45681. "Required",
  45682. "Readonly",
  45683. "Pick",
  45684. "Omit"
  45685. ]);
  45686. function resolveBuiltin(ctx, node, name, scope, typeParameters) {
  45687. const t = resolveTypeElements(
  45688. ctx,
  45689. node.typeParameters.params[0],
  45690. scope,
  45691. typeParameters
  45692. );
  45693. switch (name) {
  45694. case "Partial": {
  45695. const res2 = { props: {}, calls: t.calls };
  45696. Object.keys(t.props).forEach((key) => {
  45697. res2.props[key] = __spreadProps$1(__spreadValues$2({}, t.props[key]), { optional: true });
  45698. });
  45699. return res2;
  45700. }
  45701. case "Required": {
  45702. const res2 = { props: {}, calls: t.calls };
  45703. Object.keys(t.props).forEach((key) => {
  45704. res2.props[key] = __spreadProps$1(__spreadValues$2({}, t.props[key]), { optional: false });
  45705. });
  45706. return res2;
  45707. }
  45708. case "Readonly":
  45709. return t;
  45710. case "Pick": {
  45711. const picked = resolveStringType(
  45712. ctx,
  45713. node.typeParameters.params[1],
  45714. scope,
  45715. typeParameters
  45716. );
  45717. const res2 = { props: {}, calls: t.calls };
  45718. for (const key of picked) {
  45719. res2.props[key] = t.props[key];
  45720. }
  45721. return res2;
  45722. }
  45723. case "Omit":
  45724. const omitted = resolveStringType(
  45725. ctx,
  45726. node.typeParameters.params[1],
  45727. scope,
  45728. typeParameters
  45729. );
  45730. const res = { props: {}, calls: t.calls };
  45731. for (const key in t.props) {
  45732. if (!omitted.includes(key)) {
  45733. res.props[key] = t.props[key];
  45734. }
  45735. }
  45736. return res;
  45737. }
  45738. }
  45739. function resolveTypeReference(ctx, node, scope, name, onlyExported = false) {
  45740. const canCache = !(scope == null ? void 0 : scope.isGenericScope);
  45741. if (canCache && node._resolvedReference) {
  45742. recordScopeDep(ctx, node._resolvedReference._ownerScope);
  45743. return node._resolvedReference;
  45744. }
  45745. const resolved = innerResolveTypeReference(
  45746. ctx,
  45747. scope || ctxToScope(ctx),
  45748. name || getReferenceName(node),
  45749. node,
  45750. onlyExported
  45751. );
  45752. return canCache ? node._resolvedReference = resolved : resolved;
  45753. }
  45754. function innerResolveTypeReference(ctx, scope, name, node, onlyExported) {
  45755. if (typeof name === "string") {
  45756. if (scope.imports[name]) {
  45757. return resolveTypeFromImport(ctx, node, name, scope);
  45758. } else {
  45759. const lookupSource = node.type === "TSTypeQuery" ? onlyExported ? scope.exportedDeclares : scope.declares : onlyExported ? scope.exportedTypes : scope.types;
  45760. if (lookupSource[name]) {
  45761. return lookupSource[name];
  45762. } else {
  45763. const globalScopes = resolveGlobalScope(ctx);
  45764. if (globalScopes) {
  45765. for (const s of globalScopes) {
  45766. const src = node.type === "TSTypeQuery" ? s.declares : s.types;
  45767. if (src[name]) {
  45768. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(s.filename);
  45769. const resolved = src[name];
  45770. if (resolved._ownerScope && resolved._ownerScope !== s) {
  45771. ctx.deps.add(resolved._ownerScope.filename);
  45772. }
  45773. return resolved;
  45774. }
  45775. }
  45776. }
  45777. }
  45778. }
  45779. } else {
  45780. let ns = innerResolveTypeReference(ctx, scope, name[0], node, onlyExported);
  45781. if (ns) {
  45782. if (ns.type !== "TSModuleDeclaration") {
  45783. ns = ns._ns;
  45784. }
  45785. if (ns) {
  45786. const childScope = moduleDeclToScope(ctx, ns, ns._ownerScope || scope);
  45787. return innerResolveTypeReference(
  45788. ctx,
  45789. childScope,
  45790. name.length > 2 ? name.slice(1) : name[name.length - 1],
  45791. node,
  45792. !ns.declare
  45793. );
  45794. }
  45795. }
  45796. }
  45797. }
  45798. function getReferenceName(node) {
  45799. const ref = node.type === "TSTypeReference" ? node.typeName : node.type === "TSExpressionWithTypeArguments" ? node.expression : node.type === "TSImportType" ? node.qualifier : node.exprName;
  45800. if ((ref == null ? void 0 : ref.type) === "Identifier") {
  45801. return ref.name;
  45802. } else if ((ref == null ? void 0 : ref.type) === "TSQualifiedName") {
  45803. return qualifiedNameToPath(ref);
  45804. } else {
  45805. return "default";
  45806. }
  45807. }
  45808. function qualifiedNameToPath(node) {
  45809. if (node.type === "Identifier") {
  45810. return [node.name];
  45811. } else {
  45812. return [...qualifiedNameToPath(node.left), node.right.name];
  45813. }
  45814. }
  45815. function resolveGlobalScope(ctx) {
  45816. if (ctx.options.globalTypeFiles) {
  45817. const fs = resolveFS(ctx);
  45818. if (!fs) {
  45819. throw new Error("[vue/compiler-sfc] globalTypeFiles requires fs access.");
  45820. }
  45821. return ctx.options.globalTypeFiles.map(
  45822. (file) => fileToScope(ctx, normalizePath(file), true)
  45823. );
  45824. }
  45825. }
  45826. let ts;
  45827. let loadTS;
  45828. function registerTS(_loadTS) {
  45829. loadTS = () => {
  45830. try {
  45831. return _loadTS();
  45832. } catch (err) {
  45833. if (typeof err.message === "string" && err.message.includes("Cannot find module")) {
  45834. throw new Error(
  45835. 'Failed to load TypeScript, which is required for resolving imported types. Please make sure "TypeScript" is installed as a project dependency.'
  45836. );
  45837. } else {
  45838. throw new Error(
  45839. "Failed to load TypeScript for resolving imported types."
  45840. );
  45841. }
  45842. }
  45843. };
  45844. }
  45845. function resolveFS(ctx) {
  45846. if (ctx.fs) {
  45847. return ctx.fs;
  45848. }
  45849. if (!ts && loadTS) {
  45850. ts = loadTS();
  45851. }
  45852. const fs = ctx.options.fs || (ts == null ? void 0 : ts.sys);
  45853. if (!fs) {
  45854. return;
  45855. }
  45856. return ctx.fs = {
  45857. fileExists(file) {
  45858. if (file.endsWith(".vue.ts") && !file.endsWith(".d.vue.ts")) {
  45859. file = file.replace(/\.ts$/, "");
  45860. }
  45861. return fs.fileExists(file);
  45862. },
  45863. readFile(file) {
  45864. if (file.endsWith(".vue.ts") && !file.endsWith(".d.vue.ts")) {
  45865. file = file.replace(/\.ts$/, "");
  45866. }
  45867. return fs.readFile(file);
  45868. },
  45869. realpath: fs.realpath
  45870. };
  45871. }
  45872. function resolveTypeFromImport(ctx, node, name, scope) {
  45873. const { source, imported } = scope.imports[name];
  45874. const sourceScope = importSourceToScope(ctx, node, scope, source);
  45875. return resolveTypeReference(ctx, node, sourceScope, imported, true);
  45876. }
  45877. function importSourceToScope(ctx, node, scope, source, trackDep = true) {
  45878. let fs;
  45879. try {
  45880. fs = resolveFS(ctx);
  45881. } catch (err) {
  45882. return ctx.error(err.message, node, scope);
  45883. }
  45884. if (!fs) {
  45885. return ctx.error(
  45886. `No fs option provided to \`compileScript\` in non-Node environment. File system access is required for resolving imported types.`,
  45887. node,
  45888. scope
  45889. );
  45890. }
  45891. let resolved = scope.resolvedImportSources[source];
  45892. if (!resolved) {
  45893. if (source.startsWith("..")) {
  45894. const osSpecificJoinFn = joinPaths;
  45895. const filename = osSpecificJoinFn(dirname(scope.filename), source);
  45896. resolved = resolveExt(filename, fs);
  45897. } else if (source[0] === ".") {
  45898. const filename = joinPaths(dirname(scope.filename), source);
  45899. resolved = resolveExt(filename, fs);
  45900. } else {
  45901. {
  45902. return ctx.error(
  45903. `Type import from non-relative sources is not supported in the browser build.`,
  45904. node,
  45905. scope
  45906. );
  45907. }
  45908. }
  45909. if (!resolved && source[0] === "." && false) {
  45910. if (!ts) {
  45911. if (loadTS) ts = loadTS();
  45912. }
  45913. if (ts) {
  45914. resolved = resolveWithTS(scope.filename);
  45915. }
  45916. }
  45917. if (resolved) {
  45918. resolved = scope.resolvedImportSources[source] = normalizePath(resolved);
  45919. }
  45920. }
  45921. if (resolved) {
  45922. if (trackDep) {
  45923. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(resolved);
  45924. }
  45925. return fileToScope(ctx, resolved);
  45926. } else {
  45927. return ctx.error(
  45928. `Failed to resolve import source ${JSON.stringify(source)}.`,
  45929. node,
  45930. scope
  45931. );
  45932. }
  45933. }
  45934. function resolveExt(filename, fs) {
  45935. let moduleType = "u";
  45936. if (filename.endsWith(".mjs")) {
  45937. moduleType = "m";
  45938. } else if (filename.endsWith(".cjs")) {
  45939. moduleType = "c";
  45940. }
  45941. filename = filename.replace(/\.[cm]?jsx?$/, "");
  45942. const tryResolve = (filename2) => {
  45943. if (fs.fileExists(filename2)) return filename2;
  45944. };
  45945. const resolveTs = () => tryResolve(filename + `.ts`) || tryResolve(filename + `.tsx`) || tryResolve(filename + `.d.ts`);
  45946. const resolveMts = () => tryResolve(filename + `.mts`) || tryResolve(filename + `.d.mts`);
  45947. const resolveCts = () => tryResolve(filename + `.cts`) || tryResolve(filename + `.d.cts`);
  45948. return tryResolve(filename) || // For explicit .mjs/.cjs imports, prefer .mts/.cts declarations first.
  45949. (moduleType === "m" ? resolveMts() || resolveTs() : moduleType === "c" ? resolveCts() || resolveTs() : resolveTs() || resolveMts() || resolveCts()) || tryResolve(joinPaths(filename, `index.ts`)) || tryResolve(joinPaths(filename, `index.tsx`)) || tryResolve(joinPaths(filename, `index.d.ts`));
  45950. }
  45951. const tsConfigCache = createCache();
  45952. const tsConfigRefMap = /* @__PURE__ */ new Map();
  45953. function resolveWithTS(containingFile, source, ts2, fs) {
  45954. return;
  45955. }
  45956. const fileToScopeCache = createCache();
  45957. const fileToGlobalScopeCache = createCache();
  45958. function invalidateTypeCache(filename) {
  45959. filename = normalizePath(filename);
  45960. fileToScopeCache.delete(filename);
  45961. fileToGlobalScopeCache.delete(filename);
  45962. tsConfigCache.delete(filename);
  45963. const affectedConfig = tsConfigRefMap.get(filename);
  45964. if (affectedConfig) tsConfigCache.delete(affectedConfig);
  45965. }
  45966. function fileToScope(ctx, filename, asGlobal = false) {
  45967. const cache = asGlobal ? fileToGlobalScopeCache : fileToScopeCache;
  45968. const cached = cache.get(filename);
  45969. if (cached) {
  45970. return cached;
  45971. }
  45972. const fs = resolveFS(ctx);
  45973. const source = fs.readFile(filename) || "";
  45974. const body = parseFile(filename, source, fs, ctx.options.babelParserPlugins);
  45975. const scope = new TypeScope(filename, source, 0, recordImports(body));
  45976. recordTypes(ctx, body, scope, asGlobal);
  45977. cache.set(filename, scope);
  45978. return scope;
  45979. }
  45980. function parseFile(filename, content, fs, parserPlugins) {
  45981. const ext = extname(filename);
  45982. if (ext === ".ts" || ext === ".mts" || ext === ".tsx" || ext === ".cts" || ext === ".mtsx") {
  45983. return libExports.parse(content, {
  45984. plugins: resolveParserPlugins(
  45985. ext.slice(1),
  45986. parserPlugins,
  45987. /\.d\.[cm]?ts$/.test(filename)
  45988. ),
  45989. sourceType: "module"
  45990. }).program.body;
  45991. }
  45992. const isUnknownTypeSource = !/\.[cm]?[tj]sx?$/.test(filename);
  45993. const arbitraryTypeSource = `${filename.slice(0, -ext.length)}.d${ext}.ts`;
  45994. const hasArbitraryTypeDeclaration = isUnknownTypeSource && fs.fileExists(arbitraryTypeSource);
  45995. if (hasArbitraryTypeDeclaration) {
  45996. return libExports.parse(fs.readFile(arbitraryTypeSource), {
  45997. plugins: resolveParserPlugins("ts", parserPlugins, true),
  45998. sourceType: "module"
  45999. }).program.body;
  46000. }
  46001. if (ext === ".vue") {
  46002. const {
  46003. descriptor: { script, scriptSetup }
  46004. } = parse$2(content);
  46005. if (!script && !scriptSetup) {
  46006. return [];
  46007. }
  46008. const scriptOffset = script ? script.loc.start.offset : Infinity;
  46009. const scriptSetupOffset = scriptSetup ? scriptSetup.loc.start.offset : Infinity;
  46010. const firstBlock = scriptOffset < scriptSetupOffset ? script : scriptSetup;
  46011. const secondBlock = scriptOffset < scriptSetupOffset ? scriptSetup : script;
  46012. let scriptContent = " ".repeat(Math.min(scriptOffset, scriptSetupOffset)) + firstBlock.content;
  46013. if (secondBlock) {
  46014. scriptContent += " ".repeat(secondBlock.loc.start.offset - script.loc.end.offset) + secondBlock.content;
  46015. }
  46016. const lang = (script == null ? void 0 : script.lang) || (scriptSetup == null ? void 0 : scriptSetup.lang);
  46017. return libExports.parse(scriptContent, {
  46018. plugins: resolveParserPlugins(lang, parserPlugins),
  46019. sourceType: "module"
  46020. }).program.body;
  46021. }
  46022. return [];
  46023. }
  46024. function ctxToScope(ctx) {
  46025. if (ctx.scope) {
  46026. return ctx.scope;
  46027. }
  46028. const body = "ast" in ctx ? ctx.ast : ctx.scriptAst ? [...ctx.scriptAst.body, ...ctx.scriptSetupAst.body] : ctx.scriptSetupAst.body;
  46029. const scope = new TypeScope(
  46030. ctx.filename,
  46031. ctx.source,
  46032. "startOffset" in ctx ? ctx.startOffset : 0,
  46033. "userImports" in ctx ? Object.create(ctx.userImports) : recordImports(body)
  46034. );
  46035. recordTypes(ctx, body, scope);
  46036. return ctx.scope = scope;
  46037. }
  46038. function moduleDeclToScope(ctx, node, parentScope) {
  46039. if (node._resolvedChildScope) {
  46040. return node._resolvedChildScope;
  46041. }
  46042. const scope = createChildScope(parentScope);
  46043. if (node.body.type === "TSModuleDeclaration") {
  46044. const decl = node.body;
  46045. decl._ownerScope = scope;
  46046. const id = getId(decl.id);
  46047. scope.types[id] = scope.exportedTypes[id] = decl;
  46048. } else {
  46049. recordTypes(ctx, node.body.body, scope);
  46050. }
  46051. return node._resolvedChildScope = scope;
  46052. }
  46053. function createChildScope(parentScope) {
  46054. return new TypeScope(
  46055. parentScope.filename,
  46056. parentScope.source,
  46057. parentScope.offset,
  46058. Object.create(parentScope.imports),
  46059. Object.create(parentScope.types),
  46060. Object.create(parentScope.declares)
  46061. );
  46062. }
  46063. const importExportRE = /^Import|^Export/;
  46064. function recordTypes(ctx, body, scope, asGlobal = false) {
  46065. const { types, declares, exportedTypes, exportedDeclares, imports } = scope;
  46066. const isAmbient = asGlobal ? !body.some((s) => importExportRE.test(s.type)) : false;
  46067. for (const stmt of body) {
  46068. if (asGlobal) {
  46069. if (isAmbient) {
  46070. if (stmt.declare) {
  46071. recordType(stmt, types, declares);
  46072. }
  46073. } else if (stmt.type === "TSModuleDeclaration" && stmt.global) {
  46074. for (const s of stmt.body.body) {
  46075. if (s.type === "ExportNamedDeclaration") {
  46076. if (s.declaration) {
  46077. recordType(s.declaration, types, declares);
  46078. } else if (s.source) {
  46079. const sourceScope = importSourceToScope(
  46080. ctx,
  46081. s.source,
  46082. scope,
  46083. s.source.value,
  46084. false
  46085. );
  46086. for (const spec of s.specifiers) {
  46087. if (spec.type === "ExportSpecifier") {
  46088. const exported = getId(spec.exported);
  46089. const local = spec.local.name;
  46090. if (sourceScope.exportedTypes[local]) {
  46091. types[exported] = sourceScope.exportedTypes[local];
  46092. }
  46093. if (sourceScope.exportedDeclares[local]) {
  46094. declares[exported] = sourceScope.exportedDeclares[local];
  46095. }
  46096. }
  46097. }
  46098. }
  46099. } else if (s.type === "ExportAllDeclaration" && s.source) {
  46100. const sourceScope = importSourceToScope(
  46101. ctx,
  46102. s.source,
  46103. scope,
  46104. s.source.value,
  46105. false
  46106. );
  46107. Object.assign(types, sourceScope.exportedTypes);
  46108. Object.assign(declares, sourceScope.exportedDeclares);
  46109. } else {
  46110. recordType(s, types, declares);
  46111. }
  46112. }
  46113. }
  46114. } else {
  46115. recordType(stmt, types, declares);
  46116. }
  46117. }
  46118. if (!asGlobal) {
  46119. for (const stmt of body) {
  46120. if (stmt.type === "ExportNamedDeclaration") {
  46121. if (stmt.declaration) {
  46122. recordType(stmt.declaration, types, declares);
  46123. recordType(stmt.declaration, exportedTypes, exportedDeclares);
  46124. } else {
  46125. for (const spec of stmt.specifiers) {
  46126. if (spec.type === "ExportSpecifier") {
  46127. const local = spec.local.name;
  46128. const exported = getId(spec.exported);
  46129. if (stmt.source) {
  46130. imports[exported] = {
  46131. source: stmt.source.value,
  46132. imported: local
  46133. };
  46134. exportedTypes[exported] = {
  46135. type: "TSTypeReference",
  46136. typeName: {
  46137. type: "Identifier",
  46138. name: local
  46139. },
  46140. _ownerScope: scope
  46141. };
  46142. } else if (types[local]) {
  46143. exportedTypes[exported] = types[local];
  46144. }
  46145. }
  46146. }
  46147. }
  46148. } else if (stmt.type === "ExportAllDeclaration") {
  46149. const sourceScope = importSourceToScope(
  46150. ctx,
  46151. stmt.source,
  46152. scope,
  46153. stmt.source.value
  46154. );
  46155. Object.assign(scope.exportedTypes, sourceScope.exportedTypes);
  46156. } else if (stmt.type === "ExportDefaultDeclaration" && stmt.declaration) {
  46157. if (stmt.declaration.type !== "Identifier") {
  46158. recordType(stmt.declaration, types, declares, "default");
  46159. recordType(
  46160. stmt.declaration,
  46161. exportedTypes,
  46162. exportedDeclares,
  46163. "default"
  46164. );
  46165. } else if (types[stmt.declaration.name]) {
  46166. exportedTypes["default"] = types[stmt.declaration.name];
  46167. }
  46168. }
  46169. }
  46170. }
  46171. for (const key of Object.keys(types)) {
  46172. const node = types[key];
  46173. if (!node._ownerScope) node._ownerScope = scope;
  46174. if (node._ns && !node._ns._ownerScope) node._ns._ownerScope = scope;
  46175. }
  46176. for (const key of Object.keys(declares)) {
  46177. if (!declares[key]._ownerScope) declares[key]._ownerScope = scope;
  46178. }
  46179. }
  46180. function recordType(node, types, declares, overwriteId) {
  46181. switch (node.type) {
  46182. case "TSInterfaceDeclaration":
  46183. case "TSEnumDeclaration":
  46184. case "TSModuleDeclaration": {
  46185. if (node.type === "TSModuleDeclaration" && node.global) {
  46186. const body = node.body;
  46187. for (const s of body.body) {
  46188. if (s.type === "ExportNamedDeclaration" && s.declaration) {
  46189. recordType(s.declaration, types, declares);
  46190. } else {
  46191. recordType(s, types, declares);
  46192. }
  46193. }
  46194. break;
  46195. }
  46196. const id = overwriteId || getId(node.id);
  46197. let existing = types[id];
  46198. if (existing) {
  46199. if (node.type === "TSModuleDeclaration") {
  46200. if (existing.type === "TSModuleDeclaration") {
  46201. mergeNamespaces(existing, node);
  46202. } else {
  46203. attachNamespace(existing, node);
  46204. }
  46205. break;
  46206. }
  46207. if (existing.type === "TSModuleDeclaration") {
  46208. types[id] = node;
  46209. attachNamespace(node, existing);
  46210. break;
  46211. }
  46212. if (existing.type !== node.type) {
  46213. break;
  46214. }
  46215. if (node.type === "TSInterfaceDeclaration") {
  46216. existing.body.body.push(...node.body.body);
  46217. } else {
  46218. existing.members.push(...node.members);
  46219. }
  46220. } else {
  46221. types[id] = node;
  46222. }
  46223. break;
  46224. }
  46225. case "ClassDeclaration":
  46226. if (overwriteId || node.id) types[overwriteId || getId(node.id)] = node;
  46227. break;
  46228. case "TSTypeAliasDeclaration":
  46229. types[node.id.name] = node.typeParameters ? node : node.typeAnnotation;
  46230. break;
  46231. case "TSDeclareFunction":
  46232. if (node.id) declares[node.id.name] = node;
  46233. break;
  46234. case "VariableDeclaration": {
  46235. if (node.declare) {
  46236. for (const decl of node.declarations) {
  46237. if (decl.id.type === "Identifier" && decl.id.typeAnnotation) {
  46238. declares[decl.id.name] = decl.id.typeAnnotation.typeAnnotation;
  46239. }
  46240. }
  46241. }
  46242. break;
  46243. }
  46244. }
  46245. }
  46246. function mergeNamespaces(to, from) {
  46247. const toBody = to.body;
  46248. const fromBody = from.body;
  46249. if (toBody.type === "TSModuleDeclaration") {
  46250. if (fromBody.type === "TSModuleDeclaration") {
  46251. mergeNamespaces(toBody, fromBody);
  46252. } else {
  46253. fromBody.body.push({
  46254. type: "ExportNamedDeclaration",
  46255. declaration: toBody,
  46256. exportKind: "type",
  46257. specifiers: []
  46258. });
  46259. }
  46260. } else if (fromBody.type === "TSModuleDeclaration") {
  46261. toBody.body.push({
  46262. type: "ExportNamedDeclaration",
  46263. declaration: fromBody,
  46264. exportKind: "type",
  46265. specifiers: []
  46266. });
  46267. } else {
  46268. toBody.body.push(...fromBody.body);
  46269. }
  46270. }
  46271. function attachNamespace(to, ns) {
  46272. if (!to._ns) {
  46273. to._ns = ns;
  46274. } else {
  46275. mergeNamespaces(to._ns, ns);
  46276. }
  46277. }
  46278. function recordImports(body) {
  46279. const imports = /* @__PURE__ */ Object.create(null);
  46280. for (const s of body) {
  46281. recordImport(s, imports);
  46282. }
  46283. return imports;
  46284. }
  46285. function recordImport(node, imports) {
  46286. if (node.type !== "ImportDeclaration") {
  46287. return;
  46288. }
  46289. for (const s of node.specifiers) {
  46290. imports[s.local.name] = {
  46291. imported: getImportedName(s),
  46292. source: node.source.value
  46293. };
  46294. }
  46295. }
  46296. function inferRuntimeType(ctx, node, scope = node._ownerScope || ctxToScope(ctx), isKeyOf = false, typeParameters) {
  46297. if (node.leadingComments && node.leadingComments.some((c) => c.value.includes("@vue-ignore"))) {
  46298. return [UNKNOWN_TYPE];
  46299. }
  46300. const prevSilent = ctx.silentOnExtendsFailure;
  46301. ctx.silentOnExtendsFailure = true;
  46302. try {
  46303. switch (node.type) {
  46304. case "TSStringKeyword":
  46305. return ["String"];
  46306. case "TSNumberKeyword":
  46307. return ["Number"];
  46308. case "TSBooleanKeyword":
  46309. return ["Boolean"];
  46310. case "TSObjectKeyword":
  46311. return ["Object"];
  46312. case "TSNullKeyword":
  46313. return ["null"];
  46314. case "TSTypeLiteral":
  46315. case "TSInterfaceDeclaration": {
  46316. const types = /* @__PURE__ */ new Set();
  46317. const members = node.type === "TSTypeLiteral" ? node.members : node.body.body;
  46318. for (const m of members) {
  46319. if (isKeyOf) {
  46320. if (m.type === "TSPropertySignature" && m.key.type === "NumericLiteral") {
  46321. types.add("Number");
  46322. } else if (m.type === "TSIndexSignature") {
  46323. const annotation = m.parameters[0].typeAnnotation;
  46324. if (annotation && annotation.type !== "Noop") {
  46325. const type = inferRuntimeType(
  46326. ctx,
  46327. annotation.typeAnnotation,
  46328. scope
  46329. )[0];
  46330. if (type === UNKNOWN_TYPE) return [UNKNOWN_TYPE];
  46331. types.add(type);
  46332. }
  46333. } else {
  46334. types.add("String");
  46335. }
  46336. } else if (m.type === "TSCallSignatureDeclaration" || m.type === "TSConstructSignatureDeclaration") {
  46337. types.add("Function");
  46338. } else {
  46339. types.add("Object");
  46340. }
  46341. }
  46342. return types.size ? Array.from(types) : [isKeyOf ? UNKNOWN_TYPE : "Object"];
  46343. }
  46344. case "TSPropertySignature":
  46345. if (node.typeAnnotation) {
  46346. return inferRuntimeType(
  46347. ctx,
  46348. node.typeAnnotation.typeAnnotation,
  46349. scope
  46350. );
  46351. }
  46352. break;
  46353. case "TSMethodSignature":
  46354. case "TSFunctionType":
  46355. return ["Function"];
  46356. case "TSArrayType":
  46357. case "TSTupleType":
  46358. return ["Array"];
  46359. case "TSLiteralType":
  46360. switch (node.literal.type) {
  46361. case "StringLiteral":
  46362. return ["String"];
  46363. case "BooleanLiteral":
  46364. return ["Boolean"];
  46365. case "NumericLiteral":
  46366. case "BigIntLiteral":
  46367. return ["Number"];
  46368. default:
  46369. return [UNKNOWN_TYPE];
  46370. }
  46371. case "TSTypeReference": {
  46372. let resolved;
  46373. try {
  46374. resolved = resolveTypeReference(ctx, node, scope);
  46375. } catch (e) {
  46376. }
  46377. if (resolved) {
  46378. if (resolved.type === "TSTypeAliasDeclaration") {
  46379. if (resolved.typeAnnotation.type === "TSFunctionType") {
  46380. return ["Function"];
  46381. }
  46382. if (node.typeParameters) {
  46383. const typeParams = /* @__PURE__ */ Object.create(null);
  46384. if (resolved.typeParameters) {
  46385. resolved.typeParameters.params.forEach((p, i) => {
  46386. typeParams[p.name] = node.typeParameters.params[i];
  46387. });
  46388. }
  46389. return inferRuntimeType(
  46390. ctx,
  46391. resolved.typeAnnotation,
  46392. resolved._ownerScope,
  46393. isKeyOf,
  46394. typeParams
  46395. );
  46396. }
  46397. }
  46398. return inferRuntimeType(ctx, resolved, resolved._ownerScope, isKeyOf);
  46399. }
  46400. if (node.typeName.type === "Identifier") {
  46401. if (typeParameters && typeParameters[node.typeName.name]) {
  46402. return inferRuntimeType(
  46403. ctx,
  46404. typeParameters[node.typeName.name],
  46405. scope,
  46406. isKeyOf,
  46407. typeParameters
  46408. );
  46409. }
  46410. if (isKeyOf) {
  46411. switch (node.typeName.name) {
  46412. case "String":
  46413. case "Array":
  46414. case "ArrayLike":
  46415. case "Parameters":
  46416. case "ConstructorParameters":
  46417. case "ReadonlyArray":
  46418. return ["String", "Number"];
  46419. // TS built-in utility types
  46420. case "Record":
  46421. case "Partial":
  46422. case "Required":
  46423. case "Readonly":
  46424. if (node.typeParameters && node.typeParameters.params[0]) {
  46425. return inferRuntimeType(
  46426. ctx,
  46427. node.typeParameters.params[0],
  46428. scope,
  46429. true
  46430. );
  46431. }
  46432. break;
  46433. case "Pick":
  46434. case "Extract":
  46435. if (node.typeParameters && node.typeParameters.params[1]) {
  46436. return inferRuntimeType(
  46437. ctx,
  46438. node.typeParameters.params[1],
  46439. scope
  46440. );
  46441. }
  46442. break;
  46443. case "Function":
  46444. case "Object":
  46445. case "Set":
  46446. case "Map":
  46447. case "WeakSet":
  46448. case "WeakMap":
  46449. case "Date":
  46450. case "Promise":
  46451. case "Error":
  46452. case "Uppercase":
  46453. case "Lowercase":
  46454. case "Capitalize":
  46455. case "Uncapitalize":
  46456. case "ReadonlyMap":
  46457. case "ReadonlySet":
  46458. return ["String"];
  46459. }
  46460. } else {
  46461. switch (node.typeName.name) {
  46462. case "Array":
  46463. case "Function":
  46464. case "Object":
  46465. case "Set":
  46466. case "Map":
  46467. case "WeakSet":
  46468. case "WeakMap":
  46469. case "Date":
  46470. case "Promise":
  46471. case "Error":
  46472. return [node.typeName.name];
  46473. // TS built-in utility types
  46474. // https://www.typescriptlang.org/docs/handbook/utility-types.html
  46475. case "Partial":
  46476. case "Required":
  46477. case "Readonly":
  46478. case "Record":
  46479. case "Pick":
  46480. case "Omit":
  46481. case "InstanceType":
  46482. return ["Object"];
  46483. case "Uppercase":
  46484. case "Lowercase":
  46485. case "Capitalize":
  46486. case "Uncapitalize":
  46487. return ["String"];
  46488. case "Parameters":
  46489. case "ConstructorParameters":
  46490. case "ReadonlyArray":
  46491. return ["Array"];
  46492. case "ReadonlyMap":
  46493. return ["Map"];
  46494. case "ReadonlySet":
  46495. return ["Set"];
  46496. // Vue ref wrapper types — handled here so that runtime type
  46497. // inference still works when `vue` types cannot be resolved
  46498. // (e.g. consumed as built artifacts in another package). #14729
  46499. case "Ref":
  46500. case "ShallowRef":
  46501. case "ComputedRef":
  46502. case "WritableComputedRef":
  46503. return ["Object"];
  46504. case "MaybeRef":
  46505. case "MaybeRefOrGetter": {
  46506. const types = /* @__PURE__ */ new Set(["Object"]);
  46507. if (node.typeName.name === "MaybeRefOrGetter") {
  46508. types.add("Function");
  46509. }
  46510. if (node.typeParameters && node.typeParameters.params[0]) {
  46511. for (const t of inferRuntimeType(
  46512. ctx,
  46513. node.typeParameters.params[0],
  46514. scope,
  46515. false,
  46516. typeParameters
  46517. )) {
  46518. types.add(t);
  46519. }
  46520. }
  46521. return Array.from(types);
  46522. }
  46523. case "NonNullable":
  46524. if (node.typeParameters && node.typeParameters.params[0]) {
  46525. return inferRuntimeType(
  46526. ctx,
  46527. node.typeParameters.params[0],
  46528. scope
  46529. ).filter((t) => t !== "null");
  46530. }
  46531. break;
  46532. case "Extract":
  46533. if (node.typeParameters && node.typeParameters.params[1]) {
  46534. return inferRuntimeType(
  46535. ctx,
  46536. node.typeParameters.params[1],
  46537. scope
  46538. );
  46539. }
  46540. break;
  46541. case "Exclude":
  46542. case "OmitThisParameter":
  46543. if (node.typeParameters && node.typeParameters.params[0]) {
  46544. return inferRuntimeType(
  46545. ctx,
  46546. node.typeParameters.params[0],
  46547. scope
  46548. );
  46549. }
  46550. break;
  46551. }
  46552. }
  46553. }
  46554. break;
  46555. }
  46556. case "TSParenthesizedType":
  46557. return inferRuntimeType(ctx, node.typeAnnotation, scope);
  46558. case "TSUnionType":
  46559. return flattenTypes(ctx, node.types, scope, isKeyOf, typeParameters);
  46560. case "TSIntersectionType": {
  46561. return flattenTypes(
  46562. ctx,
  46563. node.types,
  46564. scope,
  46565. isKeyOf,
  46566. typeParameters
  46567. ).filter((t) => t !== UNKNOWN_TYPE);
  46568. }
  46569. case "TSMappedType": {
  46570. const { typeAnnotation, typeParameter } = node;
  46571. if (typeAnnotation && typeAnnotation.type === "TSIndexedAccessType" && typeParameter && typeParameter.constraint && typeParameters) {
  46572. const constraint = typeParameter.constraint;
  46573. if (constraint.type === "TSTypeOperator" && constraint.operator === "keyof" && constraint.typeAnnotation && constraint.typeAnnotation.type === "TSTypeReference" && constraint.typeAnnotation.typeName.type === "Identifier") {
  46574. const typeName = constraint.typeAnnotation.typeName.name;
  46575. const index = typeAnnotation.indexType;
  46576. const obj = typeAnnotation.objectType;
  46577. if (obj && obj.type === "TSTypeReference" && obj.typeName.type === "Identifier" && obj.typeName.name === typeName && index && index.type === "TSTypeReference" && index.typeName.type === "Identifier" && index.typeName.name === typeParameter.name) {
  46578. const targetType = typeParameters[typeName];
  46579. if (targetType) {
  46580. return inferRuntimeType(ctx, targetType, scope);
  46581. }
  46582. }
  46583. }
  46584. }
  46585. return [UNKNOWN_TYPE];
  46586. }
  46587. case "TSEnumDeclaration":
  46588. return inferEnumType(node);
  46589. case "TSSymbolKeyword":
  46590. return ["Symbol"];
  46591. case "TSIndexedAccessType": {
  46592. const types = resolveIndexType(ctx, node, scope);
  46593. return flattenTypes(ctx, types, scope, isKeyOf);
  46594. }
  46595. case "ClassDeclaration":
  46596. return ["Object"];
  46597. case "TSImportType": {
  46598. const sourceScope = importSourceToScope(
  46599. ctx,
  46600. node.argument,
  46601. scope,
  46602. node.argument.value
  46603. );
  46604. const resolved = resolveTypeReference(ctx, node, sourceScope);
  46605. if (resolved) {
  46606. return inferRuntimeType(ctx, resolved, resolved._ownerScope);
  46607. }
  46608. break;
  46609. }
  46610. case "TSTypeQuery": {
  46611. const id = node.exprName;
  46612. if (id.type === "Identifier") {
  46613. const matched = scope.declares[id.name];
  46614. if (matched) {
  46615. return inferRuntimeType(ctx, matched, matched._ownerScope, isKeyOf);
  46616. }
  46617. }
  46618. break;
  46619. }
  46620. // e.g. readonly
  46621. case "TSTypeOperator": {
  46622. return inferRuntimeType(
  46623. ctx,
  46624. node.typeAnnotation,
  46625. scope,
  46626. node.operator === "keyof"
  46627. );
  46628. }
  46629. case "TSAnyKeyword": {
  46630. if (isKeyOf) {
  46631. return ["String", "Number", "Symbol"];
  46632. }
  46633. break;
  46634. }
  46635. }
  46636. } catch (e) {
  46637. } finally {
  46638. ctx.silentOnExtendsFailure = prevSilent;
  46639. }
  46640. return [UNKNOWN_TYPE];
  46641. }
  46642. function flattenTypes(ctx, types, scope, isKeyOf = false, typeParameters = void 0) {
  46643. if (types.length === 1) {
  46644. return inferRuntimeType(
  46645. ctx,
  46646. types[0],
  46647. types[0]._ownerScope || scope,
  46648. isKeyOf,
  46649. typeParameters
  46650. );
  46651. }
  46652. return [
  46653. ...new Set(
  46654. [].concat(
  46655. ...types.map(
  46656. (t) => inferRuntimeType(
  46657. ctx,
  46658. t,
  46659. t._ownerScope || scope,
  46660. isKeyOf,
  46661. typeParameters
  46662. )
  46663. )
  46664. )
  46665. )
  46666. ];
  46667. }
  46668. function inferEnumType(node) {
  46669. const types = /* @__PURE__ */ new Set();
  46670. for (const m of node.members) {
  46671. if (m.initializer) {
  46672. switch (m.initializer.type) {
  46673. case "StringLiteral":
  46674. types.add("String");
  46675. break;
  46676. case "NumericLiteral":
  46677. types.add("Number");
  46678. break;
  46679. }
  46680. }
  46681. }
  46682. return types.size ? [...types] : ["Number"];
  46683. }
  46684. function resolveExtractPropTypes({ props }, scope) {
  46685. const res = { props: {} };
  46686. for (const key in props) {
  46687. const raw = props[key];
  46688. res.props[key] = reverseInferType(
  46689. raw.key,
  46690. raw.typeAnnotation.typeAnnotation,
  46691. scope
  46692. );
  46693. }
  46694. return res;
  46695. }
  46696. function reverseInferType(key, node, scope, optional = true, checkObjectSyntax = true) {
  46697. if (checkObjectSyntax && node.type === "TSTypeLiteral") {
  46698. const typeType = findStaticPropertyType(node, "type");
  46699. if (typeType) {
  46700. const requiredType = findStaticPropertyType(node, "required");
  46701. const optional2 = requiredType && requiredType.type === "TSLiteralType" && requiredType.literal.type === "BooleanLiteral" ? !requiredType.literal.value : true;
  46702. return reverseInferType(key, typeType, scope, optional2, false);
  46703. }
  46704. } else if (node.type === "TSTypeReference" && node.typeName.type === "Identifier") {
  46705. if (node.typeName.name.endsWith("Constructor")) {
  46706. return createProperty(
  46707. key,
  46708. ctorToType(node.typeName.name),
  46709. scope,
  46710. optional
  46711. );
  46712. } else if (node.typeName.name === "PropType" && node.typeParameters) {
  46713. return createProperty(key, node.typeParameters.params[0], scope, optional);
  46714. }
  46715. }
  46716. if ((node.type === "TSTypeReference" || node.type === "TSImportType") && node.typeParameters) {
  46717. for (const t of node.typeParameters.params) {
  46718. const inferred = reverseInferType(key, t, scope, optional);
  46719. if (inferred) return inferred;
  46720. }
  46721. }
  46722. return createProperty(key, { type: `TSNullKeyword` }, scope, optional);
  46723. }
  46724. function ctorToType(ctorType) {
  46725. const ctor = ctorType.slice(0, -11);
  46726. switch (ctor) {
  46727. case "String":
  46728. case "Number":
  46729. case "Boolean":
  46730. return { type: `TS${ctor}Keyword` };
  46731. case "Array":
  46732. case "Function":
  46733. case "Object":
  46734. case "Set":
  46735. case "Map":
  46736. case "WeakSet":
  46737. case "WeakMap":
  46738. case "Date":
  46739. case "Promise":
  46740. return {
  46741. type: "TSTypeReference",
  46742. typeName: { type: "Identifier", name: ctor }
  46743. };
  46744. }
  46745. return { type: `TSNullKeyword` };
  46746. }
  46747. function findStaticPropertyType(node, key) {
  46748. const prop = node.members.find(
  46749. (m) => m.type === "TSPropertySignature" && getStringLiteralKey(m) === key && m.typeAnnotation
  46750. );
  46751. return prop && prop.typeAnnotation.typeAnnotation;
  46752. }
  46753. function resolveReturnType(ctx, arg, scope) {
  46754. var _a;
  46755. let resolved = arg;
  46756. if (arg.type === "TSTypeReference" || arg.type === "TSTypeQuery" || arg.type === "TSImportType") {
  46757. resolved = resolveTypeReference(ctx, arg, scope);
  46758. }
  46759. if (!resolved) return;
  46760. if (resolved.type === "TSFunctionType") {
  46761. return (_a = resolved.typeAnnotation) == null ? void 0 : _a.typeAnnotation;
  46762. }
  46763. if (resolved.type === "TSDeclareFunction") {
  46764. return resolved.returnType;
  46765. }
  46766. }
  46767. function resolveUnionType(ctx, node, scope) {
  46768. if (node.type === "TSTypeReference") {
  46769. const resolved = resolveTypeReference(ctx, node, scope);
  46770. if (resolved) node = resolved;
  46771. }
  46772. let types;
  46773. if (node.type === "TSUnionType") {
  46774. types = node.types.flatMap((node2) => resolveUnionType(ctx, node2, scope));
  46775. } else {
  46776. types = [node];
  46777. }
  46778. return types;
  46779. }
  46780. const DEFINE_MODEL = "defineModel";
  46781. function processDefineModel(ctx, node, declId) {
  46782. if (!isCallOf(node, DEFINE_MODEL)) {
  46783. return false;
  46784. }
  46785. ctx.hasDefineModelCall = true;
  46786. const type = node.typeParameters && node.typeParameters.params[0] || void 0;
  46787. let modelName;
  46788. let options;
  46789. const arg0 = node.arguments[0] && unwrapTSNode(node.arguments[0]);
  46790. const hasName = arg0 && (arg0.type === "StringLiteral" || arg0.type === "TemplateLiteral" && arg0.expressions.length === 0);
  46791. if (hasName) {
  46792. modelName = arg0.type === "StringLiteral" ? arg0.value : arg0.quasis[0].value.cooked;
  46793. options = node.arguments[1];
  46794. } else {
  46795. modelName = "modelValue";
  46796. options = arg0;
  46797. }
  46798. if (ctx.modelDecls[modelName]) {
  46799. ctx.error(`duplicate model name ${JSON.stringify(modelName)}`, node);
  46800. }
  46801. let optionsString = options && ctx.getString(options);
  46802. let optionsRemoved = !options;
  46803. const runtimeOptionNodes = [];
  46804. if (options && options.type === "ObjectExpression" && !options.properties.some((p) => p.type === "SpreadElement" || p.computed)) {
  46805. let removed = 0;
  46806. for (let i = options.properties.length - 1; i >= 0; i--) {
  46807. const p = options.properties[i];
  46808. const next = options.properties[i + 1];
  46809. const start = p.start;
  46810. const end = next ? next.start : options.end - 1;
  46811. if ((p.type === "ObjectProperty" || p.type === "ObjectMethod") && (p.key.type === "Identifier" && (p.key.name === "get" || p.key.name === "set") || p.key.type === "StringLiteral" && (p.key.value === "get" || p.key.value === "set"))) {
  46812. optionsString = optionsString.slice(0, start - options.start) + optionsString.slice(end - options.start);
  46813. } else {
  46814. removed++;
  46815. ctx.s.remove(ctx.startOffset + start, ctx.startOffset + end);
  46816. runtimeOptionNodes.push(p);
  46817. }
  46818. }
  46819. if (removed === options.properties.length) {
  46820. optionsRemoved = true;
  46821. ctx.s.remove(
  46822. ctx.startOffset + (hasName ? arg0.end : options.start),
  46823. ctx.startOffset + options.end
  46824. );
  46825. }
  46826. }
  46827. ctx.modelDecls[modelName] = {
  46828. type,
  46829. options: optionsString,
  46830. runtimeOptionNodes,
  46831. identifier: declId && declId.type === "Identifier" ? declId.name : void 0
  46832. };
  46833. ctx.bindingMetadata[modelName] = "props";
  46834. ctx.s.overwrite(
  46835. ctx.startOffset + node.callee.start,
  46836. ctx.startOffset + node.callee.end,
  46837. ctx.helper("useModel")
  46838. );
  46839. ctx.s.appendLeft(
  46840. ctx.startOffset + (node.arguments.length ? node.arguments[0].start : node.end - 1),
  46841. `__props, ` + (hasName ? `` : `${JSON.stringify(modelName)}${optionsRemoved ? `` : `, `}`)
  46842. );
  46843. return true;
  46844. }
  46845. function genModelProps(ctx) {
  46846. if (!ctx.hasDefineModelCall) return;
  46847. const isProd = !!ctx.options.isProd;
  46848. let modelPropsDecl = "";
  46849. for (const [name, { type, options: runtimeOptions }] of Object.entries(
  46850. ctx.modelDecls
  46851. )) {
  46852. let skipCheck = false;
  46853. let codegenOptions = ``;
  46854. let runtimeTypes = type && inferRuntimeType(ctx, type);
  46855. if (runtimeTypes) {
  46856. const hasBoolean = runtimeTypes.includes("Boolean");
  46857. const hasFunction = runtimeTypes.includes("Function");
  46858. const hasUnknownType = runtimeTypes.includes(UNKNOWN_TYPE);
  46859. if (hasUnknownType) {
  46860. if (hasBoolean || hasFunction) {
  46861. runtimeTypes = runtimeTypes.filter((t) => t !== UNKNOWN_TYPE);
  46862. skipCheck = true;
  46863. } else {
  46864. runtimeTypes = ["null"];
  46865. }
  46866. }
  46867. if (!isProd) {
  46868. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}` + (skipCheck ? ", skipCheck: true" : "");
  46869. } else if (hasBoolean || runtimeOptions && hasFunction) {
  46870. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}`;
  46871. } else ;
  46872. }
  46873. let decl;
  46874. if (codegenOptions && runtimeOptions) {
  46875. decl = ctx.isTS ? `{ ${codegenOptions}, ...${runtimeOptions} }` : `Object.assign({ ${codegenOptions} }, ${runtimeOptions})`;
  46876. } else if (codegenOptions) {
  46877. decl = `{ ${codegenOptions} }`;
  46878. } else if (runtimeOptions) {
  46879. decl = runtimeOptions;
  46880. } else {
  46881. decl = `{}`;
  46882. }
  46883. modelPropsDecl += `
  46884. ${JSON.stringify(name)}: ${decl},`;
  46885. const modifierPropName = JSON.stringify(
  46886. name === "modelValue" ? `modelModifiers` : `${name}Modifiers`
  46887. );
  46888. modelPropsDecl += `
  46889. ${modifierPropName}: {},`;
  46890. }
  46891. return `{${modelPropsDecl}
  46892. }`;
  46893. }
  46894. const DEFINE_PROPS = "defineProps";
  46895. const WITH_DEFAULTS = "withDefaults";
  46896. function processDefineProps(ctx, node, declId, isWithDefaults = false) {
  46897. if (!isCallOf(node, DEFINE_PROPS)) {
  46898. return processWithDefaults(ctx, node, declId);
  46899. }
  46900. if (ctx.hasDefinePropsCall) {
  46901. ctx.error(`duplicate ${DEFINE_PROPS}() call`, node);
  46902. }
  46903. ctx.hasDefinePropsCall = true;
  46904. ctx.propsRuntimeDecl = node.arguments[0];
  46905. if (ctx.propsRuntimeDecl) {
  46906. for (const key of getObjectOrArrayExpressionKeys(ctx.propsRuntimeDecl)) {
  46907. if (!(key in ctx.bindingMetadata)) {
  46908. ctx.bindingMetadata[key] = "props";
  46909. }
  46910. }
  46911. }
  46912. if (node.typeParameters) {
  46913. if (ctx.propsRuntimeDecl) {
  46914. ctx.error(
  46915. `${DEFINE_PROPS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  46916. node
  46917. );
  46918. }
  46919. ctx.propsTypeDecl = node.typeParameters.params[0];
  46920. }
  46921. if (!isWithDefaults && declId && declId.type === "ObjectPattern") {
  46922. processPropsDestructure(ctx, declId);
  46923. }
  46924. ctx.propsCall = node;
  46925. ctx.propsDecl = declId;
  46926. return true;
  46927. }
  46928. function processWithDefaults(ctx, node, declId) {
  46929. if (!isCallOf(node, WITH_DEFAULTS)) {
  46930. return false;
  46931. }
  46932. if (!processDefineProps(
  46933. ctx,
  46934. node.arguments[0],
  46935. declId,
  46936. true
  46937. )) {
  46938. ctx.error(
  46939. `${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`,
  46940. node.arguments[0] || node
  46941. );
  46942. }
  46943. if (ctx.propsRuntimeDecl) {
  46944. ctx.error(
  46945. `${WITH_DEFAULTS} can only be used with type-based ${DEFINE_PROPS} declaration.`,
  46946. node
  46947. );
  46948. }
  46949. if (declId && declId.type === "ObjectPattern") {
  46950. ctx.warn(
  46951. `${WITH_DEFAULTS}() is unnecessary when using destructure with ${DEFINE_PROPS}().
  46952. Reactive destructure will be disabled when using withDefaults().
  46953. Prefer using destructure default values, e.g. const { foo = 1 } = defineProps(...). `,
  46954. node.callee
  46955. );
  46956. }
  46957. ctx.propsRuntimeDefaults = node.arguments[1];
  46958. if (!ctx.propsRuntimeDefaults) {
  46959. ctx.error(`The 2nd argument of ${WITH_DEFAULTS} is required.`, node);
  46960. }
  46961. ctx.propsCall = node;
  46962. return true;
  46963. }
  46964. function genRuntimeProps(ctx) {
  46965. let propsDecls;
  46966. if (ctx.propsRuntimeDecl) {
  46967. propsDecls = ctx.getString(ctx.propsRuntimeDecl).trim();
  46968. if (ctx.propsDestructureDecl) {
  46969. const defaults = [];
  46970. for (const key in ctx.propsDestructuredBindings) {
  46971. const d = genDestructuredDefaultValue(ctx, key);
  46972. const finalKey = getEscapedPropName(key);
  46973. if (d)
  46974. defaults.push(
  46975. `${finalKey}: ${d.valueString}${d.needSkipFactory ? `, __skip_${finalKey}: true` : ``}`
  46976. );
  46977. }
  46978. if (defaults.length) {
  46979. propsDecls = `/*@__PURE__*/${ctx.helper(
  46980. `mergeDefaults`
  46981. )}(${propsDecls}, {
  46982. ${defaults.join(",\n ")}
  46983. })`;
  46984. }
  46985. }
  46986. } else if (ctx.propsTypeDecl) {
  46987. propsDecls = extractRuntimeProps(ctx);
  46988. }
  46989. const modelsDecls = genModelProps(ctx);
  46990. if (propsDecls && modelsDecls) {
  46991. return `/*@__PURE__*/${ctx.helper(
  46992. "mergeModels"
  46993. )}(${propsDecls}, ${modelsDecls})`;
  46994. } else {
  46995. return modelsDecls || propsDecls;
  46996. }
  46997. }
  46998. function extractRuntimeProps(ctx) {
  46999. const props = resolveRuntimePropsFromType(ctx, ctx.propsTypeDecl);
  47000. if (!props.length) {
  47001. return;
  47002. }
  47003. const propStrings = [];
  47004. const hasStaticDefaults = hasStaticWithDefaults(ctx);
  47005. for (const prop of props) {
  47006. propStrings.push(genRuntimePropFromType(ctx, prop, hasStaticDefaults));
  47007. if ("bindingMetadata" in ctx && !(prop.key in ctx.bindingMetadata)) {
  47008. ctx.bindingMetadata[prop.key] = "props";
  47009. }
  47010. }
  47011. let propsDecls = `{
  47012. ${propStrings.join(",\n ")}
  47013. }`;
  47014. if (ctx.propsRuntimeDefaults && !hasStaticDefaults) {
  47015. propsDecls = `/*@__PURE__*/${ctx.helper(
  47016. "mergeDefaults"
  47017. )}(${propsDecls}, ${ctx.getString(ctx.propsRuntimeDefaults)})`;
  47018. }
  47019. return propsDecls;
  47020. }
  47021. function resolveRuntimePropsFromType(ctx, node) {
  47022. const props = [];
  47023. const elements = resolveTypeElements(ctx, node);
  47024. for (const key in elements.props) {
  47025. const e = elements.props[key];
  47026. let type = inferRuntimeType(ctx, e);
  47027. let skipCheck = false;
  47028. if (type.includes(UNKNOWN_TYPE)) {
  47029. if (type.includes("Boolean") || type.includes("Function")) {
  47030. type = type.filter((t) => t !== UNKNOWN_TYPE);
  47031. skipCheck = true;
  47032. } else {
  47033. type = ["null"];
  47034. }
  47035. }
  47036. props.push({
  47037. key,
  47038. required: !e.optional,
  47039. type: type || [`null`],
  47040. skipCheck
  47041. });
  47042. }
  47043. return props;
  47044. }
  47045. function genRuntimePropFromType(ctx, { key, required, type, skipCheck }, hasStaticDefaults) {
  47046. let defaultString;
  47047. const destructured = genDestructuredDefaultValue(ctx, key, type);
  47048. if (destructured) {
  47049. defaultString = `default: ${destructured.valueString}${destructured.needSkipFactory ? `, skipFactory: true` : ``}`;
  47050. } else if (hasStaticDefaults) {
  47051. const prop = ctx.propsRuntimeDefaults.properties.find(
  47052. (node) => {
  47053. if (node.type === "SpreadElement") return false;
  47054. return resolveObjectKey(node.key, node.computed) === key;
  47055. }
  47056. );
  47057. if (prop) {
  47058. if (prop.type === "ObjectProperty") {
  47059. defaultString = `default: ${ctx.getString(prop.value)}`;
  47060. } else {
  47061. let paramsString = "";
  47062. if (prop.params.length) {
  47063. const start = prop.params[0].start;
  47064. const end = prop.params[prop.params.length - 1].end;
  47065. paramsString = ctx.getString({ start, end });
  47066. }
  47067. defaultString = `${prop.async ? "async " : ""}${prop.kind !== "method" ? `${prop.kind} ` : ""}default(${paramsString}) ${ctx.getString(prop.body)}`;
  47068. }
  47069. }
  47070. }
  47071. const finalKey = getEscapedPropName(key);
  47072. if (!ctx.options.isProd) {
  47073. return `${finalKey}: { ${concatStrings([
  47074. `type: ${toRuntimeTypeString(type)}`,
  47075. `required: ${required}`,
  47076. skipCheck && "skipCheck: true",
  47077. defaultString
  47078. ])} }`;
  47079. } else if (type.some(
  47080. (el) => el === "Boolean" || (!hasStaticDefaults || defaultString) && el === "Function"
  47081. )) {
  47082. return `${finalKey}: { ${concatStrings([
  47083. `type: ${toRuntimeTypeString(type)}`,
  47084. defaultString
  47085. ])} }`;
  47086. } else {
  47087. if (ctx.isCE) {
  47088. if (defaultString) {
  47089. return `${finalKey}: ${`{ ${defaultString}, type: ${toRuntimeTypeString(
  47090. type
  47091. )} }`}`;
  47092. } else {
  47093. return `${finalKey}: {type: ${toRuntimeTypeString(type)}}`;
  47094. }
  47095. }
  47096. return `${finalKey}: ${defaultString ? `{ ${defaultString} }` : `{}`}`;
  47097. }
  47098. }
  47099. function hasStaticWithDefaults(ctx) {
  47100. return !!(ctx.propsRuntimeDefaults && ctx.propsRuntimeDefaults.type === "ObjectExpression" && ctx.propsRuntimeDefaults.properties.every(
  47101. (node) => node.type !== "SpreadElement" && (!node.computed || node.key.type.endsWith("Literal"))
  47102. ));
  47103. }
  47104. function genDestructuredDefaultValue(ctx, key, inferredType) {
  47105. const destructured = ctx.propsDestructuredBindings[key];
  47106. const defaultVal = destructured && destructured.default;
  47107. if (defaultVal) {
  47108. const value = ctx.getString(defaultVal);
  47109. const unwrapped = unwrapTSNode(defaultVal);
  47110. if (inferredType && inferredType.length && !inferredType.includes("null")) {
  47111. const valueType = inferValueType(unwrapped);
  47112. if (valueType && !inferredType.includes(valueType)) {
  47113. ctx.error(
  47114. `Default value of prop "${key}" does not match declared type.`,
  47115. unwrapped
  47116. );
  47117. }
  47118. }
  47119. const needSkipFactory = !inferredType && (isFunctionType(unwrapped) || unwrapped.type === "Identifier");
  47120. const needFactoryWrap = !needSkipFactory && !isLiteralNode(unwrapped) && !(inferredType == null ? void 0 : inferredType.includes("Function"));
  47121. return {
  47122. valueString: needFactoryWrap ? `() => (${value})` : value,
  47123. needSkipFactory
  47124. };
  47125. }
  47126. }
  47127. function inferValueType(node) {
  47128. switch (node.type) {
  47129. case "StringLiteral":
  47130. return "String";
  47131. case "NumericLiteral":
  47132. return "Number";
  47133. case "BooleanLiteral":
  47134. return "Boolean";
  47135. case "ObjectExpression":
  47136. return "Object";
  47137. case "ArrayExpression":
  47138. return "Array";
  47139. case "FunctionExpression":
  47140. case "ArrowFunctionExpression":
  47141. return "Function";
  47142. }
  47143. }
  47144. function processPropsDestructure(ctx, declId) {
  47145. if (ctx.options.propsDestructure === "error") {
  47146. ctx.error(`Props destructure is explicitly prohibited via config.`, declId);
  47147. } else if (ctx.options.propsDestructure === false) {
  47148. return;
  47149. }
  47150. ctx.propsDestructureDecl = declId;
  47151. const registerBinding = (key, local, defaultValue) => {
  47152. ctx.propsDestructuredBindings[key] = { local, default: defaultValue };
  47153. if (local !== key) {
  47154. ctx.bindingMetadata[local] = "props-aliased";
  47155. (ctx.bindingMetadata.__propsAliases || (ctx.bindingMetadata.__propsAliases = {}))[local] = key;
  47156. }
  47157. };
  47158. for (const prop of declId.properties) {
  47159. if (prop.type === "ObjectProperty") {
  47160. const propKey = resolveObjectKey(prop.key, prop.computed);
  47161. if (!propKey) {
  47162. ctx.error(
  47163. `${DEFINE_PROPS}() destructure cannot use computed key.`,
  47164. prop.key
  47165. );
  47166. }
  47167. if (prop.value.type === "AssignmentPattern") {
  47168. const { left, right } = prop.value;
  47169. if (left.type !== "Identifier") {
  47170. ctx.error(
  47171. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  47172. left
  47173. );
  47174. }
  47175. registerBinding(propKey, left.name, right);
  47176. } else if (prop.value.type === "Identifier") {
  47177. registerBinding(propKey, prop.value.name);
  47178. } else {
  47179. ctx.error(
  47180. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  47181. prop.value
  47182. );
  47183. }
  47184. } else {
  47185. ctx.propsDestructureRestId = prop.argument.name;
  47186. ctx.bindingMetadata[ctx.propsDestructureRestId] = "setup-reactive-const";
  47187. }
  47188. }
  47189. }
  47190. function transformDestructuredProps(ctx, vueImportAliases) {
  47191. if (ctx.options.propsDestructure === false) {
  47192. return;
  47193. }
  47194. const rootScope = /* @__PURE__ */ Object.create(null);
  47195. const scopeStack = [rootScope];
  47196. let currentScope = rootScope;
  47197. const excludedIds = /* @__PURE__ */ new WeakSet();
  47198. const parentStack = [];
  47199. const propsLocalToPublicMap = /* @__PURE__ */ Object.create(null);
  47200. for (const key in ctx.propsDestructuredBindings) {
  47201. const { local } = ctx.propsDestructuredBindings[key];
  47202. rootScope[local] = true;
  47203. propsLocalToPublicMap[local] = key;
  47204. }
  47205. function pushScope() {
  47206. scopeStack.push(currentScope = Object.create(currentScope));
  47207. }
  47208. function popScope() {
  47209. scopeStack.pop();
  47210. currentScope = scopeStack[scopeStack.length - 1] || null;
  47211. }
  47212. function registerLocalBinding(id) {
  47213. excludedIds.add(id);
  47214. if (currentScope) {
  47215. currentScope[id.name] = false;
  47216. } else {
  47217. ctx.error(
  47218. "registerBinding called without active scope, something is wrong.",
  47219. id
  47220. );
  47221. }
  47222. }
  47223. function walkScope(node, isRoot = false) {
  47224. for (const stmt of node.body) {
  47225. if (stmt.type === "VariableDeclaration") {
  47226. walkVariableDeclaration(stmt, isRoot);
  47227. } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
  47228. if (stmt.declare || !stmt.id) continue;
  47229. registerLocalBinding(stmt.id);
  47230. } else if (stmt.type === "ExportNamedDeclaration" && stmt.declaration && stmt.declaration.type === "VariableDeclaration") {
  47231. walkVariableDeclaration(stmt.declaration, isRoot);
  47232. } else if (stmt.type === "LabeledStatement" && stmt.body.type === "VariableDeclaration") {
  47233. walkVariableDeclaration(stmt.body, isRoot);
  47234. }
  47235. }
  47236. }
  47237. function walkVariableDeclaration(stmt, isRoot = false) {
  47238. if (stmt.declare) {
  47239. return;
  47240. }
  47241. for (const decl of stmt.declarations) {
  47242. const isDefineProps = isRoot && decl.init && isCallOf(unwrapTSNode(decl.init), "defineProps");
  47243. for (const id of extractIdentifiers$1(decl.id)) {
  47244. if (isDefineProps) {
  47245. excludedIds.add(id);
  47246. } else {
  47247. registerLocalBinding(id);
  47248. }
  47249. }
  47250. }
  47251. }
  47252. function rewriteId(id, parent, parentStack2) {
  47253. if (parent.type === "AssignmentExpression" && id === parent.left || parent.type === "UpdateExpression") {
  47254. ctx.error(`Cannot assign to destructured props as they are readonly.`, id);
  47255. }
  47256. if (isStaticProperty(parent) && parent.shorthand) {
  47257. if (!parent.inPattern || isInDestructureAssignment(parent, parentStack2)) {
  47258. ctx.s.appendLeft(
  47259. id.end + ctx.startOffset,
  47260. `: ${genPropsAccessExp(propsLocalToPublicMap[id.name])}`
  47261. );
  47262. }
  47263. } else {
  47264. ctx.s.overwrite(
  47265. id.start + ctx.startOffset,
  47266. id.end + ctx.startOffset,
  47267. genPropsAccessExp(propsLocalToPublicMap[id.name])
  47268. );
  47269. }
  47270. }
  47271. function checkUsage(node, method, alias = method) {
  47272. if (isCallOf(node, alias)) {
  47273. const arg = unwrapTSNode(node.arguments[0]);
  47274. if (arg.type === "Identifier" && currentScope[arg.name]) {
  47275. ctx.error(
  47276. `"${arg.name}" is a destructured prop and should not be passed directly to ${method}(). Pass a getter () => ${arg.name} instead.`,
  47277. arg
  47278. );
  47279. }
  47280. }
  47281. }
  47282. const ast = ctx.scriptSetupAst;
  47283. walkScope(ast, true);
  47284. walk$2(ast, {
  47285. enter(node, parent) {
  47286. parent && parentStack.push(parent);
  47287. if (parent && parent.type.startsWith("TS") && !TS_NODE_TYPES.includes(parent.type)) {
  47288. return this.skip();
  47289. }
  47290. checkUsage(node, "watch", vueImportAliases.watch);
  47291. checkUsage(node, "toRef", vueImportAliases.toRef);
  47292. if (isFunctionType(node)) {
  47293. pushScope();
  47294. walkFunctionParams(node, registerLocalBinding);
  47295. if (node.body.type === "BlockStatement") {
  47296. walkScope(node.body);
  47297. }
  47298. return;
  47299. }
  47300. if (node.type === "CatchClause") {
  47301. pushScope();
  47302. if (node.param && node.param.type === "Identifier") {
  47303. registerLocalBinding(node.param);
  47304. }
  47305. walkScope(node.body);
  47306. return;
  47307. }
  47308. if (node.type === "ForOfStatement" || node.type === "ForInStatement" || node.type === "ForStatement") {
  47309. pushScope();
  47310. const varDecl = node.type === "ForStatement" ? node.init : node.left;
  47311. if (varDecl && varDecl.type === "VariableDeclaration") {
  47312. walkVariableDeclaration(varDecl);
  47313. }
  47314. if (node.body.type === "BlockStatement") {
  47315. walkScope(node.body);
  47316. }
  47317. return;
  47318. }
  47319. if (node.type === "BlockStatement" && !isFunctionType(parent)) {
  47320. pushScope();
  47321. walkScope(node);
  47322. return;
  47323. }
  47324. if (node.type === "Identifier") {
  47325. if (isReferencedIdentifier(node, parent, parentStack) && !excludedIds.has(node)) {
  47326. if (currentScope[node.name]) {
  47327. rewriteId(node, parent, parentStack);
  47328. }
  47329. }
  47330. }
  47331. },
  47332. leave(node, parent) {
  47333. parent && parentStack.pop();
  47334. if (node.type === "BlockStatement" && !isFunctionType(parent) || isFunctionType(node) || node.type === "CatchClause" || node.type === "ForOfStatement" || node.type === "ForInStatement" || node.type === "ForStatement") {
  47335. popScope();
  47336. }
  47337. }
  47338. });
  47339. }
  47340. const DEFINE_EMITS = "defineEmits";
  47341. function processDefineEmits(ctx, node, declId) {
  47342. if (!isCallOf(node, DEFINE_EMITS)) {
  47343. return false;
  47344. }
  47345. if (ctx.hasDefineEmitCall) {
  47346. ctx.error(`duplicate ${DEFINE_EMITS}() call`, node);
  47347. }
  47348. ctx.hasDefineEmitCall = true;
  47349. ctx.emitsRuntimeDecl = node.arguments[0];
  47350. if (node.typeParameters) {
  47351. if (ctx.emitsRuntimeDecl) {
  47352. ctx.error(
  47353. `${DEFINE_EMITS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  47354. node
  47355. );
  47356. }
  47357. ctx.emitsTypeDecl = node.typeParameters.params[0];
  47358. }
  47359. ctx.emitDecl = declId;
  47360. return true;
  47361. }
  47362. function genRuntimeEmits(ctx) {
  47363. let emitsDecl = "";
  47364. if (ctx.emitsRuntimeDecl) {
  47365. emitsDecl = ctx.getString(ctx.emitsRuntimeDecl).trim();
  47366. } else if (ctx.emitsTypeDecl) {
  47367. const typeDeclaredEmits = extractRuntimeEmits(ctx);
  47368. emitsDecl = typeDeclaredEmits.size ? `[${Array.from(typeDeclaredEmits).map((k) => JSON.stringify(k)).join(", ")}]` : ``;
  47369. }
  47370. if (ctx.hasDefineModelCall) {
  47371. let modelEmitsDecl = `[${Object.keys(ctx.modelDecls).map((n) => JSON.stringify(`update:${n}`)).join(", ")}]`;
  47372. emitsDecl = emitsDecl ? `/*@__PURE__*/${ctx.helper(
  47373. "mergeModels"
  47374. )}(${emitsDecl}, ${modelEmitsDecl})` : modelEmitsDecl;
  47375. }
  47376. return emitsDecl;
  47377. }
  47378. function extractRuntimeEmits(ctx) {
  47379. const emits = /* @__PURE__ */ new Set();
  47380. const node = ctx.emitsTypeDecl;
  47381. if (node.type === "TSFunctionType") {
  47382. extractEventNames(ctx, node.parameters[0], emits);
  47383. return emits;
  47384. }
  47385. const { props, calls } = resolveTypeElements(ctx, node);
  47386. let hasProperty = false;
  47387. for (const key in props) {
  47388. emits.add(key);
  47389. hasProperty = true;
  47390. }
  47391. if (calls) {
  47392. if (hasProperty) {
  47393. ctx.error(
  47394. `defineEmits() type cannot mixed call signature and property syntax.`,
  47395. node
  47396. );
  47397. }
  47398. for (const call of calls) {
  47399. extractEventNames(ctx, call.parameters[0], emits);
  47400. }
  47401. }
  47402. return emits;
  47403. }
  47404. function extractEventNames(ctx, eventName, emits) {
  47405. if (eventName.type === "Identifier" && eventName.typeAnnotation && eventName.typeAnnotation.type === "TSTypeAnnotation") {
  47406. const types = resolveUnionType(ctx, eventName.typeAnnotation.typeAnnotation);
  47407. for (const type of types) {
  47408. if (type.type === "TSLiteralType") {
  47409. if (type.literal.type !== "UnaryExpression" && type.literal.type !== "TemplateLiteral") {
  47410. emits.add(String(type.literal.value));
  47411. }
  47412. }
  47413. }
  47414. }
  47415. }
  47416. const DEFINE_EXPOSE = "defineExpose";
  47417. function processDefineExpose(ctx, node) {
  47418. if (isCallOf(node, DEFINE_EXPOSE)) {
  47419. if (ctx.hasDefineExposeCall) {
  47420. ctx.error(`duplicate ${DEFINE_EXPOSE}() call`, node);
  47421. }
  47422. ctx.hasDefineExposeCall = true;
  47423. return true;
  47424. }
  47425. return false;
  47426. }
  47427. const DEFINE_SLOTS = "defineSlots";
  47428. function processDefineSlots(ctx, node, declId) {
  47429. if (!isCallOf(node, DEFINE_SLOTS)) {
  47430. return false;
  47431. }
  47432. if (ctx.hasDefineSlotsCall) {
  47433. ctx.error(`duplicate ${DEFINE_SLOTS}() call`, node);
  47434. }
  47435. ctx.hasDefineSlotsCall = true;
  47436. if (node.arguments.length > 0) {
  47437. ctx.error(`${DEFINE_SLOTS}() cannot accept arguments`, node);
  47438. }
  47439. if (declId) {
  47440. ctx.s.overwrite(
  47441. ctx.startOffset + node.start,
  47442. ctx.startOffset + node.end,
  47443. `${ctx.helper("useSlots")}()`
  47444. );
  47445. }
  47446. return true;
  47447. }
  47448. const DEFINE_OPTIONS = "defineOptions";
  47449. function processDefineOptions(ctx, node) {
  47450. if (!isCallOf(node, DEFINE_OPTIONS)) {
  47451. return false;
  47452. }
  47453. if (ctx.hasDefineOptionsCall) {
  47454. ctx.error(`duplicate ${DEFINE_OPTIONS}() call`, node);
  47455. }
  47456. if (node.typeParameters) {
  47457. ctx.error(`${DEFINE_OPTIONS}() cannot accept type arguments`, node);
  47458. }
  47459. if (!node.arguments[0]) return true;
  47460. ctx.hasDefineOptionsCall = true;
  47461. ctx.optionsRuntimeDecl = unwrapTSNode(node.arguments[0]);
  47462. let propsOption = void 0;
  47463. let emitsOption = void 0;
  47464. let exposeOption = void 0;
  47465. let slotsOption = void 0;
  47466. if (ctx.optionsRuntimeDecl.type === "ObjectExpression") {
  47467. for (const prop of ctx.optionsRuntimeDecl.properties) {
  47468. if ((prop.type === "ObjectProperty" || prop.type === "ObjectMethod") && prop.key.type === "Identifier") {
  47469. switch (prop.key.name) {
  47470. case "props":
  47471. propsOption = prop;
  47472. break;
  47473. case "emits":
  47474. emitsOption = prop;
  47475. break;
  47476. case "expose":
  47477. exposeOption = prop;
  47478. break;
  47479. case "slots":
  47480. slotsOption = prop;
  47481. break;
  47482. }
  47483. }
  47484. }
  47485. }
  47486. if (propsOption) {
  47487. ctx.error(
  47488. `${DEFINE_OPTIONS}() cannot be used to declare props. Use ${DEFINE_PROPS}() instead.`,
  47489. propsOption
  47490. );
  47491. }
  47492. if (emitsOption) {
  47493. ctx.error(
  47494. `${DEFINE_OPTIONS}() cannot be used to declare emits. Use ${DEFINE_EMITS}() instead.`,
  47495. emitsOption
  47496. );
  47497. }
  47498. if (exposeOption) {
  47499. ctx.error(
  47500. `${DEFINE_OPTIONS}() cannot be used to declare expose. Use ${DEFINE_EXPOSE}() instead.`,
  47501. exposeOption
  47502. );
  47503. }
  47504. if (slotsOption) {
  47505. ctx.error(
  47506. `${DEFINE_OPTIONS}() cannot be used to declare slots. Use ${DEFINE_SLOTS}() instead.`,
  47507. slotsOption
  47508. );
  47509. }
  47510. return true;
  47511. }
  47512. function processAwait(ctx, node, needSemi, isStatement) {
  47513. const argumentStart = node.argument.extra && node.argument.extra.parenthesized ? node.argument.extra.parenStart : node.argument.start;
  47514. const startOffset = ctx.startOffset;
  47515. const argumentStr = ctx.descriptor.source.slice(
  47516. argumentStart + startOffset,
  47517. node.argument.end + startOffset
  47518. );
  47519. const containsNestedAwait = /\bawait\b/.test(argumentStr);
  47520. ctx.s.overwrite(
  47521. node.start + startOffset,
  47522. argumentStart + startOffset,
  47523. `${needSemi ? `;` : ``}(
  47524. ([__temp,__restore] = ${ctx.helper(
  47525. `withAsyncContext`
  47526. )}(${containsNestedAwait ? `async ` : ``}() => `
  47527. );
  47528. ctx.s.appendLeft(
  47529. node.end + startOffset,
  47530. `)),
  47531. ${isStatement ? `` : `__temp = `}await __temp,
  47532. __restore()${isStatement ? `` : `,
  47533. __temp`}
  47534. )`
  47535. );
  47536. }
  47537. var __defProp$1 = Object.defineProperty;
  47538. var __defProps = Object.defineProperties;
  47539. var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
  47540. var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
  47541. var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
  47542. var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
  47543. var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  47544. var __spreadValues$1 = (a, b) => {
  47545. for (var prop in b || (b = {}))
  47546. if (__hasOwnProp$1.call(b, prop))
  47547. __defNormalProp$1(a, prop, b[prop]);
  47548. if (__getOwnPropSymbols$1)
  47549. for (var prop of __getOwnPropSymbols$1(b)) {
  47550. if (__propIsEnum$1.call(b, prop))
  47551. __defNormalProp$1(a, prop, b[prop]);
  47552. }
  47553. return a;
  47554. };
  47555. var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
  47556. const MACROS = [
  47557. DEFINE_PROPS,
  47558. DEFINE_EMITS,
  47559. DEFINE_EXPOSE,
  47560. DEFINE_OPTIONS,
  47561. DEFINE_SLOTS,
  47562. DEFINE_MODEL,
  47563. WITH_DEFAULTS
  47564. ];
  47565. function compileScript(sfc, options) {
  47566. var _a, _b, _c;
  47567. if (!options.id) {
  47568. warnOnce$1(
  47569. `compileScript now requires passing the \`id\` option.
  47570. Upgrade your vite or vue-loader version for compatibility with the latest experimental proposals.`
  47571. );
  47572. }
  47573. const { script, scriptSetup, source, filename } = sfc;
  47574. const hoistStatic = options.hoistStatic !== false && !script;
  47575. const scopeId = options.id ? options.id.replace(/^data-v-/, "") : "";
  47576. const scriptLang = script && script.lang;
  47577. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  47578. const isJSOrTS = isJS(scriptLang, scriptSetupLang) || isTS(scriptLang, scriptSetupLang);
  47579. if (script && scriptSetup && scriptLang !== scriptSetupLang) {
  47580. throw new Error(
  47581. `[@vue/compiler-sfc] <script> and <script setup> must have the same language type.`
  47582. );
  47583. }
  47584. if (!scriptSetup) {
  47585. if (!script) {
  47586. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
  47587. }
  47588. if (script.lang && !isJSOrTS) {
  47589. return script;
  47590. }
  47591. const ctx2 = new ScriptCompileContext(sfc, options);
  47592. return processNormalScript(ctx2, scopeId);
  47593. }
  47594. if (scriptSetupLang && !isJSOrTS) {
  47595. return scriptSetup;
  47596. }
  47597. const ctx = new ScriptCompileContext(sfc, options);
  47598. const scriptBindings = /* @__PURE__ */ Object.create(null);
  47599. const setupBindings = /* @__PURE__ */ Object.create(null);
  47600. let defaultExport;
  47601. let hasAwait = false;
  47602. let hasInlinedSsrRenderFn = false;
  47603. const startOffset = ctx.startOffset;
  47604. const endOffset = ctx.endOffset;
  47605. const scriptStartOffset = script && script.loc.start.offset;
  47606. const scriptEndOffset = script && script.loc.end.offset;
  47607. function hoistNode(node) {
  47608. const start = node.start + startOffset;
  47609. let end = node.end + startOffset;
  47610. if (node.trailingComments && node.trailingComments.length > 0) {
  47611. const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
  47612. end = lastCommentNode.end + startOffset;
  47613. }
  47614. while (end <= source.length) {
  47615. if (!/\s/.test(source.charAt(end))) {
  47616. break;
  47617. }
  47618. end++;
  47619. }
  47620. ctx.s.move(start, end, 0);
  47621. }
  47622. function registerUserImport(source2, local, imported, isType, isFromSetup, needTemplateUsageCheck) {
  47623. let isUsedInTemplate = needTemplateUsageCheck;
  47624. if (needTemplateUsageCheck && ctx.isTS && sfc.template && !sfc.template.src && !sfc.template.lang) {
  47625. isUsedInTemplate = isImportUsed(local, sfc);
  47626. }
  47627. ctx.userImports[local] = {
  47628. isType,
  47629. imported,
  47630. local,
  47631. source: source2,
  47632. isFromSetup,
  47633. isUsedInTemplate
  47634. };
  47635. }
  47636. function checkInvalidScopeReference(node, method) {
  47637. if (!node) return;
  47638. walkIdentifiers(node, (id) => {
  47639. const binding = setupBindings[id.name];
  47640. if (binding && binding !== "literal-const") {
  47641. ctx.error(
  47642. `\`${method}()\` in <script setup> cannot reference locally declared variables because it will be hoisted outside of the setup() function. If your component options require initialization in the module scope, use a separate normal <script> to export the options instead.`,
  47643. id
  47644. );
  47645. }
  47646. });
  47647. }
  47648. const scriptAst = ctx.scriptAst;
  47649. const scriptSetupAst = ctx.scriptSetupAst;
  47650. if (scriptAst) {
  47651. for (const node of scriptAst.body) {
  47652. if (node.type === "ImportDeclaration") {
  47653. for (const specifier of node.specifiers) {
  47654. const imported = getImportedName(specifier);
  47655. registerUserImport(
  47656. node.source.value,
  47657. specifier.local.name,
  47658. imported,
  47659. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  47660. false,
  47661. !options.inlineTemplate
  47662. );
  47663. }
  47664. }
  47665. }
  47666. }
  47667. for (const node of scriptSetupAst.body) {
  47668. if (node.type === "ImportDeclaration") {
  47669. hoistNode(node);
  47670. let removed = 0;
  47671. const removeSpecifier = (i) => {
  47672. const removeLeft = i > removed;
  47673. removed++;
  47674. const current = node.specifiers[i];
  47675. const next = node.specifiers[i + 1];
  47676. ctx.s.remove(
  47677. removeLeft ? node.specifiers[i - 1].end + startOffset : current.start + startOffset,
  47678. next && !removeLeft ? next.start + startOffset : current.end + startOffset
  47679. );
  47680. };
  47681. for (let i = 0; i < node.specifiers.length; i++) {
  47682. const specifier = node.specifiers[i];
  47683. const local = specifier.local.name;
  47684. const imported = getImportedName(specifier);
  47685. const source2 = node.source.value;
  47686. const existing = ctx.userImports[local];
  47687. if (source2 === "vue" && MACROS.includes(imported)) {
  47688. if (local === imported) {
  47689. warnOnce$1(
  47690. `\`${imported}\` is a compiler macro and no longer needs to be imported.`
  47691. );
  47692. } else {
  47693. ctx.error(
  47694. `\`${imported}\` is a compiler macro and cannot be aliased to a different name.`,
  47695. specifier
  47696. );
  47697. }
  47698. removeSpecifier(i);
  47699. } else if (existing) {
  47700. if (existing.source === source2 && existing.imported === imported) {
  47701. removeSpecifier(i);
  47702. } else {
  47703. ctx.error(
  47704. `different imports aliased to same local name.`,
  47705. specifier
  47706. );
  47707. }
  47708. } else {
  47709. registerUserImport(
  47710. source2,
  47711. local,
  47712. imported,
  47713. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  47714. true,
  47715. !options.inlineTemplate
  47716. );
  47717. }
  47718. }
  47719. if (node.specifiers.length && removed === node.specifiers.length) {
  47720. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  47721. }
  47722. }
  47723. }
  47724. const vueImportAliases = {};
  47725. for (const key in ctx.userImports) {
  47726. const { source: source2, imported, local } = ctx.userImports[key];
  47727. if (source2 === "vue") vueImportAliases[imported] = local;
  47728. }
  47729. if (script && scriptAst) {
  47730. for (const node of scriptAst.body) {
  47731. if (node.type === "ExportDefaultDeclaration") {
  47732. defaultExport = node;
  47733. let optionProperties;
  47734. if (defaultExport.declaration.type === "ObjectExpression") {
  47735. optionProperties = defaultExport.declaration.properties;
  47736. } else if (defaultExport.declaration.type === "CallExpression" && defaultExport.declaration.arguments[0] && defaultExport.declaration.arguments[0].type === "ObjectExpression") {
  47737. optionProperties = defaultExport.declaration.arguments[0].properties;
  47738. }
  47739. if (optionProperties) {
  47740. for (const p of optionProperties) {
  47741. if (p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name") {
  47742. ctx.hasDefaultExportName = true;
  47743. }
  47744. if ((p.type === "ObjectMethod" || p.type === "ObjectProperty") && p.key.type === "Identifier" && p.key.name === "render") {
  47745. ctx.hasDefaultExportRender = true;
  47746. }
  47747. }
  47748. }
  47749. const start = node.start + scriptStartOffset;
  47750. const end = node.declaration.start + scriptStartOffset;
  47751. ctx.s.overwrite(start, end, `const ${normalScriptDefaultVar} = `);
  47752. } else if (node.type === "ExportNamedDeclaration") {
  47753. const defaultSpecifier = node.specifiers.find(
  47754. (s) => s.exported.type === "Identifier" && s.exported.name === "default"
  47755. );
  47756. if (defaultSpecifier) {
  47757. defaultExport = node;
  47758. if (node.specifiers.length > 1) {
  47759. ctx.s.remove(
  47760. defaultSpecifier.start + scriptStartOffset,
  47761. defaultSpecifier.end + scriptStartOffset
  47762. );
  47763. } else {
  47764. ctx.s.remove(
  47765. node.start + scriptStartOffset,
  47766. node.end + scriptStartOffset
  47767. );
  47768. }
  47769. if (node.source) {
  47770. ctx.s.prepend(
  47771. `import { ${defaultSpecifier.local.name} as ${normalScriptDefaultVar} } from '${node.source.value}'
  47772. `
  47773. );
  47774. } else {
  47775. ctx.s.appendLeft(
  47776. scriptEndOffset,
  47777. `
  47778. const ${normalScriptDefaultVar} = ${defaultSpecifier.local.name}
  47779. `
  47780. );
  47781. }
  47782. }
  47783. if (node.declaration) {
  47784. walkDeclaration(
  47785. "script",
  47786. node.declaration,
  47787. scriptBindings,
  47788. vueImportAliases,
  47789. hoistStatic
  47790. );
  47791. }
  47792. } else if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  47793. walkDeclaration(
  47794. "script",
  47795. node,
  47796. scriptBindings,
  47797. vueImportAliases,
  47798. hoistStatic
  47799. );
  47800. }
  47801. }
  47802. if (scriptStartOffset > startOffset) {
  47803. if (!/\n$/.test(script.content.trim())) {
  47804. ctx.s.appendLeft(scriptEndOffset, `
  47805. `);
  47806. }
  47807. ctx.s.move(scriptStartOffset, scriptEndOffset, 0);
  47808. }
  47809. }
  47810. for (const node of scriptSetupAst.body) {
  47811. if (node.type === "ExpressionStatement") {
  47812. const expr = unwrapTSNode(node.expression);
  47813. if (processDefineProps(ctx, expr) || processDefineEmits(ctx, expr) || processDefineOptions(ctx, expr) || processDefineSlots(ctx, expr)) {
  47814. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  47815. } else if (processDefineExpose(ctx, expr)) {
  47816. const callee = expr.callee;
  47817. ctx.s.overwrite(
  47818. callee.start + startOffset,
  47819. callee.end + startOffset,
  47820. "__expose"
  47821. );
  47822. } else {
  47823. processDefineModel(ctx, expr);
  47824. }
  47825. }
  47826. if (node.type === "VariableDeclaration" && !node.declare) {
  47827. const total = node.declarations.length;
  47828. let left = total;
  47829. let lastNonRemoved;
  47830. for (let i = 0; i < total; i++) {
  47831. const decl = node.declarations[i];
  47832. const init = decl.init && unwrapTSNode(decl.init);
  47833. if (init) {
  47834. if (processDefineOptions(ctx, init)) {
  47835. ctx.error(
  47836. `${DEFINE_OPTIONS}() has no returning value, it cannot be assigned.`,
  47837. node
  47838. );
  47839. }
  47840. const isDefineProps = processDefineProps(ctx, init, decl.id);
  47841. if (ctx.propsDestructureRestId) {
  47842. setupBindings[ctx.propsDestructureRestId] = "setup-reactive-const";
  47843. }
  47844. const isDefineEmits = !isDefineProps && processDefineEmits(ctx, init, decl.id);
  47845. !isDefineEmits && (processDefineSlots(ctx, init, decl.id) || processDefineModel(ctx, init, decl.id));
  47846. if (isDefineProps && !ctx.propsDestructureRestId && ctx.propsDestructureDecl) {
  47847. if (left === 1) {
  47848. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  47849. } else {
  47850. let start = decl.start + startOffset;
  47851. let end = decl.end + startOffset;
  47852. if (i === total - 1) {
  47853. start = node.declarations[lastNonRemoved].end + startOffset;
  47854. } else {
  47855. end = node.declarations[i + 1].start + startOffset;
  47856. }
  47857. ctx.s.remove(start, end);
  47858. left--;
  47859. }
  47860. } else if (isDefineEmits) {
  47861. ctx.s.overwrite(
  47862. startOffset + init.start,
  47863. startOffset + init.end,
  47864. "__emit"
  47865. );
  47866. } else {
  47867. lastNonRemoved = i;
  47868. }
  47869. }
  47870. }
  47871. }
  47872. let isAllLiteral = false;
  47873. if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  47874. isAllLiteral = walkDeclaration(
  47875. "scriptSetup",
  47876. node,
  47877. setupBindings,
  47878. vueImportAliases,
  47879. hoistStatic,
  47880. !!ctx.propsDestructureDecl
  47881. );
  47882. }
  47883. if (hoistStatic && isAllLiteral) {
  47884. hoistNode(node);
  47885. }
  47886. if (node.type === "VariableDeclaration" && !node.declare || node.type.endsWith("Statement")) {
  47887. const scope = [scriptSetupAst.body];
  47888. walk$2(node, {
  47889. enter(child, parent) {
  47890. if (isFunctionType(child)) {
  47891. this.skip();
  47892. }
  47893. if (child.type === "BlockStatement") {
  47894. scope.push(child.body);
  47895. }
  47896. if (child.type === "AwaitExpression") {
  47897. hasAwait = true;
  47898. const currentScope = scope[scope.length - 1];
  47899. const needsSemi = currentScope.some((n, i) => {
  47900. return (scope.length === 1 || i > 0) && n.type === "ExpressionStatement" && n.start === child.start;
  47901. });
  47902. processAwait(
  47903. ctx,
  47904. child,
  47905. needsSemi,
  47906. parent.type === "ExpressionStatement"
  47907. );
  47908. }
  47909. },
  47910. exit(node2) {
  47911. if (node2.type === "BlockStatement") scope.pop();
  47912. }
  47913. });
  47914. }
  47915. if (node.type === "ExportNamedDeclaration" && node.exportKind !== "type" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration") {
  47916. ctx.error(
  47917. `<script setup> cannot contain ES module exports. If you are using a previous version of <script setup>, please consult the updated RFC at https://github.com/vuejs/rfcs/pull/227.`,
  47918. node
  47919. );
  47920. }
  47921. if (ctx.isTS) {
  47922. if (node.type.startsWith("TS") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "VariableDeclaration" && node.declare) {
  47923. if (node.type !== "TSEnumDeclaration") {
  47924. hoistNode(node);
  47925. }
  47926. }
  47927. }
  47928. }
  47929. if (ctx.propsDestructureDecl) {
  47930. transformDestructuredProps(ctx, vueImportAliases);
  47931. }
  47932. checkInvalidScopeReference(ctx.propsRuntimeDecl, DEFINE_PROPS);
  47933. checkInvalidScopeReference(ctx.propsRuntimeDefaults, DEFINE_PROPS);
  47934. checkInvalidScopeReference(ctx.propsDestructureDecl, DEFINE_PROPS);
  47935. checkInvalidScopeReference(ctx.emitsRuntimeDecl, DEFINE_EMITS);
  47936. checkInvalidScopeReference(ctx.optionsRuntimeDecl, DEFINE_OPTIONS);
  47937. for (const { runtimeOptionNodes } of Object.values(ctx.modelDecls)) {
  47938. for (const node of runtimeOptionNodes) {
  47939. checkInvalidScopeReference(node, DEFINE_MODEL);
  47940. }
  47941. }
  47942. if (script) {
  47943. if (startOffset < scriptStartOffset) {
  47944. ctx.s.remove(0, startOffset);
  47945. ctx.s.remove(endOffset, scriptStartOffset);
  47946. ctx.s.remove(scriptEndOffset, source.length);
  47947. } else {
  47948. ctx.s.remove(0, scriptStartOffset);
  47949. ctx.s.remove(scriptEndOffset, startOffset);
  47950. ctx.s.remove(endOffset, source.length);
  47951. }
  47952. } else {
  47953. ctx.s.remove(0, startOffset);
  47954. ctx.s.remove(endOffset, source.length);
  47955. }
  47956. if (scriptAst) {
  47957. Object.assign(ctx.bindingMetadata, analyzeScriptBindings(scriptAst.body));
  47958. }
  47959. for (const [key, { isType, imported, source: source2 }] of Object.entries(
  47960. ctx.userImports
  47961. )) {
  47962. if (isType) continue;
  47963. ctx.bindingMetadata[key] = imported === "*" || imported === "default" && source2.endsWith(".vue") || source2 === "vue" ? "setup-const" : "setup-maybe-ref";
  47964. }
  47965. for (const key in scriptBindings) {
  47966. ctx.bindingMetadata[key] = scriptBindings[key];
  47967. }
  47968. for (const key in setupBindings) {
  47969. ctx.bindingMetadata[key] = setupBindings[key];
  47970. }
  47971. if (sfc.template && !sfc.template.src && sfc.template.ast) {
  47972. const vModelIds = resolveTemplateVModelIdentifiers(sfc);
  47973. if (vModelIds.size) {
  47974. const toDemote = /* @__PURE__ */ new Set();
  47975. for (const id of vModelIds) {
  47976. if (setupBindings[id] === "setup-reactive-const") {
  47977. toDemote.add(id);
  47978. }
  47979. }
  47980. if (toDemote.size) {
  47981. for (const node of scriptSetupAst.body) {
  47982. if (node.type === "VariableDeclaration" && node.kind === "const" && !node.declare) {
  47983. const demotedInDecl = [];
  47984. for (const decl of node.declarations) {
  47985. if (decl.id.type === "Identifier" && toDemote.has(decl.id.name)) {
  47986. demotedInDecl.push(decl.id.name);
  47987. }
  47988. }
  47989. if (demotedInDecl.length) {
  47990. ctx.s.overwrite(
  47991. node.start + startOffset,
  47992. node.start + startOffset + "const".length,
  47993. "let"
  47994. );
  47995. for (const id of demotedInDecl) {
  47996. setupBindings[id] = "setup-let";
  47997. ctx.bindingMetadata[id] = "setup-let";
  47998. warnOnce$1(
  47999. `\`v-model\` cannot update a \`const\` reactive binding \`${id}\`. The compiler has transformed it to \`let\` to make the update work.`
  48000. );
  48001. }
  48002. }
  48003. }
  48004. }
  48005. }
  48006. }
  48007. }
  48008. if (sfc.cssVars.length && // no need to do this when targeting SSR
  48009. !((_a = options.templateOptions) == null ? void 0 : _a.ssr)) {
  48010. ctx.helperImports.add(CSS_VARS_HELPER);
  48011. ctx.helperImports.add("unref");
  48012. ctx.s.prependLeft(
  48013. startOffset,
  48014. `
  48015. ${genCssVarsCode(
  48016. sfc.cssVars,
  48017. ctx.bindingMetadata,
  48018. scopeId,
  48019. !!options.isProd
  48020. )}
  48021. `
  48022. );
  48023. }
  48024. let args = `__props`;
  48025. if (ctx.propsTypeDecl) {
  48026. args += `: any`;
  48027. }
  48028. if (ctx.propsDecl) {
  48029. if (ctx.propsDestructureRestId) {
  48030. ctx.s.overwrite(
  48031. startOffset + ctx.propsCall.start,
  48032. startOffset + ctx.propsCall.end,
  48033. `${ctx.helper(`createPropsRestProxy`)}(__props, ${JSON.stringify(
  48034. Object.keys(ctx.propsDestructuredBindings)
  48035. )})`
  48036. );
  48037. ctx.s.overwrite(
  48038. startOffset + ctx.propsDestructureDecl.start,
  48039. startOffset + ctx.propsDestructureDecl.end,
  48040. ctx.propsDestructureRestId
  48041. );
  48042. } else if (!ctx.propsDestructureDecl) {
  48043. ctx.s.overwrite(
  48044. startOffset + ctx.propsCall.start,
  48045. startOffset + ctx.propsCall.end,
  48046. "__props"
  48047. );
  48048. }
  48049. }
  48050. if (hasAwait) {
  48051. const any = ctx.isTS ? `: any` : ``;
  48052. ctx.s.prependLeft(startOffset, `
  48053. let __temp${any}, __restore${any}
  48054. `);
  48055. }
  48056. const destructureElements = ctx.hasDefineExposeCall || !options.inlineTemplate ? [`expose: __expose`] : [];
  48057. if (ctx.emitDecl) {
  48058. destructureElements.push(`emit: __emit`);
  48059. }
  48060. if (destructureElements.length) {
  48061. args += `, { ${destructureElements.join(", ")} }`;
  48062. }
  48063. let templateMap;
  48064. let returned;
  48065. const propsDecl = genRuntimeProps(ctx);
  48066. if (!options.inlineTemplate || !sfc.template && ctx.hasDefaultExportRender) {
  48067. const allBindings = __spreadValues$1(__spreadValues$1({}, scriptBindings), setupBindings);
  48068. for (const key in ctx.userImports) {
  48069. if (!ctx.userImports[key].isType && ctx.userImports[key].isUsedInTemplate) {
  48070. allBindings[key] = true;
  48071. }
  48072. }
  48073. returned = `{ `;
  48074. for (const key in allBindings) {
  48075. if (allBindings[key] === true && ctx.userImports[key].source !== "vue" && !ctx.userImports[key].source.endsWith(".vue")) {
  48076. returned += `get ${key}() { return ${key} }, `;
  48077. } else if (ctx.bindingMetadata[key] === "setup-let") {
  48078. const setArg = key === "v" ? `_v` : `v`;
  48079. returned += `get ${key}() { return ${key} }, set ${key}(${setArg}) { ${key} = ${setArg} }, `;
  48080. } else {
  48081. returned += `${key}, `;
  48082. }
  48083. }
  48084. returned = returned.replace(/, $/, "") + ` }`;
  48085. } else {
  48086. if (sfc.template && !sfc.template.src) {
  48087. if (options.templateOptions && options.templateOptions.ssr) {
  48088. hasInlinedSsrRenderFn = true;
  48089. }
  48090. const { code, ast, preamble, tips, errors, map: map2 } = compileTemplate(__spreadProps(__spreadValues$1({
  48091. filename,
  48092. ast: sfc.template.ast,
  48093. source: sfc.template.content,
  48094. inMap: sfc.template.map
  48095. }, options.templateOptions), {
  48096. id: scopeId,
  48097. scoped: sfc.styles.some((s) => s.scoped),
  48098. isProd: options.isProd,
  48099. ssrCssVars: sfc.cssVars,
  48100. compilerOptions: __spreadProps(__spreadValues$1({}, options.templateOptions && options.templateOptions.compilerOptions), {
  48101. inline: true,
  48102. isTS: ctx.isTS,
  48103. bindingMetadata: ctx.bindingMetadata
  48104. })
  48105. }));
  48106. templateMap = map2;
  48107. if (tips.length) {
  48108. tips.forEach(warnOnce$1);
  48109. }
  48110. const err = errors[0];
  48111. if (typeof err === "string") {
  48112. throw new Error(err);
  48113. } else if (err) {
  48114. if (err.loc) {
  48115. err.message += `
  48116. ` + sfc.filename + "\n" + generateCodeFrame(
  48117. source,
  48118. err.loc.start.offset,
  48119. err.loc.end.offset
  48120. ) + `
  48121. `;
  48122. }
  48123. throw err;
  48124. }
  48125. if (preamble) {
  48126. ctx.s.prepend(preamble);
  48127. }
  48128. if (ast && ast.helpers.has(UNREF)) {
  48129. ctx.helperImports.delete("unref");
  48130. }
  48131. returned = code;
  48132. } else {
  48133. returned = `() => {}`;
  48134. }
  48135. }
  48136. if (!options.inlineTemplate && true) {
  48137. ctx.s.appendRight(
  48138. endOffset,
  48139. `
  48140. const __returned__ = ${returned}
  48141. Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })
  48142. return __returned__
  48143. }
  48144. `
  48145. );
  48146. } else {
  48147. ctx.s.appendRight(endOffset, `
  48148. return ${returned}
  48149. }
  48150. `);
  48151. }
  48152. const genDefaultAs = options.genDefaultAs ? `const ${options.genDefaultAs} =` : `export default`;
  48153. let runtimeOptions = ``;
  48154. if (!ctx.hasDefaultExportName && filename && filename !== DEFAULT_FILENAME) {
  48155. const match = filename.match(/([^/\\]+)\.\w+$/);
  48156. if (match) {
  48157. runtimeOptions += `
  48158. __name: '${match[1]}',`;
  48159. }
  48160. }
  48161. if (hasInlinedSsrRenderFn) {
  48162. runtimeOptions += `
  48163. __ssrInlineRender: true,`;
  48164. }
  48165. if (propsDecl) runtimeOptions += `
  48166. props: ${propsDecl},`;
  48167. const emitsDecl = genRuntimeEmits(ctx);
  48168. if (emitsDecl) runtimeOptions += `
  48169. emits: ${emitsDecl},`;
  48170. let definedOptions = "";
  48171. if (ctx.optionsRuntimeDecl) {
  48172. definedOptions = scriptSetup.content.slice(ctx.optionsRuntimeDecl.start, ctx.optionsRuntimeDecl.end).trim();
  48173. }
  48174. const exposeCall = ctx.hasDefineExposeCall || options.inlineTemplate ? `` : ` __expose();
  48175. `;
  48176. if (ctx.isTS) {
  48177. const def = (defaultExport ? `
  48178. ...${normalScriptDefaultVar},` : ``) + (definedOptions ? `
  48179. ...${definedOptions},` : "");
  48180. ctx.s.prependLeft(
  48181. startOffset,
  48182. `
  48183. ${genDefaultAs} /*@__PURE__*/${ctx.helper(
  48184. `defineComponent`
  48185. )}({${def}${runtimeOptions}
  48186. ${hasAwait ? `async ` : ``}setup(${args}) {
  48187. ${exposeCall}`
  48188. );
  48189. ctx.s.appendRight(endOffset, `})`);
  48190. } else {
  48191. if (defaultExport || definedOptions) {
  48192. ctx.s.prependLeft(
  48193. startOffset,
  48194. `
  48195. ${genDefaultAs} /*@__PURE__*/Object.assign(${defaultExport ? `${normalScriptDefaultVar}, ` : ""}${definedOptions ? `${definedOptions}, ` : ""}{${runtimeOptions}
  48196. ${hasAwait ? `async ` : ``}setup(${args}) {
  48197. ${exposeCall}`
  48198. );
  48199. ctx.s.appendRight(endOffset, `})`);
  48200. } else {
  48201. ctx.s.prependLeft(
  48202. startOffset,
  48203. `
  48204. ${genDefaultAs} {${runtimeOptions}
  48205. ${hasAwait ? `async ` : ``}setup(${args}) {
  48206. ${exposeCall}`
  48207. );
  48208. ctx.s.appendRight(endOffset, `}`);
  48209. }
  48210. }
  48211. if (ctx.helperImports.size > 0) {
  48212. const runtimeModuleName = (_c = (_b = options.templateOptions) == null ? void 0 : _b.compilerOptions) == null ? void 0 : _c.runtimeModuleName;
  48213. const importSrc = runtimeModuleName ? JSON.stringify(runtimeModuleName) : `'vue'`;
  48214. ctx.s.prepend(
  48215. `import { ${[...ctx.helperImports].map((h) => `${h} as _${h}`).join(", ")} } from ${importSrc}
  48216. `
  48217. );
  48218. }
  48219. const content = ctx.s.toString();
  48220. let map = options.sourceMap !== false ? ctx.s.generateMap({
  48221. source: filename,
  48222. hires: true,
  48223. includeContent: true
  48224. }) : void 0;
  48225. if (templateMap && map) {
  48226. const offset = content.indexOf(returned);
  48227. const templateLineOffset = content.slice(0, offset).split(/\r?\n/).length - 1;
  48228. map = mergeSourceMaps(map, templateMap, templateLineOffset);
  48229. }
  48230. return __spreadProps(__spreadValues$1({}, scriptSetup), {
  48231. bindings: ctx.bindingMetadata,
  48232. imports: ctx.userImports,
  48233. content,
  48234. map,
  48235. scriptAst: scriptAst == null ? void 0 : scriptAst.body,
  48236. scriptSetupAst: scriptSetupAst == null ? void 0 : scriptSetupAst.body,
  48237. deps: ctx.deps ? [...ctx.deps] : void 0
  48238. });
  48239. }
  48240. function registerBinding(bindings, node, type) {
  48241. bindings[node.name] = type;
  48242. }
  48243. function walkDeclaration(from, node, bindings, userImportAliases, hoistStatic, isPropsDestructureEnabled = false) {
  48244. let isAllLiteral = false;
  48245. if (node.type === "VariableDeclaration") {
  48246. const isConst = node.kind === "const";
  48247. isAllLiteral = isConst && node.declarations.every(
  48248. (decl) => decl.id.type === "Identifier" && isStaticNode(decl.init)
  48249. );
  48250. for (const { id, init: _init } of node.declarations) {
  48251. const init = _init && unwrapTSNode(_init);
  48252. const isConstMacroCall = isConst && isCallOf(
  48253. init,
  48254. (c) => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS || c === DEFINE_SLOTS
  48255. );
  48256. if (id.type === "Identifier") {
  48257. let bindingType;
  48258. const userReactiveBinding = userImportAliases["reactive"];
  48259. if ((hoistStatic || from === "script") && (isAllLiteral || isConst && isStaticNode(init))) {
  48260. bindingType = "literal-const";
  48261. } else if (isCallOf(init, userReactiveBinding)) {
  48262. bindingType = isConst ? "setup-reactive-const" : "setup-let";
  48263. } else if (
  48264. // if a declaration is a const literal, we can mark it so that
  48265. // the generated render fn code doesn't need to unref() it
  48266. isConstMacroCall || isConst && canNeverBeRef(init, userReactiveBinding)
  48267. ) {
  48268. bindingType = isCallOf(init, DEFINE_PROPS) ? "setup-reactive-const" : "setup-const";
  48269. } else if (isConst) {
  48270. if (isCallOf(
  48271. init,
  48272. (m) => m === userImportAliases["ref"] || m === userImportAliases["computed"] || m === userImportAliases["shallowRef"] || m === userImportAliases["customRef"] || m === userImportAliases["toRef"] || m === userImportAliases["useTemplateRef"] || m === DEFINE_MODEL
  48273. )) {
  48274. bindingType = "setup-ref";
  48275. } else {
  48276. bindingType = "setup-maybe-ref";
  48277. }
  48278. } else {
  48279. bindingType = "setup-let";
  48280. }
  48281. registerBinding(bindings, id, bindingType);
  48282. } else {
  48283. if (isCallOf(init, DEFINE_PROPS) && isPropsDestructureEnabled) {
  48284. continue;
  48285. }
  48286. if (id.type === "ObjectPattern") {
  48287. walkObjectPattern(id, bindings, isConst, isConstMacroCall);
  48288. } else if (id.type === "ArrayPattern") {
  48289. walkArrayPattern(id, bindings, isConst, isConstMacroCall);
  48290. }
  48291. }
  48292. }
  48293. } else if (node.type === "TSEnumDeclaration") {
  48294. isAllLiteral = node.members.every(
  48295. (member) => !member.initializer || isStaticNode(member.initializer)
  48296. );
  48297. bindings[node.id.name] = isAllLiteral ? "literal-const" : "setup-const";
  48298. } else if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
  48299. bindings[node.id.name] = "setup-const";
  48300. }
  48301. return isAllLiteral;
  48302. }
  48303. function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
  48304. for (const p of node.properties) {
  48305. if (p.type === "ObjectProperty") {
  48306. if (p.key.type === "Identifier" && p.key === p.value) {
  48307. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  48308. registerBinding(bindings, p.key, type);
  48309. } else {
  48310. walkPattern(p.value, bindings, isConst, isDefineCall);
  48311. }
  48312. } else {
  48313. const type = isConst ? "setup-const" : "setup-let";
  48314. registerBinding(bindings, p.argument, type);
  48315. }
  48316. }
  48317. }
  48318. function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
  48319. for (const e of node.elements) {
  48320. e && walkPattern(e, bindings, isConst, isDefineCall);
  48321. }
  48322. }
  48323. function walkPattern(node, bindings, isConst, isDefineCall = false) {
  48324. if (node.type === "Identifier") {
  48325. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  48326. registerBinding(bindings, node, type);
  48327. } else if (node.type === "RestElement") {
  48328. const type = isConst ? "setup-const" : "setup-let";
  48329. registerBinding(bindings, node.argument, type);
  48330. } else if (node.type === "ObjectPattern") {
  48331. walkObjectPattern(node, bindings, isConst);
  48332. } else if (node.type === "ArrayPattern") {
  48333. walkArrayPattern(node, bindings, isConst);
  48334. } else if (node.type === "AssignmentPattern") {
  48335. if (node.left.type === "Identifier") {
  48336. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  48337. registerBinding(bindings, node.left, type);
  48338. } else {
  48339. walkPattern(node.left, bindings, isConst);
  48340. }
  48341. }
  48342. }
  48343. function canNeverBeRef(node, userReactiveImport) {
  48344. if (isCallOf(node, userReactiveImport)) {
  48345. return true;
  48346. }
  48347. switch (node.type) {
  48348. case "UnaryExpression":
  48349. case "BinaryExpression":
  48350. case "ArrayExpression":
  48351. case "ObjectExpression":
  48352. case "FunctionExpression":
  48353. case "ArrowFunctionExpression":
  48354. case "UpdateExpression":
  48355. case "ClassExpression":
  48356. case "TaggedTemplateExpression":
  48357. return true;
  48358. case "SequenceExpression":
  48359. return canNeverBeRef(
  48360. node.expressions[node.expressions.length - 1],
  48361. userReactiveImport
  48362. );
  48363. default:
  48364. if (isLiteralNode(node)) {
  48365. return true;
  48366. }
  48367. return false;
  48368. }
  48369. }
  48370. function isStaticNode(node) {
  48371. node = unwrapTSNode(node);
  48372. switch (node.type) {
  48373. case "UnaryExpression":
  48374. return isStaticNode(node.argument);
  48375. case "LogicalExpression":
  48376. // 1 > 2
  48377. case "BinaryExpression":
  48378. return isStaticNode(node.left) && isStaticNode(node.right);
  48379. case "ConditionalExpression": {
  48380. return isStaticNode(node.test) && isStaticNode(node.consequent) && isStaticNode(node.alternate);
  48381. }
  48382. case "SequenceExpression":
  48383. // (1, 2)
  48384. case "TemplateLiteral":
  48385. return node.expressions.every((expr) => isStaticNode(expr));
  48386. case "ParenthesizedExpression":
  48387. return isStaticNode(node.expression);
  48388. case "StringLiteral":
  48389. case "NumericLiteral":
  48390. case "BooleanLiteral":
  48391. case "NullLiteral":
  48392. case "BigIntLiteral":
  48393. return true;
  48394. }
  48395. return false;
  48396. }
  48397. function mergeSourceMaps(scriptMap, templateMap, templateLineOffset) {
  48398. const generator = new sourceMapExports.SourceMapGenerator();
  48399. const addMapping = (map, lineOffset = 0) => {
  48400. const consumer = new sourceMapExports.SourceMapConsumer(map);
  48401. consumer.sources.forEach((sourceFile) => {
  48402. generator._sources.add(sourceFile);
  48403. const sourceContent = consumer.sourceContentFor(sourceFile);
  48404. if (sourceContent != null) {
  48405. generator.setSourceContent(sourceFile, sourceContent);
  48406. }
  48407. });
  48408. consumer.eachMapping((m) => {
  48409. if (m.originalLine == null) return;
  48410. generator.addMapping({
  48411. generated: {
  48412. line: m.generatedLine + lineOffset,
  48413. column: m.generatedColumn
  48414. },
  48415. original: {
  48416. line: m.originalLine,
  48417. column: m.originalColumn
  48418. },
  48419. source: m.source,
  48420. name: m.name
  48421. });
  48422. });
  48423. };
  48424. addMapping(scriptMap);
  48425. addMapping(templateMap, templateLineOffset);
  48426. generator._sourceRoot = scriptMap.sourceRoot;
  48427. generator._file = scriptMap.file;
  48428. return generator.toJSON();
  48429. }
  48430. var __defProp = Object.defineProperty;
  48431. var __getOwnPropSymbols = Object.getOwnPropertySymbols;
  48432. var __hasOwnProp = Object.prototype.hasOwnProperty;
  48433. var __propIsEnum = Object.prototype.propertyIsEnumerable;
  48434. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  48435. var __spreadValues = (a, b) => {
  48436. for (var prop in b || (b = {}))
  48437. if (__hasOwnProp.call(b, prop))
  48438. __defNormalProp(a, prop, b[prop]);
  48439. if (__getOwnPropSymbols)
  48440. for (var prop of __getOwnPropSymbols(b)) {
  48441. if (__propIsEnum.call(b, prop))
  48442. __defNormalProp(a, prop, b[prop]);
  48443. }
  48444. return a;
  48445. };
  48446. const version = "3.5.35";
  48447. const parseCache = parseCache$1;
  48448. const errorMessages = __spreadValues(__spreadValues({}, errorMessages$1), DOMErrorMessages);
  48449. const walk = walk$2;
  48450. const shouldTransformRef = () => false;
  48451. var parse$4 = libExports.parse;
  48452. export { MagicString, parse$4 as babelParse, compileScript, compileStyle, compileStyleAsync, compileTemplate, errorMessages, extractIdentifiers$1 as extractIdentifiers, extractRuntimeEmits, extractRuntimeProps, generateCodeFrame, inferRuntimeType, invalidateTypeCache, isInDestructureAssignment, isStaticProperty, parse$2 as parse, parseCache, registerTS, resolveTypeElements, rewriteDefault, rewriteDefaultAST, shouldTransformRef, version, walk, walkIdentifiers };