compiler-sfc.esm-browser.js 1.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886
  1. /**
  2. * @vue/compiler-sfc v3.5.42
  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,inert,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected`
  212. );
  213. function includeBooleanAttr(value) {
  214. return !!value || value === "";
  215. }
  216. const unsafeAttrCharRE = /[>/="'\u0009\u000a\u000c\u000d\u0020]/;
  217. const attrValidationCache = {};
  218. function isSSRSafeAttrName(name) {
  219. if (attrValidationCache.hasOwnProperty(name)) {
  220. return attrValidationCache[name];
  221. }
  222. const isUnsafe = unsafeAttrCharRE.test(name);
  223. if (isUnsafe) {
  224. console.error(`unsafe attribute name: ${name}`);
  225. }
  226. return attrValidationCache[name] = !isUnsafe;
  227. }
  228. const propsToAttrMap = {
  229. acceptCharset: "accept-charset",
  230. className: "class",
  231. htmlFor: "for",
  232. httpEquiv: "http-equiv"
  233. };
  234. const isKnownHtmlAttr = /* @__PURE__ */ makeMap(
  235. `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`
  236. );
  237. const isKnownSvgAttr = /* @__PURE__ */ makeMap(
  238. `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`
  239. );
  240. const isKnownMathMLAttr = /* @__PURE__ */ makeMap(
  241. `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`
  242. );
  243. const escapeRE = /["'&<>]/;
  244. function escapeHtml(string) {
  245. const str = "" + string;
  246. const match = escapeRE.exec(str);
  247. if (!match) {
  248. return str;
  249. }
  250. let html = "";
  251. let escaped;
  252. let index;
  253. let lastIndex = 0;
  254. for (index = match.index; index < str.length; index++) {
  255. switch (str.charCodeAt(index)) {
  256. case 34:
  257. escaped = "&quot;";
  258. break;
  259. case 38:
  260. escaped = "&amp;";
  261. break;
  262. case 39:
  263. escaped = "&#39;";
  264. break;
  265. case 60:
  266. escaped = "&lt;";
  267. break;
  268. case 62:
  269. escaped = "&gt;";
  270. break;
  271. default:
  272. continue;
  273. }
  274. if (lastIndex !== index) {
  275. html += str.slice(lastIndex, index);
  276. }
  277. lastIndex = index + 1;
  278. html += escaped;
  279. }
  280. return lastIndex !== index ? html + str.slice(lastIndex, index) : html;
  281. }
  282. const cssVarNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/g;
  283. function getEscapedCssVarName(key, doubleEscape) {
  284. return key.replace(
  285. cssVarNameEscapeSymbolsRE,
  286. (s) => doubleEscape ? s === '"' ? '\\\\\\"' : `\\\\${s}` : `\\${s}`
  287. );
  288. }
  289. const isRef = (val) => {
  290. return !!(val && val["__v_isRef"] === true);
  291. };
  292. const toDisplayString = (val) => {
  293. 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);
  294. };
  295. const replacer = (_key, val) => {
  296. if (isRef(val)) {
  297. return replacer(_key, val.value);
  298. } else if (isMap(val)) {
  299. return {
  300. [`Map(${val.size})`]: [...val.entries()].reduce(
  301. (entries, [key, val2], i) => {
  302. entries[stringifySymbol(key, i) + " =>"] = val2;
  303. return entries;
  304. },
  305. {}
  306. )
  307. };
  308. } else if (isSet(val)) {
  309. return {
  310. [`Set(${val.size})`]: [...val.values()].map((v) => stringifySymbol(v))
  311. };
  312. } else if (isSymbol$1(val)) {
  313. return stringifySymbol(val);
  314. } else if (isObject$2(val) && !isArray$3(val) && !isPlainObject(val)) {
  315. return String(val);
  316. }
  317. return val;
  318. };
  319. const stringifySymbol = (v, i = "") => {
  320. var _a;
  321. return (
  322. // Symbol.description in es2019+ so we need to cast here to pass
  323. // the lib: es2016 check
  324. isSymbol$1(v) ? `Symbol(${(_a = v.description) != null ? _a : i})` : v
  325. );
  326. };
  327. const FRAGMENT = /* @__PURE__ */ Symbol(`Fragment` );
  328. const TELEPORT = /* @__PURE__ */ Symbol(`Teleport` );
  329. const SUSPENSE = /* @__PURE__ */ Symbol(`Suspense` );
  330. const KEEP_ALIVE = /* @__PURE__ */ Symbol(`KeepAlive` );
  331. const BASE_TRANSITION = /* @__PURE__ */ Symbol(
  332. `BaseTransition`
  333. );
  334. const OPEN_BLOCK = /* @__PURE__ */ Symbol(`openBlock` );
  335. const CREATE_BLOCK = /* @__PURE__ */ Symbol(`createBlock` );
  336. const CREATE_ELEMENT_BLOCK = /* @__PURE__ */ Symbol(
  337. `createElementBlock`
  338. );
  339. const CREATE_VNODE = /* @__PURE__ */ Symbol(`createVNode` );
  340. const CREATE_ELEMENT_VNODE = /* @__PURE__ */ Symbol(
  341. `createElementVNode`
  342. );
  343. const CREATE_COMMENT = /* @__PURE__ */ Symbol(
  344. `createCommentVNode`
  345. );
  346. const CREATE_TEXT = /* @__PURE__ */ Symbol(
  347. `createTextVNode`
  348. );
  349. const CREATE_STATIC = /* @__PURE__ */ Symbol(
  350. `createStaticVNode`
  351. );
  352. const RESOLVE_COMPONENT = /* @__PURE__ */ Symbol(
  353. `resolveComponent`
  354. );
  355. const RESOLVE_DYNAMIC_COMPONENT = /* @__PURE__ */ Symbol(
  356. `resolveDynamicComponent`
  357. );
  358. const RESOLVE_DIRECTIVE = /* @__PURE__ */ Symbol(
  359. `resolveDirective`
  360. );
  361. const RESOLVE_FILTER = /* @__PURE__ */ Symbol(
  362. `resolveFilter`
  363. );
  364. const WITH_DIRECTIVES = /* @__PURE__ */ Symbol(
  365. `withDirectives`
  366. );
  367. const RENDER_LIST = /* @__PURE__ */ Symbol(`renderList` );
  368. const RENDER_SLOT = /* @__PURE__ */ Symbol(`renderSlot` );
  369. const CREATE_SLOTS = /* @__PURE__ */ Symbol(`createSlots` );
  370. const TO_DISPLAY_STRING = /* @__PURE__ */ Symbol(
  371. `toDisplayString`
  372. );
  373. const MERGE_PROPS = /* @__PURE__ */ Symbol(`mergeProps` );
  374. const NORMALIZE_CLASS = /* @__PURE__ */ Symbol(
  375. `normalizeClass`
  376. );
  377. const NORMALIZE_STYLE = /* @__PURE__ */ Symbol(
  378. `normalizeStyle`
  379. );
  380. const NORMALIZE_PROPS = /* @__PURE__ */ Symbol(
  381. `normalizeProps`
  382. );
  383. const GUARD_REACTIVE_PROPS = /* @__PURE__ */ Symbol(
  384. `guardReactiveProps`
  385. );
  386. const TO_HANDLERS = /* @__PURE__ */ Symbol(`toHandlers` );
  387. const CAMELIZE = /* @__PURE__ */ Symbol(`camelize` );
  388. const CAPITALIZE = /* @__PURE__ */ Symbol(`capitalize` );
  389. const TO_HANDLER_KEY = /* @__PURE__ */ Symbol(
  390. `toHandlerKey`
  391. );
  392. const SET_BLOCK_TRACKING = /* @__PURE__ */ Symbol(
  393. `setBlockTracking`
  394. );
  395. const PUSH_SCOPE_ID = /* @__PURE__ */ Symbol(`pushScopeId` );
  396. const POP_SCOPE_ID = /* @__PURE__ */ Symbol(`popScopeId` );
  397. const WITH_CTX = /* @__PURE__ */ Symbol(`withCtx` );
  398. const UNREF = /* @__PURE__ */ Symbol(`unref` );
  399. const IS_REF = /* @__PURE__ */ Symbol(`isRef` );
  400. const WITH_MEMO = /* @__PURE__ */ Symbol(`withMemo` );
  401. const IS_MEMO_SAME = /* @__PURE__ */ Symbol(`isMemoSame` );
  402. const helperNameMap = {
  403. [FRAGMENT]: `Fragment`,
  404. [TELEPORT]: `Teleport`,
  405. [SUSPENSE]: `Suspense`,
  406. [KEEP_ALIVE]: `KeepAlive`,
  407. [BASE_TRANSITION]: `BaseTransition`,
  408. [OPEN_BLOCK]: `openBlock`,
  409. [CREATE_BLOCK]: `createBlock`,
  410. [CREATE_ELEMENT_BLOCK]: `createElementBlock`,
  411. [CREATE_VNODE]: `createVNode`,
  412. [CREATE_ELEMENT_VNODE]: `createElementVNode`,
  413. [CREATE_COMMENT]: `createCommentVNode`,
  414. [CREATE_TEXT]: `createTextVNode`,
  415. [CREATE_STATIC]: `createStaticVNode`,
  416. [RESOLVE_COMPONENT]: `resolveComponent`,
  417. [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
  418. [RESOLVE_DIRECTIVE]: `resolveDirective`,
  419. [RESOLVE_FILTER]: `resolveFilter`,
  420. [WITH_DIRECTIVES]: `withDirectives`,
  421. [RENDER_LIST]: `renderList`,
  422. [RENDER_SLOT]: `renderSlot`,
  423. [CREATE_SLOTS]: `createSlots`,
  424. [TO_DISPLAY_STRING]: `toDisplayString`,
  425. [MERGE_PROPS]: `mergeProps`,
  426. [NORMALIZE_CLASS]: `normalizeClass`,
  427. [NORMALIZE_STYLE]: `normalizeStyle`,
  428. [NORMALIZE_PROPS]: `normalizeProps`,
  429. [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
  430. [TO_HANDLERS]: `toHandlers`,
  431. [CAMELIZE]: `camelize`,
  432. [CAPITALIZE]: `capitalize`,
  433. [TO_HANDLER_KEY]: `toHandlerKey`,
  434. [SET_BLOCK_TRACKING]: `setBlockTracking`,
  435. [PUSH_SCOPE_ID]: `pushScopeId`,
  436. [POP_SCOPE_ID]: `popScopeId`,
  437. [WITH_CTX]: `withCtx`,
  438. [UNREF]: `unref`,
  439. [IS_REF]: `isRef`,
  440. [WITH_MEMO]: `withMemo`,
  441. [IS_MEMO_SAME]: `isMemoSame`
  442. };
  443. function registerRuntimeHelpers(helpers) {
  444. Object.getOwnPropertySymbols(helpers).forEach((s) => {
  445. helperNameMap[s] = helpers[s];
  446. });
  447. }
  448. const Namespaces = {
  449. "HTML": 0,
  450. "0": "HTML",
  451. "SVG": 1,
  452. "1": "SVG",
  453. "MATH_ML": 2,
  454. "2": "MATH_ML"
  455. };
  456. const NodeTypes = {
  457. "ROOT": 0,
  458. "0": "ROOT",
  459. "ELEMENT": 1,
  460. "1": "ELEMENT",
  461. "TEXT": 2,
  462. "2": "TEXT",
  463. "COMMENT": 3,
  464. "3": "COMMENT",
  465. "SIMPLE_EXPRESSION": 4,
  466. "4": "SIMPLE_EXPRESSION",
  467. "INTERPOLATION": 5,
  468. "5": "INTERPOLATION",
  469. "ATTRIBUTE": 6,
  470. "6": "ATTRIBUTE",
  471. "DIRECTIVE": 7,
  472. "7": "DIRECTIVE",
  473. "COMPOUND_EXPRESSION": 8,
  474. "8": "COMPOUND_EXPRESSION",
  475. "IF": 9,
  476. "9": "IF",
  477. "IF_BRANCH": 10,
  478. "10": "IF_BRANCH",
  479. "FOR": 11,
  480. "11": "FOR",
  481. "TEXT_CALL": 12,
  482. "12": "TEXT_CALL",
  483. "VNODE_CALL": 13,
  484. "13": "VNODE_CALL",
  485. "JS_CALL_EXPRESSION": 14,
  486. "14": "JS_CALL_EXPRESSION",
  487. "JS_OBJECT_EXPRESSION": 15,
  488. "15": "JS_OBJECT_EXPRESSION",
  489. "JS_PROPERTY": 16,
  490. "16": "JS_PROPERTY",
  491. "JS_ARRAY_EXPRESSION": 17,
  492. "17": "JS_ARRAY_EXPRESSION",
  493. "JS_FUNCTION_EXPRESSION": 18,
  494. "18": "JS_FUNCTION_EXPRESSION",
  495. "JS_CONDITIONAL_EXPRESSION": 19,
  496. "19": "JS_CONDITIONAL_EXPRESSION",
  497. "JS_CACHE_EXPRESSION": 20,
  498. "20": "JS_CACHE_EXPRESSION",
  499. "JS_BLOCK_STATEMENT": 21,
  500. "21": "JS_BLOCK_STATEMENT",
  501. "JS_TEMPLATE_LITERAL": 22,
  502. "22": "JS_TEMPLATE_LITERAL",
  503. "JS_IF_STATEMENT": 23,
  504. "23": "JS_IF_STATEMENT",
  505. "JS_ASSIGNMENT_EXPRESSION": 24,
  506. "24": "JS_ASSIGNMENT_EXPRESSION",
  507. "JS_SEQUENCE_EXPRESSION": 25,
  508. "25": "JS_SEQUENCE_EXPRESSION",
  509. "JS_RETURN_STATEMENT": 26,
  510. "26": "JS_RETURN_STATEMENT"
  511. };
  512. const ElementTypes = {
  513. "ELEMENT": 0,
  514. "0": "ELEMENT",
  515. "COMPONENT": 1,
  516. "1": "COMPONENT",
  517. "SLOT": 2,
  518. "2": "SLOT",
  519. "TEMPLATE": 3,
  520. "3": "TEMPLATE"
  521. };
  522. const ConstantTypes = {
  523. "NOT_CONSTANT": 0,
  524. "0": "NOT_CONSTANT",
  525. "CAN_SKIP_PATCH": 1,
  526. "1": "CAN_SKIP_PATCH",
  527. "CAN_CACHE": 2,
  528. "2": "CAN_CACHE",
  529. "CAN_STRINGIFY": 3,
  530. "3": "CAN_STRINGIFY"
  531. };
  532. const locStub = {
  533. start: { line: 1, column: 1, offset: 0 },
  534. end: { line: 1, column: 1, offset: 0 },
  535. source: ""
  536. };
  537. function createRoot(children, source = "") {
  538. return {
  539. type: 0,
  540. source,
  541. children,
  542. helpers: /* @__PURE__ */ new Set(),
  543. components: [],
  544. directives: [],
  545. hoists: [],
  546. imports: [],
  547. cached: [],
  548. temps: 0,
  549. codegenNode: void 0,
  550. loc: locStub
  551. };
  552. }
  553. function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) {
  554. if (context) {
  555. if (isBlock) {
  556. context.helper(OPEN_BLOCK);
  557. context.helper(getVNodeBlockHelper(context.inSSR, isComponent));
  558. } else {
  559. context.helper(getVNodeHelper(context.inSSR, isComponent));
  560. }
  561. if (directives) {
  562. context.helper(WITH_DIRECTIVES);
  563. }
  564. }
  565. return {
  566. type: 13,
  567. tag,
  568. props,
  569. children,
  570. patchFlag,
  571. dynamicProps,
  572. directives,
  573. isBlock,
  574. disableTracking,
  575. isComponent,
  576. loc
  577. };
  578. }
  579. function createArrayExpression(elements, loc = locStub) {
  580. return {
  581. type: 17,
  582. loc,
  583. elements
  584. };
  585. }
  586. function createObjectExpression(properties, loc = locStub) {
  587. return {
  588. type: 15,
  589. loc,
  590. properties
  591. };
  592. }
  593. function createObjectProperty(key, value) {
  594. return {
  595. type: 16,
  596. loc: locStub,
  597. key: isString$1(key) ? createSimpleExpression(key, true) : key,
  598. value
  599. };
  600. }
  601. function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0) {
  602. return {
  603. type: 4,
  604. loc,
  605. content,
  606. isStatic,
  607. constType: isStatic ? 3 : constType
  608. };
  609. }
  610. function createInterpolation(content, loc) {
  611. return {
  612. type: 5,
  613. loc,
  614. content: isString$1(content) ? createSimpleExpression(content, false, loc) : content
  615. };
  616. }
  617. function createCompoundExpression(children, loc = locStub) {
  618. return {
  619. type: 8,
  620. loc,
  621. children
  622. };
  623. }
  624. function createCallExpression(callee, args = [], loc = locStub) {
  625. return {
  626. type: 14,
  627. loc,
  628. callee,
  629. arguments: args
  630. };
  631. }
  632. function createFunctionExpression(params, returns = void 0, newline = false, isSlot = false, loc = locStub) {
  633. return {
  634. type: 18,
  635. params,
  636. returns,
  637. newline,
  638. isSlot,
  639. loc
  640. };
  641. }
  642. function createConditionalExpression(test, consequent, alternate, newline = true) {
  643. return {
  644. type: 19,
  645. test,
  646. consequent,
  647. alternate,
  648. newline,
  649. loc: locStub
  650. };
  651. }
  652. function createCacheExpression(index, value, needPauseTracking = false, inVOnce = false) {
  653. return {
  654. type: 20,
  655. index,
  656. value,
  657. needPauseTracking,
  658. inVOnce,
  659. needArraySpread: false,
  660. loc: locStub
  661. };
  662. }
  663. function createBlockStatement(body) {
  664. return {
  665. type: 21,
  666. body,
  667. loc: locStub
  668. };
  669. }
  670. function createTemplateLiteral(elements) {
  671. return {
  672. type: 22,
  673. elements,
  674. loc: locStub
  675. };
  676. }
  677. function createIfStatement(test, consequent, alternate) {
  678. return {
  679. type: 23,
  680. test,
  681. consequent,
  682. alternate,
  683. loc: locStub
  684. };
  685. }
  686. function createAssignmentExpression(left, right) {
  687. return {
  688. type: 24,
  689. left,
  690. right,
  691. loc: locStub
  692. };
  693. }
  694. function createSequenceExpression(expressions) {
  695. return {
  696. type: 25,
  697. expressions,
  698. loc: locStub
  699. };
  700. }
  701. function createReturnStatement(returns) {
  702. return {
  703. type: 26,
  704. returns,
  705. loc: locStub
  706. };
  707. }
  708. function getVNodeHelper(ssr, isComponent) {
  709. return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
  710. }
  711. function getVNodeBlockHelper(ssr, isComponent) {
  712. return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
  713. }
  714. function convertToBlock(node, { helper, removeHelper, inSSR }) {
  715. if (!node.isBlock) {
  716. node.isBlock = true;
  717. removeHelper(getVNodeHelper(inSSR, node.isComponent));
  718. helper(OPEN_BLOCK);
  719. helper(getVNodeBlockHelper(inSSR, node.isComponent));
  720. }
  721. }
  722. // Adapted from https://github.com/mathiasbynens/he/blob/36afe179392226cf1b6ccdb16ebbb7a5a844d93a/src/he.js#L106-L134
  723. var _a$1;
  724. const decodeMap = new Map([
  725. [0, 65533],
  726. // C1 Unicode control character reference replacements
  727. [128, 8364],
  728. [130, 8218],
  729. [131, 402],
  730. [132, 8222],
  731. [133, 8230],
  732. [134, 8224],
  733. [135, 8225],
  734. [136, 710],
  735. [137, 8240],
  736. [138, 352],
  737. [139, 8249],
  738. [140, 338],
  739. [142, 381],
  740. [145, 8216],
  741. [146, 8217],
  742. [147, 8220],
  743. [148, 8221],
  744. [149, 8226],
  745. [150, 8211],
  746. [151, 8212],
  747. [152, 732],
  748. [153, 8482],
  749. [154, 353],
  750. [155, 8250],
  751. [156, 339],
  752. [158, 382],
  753. [159, 376],
  754. ]);
  755. /**
  756. * Polyfill for `String.fromCodePoint`. It is used to create a string from a Unicode code point.
  757. */
  758. const fromCodePoint =
  759. // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, n/no-unsupported-features/es-builtins
  760. (_a$1 = String.fromCodePoint) !== null && _a$1 !== void 0 ? _a$1 : ((codePoint) => {
  761. let output = "";
  762. if (codePoint > 65535) {
  763. codePoint -= 65536;
  764. output += String.fromCharCode(((codePoint >>> 10) & 1023) | 55296);
  765. codePoint = 56320 | (codePoint & 1023);
  766. }
  767. output += String.fromCharCode(codePoint);
  768. return output;
  769. });
  770. /**
  771. * Replace the given code point with a replacement character if it is a
  772. * surrogate or is outside the valid range. Otherwise return the code
  773. * point unchanged.
  774. */
  775. function replaceCodePoint(codePoint) {
  776. var _a;
  777. if ((codePoint >= 55296 && codePoint <= 57343) ||
  778. codePoint > 1114111) {
  779. return 65533;
  780. }
  781. return (_a = decodeMap.get(codePoint)) !== null && _a !== void 0 ? _a : codePoint;
  782. }
  783. var global$1 = (typeof global !== "undefined" ? global :
  784. typeof self !== "undefined" ? self :
  785. typeof window !== "undefined" ? window : {});
  786. var lookup = [];
  787. var revLookup = [];
  788. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
  789. var inited = false;
  790. function init () {
  791. inited = true;
  792. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  793. for (var i = 0, len = code.length; i < len; ++i) {
  794. lookup[i] = code[i];
  795. revLookup[code.charCodeAt(i)] = i;
  796. }
  797. revLookup['-'.charCodeAt(0)] = 62;
  798. revLookup['_'.charCodeAt(0)] = 63;
  799. }
  800. function toByteArray (b64) {
  801. if (!inited) {
  802. init();
  803. }
  804. var i, j, l, tmp, placeHolders, arr;
  805. var len = b64.length;
  806. if (len % 4 > 0) {
  807. throw new Error('Invalid string. Length must be a multiple of 4')
  808. }
  809. // the number of equal signs (place holders)
  810. // if there are two placeholders, than the two characters before it
  811. // represent one byte
  812. // if there is only one, then the three characters before it represent 2 bytes
  813. // this is just a cheap hack to not do indexOf twice
  814. placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
  815. // base64 is 4/3 + up to two characters of the original data
  816. arr = new Arr(len * 3 / 4 - placeHolders);
  817. // if there are placeholders, only get up to the last complete 4 chars
  818. l = placeHolders > 0 ? len - 4 : len;
  819. var L = 0;
  820. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  821. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];
  822. arr[L++] = (tmp >> 16) & 0xFF;
  823. arr[L++] = (tmp >> 8) & 0xFF;
  824. arr[L++] = tmp & 0xFF;
  825. }
  826. if (placeHolders === 2) {
  827. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
  828. arr[L++] = tmp & 0xFF;
  829. } else if (placeHolders === 1) {
  830. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);
  831. arr[L++] = (tmp >> 8) & 0xFF;
  832. arr[L++] = tmp & 0xFF;
  833. }
  834. return arr
  835. }
  836. function tripletToBase64 (num) {
  837. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  838. }
  839. function encodeChunk (uint8, start, end) {
  840. var tmp;
  841. var output = [];
  842. for (var i = start; i < end; i += 3) {
  843. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
  844. output.push(tripletToBase64(tmp));
  845. }
  846. return output.join('')
  847. }
  848. function fromByteArray (uint8) {
  849. if (!inited) {
  850. init();
  851. }
  852. var tmp;
  853. var len = uint8.length;
  854. var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
  855. var output = '';
  856. var parts = [];
  857. var maxChunkLength = 16383; // must be multiple of 3
  858. // go through the array every three bytes, we'll deal with trailing stuff later
  859. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  860. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));
  861. }
  862. // pad the end with zeros, but make sure to not forget the extra bytes
  863. if (extraBytes === 1) {
  864. tmp = uint8[len - 1];
  865. output += lookup[tmp >> 2];
  866. output += lookup[(tmp << 4) & 0x3F];
  867. output += '==';
  868. } else if (extraBytes === 2) {
  869. tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);
  870. output += lookup[tmp >> 10];
  871. output += lookup[(tmp >> 4) & 0x3F];
  872. output += lookup[(tmp << 2) & 0x3F];
  873. output += '=';
  874. }
  875. parts.push(output);
  876. return parts.join('')
  877. }
  878. function read (buffer, offset, isLE, mLen, nBytes) {
  879. var e, m;
  880. var eLen = nBytes * 8 - mLen - 1;
  881. var eMax = (1 << eLen) - 1;
  882. var eBias = eMax >> 1;
  883. var nBits = -7;
  884. var i = isLE ? (nBytes - 1) : 0;
  885. var d = isLE ? -1 : 1;
  886. var s = buffer[offset + i];
  887. i += d;
  888. e = s & ((1 << (-nBits)) - 1);
  889. s >>= (-nBits);
  890. nBits += eLen;
  891. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  892. m = e & ((1 << (-nBits)) - 1);
  893. e >>= (-nBits);
  894. nBits += mLen;
  895. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  896. if (e === 0) {
  897. e = 1 - eBias;
  898. } else if (e === eMax) {
  899. return m ? NaN : ((s ? -1 : 1) * Infinity)
  900. } else {
  901. m = m + Math.pow(2, mLen);
  902. e = e - eBias;
  903. }
  904. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  905. }
  906. function write (buffer, value, offset, isLE, mLen, nBytes) {
  907. var e, m, c;
  908. var eLen = nBytes * 8 - mLen - 1;
  909. var eMax = (1 << eLen) - 1;
  910. var eBias = eMax >> 1;
  911. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
  912. var i = isLE ? 0 : (nBytes - 1);
  913. var d = isLE ? 1 : -1;
  914. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
  915. value = Math.abs(value);
  916. if (isNaN(value) || value === Infinity) {
  917. m = isNaN(value) ? 1 : 0;
  918. e = eMax;
  919. } else {
  920. e = Math.floor(Math.log(value) / Math.LN2);
  921. if (value * (c = Math.pow(2, -e)) < 1) {
  922. e--;
  923. c *= 2;
  924. }
  925. if (e + eBias >= 1) {
  926. value += rt / c;
  927. } else {
  928. value += rt * Math.pow(2, 1 - eBias);
  929. }
  930. if (value * c >= 2) {
  931. e++;
  932. c /= 2;
  933. }
  934. if (e + eBias >= eMax) {
  935. m = 0;
  936. e = eMax;
  937. } else if (e + eBias >= 1) {
  938. m = (value * c - 1) * Math.pow(2, mLen);
  939. e = e + eBias;
  940. } else {
  941. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  942. e = 0;
  943. }
  944. }
  945. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  946. e = (e << mLen) | m;
  947. eLen += mLen;
  948. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  949. buffer[offset + i - d] |= s * 128;
  950. }
  951. var toString$1 = {}.toString;
  952. var isArray$2 = Array.isArray || function (arr) {
  953. return toString$1.call(arr) == '[object Array]';
  954. };
  955. /*!
  956. * The buffer module from node.js, for the browser.
  957. *
  958. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  959. * @license MIT
  960. */
  961. /* eslint-disable no-proto */
  962. var INSPECT_MAX_BYTES = 50;
  963. /**
  964. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  965. * === true Use Uint8Array implementation (fastest)
  966. * === false Use Object implementation (most compatible, even IE6)
  967. *
  968. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  969. * Opera 11.6+, iOS 4.2+.
  970. *
  971. * Due to various browser bugs, sometimes the Object implementation will be used even
  972. * when the browser supports typed arrays.
  973. *
  974. * Note:
  975. *
  976. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  977. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  978. *
  979. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  980. *
  981. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  982. * incorrect length in some situations.
  983. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  984. * get the Object implementation, which is slower but behaves correctly.
  985. */
  986. Buffer$1.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined
  987. ? global$1.TYPED_ARRAY_SUPPORT
  988. : true;
  989. /*
  990. * Export kMaxLength after typed array support is determined.
  991. */
  992. kMaxLength();
  993. function kMaxLength () {
  994. return Buffer$1.TYPED_ARRAY_SUPPORT
  995. ? 0x7fffffff
  996. : 0x3fffffff
  997. }
  998. function createBuffer (that, length) {
  999. if (kMaxLength() < length) {
  1000. throw new RangeError('Invalid typed array length')
  1001. }
  1002. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  1003. // Return an augmented `Uint8Array` instance, for best performance
  1004. that = new Uint8Array(length);
  1005. that.__proto__ = Buffer$1.prototype;
  1006. } else {
  1007. // Fallback: Return an object instance of the Buffer class
  1008. if (that === null) {
  1009. that = new Buffer$1(length);
  1010. }
  1011. that.length = length;
  1012. }
  1013. return that
  1014. }
  1015. /**
  1016. * The Buffer constructor returns instances of `Uint8Array` that have their
  1017. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  1018. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  1019. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  1020. * returns a single octet.
  1021. *
  1022. * The `Uint8Array` prototype remains unmodified.
  1023. */
  1024. function Buffer$1 (arg, encodingOrOffset, length) {
  1025. if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) {
  1026. return new Buffer$1(arg, encodingOrOffset, length)
  1027. }
  1028. // Common case.
  1029. if (typeof arg === 'number') {
  1030. if (typeof encodingOrOffset === 'string') {
  1031. throw new Error(
  1032. 'If encoding is specified then the first argument must be a string'
  1033. )
  1034. }
  1035. return allocUnsafe(this, arg)
  1036. }
  1037. return from(this, arg, encodingOrOffset, length)
  1038. }
  1039. Buffer$1.poolSize = 8192; // not used by this implementation
  1040. // TODO: Legacy, not needed anymore. Remove in next major version.
  1041. Buffer$1._augment = function (arr) {
  1042. arr.__proto__ = Buffer$1.prototype;
  1043. return arr
  1044. };
  1045. function from (that, value, encodingOrOffset, length) {
  1046. if (typeof value === 'number') {
  1047. throw new TypeError('"value" argument must not be a number')
  1048. }
  1049. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  1050. return fromArrayBuffer(that, value, encodingOrOffset, length)
  1051. }
  1052. if (typeof value === 'string') {
  1053. return fromString(that, value, encodingOrOffset)
  1054. }
  1055. return fromObject(that, value)
  1056. }
  1057. /**
  1058. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  1059. * if value is a number.
  1060. * Buffer.from(str[, encoding])
  1061. * Buffer.from(array)
  1062. * Buffer.from(buffer)
  1063. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  1064. **/
  1065. Buffer$1.from = function (value, encodingOrOffset, length) {
  1066. return from(null, value, encodingOrOffset, length)
  1067. };
  1068. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  1069. Buffer$1.prototype.__proto__ = Uint8Array.prototype;
  1070. Buffer$1.__proto__ = Uint8Array;
  1071. if (typeof Symbol !== 'undefined' && Symbol.species &&
  1072. Buffer$1[Symbol.species] === Buffer$1) ;
  1073. }
  1074. function assertSize (size) {
  1075. if (typeof size !== 'number') {
  1076. throw new TypeError('"size" argument must be a number')
  1077. } else if (size < 0) {
  1078. throw new RangeError('"size" argument must not be negative')
  1079. }
  1080. }
  1081. function alloc (that, size, fill, encoding) {
  1082. assertSize(size);
  1083. if (size <= 0) {
  1084. return createBuffer(that, size)
  1085. }
  1086. if (fill !== undefined) {
  1087. // Only pay attention to encoding if it's a string. This
  1088. // prevents accidentally sending in a number that would
  1089. // be interpretted as a start offset.
  1090. return typeof encoding === 'string'
  1091. ? createBuffer(that, size).fill(fill, encoding)
  1092. : createBuffer(that, size).fill(fill)
  1093. }
  1094. return createBuffer(that, size)
  1095. }
  1096. /**
  1097. * Creates a new filled Buffer instance.
  1098. * alloc(size[, fill[, encoding]])
  1099. **/
  1100. Buffer$1.alloc = function (size, fill, encoding) {
  1101. return alloc(null, size, fill, encoding)
  1102. };
  1103. function allocUnsafe (that, size) {
  1104. assertSize(size);
  1105. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
  1106. if (!Buffer$1.TYPED_ARRAY_SUPPORT) {
  1107. for (var i = 0; i < size; ++i) {
  1108. that[i] = 0;
  1109. }
  1110. }
  1111. return that
  1112. }
  1113. /**
  1114. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  1115. * */
  1116. Buffer$1.allocUnsafe = function (size) {
  1117. return allocUnsafe(null, size)
  1118. };
  1119. /**
  1120. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  1121. */
  1122. Buffer$1.allocUnsafeSlow = function (size) {
  1123. return allocUnsafe(null, size)
  1124. };
  1125. function fromString (that, string, encoding) {
  1126. if (typeof encoding !== 'string' || encoding === '') {
  1127. encoding = 'utf8';
  1128. }
  1129. if (!Buffer$1.isEncoding(encoding)) {
  1130. throw new TypeError('"encoding" must be a valid string encoding')
  1131. }
  1132. var length = byteLength(string, encoding) | 0;
  1133. that = createBuffer(that, length);
  1134. var actual = that.write(string, encoding);
  1135. if (actual !== length) {
  1136. // Writing a hex string, for example, that contains invalid characters will
  1137. // cause everything after the first invalid character to be ignored. (e.g.
  1138. // 'abxxcd' will be treated as 'ab')
  1139. that = that.slice(0, actual);
  1140. }
  1141. return that
  1142. }
  1143. function fromArrayLike (that, array) {
  1144. var length = array.length < 0 ? 0 : checked(array.length) | 0;
  1145. that = createBuffer(that, length);
  1146. for (var i = 0; i < length; i += 1) {
  1147. that[i] = array[i] & 255;
  1148. }
  1149. return that
  1150. }
  1151. function fromArrayBuffer (that, array, byteOffset, length) {
  1152. array.byteLength; // this throws if `array` is not a valid ArrayBuffer
  1153. if (byteOffset < 0 || array.byteLength < byteOffset) {
  1154. throw new RangeError('\'offset\' is out of bounds')
  1155. }
  1156. if (array.byteLength < byteOffset + (length || 0)) {
  1157. throw new RangeError('\'length\' is out of bounds')
  1158. }
  1159. if (byteOffset === undefined && length === undefined) {
  1160. array = new Uint8Array(array);
  1161. } else if (length === undefined) {
  1162. array = new Uint8Array(array, byteOffset);
  1163. } else {
  1164. array = new Uint8Array(array, byteOffset, length);
  1165. }
  1166. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  1167. // Return an augmented `Uint8Array` instance, for best performance
  1168. that = array;
  1169. that.__proto__ = Buffer$1.prototype;
  1170. } else {
  1171. // Fallback: Return an object instance of the Buffer class
  1172. that = fromArrayLike(that, array);
  1173. }
  1174. return that
  1175. }
  1176. function fromObject (that, obj) {
  1177. if (internalIsBuffer(obj)) {
  1178. var len = checked(obj.length) | 0;
  1179. that = createBuffer(that, len);
  1180. if (that.length === 0) {
  1181. return that
  1182. }
  1183. obj.copy(that, 0, 0, len);
  1184. return that
  1185. }
  1186. if (obj) {
  1187. if ((typeof ArrayBuffer !== 'undefined' &&
  1188. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  1189. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  1190. return createBuffer(that, 0)
  1191. }
  1192. return fromArrayLike(that, obj)
  1193. }
  1194. if (obj.type === 'Buffer' && isArray$2(obj.data)) {
  1195. return fromArrayLike(that, obj.data)
  1196. }
  1197. }
  1198. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  1199. }
  1200. function checked (length) {
  1201. // Note: cannot use `length < kMaxLength()` here because that fails when
  1202. // length is NaN (which is otherwise coerced to zero.)
  1203. if (length >= kMaxLength()) {
  1204. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  1205. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  1206. }
  1207. return length | 0
  1208. }
  1209. Buffer$1.isBuffer = isBuffer$1;
  1210. function internalIsBuffer (b) {
  1211. return !!(b != null && b._isBuffer)
  1212. }
  1213. Buffer$1.compare = function compare (a, b) {
  1214. if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
  1215. throw new TypeError('Arguments must be Buffers')
  1216. }
  1217. if (a === b) return 0
  1218. var x = a.length;
  1219. var y = b.length;
  1220. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  1221. if (a[i] !== b[i]) {
  1222. x = a[i];
  1223. y = b[i];
  1224. break
  1225. }
  1226. }
  1227. if (x < y) return -1
  1228. if (y < x) return 1
  1229. return 0
  1230. };
  1231. Buffer$1.isEncoding = function isEncoding (encoding) {
  1232. switch (String(encoding).toLowerCase()) {
  1233. case 'hex':
  1234. case 'utf8':
  1235. case 'utf-8':
  1236. case 'ascii':
  1237. case 'latin1':
  1238. case 'binary':
  1239. case 'base64':
  1240. case 'ucs2':
  1241. case 'ucs-2':
  1242. case 'utf16le':
  1243. case 'utf-16le':
  1244. return true
  1245. default:
  1246. return false
  1247. }
  1248. };
  1249. Buffer$1.concat = function concat (list, length) {
  1250. if (!isArray$2(list)) {
  1251. throw new TypeError('"list" argument must be an Array of Buffers')
  1252. }
  1253. if (list.length === 0) {
  1254. return Buffer$1.alloc(0)
  1255. }
  1256. var i;
  1257. if (length === undefined) {
  1258. length = 0;
  1259. for (i = 0; i < list.length; ++i) {
  1260. length += list[i].length;
  1261. }
  1262. }
  1263. var buffer = Buffer$1.allocUnsafe(length);
  1264. var pos = 0;
  1265. for (i = 0; i < list.length; ++i) {
  1266. var buf = list[i];
  1267. if (!internalIsBuffer(buf)) {
  1268. throw new TypeError('"list" argument must be an Array of Buffers')
  1269. }
  1270. buf.copy(buffer, pos);
  1271. pos += buf.length;
  1272. }
  1273. return buffer
  1274. };
  1275. function byteLength (string, encoding) {
  1276. if (internalIsBuffer(string)) {
  1277. return string.length
  1278. }
  1279. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  1280. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  1281. return string.byteLength
  1282. }
  1283. if (typeof string !== 'string') {
  1284. string = '' + string;
  1285. }
  1286. var len = string.length;
  1287. if (len === 0) return 0
  1288. // Use a for loop to avoid recursion
  1289. var loweredCase = false;
  1290. for (;;) {
  1291. switch (encoding) {
  1292. case 'ascii':
  1293. case 'latin1':
  1294. case 'binary':
  1295. return len
  1296. case 'utf8':
  1297. case 'utf-8':
  1298. case undefined:
  1299. return utf8ToBytes(string).length
  1300. case 'ucs2':
  1301. case 'ucs-2':
  1302. case 'utf16le':
  1303. case 'utf-16le':
  1304. return len * 2
  1305. case 'hex':
  1306. return len >>> 1
  1307. case 'base64':
  1308. return base64ToBytes(string).length
  1309. default:
  1310. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  1311. encoding = ('' + encoding).toLowerCase();
  1312. loweredCase = true;
  1313. }
  1314. }
  1315. }
  1316. Buffer$1.byteLength = byteLength;
  1317. function slowToString (encoding, start, end) {
  1318. var loweredCase = false;
  1319. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  1320. // property of a typed array.
  1321. // This behaves neither like String nor Uint8Array in that we set start/end
  1322. // to their upper/lower bounds if the value passed is out of range.
  1323. // undefined is handled specially as per ECMA-262 6th Edition,
  1324. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  1325. if (start === undefined || start < 0) {
  1326. start = 0;
  1327. }
  1328. // Return early if start > this.length. Done here to prevent potential uint32
  1329. // coercion fail below.
  1330. if (start > this.length) {
  1331. return ''
  1332. }
  1333. if (end === undefined || end > this.length) {
  1334. end = this.length;
  1335. }
  1336. if (end <= 0) {
  1337. return ''
  1338. }
  1339. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  1340. end >>>= 0;
  1341. start >>>= 0;
  1342. if (end <= start) {
  1343. return ''
  1344. }
  1345. if (!encoding) encoding = 'utf8';
  1346. while (true) {
  1347. switch (encoding) {
  1348. case 'hex':
  1349. return hexSlice(this, start, end)
  1350. case 'utf8':
  1351. case 'utf-8':
  1352. return utf8Slice(this, start, end)
  1353. case 'ascii':
  1354. return asciiSlice(this, start, end)
  1355. case 'latin1':
  1356. case 'binary':
  1357. return latin1Slice(this, start, end)
  1358. case 'base64':
  1359. return base64Slice(this, start, end)
  1360. case 'ucs2':
  1361. case 'ucs-2':
  1362. case 'utf16le':
  1363. case 'utf-16le':
  1364. return utf16leSlice(this, start, end)
  1365. default:
  1366. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  1367. encoding = (encoding + '').toLowerCase();
  1368. loweredCase = true;
  1369. }
  1370. }
  1371. }
  1372. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  1373. // Buffer instances.
  1374. Buffer$1.prototype._isBuffer = true;
  1375. function swap (b, n, m) {
  1376. var i = b[n];
  1377. b[n] = b[m];
  1378. b[m] = i;
  1379. }
  1380. Buffer$1.prototype.swap16 = function swap16 () {
  1381. var len = this.length;
  1382. if (len % 2 !== 0) {
  1383. throw new RangeError('Buffer size must be a multiple of 16-bits')
  1384. }
  1385. for (var i = 0; i < len; i += 2) {
  1386. swap(this, i, i + 1);
  1387. }
  1388. return this
  1389. };
  1390. Buffer$1.prototype.swap32 = function swap32 () {
  1391. var len = this.length;
  1392. if (len % 4 !== 0) {
  1393. throw new RangeError('Buffer size must be a multiple of 32-bits')
  1394. }
  1395. for (var i = 0; i < len; i += 4) {
  1396. swap(this, i, i + 3);
  1397. swap(this, i + 1, i + 2);
  1398. }
  1399. return this
  1400. };
  1401. Buffer$1.prototype.swap64 = function swap64 () {
  1402. var len = this.length;
  1403. if (len % 8 !== 0) {
  1404. throw new RangeError('Buffer size must be a multiple of 64-bits')
  1405. }
  1406. for (var i = 0; i < len; i += 8) {
  1407. swap(this, i, i + 7);
  1408. swap(this, i + 1, i + 6);
  1409. swap(this, i + 2, i + 5);
  1410. swap(this, i + 3, i + 4);
  1411. }
  1412. return this
  1413. };
  1414. Buffer$1.prototype.toString = function toString () {
  1415. var length = this.length | 0;
  1416. if (length === 0) return ''
  1417. if (arguments.length === 0) return utf8Slice(this, 0, length)
  1418. return slowToString.apply(this, arguments)
  1419. };
  1420. Buffer$1.prototype.equals = function equals (b) {
  1421. if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')
  1422. if (this === b) return true
  1423. return Buffer$1.compare(this, b) === 0
  1424. };
  1425. Buffer$1.prototype.inspect = function inspect () {
  1426. var str = '';
  1427. var max = INSPECT_MAX_BYTES;
  1428. if (this.length > 0) {
  1429. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
  1430. if (this.length > max) str += ' ... ';
  1431. }
  1432. return '<Buffer ' + str + '>'
  1433. };
  1434. Buffer$1.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  1435. if (!internalIsBuffer(target)) {
  1436. throw new TypeError('Argument must be a Buffer')
  1437. }
  1438. if (start === undefined) {
  1439. start = 0;
  1440. }
  1441. if (end === undefined) {
  1442. end = target ? target.length : 0;
  1443. }
  1444. if (thisStart === undefined) {
  1445. thisStart = 0;
  1446. }
  1447. if (thisEnd === undefined) {
  1448. thisEnd = this.length;
  1449. }
  1450. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  1451. throw new RangeError('out of range index')
  1452. }
  1453. if (thisStart >= thisEnd && start >= end) {
  1454. return 0
  1455. }
  1456. if (thisStart >= thisEnd) {
  1457. return -1
  1458. }
  1459. if (start >= end) {
  1460. return 1
  1461. }
  1462. start >>>= 0;
  1463. end >>>= 0;
  1464. thisStart >>>= 0;
  1465. thisEnd >>>= 0;
  1466. if (this === target) return 0
  1467. var x = thisEnd - thisStart;
  1468. var y = end - start;
  1469. var len = Math.min(x, y);
  1470. var thisCopy = this.slice(thisStart, thisEnd);
  1471. var targetCopy = target.slice(start, end);
  1472. for (var i = 0; i < len; ++i) {
  1473. if (thisCopy[i] !== targetCopy[i]) {
  1474. x = thisCopy[i];
  1475. y = targetCopy[i];
  1476. break
  1477. }
  1478. }
  1479. if (x < y) return -1
  1480. if (y < x) return 1
  1481. return 0
  1482. };
  1483. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  1484. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  1485. //
  1486. // Arguments:
  1487. // - buffer - a Buffer to search
  1488. // - val - a string, Buffer, or number
  1489. // - byteOffset - an index into `buffer`; will be clamped to an int32
  1490. // - encoding - an optional encoding, relevant is val is a string
  1491. // - dir - true for indexOf, false for lastIndexOf
  1492. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  1493. // Empty buffer means no match
  1494. if (buffer.length === 0) return -1
  1495. // Normalize byteOffset
  1496. if (typeof byteOffset === 'string') {
  1497. encoding = byteOffset;
  1498. byteOffset = 0;
  1499. } else if (byteOffset > 0x7fffffff) {
  1500. byteOffset = 0x7fffffff;
  1501. } else if (byteOffset < -2147483648) {
  1502. byteOffset = -2147483648;
  1503. }
  1504. byteOffset = +byteOffset; // Coerce to Number.
  1505. if (isNaN(byteOffset)) {
  1506. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  1507. byteOffset = dir ? 0 : (buffer.length - 1);
  1508. }
  1509. // Normalize byteOffset: negative offsets start from the end of the buffer
  1510. if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
  1511. if (byteOffset >= buffer.length) {
  1512. if (dir) return -1
  1513. else byteOffset = buffer.length - 1;
  1514. } else if (byteOffset < 0) {
  1515. if (dir) byteOffset = 0;
  1516. else return -1
  1517. }
  1518. // Normalize val
  1519. if (typeof val === 'string') {
  1520. val = Buffer$1.from(val, encoding);
  1521. }
  1522. // Finally, search either indexOf (if dir is true) or lastIndexOf
  1523. if (internalIsBuffer(val)) {
  1524. // Special case: looking for empty string/buffer always fails
  1525. if (val.length === 0) {
  1526. return -1
  1527. }
  1528. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  1529. } else if (typeof val === 'number') {
  1530. val = val & 0xFF; // Search for a byte value [0-255]
  1531. if (Buffer$1.TYPED_ARRAY_SUPPORT &&
  1532. typeof Uint8Array.prototype.indexOf === 'function') {
  1533. if (dir) {
  1534. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  1535. } else {
  1536. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  1537. }
  1538. }
  1539. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  1540. }
  1541. throw new TypeError('val must be string, number or Buffer')
  1542. }
  1543. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  1544. var indexSize = 1;
  1545. var arrLength = arr.length;
  1546. var valLength = val.length;
  1547. if (encoding !== undefined) {
  1548. encoding = String(encoding).toLowerCase();
  1549. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  1550. encoding === 'utf16le' || encoding === 'utf-16le') {
  1551. if (arr.length < 2 || val.length < 2) {
  1552. return -1
  1553. }
  1554. indexSize = 2;
  1555. arrLength /= 2;
  1556. valLength /= 2;
  1557. byteOffset /= 2;
  1558. }
  1559. }
  1560. function read (buf, i) {
  1561. if (indexSize === 1) {
  1562. return buf[i]
  1563. } else {
  1564. return buf.readUInt16BE(i * indexSize)
  1565. }
  1566. }
  1567. var i;
  1568. if (dir) {
  1569. var foundIndex = -1;
  1570. for (i = byteOffset; i < arrLength; i++) {
  1571. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  1572. if (foundIndex === -1) foundIndex = i;
  1573. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  1574. } else {
  1575. if (foundIndex !== -1) i -= i - foundIndex;
  1576. foundIndex = -1;
  1577. }
  1578. }
  1579. } else {
  1580. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
  1581. for (i = byteOffset; i >= 0; i--) {
  1582. var found = true;
  1583. for (var j = 0; j < valLength; j++) {
  1584. if (read(arr, i + j) !== read(val, j)) {
  1585. found = false;
  1586. break
  1587. }
  1588. }
  1589. if (found) return i
  1590. }
  1591. }
  1592. return -1
  1593. }
  1594. Buffer$1.prototype.includes = function includes (val, byteOffset, encoding) {
  1595. return this.indexOf(val, byteOffset, encoding) !== -1
  1596. };
  1597. Buffer$1.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  1598. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  1599. };
  1600. Buffer$1.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  1601. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  1602. };
  1603. function hexWrite (buf, string, offset, length) {
  1604. offset = Number(offset) || 0;
  1605. var remaining = buf.length - offset;
  1606. if (!length) {
  1607. length = remaining;
  1608. } else {
  1609. length = Number(length);
  1610. if (length > remaining) {
  1611. length = remaining;
  1612. }
  1613. }
  1614. // must be an even number of digits
  1615. var strLen = string.length;
  1616. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  1617. if (length > strLen / 2) {
  1618. length = strLen / 2;
  1619. }
  1620. for (var i = 0; i < length; ++i) {
  1621. var parsed = parseInt(string.substr(i * 2, 2), 16);
  1622. if (isNaN(parsed)) return i
  1623. buf[offset + i] = parsed;
  1624. }
  1625. return i
  1626. }
  1627. function utf8Write (buf, string, offset, length) {
  1628. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  1629. }
  1630. function asciiWrite (buf, string, offset, length) {
  1631. return blitBuffer(asciiToBytes(string), buf, offset, length)
  1632. }
  1633. function latin1Write (buf, string, offset, length) {
  1634. return asciiWrite(buf, string, offset, length)
  1635. }
  1636. function base64Write (buf, string, offset, length) {
  1637. return blitBuffer(base64ToBytes(string), buf, offset, length)
  1638. }
  1639. function ucs2Write (buf, string, offset, length) {
  1640. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  1641. }
  1642. Buffer$1.prototype.write = function write (string, offset, length, encoding) {
  1643. // Buffer#write(string)
  1644. if (offset === undefined) {
  1645. encoding = 'utf8';
  1646. length = this.length;
  1647. offset = 0;
  1648. // Buffer#write(string, encoding)
  1649. } else if (length === undefined && typeof offset === 'string') {
  1650. encoding = offset;
  1651. length = this.length;
  1652. offset = 0;
  1653. // Buffer#write(string, offset[, length][, encoding])
  1654. } else if (isFinite(offset)) {
  1655. offset = offset | 0;
  1656. if (isFinite(length)) {
  1657. length = length | 0;
  1658. if (encoding === undefined) encoding = 'utf8';
  1659. } else {
  1660. encoding = length;
  1661. length = undefined;
  1662. }
  1663. // legacy write(string, encoding, offset, length) - remove in v0.13
  1664. } else {
  1665. throw new Error(
  1666. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  1667. )
  1668. }
  1669. var remaining = this.length - offset;
  1670. if (length === undefined || length > remaining) length = remaining;
  1671. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  1672. throw new RangeError('Attempt to write outside buffer bounds')
  1673. }
  1674. if (!encoding) encoding = 'utf8';
  1675. var loweredCase = false;
  1676. for (;;) {
  1677. switch (encoding) {
  1678. case 'hex':
  1679. return hexWrite(this, string, offset, length)
  1680. case 'utf8':
  1681. case 'utf-8':
  1682. return utf8Write(this, string, offset, length)
  1683. case 'ascii':
  1684. return asciiWrite(this, string, offset, length)
  1685. case 'latin1':
  1686. case 'binary':
  1687. return latin1Write(this, string, offset, length)
  1688. case 'base64':
  1689. // Warning: maxLength not taken into account in base64Write
  1690. return base64Write(this, string, offset, length)
  1691. case 'ucs2':
  1692. case 'ucs-2':
  1693. case 'utf16le':
  1694. case 'utf-16le':
  1695. return ucs2Write(this, string, offset, length)
  1696. default:
  1697. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  1698. encoding = ('' + encoding).toLowerCase();
  1699. loweredCase = true;
  1700. }
  1701. }
  1702. };
  1703. Buffer$1.prototype.toJSON = function toJSON () {
  1704. return {
  1705. type: 'Buffer',
  1706. data: Array.prototype.slice.call(this._arr || this, 0)
  1707. }
  1708. };
  1709. function base64Slice (buf, start, end) {
  1710. if (start === 0 && end === buf.length) {
  1711. return fromByteArray(buf)
  1712. } else {
  1713. return fromByteArray(buf.slice(start, end))
  1714. }
  1715. }
  1716. function utf8Slice (buf, start, end) {
  1717. end = Math.min(buf.length, end);
  1718. var res = [];
  1719. var i = start;
  1720. while (i < end) {
  1721. var firstByte = buf[i];
  1722. var codePoint = null;
  1723. var bytesPerSequence = (firstByte > 0xEF) ? 4
  1724. : (firstByte > 0xDF) ? 3
  1725. : (firstByte > 0xBF) ? 2
  1726. : 1;
  1727. if (i + bytesPerSequence <= end) {
  1728. var secondByte, thirdByte, fourthByte, tempCodePoint;
  1729. switch (bytesPerSequence) {
  1730. case 1:
  1731. if (firstByte < 0x80) {
  1732. codePoint = firstByte;
  1733. }
  1734. break
  1735. case 2:
  1736. secondByte = buf[i + 1];
  1737. if ((secondByte & 0xC0) === 0x80) {
  1738. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
  1739. if (tempCodePoint > 0x7F) {
  1740. codePoint = tempCodePoint;
  1741. }
  1742. }
  1743. break
  1744. case 3:
  1745. secondByte = buf[i + 1];
  1746. thirdByte = buf[i + 2];
  1747. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  1748. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
  1749. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  1750. codePoint = tempCodePoint;
  1751. }
  1752. }
  1753. break
  1754. case 4:
  1755. secondByte = buf[i + 1];
  1756. thirdByte = buf[i + 2];
  1757. fourthByte = buf[i + 3];
  1758. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  1759. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
  1760. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  1761. codePoint = tempCodePoint;
  1762. }
  1763. }
  1764. }
  1765. }
  1766. if (codePoint === null) {
  1767. // we did not generate a valid codePoint so insert a
  1768. // replacement char (U+FFFD) and advance only 1 byte
  1769. codePoint = 0xFFFD;
  1770. bytesPerSequence = 1;
  1771. } else if (codePoint > 0xFFFF) {
  1772. // encode to utf16 (surrogate pair dance)
  1773. codePoint -= 0x10000;
  1774. res.push(codePoint >>> 10 & 0x3FF | 0xD800);
  1775. codePoint = 0xDC00 | codePoint & 0x3FF;
  1776. }
  1777. res.push(codePoint);
  1778. i += bytesPerSequence;
  1779. }
  1780. return decodeCodePointsArray(res)
  1781. }
  1782. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  1783. // the lowest limit is Chrome, with 0x10000 args.
  1784. // We go 1 magnitude less, for safety
  1785. var MAX_ARGUMENTS_LENGTH = 0x1000;
  1786. function decodeCodePointsArray (codePoints) {
  1787. var len = codePoints.length;
  1788. if (len <= MAX_ARGUMENTS_LENGTH) {
  1789. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  1790. }
  1791. // Decode in chunks to avoid "call stack size exceeded".
  1792. var res = '';
  1793. var i = 0;
  1794. while (i < len) {
  1795. res += String.fromCharCode.apply(
  1796. String,
  1797. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  1798. );
  1799. }
  1800. return res
  1801. }
  1802. function asciiSlice (buf, start, end) {
  1803. var ret = '';
  1804. end = Math.min(buf.length, end);
  1805. for (var i = start; i < end; ++i) {
  1806. ret += String.fromCharCode(buf[i] & 0x7F);
  1807. }
  1808. return ret
  1809. }
  1810. function latin1Slice (buf, start, end) {
  1811. var ret = '';
  1812. end = Math.min(buf.length, end);
  1813. for (var i = start; i < end; ++i) {
  1814. ret += String.fromCharCode(buf[i]);
  1815. }
  1816. return ret
  1817. }
  1818. function hexSlice (buf, start, end) {
  1819. var len = buf.length;
  1820. if (!start || start < 0) start = 0;
  1821. if (!end || end < 0 || end > len) end = len;
  1822. var out = '';
  1823. for (var i = start; i < end; ++i) {
  1824. out += toHex(buf[i]);
  1825. }
  1826. return out
  1827. }
  1828. function utf16leSlice (buf, start, end) {
  1829. var bytes = buf.slice(start, end);
  1830. var res = '';
  1831. for (var i = 0; i < bytes.length; i += 2) {
  1832. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
  1833. }
  1834. return res
  1835. }
  1836. Buffer$1.prototype.slice = function slice (start, end) {
  1837. var len = this.length;
  1838. start = ~~start;
  1839. end = end === undefined ? len : ~~end;
  1840. if (start < 0) {
  1841. start += len;
  1842. if (start < 0) start = 0;
  1843. } else if (start > len) {
  1844. start = len;
  1845. }
  1846. if (end < 0) {
  1847. end += len;
  1848. if (end < 0) end = 0;
  1849. } else if (end > len) {
  1850. end = len;
  1851. }
  1852. if (end < start) end = start;
  1853. var newBuf;
  1854. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  1855. newBuf = this.subarray(start, end);
  1856. newBuf.__proto__ = Buffer$1.prototype;
  1857. } else {
  1858. var sliceLen = end - start;
  1859. newBuf = new Buffer$1(sliceLen, undefined);
  1860. for (var i = 0; i < sliceLen; ++i) {
  1861. newBuf[i] = this[i + start];
  1862. }
  1863. }
  1864. return newBuf
  1865. };
  1866. /*
  1867. * Need to make sure that buffer isn't trying to write out of bounds.
  1868. */
  1869. function checkOffset (offset, ext, length) {
  1870. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  1871. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  1872. }
  1873. Buffer$1.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  1874. offset = offset | 0;
  1875. byteLength = byteLength | 0;
  1876. if (!noAssert) checkOffset(offset, byteLength, this.length);
  1877. var val = this[offset];
  1878. var mul = 1;
  1879. var i = 0;
  1880. while (++i < byteLength && (mul *= 0x100)) {
  1881. val += this[offset + i] * mul;
  1882. }
  1883. return val
  1884. };
  1885. Buffer$1.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  1886. offset = offset | 0;
  1887. byteLength = byteLength | 0;
  1888. if (!noAssert) {
  1889. checkOffset(offset, byteLength, this.length);
  1890. }
  1891. var val = this[offset + --byteLength];
  1892. var mul = 1;
  1893. while (byteLength > 0 && (mul *= 0x100)) {
  1894. val += this[offset + --byteLength] * mul;
  1895. }
  1896. return val
  1897. };
  1898. Buffer$1.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1899. if (!noAssert) checkOffset(offset, 1, this.length);
  1900. return this[offset]
  1901. };
  1902. Buffer$1.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1903. if (!noAssert) checkOffset(offset, 2, this.length);
  1904. return this[offset] | (this[offset + 1] << 8)
  1905. };
  1906. Buffer$1.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1907. if (!noAssert) checkOffset(offset, 2, this.length);
  1908. return (this[offset] << 8) | this[offset + 1]
  1909. };
  1910. Buffer$1.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1911. if (!noAssert) checkOffset(offset, 4, this.length);
  1912. return ((this[offset]) |
  1913. (this[offset + 1] << 8) |
  1914. (this[offset + 2] << 16)) +
  1915. (this[offset + 3] * 0x1000000)
  1916. };
  1917. Buffer$1.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1918. if (!noAssert) checkOffset(offset, 4, this.length);
  1919. return (this[offset] * 0x1000000) +
  1920. ((this[offset + 1] << 16) |
  1921. (this[offset + 2] << 8) |
  1922. this[offset + 3])
  1923. };
  1924. Buffer$1.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1925. offset = offset | 0;
  1926. byteLength = byteLength | 0;
  1927. if (!noAssert) checkOffset(offset, byteLength, this.length);
  1928. var val = this[offset];
  1929. var mul = 1;
  1930. var i = 0;
  1931. while (++i < byteLength && (mul *= 0x100)) {
  1932. val += this[offset + i] * mul;
  1933. }
  1934. mul *= 0x80;
  1935. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  1936. return val
  1937. };
  1938. Buffer$1.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1939. offset = offset | 0;
  1940. byteLength = byteLength | 0;
  1941. if (!noAssert) checkOffset(offset, byteLength, this.length);
  1942. var i = byteLength;
  1943. var mul = 1;
  1944. var val = this[offset + --i];
  1945. while (i > 0 && (mul *= 0x100)) {
  1946. val += this[offset + --i] * mul;
  1947. }
  1948. mul *= 0x80;
  1949. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  1950. return val
  1951. };
  1952. Buffer$1.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1953. if (!noAssert) checkOffset(offset, 1, this.length);
  1954. if (!(this[offset] & 0x80)) return (this[offset])
  1955. return ((0xff - this[offset] + 1) * -1)
  1956. };
  1957. Buffer$1.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1958. if (!noAssert) checkOffset(offset, 2, this.length);
  1959. var val = this[offset] | (this[offset + 1] << 8);
  1960. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1961. };
  1962. Buffer$1.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1963. if (!noAssert) checkOffset(offset, 2, this.length);
  1964. var val = this[offset + 1] | (this[offset] << 8);
  1965. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1966. };
  1967. Buffer$1.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1968. if (!noAssert) checkOffset(offset, 4, this.length);
  1969. return (this[offset]) |
  1970. (this[offset + 1] << 8) |
  1971. (this[offset + 2] << 16) |
  1972. (this[offset + 3] << 24)
  1973. };
  1974. Buffer$1.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1975. if (!noAssert) checkOffset(offset, 4, this.length);
  1976. return (this[offset] << 24) |
  1977. (this[offset + 1] << 16) |
  1978. (this[offset + 2] << 8) |
  1979. (this[offset + 3])
  1980. };
  1981. Buffer$1.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1982. if (!noAssert) checkOffset(offset, 4, this.length);
  1983. return read(this, offset, true, 23, 4)
  1984. };
  1985. Buffer$1.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1986. if (!noAssert) checkOffset(offset, 4, this.length);
  1987. return read(this, offset, false, 23, 4)
  1988. };
  1989. Buffer$1.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1990. if (!noAssert) checkOffset(offset, 8, this.length);
  1991. return read(this, offset, true, 52, 8)
  1992. };
  1993. Buffer$1.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1994. if (!noAssert) checkOffset(offset, 8, this.length);
  1995. return read(this, offset, false, 52, 8)
  1996. };
  1997. function checkInt (buf, value, offset, ext, max, min) {
  1998. if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1999. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  2000. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  2001. }
  2002. Buffer$1.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  2003. value = +value;
  2004. offset = offset | 0;
  2005. byteLength = byteLength | 0;
  2006. if (!noAssert) {
  2007. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  2008. checkInt(this, value, offset, byteLength, maxBytes, 0);
  2009. }
  2010. var mul = 1;
  2011. var i = 0;
  2012. this[offset] = value & 0xFF;
  2013. while (++i < byteLength && (mul *= 0x100)) {
  2014. this[offset + i] = (value / mul) & 0xFF;
  2015. }
  2016. return offset + byteLength
  2017. };
  2018. Buffer$1.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  2019. value = +value;
  2020. offset = offset | 0;
  2021. byteLength = byteLength | 0;
  2022. if (!noAssert) {
  2023. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  2024. checkInt(this, value, offset, byteLength, maxBytes, 0);
  2025. }
  2026. var i = byteLength - 1;
  2027. var mul = 1;
  2028. this[offset + i] = value & 0xFF;
  2029. while (--i >= 0 && (mul *= 0x100)) {
  2030. this[offset + i] = (value / mul) & 0xFF;
  2031. }
  2032. return offset + byteLength
  2033. };
  2034. Buffer$1.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  2035. value = +value;
  2036. offset = offset | 0;
  2037. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
  2038. if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
  2039. this[offset] = (value & 0xff);
  2040. return offset + 1
  2041. };
  2042. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  2043. if (value < 0) value = 0xffff + value + 1;
  2044. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  2045. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  2046. (littleEndian ? i : 1 - i) * 8;
  2047. }
  2048. }
  2049. Buffer$1.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  2050. value = +value;
  2051. offset = offset | 0;
  2052. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  2053. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  2054. this[offset] = (value & 0xff);
  2055. this[offset + 1] = (value >>> 8);
  2056. } else {
  2057. objectWriteUInt16(this, value, offset, true);
  2058. }
  2059. return offset + 2
  2060. };
  2061. Buffer$1.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  2062. value = +value;
  2063. offset = offset | 0;
  2064. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  2065. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  2066. this[offset] = (value >>> 8);
  2067. this[offset + 1] = (value & 0xff);
  2068. } else {
  2069. objectWriteUInt16(this, value, offset, false);
  2070. }
  2071. return offset + 2
  2072. };
  2073. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  2074. if (value < 0) value = 0xffffffff + value + 1;
  2075. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  2076. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;
  2077. }
  2078. }
  2079. Buffer$1.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  2080. value = +value;
  2081. offset = offset | 0;
  2082. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  2083. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  2084. this[offset + 3] = (value >>> 24);
  2085. this[offset + 2] = (value >>> 16);
  2086. this[offset + 1] = (value >>> 8);
  2087. this[offset] = (value & 0xff);
  2088. } else {
  2089. objectWriteUInt32(this, value, offset, true);
  2090. }
  2091. return offset + 4
  2092. };
  2093. Buffer$1.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  2094. value = +value;
  2095. offset = offset | 0;
  2096. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  2097. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  2098. this[offset] = (value >>> 24);
  2099. this[offset + 1] = (value >>> 16);
  2100. this[offset + 2] = (value >>> 8);
  2101. this[offset + 3] = (value & 0xff);
  2102. } else {
  2103. objectWriteUInt32(this, value, offset, false);
  2104. }
  2105. return offset + 4
  2106. };
  2107. Buffer$1.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  2108. value = +value;
  2109. offset = offset | 0;
  2110. if (!noAssert) {
  2111. var limit = Math.pow(2, 8 * byteLength - 1);
  2112. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  2113. }
  2114. var i = 0;
  2115. var mul = 1;
  2116. var sub = 0;
  2117. this[offset] = value & 0xFF;
  2118. while (++i < byteLength && (mul *= 0x100)) {
  2119. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  2120. sub = 1;
  2121. }
  2122. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  2123. }
  2124. return offset + byteLength
  2125. };
  2126. Buffer$1.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  2127. value = +value;
  2128. offset = offset | 0;
  2129. if (!noAssert) {
  2130. var limit = Math.pow(2, 8 * byteLength - 1);
  2131. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  2132. }
  2133. var i = byteLength - 1;
  2134. var mul = 1;
  2135. var sub = 0;
  2136. this[offset + i] = value & 0xFF;
  2137. while (--i >= 0 && (mul *= 0x100)) {
  2138. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  2139. sub = 1;
  2140. }
  2141. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  2142. }
  2143. return offset + byteLength
  2144. };
  2145. Buffer$1.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  2146. value = +value;
  2147. offset = offset | 0;
  2148. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -128);
  2149. if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
  2150. if (value < 0) value = 0xff + value + 1;
  2151. this[offset] = (value & 0xff);
  2152. return offset + 1
  2153. };
  2154. Buffer$1.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  2155. value = +value;
  2156. offset = offset | 0;
  2157. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -32768);
  2158. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  2159. this[offset] = (value & 0xff);
  2160. this[offset + 1] = (value >>> 8);
  2161. } else {
  2162. objectWriteUInt16(this, value, offset, true);
  2163. }
  2164. return offset + 2
  2165. };
  2166. Buffer$1.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  2167. value = +value;
  2168. offset = offset | 0;
  2169. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -32768);
  2170. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  2171. this[offset] = (value >>> 8);
  2172. this[offset + 1] = (value & 0xff);
  2173. } else {
  2174. objectWriteUInt16(this, value, offset, false);
  2175. }
  2176. return offset + 2
  2177. };
  2178. Buffer$1.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  2179. value = +value;
  2180. offset = offset | 0;
  2181. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -2147483648);
  2182. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  2183. this[offset] = (value & 0xff);
  2184. this[offset + 1] = (value >>> 8);
  2185. this[offset + 2] = (value >>> 16);
  2186. this[offset + 3] = (value >>> 24);
  2187. } else {
  2188. objectWriteUInt32(this, value, offset, true);
  2189. }
  2190. return offset + 4
  2191. };
  2192. Buffer$1.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  2193. value = +value;
  2194. offset = offset | 0;
  2195. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -2147483648);
  2196. if (value < 0) value = 0xffffffff + value + 1;
  2197. if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  2198. this[offset] = (value >>> 24);
  2199. this[offset + 1] = (value >>> 16);
  2200. this[offset + 2] = (value >>> 8);
  2201. this[offset + 3] = (value & 0xff);
  2202. } else {
  2203. objectWriteUInt32(this, value, offset, false);
  2204. }
  2205. return offset + 4
  2206. };
  2207. function checkIEEE754 (buf, value, offset, ext, max, min) {
  2208. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  2209. if (offset < 0) throw new RangeError('Index out of range')
  2210. }
  2211. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  2212. if (!noAssert) {
  2213. checkIEEE754(buf, value, offset, 4);
  2214. }
  2215. write(buf, value, offset, littleEndian, 23, 4);
  2216. return offset + 4
  2217. }
  2218. Buffer$1.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  2219. return writeFloat(this, value, offset, true, noAssert)
  2220. };
  2221. Buffer$1.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  2222. return writeFloat(this, value, offset, false, noAssert)
  2223. };
  2224. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  2225. if (!noAssert) {
  2226. checkIEEE754(buf, value, offset, 8);
  2227. }
  2228. write(buf, value, offset, littleEndian, 52, 8);
  2229. return offset + 8
  2230. }
  2231. Buffer$1.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  2232. return writeDouble(this, value, offset, true, noAssert)
  2233. };
  2234. Buffer$1.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  2235. return writeDouble(this, value, offset, false, noAssert)
  2236. };
  2237. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  2238. Buffer$1.prototype.copy = function copy (target, targetStart, start, end) {
  2239. if (!start) start = 0;
  2240. if (!end && end !== 0) end = this.length;
  2241. if (targetStart >= target.length) targetStart = target.length;
  2242. if (!targetStart) targetStart = 0;
  2243. if (end > 0 && end < start) end = start;
  2244. // Copy 0 bytes; we're done
  2245. if (end === start) return 0
  2246. if (target.length === 0 || this.length === 0) return 0
  2247. // Fatal error conditions
  2248. if (targetStart < 0) {
  2249. throw new RangeError('targetStart out of bounds')
  2250. }
  2251. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  2252. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  2253. // Are we oob?
  2254. if (end > this.length) end = this.length;
  2255. if (target.length - targetStart < end - start) {
  2256. end = target.length - targetStart + start;
  2257. }
  2258. var len = end - start;
  2259. var i;
  2260. if (this === target && start < targetStart && targetStart < end) {
  2261. // descending copy from end
  2262. for (i = len - 1; i >= 0; --i) {
  2263. target[i + targetStart] = this[i + start];
  2264. }
  2265. } else if (len < 1000 || !Buffer$1.TYPED_ARRAY_SUPPORT) {
  2266. // ascending copy from start
  2267. for (i = 0; i < len; ++i) {
  2268. target[i + targetStart] = this[i + start];
  2269. }
  2270. } else {
  2271. Uint8Array.prototype.set.call(
  2272. target,
  2273. this.subarray(start, start + len),
  2274. targetStart
  2275. );
  2276. }
  2277. return len
  2278. };
  2279. // Usage:
  2280. // buffer.fill(number[, offset[, end]])
  2281. // buffer.fill(buffer[, offset[, end]])
  2282. // buffer.fill(string[, offset[, end]][, encoding])
  2283. Buffer$1.prototype.fill = function fill (val, start, end, encoding) {
  2284. // Handle string cases:
  2285. if (typeof val === 'string') {
  2286. if (typeof start === 'string') {
  2287. encoding = start;
  2288. start = 0;
  2289. end = this.length;
  2290. } else if (typeof end === 'string') {
  2291. encoding = end;
  2292. end = this.length;
  2293. }
  2294. if (val.length === 1) {
  2295. var code = val.charCodeAt(0);
  2296. if (code < 256) {
  2297. val = code;
  2298. }
  2299. }
  2300. if (encoding !== undefined && typeof encoding !== 'string') {
  2301. throw new TypeError('encoding must be a string')
  2302. }
  2303. if (typeof encoding === 'string' && !Buffer$1.isEncoding(encoding)) {
  2304. throw new TypeError('Unknown encoding: ' + encoding)
  2305. }
  2306. } else if (typeof val === 'number') {
  2307. val = val & 255;
  2308. }
  2309. // Invalid ranges are not set to a default, so can range check early.
  2310. if (start < 0 || this.length < start || this.length < end) {
  2311. throw new RangeError('Out of range index')
  2312. }
  2313. if (end <= start) {
  2314. return this
  2315. }
  2316. start = start >>> 0;
  2317. end = end === undefined ? this.length : end >>> 0;
  2318. if (!val) val = 0;
  2319. var i;
  2320. if (typeof val === 'number') {
  2321. for (i = start; i < end; ++i) {
  2322. this[i] = val;
  2323. }
  2324. } else {
  2325. var bytes = internalIsBuffer(val)
  2326. ? val
  2327. : utf8ToBytes(new Buffer$1(val, encoding).toString());
  2328. var len = bytes.length;
  2329. for (i = 0; i < end - start; ++i) {
  2330. this[i + start] = bytes[i % len];
  2331. }
  2332. }
  2333. return this
  2334. };
  2335. // HELPER FUNCTIONS
  2336. // ================
  2337. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
  2338. function base64clean (str) {
  2339. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  2340. str = stringtrim(str).replace(INVALID_BASE64_RE, '');
  2341. // Node converts strings with length < 2 to ''
  2342. if (str.length < 2) return ''
  2343. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  2344. while (str.length % 4 !== 0) {
  2345. str = str + '=';
  2346. }
  2347. return str
  2348. }
  2349. function stringtrim (str) {
  2350. if (str.trim) return str.trim()
  2351. return str.replace(/^\s+|\s+$/g, '')
  2352. }
  2353. function toHex (n) {
  2354. if (n < 16) return '0' + n.toString(16)
  2355. return n.toString(16)
  2356. }
  2357. function utf8ToBytes (string, units) {
  2358. units = units || Infinity;
  2359. var codePoint;
  2360. var length = string.length;
  2361. var leadSurrogate = null;
  2362. var bytes = [];
  2363. for (var i = 0; i < length; ++i) {
  2364. codePoint = string.charCodeAt(i);
  2365. // is surrogate component
  2366. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  2367. // last char was a lead
  2368. if (!leadSurrogate) {
  2369. // no lead yet
  2370. if (codePoint > 0xDBFF) {
  2371. // unexpected trail
  2372. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  2373. continue
  2374. } else if (i + 1 === length) {
  2375. // unpaired lead
  2376. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  2377. continue
  2378. }
  2379. // valid lead
  2380. leadSurrogate = codePoint;
  2381. continue
  2382. }
  2383. // 2 leads in a row
  2384. if (codePoint < 0xDC00) {
  2385. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  2386. leadSurrogate = codePoint;
  2387. continue
  2388. }
  2389. // valid surrogate pair
  2390. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
  2391. } else if (leadSurrogate) {
  2392. // valid bmp char, but last char was a lead
  2393. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  2394. }
  2395. leadSurrogate = null;
  2396. // encode utf8
  2397. if (codePoint < 0x80) {
  2398. if ((units -= 1) < 0) break
  2399. bytes.push(codePoint);
  2400. } else if (codePoint < 0x800) {
  2401. if ((units -= 2) < 0) break
  2402. bytes.push(
  2403. codePoint >> 0x6 | 0xC0,
  2404. codePoint & 0x3F | 0x80
  2405. );
  2406. } else if (codePoint < 0x10000) {
  2407. if ((units -= 3) < 0) break
  2408. bytes.push(
  2409. codePoint >> 0xC | 0xE0,
  2410. codePoint >> 0x6 & 0x3F | 0x80,
  2411. codePoint & 0x3F | 0x80
  2412. );
  2413. } else if (codePoint < 0x110000) {
  2414. if ((units -= 4) < 0) break
  2415. bytes.push(
  2416. codePoint >> 0x12 | 0xF0,
  2417. codePoint >> 0xC & 0x3F | 0x80,
  2418. codePoint >> 0x6 & 0x3F | 0x80,
  2419. codePoint & 0x3F | 0x80
  2420. );
  2421. } else {
  2422. throw new Error('Invalid code point')
  2423. }
  2424. }
  2425. return bytes
  2426. }
  2427. function asciiToBytes (str) {
  2428. var byteArray = [];
  2429. for (var i = 0; i < str.length; ++i) {
  2430. // Node's code seems to be doing this and not & 0x7F..
  2431. byteArray.push(str.charCodeAt(i) & 0xFF);
  2432. }
  2433. return byteArray
  2434. }
  2435. function utf16leToBytes (str, units) {
  2436. var c, hi, lo;
  2437. var byteArray = [];
  2438. for (var i = 0; i < str.length; ++i) {
  2439. if ((units -= 2) < 0) break
  2440. c = str.charCodeAt(i);
  2441. hi = c >> 8;
  2442. lo = c % 256;
  2443. byteArray.push(lo);
  2444. byteArray.push(hi);
  2445. }
  2446. return byteArray
  2447. }
  2448. function base64ToBytes (str) {
  2449. return toByteArray(base64clean(str))
  2450. }
  2451. function blitBuffer (src, dst, offset, length) {
  2452. for (var i = 0; i < length; ++i) {
  2453. if ((i + offset >= dst.length) || (i >= src.length)) break
  2454. dst[i + offset] = src[i];
  2455. }
  2456. return i
  2457. }
  2458. function isnan (val) {
  2459. return val !== val // eslint-disable-line no-self-compare
  2460. }
  2461. // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
  2462. // The _isBuffer check is for Safari 5-7 support, because it's missing
  2463. // Object.prototype.constructor. Remove this eventually
  2464. function isBuffer$1(obj) {
  2465. return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
  2466. }
  2467. function isFastBuffer (obj) {
  2468. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  2469. }
  2470. // For Node v0.10 support. Remove this eventually.
  2471. function isSlowBuffer (obj) {
  2472. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
  2473. }
  2474. /*
  2475. * Shared base64 decode helper for generated decode data.
  2476. * Assumes global atob is available.
  2477. */
  2478. function decodeBase64(input) {
  2479. const binary =
  2480. // eslint-disable-next-line n/no-unsupported-features/node-builtins
  2481. typeof atob === "function"
  2482. ? // Browser (and Node >=16)
  2483. // eslint-disable-next-line n/no-unsupported-features/node-builtins
  2484. atob(input)
  2485. : // Older Node versions (<16)
  2486. // eslint-disable-next-line n/no-unsupported-features/node-builtins
  2487. typeof Buffer$1.from === "function"
  2488. ? // eslint-disable-next-line n/no-unsupported-features/node-builtins
  2489. Buffer$1.from(input, "base64").toString("binary")
  2490. : // eslint-disable-next-line unicorn/no-new-buffer, n/no-deprecated-api
  2491. new Buffer$1(input, "base64").toString("binary");
  2492. const evenLength = binary.length & -2; // Round down to even length
  2493. const out = new Uint16Array(evenLength / 2);
  2494. for (let index = 0, outIndex = 0; index < evenLength; index += 2) {
  2495. const lo = binary.charCodeAt(index);
  2496. const hi = binary.charCodeAt(index + 1);
  2497. out[outIndex++] = lo | (hi << 8);
  2498. }
  2499. return out;
  2500. }
  2501. // Generated using scripts/write-decode-map.ts
  2502. 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");
  2503. /**
  2504. * Bit flags & masks for the binary trie encoding used for entity decoding.
  2505. *
  2506. * Bit layout (16 bits total):
  2507. * 15..14 VALUE_LENGTH (+1 encoding; 0 => no value)
  2508. * 13 FLAG13. If valueLength>0: semicolon required flag (implicit ';').
  2509. * If valueLength==0: compact run flag.
  2510. * 12..7 BRANCH_LENGTH Branch length (0 => single branch in 6..0 if jumpOffset==char) OR run length (when compact run)
  2511. * 6..0 JUMP_TABLE Jump offset (jump table) OR single-branch char code OR first run char
  2512. */
  2513. var BinTrieFlags;
  2514. (function (BinTrieFlags) {
  2515. BinTrieFlags[BinTrieFlags["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH";
  2516. BinTrieFlags[BinTrieFlags["FLAG13"] = 8192] = "FLAG13";
  2517. BinTrieFlags[BinTrieFlags["BRANCH_LENGTH"] = 8064] = "BRANCH_LENGTH";
  2518. BinTrieFlags[BinTrieFlags["JUMP_TABLE"] = 127] = "JUMP_TABLE";
  2519. })(BinTrieFlags || (BinTrieFlags = {}));
  2520. var CharCodes;
  2521. (function (CharCodes) {
  2522. CharCodes[CharCodes["NUM"] = 35] = "NUM";
  2523. CharCodes[CharCodes["SEMI"] = 59] = "SEMI";
  2524. CharCodes[CharCodes["EQUALS"] = 61] = "EQUALS";
  2525. CharCodes[CharCodes["ZERO"] = 48] = "ZERO";
  2526. CharCodes[CharCodes["NINE"] = 57] = "NINE";
  2527. CharCodes[CharCodes["LOWER_A"] = 97] = "LOWER_A";
  2528. CharCodes[CharCodes["LOWER_F"] = 102] = "LOWER_F";
  2529. CharCodes[CharCodes["LOWER_X"] = 120] = "LOWER_X";
  2530. CharCodes[CharCodes["LOWER_Z"] = 122] = "LOWER_Z";
  2531. CharCodes[CharCodes["UPPER_A"] = 65] = "UPPER_A";
  2532. CharCodes[CharCodes["UPPER_F"] = 70] = "UPPER_F";
  2533. CharCodes[CharCodes["UPPER_Z"] = 90] = "UPPER_Z";
  2534. })(CharCodes || (CharCodes = {}));
  2535. /** Bit that needs to be set to convert an upper case ASCII character to lower case */
  2536. const TO_LOWER_BIT = 32;
  2537. function isNumber$1(code) {
  2538. return code >= CharCodes.ZERO && code <= CharCodes.NINE;
  2539. }
  2540. function isHexadecimalCharacter(code) {
  2541. return ((code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_F) ||
  2542. (code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_F));
  2543. }
  2544. function isAsciiAlphaNumeric(code) {
  2545. return ((code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_Z) ||
  2546. (code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_Z) ||
  2547. isNumber$1(code));
  2548. }
  2549. /**
  2550. * Checks if the given character is a valid end character for an entity in an attribute.
  2551. *
  2552. * Attribute values that aren't terminated properly aren't parsed, and shouldn't lead to a parser error.
  2553. * See the example in https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state
  2554. */
  2555. function isEntityInAttributeInvalidEnd(code) {
  2556. return code === CharCodes.EQUALS || isAsciiAlphaNumeric(code);
  2557. }
  2558. var EntityDecoderState;
  2559. (function (EntityDecoderState) {
  2560. EntityDecoderState[EntityDecoderState["EntityStart"] = 0] = "EntityStart";
  2561. EntityDecoderState[EntityDecoderState["NumericStart"] = 1] = "NumericStart";
  2562. EntityDecoderState[EntityDecoderState["NumericDecimal"] = 2] = "NumericDecimal";
  2563. EntityDecoderState[EntityDecoderState["NumericHex"] = 3] = "NumericHex";
  2564. EntityDecoderState[EntityDecoderState["NamedEntity"] = 4] = "NamedEntity";
  2565. })(EntityDecoderState || (EntityDecoderState = {}));
  2566. var DecodingMode;
  2567. (function (DecodingMode) {
  2568. /** Entities in text nodes that can end with any character. */
  2569. DecodingMode[DecodingMode["Legacy"] = 0] = "Legacy";
  2570. /** Only allow entities terminated with a semicolon. */
  2571. DecodingMode[DecodingMode["Strict"] = 1] = "Strict";
  2572. /** Entities in attributes have limitations on ending characters. */
  2573. DecodingMode[DecodingMode["Attribute"] = 2] = "Attribute";
  2574. })(DecodingMode || (DecodingMode = {}));
  2575. /**
  2576. * Token decoder with support of writing partial entities.
  2577. */
  2578. class EntityDecoder {
  2579. constructor(
  2580. /** The tree used to decode entities. */
  2581. // biome-ignore lint/correctness/noUnusedPrivateClassMembers: False positive
  2582. decodeTree,
  2583. /**
  2584. * The function that is called when a codepoint is decoded.
  2585. *
  2586. * For multi-byte named entities, this will be called multiple times,
  2587. * with the second codepoint, and the same `consumed` value.
  2588. *
  2589. * @param codepoint The decoded codepoint.
  2590. * @param consumed The number of bytes consumed by the decoder.
  2591. */
  2592. emitCodePoint,
  2593. /** An object that is used to produce errors. */
  2594. errors) {
  2595. this.decodeTree = decodeTree;
  2596. this.emitCodePoint = emitCodePoint;
  2597. this.errors = errors;
  2598. /** The current state of the decoder. */
  2599. this.state = EntityDecoderState.EntityStart;
  2600. /** Characters that were consumed while parsing an entity. */
  2601. this.consumed = 1;
  2602. /**
  2603. * The result of the entity.
  2604. *
  2605. * Either the result index of a numeric entity, or the codepoint of a
  2606. * numeric entity.
  2607. */
  2608. this.result = 0;
  2609. /** The current index in the decode tree. */
  2610. this.treeIndex = 0;
  2611. /** The number of characters that were consumed in excess. */
  2612. this.excess = 1;
  2613. /** The mode in which the decoder is operating. */
  2614. this.decodeMode = DecodingMode.Strict;
  2615. /** The number of characters that have been consumed in the current run. */
  2616. this.runConsumed = 0;
  2617. }
  2618. /** Resets the instance to make it reusable. */
  2619. startEntity(decodeMode) {
  2620. this.decodeMode = decodeMode;
  2621. this.state = EntityDecoderState.EntityStart;
  2622. this.result = 0;
  2623. this.treeIndex = 0;
  2624. this.excess = 1;
  2625. this.consumed = 1;
  2626. this.runConsumed = 0;
  2627. }
  2628. /**
  2629. * Write an entity to the decoder. This can be called multiple times with partial entities.
  2630. * If the entity is incomplete, the decoder will return -1.
  2631. *
  2632. * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the
  2633. * entity is incomplete, and resume when the next string is written.
  2634. *
  2635. * @param input The string containing the entity (or a continuation of the entity).
  2636. * @param offset The offset at which the entity begins. Should be 0 if this is not the first call.
  2637. * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
  2638. */
  2639. write(input, offset) {
  2640. switch (this.state) {
  2641. case EntityDecoderState.EntityStart: {
  2642. if (input.charCodeAt(offset) === CharCodes.NUM) {
  2643. this.state = EntityDecoderState.NumericStart;
  2644. this.consumed += 1;
  2645. return this.stateNumericStart(input, offset + 1);
  2646. }
  2647. this.state = EntityDecoderState.NamedEntity;
  2648. return this.stateNamedEntity(input, offset);
  2649. }
  2650. case EntityDecoderState.NumericStart: {
  2651. return this.stateNumericStart(input, offset);
  2652. }
  2653. case EntityDecoderState.NumericDecimal: {
  2654. return this.stateNumericDecimal(input, offset);
  2655. }
  2656. case EntityDecoderState.NumericHex: {
  2657. return this.stateNumericHex(input, offset);
  2658. }
  2659. case EntityDecoderState.NamedEntity: {
  2660. return this.stateNamedEntity(input, offset);
  2661. }
  2662. }
  2663. }
  2664. /**
  2665. * Switches between the numeric decimal and hexadecimal states.
  2666. *
  2667. * Equivalent to the `Numeric character reference state` in the HTML spec.
  2668. *
  2669. * @param input The string containing the entity (or a continuation of the entity).
  2670. * @param offset The current offset.
  2671. * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
  2672. */
  2673. stateNumericStart(input, offset) {
  2674. if (offset >= input.length) {
  2675. return -1;
  2676. }
  2677. if ((input.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) {
  2678. this.state = EntityDecoderState.NumericHex;
  2679. this.consumed += 1;
  2680. return this.stateNumericHex(input, offset + 1);
  2681. }
  2682. this.state = EntityDecoderState.NumericDecimal;
  2683. return this.stateNumericDecimal(input, offset);
  2684. }
  2685. /**
  2686. * Parses a hexadecimal numeric entity.
  2687. *
  2688. * Equivalent to the `Hexademical character reference state` in the HTML spec.
  2689. *
  2690. * @param input The string containing the entity (or a continuation of the entity).
  2691. * @param offset The current offset.
  2692. * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
  2693. */
  2694. stateNumericHex(input, offset) {
  2695. while (offset < input.length) {
  2696. const char = input.charCodeAt(offset);
  2697. if (isNumber$1(char) || isHexadecimalCharacter(char)) {
  2698. // Convert hex digit to value (0-15); 'a'/'A' -> 10.
  2699. const digit = char <= CharCodes.NINE
  2700. ? char - CharCodes.ZERO
  2701. : (char | TO_LOWER_BIT) - CharCodes.LOWER_A + 10;
  2702. this.result = this.result * 16 + digit;
  2703. this.consumed++;
  2704. offset++;
  2705. }
  2706. else {
  2707. return this.emitNumericEntity(char, 3);
  2708. }
  2709. }
  2710. return -1; // Incomplete entity
  2711. }
  2712. /**
  2713. * Parses a decimal numeric entity.
  2714. *
  2715. * Equivalent to the `Decimal character reference state` in the HTML spec.
  2716. *
  2717. * @param input The string containing the entity (or a continuation of the entity).
  2718. * @param offset The current offset.
  2719. * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
  2720. */
  2721. stateNumericDecimal(input, offset) {
  2722. while (offset < input.length) {
  2723. const char = input.charCodeAt(offset);
  2724. if (isNumber$1(char)) {
  2725. this.result = this.result * 10 + (char - CharCodes.ZERO);
  2726. this.consumed++;
  2727. offset++;
  2728. }
  2729. else {
  2730. return this.emitNumericEntity(char, 2);
  2731. }
  2732. }
  2733. return -1; // Incomplete entity
  2734. }
  2735. /**
  2736. * Validate and emit a numeric entity.
  2737. *
  2738. * Implements the logic from the `Hexademical character reference start
  2739. * state` and `Numeric character reference end state` in the HTML spec.
  2740. *
  2741. * @param lastCp The last code point of the entity. Used to see if the
  2742. * entity was terminated with a semicolon.
  2743. * @param expectedLength The minimum number of characters that should be
  2744. * consumed. Used to validate that at least one digit
  2745. * was consumed.
  2746. * @returns The number of characters that were consumed.
  2747. */
  2748. emitNumericEntity(lastCp, expectedLength) {
  2749. var _a;
  2750. // Ensure we consumed at least one digit.
  2751. if (this.consumed <= expectedLength) {
  2752. (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed);
  2753. return 0;
  2754. }
  2755. // Figure out if this is a legit end of the entity
  2756. if (lastCp === CharCodes.SEMI) {
  2757. this.consumed += 1;
  2758. }
  2759. else if (this.decodeMode === DecodingMode.Strict) {
  2760. return 0;
  2761. }
  2762. this.emitCodePoint(replaceCodePoint(this.result), this.consumed);
  2763. if (this.errors) {
  2764. if (lastCp !== CharCodes.SEMI) {
  2765. this.errors.missingSemicolonAfterCharacterReference();
  2766. }
  2767. this.errors.validateNumericCharacterReference(this.result);
  2768. }
  2769. return this.consumed;
  2770. }
  2771. /**
  2772. * Parses a named entity.
  2773. *
  2774. * Equivalent to the `Named character reference state` in the HTML spec.
  2775. *
  2776. * @param input The string containing the entity (or a continuation of the entity).
  2777. * @param offset The current offset.
  2778. * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
  2779. */
  2780. stateNamedEntity(input, offset) {
  2781. const { decodeTree } = this;
  2782. let current = decodeTree[this.treeIndex];
  2783. // The length is the number of bytes of the value, including the current byte.
  2784. let valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
  2785. while (offset < input.length) {
  2786. // Handle compact runs (possibly inline): valueLength == 0 and SEMI_REQUIRED bit set.
  2787. if (valueLength === 0 && (current & BinTrieFlags.FLAG13) !== 0) {
  2788. const runLength = (current & BinTrieFlags.BRANCH_LENGTH) >> 7; /* 2..63 */
  2789. // If we are starting a run, check the first char.
  2790. if (this.runConsumed === 0) {
  2791. const firstChar = current & BinTrieFlags.JUMP_TABLE;
  2792. if (input.charCodeAt(offset) !== firstChar) {
  2793. return this.result === 0
  2794. ? 0
  2795. : this.emitNotTerminatedNamedEntity();
  2796. }
  2797. offset++;
  2798. this.excess++;
  2799. this.runConsumed++;
  2800. }
  2801. // Check remaining characters in the run.
  2802. while (this.runConsumed < runLength) {
  2803. if (offset >= input.length) {
  2804. return -1;
  2805. }
  2806. const charIndexInPacked = this.runConsumed - 1;
  2807. const packedWord = decodeTree[this.treeIndex + 1 + (charIndexInPacked >> 1)];
  2808. const expectedChar = charIndexInPacked % 2 === 0
  2809. ? packedWord & 0xff
  2810. : (packedWord >> 8) & 0xff;
  2811. if (input.charCodeAt(offset) !== expectedChar) {
  2812. this.runConsumed = 0;
  2813. return this.result === 0
  2814. ? 0
  2815. : this.emitNotTerminatedNamedEntity();
  2816. }
  2817. offset++;
  2818. this.excess++;
  2819. this.runConsumed++;
  2820. }
  2821. this.runConsumed = 0;
  2822. this.treeIndex += 1 + (runLength >> 1);
  2823. current = decodeTree[this.treeIndex];
  2824. valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
  2825. }
  2826. if (offset >= input.length)
  2827. break;
  2828. const char = input.charCodeAt(offset);
  2829. /*
  2830. * Implicit semicolon handling for nodes that require a semicolon but
  2831. * don't have an explicit ';' branch stored in the trie. If we have
  2832. * a value on the current node, it requires a semicolon, and the
  2833. * current input character is a semicolon, emit the entity using the
  2834. * current node (without descending further).
  2835. */
  2836. if (char === CharCodes.SEMI &&
  2837. valueLength !== 0 &&
  2838. (current & BinTrieFlags.FLAG13) !== 0) {
  2839. return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess);
  2840. }
  2841. this.treeIndex = determineBranch(decodeTree, current, this.treeIndex + Math.max(1, valueLength), char);
  2842. if (this.treeIndex < 0) {
  2843. return this.result === 0 ||
  2844. // If we are parsing an attribute
  2845. (this.decodeMode === DecodingMode.Attribute &&
  2846. // We shouldn't have consumed any characters after the entity,
  2847. (valueLength === 0 ||
  2848. // And there should be no invalid characters.
  2849. isEntityInAttributeInvalidEnd(char)))
  2850. ? 0
  2851. : this.emitNotTerminatedNamedEntity();
  2852. }
  2853. current = decodeTree[this.treeIndex];
  2854. valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
  2855. // If the branch is a value, store it and continue
  2856. if (valueLength !== 0) {
  2857. // If the entity is terminated by a semicolon, we are done.
  2858. if (char === CharCodes.SEMI) {
  2859. return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess);
  2860. }
  2861. // If we encounter a non-terminated (legacy) entity while parsing strictly, then ignore it.
  2862. if (this.decodeMode !== DecodingMode.Strict &&
  2863. (current & BinTrieFlags.FLAG13) === 0) {
  2864. this.result = this.treeIndex;
  2865. this.consumed += this.excess;
  2866. this.excess = 0;
  2867. }
  2868. }
  2869. // Increment offset & excess for next iteration
  2870. offset++;
  2871. this.excess++;
  2872. }
  2873. return -1;
  2874. }
  2875. /**
  2876. * Emit a named entity that was not terminated with a semicolon.
  2877. *
  2878. * @returns The number of characters consumed.
  2879. */
  2880. emitNotTerminatedNamedEntity() {
  2881. var _a;
  2882. const { result, decodeTree } = this;
  2883. const valueLength = (decodeTree[result] & BinTrieFlags.VALUE_LENGTH) >> 14;
  2884. this.emitNamedEntityData(result, valueLength, this.consumed);
  2885. (_a = this.errors) === null || _a === void 0 ? void 0 : _a.missingSemicolonAfterCharacterReference();
  2886. return this.consumed;
  2887. }
  2888. /**
  2889. * Emit a named entity.
  2890. *
  2891. * @param result The index of the entity in the decode tree.
  2892. * @param valueLength The number of bytes in the entity.
  2893. * @param consumed The number of characters consumed.
  2894. *
  2895. * @returns The number of characters consumed.
  2896. */
  2897. emitNamedEntityData(result, valueLength, consumed) {
  2898. const { decodeTree } = this;
  2899. this.emitCodePoint(valueLength === 1
  2900. ? decodeTree[result] &
  2901. ~(BinTrieFlags.VALUE_LENGTH | BinTrieFlags.FLAG13)
  2902. : decodeTree[result + 1], consumed);
  2903. if (valueLength === 3) {
  2904. // For multi-byte values, we need to emit the second byte.
  2905. this.emitCodePoint(decodeTree[result + 2], consumed);
  2906. }
  2907. return consumed;
  2908. }
  2909. /**
  2910. * Signal to the parser that the end of the input was reached.
  2911. *
  2912. * Remaining data will be emitted and relevant errors will be produced.
  2913. *
  2914. * @returns The number of characters consumed.
  2915. */
  2916. end() {
  2917. var _a;
  2918. switch (this.state) {
  2919. case EntityDecoderState.NamedEntity: {
  2920. // Emit a named entity if we have one.
  2921. return this.result !== 0 &&
  2922. (this.decodeMode !== DecodingMode.Attribute ||
  2923. this.result === this.treeIndex)
  2924. ? this.emitNotTerminatedNamedEntity()
  2925. : 0;
  2926. }
  2927. // Otherwise, emit a numeric entity if we have one.
  2928. case EntityDecoderState.NumericDecimal: {
  2929. return this.emitNumericEntity(0, 2);
  2930. }
  2931. case EntityDecoderState.NumericHex: {
  2932. return this.emitNumericEntity(0, 3);
  2933. }
  2934. case EntityDecoderState.NumericStart: {
  2935. (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed);
  2936. return 0;
  2937. }
  2938. case EntityDecoderState.EntityStart: {
  2939. // Return 0 if we have no entity.
  2940. return 0;
  2941. }
  2942. }
  2943. }
  2944. }
  2945. /**
  2946. * Creates a function that decodes entities in a string.
  2947. *
  2948. * @param decodeTree The decode tree.
  2949. * @returns A function that decodes entities in a string.
  2950. */
  2951. function getDecoder(decodeTree) {
  2952. let returnValue = "";
  2953. const decoder = new EntityDecoder(decodeTree, (data) => (returnValue += fromCodePoint(data)));
  2954. return function decodeWithTrie(input, decodeMode) {
  2955. let lastIndex = 0;
  2956. let offset = 0;
  2957. while ((offset = input.indexOf("&", offset)) >= 0) {
  2958. returnValue += input.slice(lastIndex, offset);
  2959. decoder.startEntity(decodeMode);
  2960. const length = decoder.write(input,
  2961. // Skip the "&"
  2962. offset + 1);
  2963. if (length < 0) {
  2964. lastIndex = offset + decoder.end();
  2965. break;
  2966. }
  2967. lastIndex = offset + length;
  2968. // If `length` is 0, skip the current `&` and continue.
  2969. offset = length === 0 ? lastIndex + 1 : lastIndex;
  2970. }
  2971. const result = returnValue + input.slice(lastIndex);
  2972. // Make sure we don't keep a reference to the final string.
  2973. returnValue = "";
  2974. return result;
  2975. };
  2976. }
  2977. /**
  2978. * Determines the branch of the current node that is taken given the current
  2979. * character. This function is used to traverse the trie.
  2980. *
  2981. * @param decodeTree The trie.
  2982. * @param current The current node.
  2983. * @param nodeIdx The index right after the current node and its value.
  2984. * @param char The current character.
  2985. * @returns The index of the next node, or -1 if no branch is taken.
  2986. */
  2987. function determineBranch(decodeTree, current, nodeIndex, char) {
  2988. const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;
  2989. const jumpOffset = current & BinTrieFlags.JUMP_TABLE;
  2990. // Case 1: Single branch encoded in jump offset
  2991. if (branchCount === 0) {
  2992. return jumpOffset !== 0 && char === jumpOffset ? nodeIndex : -1;
  2993. }
  2994. // Case 2: Multiple branches encoded in jump table
  2995. if (jumpOffset) {
  2996. const value = char - jumpOffset;
  2997. return value < 0 || value >= branchCount
  2998. ? -1
  2999. : decodeTree[nodeIndex + value] - 1;
  3000. }
  3001. // Case 3: Multiple branches encoded in packed dictionary (two keys per uint16)
  3002. const packedKeySlots = (branchCount + 1) >> 1;
  3003. /*
  3004. * Treat packed keys as a virtual sorted array of length `branchCount`.
  3005. * Key(i) = low byte for even i, high byte for odd i in slot i>>1.
  3006. */
  3007. let lo = 0;
  3008. let hi = branchCount - 1;
  3009. while (lo <= hi) {
  3010. const mid = (lo + hi) >>> 1;
  3011. const slot = mid >> 1;
  3012. const packed = decodeTree[nodeIndex + slot];
  3013. const midKey = (packed >> ((mid & 1) * 8)) & 0xff;
  3014. if (midKey < char) {
  3015. lo = mid + 1;
  3016. }
  3017. else if (midKey > char) {
  3018. hi = mid - 1;
  3019. }
  3020. else {
  3021. return decodeTree[nodeIndex + packedKeySlots + mid];
  3022. }
  3023. }
  3024. return -1;
  3025. }
  3026. const htmlDecoder = /* #__PURE__ */ getDecoder(htmlDecodeTree);
  3027. /**
  3028. * Decodes an HTML string.
  3029. *
  3030. * @param htmlString The string to decode.
  3031. * @param mode The decoding mode.
  3032. * @returns The decoded string.
  3033. */
  3034. function decodeHTML(htmlString, mode = DecodingMode.Legacy) {
  3035. return htmlDecoder(htmlString, mode);
  3036. }
  3037. const defaultDelimitersOpen = new Uint8Array([123, 123]);
  3038. const defaultDelimitersClose = new Uint8Array([125, 125]);
  3039. function isTagStartChar(c) {
  3040. return c >= 97 && c <= 122 || c >= 65 && c <= 90;
  3041. }
  3042. function isWhitespace(c) {
  3043. return c === 32 || c === 10 || c === 9 || c === 12 || c === 13;
  3044. }
  3045. function isEndOfTagSection(c) {
  3046. return c === 47 || c === 62 || isWhitespace(c);
  3047. }
  3048. function toCharCodes(str) {
  3049. const ret = new Uint8Array(str.length);
  3050. for (let i = 0; i < str.length; i++) {
  3051. ret[i] = str.charCodeAt(i);
  3052. }
  3053. return ret;
  3054. }
  3055. const Sequences = {
  3056. Cdata: new Uint8Array([67, 68, 65, 84, 65, 91]),
  3057. // CDATA[
  3058. CdataEnd: new Uint8Array([93, 93, 62]),
  3059. // ]]>
  3060. CommentEnd: new Uint8Array([45, 45, 62]),
  3061. // `-->`
  3062. ScriptEnd: new Uint8Array([60, 47, 115, 99, 114, 105, 112, 116]),
  3063. // `<\/script`
  3064. StyleEnd: new Uint8Array([60, 47, 115, 116, 121, 108, 101]),
  3065. // `</style`
  3066. TitleEnd: new Uint8Array([60, 47, 116, 105, 116, 108, 101]),
  3067. // `</title`
  3068. TextareaEnd: new Uint8Array([
  3069. 60,
  3070. 47,
  3071. 116,
  3072. 101,
  3073. 120,
  3074. 116,
  3075. 97,
  3076. 114,
  3077. 101,
  3078. 97
  3079. ])
  3080. // `</textarea
  3081. };
  3082. class Tokenizer {
  3083. constructor(stack, cbs) {
  3084. this.stack = stack;
  3085. this.cbs = cbs;
  3086. /** The current state the tokenizer is in. */
  3087. this.state = 1;
  3088. /** The read buffer. */
  3089. this.buffer = "";
  3090. /** The beginning of the section that is currently being read. */
  3091. this.sectionStart = 0;
  3092. /** The index within the buffer that we are currently looking at. */
  3093. this.index = 0;
  3094. /** The start of the last entity. */
  3095. this.entityStart = 0;
  3096. /** Some behavior, eg. when decoding entities, is done while we are in another state. This keeps track of the other state type. */
  3097. this.baseState = 1;
  3098. /** For special parsing behavior inside of script and style tags. */
  3099. this.inRCDATA = false;
  3100. /** For disabling RCDATA tags handling */
  3101. this.inXML = false;
  3102. /** For disabling interpolation parsing in v-pre */
  3103. this.inVPre = false;
  3104. /** Record newline positions for fast line / column calculation */
  3105. this.newlines = [];
  3106. this.mode = 0;
  3107. this.delimiterOpen = defaultDelimitersOpen;
  3108. this.delimiterClose = defaultDelimitersClose;
  3109. this.delimiterIndex = -1;
  3110. this.currentSequence = void 0;
  3111. this.sequenceIndex = 0;
  3112. {
  3113. this.entityDecoder = new EntityDecoder(
  3114. htmlDecodeTree,
  3115. (cp, consumed) => this.emitCodePoint(cp, consumed)
  3116. );
  3117. }
  3118. }
  3119. get inSFCRoot() {
  3120. return this.mode === 2 && this.stack.length === 0;
  3121. }
  3122. reset() {
  3123. this.state = 1;
  3124. this.mode = 0;
  3125. this.buffer = "";
  3126. this.sectionStart = 0;
  3127. this.index = 0;
  3128. this.baseState = 1;
  3129. this.inRCDATA = false;
  3130. this.currentSequence = void 0;
  3131. this.newlines.length = 0;
  3132. this.delimiterOpen = defaultDelimitersOpen;
  3133. this.delimiterClose = defaultDelimitersClose;
  3134. }
  3135. /**
  3136. * Generate Position object with line / column information using recorded
  3137. * newline positions. We know the index is always going to be an already
  3138. * processed index, so all the newlines up to this index should have been
  3139. * recorded.
  3140. */
  3141. getPos(index) {
  3142. let line = 1;
  3143. let column = index + 1;
  3144. const length = this.newlines.length;
  3145. let j = -1;
  3146. if (length > 100) {
  3147. let l = -1;
  3148. let r = length;
  3149. while (l + 1 < r) {
  3150. const m = l + r >>> 1;
  3151. this.newlines[m] < index ? l = m : r = m;
  3152. }
  3153. j = l;
  3154. } else {
  3155. for (let i = length - 1; i >= 0; i--) {
  3156. if (index > this.newlines[i]) {
  3157. j = i;
  3158. break;
  3159. }
  3160. }
  3161. }
  3162. if (j >= 0) {
  3163. line = j + 2;
  3164. column = index - this.newlines[j];
  3165. }
  3166. return {
  3167. column,
  3168. line,
  3169. offset: index
  3170. };
  3171. }
  3172. peek() {
  3173. return this.buffer.charCodeAt(this.index + 1);
  3174. }
  3175. stateText(c) {
  3176. if (c === 60) {
  3177. if (this.index > this.sectionStart) {
  3178. this.cbs.ontext(this.sectionStart, this.index);
  3179. }
  3180. this.state = 5;
  3181. this.sectionStart = this.index;
  3182. } else if (c === 38) {
  3183. this.startEntity();
  3184. } else if (!this.inVPre && c === this.delimiterOpen[0]) {
  3185. this.state = 2;
  3186. this.delimiterIndex = 0;
  3187. this.stateInterpolationOpen(c);
  3188. }
  3189. }
  3190. stateInterpolationOpen(c) {
  3191. if (c === this.delimiterOpen[this.delimiterIndex]) {
  3192. if (this.delimiterIndex === this.delimiterOpen.length - 1) {
  3193. const start = this.index + 1 - this.delimiterOpen.length;
  3194. if (start > this.sectionStart) {
  3195. this.cbs.ontext(this.sectionStart, start);
  3196. }
  3197. this.state = 3;
  3198. this.sectionStart = start;
  3199. } else {
  3200. this.delimiterIndex++;
  3201. }
  3202. } else if (this.inRCDATA) {
  3203. this.state = 32;
  3204. this.stateInRCDATA(c);
  3205. } else {
  3206. this.state = 1;
  3207. this.stateText(c);
  3208. }
  3209. }
  3210. stateInterpolation(c) {
  3211. if (c === this.delimiterClose[0]) {
  3212. this.state = 4;
  3213. this.delimiterIndex = 0;
  3214. this.stateInterpolationClose(c);
  3215. }
  3216. }
  3217. stateInterpolationClose(c) {
  3218. if (c === this.delimiterClose[this.delimiterIndex]) {
  3219. if (this.delimiterIndex === this.delimiterClose.length - 1) {
  3220. this.cbs.oninterpolation(this.sectionStart, this.index + 1);
  3221. if (this.inRCDATA) {
  3222. this.state = 32;
  3223. } else {
  3224. this.state = 1;
  3225. }
  3226. this.sectionStart = this.index + 1;
  3227. } else {
  3228. this.delimiterIndex++;
  3229. }
  3230. } else {
  3231. this.state = 3;
  3232. this.stateInterpolation(c);
  3233. }
  3234. }
  3235. stateSpecialStartSequence(c) {
  3236. const isEnd = this.sequenceIndex === this.currentSequence.length;
  3237. const isMatch = isEnd ? (
  3238. // If we are at the end of the sequence, make sure the tag name has ended
  3239. isEndOfTagSection(c)
  3240. ) : (
  3241. // Otherwise, do a case-insensitive comparison
  3242. (c | 32) === this.currentSequence[this.sequenceIndex]
  3243. );
  3244. if (!isMatch) {
  3245. this.inRCDATA = false;
  3246. } else if (!isEnd) {
  3247. this.sequenceIndex++;
  3248. return;
  3249. }
  3250. this.sequenceIndex = 0;
  3251. this.state = 6;
  3252. this.stateInTagName(c);
  3253. }
  3254. /** Look for an end tag. For <title> and <textarea>, also decode entities. */
  3255. stateInRCDATA(c) {
  3256. if (this.sequenceIndex === this.currentSequence.length) {
  3257. if (c === 62 || isWhitespace(c)) {
  3258. const endOfText = this.index - this.currentSequence.length;
  3259. if (this.sectionStart < endOfText) {
  3260. const actualIndex = this.index;
  3261. this.index = endOfText;
  3262. this.cbs.ontext(this.sectionStart, endOfText);
  3263. this.index = actualIndex;
  3264. }
  3265. this.sectionStart = endOfText + 2;
  3266. this.stateInClosingTagName(c);
  3267. this.inRCDATA = false;
  3268. return;
  3269. }
  3270. this.sequenceIndex = 0;
  3271. }
  3272. if ((c | 32) === this.currentSequence[this.sequenceIndex]) {
  3273. this.sequenceIndex += 1;
  3274. } else if (this.sequenceIndex === 0) {
  3275. if (this.currentSequence === Sequences.TitleEnd || this.currentSequence === Sequences.TextareaEnd && !this.inSFCRoot) {
  3276. if (c === 38) {
  3277. this.startEntity();
  3278. } else if (!this.inVPre && c === this.delimiterOpen[0]) {
  3279. this.state = 2;
  3280. this.delimiterIndex = 0;
  3281. this.stateInterpolationOpen(c);
  3282. }
  3283. } else if (this.fastForwardTo(60)) {
  3284. this.sequenceIndex = 1;
  3285. }
  3286. } else {
  3287. this.sequenceIndex = Number(c === 60);
  3288. }
  3289. }
  3290. stateCDATASequence(c) {
  3291. if (c === Sequences.Cdata[this.sequenceIndex]) {
  3292. if (++this.sequenceIndex === Sequences.Cdata.length) {
  3293. this.state = 28;
  3294. this.currentSequence = Sequences.CdataEnd;
  3295. this.sequenceIndex = 0;
  3296. this.sectionStart = this.index + 1;
  3297. }
  3298. } else {
  3299. this.sequenceIndex = 0;
  3300. this.state = 23;
  3301. this.stateInDeclaration(c);
  3302. }
  3303. }
  3304. /**
  3305. * When we wait for one specific character, we can speed things up
  3306. * by skipping through the buffer until we find it.
  3307. *
  3308. * @returns Whether the character was found.
  3309. */
  3310. fastForwardTo(c) {
  3311. while (++this.index < this.buffer.length) {
  3312. const cc = this.buffer.charCodeAt(this.index);
  3313. if (cc === 10) {
  3314. this.newlines.push(this.index);
  3315. }
  3316. if (cc === c) {
  3317. return true;
  3318. }
  3319. }
  3320. this.index = this.buffer.length - 1;
  3321. return false;
  3322. }
  3323. /**
  3324. * Comments and CDATA end with `-->` and `]]>`.
  3325. *
  3326. * Their common qualities are:
  3327. * - Their end sequences have a distinct character they start with.
  3328. * - That character is then repeated, so we have to check multiple repeats.
  3329. * - All characters but the start character of the sequence can be skipped.
  3330. */
  3331. stateInCommentLike(c) {
  3332. if (c === this.currentSequence[this.sequenceIndex]) {
  3333. if (++this.sequenceIndex === this.currentSequence.length) {
  3334. if (this.currentSequence === Sequences.CdataEnd) {
  3335. this.cbs.oncdata(this.sectionStart, this.index - 2);
  3336. } else {
  3337. this.cbs.oncomment(this.sectionStart, this.index - 2);
  3338. }
  3339. this.sequenceIndex = 0;
  3340. this.sectionStart = this.index + 1;
  3341. this.state = 1;
  3342. }
  3343. } else if (this.sequenceIndex === 0) {
  3344. if (this.fastForwardTo(this.currentSequence[0])) {
  3345. this.sequenceIndex = 1;
  3346. }
  3347. } else if (c !== this.currentSequence[this.sequenceIndex - 1]) {
  3348. this.sequenceIndex = 0;
  3349. }
  3350. }
  3351. startSpecial(sequence, offset) {
  3352. this.enterRCDATA(sequence, offset);
  3353. this.state = 31;
  3354. }
  3355. enterRCDATA(sequence, offset) {
  3356. this.inRCDATA = true;
  3357. this.currentSequence = sequence;
  3358. this.sequenceIndex = offset;
  3359. }
  3360. stateBeforeTagName(c) {
  3361. if (c === 33) {
  3362. this.state = 22;
  3363. this.sectionStart = this.index + 1;
  3364. } else if (c === 63) {
  3365. this.state = 24;
  3366. this.sectionStart = this.index + 1;
  3367. } else if (isTagStartChar(c)) {
  3368. this.sectionStart = this.index;
  3369. if (this.mode === 0) {
  3370. this.state = 6;
  3371. } else if (this.inSFCRoot) {
  3372. this.state = 34;
  3373. } else if (!this.inXML) {
  3374. if (c === 116) {
  3375. this.state = 30;
  3376. } else {
  3377. this.state = c === 115 ? 29 : 6;
  3378. }
  3379. } else {
  3380. this.state = 6;
  3381. }
  3382. } else if (c === 47) {
  3383. this.state = 8;
  3384. } else {
  3385. this.state = 1;
  3386. this.stateText(c);
  3387. }
  3388. }
  3389. stateInTagName(c) {
  3390. if (isEndOfTagSection(c)) {
  3391. this.handleTagName(c);
  3392. }
  3393. }
  3394. stateInSFCRootTagName(c) {
  3395. if (isEndOfTagSection(c)) {
  3396. const tag = this.buffer.slice(this.sectionStart, this.index);
  3397. if (tag !== "template") {
  3398. this.enterRCDATA(toCharCodes(`</` + tag), 0);
  3399. }
  3400. this.handleTagName(c);
  3401. }
  3402. }
  3403. handleTagName(c) {
  3404. this.cbs.onopentagname(this.sectionStart, this.index);
  3405. this.sectionStart = -1;
  3406. this.state = 11;
  3407. this.stateBeforeAttrName(c);
  3408. }
  3409. stateBeforeClosingTagName(c) {
  3410. if (isWhitespace(c)) ; else if (c === 62) {
  3411. {
  3412. this.cbs.onerr(14, this.index);
  3413. }
  3414. this.state = 1;
  3415. this.sectionStart = this.index + 1;
  3416. } else {
  3417. this.state = isTagStartChar(c) ? 9 : 27;
  3418. this.sectionStart = this.index;
  3419. }
  3420. }
  3421. stateInClosingTagName(c) {
  3422. if (c === 62 || isWhitespace(c)) {
  3423. this.cbs.onclosetag(this.sectionStart, this.index);
  3424. this.sectionStart = -1;
  3425. this.state = 10;
  3426. this.stateAfterClosingTagName(c);
  3427. }
  3428. }
  3429. stateAfterClosingTagName(c) {
  3430. if (c === 62) {
  3431. this.state = 1;
  3432. this.sectionStart = this.index + 1;
  3433. }
  3434. }
  3435. stateBeforeAttrName(c) {
  3436. if (c === 62) {
  3437. this.cbs.onopentagend(this.index);
  3438. if (this.inRCDATA) {
  3439. this.state = 32;
  3440. } else {
  3441. this.state = 1;
  3442. }
  3443. this.sectionStart = this.index + 1;
  3444. } else if (c === 47) {
  3445. this.state = 7;
  3446. if (this.peek() !== 62) {
  3447. this.cbs.onerr(22, this.index);
  3448. }
  3449. } else if (c === 60 && this.peek() === 47) {
  3450. this.cbs.onopentagend(this.index);
  3451. this.state = 5;
  3452. this.sectionStart = this.index;
  3453. } else if (!isWhitespace(c)) {
  3454. if (c === 61) {
  3455. this.cbs.onerr(
  3456. 19,
  3457. this.index
  3458. );
  3459. }
  3460. this.handleAttrStart(c);
  3461. }
  3462. }
  3463. handleAttrStart(c) {
  3464. if (c === 118 && this.peek() === 45) {
  3465. this.state = 13;
  3466. this.sectionStart = this.index;
  3467. } else if (c === 46 || c === 58 || c === 64 || c === 35) {
  3468. this.cbs.ondirname(this.index, this.index + 1);
  3469. this.state = 14;
  3470. this.sectionStart = this.index + 1;
  3471. } else {
  3472. this.state = 12;
  3473. this.sectionStart = this.index;
  3474. }
  3475. }
  3476. stateInSelfClosingTag(c) {
  3477. if (c === 62) {
  3478. this.cbs.onselfclosingtag(this.index);
  3479. this.state = 1;
  3480. this.sectionStart = this.index + 1;
  3481. this.inRCDATA = false;
  3482. } else if (!isWhitespace(c)) {
  3483. this.state = 11;
  3484. this.stateBeforeAttrName(c);
  3485. }
  3486. }
  3487. stateInAttrName(c) {
  3488. if (c === 61 || isEndOfTagSection(c)) {
  3489. this.cbs.onattribname(this.sectionStart, this.index);
  3490. this.handleAttrNameEnd(c);
  3491. } else if (c === 34 || c === 39 || c === 60) {
  3492. this.cbs.onerr(
  3493. 17,
  3494. this.index
  3495. );
  3496. }
  3497. }
  3498. stateInDirName(c) {
  3499. if (c === 61 || isEndOfTagSection(c)) {
  3500. this.cbs.ondirname(this.sectionStart, this.index);
  3501. this.handleAttrNameEnd(c);
  3502. } else if (c === 58) {
  3503. this.cbs.ondirname(this.sectionStart, this.index);
  3504. this.state = 14;
  3505. this.sectionStart = this.index + 1;
  3506. } else if (c === 46) {
  3507. this.cbs.ondirname(this.sectionStart, this.index);
  3508. this.state = 16;
  3509. this.sectionStart = this.index + 1;
  3510. }
  3511. }
  3512. stateInDirArg(c) {
  3513. if (c === 61 || isEndOfTagSection(c)) {
  3514. this.cbs.ondirarg(this.sectionStart, this.index);
  3515. this.handleAttrNameEnd(c);
  3516. } else if (c === 91) {
  3517. this.state = 15;
  3518. } else if (c === 46) {
  3519. this.cbs.ondirarg(this.sectionStart, this.index);
  3520. this.state = 16;
  3521. this.sectionStart = this.index + 1;
  3522. }
  3523. }
  3524. stateInDynamicDirArg(c) {
  3525. if (c === 93) {
  3526. this.state = 14;
  3527. } else if (c === 61 || isEndOfTagSection(c)) {
  3528. this.cbs.ondirarg(this.sectionStart, this.index + 1);
  3529. this.handleAttrNameEnd(c);
  3530. {
  3531. this.cbs.onerr(
  3532. 27,
  3533. this.index
  3534. );
  3535. }
  3536. }
  3537. }
  3538. stateInDirModifier(c) {
  3539. if (c === 61 || isEndOfTagSection(c)) {
  3540. this.cbs.ondirmodifier(this.sectionStart, this.index);
  3541. this.handleAttrNameEnd(c);
  3542. } else if (c === 46) {
  3543. this.cbs.ondirmodifier(this.sectionStart, this.index);
  3544. this.sectionStart = this.index + 1;
  3545. }
  3546. }
  3547. handleAttrNameEnd(c) {
  3548. this.sectionStart = this.index;
  3549. this.state = 17;
  3550. this.cbs.onattribnameend(this.index);
  3551. this.stateAfterAttrName(c);
  3552. }
  3553. stateAfterAttrName(c) {
  3554. if (c === 61) {
  3555. this.state = 18;
  3556. } else if (c === 47 || c === 62) {
  3557. this.cbs.onattribend(0, this.sectionStart);
  3558. this.sectionStart = -1;
  3559. this.state = 11;
  3560. this.stateBeforeAttrName(c);
  3561. } else if (!isWhitespace(c)) {
  3562. this.cbs.onattribend(0, this.sectionStart);
  3563. this.handleAttrStart(c);
  3564. }
  3565. }
  3566. stateBeforeAttrValue(c) {
  3567. if (c === 34) {
  3568. this.state = 19;
  3569. this.sectionStart = this.index + 1;
  3570. } else if (c === 39) {
  3571. this.state = 20;
  3572. this.sectionStart = this.index + 1;
  3573. } else if (!isWhitespace(c)) {
  3574. this.sectionStart = this.index;
  3575. this.state = 21;
  3576. this.stateInAttrValueNoQuotes(c);
  3577. }
  3578. }
  3579. handleInAttrValue(c, quote) {
  3580. if (c === quote || false) {
  3581. this.cbs.onattribdata(this.sectionStart, this.index);
  3582. this.sectionStart = -1;
  3583. this.cbs.onattribend(
  3584. quote === 34 ? 3 : 2,
  3585. this.index + 1
  3586. );
  3587. this.state = 11;
  3588. } else if (c === 38) {
  3589. this.startEntity();
  3590. }
  3591. }
  3592. stateInAttrValueDoubleQuotes(c) {
  3593. this.handleInAttrValue(c, 34);
  3594. }
  3595. stateInAttrValueSingleQuotes(c) {
  3596. this.handleInAttrValue(c, 39);
  3597. }
  3598. stateInAttrValueNoQuotes(c) {
  3599. if (isWhitespace(c) || c === 62) {
  3600. this.cbs.onattribdata(this.sectionStart, this.index);
  3601. this.sectionStart = -1;
  3602. this.cbs.onattribend(1, this.index);
  3603. this.state = 11;
  3604. this.stateBeforeAttrName(c);
  3605. } else if (c === 34 || c === 39 || c === 60 || c === 61 || c === 96) {
  3606. this.cbs.onerr(
  3607. 18,
  3608. this.index
  3609. );
  3610. } else if (c === 38) {
  3611. this.startEntity();
  3612. }
  3613. }
  3614. stateBeforeDeclaration(c) {
  3615. if (c === 91) {
  3616. this.state = 26;
  3617. this.sequenceIndex = 0;
  3618. } else {
  3619. this.state = c === 45 ? 25 : 23;
  3620. }
  3621. }
  3622. stateInDeclaration(c) {
  3623. if (c === 62 || this.fastForwardTo(62)) {
  3624. this.state = 1;
  3625. this.sectionStart = this.index + 1;
  3626. }
  3627. }
  3628. stateInProcessingInstruction(c) {
  3629. if (c === 62 || this.fastForwardTo(62)) {
  3630. this.cbs.onprocessinginstruction(this.sectionStart, this.index);
  3631. this.state = 1;
  3632. this.sectionStart = this.index + 1;
  3633. }
  3634. }
  3635. stateBeforeComment(c) {
  3636. if (c === 45) {
  3637. this.state = 28;
  3638. this.currentSequence = Sequences.CommentEnd;
  3639. this.sequenceIndex = 2;
  3640. this.sectionStart = this.index + 1;
  3641. } else {
  3642. this.state = 23;
  3643. }
  3644. }
  3645. stateInSpecialComment(c) {
  3646. if (c === 62 || this.fastForwardTo(62)) {
  3647. this.cbs.oncomment(this.sectionStart, this.index);
  3648. this.state = 1;
  3649. this.sectionStart = this.index + 1;
  3650. }
  3651. }
  3652. stateBeforeSpecialS(c) {
  3653. if (c === Sequences.ScriptEnd[3]) {
  3654. this.startSpecial(Sequences.ScriptEnd, 4);
  3655. } else if (c === Sequences.StyleEnd[3]) {
  3656. this.startSpecial(Sequences.StyleEnd, 4);
  3657. } else {
  3658. this.state = 6;
  3659. this.stateInTagName(c);
  3660. }
  3661. }
  3662. stateBeforeSpecialT(c) {
  3663. if (c === Sequences.TitleEnd[3]) {
  3664. this.startSpecial(Sequences.TitleEnd, 4);
  3665. } else if (c === Sequences.TextareaEnd[3]) {
  3666. this.startSpecial(Sequences.TextareaEnd, 4);
  3667. } else {
  3668. this.state = 6;
  3669. this.stateInTagName(c);
  3670. }
  3671. }
  3672. startEntity() {
  3673. {
  3674. this.baseState = this.state;
  3675. this.state = 33;
  3676. this.entityStart = this.index;
  3677. this.entityDecoder.startEntity(
  3678. this.baseState === 1 || this.baseState === 32 ? DecodingMode.Legacy : DecodingMode.Attribute
  3679. );
  3680. }
  3681. }
  3682. stateInEntity() {
  3683. {
  3684. const length = this.entityDecoder.write(this.buffer, this.index);
  3685. if (length >= 0) {
  3686. this.state = this.baseState;
  3687. if (length === 0) {
  3688. this.index = this.entityStart;
  3689. }
  3690. } else {
  3691. this.index = this.buffer.length - 1;
  3692. }
  3693. }
  3694. }
  3695. /**
  3696. * Iterates through the buffer, calling the function corresponding to the current state.
  3697. *
  3698. * States that are more likely to be hit are higher up, as a performance improvement.
  3699. */
  3700. parse(input) {
  3701. this.buffer = input;
  3702. while (this.index < this.buffer.length) {
  3703. const c = this.buffer.charCodeAt(this.index);
  3704. if (c === 10 && this.state !== 33) {
  3705. this.newlines.push(this.index);
  3706. }
  3707. switch (this.state) {
  3708. case 1: {
  3709. this.stateText(c);
  3710. break;
  3711. }
  3712. case 2: {
  3713. this.stateInterpolationOpen(c);
  3714. break;
  3715. }
  3716. case 3: {
  3717. this.stateInterpolation(c);
  3718. break;
  3719. }
  3720. case 4: {
  3721. this.stateInterpolationClose(c);
  3722. break;
  3723. }
  3724. case 31: {
  3725. this.stateSpecialStartSequence(c);
  3726. break;
  3727. }
  3728. case 32: {
  3729. this.stateInRCDATA(c);
  3730. break;
  3731. }
  3732. case 26: {
  3733. this.stateCDATASequence(c);
  3734. break;
  3735. }
  3736. case 19: {
  3737. this.stateInAttrValueDoubleQuotes(c);
  3738. break;
  3739. }
  3740. case 12: {
  3741. this.stateInAttrName(c);
  3742. break;
  3743. }
  3744. case 13: {
  3745. this.stateInDirName(c);
  3746. break;
  3747. }
  3748. case 14: {
  3749. this.stateInDirArg(c);
  3750. break;
  3751. }
  3752. case 15: {
  3753. this.stateInDynamicDirArg(c);
  3754. break;
  3755. }
  3756. case 16: {
  3757. this.stateInDirModifier(c);
  3758. break;
  3759. }
  3760. case 28: {
  3761. this.stateInCommentLike(c);
  3762. break;
  3763. }
  3764. case 27: {
  3765. this.stateInSpecialComment(c);
  3766. break;
  3767. }
  3768. case 11: {
  3769. this.stateBeforeAttrName(c);
  3770. break;
  3771. }
  3772. case 6: {
  3773. this.stateInTagName(c);
  3774. break;
  3775. }
  3776. case 34: {
  3777. this.stateInSFCRootTagName(c);
  3778. break;
  3779. }
  3780. case 9: {
  3781. this.stateInClosingTagName(c);
  3782. break;
  3783. }
  3784. case 5: {
  3785. this.stateBeforeTagName(c);
  3786. break;
  3787. }
  3788. case 17: {
  3789. this.stateAfterAttrName(c);
  3790. break;
  3791. }
  3792. case 20: {
  3793. this.stateInAttrValueSingleQuotes(c);
  3794. break;
  3795. }
  3796. case 18: {
  3797. this.stateBeforeAttrValue(c);
  3798. break;
  3799. }
  3800. case 8: {
  3801. this.stateBeforeClosingTagName(c);
  3802. break;
  3803. }
  3804. case 10: {
  3805. this.stateAfterClosingTagName(c);
  3806. break;
  3807. }
  3808. case 29: {
  3809. this.stateBeforeSpecialS(c);
  3810. break;
  3811. }
  3812. case 30: {
  3813. this.stateBeforeSpecialT(c);
  3814. break;
  3815. }
  3816. case 21: {
  3817. this.stateInAttrValueNoQuotes(c);
  3818. break;
  3819. }
  3820. case 7: {
  3821. this.stateInSelfClosingTag(c);
  3822. break;
  3823. }
  3824. case 23: {
  3825. this.stateInDeclaration(c);
  3826. break;
  3827. }
  3828. case 22: {
  3829. this.stateBeforeDeclaration(c);
  3830. break;
  3831. }
  3832. case 25: {
  3833. this.stateBeforeComment(c);
  3834. break;
  3835. }
  3836. case 24: {
  3837. this.stateInProcessingInstruction(c);
  3838. break;
  3839. }
  3840. case 33: {
  3841. this.stateInEntity();
  3842. break;
  3843. }
  3844. }
  3845. this.index++;
  3846. }
  3847. this.cleanup();
  3848. this.finish();
  3849. }
  3850. /**
  3851. * Remove data that has already been consumed from the buffer.
  3852. */
  3853. cleanup() {
  3854. if (this.sectionStart !== this.index) {
  3855. if (this.state === 1 || this.state === 32 && this.sequenceIndex === 0) {
  3856. this.cbs.ontext(this.sectionStart, this.index);
  3857. this.sectionStart = this.index;
  3858. } else if (this.state === 19 || this.state === 20 || this.state === 21) {
  3859. this.cbs.onattribdata(this.sectionStart, this.index);
  3860. this.sectionStart = this.index;
  3861. }
  3862. }
  3863. }
  3864. finish() {
  3865. if (this.state === 33) {
  3866. this.entityDecoder.end();
  3867. this.state = this.baseState;
  3868. }
  3869. this.handleTrailingData();
  3870. this.cbs.onend();
  3871. }
  3872. /** Handle any trailing data. */
  3873. handleTrailingData() {
  3874. const endIndex = this.buffer.length;
  3875. if (this.sectionStart >= endIndex) {
  3876. return;
  3877. }
  3878. if (this.state === 28) {
  3879. if (this.currentSequence === Sequences.CdataEnd) {
  3880. this.cbs.oncdata(this.sectionStart, endIndex);
  3881. } else {
  3882. this.cbs.oncomment(this.sectionStart, endIndex);
  3883. }
  3884. } 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 {
  3885. this.cbs.ontext(this.sectionStart, endIndex);
  3886. }
  3887. }
  3888. emitCodePoint(cp, consumed) {
  3889. {
  3890. if (this.baseState !== 1 && this.baseState !== 32) {
  3891. if (this.sectionStart < this.entityStart) {
  3892. this.cbs.onattribdata(this.sectionStart, this.entityStart);
  3893. }
  3894. this.sectionStart = this.entityStart + consumed;
  3895. this.index = this.sectionStart - 1;
  3896. this.cbs.onattribentity(
  3897. fromCodePoint(cp),
  3898. this.entityStart,
  3899. this.sectionStart
  3900. );
  3901. } else {
  3902. if (this.sectionStart < this.entityStart) {
  3903. this.cbs.ontext(this.sectionStart, this.entityStart);
  3904. }
  3905. this.sectionStart = this.entityStart + consumed;
  3906. this.index = this.sectionStart - 1;
  3907. this.cbs.ontextentity(
  3908. fromCodePoint(cp),
  3909. this.entityStart,
  3910. this.sectionStart
  3911. );
  3912. }
  3913. }
  3914. }
  3915. }
  3916. const CompilerDeprecationTypes = {
  3917. "COMPILER_IS_ON_ELEMENT": "COMPILER_IS_ON_ELEMENT",
  3918. "COMPILER_V_BIND_SYNC": "COMPILER_V_BIND_SYNC",
  3919. "COMPILER_V_BIND_OBJECT_ORDER": "COMPILER_V_BIND_OBJECT_ORDER",
  3920. "COMPILER_V_ON_NATIVE": "COMPILER_V_ON_NATIVE",
  3921. "COMPILER_V_IF_V_FOR_PRECEDENCE": "COMPILER_V_IF_V_FOR_PRECEDENCE",
  3922. "COMPILER_NATIVE_TEMPLATE": "COMPILER_NATIVE_TEMPLATE",
  3923. "COMPILER_INLINE_TEMPLATE": "COMPILER_INLINE_TEMPLATE",
  3924. "COMPILER_FILTERS": "COMPILER_FILTERS"
  3925. };
  3926. const deprecationData = {
  3927. ["COMPILER_IS_ON_ELEMENT"]: {
  3928. 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:".`,
  3929. link: `https://v3-migration.vuejs.org/breaking-changes/custom-elements-interop.html`
  3930. },
  3931. ["COMPILER_V_BIND_SYNC"]: {
  3932. 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}\`.`,
  3933. link: `https://v3-migration.vuejs.org/breaking-changes/v-model.html`
  3934. },
  3935. ["COMPILER_V_BIND_OBJECT_ORDER"]: {
  3936. 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.`,
  3937. link: `https://v3-migration.vuejs.org/breaking-changes/v-bind.html`
  3938. },
  3939. ["COMPILER_V_ON_NATIVE"]: {
  3940. message: `.native modifier for v-on has been removed as is no longer necessary.`,
  3941. link: `https://v3-migration.vuejs.org/breaking-changes/v-on-native-modifier-removed.html`
  3942. },
  3943. ["COMPILER_V_IF_V_FOR_PRECEDENCE"]: {
  3944. 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.`,
  3945. link: `https://v3-migration.vuejs.org/breaking-changes/v-if-v-for.html`
  3946. },
  3947. ["COMPILER_NATIVE_TEMPLATE"]: {
  3948. message: `<template> with no special directives will render as a native template element instead of its inner content in Vue 3.`
  3949. },
  3950. ["COMPILER_INLINE_TEMPLATE"]: {
  3951. message: `"inline-template" has been removed in Vue 3.`,
  3952. link: `https://v3-migration.vuejs.org/breaking-changes/inline-template-attribute.html`
  3953. },
  3954. ["COMPILER_FILTERS"]: {
  3955. 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.`,
  3956. link: `https://v3-migration.vuejs.org/breaking-changes/filters.html`
  3957. }
  3958. };
  3959. function getCompatValue(key, { compatConfig }) {
  3960. const value = compatConfig && compatConfig[key];
  3961. if (key === "MODE") {
  3962. return value || 3;
  3963. } else {
  3964. return value;
  3965. }
  3966. }
  3967. function isCompatEnabled(key, context) {
  3968. const mode = getCompatValue("MODE", context);
  3969. const value = getCompatValue(key, context);
  3970. return mode === 3 ? value === true : value !== false;
  3971. }
  3972. function checkCompatEnabled(key, context, loc, ...args) {
  3973. const enabled = isCompatEnabled(key, context);
  3974. if (enabled) {
  3975. warnDeprecation(key, context, loc, ...args);
  3976. }
  3977. return enabled;
  3978. }
  3979. function warnDeprecation(key, context, loc, ...args) {
  3980. const val = getCompatValue(key, context);
  3981. if (val === "suppress-warning") {
  3982. return;
  3983. }
  3984. const { message, link } = deprecationData[key];
  3985. const msg = `(deprecation ${key}) ${typeof message === "function" ? message(...args) : message}${link ? `
  3986. Details: ${link}` : ``}`;
  3987. const err = new SyntaxError(msg);
  3988. err.code = key;
  3989. if (loc) err.loc = loc;
  3990. context.onWarn(err);
  3991. }
  3992. function defaultOnError(error) {
  3993. throw error;
  3994. }
  3995. function defaultOnWarn(msg) {
  3996. console.warn(`[Vue warn] ${msg.message}`);
  3997. }
  3998. function createCompilerError(code, loc, messages, additionalMessage) {
  3999. const msg = (messages || errorMessages$1)[code] + (additionalMessage || ``) ;
  4000. const error = new SyntaxError(String(msg));
  4001. error.code = code;
  4002. error.loc = loc;
  4003. return error;
  4004. }
  4005. const ErrorCodes = {
  4006. "ABRUPT_CLOSING_OF_EMPTY_COMMENT": 0,
  4007. "0": "ABRUPT_CLOSING_OF_EMPTY_COMMENT",
  4008. "CDATA_IN_HTML_CONTENT": 1,
  4009. "1": "CDATA_IN_HTML_CONTENT",
  4010. "DUPLICATE_ATTRIBUTE": 2,
  4011. "2": "DUPLICATE_ATTRIBUTE",
  4012. "END_TAG_WITH_ATTRIBUTES": 3,
  4013. "3": "END_TAG_WITH_ATTRIBUTES",
  4014. "END_TAG_WITH_TRAILING_SOLIDUS": 4,
  4015. "4": "END_TAG_WITH_TRAILING_SOLIDUS",
  4016. "EOF_BEFORE_TAG_NAME": 5,
  4017. "5": "EOF_BEFORE_TAG_NAME",
  4018. "EOF_IN_CDATA": 6,
  4019. "6": "EOF_IN_CDATA",
  4020. "EOF_IN_COMMENT": 7,
  4021. "7": "EOF_IN_COMMENT",
  4022. "EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT": 8,
  4023. "8": "EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT",
  4024. "EOF_IN_TAG": 9,
  4025. "9": "EOF_IN_TAG",
  4026. "INCORRECTLY_CLOSED_COMMENT": 10,
  4027. "10": "INCORRECTLY_CLOSED_COMMENT",
  4028. "INCORRECTLY_OPENED_COMMENT": 11,
  4029. "11": "INCORRECTLY_OPENED_COMMENT",
  4030. "INVALID_FIRST_CHARACTER_OF_TAG_NAME": 12,
  4031. "12": "INVALID_FIRST_CHARACTER_OF_TAG_NAME",
  4032. "MISSING_ATTRIBUTE_VALUE": 13,
  4033. "13": "MISSING_ATTRIBUTE_VALUE",
  4034. "MISSING_END_TAG_NAME": 14,
  4035. "14": "MISSING_END_TAG_NAME",
  4036. "MISSING_WHITESPACE_BETWEEN_ATTRIBUTES": 15,
  4037. "15": "MISSING_WHITESPACE_BETWEEN_ATTRIBUTES",
  4038. "NESTED_COMMENT": 16,
  4039. "16": "NESTED_COMMENT",
  4040. "UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME": 17,
  4041. "17": "UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME",
  4042. "UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE": 18,
  4043. "18": "UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE",
  4044. "UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME": 19,
  4045. "19": "UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME",
  4046. "UNEXPECTED_NULL_CHARACTER": 20,
  4047. "20": "UNEXPECTED_NULL_CHARACTER",
  4048. "UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME": 21,
  4049. "21": "UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME",
  4050. "UNEXPECTED_SOLIDUS_IN_TAG": 22,
  4051. "22": "UNEXPECTED_SOLIDUS_IN_TAG",
  4052. "X_INVALID_END_TAG": 23,
  4053. "23": "X_INVALID_END_TAG",
  4054. "X_MISSING_END_TAG": 24,
  4055. "24": "X_MISSING_END_TAG",
  4056. "X_MISSING_INTERPOLATION_END": 25,
  4057. "25": "X_MISSING_INTERPOLATION_END",
  4058. "X_MISSING_DIRECTIVE_NAME": 26,
  4059. "26": "X_MISSING_DIRECTIVE_NAME",
  4060. "X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END": 27,
  4061. "27": "X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END",
  4062. "X_V_IF_NO_EXPRESSION": 28,
  4063. "28": "X_V_IF_NO_EXPRESSION",
  4064. "X_V_IF_SAME_KEY": 29,
  4065. "29": "X_V_IF_SAME_KEY",
  4066. "X_V_ELSE_NO_ADJACENT_IF": 30,
  4067. "30": "X_V_ELSE_NO_ADJACENT_IF",
  4068. "X_V_FOR_NO_EXPRESSION": 31,
  4069. "31": "X_V_FOR_NO_EXPRESSION",
  4070. "X_V_FOR_MALFORMED_EXPRESSION": 32,
  4071. "32": "X_V_FOR_MALFORMED_EXPRESSION",
  4072. "X_V_FOR_TEMPLATE_KEY_PLACEMENT": 33,
  4073. "33": "X_V_FOR_TEMPLATE_KEY_PLACEMENT",
  4074. "X_V_BIND_NO_EXPRESSION": 34,
  4075. "34": "X_V_BIND_NO_EXPRESSION",
  4076. "X_V_ON_NO_EXPRESSION": 35,
  4077. "35": "X_V_ON_NO_EXPRESSION",
  4078. "X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET": 36,
  4079. "36": "X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET",
  4080. "X_V_SLOT_MIXED_SLOT_USAGE": 37,
  4081. "37": "X_V_SLOT_MIXED_SLOT_USAGE",
  4082. "X_V_SLOT_DUPLICATE_SLOT_NAMES": 38,
  4083. "38": "X_V_SLOT_DUPLICATE_SLOT_NAMES",
  4084. "X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN": 39,
  4085. "39": "X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN",
  4086. "X_V_SLOT_MISPLACED": 40,
  4087. "40": "X_V_SLOT_MISPLACED",
  4088. "X_V_MODEL_NO_EXPRESSION": 41,
  4089. "41": "X_V_MODEL_NO_EXPRESSION",
  4090. "X_V_MODEL_MALFORMED_EXPRESSION": 42,
  4091. "42": "X_V_MODEL_MALFORMED_EXPRESSION",
  4092. "X_V_MODEL_ON_SCOPE_VARIABLE": 43,
  4093. "43": "X_V_MODEL_ON_SCOPE_VARIABLE",
  4094. "X_V_MODEL_ON_PROPS": 44,
  4095. "44": "X_V_MODEL_ON_PROPS",
  4096. "X_V_MODEL_ON_CONST": 45,
  4097. "45": "X_V_MODEL_ON_CONST",
  4098. "X_INVALID_EXPRESSION": 46,
  4099. "46": "X_INVALID_EXPRESSION",
  4100. "X_KEEP_ALIVE_INVALID_CHILDREN": 47,
  4101. "47": "X_KEEP_ALIVE_INVALID_CHILDREN",
  4102. "X_PREFIX_ID_NOT_SUPPORTED": 48,
  4103. "48": "X_PREFIX_ID_NOT_SUPPORTED",
  4104. "X_MODULE_MODE_NOT_SUPPORTED": 49,
  4105. "49": "X_MODULE_MODE_NOT_SUPPORTED",
  4106. "X_CACHE_HANDLER_NOT_SUPPORTED": 50,
  4107. "50": "X_CACHE_HANDLER_NOT_SUPPORTED",
  4108. "X_SCOPE_ID_NOT_SUPPORTED": 51,
  4109. "51": "X_SCOPE_ID_NOT_SUPPORTED",
  4110. "X_VNODE_HOOKS": 52,
  4111. "52": "X_VNODE_HOOKS",
  4112. "X_V_BIND_INVALID_SAME_NAME_ARGUMENT": 53,
  4113. "53": "X_V_BIND_INVALID_SAME_NAME_ARGUMENT",
  4114. "__EXTEND_POINT__": 54,
  4115. "54": "__EXTEND_POINT__"
  4116. };
  4117. const errorMessages$1 = {
  4118. // parse errors
  4119. [0]: "Illegal comment.",
  4120. [1]: "CDATA section is allowed only in XML context.",
  4121. [2]: "Duplicate attribute.",
  4122. [3]: "End tag cannot have attributes.",
  4123. [4]: "Illegal '/' in tags.",
  4124. [5]: "Unexpected EOF in tag.",
  4125. [6]: "Unexpected EOF in CDATA section.",
  4126. [7]: "Unexpected EOF in comment.",
  4127. [8]: "Unexpected EOF in script.",
  4128. [9]: "Unexpected EOF in tag.",
  4129. [10]: "Incorrectly closed comment.",
  4130. [11]: "Incorrectly opened comment.",
  4131. [12]: "Illegal tag name. Use '&lt;' to print '<'.",
  4132. [13]: "Attribute value was expected.",
  4133. [14]: "End tag name was expected.",
  4134. [15]: "Whitespace was expected.",
  4135. [16]: "Unexpected '<!--' in comment.",
  4136. [17]: `Attribute name cannot contain U+0022 ("), U+0027 ('), and U+003C (<).`,
  4137. [18]: "Unquoted attribute value cannot contain U+0022 (\"), U+0027 ('), U+003C (<), U+003D (=), and U+0060 (`).",
  4138. [19]: "Attribute name cannot start with '='.",
  4139. [21]: "'<?' is allowed only in XML context.",
  4140. [20]: `Unexpected null character.`,
  4141. [22]: "Illegal '/' in tags.",
  4142. // Vue-specific parse errors
  4143. [23]: "Invalid end tag.",
  4144. [24]: "Element is missing end tag.",
  4145. [25]: "Interpolation end sign was not found.",
  4146. [27]: "End bracket for dynamic directive argument was not found. Note that dynamic directive argument cannot contain spaces.",
  4147. [26]: "Legal directive name was expected.",
  4148. // transform errors
  4149. [28]: `v-if/v-else-if is missing expression.`,
  4150. [29]: `v-if/else branches must use unique keys.`,
  4151. [30]: `v-else/v-else-if has no adjacent v-if or v-else-if.`,
  4152. [31]: `v-for is missing expression.`,
  4153. [32]: `v-for has invalid expression.`,
  4154. [33]: `<template v-for> key should be placed on the <template> tag.`,
  4155. [34]: `v-bind is missing expression.`,
  4156. [53]: `v-bind with same-name shorthand only allows static argument.`,
  4157. [35]: `v-on is missing expression.`,
  4158. [36]: `Unexpected custom directive on <slot> outlet.`,
  4159. [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.`,
  4160. [38]: `Duplicate slot names found. `,
  4161. [39]: `Extraneous children found when component already has explicitly named default slot. These children will be ignored.`,
  4162. [40]: `v-slot can only be used on components or <template> tags.`,
  4163. [41]: `v-model is missing expression.`,
  4164. [42]: `v-model value must be a valid JavaScript member expression.`,
  4165. [43]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
  4166. [44]: `v-model cannot be used on a prop, because local prop bindings are not writable.
  4167. Use a v-bind binding combined with a v-on listener that emits update:x event instead.`,
  4168. [45]: `v-model cannot be used on a const binding because it is not writable.`,
  4169. [46]: `Error parsing JavaScript expression: `,
  4170. [47]: `<KeepAlive> expects exactly one child component.`,
  4171. [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.`,
  4172. // generic errors
  4173. [48]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
  4174. [49]: `ES module mode is not supported in this build of compiler.`,
  4175. [50]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
  4176. [51]: `"scopeId" option is only supported in module mode.`,
  4177. // just to fulfill types
  4178. [54]: ``
  4179. };
  4180. function getDefaultExportFromCjs (x) {
  4181. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  4182. }
  4183. function getAugmentedNamespace(n) {
  4184. if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n;
  4185. var f = n.default;
  4186. if (typeof f == "function") {
  4187. var a = function a () {
  4188. var isInstance = false;
  4189. try {
  4190. isInstance = this instanceof a;
  4191. } catch (e) {}
  4192. if (isInstance) {
  4193. return Reflect.construct(f, arguments, this.constructor);
  4194. }
  4195. return f.apply(this, arguments);
  4196. };
  4197. a.prototype = f.prototype;
  4198. } else a = {};
  4199. Object.defineProperty(a, '__esModule', {value: true});
  4200. Object.keys(n).forEach(function (k) {
  4201. var d = Object.getOwnPropertyDescriptor(n, k);
  4202. Object.defineProperty(a, k, d.get ? d : {
  4203. enumerable: true,
  4204. get: function () {
  4205. return n[k];
  4206. }
  4207. });
  4208. });
  4209. return a;
  4210. }
  4211. var lib = {};
  4212. var hasRequiredLib;
  4213. function requireLib () {
  4214. if (hasRequiredLib) return lib;
  4215. hasRequiredLib = 1;
  4216. Object.defineProperty(lib, '__esModule', {
  4217. value: true
  4218. });
  4219. function _objectWithoutPropertiesLoose(r, e) {
  4220. if (null == r) return {};
  4221. var t = {};
  4222. for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
  4223. if (-1 !== e.indexOf(n)) continue;
  4224. t[n] = r[n];
  4225. }
  4226. return t;
  4227. }
  4228. class Position {
  4229. constructor(line, col, index) {
  4230. this.line = void 0;
  4231. this.column = void 0;
  4232. this.index = void 0;
  4233. this.line = line;
  4234. this.column = col;
  4235. this.index = index;
  4236. }
  4237. }
  4238. class SourceLocation {
  4239. constructor(start, end) {
  4240. this.start = void 0;
  4241. this.end = void 0;
  4242. this.filename = void 0;
  4243. this.identifierName = void 0;
  4244. this.start = start;
  4245. this.end = end;
  4246. }
  4247. }
  4248. function createPositionWithColumnOffset(position, columnOffset) {
  4249. const {
  4250. line,
  4251. column,
  4252. index
  4253. } = position;
  4254. return new Position(line, column + columnOffset, index + columnOffset);
  4255. }
  4256. const code = "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED";
  4257. var ModuleErrors = {
  4258. ImportMetaOutsideModule: {
  4259. message: `import.meta may appear only with 'sourceType: "module"'`,
  4260. code
  4261. },
  4262. ImportOutsideModule: {
  4263. message: `'import' and 'export' may appear only with 'sourceType: "module"'`,
  4264. code
  4265. }
  4266. };
  4267. const NodeDescriptions = {
  4268. ArrayPattern: "array destructuring pattern",
  4269. AssignmentExpression: "assignment expression",
  4270. AssignmentPattern: "assignment expression",
  4271. ArrowFunctionExpression: "arrow function expression",
  4272. ConditionalExpression: "conditional expression",
  4273. CatchClause: "catch clause",
  4274. ForOfStatement: "for-of statement",
  4275. ForInStatement: "for-in statement",
  4276. ForStatement: "for-loop",
  4277. FormalParameters: "function parameter list",
  4278. Identifier: "identifier",
  4279. ImportSpecifier: "import specifier",
  4280. ImportDefaultSpecifier: "import default specifier",
  4281. ImportNamespaceSpecifier: "import namespace specifier",
  4282. ObjectPattern: "object destructuring pattern",
  4283. ParenthesizedExpression: "parenthesized expression",
  4284. RestElement: "rest element",
  4285. UpdateExpression: {
  4286. true: "prefix operation",
  4287. false: "postfix operation"
  4288. },
  4289. VariableDeclarator: "variable declaration",
  4290. YieldExpression: "yield expression"
  4291. };
  4292. const toNodeDescription = node => node.type === "UpdateExpression" ? NodeDescriptions.UpdateExpression[`${node.prefix}`] : NodeDescriptions[node.type];
  4293. var StandardErrors = {
  4294. AccessorIsGenerator: ({
  4295. kind
  4296. }) => `A ${kind}ter cannot be a generator.`,
  4297. ArgumentsInClass: "'arguments' is only allowed in functions and class methods.",
  4298. AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block.",
  4299. AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function.",
  4300. AwaitBindingIdentifierInStaticBlock: "Can not use 'await' as identifier inside a static block.",
  4301. AwaitExpressionFormalParameter: "'await' is not allowed in async function parameters.",
  4302. AwaitUsingNotInAsyncContext: "'await using' is only allowed within async functions and at the top levels of modules.",
  4303. AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules.",
  4304. BadGetterArity: "A 'get' accessor must not have any formal parameters.",
  4305. BadSetterArity: "A 'set' accessor must have exactly one formal parameter.",
  4306. BadSetterRestParameter: "A 'set' accessor function argument must not be a rest parameter.",
  4307. ConstructorClassField: "Classes may not have a field named 'constructor'.",
  4308. ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'.",
  4309. ConstructorIsAccessor: "Class constructor may not be an accessor.",
  4310. ConstructorIsAsync: "Constructor can't be an async function.",
  4311. ConstructorIsGenerator: "Constructor can't be a generator.",
  4312. DeclarationMissingInitializer: ({
  4313. kind
  4314. }) => `Missing initializer in ${kind} declaration.`,
  4315. DecoratorArgumentsOutsideParentheses: "Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.",
  4316. DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.",
  4317. DecoratorsBeforeAfterExport: "Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.",
  4318. DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",
  4319. DecoratorExportClass: "Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.",
  4320. DecoratorSemicolon: "Decorators must not be followed by a semicolon.",
  4321. DecoratorStaticBlock: "Decorators can't be used with a static block.",
  4322. DeferImportRequiresNamespace: 'Only `import defer * as x from "./module"` is valid.',
  4323. DeletePrivateField: "Deleting a private field is not allowed.",
  4324. DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.",
  4325. DuplicateConstructor: "Duplicate constructor in the same class.",
  4326. DuplicateDefaultExport: "Only one default export allowed per module.",
  4327. DuplicateExport: ({
  4328. exportName
  4329. }) => `\`${exportName}\` has already been exported. Exported identifiers must be unique.`,
  4330. DuplicateProto: "Redefinition of __proto__ property.",
  4331. DuplicateRegExpFlags: "Duplicate regular expression flag.",
  4332. ElementAfterRest: "Rest element must be last element.",
  4333. EscapedCharNotAnIdentifier: "Invalid Unicode escape.",
  4334. ExportBindingIsString: ({
  4335. localName,
  4336. exportName
  4337. }) => `A string literal cannot be used as an exported binding without \`from\`.\n- Did you mean \`export { '${localName}' as '${exportName}' } from 'some-module'\`?`,
  4338. ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'.",
  4339. ForInOfLoopInitializer: ({
  4340. type
  4341. }) => `'${type === "ForInStatement" ? "for-in" : "for-of"}' loop variable declaration may not have an initializer.`,
  4342. ForInUsing: "For-in loop may not start with 'using' declaration.",
  4343. ForOfAsync: "The left-hand side of a for-of loop may not be 'async'.",
  4344. ForOfLet: "The left-hand side of a for-of loop may not start with 'let'.",
  4345. GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block.",
  4346. IllegalBreakContinue: ({
  4347. type
  4348. }) => `Unsyntactic ${type === "BreakStatement" ? "break" : "continue"}.`,
  4349. IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list.",
  4350. IllegalReturn: "'return' outside of function.",
  4351. 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.",
  4352. ImportBindingIsString: ({
  4353. importName
  4354. }) => `A string literal cannot be used as an imported binding.\n- Did you mean \`import { "${importName}" as foo }\`?`,
  4355. ImportCallArity: `\`import()\` requires exactly one or two arguments.`,
  4356. ImportCallNotNewExpression: "Cannot use new with import(...).",
  4357. ImportCallSpreadArgument: "`...` is not allowed in `import()`.",
  4358. ImportJSONBindingNotDefault: "A JSON module can only be imported with `default`.",
  4359. ImportReflectionHasAssertion: "`import module x` cannot have assertions.",
  4360. ImportReflectionNotBinding: 'Only `import module x from "./module"` is valid.',
  4361. IncompatibleRegExpUVFlags: "The 'u' and 'v' regular expression flags cannot be enabled at the same time.",
  4362. InvalidBigIntLiteral: "Invalid BigIntLiteral.",
  4363. InvalidCodePoint: "Code point out of bounds.",
  4364. InvalidCoverDiscardElement: "'void' must be followed by an expression when not used in a binding position.",
  4365. InvalidCoverInitializedName: "Invalid shorthand property initializer.",
  4366. InvalidDecimal: "Invalid decimal.",
  4367. InvalidDigit: ({
  4368. radix
  4369. }) => `Expected number in radix ${radix}.`,
  4370. InvalidEscapeSequence: "Bad character escape sequence.",
  4371. InvalidEscapeSequenceTemplate: "Invalid escape sequence in template.",
  4372. InvalidEscapedReservedWord: ({
  4373. reservedWord
  4374. }) => `Escape sequence in keyword ${reservedWord}.`,
  4375. InvalidIdentifier: ({
  4376. identifierName
  4377. }) => `Invalid identifier ${identifierName}.`,
  4378. InvalidLhs: ({
  4379. ancestor
  4380. }) => `Invalid left-hand side in ${toNodeDescription(ancestor)}.`,
  4381. InvalidLhsBinding: ({
  4382. ancestor
  4383. }) => `Binding invalid left-hand side in ${toNodeDescription(ancestor)}.`,
  4384. InvalidLhsOptionalChaining: ({
  4385. ancestor
  4386. }) => `Invalid optional chaining in the left-hand side of ${toNodeDescription(ancestor)}.`,
  4387. InvalidNumber: "Invalid number.",
  4388. InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'.",
  4389. InvalidOrUnexpectedToken: ({
  4390. unexpected
  4391. }) => `Unexpected character '${unexpected}'.`,
  4392. InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern.",
  4393. InvalidPrivateFieldResolution: ({
  4394. identifierName
  4395. }) => `Private name #${identifierName} is not defined.`,
  4396. InvalidPropertyBindingPattern: "Binding member expression.",
  4397. InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions.",
  4398. InvalidRestAssignmentPattern: "Invalid rest operator's argument.",
  4399. LabelRedeclaration: ({
  4400. labelName
  4401. }) => `Label '${labelName}' is already declared.`,
  4402. LetInLexicalBinding: "'let' is disallowed as a lexically bound name.",
  4403. LineTerminatorBeforeArrow: "No line break is allowed before '=>'.",
  4404. MalformedRegExpFlags: "Invalid regular expression flag.",
  4405. MissingClassName: "A class name is required.",
  4406. MissingEqInAssignment: "Only '=' operator can be used for specifying default value.",
  4407. MissingSemicolon: "Missing semicolon.",
  4408. MissingPlugin: ({
  4409. missingPlugin
  4410. }) => `This experimental syntax requires enabling the parser plugin: ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`,
  4411. MissingOneOfPlugins: ({
  4412. missingPlugin
  4413. }) => `This experimental syntax requires enabling one of the following parser plugin(s): ${missingPlugin.map(name => JSON.stringify(name)).join(", ")}.`,
  4414. MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX.",
  4415. MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators.",
  4416. ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`.",
  4417. ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values.",
  4418. ModuleAttributesWithDuplicateKeys: ({
  4419. key
  4420. }) => `Duplicate key "${key}" is not allowed in module attributes.`,
  4421. ModuleExportNameHasLoneSurrogate: ({
  4422. surrogateCharCode
  4423. }) => `An export name cannot include a lone surrogate, found '\\u${surrogateCharCode.toString(16)}'.`,
  4424. ModuleExportUndefined: ({
  4425. localName
  4426. }) => `Export '${localName}' is not defined.`,
  4427. MultipleDefaultsInSwitch: "Multiple default clauses.",
  4428. NewlineAfterThrow: "Illegal newline after throw.",
  4429. NoCatchOrFinally: "Missing catch or finally clause.",
  4430. NumberIdentifier: "Identifier directly after number.",
  4431. NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.",
  4432. ObsoleteAwaitStar: "'await*' has been removed from the async functions proposal. Use Promise.all() instead.",
  4433. OptionalChainingNoNew: "Constructors in/after an Optional Chain are not allowed.",
  4434. OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain.",
  4435. OverrideOnConstructor: "'override' modifier cannot appear on a constructor declaration.",
  4436. ParamDupe: "Argument name clash.",
  4437. PatternHasAccessor: "Object pattern can't contain getter or setter.",
  4438. PatternHasMethod: "Object pattern can't contain methods.",
  4439. PrivateInExpectedIn: ({
  4440. identifierName
  4441. }) => `Private names are only allowed in property accesses (\`obj.#${identifierName}\`) or in \`in\` expressions (\`#${identifierName} in obj\`).`,
  4442. PrivateNameRedeclaration: ({
  4443. identifierName
  4444. }) => `Duplicate private name #${identifierName}.`,
  4445. RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  4446. RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  4447. RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",
  4448. RecordNoProto: "'__proto__' is not allowed in Record expressions.",
  4449. RestTrailingComma: "Unexpected trailing comma after rest element.",
  4450. SloppyFunction: "In non-strict mode code, functions can only be declared at top level or inside a block.",
  4451. 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.",
  4452. SourcePhaseImportRequiresDefault: 'Only `import source x from "./module"` is valid.',
  4453. StaticPrototype: "Classes may not have static property named prototype.",
  4454. SuperCallNotNewExpression: "Cannot use new with super(...).",
  4455. 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?",
  4456. SuperPrivateField: "Private fields can't be accessed on super.",
  4457. TrailingDecorator: "Decorators must be attached to a class element.",
  4458. TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  4459. TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  4460. TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",
  4461. UnexpectedArgumentPlaceholder: "Unexpected argument placeholder.",
  4462. UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal.',
  4463. UnexpectedDigitAfterHash: "Unexpected digit after hash token.",
  4464. UnexpectedImportExport: "'import' and 'export' may only appear at the top level.",
  4465. UnexpectedKeyword: ({
  4466. keyword
  4467. }) => `Unexpected keyword '${keyword}'.`,
  4468. UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration.",
  4469. UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context.",
  4470. UnexpectedNewTarget: "`new.target` can only be used in functions or class properties.",
  4471. UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits.",
  4472. UnexpectedPrivateField: "Unexpected private name.",
  4473. UnexpectedReservedWord: ({
  4474. reservedWord
  4475. }) => `Unexpected reserved word '${reservedWord}'.`,
  4476. UnexpectedSuper: "'super' is only allowed in object methods and classes.",
  4477. UnexpectedToken: ({
  4478. expected,
  4479. unexpected
  4480. }) => `Unexpected token${unexpected ? ` '${unexpected}'.` : ""}${expected ? `, expected "${expected}"` : ""}`,
  4481. UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",
  4482. UnexpectedUsingDeclaration: "Using declaration cannot appear in the top level when source type is `script` or in the bare case statement.",
  4483. UnexpectedVoidPattern: "Unexpected void binding.",
  4484. UnsupportedDecoratorExport: "A decorated export must export a class declaration.",
  4485. UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.",
  4486. UnsupportedImport: "`import` can only be used in `import()` or `import.meta`.",
  4487. UnsupportedMetaProperty: ({
  4488. target,
  4489. onlyValidPropertyName
  4490. }) => `The only valid meta property for ${target} is ${target}.${onlyValidPropertyName}.`,
  4491. UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters.",
  4492. UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties.",
  4493. UnsupportedSuper: "'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).",
  4494. UnterminatedComment: "Unterminated comment.",
  4495. UnterminatedRegExp: "Unterminated regular expression.",
  4496. UnterminatedString: "Unterminated string constant.",
  4497. UnterminatedTemplate: "Unterminated template.",
  4498. UsingDeclarationExport: "Using declaration cannot be exported.",
  4499. UsingDeclarationHasBindingPattern: "Using declaration cannot have destructuring patterns.",
  4500. VarRedeclaration: ({
  4501. identifierName
  4502. }) => `Identifier '${identifierName}' has already been declared.`,
  4503. VoidPatternCatchClauseParam: "A void binding can not be the catch clause parameter. Use `try { ... } catch { ... }` if you want to discard the caught error.",
  4504. VoidPatternInitializer: "A void binding may not have an initializer.",
  4505. YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator.",
  4506. YieldInParameter: "Yield expression is not allowed in formal parameters.",
  4507. YieldNotInGeneratorFunction: "'yield' is only allowed within generator functions.",
  4508. ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0."
  4509. };
  4510. var StrictModeErrors = {
  4511. StrictDelete: "Deleting local variable in strict mode.",
  4512. StrictEvalArguments: ({
  4513. referenceName
  4514. }) => `Assigning to '${referenceName}' in strict mode.`,
  4515. StrictEvalArgumentsBinding: ({
  4516. bindingName
  4517. }) => `Binding '${bindingName}' in strict mode.`,
  4518. StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block.",
  4519. StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'.",
  4520. StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode.",
  4521. StrictWith: "'with' in strict mode."
  4522. };
  4523. var ParseExpressionErrors = {
  4524. ParseExpressionEmptyInput: "Unexpected parseExpression() input: The input is empty or contains only comments.",
  4525. ParseExpressionExpectsEOF: ({
  4526. unexpected
  4527. }) => `Unexpected parseExpression() input: The input should contain exactly one expression, but the first expression is followed by the unexpected character \`${String.fromCodePoint(unexpected)}\`.`
  4528. };
  4529. const UnparenthesizedPipeBodyDescriptions = new Set(["ArrowFunctionExpression", "AssignmentExpression", "ConditionalExpression", "YieldExpression"]);
  4530. var PipelineOperatorErrors = Object.assign({
  4531. PipeBodyIsTighter: "Unexpected yield after pipeline body; any yield expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.",
  4532. PipeTopicRequiresHackPipes: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.',
  4533. PipeTopicUnbound: "Topic reference is unbound; it must be inside a pipe body.",
  4534. PipeTopicUnconfiguredToken: ({
  4535. token
  4536. }) => `Invalid topic token ${token}. In order to use ${token} as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "${token}" }.`,
  4537. PipeTopicUnused: "Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.",
  4538. PipeUnparenthesizedBody: ({
  4539. type
  4540. }) => `Hack-style pipe body cannot be an unparenthesized ${toNodeDescription({
  4541. type
  4542. })}; please wrap it in parentheses.`
  4543. }, {
  4544. PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized.',
  4545. PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression.",
  4546. PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression.",
  4547. PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference.",
  4548. PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding.",
  4549. PrimaryTopicRequiresSmartPipeline: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.'
  4550. });
  4551. var FunctionBindErrors = {
  4552. UnsupportedBind: "Binding should be performed on object property.",
  4553. UnsupportedBindRHS: "The right-hand side of binding can not be super or import."
  4554. };
  4555. const _excluded = ["message"];
  4556. function defineHidden(obj, key, value) {
  4557. Object.defineProperty(obj, key, {
  4558. enumerable: false,
  4559. configurable: true,
  4560. value
  4561. });
  4562. }
  4563. function toParseErrorConstructor({
  4564. toMessage,
  4565. code,
  4566. reasonCode,
  4567. syntaxPlugin
  4568. }) {
  4569. const hasMissingPlugin = reasonCode === "MissingPlugin" || reasonCode === "MissingOneOfPlugins";
  4570. const oldReasonCodes = {
  4571. AccessorCannotDeclareThisParameter: "AccesorCannotDeclareThisParameter",
  4572. AccessorCannotHaveTypeParameters: "AccesorCannotHaveTypeParameters",
  4573. ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference: "ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference",
  4574. SetAccessorCannotHaveOptionalParameter: "SetAccesorCannotHaveOptionalParameter",
  4575. SetAccessorCannotHaveRestParameter: "SetAccesorCannotHaveRestParameter",
  4576. SetAccessorCannotHaveReturnType: "SetAccesorCannotHaveReturnType"
  4577. };
  4578. if (oldReasonCodes[reasonCode]) {
  4579. reasonCode = oldReasonCodes[reasonCode];
  4580. }
  4581. return function constructor(loc, details) {
  4582. const error = new SyntaxError();
  4583. error.code = code;
  4584. error.reasonCode = reasonCode;
  4585. error.loc = loc;
  4586. error.pos = loc.index;
  4587. error.syntaxPlugin = syntaxPlugin;
  4588. if (hasMissingPlugin) {
  4589. error.missingPlugin = details.missingPlugin;
  4590. }
  4591. defineHidden(error, "clone", function clone(overrides = {}) {
  4592. var _overrides$loc;
  4593. const {
  4594. line,
  4595. column,
  4596. index
  4597. } = (_overrides$loc = overrides.loc) != null ? _overrides$loc : loc;
  4598. return constructor(new Position(line, column, index), Object.assign({}, details, overrides.details));
  4599. });
  4600. defineHidden(error, "details", details);
  4601. Object.defineProperty(error, "message", {
  4602. configurable: true,
  4603. get() {
  4604. const message = `${toMessage(details)} (${loc.line}:${loc.column})`;
  4605. this.message = message;
  4606. return message;
  4607. },
  4608. set(value) {
  4609. Object.defineProperty(this, "message", {
  4610. value,
  4611. writable: true
  4612. });
  4613. }
  4614. });
  4615. return error;
  4616. };
  4617. }
  4618. function ParseErrorEnum(argument, syntaxPlugin) {
  4619. if (Array.isArray(argument)) {
  4620. return parseErrorTemplates => ParseErrorEnum(parseErrorTemplates, argument[0]);
  4621. }
  4622. const ParseErrorConstructors = {};
  4623. for (const reasonCode of Object.keys(argument)) {
  4624. const template = argument[reasonCode];
  4625. const _ref = typeof template === "string" ? {
  4626. message: () => template
  4627. } : typeof template === "function" ? {
  4628. message: template
  4629. } : template,
  4630. {
  4631. message
  4632. } = _ref,
  4633. rest = _objectWithoutPropertiesLoose(_ref, _excluded);
  4634. const toMessage = typeof message === "string" ? () => message : message;
  4635. ParseErrorConstructors[reasonCode] = toParseErrorConstructor(Object.assign({
  4636. code: "BABEL_PARSER_SYNTAX_ERROR",
  4637. reasonCode,
  4638. toMessage
  4639. }, syntaxPlugin ? {
  4640. syntaxPlugin
  4641. } : {}, rest));
  4642. }
  4643. return ParseErrorConstructors;
  4644. }
  4645. const Errors = Object.assign({}, ParseErrorEnum(ModuleErrors), ParseErrorEnum(StandardErrors), ParseErrorEnum(StrictModeErrors), ParseErrorEnum(ParseExpressionErrors), ParseErrorEnum`pipelineOperator`(PipelineOperatorErrors), ParseErrorEnum`functionBind`(FunctionBindErrors));
  4646. function createDefaultOptions() {
  4647. return {
  4648. sourceType: "script",
  4649. sourceFilename: undefined,
  4650. startIndex: 0,
  4651. startColumn: 0,
  4652. startLine: 1,
  4653. allowAwaitOutsideFunction: false,
  4654. allowReturnOutsideFunction: false,
  4655. allowNewTargetOutsideFunction: false,
  4656. allowImportExportEverywhere: false,
  4657. allowSuperOutsideMethod: false,
  4658. allowUndeclaredExports: false,
  4659. allowYieldOutsideFunction: false,
  4660. plugins: [],
  4661. strictMode: undefined,
  4662. ranges: false,
  4663. tokens: false,
  4664. createImportExpressions: false,
  4665. createParenthesizedExpressions: false,
  4666. errorRecovery: false,
  4667. attachComment: true,
  4668. annexB: true
  4669. };
  4670. }
  4671. function getOptions(opts) {
  4672. const options = createDefaultOptions();
  4673. if (opts == null) {
  4674. return options;
  4675. }
  4676. if (opts.annexB != null && opts.annexB !== false) {
  4677. throw new Error("The `annexB` option can only be set to `false`.");
  4678. }
  4679. for (const key of Object.keys(options)) {
  4680. if (opts[key] != null) options[key] = opts[key];
  4681. }
  4682. if (options.startLine === 1) {
  4683. if (opts.startIndex == null && options.startColumn > 0) {
  4684. options.startIndex = options.startColumn;
  4685. } else if (opts.startColumn == null && options.startIndex > 0) {
  4686. options.startColumn = options.startIndex;
  4687. }
  4688. } else if (opts.startColumn == null || opts.startIndex == null) {
  4689. if (opts.startIndex != null) {
  4690. throw new Error("With a `startLine > 1` you must also specify `startIndex` and `startColumn`.");
  4691. }
  4692. }
  4693. if (options.sourceType === "commonjs") {
  4694. if (opts.allowAwaitOutsideFunction != null) {
  4695. throw new Error("The `allowAwaitOutsideFunction` option cannot be used with `sourceType: 'commonjs'`.");
  4696. }
  4697. if (opts.allowReturnOutsideFunction != null) {
  4698. throw new Error("`sourceType: 'commonjs'` implies `allowReturnOutsideFunction: true`, please remove the `allowReturnOutsideFunction` option or use `sourceType: 'script'`.");
  4699. }
  4700. if (opts.allowNewTargetOutsideFunction != null) {
  4701. throw new Error("`sourceType: 'commonjs'` implies `allowNewTargetOutsideFunction: true`, please remove the `allowNewTargetOutsideFunction` option or use `sourceType: 'script'`.");
  4702. }
  4703. }
  4704. return options;
  4705. }
  4706. const {
  4707. defineProperty
  4708. } = Object;
  4709. const toUnenumerable = (object, key) => {
  4710. if (object) {
  4711. defineProperty(object, key, {
  4712. enumerable: false,
  4713. value: object[key]
  4714. });
  4715. }
  4716. };
  4717. function toESTreeLocation(node) {
  4718. toUnenumerable(node.loc.start, "index");
  4719. toUnenumerable(node.loc.end, "index");
  4720. return node;
  4721. }
  4722. var estree = superClass => class ESTreeParserMixin extends superClass {
  4723. parse() {
  4724. const file = toESTreeLocation(super.parse());
  4725. if (this.optionFlags & 256) {
  4726. file.tokens = file.tokens.map(toESTreeLocation);
  4727. }
  4728. return file;
  4729. }
  4730. parseRegExpLiteral({
  4731. pattern,
  4732. flags
  4733. }) {
  4734. let regex = null;
  4735. try {
  4736. regex = new RegExp(pattern, flags);
  4737. } catch (_) {}
  4738. const node = this.estreeParseLiteral(regex);
  4739. node.regex = {
  4740. pattern,
  4741. flags
  4742. };
  4743. return node;
  4744. }
  4745. parseBigIntLiteral(value) {
  4746. let bigInt;
  4747. try {
  4748. bigInt = BigInt(value);
  4749. } catch (_unused) {
  4750. bigInt = null;
  4751. }
  4752. const node = this.estreeParseLiteral(bigInt);
  4753. node.bigint = String(node.value || value);
  4754. return node;
  4755. }
  4756. parseDecimalLiteral(value) {
  4757. const decimal = null;
  4758. const node = this.estreeParseLiteral(decimal);
  4759. node.decimal = String(node.value || value);
  4760. return node;
  4761. }
  4762. estreeParseLiteral(value) {
  4763. return this.parseLiteral(value, "Literal");
  4764. }
  4765. parseStringLiteral(value) {
  4766. return this.estreeParseLiteral(value);
  4767. }
  4768. parseNumericLiteral(value) {
  4769. return this.estreeParseLiteral(value);
  4770. }
  4771. parseNullLiteral() {
  4772. return this.estreeParseLiteral(null);
  4773. }
  4774. parseBooleanLiteral(value) {
  4775. return this.estreeParseLiteral(value);
  4776. }
  4777. estreeParseChainExpression(node, endLoc) {
  4778. const chain = this.startNodeAtNode(node);
  4779. chain.expression = node;
  4780. return this.finishNodeAt(chain, "ChainExpression", endLoc);
  4781. }
  4782. directiveToStmt(directive) {
  4783. const expression = directive.value;
  4784. delete directive.value;
  4785. this.castNodeTo(expression, "Literal");
  4786. expression.raw = expression.extra.raw;
  4787. expression.value = expression.extra.expressionValue;
  4788. const stmt = this.castNodeTo(directive, "ExpressionStatement");
  4789. stmt.expression = expression;
  4790. stmt.directive = expression.extra.rawValue;
  4791. delete expression.extra;
  4792. return stmt;
  4793. }
  4794. fillOptionalPropertiesForTSESLint(node) {}
  4795. cloneEstreeStringLiteral(node) {
  4796. const {
  4797. start,
  4798. end,
  4799. loc,
  4800. range,
  4801. raw,
  4802. value
  4803. } = node;
  4804. const cloned = Object.create(node.constructor.prototype);
  4805. cloned.type = "Literal";
  4806. cloned.start = start;
  4807. cloned.end = end;
  4808. cloned.loc = loc;
  4809. cloned.range = range;
  4810. cloned.raw = raw;
  4811. cloned.value = value;
  4812. return cloned;
  4813. }
  4814. initFunction(node, isAsync) {
  4815. super.initFunction(node, isAsync);
  4816. node.expression = false;
  4817. }
  4818. checkDeclaration(node) {
  4819. if (node != null && this.isObjectProperty(node)) {
  4820. this.checkDeclaration(node.value);
  4821. } else {
  4822. super.checkDeclaration(node);
  4823. }
  4824. }
  4825. getObjectOrClassMethodParams(method) {
  4826. return method.value.params;
  4827. }
  4828. isValidDirective(stmt) {
  4829. var _stmt$expression$extr;
  4830. return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) != null && _stmt$expression$extr.parenthesized);
  4831. }
  4832. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  4833. super.parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse);
  4834. const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
  4835. node.body = directiveStatements.concat(node.body);
  4836. delete node.directives;
  4837. }
  4838. parsePrivateName() {
  4839. const node = super.parsePrivateName();
  4840. if (!this.getPluginOption("estree", "classFeatures")) {
  4841. return node;
  4842. }
  4843. return this.convertPrivateNameToPrivateIdentifier(node);
  4844. }
  4845. convertPrivateNameToPrivateIdentifier(node) {
  4846. const name = super.getPrivateNameSV(node);
  4847. delete node.id;
  4848. node.name = name;
  4849. return this.castNodeTo(node, "PrivateIdentifier");
  4850. }
  4851. isPrivateName(node) {
  4852. if (!this.getPluginOption("estree", "classFeatures")) {
  4853. return super.isPrivateName(node);
  4854. }
  4855. return node.type === "PrivateIdentifier";
  4856. }
  4857. getPrivateNameSV(node) {
  4858. if (!this.getPluginOption("estree", "classFeatures")) {
  4859. return super.getPrivateNameSV(node);
  4860. }
  4861. return node.name;
  4862. }
  4863. parseLiteral(value, type) {
  4864. const node = super.parseLiteral(value, type);
  4865. node.raw = node.extra.raw;
  4866. delete node.extra;
  4867. return node;
  4868. }
  4869. parseFunctionBody(node, allowExpression, isMethod = false) {
  4870. super.parseFunctionBody(node, allowExpression, isMethod);
  4871. node.expression = node.body.type !== "BlockStatement";
  4872. }
  4873. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  4874. let funcNode = this.startNode();
  4875. funcNode.kind = node.kind;
  4876. funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  4877. delete funcNode.kind;
  4878. const {
  4879. typeParameters
  4880. } = node;
  4881. if (typeParameters) {
  4882. delete node.typeParameters;
  4883. funcNode.typeParameters = typeParameters;
  4884. this.resetStartLocationFromNode(funcNode, typeParameters);
  4885. }
  4886. const valueNode = this.castNodeTo(funcNode, "FunctionExpression");
  4887. node.value = valueNode;
  4888. if (type === "ClassPrivateMethod") {
  4889. node.computed = false;
  4890. }
  4891. if (type === "ObjectMethod") {
  4892. if (node.kind === "method") {
  4893. node.kind = "init";
  4894. }
  4895. node.shorthand = false;
  4896. return this.finishNode(node, "Property");
  4897. } else {
  4898. return this.finishNode(node, "MethodDefinition");
  4899. }
  4900. }
  4901. nameIsConstructor(key) {
  4902. if (key.type === "Literal") return key.value === "constructor";
  4903. return super.nameIsConstructor(key);
  4904. }
  4905. parseClassProperty(...args) {
  4906. const propertyNode = super.parseClassProperty(...args);
  4907. if (!this.getPluginOption("estree", "classFeatures")) {
  4908. return propertyNode;
  4909. }
  4910. this.castNodeTo(propertyNode, "PropertyDefinition");
  4911. return propertyNode;
  4912. }
  4913. parseClassPrivateProperty(...args) {
  4914. const propertyNode = super.parseClassPrivateProperty(...args);
  4915. if (!this.getPluginOption("estree", "classFeatures")) {
  4916. return propertyNode;
  4917. }
  4918. this.castNodeTo(propertyNode, "PropertyDefinition");
  4919. propertyNode.computed = false;
  4920. return propertyNode;
  4921. }
  4922. parseClassAccessorProperty(node) {
  4923. const accessorPropertyNode = super.parseClassAccessorProperty(node);
  4924. if (!this.getPluginOption("estree", "classFeatures")) {
  4925. return accessorPropertyNode;
  4926. }
  4927. if (accessorPropertyNode.abstract && this.hasPlugin("typescript")) {
  4928. delete accessorPropertyNode.abstract;
  4929. this.castNodeTo(accessorPropertyNode, "TSAbstractAccessorProperty");
  4930. } else {
  4931. this.castNodeTo(accessorPropertyNode, "AccessorProperty");
  4932. }
  4933. return accessorPropertyNode;
  4934. }
  4935. parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) {
  4936. const node = super.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors);
  4937. if (node) {
  4938. node.kind = "init";
  4939. this.castNodeTo(node, "Property");
  4940. }
  4941. return node;
  4942. }
  4943. finishObjectProperty(node) {
  4944. node.kind = "init";
  4945. return this.finishNode(node, "Property");
  4946. }
  4947. isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding) {
  4948. return type === "Property" ? "value" : super.isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding);
  4949. }
  4950. isAssignable(node, isBinding) {
  4951. if (node != null && this.isObjectProperty(node)) {
  4952. return this.isAssignable(node.value, isBinding);
  4953. }
  4954. return super.isAssignable(node, isBinding);
  4955. }
  4956. toAssignable(node, isLHS = false) {
  4957. if (node != null && this.isObjectProperty(node)) {
  4958. const {
  4959. key,
  4960. value
  4961. } = node;
  4962. if (this.isPrivateName(key)) {
  4963. this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start);
  4964. }
  4965. this.toAssignable(value, isLHS);
  4966. } else {
  4967. super.toAssignable(node, isLHS);
  4968. }
  4969. }
  4970. toAssignableObjectExpressionProp(prop, isLast, isLHS) {
  4971. if (prop.type === "Property" && (prop.kind === "get" || prop.kind === "set")) {
  4972. this.raise(Errors.PatternHasAccessor, prop.key);
  4973. } else if (prop.type === "Property" && prop.method) {
  4974. this.raise(Errors.PatternHasMethod, prop.key);
  4975. } else {
  4976. super.toAssignableObjectExpressionProp(prop, isLast, isLHS);
  4977. }
  4978. }
  4979. finishCallExpression(unfinished, optional) {
  4980. const node = super.finishCallExpression(unfinished, optional);
  4981. if (node.callee.type === "Import") {
  4982. var _ref, _ref2;
  4983. this.castNodeTo(node, "ImportExpression");
  4984. node.source = node.arguments[0];
  4985. node.options = (_ref = node.arguments[1]) != null ? _ref : null;
  4986. node.attributes = (_ref2 = node.arguments[1]) != null ? _ref2 : null;
  4987. delete node.arguments;
  4988. delete node.callee;
  4989. } else if (node.type === "OptionalCallExpression") {
  4990. this.castNodeTo(node, "CallExpression");
  4991. } else {
  4992. node.optional = false;
  4993. }
  4994. return node;
  4995. }
  4996. toReferencedArguments(node) {
  4997. if (node.type === "ImportExpression") {
  4998. return;
  4999. }
  5000. super.toReferencedArguments(node);
  5001. }
  5002. parseExport(unfinished, decorators) {
  5003. const exportStartLoc = this.state.lastTokStartLoc;
  5004. const node = super.parseExport(unfinished, decorators);
  5005. switch (node.type) {
  5006. case "ExportAllDeclaration":
  5007. node.exported = null;
  5008. break;
  5009. case "ExportNamedDeclaration":
  5010. if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") {
  5011. this.castNodeTo(node, "ExportAllDeclaration");
  5012. node.exported = node.specifiers[0].exported;
  5013. delete node.specifiers;
  5014. }
  5015. case "ExportDefaultDeclaration":
  5016. {
  5017. var _declaration$decorato;
  5018. const {
  5019. declaration
  5020. } = node;
  5021. if ((declaration == null ? void 0 : declaration.type) === "ClassDeclaration" && ((_declaration$decorato = declaration.decorators) == null ? void 0 : _declaration$decorato.length) > 0 && declaration.start === node.start) {
  5022. this.resetStartLocation(node, exportStartLoc);
  5023. }
  5024. }
  5025. break;
  5026. }
  5027. return node;
  5028. }
  5029. stopParseSubscript(base, state) {
  5030. const node = super.stopParseSubscript(base, state);
  5031. if (state.optionalChainMember) {
  5032. return this.estreeParseChainExpression(node, base.loc.end);
  5033. }
  5034. return node;
  5035. }
  5036. parseMember(base, startLoc, state, computed, optional) {
  5037. const node = super.parseMember(base, startLoc, state, computed, optional);
  5038. if (node.type === "OptionalMemberExpression") {
  5039. this.castNodeTo(node, "MemberExpression");
  5040. } else {
  5041. node.optional = false;
  5042. }
  5043. return node;
  5044. }
  5045. isOptionalMemberExpression(node) {
  5046. if (node.type === "ChainExpression") {
  5047. return node.expression.type === "MemberExpression";
  5048. }
  5049. return super.isOptionalMemberExpression(node);
  5050. }
  5051. hasPropertyAsPrivateName(node) {
  5052. if (node.type === "ChainExpression") {
  5053. node = node.expression;
  5054. }
  5055. return super.hasPropertyAsPrivateName(node);
  5056. }
  5057. isObjectProperty(node) {
  5058. return node.type === "Property" && node.kind === "init" && !node.method;
  5059. }
  5060. isObjectMethod(node) {
  5061. return node.type === "Property" && (node.method || node.kind === "get" || node.kind === "set");
  5062. }
  5063. castNodeTo(node, type) {
  5064. const result = super.castNodeTo(node, type);
  5065. this.fillOptionalPropertiesForTSESLint(result);
  5066. return result;
  5067. }
  5068. cloneIdentifier(node) {
  5069. const cloned = super.cloneIdentifier(node);
  5070. this.fillOptionalPropertiesForTSESLint(cloned);
  5071. return cloned;
  5072. }
  5073. cloneStringLiteral(node) {
  5074. if (node.type === "Literal") {
  5075. return this.cloneEstreeStringLiteral(node);
  5076. }
  5077. return super.cloneStringLiteral(node);
  5078. }
  5079. finishNodeAt(node, type, endLoc) {
  5080. return toESTreeLocation(super.finishNodeAt(node, type, endLoc));
  5081. }
  5082. finishNode(node, type) {
  5083. const result = super.finishNode(node, type);
  5084. this.fillOptionalPropertiesForTSESLint(result);
  5085. return result;
  5086. }
  5087. resetStartLocation(node, startLoc) {
  5088. super.resetStartLocation(node, startLoc);
  5089. toESTreeLocation(node);
  5090. }
  5091. resetEndLocation(node, endLoc = this.state.lastTokEndLoc) {
  5092. super.resetEndLocation(node, endLoc);
  5093. toESTreeLocation(node);
  5094. }
  5095. };
  5096. class TokContext {
  5097. constructor(token, preserveSpace) {
  5098. this.token = void 0;
  5099. this.preserveSpace = void 0;
  5100. this.token = token;
  5101. this.preserveSpace = !!preserveSpace;
  5102. }
  5103. }
  5104. const types = {
  5105. brace: new TokContext("{"),
  5106. j_oTag: new TokContext("<tag"),
  5107. j_cTag: new TokContext("</tag"),
  5108. j_expr: new TokContext("<tag>...</tag>", true)
  5109. };
  5110. types.template = new TokContext("`", true);
  5111. const beforeExpr = true;
  5112. const startsExpr = true;
  5113. const isLoop = true;
  5114. const isAssign = true;
  5115. const prefix = true;
  5116. const postfix = true;
  5117. class ExportedTokenType {
  5118. constructor(label, conf = {}) {
  5119. this.label = void 0;
  5120. this.keyword = void 0;
  5121. this.beforeExpr = void 0;
  5122. this.startsExpr = void 0;
  5123. this.rightAssociative = void 0;
  5124. this.isLoop = void 0;
  5125. this.isAssign = void 0;
  5126. this.prefix = void 0;
  5127. this.postfix = void 0;
  5128. this.binop = void 0;
  5129. this.label = label;
  5130. this.keyword = conf.keyword;
  5131. this.beforeExpr = !!conf.beforeExpr;
  5132. this.startsExpr = !!conf.startsExpr;
  5133. this.rightAssociative = !!conf.rightAssociative;
  5134. this.isLoop = !!conf.isLoop;
  5135. this.isAssign = !!conf.isAssign;
  5136. this.prefix = !!conf.prefix;
  5137. this.postfix = !!conf.postfix;
  5138. this.binop = conf.binop != null ? conf.binop : null;
  5139. this.updateContext = null;
  5140. }
  5141. }
  5142. const keywords$1 = new Map();
  5143. function createKeyword(name, options = {}) {
  5144. options.keyword = name;
  5145. const token = createToken(name, options);
  5146. keywords$1.set(name, token);
  5147. return token;
  5148. }
  5149. function createBinop(name, binop) {
  5150. return createToken(name, {
  5151. beforeExpr,
  5152. binop
  5153. });
  5154. }
  5155. let tokenTypeCounter = -1;
  5156. const tokenTypes = [];
  5157. const tokenLabels = [];
  5158. const tokenBinops = [];
  5159. const tokenBeforeExprs = [];
  5160. const tokenStartsExprs = [];
  5161. const tokenPrefixes = [];
  5162. function createToken(name, options = {}) {
  5163. var _options$binop, _options$beforeExpr, _options$startsExpr, _options$prefix;
  5164. ++tokenTypeCounter;
  5165. tokenLabels.push(name);
  5166. tokenBinops.push((_options$binop = options.binop) != null ? _options$binop : -1);
  5167. tokenBeforeExprs.push((_options$beforeExpr = options.beforeExpr) != null ? _options$beforeExpr : false);
  5168. tokenStartsExprs.push((_options$startsExpr = options.startsExpr) != null ? _options$startsExpr : false);
  5169. tokenPrefixes.push((_options$prefix = options.prefix) != null ? _options$prefix : false);
  5170. tokenTypes.push(new ExportedTokenType(name, options));
  5171. return tokenTypeCounter;
  5172. }
  5173. function createKeywordLike(name, options = {}) {
  5174. var _options$binop2, _options$beforeExpr2, _options$startsExpr2, _options$prefix2;
  5175. ++tokenTypeCounter;
  5176. keywords$1.set(name, tokenTypeCounter);
  5177. tokenLabels.push(name);
  5178. tokenBinops.push((_options$binop2 = options.binop) != null ? _options$binop2 : -1);
  5179. tokenBeforeExprs.push((_options$beforeExpr2 = options.beforeExpr) != null ? _options$beforeExpr2 : false);
  5180. tokenStartsExprs.push((_options$startsExpr2 = options.startsExpr) != null ? _options$startsExpr2 : false);
  5181. tokenPrefixes.push((_options$prefix2 = options.prefix) != null ? _options$prefix2 : false);
  5182. tokenTypes.push(new ExportedTokenType("name", options));
  5183. return tokenTypeCounter;
  5184. }
  5185. const tt = {
  5186. bracketL: createToken("[", {
  5187. beforeExpr,
  5188. startsExpr
  5189. }),
  5190. bracketHashL: createToken("#[", {
  5191. beforeExpr,
  5192. startsExpr
  5193. }),
  5194. bracketBarL: createToken("[|", {
  5195. beforeExpr,
  5196. startsExpr
  5197. }),
  5198. bracketR: createToken("]"),
  5199. bracketBarR: createToken("|]"),
  5200. braceL: createToken("{", {
  5201. beforeExpr,
  5202. startsExpr
  5203. }),
  5204. braceBarL: createToken("{|", {
  5205. beforeExpr,
  5206. startsExpr
  5207. }),
  5208. braceHashL: createToken("#{", {
  5209. beforeExpr,
  5210. startsExpr
  5211. }),
  5212. braceR: createToken("}"),
  5213. braceBarR: createToken("|}"),
  5214. parenL: createToken("(", {
  5215. beforeExpr,
  5216. startsExpr
  5217. }),
  5218. parenR: createToken(")"),
  5219. comma: createToken(",", {
  5220. beforeExpr
  5221. }),
  5222. semi: createToken(";", {
  5223. beforeExpr
  5224. }),
  5225. colon: createToken(":", {
  5226. beforeExpr
  5227. }),
  5228. doubleColon: createToken("::", {
  5229. beforeExpr
  5230. }),
  5231. dot: createToken("."),
  5232. question: createToken("?", {
  5233. beforeExpr
  5234. }),
  5235. questionDot: createToken("?."),
  5236. arrow: createToken("=>", {
  5237. beforeExpr
  5238. }),
  5239. template: createToken("template"),
  5240. ellipsis: createToken("...", {
  5241. beforeExpr
  5242. }),
  5243. backQuote: createToken("`", {
  5244. startsExpr
  5245. }),
  5246. dollarBraceL: createToken("${", {
  5247. beforeExpr,
  5248. startsExpr
  5249. }),
  5250. templateTail: createToken("...`", {
  5251. startsExpr
  5252. }),
  5253. templateNonTail: createToken("...${", {
  5254. beforeExpr,
  5255. startsExpr
  5256. }),
  5257. at: createToken("@"),
  5258. hash: createToken("#", {
  5259. startsExpr
  5260. }),
  5261. interpreterDirective: createToken("#!..."),
  5262. eq: createToken("=", {
  5263. beforeExpr,
  5264. isAssign
  5265. }),
  5266. assign: createToken("_=", {
  5267. beforeExpr,
  5268. isAssign
  5269. }),
  5270. slashAssign: createToken("_=", {
  5271. beforeExpr,
  5272. isAssign
  5273. }),
  5274. xorAssign: createToken("_=", {
  5275. beforeExpr,
  5276. isAssign
  5277. }),
  5278. moduloAssign: createToken("_=", {
  5279. beforeExpr,
  5280. isAssign
  5281. }),
  5282. incDec: createToken("++/--", {
  5283. prefix,
  5284. postfix,
  5285. startsExpr
  5286. }),
  5287. bang: createToken("!", {
  5288. beforeExpr,
  5289. prefix,
  5290. startsExpr
  5291. }),
  5292. tilde: createToken("~", {
  5293. beforeExpr,
  5294. prefix,
  5295. startsExpr
  5296. }),
  5297. doubleCaret: createToken("^^", {
  5298. startsExpr
  5299. }),
  5300. doubleAt: createToken("@@", {
  5301. startsExpr
  5302. }),
  5303. pipeline: createBinop("|>", 0),
  5304. nullishCoalescing: createBinop("??", 1),
  5305. logicalOR: createBinop("||", 1),
  5306. logicalAND: createBinop("&&", 2),
  5307. bitwiseOR: createBinop("|", 3),
  5308. bitwiseXOR: createBinop("^", 4),
  5309. bitwiseAND: createBinop("&", 5),
  5310. equality: createBinop("==/!=/===/!==", 6),
  5311. lt: createBinop("</>/<=/>=", 7),
  5312. gt: createBinop("</>/<=/>=", 7),
  5313. relational: createBinop("</>/<=/>=", 7),
  5314. bitShift: createBinop("<</>>/>>>", 8),
  5315. bitShiftL: createBinop("<</>>/>>>", 8),
  5316. bitShiftR: createBinop("<</>>/>>>", 8),
  5317. plusMin: createToken("+/-", {
  5318. beforeExpr,
  5319. binop: 9,
  5320. prefix,
  5321. startsExpr
  5322. }),
  5323. modulo: createToken("%", {
  5324. binop: 10,
  5325. startsExpr
  5326. }),
  5327. star: createToken("*", {
  5328. binop: 10
  5329. }),
  5330. slash: createBinop("/", 10),
  5331. exponent: createToken("**", {
  5332. beforeExpr,
  5333. binop: 11,
  5334. rightAssociative: true
  5335. }),
  5336. _in: createKeyword("in", {
  5337. beforeExpr,
  5338. binop: 7
  5339. }),
  5340. _instanceof: createKeyword("instanceof", {
  5341. beforeExpr,
  5342. binop: 7
  5343. }),
  5344. _break: createKeyword("break"),
  5345. _case: createKeyword("case", {
  5346. beforeExpr
  5347. }),
  5348. _catch: createKeyword("catch"),
  5349. _continue: createKeyword("continue"),
  5350. _debugger: createKeyword("debugger"),
  5351. _default: createKeyword("default", {
  5352. beforeExpr
  5353. }),
  5354. _else: createKeyword("else", {
  5355. beforeExpr
  5356. }),
  5357. _finally: createKeyword("finally"),
  5358. _function: createKeyword("function", {
  5359. startsExpr
  5360. }),
  5361. _if: createKeyword("if"),
  5362. _return: createKeyword("return", {
  5363. beforeExpr
  5364. }),
  5365. _switch: createKeyword("switch"),
  5366. _throw: createKeyword("throw", {
  5367. beforeExpr,
  5368. prefix,
  5369. startsExpr
  5370. }),
  5371. _try: createKeyword("try"),
  5372. _var: createKeyword("var"),
  5373. _const: createKeyword("const"),
  5374. _with: createKeyword("with"),
  5375. _new: createKeyword("new", {
  5376. beforeExpr,
  5377. startsExpr
  5378. }),
  5379. _this: createKeyword("this", {
  5380. startsExpr
  5381. }),
  5382. _super: createKeyword("super", {
  5383. startsExpr
  5384. }),
  5385. _class: createKeyword("class", {
  5386. startsExpr
  5387. }),
  5388. _extends: createKeyword("extends", {
  5389. beforeExpr
  5390. }),
  5391. _export: createKeyword("export"),
  5392. _import: createKeyword("import", {
  5393. startsExpr
  5394. }),
  5395. _null: createKeyword("null", {
  5396. startsExpr
  5397. }),
  5398. _true: createKeyword("true", {
  5399. startsExpr
  5400. }),
  5401. _false: createKeyword("false", {
  5402. startsExpr
  5403. }),
  5404. _typeof: createKeyword("typeof", {
  5405. beforeExpr,
  5406. prefix,
  5407. startsExpr
  5408. }),
  5409. _void: createKeyword("void", {
  5410. beforeExpr,
  5411. prefix,
  5412. startsExpr
  5413. }),
  5414. _delete: createKeyword("delete", {
  5415. beforeExpr,
  5416. prefix,
  5417. startsExpr
  5418. }),
  5419. _do: createKeyword("do", {
  5420. isLoop,
  5421. beforeExpr
  5422. }),
  5423. _for: createKeyword("for", {
  5424. isLoop
  5425. }),
  5426. _while: createKeyword("while", {
  5427. isLoop
  5428. }),
  5429. _as: createKeywordLike("as", {
  5430. startsExpr
  5431. }),
  5432. _assert: createKeywordLike("assert", {
  5433. startsExpr
  5434. }),
  5435. _async: createKeywordLike("async", {
  5436. startsExpr
  5437. }),
  5438. _await: createKeywordLike("await", {
  5439. startsExpr
  5440. }),
  5441. _defer: createKeywordLike("defer", {
  5442. startsExpr
  5443. }),
  5444. _from: createKeywordLike("from", {
  5445. startsExpr
  5446. }),
  5447. _get: createKeywordLike("get", {
  5448. startsExpr
  5449. }),
  5450. _let: createKeywordLike("let", {
  5451. startsExpr
  5452. }),
  5453. _meta: createKeywordLike("meta", {
  5454. startsExpr
  5455. }),
  5456. _of: createKeywordLike("of", {
  5457. startsExpr
  5458. }),
  5459. _sent: createKeywordLike("sent", {
  5460. startsExpr
  5461. }),
  5462. _set: createKeywordLike("set", {
  5463. startsExpr
  5464. }),
  5465. _source: createKeywordLike("source", {
  5466. startsExpr
  5467. }),
  5468. _static: createKeywordLike("static", {
  5469. startsExpr
  5470. }),
  5471. _using: createKeywordLike("using", {
  5472. startsExpr
  5473. }),
  5474. _yield: createKeywordLike("yield", {
  5475. startsExpr
  5476. }),
  5477. _asserts: createKeywordLike("asserts", {
  5478. startsExpr
  5479. }),
  5480. _checks: createKeywordLike("checks", {
  5481. startsExpr
  5482. }),
  5483. _exports: createKeywordLike("exports", {
  5484. startsExpr
  5485. }),
  5486. _global: createKeywordLike("global", {
  5487. startsExpr
  5488. }),
  5489. _implements: createKeywordLike("implements", {
  5490. startsExpr
  5491. }),
  5492. _intrinsic: createKeywordLike("intrinsic", {
  5493. startsExpr
  5494. }),
  5495. _infer: createKeywordLike("infer", {
  5496. startsExpr
  5497. }),
  5498. _is: createKeywordLike("is", {
  5499. startsExpr
  5500. }),
  5501. _mixins: createKeywordLike("mixins", {
  5502. startsExpr
  5503. }),
  5504. _proto: createKeywordLike("proto", {
  5505. startsExpr
  5506. }),
  5507. _require: createKeywordLike("require", {
  5508. startsExpr
  5509. }),
  5510. _satisfies: createKeywordLike("satisfies", {
  5511. startsExpr
  5512. }),
  5513. _keyof: createKeywordLike("keyof", {
  5514. startsExpr
  5515. }),
  5516. _readonly: createKeywordLike("readonly", {
  5517. startsExpr
  5518. }),
  5519. _unique: createKeywordLike("unique", {
  5520. startsExpr
  5521. }),
  5522. _abstract: createKeywordLike("abstract", {
  5523. startsExpr
  5524. }),
  5525. _declare: createKeywordLike("declare", {
  5526. startsExpr
  5527. }),
  5528. _enum: createKeywordLike("enum", {
  5529. startsExpr
  5530. }),
  5531. _module: createKeywordLike("module", {
  5532. startsExpr
  5533. }),
  5534. _namespace: createKeywordLike("namespace", {
  5535. startsExpr
  5536. }),
  5537. _interface: createKeywordLike("interface", {
  5538. startsExpr
  5539. }),
  5540. _type: createKeywordLike("type", {
  5541. startsExpr
  5542. }),
  5543. _opaque: createKeywordLike("opaque", {
  5544. startsExpr
  5545. }),
  5546. name: createToken("name", {
  5547. startsExpr
  5548. }),
  5549. placeholder: createToken("%%", {
  5550. startsExpr
  5551. }),
  5552. string: createToken("string", {
  5553. startsExpr
  5554. }),
  5555. num: createToken("num", {
  5556. startsExpr
  5557. }),
  5558. bigint: createToken("bigint", {
  5559. startsExpr
  5560. }),
  5561. decimal: createToken("decimal", {
  5562. startsExpr
  5563. }),
  5564. regexp: createToken("regexp", {
  5565. startsExpr
  5566. }),
  5567. privateName: createToken("#name", {
  5568. startsExpr
  5569. }),
  5570. eof: createToken("eof"),
  5571. jsxName: createToken("jsxName"),
  5572. jsxText: createToken("jsxText", {
  5573. beforeExpr
  5574. }),
  5575. jsxTagStart: createToken("jsxTagStart", {
  5576. startsExpr
  5577. }),
  5578. jsxTagEnd: createToken("jsxTagEnd")
  5579. };
  5580. function tokenIsIdentifier(token) {
  5581. return token >= 93 && token <= 133;
  5582. }
  5583. function tokenKeywordOrIdentifierIsKeyword(token) {
  5584. return token <= 92;
  5585. }
  5586. function tokenIsKeywordOrIdentifier(token) {
  5587. return token >= 58 && token <= 133;
  5588. }
  5589. function tokenIsLiteralPropertyName(token) {
  5590. return token >= 58 && token <= 137;
  5591. }
  5592. function tokenComesBeforeExpression(token) {
  5593. return tokenBeforeExprs[token];
  5594. }
  5595. function tokenCanStartExpression(token) {
  5596. return tokenStartsExprs[token];
  5597. }
  5598. function tokenIsAssignment(token) {
  5599. return token >= 29 && token <= 33;
  5600. }
  5601. function tokenIsFlowInterfaceOrTypeOrOpaque(token) {
  5602. return token >= 129 && token <= 131;
  5603. }
  5604. function tokenIsLoop(token) {
  5605. return token >= 90 && token <= 92;
  5606. }
  5607. function tokenIsKeyword(token) {
  5608. return token >= 58 && token <= 92;
  5609. }
  5610. function tokenIsOperator(token) {
  5611. return token >= 39 && token <= 59;
  5612. }
  5613. function tokenIsPostfix(token) {
  5614. return token === 34;
  5615. }
  5616. function tokenIsPrefix(token) {
  5617. return tokenPrefixes[token];
  5618. }
  5619. function tokenIsTSTypeOperator(token) {
  5620. return token >= 121 && token <= 123;
  5621. }
  5622. function tokenIsTSDeclarationStart(token) {
  5623. return token >= 124 && token <= 130;
  5624. }
  5625. function tokenLabelName(token) {
  5626. return tokenLabels[token];
  5627. }
  5628. function tokenOperatorPrecedence(token) {
  5629. return tokenBinops[token];
  5630. }
  5631. function tokenIsRightAssociative(token) {
  5632. return token === 57;
  5633. }
  5634. function tokenIsTemplate(token) {
  5635. return token >= 24 && token <= 25;
  5636. }
  5637. function getExportedToken(token) {
  5638. return tokenTypes[token];
  5639. }
  5640. tokenTypes[8].updateContext = context => {
  5641. context.pop();
  5642. };
  5643. tokenTypes[5].updateContext = tokenTypes[7].updateContext = tokenTypes[23].updateContext = context => {
  5644. context.push(types.brace);
  5645. };
  5646. tokenTypes[22].updateContext = context => {
  5647. if (context[context.length - 1] === types.template) {
  5648. context.pop();
  5649. } else {
  5650. context.push(types.template);
  5651. }
  5652. };
  5653. tokenTypes[143].updateContext = context => {
  5654. context.push(types.j_expr, types.j_oTag);
  5655. };
  5656. 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";
  5657. 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";
  5658. const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  5659. const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  5660. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  5661. 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];
  5662. 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];
  5663. function isInAstralSet(code, set) {
  5664. let pos = 0x10000;
  5665. for (let i = 0, length = set.length; i < length; i += 2) {
  5666. pos += set[i];
  5667. if (pos > code) return false;
  5668. pos += set[i + 1];
  5669. if (pos >= code) return true;
  5670. }
  5671. return false;
  5672. }
  5673. function isIdentifierStart(code) {
  5674. if (code < 65) return code === 36;
  5675. if (code <= 90) return true;
  5676. if (code < 97) return code === 95;
  5677. if (code <= 122) return true;
  5678. if (code <= 0xffff) {
  5679. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  5680. }
  5681. return isInAstralSet(code, astralIdentifierStartCodes);
  5682. }
  5683. function isIdentifierChar(code) {
  5684. if (code < 48) return code === 36;
  5685. if (code < 58) return true;
  5686. if (code < 65) return false;
  5687. if (code <= 90) return true;
  5688. if (code < 97) return code === 95;
  5689. if (code <= 122) return true;
  5690. if (code <= 0xffff) {
  5691. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  5692. }
  5693. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  5694. }
  5695. const reservedWords = {
  5696. 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"],
  5697. strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  5698. strictBind: ["eval", "arguments"]
  5699. };
  5700. const keywords = new Set(reservedWords.keyword);
  5701. const reservedWordsStrictSet = new Set(reservedWords.strict);
  5702. const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
  5703. function isReservedWord(word, inModule) {
  5704. return inModule && word === "await" || word === "enum";
  5705. }
  5706. function isStrictReservedWord(word, inModule) {
  5707. return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
  5708. }
  5709. function isStrictBindOnlyReservedWord(word) {
  5710. return reservedWordsStrictBindSet.has(word);
  5711. }
  5712. function isStrictBindReservedWord(word, inModule) {
  5713. return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
  5714. }
  5715. function isKeyword(word) {
  5716. return keywords.has(word);
  5717. }
  5718. function isIteratorStart(current, next, next2) {
  5719. return current === 64 && next === 64 && isIdentifierStart(next2);
  5720. }
  5721. 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"]);
  5722. function canBeReservedWord(word) {
  5723. return reservedWordLikeSet.has(word);
  5724. }
  5725. class Scope {
  5726. constructor(flags) {
  5727. this.flags = 0;
  5728. this.names = new Map();
  5729. this.firstLexicalName = "";
  5730. this.flags = flags;
  5731. }
  5732. }
  5733. class ScopeHandler {
  5734. constructor(parser, inModule) {
  5735. this.parser = void 0;
  5736. this.scopeStack = [];
  5737. this.inModule = void 0;
  5738. this.undefinedExports = new Map();
  5739. this.parser = parser;
  5740. this.inModule = inModule;
  5741. }
  5742. get inTopLevel() {
  5743. return (this.currentScope().flags & 1) > 0;
  5744. }
  5745. get inFunction() {
  5746. return (this.currentVarScopeFlags() & 2) > 0;
  5747. }
  5748. get allowSuper() {
  5749. return (this.currentThisScopeFlags() & 16) > 0;
  5750. }
  5751. get allowDirectSuper() {
  5752. return (this.currentThisScopeFlags() & 32) > 0;
  5753. }
  5754. get allowNewTarget() {
  5755. return (this.currentThisScopeFlags() & 512) > 0;
  5756. }
  5757. get inClass() {
  5758. return (this.currentThisScopeFlags() & 64) > 0;
  5759. }
  5760. get inClassAndNotInNonArrowFunction() {
  5761. const flags = this.currentThisScopeFlags();
  5762. return (flags & 64) > 0 && (flags & 2) === 0;
  5763. }
  5764. get inStaticBlock() {
  5765. for (let i = this.scopeStack.length - 1;; i--) {
  5766. const {
  5767. flags
  5768. } = this.scopeStack[i];
  5769. if (flags & 128) {
  5770. return true;
  5771. }
  5772. if (flags & (1667 | 64)) {
  5773. return false;
  5774. }
  5775. }
  5776. }
  5777. get inNonArrowFunction() {
  5778. return (this.currentThisScopeFlags() & 2) > 0;
  5779. }
  5780. get inBareCaseStatement() {
  5781. return (this.currentScope().flags & 256) > 0;
  5782. }
  5783. get treatFunctionsAsVar() {
  5784. return this.treatFunctionsAsVarInScope(this.currentScope());
  5785. }
  5786. createScope(flags) {
  5787. return new Scope(flags);
  5788. }
  5789. enter(flags) {
  5790. this.scopeStack.push(this.createScope(flags));
  5791. }
  5792. exit() {
  5793. const scope = this.scopeStack.pop();
  5794. return scope.flags;
  5795. }
  5796. treatFunctionsAsVarInScope(scope) {
  5797. return !!(scope.flags & (2 | 128) || !this.parser.inModule && scope.flags & 1);
  5798. }
  5799. declareName(name, bindingType, loc) {
  5800. let scope = this.currentScope();
  5801. if (bindingType & 8 || bindingType & 16) {
  5802. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  5803. let type = scope.names.get(name) || 0;
  5804. if (bindingType & 16) {
  5805. type = type | 4;
  5806. } else {
  5807. if (!scope.firstLexicalName) {
  5808. scope.firstLexicalName = name;
  5809. }
  5810. type = type | 2;
  5811. }
  5812. scope.names.set(name, type);
  5813. if (bindingType & 8) {
  5814. this.maybeExportDefined(scope, name);
  5815. }
  5816. } else if (bindingType & 4) {
  5817. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  5818. scope = this.scopeStack[i];
  5819. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  5820. scope.names.set(name, (scope.names.get(name) || 0) | 1);
  5821. this.maybeExportDefined(scope, name);
  5822. if (scope.flags & 1667) break;
  5823. }
  5824. }
  5825. if (this.parser.inModule && scope.flags & 1) {
  5826. this.undefinedExports.delete(name);
  5827. }
  5828. }
  5829. maybeExportDefined(scope, name) {
  5830. if (this.parser.inModule && scope.flags & 1) {
  5831. this.undefinedExports.delete(name);
  5832. }
  5833. }
  5834. checkRedeclarationInScope(scope, name, bindingType, loc) {
  5835. if (this.isRedeclaredInScope(scope, name, bindingType)) {
  5836. this.parser.raise(Errors.VarRedeclaration, loc, {
  5837. identifierName: name
  5838. });
  5839. }
  5840. }
  5841. isRedeclaredInScope(scope, name, bindingType) {
  5842. if (!(bindingType & 1)) return false;
  5843. if (bindingType & 8) {
  5844. return scope.names.has(name);
  5845. }
  5846. const type = scope.names.get(name) || 0;
  5847. if (bindingType & 16) {
  5848. return (type & 2) > 0 || !this.treatFunctionsAsVarInScope(scope) && (type & 1) > 0;
  5849. }
  5850. return (type & 2) > 0 && !(scope.flags & 8 && scope.firstLexicalName === name) || !this.treatFunctionsAsVarInScope(scope) && (type & 4) > 0;
  5851. }
  5852. checkLocalExport(id) {
  5853. const {
  5854. name
  5855. } = id;
  5856. const topLevelScope = this.scopeStack[0];
  5857. if (!topLevelScope.names.has(name)) {
  5858. this.undefinedExports.set(name, id.loc.start);
  5859. }
  5860. }
  5861. currentScope() {
  5862. return this.scopeStack[this.scopeStack.length - 1];
  5863. }
  5864. currentVarScopeFlags() {
  5865. for (let i = this.scopeStack.length - 1;; i--) {
  5866. const {
  5867. flags
  5868. } = this.scopeStack[i];
  5869. if (flags & 1667) {
  5870. return flags;
  5871. }
  5872. }
  5873. }
  5874. currentThisScopeFlags() {
  5875. for (let i = this.scopeStack.length - 1;; i--) {
  5876. const {
  5877. flags
  5878. } = this.scopeStack[i];
  5879. if (flags & (1667 | 64) && !(flags & 4)) {
  5880. return flags;
  5881. }
  5882. }
  5883. }
  5884. }
  5885. class FlowScope extends Scope {
  5886. constructor(...args) {
  5887. super(...args);
  5888. this.declareFunctions = new Set();
  5889. }
  5890. }
  5891. class FlowScopeHandler extends ScopeHandler {
  5892. createScope(flags) {
  5893. return new FlowScope(flags);
  5894. }
  5895. declareName(name, bindingType, loc) {
  5896. const scope = this.currentScope();
  5897. if (bindingType & 2048) {
  5898. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  5899. this.maybeExportDefined(scope, name);
  5900. scope.declareFunctions.add(name);
  5901. return;
  5902. }
  5903. super.declareName(name, bindingType, loc);
  5904. }
  5905. isRedeclaredInScope(scope, name, bindingType) {
  5906. if (super.isRedeclaredInScope(scope, name, bindingType)) return true;
  5907. if (bindingType & 2048 && !scope.declareFunctions.has(name)) {
  5908. const type = scope.names.get(name);
  5909. return (type & 4) > 0 || (type & 2) > 0;
  5910. }
  5911. return false;
  5912. }
  5913. checkLocalExport(id) {
  5914. if (!this.scopeStack[0].declareFunctions.has(id.name)) {
  5915. super.checkLocalExport(id);
  5916. }
  5917. }
  5918. }
  5919. const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
  5920. const FlowErrors = ParseErrorEnum`flow`({
  5921. AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
  5922. 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.",
  5923. AssignReservedType: ({
  5924. reservedType
  5925. }) => `Cannot overwrite reserved type ${reservedType}.`,
  5926. DeclareClassElement: "The `declare` modifier can only appear on class fields.",
  5927. DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.",
  5928. DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement.",
  5929. EnumBooleanMemberNotInitialized: ({
  5930. memberName,
  5931. enumName
  5932. }) => `Boolean enum members need to be initialized. Use either \`${memberName} = true,\` or \`${memberName} = false,\` in enum \`${enumName}\`.`,
  5933. EnumDuplicateMemberName: ({
  5934. memberName,
  5935. enumName
  5936. }) => `Enum member names need to be unique, but the name \`${memberName}\` has already been used before in enum \`${enumName}\`.`,
  5937. EnumInconsistentMemberValues: ({
  5938. enumName
  5939. }) => `Enum \`${enumName}\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`,
  5940. EnumInvalidExplicitType: ({
  5941. invalidEnumType,
  5942. enumName
  5943. }) => `Enum type \`${invalidEnumType}\` is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`,
  5944. EnumInvalidExplicitTypeUnknownSupplied: ({
  5945. enumName
  5946. }) => `Supplied enum type is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`,
  5947. EnumInvalidMemberInitializerPrimaryType: ({
  5948. enumName,
  5949. memberName,
  5950. explicitType
  5951. }) => `Enum \`${enumName}\` has type \`${explicitType}\`, so the initializer of \`${memberName}\` needs to be a ${explicitType} literal.`,
  5952. EnumInvalidMemberInitializerSymbolType: ({
  5953. enumName,
  5954. memberName
  5955. }) => `Symbol enum members cannot be initialized. Use \`${memberName},\` in enum \`${enumName}\`.`,
  5956. EnumInvalidMemberInitializerUnknownType: ({
  5957. enumName,
  5958. memberName
  5959. }) => `The enum member initializer for \`${memberName}\` needs to be a literal (either a boolean, number, or string) in enum \`${enumName}\`.`,
  5960. EnumInvalidMemberName: ({
  5961. enumName,
  5962. memberName,
  5963. suggestion
  5964. }) => `Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \`${memberName}\`, consider using \`${suggestion}\`, in enum \`${enumName}\`.`,
  5965. EnumNumberMemberNotInitialized: ({
  5966. enumName,
  5967. memberName
  5968. }) => `Number enum members need to be initialized, e.g. \`${memberName} = 1\` in enum \`${enumName}\`.`,
  5969. EnumStringMemberInconsistentlyInitialized: ({
  5970. enumName
  5971. }) => `String enum members need to consistently either all use initializers, or use no initializers, in enum \`${enumName}\`.`,
  5972. GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.",
  5973. ImportReflectionHasImportType: "An `import module` declaration can not use `type` or `typeof` keyword.",
  5974. 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.",
  5975. InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type.",
  5976. InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions.",
  5977. InexactVariance: "Explicit inexact syntax cannot have variance.",
  5978. InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`.",
  5979. MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
  5980. NestedDeclareModule: "`declare module` cannot be used inside another `declare module`.",
  5981. NestedFlowComment: "Cannot have a flow comment inside another flow comment.",
  5982. PatternIsOptional: Object.assign({
  5983. message: "A binding pattern parameter cannot be optional in an implementation signature."
  5984. }, {
  5985. reasonCode: "OptionalBindingPattern"
  5986. }),
  5987. SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.",
  5988. SpreadVariance: "Spread properties cannot have variance.",
  5989. ThisParamAnnotationRequired: "A type annotation is required for the `this` parameter.",
  5990. ThisParamBannedInConstructor: "Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",
  5991. ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.",
  5992. ThisParamMustBeFirst: "The `this` parameter must be the first function parameter.",
  5993. ThisParamNoDefault: "The `this` parameter may not have a default value.",
  5994. TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
  5995. TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis.",
  5996. UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object.",
  5997. UnexpectedReservedType: ({
  5998. reservedType
  5999. }) => `Unexpected reserved type ${reservedType}.`,
  6000. UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new.",
  6001. UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.",
  6002. UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions.",
  6003. UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint".',
  6004. UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration.",
  6005. UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`.",
  6006. UnsupportedDeclareExportKind: ({
  6007. unsupportedExportKind,
  6008. suggestion
  6009. }) => `\`declare export ${unsupportedExportKind}\` is not supported. Use \`${suggestion}\` instead.`,
  6010. UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module.",
  6011. UnterminatedFlowComment: "Unterminated flow-comment."
  6012. });
  6013. function isEsModuleType(bodyElement) {
  6014. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  6015. }
  6016. function hasTypeImportKind(node) {
  6017. return node.importKind === "type" || node.importKind === "typeof";
  6018. }
  6019. const exportSuggestions = {
  6020. const: "declare export var",
  6021. let: "declare export var",
  6022. type: "export type",
  6023. interface: "export interface"
  6024. };
  6025. function partition(list, test) {
  6026. const list1 = [];
  6027. const list2 = [];
  6028. for (let i = 0; i < list.length; i++) {
  6029. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  6030. }
  6031. return [list1, list2];
  6032. }
  6033. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  6034. var flow = superClass => class FlowParserMixin extends superClass {
  6035. constructor(...args) {
  6036. super(...args);
  6037. this.flowPragma = undefined;
  6038. }
  6039. getScopeHandler() {
  6040. return FlowScopeHandler;
  6041. }
  6042. shouldParseTypes() {
  6043. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  6044. }
  6045. finishToken(type, val) {
  6046. if (type !== 134 && type !== 13 && type !== 28) {
  6047. if (this.flowPragma === undefined) {
  6048. this.flowPragma = null;
  6049. }
  6050. }
  6051. super.finishToken(type, val);
  6052. }
  6053. addComment(comment) {
  6054. if (this.flowPragma === undefined) {
  6055. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  6056. if (!matches) ;else if (matches[1] === "flow") {
  6057. this.flowPragma = "flow";
  6058. } else if (matches[1] === "noflow") {
  6059. this.flowPragma = "noflow";
  6060. } else {
  6061. throw new Error("Unexpected flow pragma");
  6062. }
  6063. }
  6064. super.addComment(comment);
  6065. }
  6066. flowParseTypeInitialiser(tok) {
  6067. const oldInType = this.state.inType;
  6068. this.state.inType = true;
  6069. this.expect(tok || 14);
  6070. const type = this.flowParseType();
  6071. this.state.inType = oldInType;
  6072. return type;
  6073. }
  6074. flowParsePredicate() {
  6075. const node = this.startNode();
  6076. const moduloLoc = this.state.startLoc;
  6077. this.next();
  6078. this.expectContextual(110);
  6079. if (this.state.lastTokStartLoc.index > moduloLoc.index + 1) {
  6080. this.raise(FlowErrors.UnexpectedSpaceBetweenModuloChecks, moduloLoc);
  6081. }
  6082. if (this.eat(10)) {
  6083. node.value = super.parseExpression();
  6084. this.expect(11);
  6085. return this.finishNode(node, "DeclaredPredicate");
  6086. } else {
  6087. return this.finishNode(node, "InferredPredicate");
  6088. }
  6089. }
  6090. flowParseTypeAndPredicateInitialiser() {
  6091. const oldInType = this.state.inType;
  6092. this.state.inType = true;
  6093. this.expect(14);
  6094. let type = null;
  6095. let predicate = null;
  6096. if (this.match(54)) {
  6097. this.state.inType = oldInType;
  6098. predicate = this.flowParsePredicate();
  6099. } else {
  6100. type = this.flowParseType();
  6101. this.state.inType = oldInType;
  6102. if (this.match(54)) {
  6103. predicate = this.flowParsePredicate();
  6104. }
  6105. }
  6106. return [type, predicate];
  6107. }
  6108. flowParseDeclareClass(node) {
  6109. this.next();
  6110. this.flowParseInterfaceish(node, true);
  6111. return this.finishNode(node, "DeclareClass");
  6112. }
  6113. flowParseDeclareFunction(node) {
  6114. this.next();
  6115. const id = node.id = this.parseIdentifier();
  6116. const typeNode = this.startNode();
  6117. const typeContainer = this.startNode();
  6118. if (this.match(47)) {
  6119. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  6120. } else {
  6121. typeNode.typeParameters = null;
  6122. }
  6123. this.expect(10);
  6124. const tmp = this.flowParseFunctionTypeParams();
  6125. typeNode.params = tmp.params;
  6126. typeNode.rest = tmp.rest;
  6127. typeNode.this = tmp._this;
  6128. this.expect(11);
  6129. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  6130. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  6131. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  6132. this.resetEndLocation(id);
  6133. this.semicolon();
  6134. this.scope.declareName(node.id.name, 2048, node.id.loc.start);
  6135. return this.finishNode(node, "DeclareFunction");
  6136. }
  6137. flowParseDeclare(node, insideModule) {
  6138. if (this.match(80)) {
  6139. return this.flowParseDeclareClass(node);
  6140. } else if (this.match(68)) {
  6141. return this.flowParseDeclareFunction(node);
  6142. } else if (this.match(74)) {
  6143. return this.flowParseDeclareVariable(node);
  6144. } else if (this.eatContextual(127)) {
  6145. if (this.match(16)) {
  6146. return this.flowParseDeclareModuleExports(node);
  6147. } else {
  6148. if (insideModule) {
  6149. this.raise(FlowErrors.NestedDeclareModule, this.state.lastTokStartLoc);
  6150. }
  6151. return this.flowParseDeclareModule(node);
  6152. }
  6153. } else if (this.isContextual(130)) {
  6154. return this.flowParseDeclareTypeAlias(node);
  6155. } else if (this.isContextual(131)) {
  6156. return this.flowParseDeclareOpaqueType(node);
  6157. } else if (this.isContextual(129)) {
  6158. return this.flowParseDeclareInterface(node);
  6159. } else if (this.match(82)) {
  6160. return this.flowParseDeclareExportDeclaration(node, insideModule);
  6161. }
  6162. throw this.unexpected();
  6163. }
  6164. flowParseDeclareVariable(node) {
  6165. this.next();
  6166. node.id = this.flowParseTypeAnnotatableIdentifier();
  6167. this.scope.declareName(node.id.name, 5, node.id.loc.start);
  6168. this.semicolon();
  6169. return this.finishNode(node, "DeclareVariable");
  6170. }
  6171. flowParseDeclareModule(node) {
  6172. this.scope.enter(0);
  6173. if (this.match(134)) {
  6174. node.id = super.parseExprAtom();
  6175. } else {
  6176. node.id = this.parseIdentifier();
  6177. }
  6178. const bodyNode = node.body = this.startNode();
  6179. const body = bodyNode.body = [];
  6180. this.expect(5);
  6181. while (!this.match(8)) {
  6182. const bodyNode = this.startNode();
  6183. if (this.match(83)) {
  6184. this.next();
  6185. if (!this.isContextual(130) && !this.match(87)) {
  6186. this.raise(FlowErrors.InvalidNonTypeImportInDeclareModule, this.state.lastTokStartLoc);
  6187. }
  6188. body.push(super.parseImport(bodyNode));
  6189. } else {
  6190. this.expectContextual(125, FlowErrors.UnsupportedStatementInDeclareModule);
  6191. body.push(this.flowParseDeclare(bodyNode, true));
  6192. }
  6193. }
  6194. this.scope.exit();
  6195. this.expect(8);
  6196. this.finishNode(bodyNode, "BlockStatement");
  6197. let kind = null;
  6198. let hasModuleExport = false;
  6199. body.forEach(bodyElement => {
  6200. if (isEsModuleType(bodyElement)) {
  6201. if (kind === "CommonJS") {
  6202. this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement);
  6203. }
  6204. kind = "ES";
  6205. } else if (bodyElement.type === "DeclareModuleExports") {
  6206. if (hasModuleExport) {
  6207. this.raise(FlowErrors.DuplicateDeclareModuleExports, bodyElement);
  6208. }
  6209. if (kind === "ES") {
  6210. this.raise(FlowErrors.AmbiguousDeclareModuleKind, bodyElement);
  6211. }
  6212. kind = "CommonJS";
  6213. hasModuleExport = true;
  6214. }
  6215. });
  6216. node.kind = kind || "CommonJS";
  6217. return this.finishNode(node, "DeclareModule");
  6218. }
  6219. flowParseDeclareExportDeclaration(node, insideModule) {
  6220. this.expect(82);
  6221. if (this.eat(65)) {
  6222. if (this.match(68) || this.match(80)) {
  6223. node.declaration = this.flowParseDeclare(this.startNode());
  6224. } else {
  6225. node.declaration = this.flowParseType();
  6226. this.semicolon();
  6227. }
  6228. node.default = true;
  6229. return this.finishNode(node, "DeclareExportDeclaration");
  6230. } else {
  6231. if (this.match(75) || this.isLet() || (this.isContextual(130) || this.isContextual(129)) && !insideModule) {
  6232. const label = this.state.value;
  6233. throw this.raise(FlowErrors.UnsupportedDeclareExportKind, this.state.startLoc, {
  6234. unsupportedExportKind: label,
  6235. suggestion: exportSuggestions[label]
  6236. });
  6237. }
  6238. if (this.match(74) || this.match(68) || this.match(80) || this.isContextual(131)) {
  6239. node.declaration = this.flowParseDeclare(this.startNode());
  6240. node.default = false;
  6241. return this.finishNode(node, "DeclareExportDeclaration");
  6242. } else if (this.match(55) || this.match(5) || this.isContextual(129) || this.isContextual(130) || this.isContextual(131)) {
  6243. node = this.parseExport(node, null);
  6244. if (node.type === "ExportNamedDeclaration") {
  6245. node.default = false;
  6246. delete node.exportKind;
  6247. return this.castNodeTo(node, "DeclareExportDeclaration");
  6248. } else {
  6249. return this.castNodeTo(node, "DeclareExportAllDeclaration");
  6250. }
  6251. }
  6252. }
  6253. throw this.unexpected();
  6254. }
  6255. flowParseDeclareModuleExports(node) {
  6256. this.next();
  6257. this.expectContextual(111);
  6258. node.typeAnnotation = this.flowParseTypeAnnotation();
  6259. this.semicolon();
  6260. return this.finishNode(node, "DeclareModuleExports");
  6261. }
  6262. flowParseDeclareTypeAlias(node) {
  6263. this.next();
  6264. const finished = this.flowParseTypeAlias(node);
  6265. this.castNodeTo(finished, "DeclareTypeAlias");
  6266. return finished;
  6267. }
  6268. flowParseDeclareOpaqueType(node) {
  6269. this.next();
  6270. const finished = this.flowParseOpaqueType(node, true);
  6271. this.castNodeTo(finished, "DeclareOpaqueType");
  6272. return finished;
  6273. }
  6274. flowParseDeclareInterface(node) {
  6275. this.next();
  6276. this.flowParseInterfaceish(node, false);
  6277. return this.finishNode(node, "DeclareInterface");
  6278. }
  6279. flowParseInterfaceish(node, isClass) {
  6280. node.id = this.flowParseRestrictedIdentifier(!isClass, true);
  6281. this.scope.declareName(node.id.name, isClass ? 17 : 8201, node.id.loc.start);
  6282. if (this.match(47)) {
  6283. node.typeParameters = this.flowParseTypeParameterDeclaration();
  6284. } else {
  6285. node.typeParameters = null;
  6286. }
  6287. node.extends = [];
  6288. if (this.eat(81)) {
  6289. do {
  6290. node.extends.push(this.flowParseInterfaceExtends());
  6291. } while (!isClass && this.eat(12));
  6292. }
  6293. if (isClass) {
  6294. node.implements = [];
  6295. node.mixins = [];
  6296. if (this.eatContextual(117)) {
  6297. do {
  6298. node.mixins.push(this.flowParseInterfaceExtends());
  6299. } while (this.eat(12));
  6300. }
  6301. if (this.eatContextual(113)) {
  6302. do {
  6303. node.implements.push(this.flowParseInterfaceExtends());
  6304. } while (this.eat(12));
  6305. }
  6306. }
  6307. node.body = this.flowParseObjectType({
  6308. allowStatic: isClass,
  6309. allowExact: false,
  6310. allowSpread: false,
  6311. allowProto: isClass,
  6312. allowInexact: false
  6313. });
  6314. }
  6315. flowParseInterfaceExtends() {
  6316. const node = this.startNode();
  6317. node.id = this.flowParseQualifiedTypeIdentifier();
  6318. if (this.match(47)) {
  6319. node.typeParameters = this.flowParseTypeParameterInstantiation();
  6320. } else {
  6321. node.typeParameters = null;
  6322. }
  6323. return this.finishNode(node, "InterfaceExtends");
  6324. }
  6325. flowParseInterface(node) {
  6326. this.flowParseInterfaceish(node, false);
  6327. return this.finishNode(node, "InterfaceDeclaration");
  6328. }
  6329. checkNotUnderscore(word) {
  6330. if (word === "_") {
  6331. this.raise(FlowErrors.UnexpectedReservedUnderscore, this.state.startLoc);
  6332. }
  6333. }
  6334. checkReservedType(word, startLoc, declaration) {
  6335. if (!reservedTypes.has(word)) return;
  6336. this.raise(declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, startLoc, {
  6337. reservedType: word
  6338. });
  6339. }
  6340. flowParseRestrictedIdentifierName(liberal, declaration) {
  6341. this.checkReservedType(this.state.value, this.state.startLoc, declaration);
  6342. return this.parseIdentifierName(liberal);
  6343. }
  6344. flowParseRestrictedIdentifier(liberal, declaration) {
  6345. const node = this.startNode();
  6346. const name = this.flowParseRestrictedIdentifierName(liberal, declaration);
  6347. return this.createIdentifier(node, name);
  6348. }
  6349. flowParseTypeAlias(node) {
  6350. node.id = this.flowParseRestrictedIdentifier(false, true);
  6351. this.scope.declareName(node.id.name, 8201, node.id.loc.start);
  6352. if (this.match(47)) {
  6353. node.typeParameters = this.flowParseTypeParameterDeclaration();
  6354. } else {
  6355. node.typeParameters = null;
  6356. }
  6357. node.right = this.flowParseTypeInitialiser(29);
  6358. this.semicolon();
  6359. return this.finishNode(node, "TypeAlias");
  6360. }
  6361. flowParseOpaqueType(node, declare) {
  6362. this.expectContextual(130);
  6363. node.id = this.flowParseRestrictedIdentifier(true, true);
  6364. this.scope.declareName(node.id.name, 8201, node.id.loc.start);
  6365. if (this.match(47)) {
  6366. node.typeParameters = this.flowParseTypeParameterDeclaration();
  6367. } else {
  6368. node.typeParameters = null;
  6369. }
  6370. node.supertype = null;
  6371. if (this.match(14)) {
  6372. node.supertype = this.flowParseTypeInitialiser(14);
  6373. }
  6374. node.impltype = null;
  6375. if (!declare) {
  6376. node.impltype = this.flowParseTypeInitialiser(29);
  6377. }
  6378. this.semicolon();
  6379. return this.finishNode(node, "OpaqueType");
  6380. }
  6381. flowParseTypeParameterBound() {
  6382. if (this.match(14) || this.isContextual(81)) {
  6383. const node = this.startNode();
  6384. this.next();
  6385. node.typeAnnotation = this.flowParseType();
  6386. return this.finishNode(node, "TypeAnnotation");
  6387. }
  6388. }
  6389. flowParseTypeParameter(requireDefault = false) {
  6390. const nodeStartLoc = this.state.startLoc;
  6391. const node = this.startNode();
  6392. const variance = this.flowParseVariance();
  6393. node.name = this.flowParseRestrictedIdentifierName();
  6394. node.variance = variance;
  6395. node.bound = this.flowParseTypeParameterBound();
  6396. if (this.match(29)) {
  6397. this.eat(29);
  6398. node.default = this.flowParseType();
  6399. } else {
  6400. if (requireDefault) {
  6401. this.raise(FlowErrors.MissingTypeParamDefault, nodeStartLoc);
  6402. }
  6403. }
  6404. return this.finishNode(node, "TypeParameter");
  6405. }
  6406. flowParseTypeParameterDeclaration() {
  6407. const oldInType = this.state.inType;
  6408. const node = this.startNode();
  6409. node.params = [];
  6410. this.state.inType = true;
  6411. if (this.match(47) || this.match(143)) {
  6412. this.next();
  6413. } else {
  6414. this.unexpected();
  6415. }
  6416. let defaultRequired = false;
  6417. do {
  6418. const typeParameter = this.flowParseTypeParameter(defaultRequired);
  6419. node.params.push(typeParameter);
  6420. if (typeParameter.default) {
  6421. defaultRequired = true;
  6422. }
  6423. if (!this.match(48)) {
  6424. this.expect(12);
  6425. }
  6426. } while (!this.match(48));
  6427. this.expect(48);
  6428. this.state.inType = oldInType;
  6429. return this.finishNode(node, "TypeParameterDeclaration");
  6430. }
  6431. flowInTopLevelContext(cb) {
  6432. if (this.curContext() !== types.brace) {
  6433. const oldContext = this.state.context;
  6434. this.state.context = [oldContext[0]];
  6435. try {
  6436. return cb();
  6437. } finally {
  6438. this.state.context = oldContext;
  6439. }
  6440. } else {
  6441. return cb();
  6442. }
  6443. }
  6444. flowParseTypeParameterInstantiationInExpression() {
  6445. if (this.reScan_lt() !== 47) return;
  6446. return this.flowParseTypeParameterInstantiation();
  6447. }
  6448. flowParseTypeParameterInstantiation() {
  6449. const node = this.startNode();
  6450. const oldInType = this.state.inType;
  6451. this.state.inType = true;
  6452. node.params = [];
  6453. this.flowInTopLevelContext(() => {
  6454. this.expect(47);
  6455. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  6456. this.state.noAnonFunctionType = false;
  6457. while (!this.match(48)) {
  6458. node.params.push(this.flowParseType());
  6459. if (!this.match(48)) {
  6460. this.expect(12);
  6461. }
  6462. }
  6463. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  6464. });
  6465. this.state.inType = oldInType;
  6466. if (!this.state.inType && this.curContext() === types.brace) {
  6467. this.reScan_lt_gt();
  6468. }
  6469. this.expect(48);
  6470. return this.finishNode(node, "TypeParameterInstantiation");
  6471. }
  6472. flowParseTypeParameterInstantiationCallOrNew() {
  6473. if (this.reScan_lt() !== 47) return null;
  6474. const node = this.startNode();
  6475. const oldInType = this.state.inType;
  6476. node.params = [];
  6477. this.state.inType = true;
  6478. this.expect(47);
  6479. while (!this.match(48)) {
  6480. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  6481. if (!this.match(48)) {
  6482. this.expect(12);
  6483. }
  6484. }
  6485. this.expect(48);
  6486. this.state.inType = oldInType;
  6487. return this.finishNode(node, "TypeParameterInstantiation");
  6488. }
  6489. flowParseInterfaceType() {
  6490. const node = this.startNode();
  6491. this.expectContextual(129);
  6492. node.extends = [];
  6493. if (this.eat(81)) {
  6494. do {
  6495. node.extends.push(this.flowParseInterfaceExtends());
  6496. } while (this.eat(12));
  6497. }
  6498. node.body = this.flowParseObjectType({
  6499. allowStatic: false,
  6500. allowExact: false,
  6501. allowSpread: false,
  6502. allowProto: false,
  6503. allowInexact: false
  6504. });
  6505. return this.finishNode(node, "InterfaceTypeAnnotation");
  6506. }
  6507. flowParseObjectPropertyKey() {
  6508. return this.match(135) || this.match(134) ? super.parseExprAtom() : this.parseIdentifier(true);
  6509. }
  6510. flowParseObjectTypeIndexer(node, isStatic, variance) {
  6511. node.static = isStatic;
  6512. if (this.lookahead().type === 14) {
  6513. node.id = this.flowParseObjectPropertyKey();
  6514. node.key = this.flowParseTypeInitialiser();
  6515. } else {
  6516. node.id = null;
  6517. node.key = this.flowParseType();
  6518. }
  6519. this.expect(3);
  6520. node.value = this.flowParseTypeInitialiser();
  6521. node.variance = variance;
  6522. return this.finishNode(node, "ObjectTypeIndexer");
  6523. }
  6524. flowParseObjectTypeInternalSlot(node, isStatic) {
  6525. node.static = isStatic;
  6526. node.id = this.flowParseObjectPropertyKey();
  6527. this.expect(3);
  6528. this.expect(3);
  6529. if (this.match(47) || this.match(10)) {
  6530. node.method = true;
  6531. node.optional = false;
  6532. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start));
  6533. } else {
  6534. node.method = false;
  6535. if (this.eat(17)) {
  6536. node.optional = true;
  6537. }
  6538. node.value = this.flowParseTypeInitialiser();
  6539. }
  6540. return this.finishNode(node, "ObjectTypeInternalSlot");
  6541. }
  6542. flowParseObjectTypeMethodish(node) {
  6543. node.params = [];
  6544. node.rest = null;
  6545. node.typeParameters = null;
  6546. node.this = null;
  6547. if (this.match(47)) {
  6548. node.typeParameters = this.flowParseTypeParameterDeclaration();
  6549. }
  6550. this.expect(10);
  6551. if (this.match(78)) {
  6552. node.this = this.flowParseFunctionTypeParam(true);
  6553. node.this.name = null;
  6554. if (!this.match(11)) {
  6555. this.expect(12);
  6556. }
  6557. }
  6558. while (!this.match(11) && !this.match(21)) {
  6559. node.params.push(this.flowParseFunctionTypeParam(false));
  6560. if (!this.match(11)) {
  6561. this.expect(12);
  6562. }
  6563. }
  6564. if (this.eat(21)) {
  6565. node.rest = this.flowParseFunctionTypeParam(false);
  6566. }
  6567. this.expect(11);
  6568. node.returnType = this.flowParseTypeInitialiser();
  6569. return this.finishNode(node, "FunctionTypeAnnotation");
  6570. }
  6571. flowParseObjectTypeCallProperty(node, isStatic) {
  6572. const valueNode = this.startNode();
  6573. node.static = isStatic;
  6574. node.value = this.flowParseObjectTypeMethodish(valueNode);
  6575. return this.finishNode(node, "ObjectTypeCallProperty");
  6576. }
  6577. flowParseObjectType({
  6578. allowStatic,
  6579. allowExact,
  6580. allowSpread,
  6581. allowProto,
  6582. allowInexact
  6583. }) {
  6584. const oldInType = this.state.inType;
  6585. this.state.inType = true;
  6586. const nodeStart = this.startNode();
  6587. nodeStart.callProperties = [];
  6588. nodeStart.properties = [];
  6589. nodeStart.indexers = [];
  6590. nodeStart.internalSlots = [];
  6591. let endDelim;
  6592. let exact;
  6593. let inexact = false;
  6594. if (allowExact && this.match(6)) {
  6595. this.expect(6);
  6596. endDelim = 9;
  6597. exact = true;
  6598. } else {
  6599. this.expect(5);
  6600. endDelim = 8;
  6601. exact = false;
  6602. }
  6603. nodeStart.exact = exact;
  6604. while (!this.match(endDelim)) {
  6605. let isStatic = false;
  6606. let protoStartLoc = null;
  6607. let inexactStartLoc = null;
  6608. const node = this.startNode();
  6609. if (allowProto && this.isContextual(118)) {
  6610. const lookahead = this.lookahead();
  6611. if (lookahead.type !== 14 && lookahead.type !== 17) {
  6612. this.next();
  6613. protoStartLoc = this.state.startLoc;
  6614. allowStatic = false;
  6615. }
  6616. }
  6617. if (allowStatic && this.isContextual(106)) {
  6618. const lookahead = this.lookahead();
  6619. if (lookahead.type !== 14 && lookahead.type !== 17) {
  6620. this.next();
  6621. isStatic = true;
  6622. }
  6623. }
  6624. const variance = this.flowParseVariance();
  6625. if (this.eat(0)) {
  6626. if (protoStartLoc != null) {
  6627. this.unexpected(protoStartLoc);
  6628. }
  6629. if (this.eat(0)) {
  6630. if (variance) {
  6631. this.unexpected(variance.loc.start);
  6632. }
  6633. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  6634. } else {
  6635. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  6636. }
  6637. } else if (this.match(10) || this.match(47)) {
  6638. if (protoStartLoc != null) {
  6639. this.unexpected(protoStartLoc);
  6640. }
  6641. if (variance) {
  6642. this.unexpected(variance.loc.start);
  6643. }
  6644. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  6645. } else {
  6646. let kind = "init";
  6647. if (this.isContextual(99) || this.isContextual(104)) {
  6648. const lookahead = this.lookahead();
  6649. if (tokenIsLiteralPropertyName(lookahead.type)) {
  6650. kind = this.state.value;
  6651. this.next();
  6652. }
  6653. }
  6654. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact);
  6655. if (propOrInexact === null) {
  6656. inexact = true;
  6657. inexactStartLoc = this.state.lastTokStartLoc;
  6658. } else {
  6659. nodeStart.properties.push(propOrInexact);
  6660. }
  6661. }
  6662. this.flowObjectTypeSemicolon();
  6663. if (inexactStartLoc && !this.match(8) && !this.match(9)) {
  6664. this.raise(FlowErrors.UnexpectedExplicitInexactInObject, inexactStartLoc);
  6665. }
  6666. }
  6667. this.expect(endDelim);
  6668. if (allowSpread) {
  6669. nodeStart.inexact = inexact;
  6670. }
  6671. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  6672. this.state.inType = oldInType;
  6673. return out;
  6674. }
  6675. flowParseObjectTypeProperty(node, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact) {
  6676. if (this.eat(21)) {
  6677. const isInexactToken = this.match(12) || this.match(13) || this.match(8) || this.match(9);
  6678. if (isInexactToken) {
  6679. if (!allowSpread) {
  6680. this.raise(FlowErrors.InexactInsideNonObject, this.state.lastTokStartLoc);
  6681. } else if (!allowInexact) {
  6682. this.raise(FlowErrors.InexactInsideExact, this.state.lastTokStartLoc);
  6683. }
  6684. if (variance) {
  6685. this.raise(FlowErrors.InexactVariance, variance);
  6686. }
  6687. return null;
  6688. }
  6689. if (!allowSpread) {
  6690. this.raise(FlowErrors.UnexpectedSpreadType, this.state.lastTokStartLoc);
  6691. }
  6692. if (protoStartLoc != null) {
  6693. this.unexpected(protoStartLoc);
  6694. }
  6695. if (variance) {
  6696. this.raise(FlowErrors.SpreadVariance, variance);
  6697. }
  6698. node.argument = this.flowParseType();
  6699. return this.finishNode(node, "ObjectTypeSpreadProperty");
  6700. } else {
  6701. node.key = this.flowParseObjectPropertyKey();
  6702. node.static = isStatic;
  6703. node.proto = protoStartLoc != null;
  6704. node.kind = kind;
  6705. let optional = false;
  6706. if (this.match(47) || this.match(10)) {
  6707. node.method = true;
  6708. if (protoStartLoc != null) {
  6709. this.unexpected(protoStartLoc);
  6710. }
  6711. if (variance) {
  6712. this.unexpected(variance.loc.start);
  6713. }
  6714. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.loc.start));
  6715. if (kind === "get" || kind === "set") {
  6716. this.flowCheckGetterSetterParams(node);
  6717. }
  6718. if (!allowSpread && node.key.name === "constructor" && node.value.this) {
  6719. this.raise(FlowErrors.ThisParamBannedInConstructor, node.value.this);
  6720. }
  6721. } else {
  6722. if (kind !== "init") this.unexpected();
  6723. node.method = false;
  6724. if (this.eat(17)) {
  6725. optional = true;
  6726. }
  6727. node.value = this.flowParseTypeInitialiser();
  6728. node.variance = variance;
  6729. }
  6730. node.optional = optional;
  6731. return this.finishNode(node, "ObjectTypeProperty");
  6732. }
  6733. }
  6734. flowCheckGetterSetterParams(property) {
  6735. const paramCount = property.kind === "get" ? 0 : 1;
  6736. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  6737. if (property.value.this) {
  6738. this.raise(property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam : FlowErrors.SetterMayNotHaveThisParam, property.value.this);
  6739. }
  6740. if (length !== paramCount) {
  6741. this.raise(property.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, property);
  6742. }
  6743. if (property.kind === "set" && property.value.rest) {
  6744. this.raise(Errors.BadSetterRestParameter, property);
  6745. }
  6746. }
  6747. flowObjectTypeSemicolon() {
  6748. if (!this.eat(13) && !this.eat(12) && !this.match(8) && !this.match(9)) {
  6749. this.unexpected();
  6750. }
  6751. }
  6752. flowParseQualifiedTypeIdentifier(startLoc, id) {
  6753. startLoc != null ? startLoc : startLoc = this.state.startLoc;
  6754. let node = id || this.flowParseRestrictedIdentifier(true);
  6755. while (this.eat(16)) {
  6756. const node2 = this.startNodeAt(startLoc);
  6757. node2.qualification = node;
  6758. node2.id = this.flowParseRestrictedIdentifier(true);
  6759. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  6760. }
  6761. return node;
  6762. }
  6763. flowParseGenericType(startLoc, id) {
  6764. const node = this.startNodeAt(startLoc);
  6765. node.typeParameters = null;
  6766. node.id = this.flowParseQualifiedTypeIdentifier(startLoc, id);
  6767. if (this.match(47)) {
  6768. node.typeParameters = this.flowParseTypeParameterInstantiation();
  6769. }
  6770. return this.finishNode(node, "GenericTypeAnnotation");
  6771. }
  6772. flowParseTypeofType() {
  6773. const node = this.startNode();
  6774. this.expect(87);
  6775. node.argument = this.flowParsePrimaryType();
  6776. return this.finishNode(node, "TypeofTypeAnnotation");
  6777. }
  6778. flowParseTupleType() {
  6779. const node = this.startNode();
  6780. node.types = [];
  6781. this.expect(0);
  6782. while (this.state.pos < this.length && !this.match(3)) {
  6783. node.types.push(this.flowParseType());
  6784. if (this.match(3)) break;
  6785. this.expect(12);
  6786. }
  6787. this.expect(3);
  6788. return this.finishNode(node, "TupleTypeAnnotation");
  6789. }
  6790. flowParseFunctionTypeParam(first) {
  6791. let name = null;
  6792. let optional = false;
  6793. let typeAnnotation = null;
  6794. const node = this.startNode();
  6795. const lh = this.lookahead();
  6796. const isThis = this.state.type === 78;
  6797. if (lh.type === 14 || lh.type === 17) {
  6798. if (isThis && !first) {
  6799. this.raise(FlowErrors.ThisParamMustBeFirst, node);
  6800. }
  6801. name = this.parseIdentifier(isThis);
  6802. if (this.eat(17)) {
  6803. optional = true;
  6804. if (isThis) {
  6805. this.raise(FlowErrors.ThisParamMayNotBeOptional, node);
  6806. }
  6807. }
  6808. typeAnnotation = this.flowParseTypeInitialiser();
  6809. } else {
  6810. typeAnnotation = this.flowParseType();
  6811. }
  6812. node.name = name;
  6813. node.optional = optional;
  6814. node.typeAnnotation = typeAnnotation;
  6815. return this.finishNode(node, "FunctionTypeParam");
  6816. }
  6817. reinterpretTypeAsFunctionTypeParam(type) {
  6818. const node = this.startNodeAt(type.loc.start);
  6819. node.name = null;
  6820. node.optional = false;
  6821. node.typeAnnotation = type;
  6822. return this.finishNode(node, "FunctionTypeParam");
  6823. }
  6824. flowParseFunctionTypeParams(params = []) {
  6825. let rest = null;
  6826. let _this = null;
  6827. if (this.match(78)) {
  6828. _this = this.flowParseFunctionTypeParam(true);
  6829. _this.name = null;
  6830. if (!this.match(11)) {
  6831. this.expect(12);
  6832. }
  6833. }
  6834. while (!this.match(11) && !this.match(21)) {
  6835. params.push(this.flowParseFunctionTypeParam(false));
  6836. if (!this.match(11)) {
  6837. this.expect(12);
  6838. }
  6839. }
  6840. if (this.eat(21)) {
  6841. rest = this.flowParseFunctionTypeParam(false);
  6842. }
  6843. return {
  6844. params,
  6845. rest,
  6846. _this
  6847. };
  6848. }
  6849. flowIdentToTypeAnnotation(startLoc, node, id) {
  6850. switch (id.name) {
  6851. case "any":
  6852. return this.finishNode(node, "AnyTypeAnnotation");
  6853. case "bool":
  6854. case "boolean":
  6855. return this.finishNode(node, "BooleanTypeAnnotation");
  6856. case "mixed":
  6857. return this.finishNode(node, "MixedTypeAnnotation");
  6858. case "empty":
  6859. return this.finishNode(node, "EmptyTypeAnnotation");
  6860. case "number":
  6861. return this.finishNode(node, "NumberTypeAnnotation");
  6862. case "string":
  6863. return this.finishNode(node, "StringTypeAnnotation");
  6864. case "symbol":
  6865. return this.finishNode(node, "SymbolTypeAnnotation");
  6866. default:
  6867. this.checkNotUnderscore(id.name);
  6868. return this.flowParseGenericType(startLoc, id);
  6869. }
  6870. }
  6871. flowParsePrimaryType() {
  6872. const startLoc = this.state.startLoc;
  6873. const node = this.startNode();
  6874. let tmp;
  6875. let type;
  6876. let isGroupedType = false;
  6877. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  6878. switch (this.state.type) {
  6879. case 5:
  6880. return this.flowParseObjectType({
  6881. allowStatic: false,
  6882. allowExact: false,
  6883. allowSpread: true,
  6884. allowProto: false,
  6885. allowInexact: true
  6886. });
  6887. case 6:
  6888. return this.flowParseObjectType({
  6889. allowStatic: false,
  6890. allowExact: true,
  6891. allowSpread: true,
  6892. allowProto: false,
  6893. allowInexact: false
  6894. });
  6895. case 0:
  6896. this.state.noAnonFunctionType = false;
  6897. type = this.flowParseTupleType();
  6898. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  6899. return type;
  6900. case 47:
  6901. {
  6902. const node = this.startNode();
  6903. node.typeParameters = this.flowParseTypeParameterDeclaration();
  6904. this.expect(10);
  6905. tmp = this.flowParseFunctionTypeParams();
  6906. node.params = tmp.params;
  6907. node.rest = tmp.rest;
  6908. node.this = tmp._this;
  6909. this.expect(11);
  6910. this.expect(19);
  6911. node.returnType = this.flowParseType();
  6912. return this.finishNode(node, "FunctionTypeAnnotation");
  6913. }
  6914. case 10:
  6915. {
  6916. const node = this.startNode();
  6917. this.next();
  6918. if (!this.match(11) && !this.match(21)) {
  6919. if (tokenIsIdentifier(this.state.type) || this.match(78)) {
  6920. const token = this.lookahead().type;
  6921. isGroupedType = token !== 17 && token !== 14;
  6922. } else {
  6923. isGroupedType = true;
  6924. }
  6925. }
  6926. if (isGroupedType) {
  6927. this.state.noAnonFunctionType = false;
  6928. type = this.flowParseType();
  6929. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  6930. if (this.state.noAnonFunctionType || !(this.match(12) || this.match(11) && this.lookahead().type === 19)) {
  6931. this.expect(11);
  6932. return type;
  6933. } else {
  6934. this.eat(12);
  6935. }
  6936. }
  6937. if (type) {
  6938. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  6939. } else {
  6940. tmp = this.flowParseFunctionTypeParams();
  6941. }
  6942. node.params = tmp.params;
  6943. node.rest = tmp.rest;
  6944. node.this = tmp._this;
  6945. this.expect(11);
  6946. this.expect(19);
  6947. node.returnType = this.flowParseType();
  6948. node.typeParameters = null;
  6949. return this.finishNode(node, "FunctionTypeAnnotation");
  6950. }
  6951. case 134:
  6952. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  6953. case 85:
  6954. case 86:
  6955. node.value = this.match(85);
  6956. this.next();
  6957. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  6958. case 53:
  6959. if (this.state.value === "-") {
  6960. this.next();
  6961. if (this.match(135)) {
  6962. return this.parseLiteralAtNode(-this.state.value, "NumberLiteralTypeAnnotation", node);
  6963. }
  6964. if (this.match(136)) {
  6965. return this.parseLiteralAtNode(-this.state.value, "BigIntLiteralTypeAnnotation", node);
  6966. }
  6967. throw this.raise(FlowErrors.UnexpectedSubtractionOperand, this.state.startLoc);
  6968. }
  6969. throw this.unexpected();
  6970. case 135:
  6971. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  6972. case 136:
  6973. return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
  6974. case 88:
  6975. this.next();
  6976. return this.finishNode(node, "VoidTypeAnnotation");
  6977. case 84:
  6978. this.next();
  6979. return this.finishNode(node, "NullLiteralTypeAnnotation");
  6980. case 78:
  6981. this.next();
  6982. return this.finishNode(node, "ThisTypeAnnotation");
  6983. case 55:
  6984. this.next();
  6985. return this.finishNode(node, "ExistsTypeAnnotation");
  6986. case 87:
  6987. return this.flowParseTypeofType();
  6988. default:
  6989. if (tokenIsKeyword(this.state.type)) {
  6990. const label = tokenLabelName(this.state.type);
  6991. this.next();
  6992. return super.createIdentifier(node, label);
  6993. } else if (tokenIsIdentifier(this.state.type)) {
  6994. if (this.isContextual(129)) {
  6995. return this.flowParseInterfaceType();
  6996. }
  6997. return this.flowIdentToTypeAnnotation(startLoc, node, this.parseIdentifier());
  6998. }
  6999. }
  7000. throw this.unexpected();
  7001. }
  7002. flowParsePostfixType() {
  7003. const startLoc = this.state.startLoc;
  7004. let type = this.flowParsePrimaryType();
  7005. let seenOptionalIndexedAccess = false;
  7006. while ((this.match(0) || this.match(18)) && !this.canInsertSemicolon()) {
  7007. const node = this.startNodeAt(startLoc);
  7008. const optional = this.eat(18);
  7009. seenOptionalIndexedAccess = seenOptionalIndexedAccess || optional;
  7010. this.expect(0);
  7011. if (!optional && this.match(3)) {
  7012. node.elementType = type;
  7013. this.next();
  7014. type = this.finishNode(node, "ArrayTypeAnnotation");
  7015. } else {
  7016. node.objectType = type;
  7017. node.indexType = this.flowParseType();
  7018. this.expect(3);
  7019. if (seenOptionalIndexedAccess) {
  7020. node.optional = optional;
  7021. type = this.finishNode(node, "OptionalIndexedAccessType");
  7022. } else {
  7023. type = this.finishNode(node, "IndexedAccessType");
  7024. }
  7025. }
  7026. }
  7027. return type;
  7028. }
  7029. flowParsePrefixType() {
  7030. const node = this.startNode();
  7031. if (this.eat(17)) {
  7032. node.typeAnnotation = this.flowParsePrefixType();
  7033. return this.finishNode(node, "NullableTypeAnnotation");
  7034. } else {
  7035. return this.flowParsePostfixType();
  7036. }
  7037. }
  7038. flowParseAnonFunctionWithoutParens() {
  7039. const param = this.flowParsePrefixType();
  7040. if (!this.state.noAnonFunctionType && this.eat(19)) {
  7041. const node = this.startNodeAt(param.loc.start);
  7042. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  7043. node.rest = null;
  7044. node.this = null;
  7045. node.returnType = this.flowParseType();
  7046. node.typeParameters = null;
  7047. return this.finishNode(node, "FunctionTypeAnnotation");
  7048. }
  7049. return param;
  7050. }
  7051. flowParseIntersectionType() {
  7052. const node = this.startNode();
  7053. this.eat(45);
  7054. const type = this.flowParseAnonFunctionWithoutParens();
  7055. node.types = [type];
  7056. while (this.eat(45)) {
  7057. node.types.push(this.flowParseAnonFunctionWithoutParens());
  7058. }
  7059. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  7060. }
  7061. flowParseUnionType() {
  7062. const node = this.startNode();
  7063. this.eat(43);
  7064. const type = this.flowParseIntersectionType();
  7065. node.types = [type];
  7066. while (this.eat(43)) {
  7067. node.types.push(this.flowParseIntersectionType());
  7068. }
  7069. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  7070. }
  7071. flowParseType() {
  7072. const oldInType = this.state.inType;
  7073. this.state.inType = true;
  7074. const type = this.flowParseUnionType();
  7075. this.state.inType = oldInType;
  7076. return type;
  7077. }
  7078. flowParseTypeOrImplicitInstantiation() {
  7079. if (this.state.type === 132 && this.state.value === "_") {
  7080. const startLoc = this.state.startLoc;
  7081. const node = this.parseIdentifier();
  7082. return this.flowParseGenericType(startLoc, node);
  7083. } else {
  7084. return this.flowParseType();
  7085. }
  7086. }
  7087. flowParseTypeAnnotation() {
  7088. const node = this.startNode();
  7089. node.typeAnnotation = this.flowParseTypeInitialiser();
  7090. return this.finishNode(node, "TypeAnnotation");
  7091. }
  7092. flowParseTypeAnnotatableIdentifier() {
  7093. const node = this.startNode();
  7094. const name = this.parseIdentifierName();
  7095. if (this.match(14)) {
  7096. node.typeAnnotation = this.flowParseTypeAnnotation();
  7097. }
  7098. return this.createIdentifier(node, name);
  7099. }
  7100. typeCastToParameter(node) {
  7101. node.expression.typeAnnotation = node.typeAnnotation;
  7102. this.resetEndLocation(node.expression, node.typeAnnotation.loc.end);
  7103. return node.expression;
  7104. }
  7105. flowParseVariance() {
  7106. let variance = null;
  7107. if (this.match(53)) {
  7108. variance = this.startNode();
  7109. if (this.state.value === "+") {
  7110. variance.kind = "plus";
  7111. } else {
  7112. variance.kind = "minus";
  7113. }
  7114. this.next();
  7115. return this.finishNode(variance, "Variance");
  7116. }
  7117. return variance;
  7118. }
  7119. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  7120. if (allowExpressionBody) {
  7121. this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  7122. return;
  7123. }
  7124. super.parseFunctionBody(node, false, isMethod);
  7125. }
  7126. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  7127. if (this.match(14)) {
  7128. const typeNode = this.startNode();
  7129. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  7130. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  7131. }
  7132. return super.parseFunctionBodyAndFinish(node, type, isMethod);
  7133. }
  7134. parseStatementLike(flags) {
  7135. if (this.state.strict && this.isContextual(129)) {
  7136. const lookahead = this.lookahead();
  7137. if (tokenIsKeywordOrIdentifier(lookahead.type)) {
  7138. const node = this.startNode();
  7139. this.next();
  7140. return this.flowParseInterface(node);
  7141. }
  7142. } else if (this.isContextual(126)) {
  7143. const node = this.startNode();
  7144. this.next();
  7145. return this.flowParseEnumDeclaration(node);
  7146. }
  7147. const stmt = super.parseStatementLike(flags);
  7148. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  7149. this.flowPragma = null;
  7150. }
  7151. return stmt;
  7152. }
  7153. parseExpressionStatement(node, expr, decorators) {
  7154. if (expr.type === "Identifier") {
  7155. if (expr.name === "declare") {
  7156. if (this.match(80) || tokenIsIdentifier(this.state.type) || this.match(68) || this.match(74) || this.match(82)) {
  7157. return this.flowParseDeclare(node);
  7158. }
  7159. } else if (tokenIsIdentifier(this.state.type)) {
  7160. if (expr.name === "interface") {
  7161. return this.flowParseInterface(node);
  7162. } else if (expr.name === "type") {
  7163. return this.flowParseTypeAlias(node);
  7164. } else if (expr.name === "opaque") {
  7165. return this.flowParseOpaqueType(node, false);
  7166. }
  7167. }
  7168. }
  7169. return super.parseExpressionStatement(node, expr, decorators);
  7170. }
  7171. shouldParseExportDeclaration() {
  7172. const {
  7173. type
  7174. } = this.state;
  7175. if (type === 126 || tokenIsFlowInterfaceOrTypeOrOpaque(type)) {
  7176. return !this.state.containsEsc;
  7177. }
  7178. return super.shouldParseExportDeclaration();
  7179. }
  7180. isExportDefaultSpecifier() {
  7181. const {
  7182. type
  7183. } = this.state;
  7184. if (type === 126 || tokenIsFlowInterfaceOrTypeOrOpaque(type)) {
  7185. return this.state.containsEsc;
  7186. }
  7187. return super.isExportDefaultSpecifier();
  7188. }
  7189. parseExportDefaultExpression() {
  7190. if (this.isContextual(126)) {
  7191. const node = this.startNode();
  7192. this.next();
  7193. return this.flowParseEnumDeclaration(node);
  7194. }
  7195. return super.parseExportDefaultExpression();
  7196. }
  7197. parseConditional(expr, startLoc, refExpressionErrors) {
  7198. if (!this.match(17)) return expr;
  7199. if (this.state.maybeInArrowParameters) {
  7200. const nextCh = this.lookaheadCharCode();
  7201. if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) {
  7202. this.setOptionalParametersError(refExpressionErrors);
  7203. return expr;
  7204. }
  7205. }
  7206. this.expect(17);
  7207. const state = this.state.clone();
  7208. const originalNoArrowAt = this.state.noArrowAt;
  7209. const node = this.startNodeAt(startLoc);
  7210. let {
  7211. consequent,
  7212. failed
  7213. } = this.tryParseConditionalConsequent();
  7214. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  7215. if (failed || invalid.length > 0) {
  7216. const noArrowAt = [...originalNoArrowAt];
  7217. if (invalid.length > 0) {
  7218. this.state = state;
  7219. this.state.noArrowAt = noArrowAt;
  7220. for (let i = 0; i < invalid.length; i++) {
  7221. noArrowAt.push(invalid[i].start);
  7222. }
  7223. ({
  7224. consequent,
  7225. failed
  7226. } = this.tryParseConditionalConsequent());
  7227. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  7228. }
  7229. if (failed && valid.length > 1) {
  7230. this.raise(FlowErrors.AmbiguousConditionalArrow, state.startLoc);
  7231. }
  7232. if (failed && valid.length === 1) {
  7233. this.state = state;
  7234. noArrowAt.push(valid[0].start);
  7235. this.state.noArrowAt = noArrowAt;
  7236. ({
  7237. consequent,
  7238. failed
  7239. } = this.tryParseConditionalConsequent());
  7240. }
  7241. }
  7242. this.getArrowLikeExpressions(consequent, true);
  7243. this.state.noArrowAt = originalNoArrowAt;
  7244. this.expect(14);
  7245. node.test = expr;
  7246. node.consequent = consequent;
  7247. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined));
  7248. return this.finishNode(node, "ConditionalExpression");
  7249. }
  7250. tryParseConditionalConsequent() {
  7251. this.state.noArrowParamsConversionAt.push(this.state.start);
  7252. const consequent = this.parseMaybeAssignAllowIn();
  7253. const failed = !this.match(14);
  7254. this.state.noArrowParamsConversionAt.pop();
  7255. return {
  7256. consequent,
  7257. failed
  7258. };
  7259. }
  7260. getArrowLikeExpressions(node, disallowInvalid) {
  7261. const stack = [node];
  7262. const arrows = [];
  7263. while (stack.length !== 0) {
  7264. const node = stack.pop();
  7265. if (node.type === "ArrowFunctionExpression" && node.body.type !== "BlockStatement") {
  7266. if (node.typeParameters || !node.returnType) {
  7267. this.finishArrowValidation(node);
  7268. } else {
  7269. arrows.push(node);
  7270. }
  7271. stack.push(node.body);
  7272. } else if (node.type === "ConditionalExpression") {
  7273. stack.push(node.consequent);
  7274. stack.push(node.alternate);
  7275. }
  7276. }
  7277. if (disallowInvalid) {
  7278. arrows.forEach(node => this.finishArrowValidation(node));
  7279. return [arrows, []];
  7280. }
  7281. return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
  7282. }
  7283. finishArrowValidation(node) {
  7284. var _node$extra;
  7285. this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingCommaLoc, false);
  7286. this.scope.enter(514 | 4);
  7287. super.checkParams(node, false, true);
  7288. this.scope.exit();
  7289. }
  7290. forwardNoArrowParamsConversionAt(node, parse) {
  7291. let result;
  7292. if (this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))) {
  7293. this.state.noArrowParamsConversionAt.push(this.state.start);
  7294. result = parse();
  7295. this.state.noArrowParamsConversionAt.pop();
  7296. } else {
  7297. result = parse();
  7298. }
  7299. return result;
  7300. }
  7301. parseParenItem(node, startLoc) {
  7302. const newNode = super.parseParenItem(node, startLoc);
  7303. if (this.eat(17)) {
  7304. newNode.optional = true;
  7305. this.resetEndLocation(node);
  7306. }
  7307. if (this.match(14)) {
  7308. const typeCastNode = this.startNodeAt(startLoc);
  7309. typeCastNode.expression = newNode;
  7310. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  7311. return this.finishNode(typeCastNode, "TypeCastExpression");
  7312. }
  7313. return newNode;
  7314. }
  7315. assertModuleNodeAllowed(node) {
  7316. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  7317. return;
  7318. }
  7319. super.assertModuleNodeAllowed(node);
  7320. }
  7321. parseExportDeclaration(node) {
  7322. if (this.isContextual(130)) {
  7323. node.exportKind = "type";
  7324. const declarationNode = this.startNode();
  7325. this.next();
  7326. if (this.match(5)) {
  7327. node.specifiers = this.parseExportSpecifiers(true);
  7328. super.parseExportFrom(node);
  7329. return null;
  7330. } else {
  7331. return this.flowParseTypeAlias(declarationNode);
  7332. }
  7333. } else if (this.isContextual(131)) {
  7334. node.exportKind = "type";
  7335. const declarationNode = this.startNode();
  7336. this.next();
  7337. return this.flowParseOpaqueType(declarationNode, false);
  7338. } else if (this.isContextual(129)) {
  7339. node.exportKind = "type";
  7340. const declarationNode = this.startNode();
  7341. this.next();
  7342. return this.flowParseInterface(declarationNode);
  7343. } else if (this.isContextual(126)) {
  7344. node.exportKind = "value";
  7345. const declarationNode = this.startNode();
  7346. this.next();
  7347. return this.flowParseEnumDeclaration(declarationNode);
  7348. } else {
  7349. return super.parseExportDeclaration(node);
  7350. }
  7351. }
  7352. eatExportStar(node) {
  7353. if (super.eatExportStar(node)) return true;
  7354. if (this.isContextual(130) && this.lookahead().type === 55) {
  7355. node.exportKind = "type";
  7356. this.next();
  7357. this.next();
  7358. return true;
  7359. }
  7360. return false;
  7361. }
  7362. maybeParseExportNamespaceSpecifier(node) {
  7363. const {
  7364. startLoc
  7365. } = this.state;
  7366. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  7367. if (hasNamespace && node.exportKind === "type") {
  7368. this.unexpected(startLoc);
  7369. }
  7370. return hasNamespace;
  7371. }
  7372. parseClassId(node, isStatement, optionalId) {
  7373. super.parseClassId(node, isStatement, optionalId);
  7374. if (this.match(47)) {
  7375. node.typeParameters = this.flowParseTypeParameterDeclaration();
  7376. }
  7377. }
  7378. parseClassMember(classBody, member, state) {
  7379. const {
  7380. startLoc
  7381. } = this.state;
  7382. if (this.isContextual(125)) {
  7383. if (super.parseClassMemberFromModifier(classBody, member)) {
  7384. return;
  7385. }
  7386. member.declare = true;
  7387. }
  7388. super.parseClassMember(classBody, member, state);
  7389. if (member.declare) {
  7390. if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty" && member.type !== "PropertyDefinition") {
  7391. this.raise(FlowErrors.DeclareClassElement, startLoc);
  7392. } else if (member.value) {
  7393. this.raise(FlowErrors.DeclareClassFieldInitializer, member.value);
  7394. }
  7395. }
  7396. }
  7397. isIterator(word) {
  7398. return word === "iterator" || word === "asyncIterator";
  7399. }
  7400. readIterator() {
  7401. const word = super.readWord1();
  7402. const fullWord = "@@" + word;
  7403. if (!this.isIterator(word) || !this.state.inType) {
  7404. this.raise(Errors.InvalidIdentifier, this.state.curPosition(), {
  7405. identifierName: fullWord
  7406. });
  7407. }
  7408. this.finishToken(132, fullWord);
  7409. }
  7410. getTokenFromCode(code) {
  7411. const next = this.input.charCodeAt(this.state.pos + 1);
  7412. if (code === 123 && next === 124) {
  7413. this.finishOp(6, 2);
  7414. } else if (this.state.inType && (code === 62 || code === 60)) {
  7415. this.finishOp(code === 62 ? 48 : 47, 1);
  7416. } else if (this.state.inType && code === 63) {
  7417. if (next === 46) {
  7418. this.finishOp(18, 2);
  7419. } else {
  7420. this.finishOp(17, 1);
  7421. }
  7422. } else if (isIteratorStart(code, next, this.input.charCodeAt(this.state.pos + 2))) {
  7423. this.state.pos += 2;
  7424. this.readIterator();
  7425. } else {
  7426. super.getTokenFromCode(code);
  7427. }
  7428. }
  7429. isAssignable(node, isBinding) {
  7430. if (node.type === "TypeCastExpression") {
  7431. return this.isAssignable(node.expression, isBinding);
  7432. } else {
  7433. return super.isAssignable(node, isBinding);
  7434. }
  7435. }
  7436. toAssignable(node, isLHS = false) {
  7437. if (!isLHS && node.type === "AssignmentExpression" && node.left.type === "TypeCastExpression") {
  7438. node.left = this.typeCastToParameter(node.left);
  7439. }
  7440. super.toAssignable(node, isLHS);
  7441. }
  7442. toAssignableList(exprList, trailingCommaLoc, isLHS) {
  7443. for (let i = 0; i < exprList.length; i++) {
  7444. const expr = exprList[i];
  7445. if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") {
  7446. exprList[i] = this.typeCastToParameter(expr);
  7447. }
  7448. }
  7449. super.toAssignableList(exprList, trailingCommaLoc, isLHS);
  7450. }
  7451. toReferencedList(exprList, isParenthesizedExpr) {
  7452. for (let i = 0; i < exprList.length; i++) {
  7453. var _expr$extra;
  7454. const expr = exprList[i];
  7455. if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) != null && _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
  7456. this.raise(FlowErrors.TypeCastInPattern, expr.typeAnnotation);
  7457. }
  7458. }
  7459. return exprList;
  7460. }
  7461. parseArrayLike(close, isTuple, refExpressionErrors) {
  7462. const node = super.parseArrayLike(close, isTuple, refExpressionErrors);
  7463. if (refExpressionErrors != null && !this.state.maybeInArrowParameters) {
  7464. this.toReferencedList(node.elements);
  7465. }
  7466. return node;
  7467. }
  7468. isValidLVal(type, disallowCallExpression, isParenthesized, binding) {
  7469. return type === "TypeCastExpression" || super.isValidLVal(type, disallowCallExpression, isParenthesized, binding);
  7470. }
  7471. parseClassProperty(node) {
  7472. if (this.match(14)) {
  7473. node.typeAnnotation = this.flowParseTypeAnnotation();
  7474. }
  7475. return super.parseClassProperty(node);
  7476. }
  7477. parseClassPrivateProperty(node) {
  7478. if (this.match(14)) {
  7479. node.typeAnnotation = this.flowParseTypeAnnotation();
  7480. }
  7481. return super.parseClassPrivateProperty(node);
  7482. }
  7483. isClassMethod() {
  7484. return this.match(47) || super.isClassMethod();
  7485. }
  7486. isClassProperty() {
  7487. return this.match(14) || super.isClassProperty();
  7488. }
  7489. isNonstaticConstructor(method) {
  7490. return !this.match(14) && super.isNonstaticConstructor(method);
  7491. }
  7492. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  7493. if (method.variance) {
  7494. this.unexpected(method.variance.loc.start);
  7495. }
  7496. delete method.variance;
  7497. if (this.match(47)) {
  7498. method.typeParameters = this.flowParseTypeParameterDeclaration();
  7499. }
  7500. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  7501. if (method.params && isConstructor) {
  7502. const params = method.params;
  7503. if (params.length > 0 && this.isThisParam(params[0])) {
  7504. this.raise(FlowErrors.ThisParamBannedInConstructor, method);
  7505. }
  7506. } else if (method.type === "MethodDefinition" && isConstructor && method.value.params) {
  7507. const params = method.value.params;
  7508. if (params.length > 0 && this.isThisParam(params[0])) {
  7509. this.raise(FlowErrors.ThisParamBannedInConstructor, method);
  7510. }
  7511. }
  7512. }
  7513. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  7514. if (method.variance) {
  7515. this.unexpected(method.variance.loc.start);
  7516. }
  7517. delete method.variance;
  7518. if (this.match(47)) {
  7519. method.typeParameters = this.flowParseTypeParameterDeclaration();
  7520. }
  7521. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  7522. }
  7523. parseClassSuper(node) {
  7524. super.parseClassSuper(node);
  7525. if (node.superClass && (this.match(47) || this.match(51))) {
  7526. node.superTypeParameters = this.flowParseTypeParameterInstantiationInExpression();
  7527. }
  7528. if (this.isContextual(113)) {
  7529. this.next();
  7530. const implemented = node.implements = [];
  7531. do {
  7532. const node = this.startNode();
  7533. node.id = this.flowParseRestrictedIdentifier(true);
  7534. if (this.match(47)) {
  7535. node.typeParameters = this.flowParseTypeParameterInstantiation();
  7536. } else {
  7537. node.typeParameters = null;
  7538. }
  7539. implemented.push(this.finishNode(node, "ClassImplements"));
  7540. } while (this.eat(12));
  7541. }
  7542. }
  7543. checkGetterSetterParams(method) {
  7544. super.checkGetterSetterParams(method);
  7545. const params = this.getObjectOrClassMethodParams(method);
  7546. if (params.length > 0) {
  7547. const param = params[0];
  7548. if (this.isThisParam(param) && method.kind === "get") {
  7549. this.raise(FlowErrors.GetterMayNotHaveThisParam, param);
  7550. } else if (this.isThisParam(param)) {
  7551. this.raise(FlowErrors.SetterMayNotHaveThisParam, param);
  7552. }
  7553. }
  7554. }
  7555. parsePropertyNamePrefixOperator(node) {
  7556. node.variance = this.flowParseVariance();
  7557. }
  7558. parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  7559. if (prop.variance) {
  7560. this.unexpected(prop.variance.loc.start);
  7561. }
  7562. delete prop.variance;
  7563. let typeParameters;
  7564. if (this.match(47) && !isAccessor) {
  7565. typeParameters = this.flowParseTypeParameterDeclaration();
  7566. if (!this.match(10)) this.unexpected();
  7567. }
  7568. const result = super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  7569. if (typeParameters) {
  7570. (result.value || result).typeParameters = typeParameters;
  7571. }
  7572. return result;
  7573. }
  7574. parseFunctionParamType(param) {
  7575. if (this.eat(17)) {
  7576. if (param.type !== "Identifier") {
  7577. this.raise(FlowErrors.PatternIsOptional, param);
  7578. }
  7579. if (this.isThisParam(param)) {
  7580. this.raise(FlowErrors.ThisParamMayNotBeOptional, param);
  7581. }
  7582. param.optional = true;
  7583. }
  7584. if (this.match(14)) {
  7585. param.typeAnnotation = this.flowParseTypeAnnotation();
  7586. } else if (this.isThisParam(param)) {
  7587. this.raise(FlowErrors.ThisParamAnnotationRequired, param);
  7588. }
  7589. if (this.match(29) && this.isThisParam(param)) {
  7590. this.raise(FlowErrors.ThisParamNoDefault, param);
  7591. }
  7592. this.resetEndLocation(param);
  7593. return param;
  7594. }
  7595. parseMaybeDefault(startLoc, left) {
  7596. const node = super.parseMaybeDefault(startLoc, left);
  7597. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  7598. this.raise(FlowErrors.TypeBeforeInitializer, node.typeAnnotation);
  7599. }
  7600. return node;
  7601. }
  7602. checkImportReflection(node) {
  7603. super.checkImportReflection(node);
  7604. if (node.module && node.importKind !== "value") {
  7605. this.raise(FlowErrors.ImportReflectionHasImportType, node.specifiers[0].loc.start);
  7606. }
  7607. }
  7608. parseImportSpecifierLocal(node, specifier, type) {
  7609. specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
  7610. node.specifiers.push(this.finishImportSpecifier(specifier, type));
  7611. }
  7612. isPotentialImportPhase(isExport) {
  7613. if (super.isPotentialImportPhase(isExport)) return true;
  7614. if (this.isContextual(130)) {
  7615. if (!isExport) return true;
  7616. const ch = this.lookaheadCharCode();
  7617. return ch === 123 || ch === 42;
  7618. }
  7619. return !isExport && this.isContextual(87);
  7620. }
  7621. applyImportPhase(node, isExport, phase, loc) {
  7622. super.applyImportPhase(node, isExport, phase, loc);
  7623. if (isExport) {
  7624. if (!phase && this.match(65)) {
  7625. return;
  7626. }
  7627. node.exportKind = phase === "type" ? phase : "value";
  7628. } else {
  7629. if (phase === "type" && this.match(55)) this.unexpected();
  7630. node.importKind = phase === "type" || phase === "typeof" ? phase : "value";
  7631. }
  7632. }
  7633. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) {
  7634. const firstIdent = specifier.imported;
  7635. let specifierTypeKind = null;
  7636. if (firstIdent.type === "Identifier") {
  7637. if (firstIdent.name === "type") {
  7638. specifierTypeKind = "type";
  7639. } else if (firstIdent.name === "typeof") {
  7640. specifierTypeKind = "typeof";
  7641. }
  7642. }
  7643. let isBinding = false;
  7644. if (this.isContextual(93) && !this.isLookaheadContextual("as")) {
  7645. const as_ident = this.parseIdentifier(true);
  7646. if (specifierTypeKind !== null && !tokenIsKeywordOrIdentifier(this.state.type)) {
  7647. specifier.imported = as_ident;
  7648. specifier.importKind = specifierTypeKind;
  7649. specifier.local = this.cloneIdentifier(as_ident);
  7650. } else {
  7651. specifier.imported = firstIdent;
  7652. specifier.importKind = null;
  7653. specifier.local = this.parseIdentifier();
  7654. }
  7655. } else {
  7656. if (specifierTypeKind !== null && tokenIsKeywordOrIdentifier(this.state.type)) {
  7657. specifier.imported = this.parseIdentifier(true);
  7658. specifier.importKind = specifierTypeKind;
  7659. } else {
  7660. if (importedIsString) {
  7661. throw this.raise(Errors.ImportBindingIsString, specifier, {
  7662. importName: firstIdent.value
  7663. });
  7664. }
  7665. specifier.imported = firstIdent;
  7666. specifier.importKind = null;
  7667. }
  7668. if (this.eatContextual(93)) {
  7669. specifier.local = this.parseIdentifier();
  7670. } else {
  7671. isBinding = true;
  7672. specifier.local = this.cloneIdentifier(specifier.imported);
  7673. }
  7674. }
  7675. const specifierIsTypeImport = hasTypeImportKind(specifier);
  7676. if (isInTypeOnlyImport && specifierIsTypeImport) {
  7677. this.raise(FlowErrors.ImportTypeShorthandOnlyInPureImport, specifier);
  7678. }
  7679. if (isInTypeOnlyImport || specifierIsTypeImport) {
  7680. this.checkReservedType(specifier.local.name, specifier.local.loc.start, true);
  7681. }
  7682. if (isBinding && !isInTypeOnlyImport && !specifierIsTypeImport) {
  7683. this.checkReservedWord(specifier.local.name, specifier.loc.start, true, true);
  7684. }
  7685. return this.finishImportSpecifier(specifier, "ImportSpecifier");
  7686. }
  7687. parseBindingAtom() {
  7688. switch (this.state.type) {
  7689. case 78:
  7690. return this.parseIdentifier(true);
  7691. default:
  7692. return super.parseBindingAtom();
  7693. }
  7694. }
  7695. parseFunctionParams(node, isConstructor) {
  7696. const kind = node.kind;
  7697. if (kind !== "get" && kind !== "set" && this.match(47)) {
  7698. node.typeParameters = this.flowParseTypeParameterDeclaration();
  7699. }
  7700. super.parseFunctionParams(node, isConstructor);
  7701. }
  7702. parseVarId(decl, kind) {
  7703. super.parseVarId(decl, kind);
  7704. if (this.match(14)) {
  7705. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  7706. this.resetEndLocation(decl.id);
  7707. }
  7708. }
  7709. parseAsyncArrowFromCallExpression(node, call) {
  7710. if (this.match(14)) {
  7711. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  7712. this.state.noAnonFunctionType = true;
  7713. node.returnType = this.flowParseTypeAnnotation();
  7714. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  7715. }
  7716. return super.parseAsyncArrowFromCallExpression(node, call);
  7717. }
  7718. shouldParseAsyncArrow() {
  7719. return this.match(14) || super.shouldParseAsyncArrow();
  7720. }
  7721. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  7722. var _jsx;
  7723. let state = null;
  7724. let jsx;
  7725. if (this.hasPlugin("jsx") && (this.match(143) || this.match(47))) {
  7726. state = this.state.clone();
  7727. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  7728. if (!jsx.error) return jsx.node;
  7729. const {
  7730. context
  7731. } = this.state;
  7732. const currentContext = context[context.length - 1];
  7733. if (currentContext === types.j_oTag || currentContext === types.j_expr) {
  7734. context.pop();
  7735. }
  7736. }
  7737. if ((_jsx = jsx) != null && _jsx.error || this.match(47)) {
  7738. var _jsx2, _jsx3;
  7739. state = state || this.state.clone();
  7740. let typeParameters;
  7741. const arrow = this.tryParse(abort => {
  7742. var _arrowExpression$extr;
  7743. typeParameters = this.flowParseTypeParameterDeclaration();
  7744. const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => {
  7745. const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  7746. this.resetStartLocationFromNode(result, typeParameters);
  7747. return result;
  7748. });
  7749. if ((_arrowExpression$extr = arrowExpression.extra) != null && _arrowExpression$extr.parenthesized) abort();
  7750. const expr = this.maybeUnwrapTypeCastExpression(arrowExpression);
  7751. if (expr.type !== "ArrowFunctionExpression") abort();
  7752. expr.typeParameters = typeParameters;
  7753. this.resetStartLocationFromNode(expr, typeParameters);
  7754. return arrowExpression;
  7755. }, state);
  7756. let arrowExpression = null;
  7757. if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") {
  7758. if (!arrow.error && !arrow.aborted) {
  7759. if (arrow.node.async) {
  7760. this.raise(FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction, typeParameters);
  7761. }
  7762. return arrow.node;
  7763. }
  7764. arrowExpression = arrow.node;
  7765. }
  7766. if ((_jsx2 = jsx) != null && _jsx2.node) {
  7767. this.state = jsx.failState;
  7768. return jsx.node;
  7769. }
  7770. if (arrowExpression) {
  7771. this.state = arrow.failState;
  7772. return arrowExpression;
  7773. }
  7774. if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error;
  7775. if (arrow.thrown) throw arrow.error;
  7776. throw this.raise(FlowErrors.UnexpectedTokenAfterTypeParameter, typeParameters);
  7777. }
  7778. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  7779. }
  7780. parseArrow(node) {
  7781. if (this.match(14)) {
  7782. const result = this.tryParse(() => {
  7783. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  7784. this.state.noAnonFunctionType = true;
  7785. const typeNode = this.startNode();
  7786. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  7787. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  7788. if (this.canInsertSemicolon()) this.unexpected();
  7789. if (!this.match(19)) this.unexpected();
  7790. return typeNode;
  7791. });
  7792. if (result.thrown) return null;
  7793. if (result.error) this.state = result.failState;
  7794. node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
  7795. }
  7796. return super.parseArrow(node);
  7797. }
  7798. shouldParseArrow(params) {
  7799. return this.match(14) || super.shouldParseArrow(params);
  7800. }
  7801. setArrowFunctionParameters(node, params) {
  7802. if (this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))) {
  7803. node.params = params;
  7804. } else {
  7805. super.setArrowFunctionParameters(node, params);
  7806. }
  7807. }
  7808. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  7809. if (isArrowFunction && this.state.noArrowParamsConversionAt.includes(this.offsetToSourcePos(node.start))) {
  7810. return;
  7811. }
  7812. for (let i = 0; i < node.params.length; i++) {
  7813. if (this.isThisParam(node.params[i]) && i > 0) {
  7814. this.raise(FlowErrors.ThisParamMustBeFirst, node.params[i]);
  7815. }
  7816. }
  7817. super.checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged);
  7818. }
  7819. parseParenAndDistinguishExpression(canBeArrow) {
  7820. return super.parseParenAndDistinguishExpression(canBeArrow && !this.state.noArrowAt.includes(this.sourceToOffsetPos(this.state.start)));
  7821. }
  7822. parseSubscripts(base, startLoc, noCalls) {
  7823. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.includes(startLoc.index)) {
  7824. this.next();
  7825. const node = this.startNodeAt(startLoc);
  7826. node.callee = base;
  7827. node.arguments = super.parseCallExpressionArguments();
  7828. base = this.finishNode(node, "CallExpression");
  7829. } else if (base.type === "Identifier" && base.name === "async" && this.match(47)) {
  7830. const state = this.state.clone();
  7831. const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startLoc) || abort(), state);
  7832. if (!arrow.error && !arrow.aborted) return arrow.node;
  7833. const result = this.tryParse(() => super.parseSubscripts(base, startLoc, noCalls), state);
  7834. if (result.node && !result.error) return result.node;
  7835. if (arrow.node) {
  7836. this.state = arrow.failState;
  7837. return arrow.node;
  7838. }
  7839. if (result.node) {
  7840. this.state = result.failState;
  7841. return result.node;
  7842. }
  7843. throw arrow.error || result.error;
  7844. }
  7845. return super.parseSubscripts(base, startLoc, noCalls);
  7846. }
  7847. parseSubscript(base, startLoc, noCalls, subscriptState) {
  7848. if (this.match(18) && this.isLookaheadToken_lt()) {
  7849. subscriptState.optionalChainMember = true;
  7850. if (noCalls) {
  7851. subscriptState.stop = true;
  7852. return base;
  7853. }
  7854. this.next();
  7855. const node = this.startNodeAt(startLoc);
  7856. node.callee = base;
  7857. node.typeArguments = this.flowParseTypeParameterInstantiationInExpression();
  7858. this.expect(10);
  7859. node.arguments = this.parseCallExpressionArguments();
  7860. node.optional = true;
  7861. return this.finishCallExpression(node, true);
  7862. } else if (!noCalls && this.shouldParseTypes() && (this.match(47) || this.match(51))) {
  7863. const node = this.startNodeAt(startLoc);
  7864. node.callee = base;
  7865. const result = this.tryParse(() => {
  7866. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  7867. this.expect(10);
  7868. node.arguments = super.parseCallExpressionArguments();
  7869. if (subscriptState.optionalChainMember) {
  7870. node.optional = false;
  7871. }
  7872. return this.finishCallExpression(node, subscriptState.optionalChainMember);
  7873. });
  7874. if (result.node) {
  7875. if (result.error) this.state = result.failState;
  7876. return result.node;
  7877. }
  7878. }
  7879. return super.parseSubscript(base, startLoc, noCalls, subscriptState);
  7880. }
  7881. parseNewCallee(node) {
  7882. super.parseNewCallee(node);
  7883. let targs = null;
  7884. if (this.shouldParseTypes() && this.match(47)) {
  7885. targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
  7886. }
  7887. node.typeArguments = targs;
  7888. }
  7889. parseAsyncArrowWithTypeParameters(startLoc) {
  7890. const node = this.startNodeAt(startLoc);
  7891. this.parseFunctionParams(node, false);
  7892. if (!this.parseArrow(node)) return;
  7893. return super.parseArrowExpression(node, undefined, true);
  7894. }
  7895. readToken_mult_modulo(code) {
  7896. const next = this.input.charCodeAt(this.state.pos + 1);
  7897. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  7898. this.state.hasFlowComment = false;
  7899. this.state.pos += 2;
  7900. this.nextToken();
  7901. return;
  7902. }
  7903. super.readToken_mult_modulo(code);
  7904. }
  7905. readToken_pipe_amp(code) {
  7906. const next = this.input.charCodeAt(this.state.pos + 1);
  7907. if (code === 124 && next === 125) {
  7908. this.finishOp(9, 2);
  7909. return;
  7910. }
  7911. super.readToken_pipe_amp(code);
  7912. }
  7913. parseTopLevel(file, program) {
  7914. const fileNode = super.parseTopLevel(file, program);
  7915. if (this.state.hasFlowComment) {
  7916. this.raise(FlowErrors.UnterminatedFlowComment, this.state.curPosition());
  7917. }
  7918. return fileNode;
  7919. }
  7920. skipBlockComment() {
  7921. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  7922. if (this.state.hasFlowComment) {
  7923. throw this.raise(FlowErrors.NestedFlowComment, this.state.startLoc);
  7924. }
  7925. this.hasFlowCommentCompletion();
  7926. const commentSkip = this.skipFlowComment();
  7927. if (commentSkip) {
  7928. this.state.pos += commentSkip;
  7929. this.state.hasFlowComment = true;
  7930. }
  7931. return;
  7932. }
  7933. return super.skipBlockComment(this.state.hasFlowComment ? "*-/" : "*/");
  7934. }
  7935. skipFlowComment() {
  7936. const {
  7937. pos
  7938. } = this.state;
  7939. let shiftToFirstNonWhiteSpace = 2;
  7940. while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  7941. shiftToFirstNonWhiteSpace++;
  7942. }
  7943. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  7944. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  7945. if (ch2 === 58 && ch3 === 58) {
  7946. return shiftToFirstNonWhiteSpace + 2;
  7947. }
  7948. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  7949. return shiftToFirstNonWhiteSpace + 12;
  7950. }
  7951. if (ch2 === 58 && ch3 !== 58) {
  7952. return shiftToFirstNonWhiteSpace;
  7953. }
  7954. return false;
  7955. }
  7956. hasFlowCommentCompletion() {
  7957. const end = this.input.indexOf("*/", this.state.pos);
  7958. if (end === -1) {
  7959. throw this.raise(Errors.UnterminatedComment, this.state.curPosition());
  7960. }
  7961. }
  7962. flowEnumErrorBooleanMemberNotInitialized(loc, {
  7963. enumName,
  7964. memberName
  7965. }) {
  7966. this.raise(FlowErrors.EnumBooleanMemberNotInitialized, loc, {
  7967. memberName,
  7968. enumName
  7969. });
  7970. }
  7971. flowEnumErrorInvalidMemberInitializer(loc, enumContext) {
  7972. return this.raise(!enumContext.explicitType ? FlowErrors.EnumInvalidMemberInitializerUnknownType : enumContext.explicitType === "symbol" ? FlowErrors.EnumInvalidMemberInitializerSymbolType : FlowErrors.EnumInvalidMemberInitializerPrimaryType, loc, enumContext);
  7973. }
  7974. flowEnumErrorNumberMemberNotInitialized(loc, details) {
  7975. this.raise(FlowErrors.EnumNumberMemberNotInitialized, loc, details);
  7976. }
  7977. flowEnumErrorStringMemberInconsistentlyInitialized(node, details) {
  7978. this.raise(FlowErrors.EnumStringMemberInconsistentlyInitialized, node, details);
  7979. }
  7980. flowEnumMemberInit() {
  7981. const startLoc = this.state.startLoc;
  7982. const endOfInit = () => this.match(12) || this.match(8);
  7983. switch (this.state.type) {
  7984. case 135:
  7985. {
  7986. const literal = this.parseNumericLiteral(this.state.value);
  7987. if (endOfInit()) {
  7988. return {
  7989. type: "number",
  7990. loc: literal.loc.start,
  7991. value: literal
  7992. };
  7993. }
  7994. return {
  7995. type: "invalid",
  7996. loc: startLoc
  7997. };
  7998. }
  7999. case 134:
  8000. {
  8001. const literal = this.parseStringLiteral(this.state.value);
  8002. if (endOfInit()) {
  8003. return {
  8004. type: "string",
  8005. loc: literal.loc.start,
  8006. value: literal
  8007. };
  8008. }
  8009. return {
  8010. type: "invalid",
  8011. loc: startLoc
  8012. };
  8013. }
  8014. case 85:
  8015. case 86:
  8016. {
  8017. const literal = this.parseBooleanLiteral(this.match(85));
  8018. if (endOfInit()) {
  8019. return {
  8020. type: "boolean",
  8021. loc: literal.loc.start,
  8022. value: literal
  8023. };
  8024. }
  8025. return {
  8026. type: "invalid",
  8027. loc: startLoc
  8028. };
  8029. }
  8030. default:
  8031. return {
  8032. type: "invalid",
  8033. loc: startLoc
  8034. };
  8035. }
  8036. }
  8037. flowEnumMemberRaw() {
  8038. const loc = this.state.startLoc;
  8039. const id = this.parseIdentifier(true);
  8040. const init = this.eat(29) ? this.flowEnumMemberInit() : {
  8041. type: "none",
  8042. loc
  8043. };
  8044. return {
  8045. id,
  8046. init
  8047. };
  8048. }
  8049. flowEnumCheckExplicitTypeMismatch(loc, context, expectedType) {
  8050. const {
  8051. explicitType
  8052. } = context;
  8053. if (explicitType === null) {
  8054. return;
  8055. }
  8056. if (explicitType !== expectedType) {
  8057. this.flowEnumErrorInvalidMemberInitializer(loc, context);
  8058. }
  8059. }
  8060. flowEnumMembers({
  8061. enumName,
  8062. explicitType
  8063. }) {
  8064. const seenNames = new Set();
  8065. const members = {
  8066. booleanMembers: [],
  8067. numberMembers: [],
  8068. stringMembers: [],
  8069. defaultedMembers: []
  8070. };
  8071. let hasUnknownMembers = false;
  8072. while (!this.match(8)) {
  8073. if (this.eat(21)) {
  8074. hasUnknownMembers = true;
  8075. break;
  8076. }
  8077. const memberNode = this.startNode();
  8078. const {
  8079. id,
  8080. init
  8081. } = this.flowEnumMemberRaw();
  8082. const memberName = id.name;
  8083. if (memberName === "") {
  8084. continue;
  8085. }
  8086. if (/^[a-z]/.test(memberName)) {
  8087. this.raise(FlowErrors.EnumInvalidMemberName, id, {
  8088. memberName,
  8089. suggestion: memberName[0].toUpperCase() + memberName.slice(1),
  8090. enumName
  8091. });
  8092. }
  8093. if (seenNames.has(memberName)) {
  8094. this.raise(FlowErrors.EnumDuplicateMemberName, id, {
  8095. memberName,
  8096. enumName
  8097. });
  8098. }
  8099. seenNames.add(memberName);
  8100. const context = {
  8101. enumName,
  8102. explicitType,
  8103. memberName
  8104. };
  8105. memberNode.id = id;
  8106. switch (init.type) {
  8107. case "boolean":
  8108. {
  8109. this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "boolean");
  8110. memberNode.init = init.value;
  8111. members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
  8112. break;
  8113. }
  8114. case "number":
  8115. {
  8116. this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "number");
  8117. memberNode.init = init.value;
  8118. members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
  8119. break;
  8120. }
  8121. case "string":
  8122. {
  8123. this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "string");
  8124. memberNode.init = init.value;
  8125. members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
  8126. break;
  8127. }
  8128. case "invalid":
  8129. {
  8130. throw this.flowEnumErrorInvalidMemberInitializer(init.loc, context);
  8131. }
  8132. case "none":
  8133. {
  8134. switch (explicitType) {
  8135. case "boolean":
  8136. this.flowEnumErrorBooleanMemberNotInitialized(init.loc, context);
  8137. break;
  8138. case "number":
  8139. this.flowEnumErrorNumberMemberNotInitialized(init.loc, context);
  8140. break;
  8141. default:
  8142. members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
  8143. }
  8144. }
  8145. }
  8146. if (!this.match(8)) {
  8147. this.expect(12);
  8148. }
  8149. }
  8150. return {
  8151. members,
  8152. hasUnknownMembers
  8153. };
  8154. }
  8155. flowEnumStringMembers(initializedMembers, defaultedMembers, {
  8156. enumName
  8157. }) {
  8158. if (initializedMembers.length === 0) {
  8159. return defaultedMembers;
  8160. } else if (defaultedMembers.length === 0) {
  8161. return initializedMembers;
  8162. } else if (defaultedMembers.length > initializedMembers.length) {
  8163. for (const member of initializedMembers) {
  8164. this.flowEnumErrorStringMemberInconsistentlyInitialized(member, {
  8165. enumName
  8166. });
  8167. }
  8168. return defaultedMembers;
  8169. } else {
  8170. for (const member of defaultedMembers) {
  8171. this.flowEnumErrorStringMemberInconsistentlyInitialized(member, {
  8172. enumName
  8173. });
  8174. }
  8175. return initializedMembers;
  8176. }
  8177. }
  8178. flowEnumParseExplicitType({
  8179. enumName
  8180. }) {
  8181. if (!this.eatContextual(102)) return null;
  8182. if (!tokenIsIdentifier(this.state.type)) {
  8183. throw this.raise(FlowErrors.EnumInvalidExplicitTypeUnknownSupplied, this.state.startLoc, {
  8184. enumName
  8185. });
  8186. }
  8187. const {
  8188. value
  8189. } = this.state;
  8190. this.next();
  8191. if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
  8192. this.raise(FlowErrors.EnumInvalidExplicitType, this.state.startLoc, {
  8193. enumName,
  8194. invalidEnumType: value
  8195. });
  8196. }
  8197. return value;
  8198. }
  8199. flowEnumBody(node, id) {
  8200. const enumName = id.name;
  8201. const nameLoc = id.loc.start;
  8202. const explicitType = this.flowEnumParseExplicitType({
  8203. enumName
  8204. });
  8205. this.expect(5);
  8206. const {
  8207. members,
  8208. hasUnknownMembers
  8209. } = this.flowEnumMembers({
  8210. enumName,
  8211. explicitType
  8212. });
  8213. node.hasUnknownMembers = hasUnknownMembers;
  8214. switch (explicitType) {
  8215. case "boolean":
  8216. node.explicitType = true;
  8217. node.members = members.booleanMembers;
  8218. this.expect(8);
  8219. return this.finishNode(node, "EnumBooleanBody");
  8220. case "number":
  8221. node.explicitType = true;
  8222. node.members = members.numberMembers;
  8223. this.expect(8);
  8224. return this.finishNode(node, "EnumNumberBody");
  8225. case "string":
  8226. node.explicitType = true;
  8227. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  8228. enumName
  8229. });
  8230. this.expect(8);
  8231. return this.finishNode(node, "EnumStringBody");
  8232. case "symbol":
  8233. node.members = members.defaultedMembers;
  8234. this.expect(8);
  8235. return this.finishNode(node, "EnumSymbolBody");
  8236. default:
  8237. {
  8238. const empty = () => {
  8239. node.members = [];
  8240. this.expect(8);
  8241. return this.finishNode(node, "EnumStringBody");
  8242. };
  8243. node.explicitType = false;
  8244. const boolsLen = members.booleanMembers.length;
  8245. const numsLen = members.numberMembers.length;
  8246. const strsLen = members.stringMembers.length;
  8247. const defaultedLen = members.defaultedMembers.length;
  8248. if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
  8249. return empty();
  8250. } else if (!boolsLen && !numsLen) {
  8251. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  8252. enumName
  8253. });
  8254. this.expect(8);
  8255. return this.finishNode(node, "EnumStringBody");
  8256. } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
  8257. for (const member of members.defaultedMembers) {
  8258. this.flowEnumErrorBooleanMemberNotInitialized(member.loc.start, {
  8259. enumName,
  8260. memberName: member.id.name
  8261. });
  8262. }
  8263. node.members = members.booleanMembers;
  8264. this.expect(8);
  8265. return this.finishNode(node, "EnumBooleanBody");
  8266. } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
  8267. for (const member of members.defaultedMembers) {
  8268. this.flowEnumErrorNumberMemberNotInitialized(member.loc.start, {
  8269. enumName,
  8270. memberName: member.id.name
  8271. });
  8272. }
  8273. node.members = members.numberMembers;
  8274. this.expect(8);
  8275. return this.finishNode(node, "EnumNumberBody");
  8276. } else {
  8277. this.raise(FlowErrors.EnumInconsistentMemberValues, nameLoc, {
  8278. enumName
  8279. });
  8280. return empty();
  8281. }
  8282. }
  8283. }
  8284. }
  8285. flowParseEnumDeclaration(node) {
  8286. const id = this.parseIdentifier();
  8287. node.id = id;
  8288. node.body = this.flowEnumBody(this.startNode(), id);
  8289. return this.finishNode(node, "EnumDeclaration");
  8290. }
  8291. jsxParseOpeningElementAfterName(node) {
  8292. if (this.shouldParseTypes()) {
  8293. if (this.match(47) || this.match(51)) {
  8294. node.typeArguments = this.flowParseTypeParameterInstantiationInExpression();
  8295. }
  8296. }
  8297. return super.jsxParseOpeningElementAfterName(node);
  8298. }
  8299. isLookaheadToken_lt() {
  8300. const next = this.nextTokenStart();
  8301. if (this.input.charCodeAt(next) === 60) {
  8302. const afterNext = this.input.charCodeAt(next + 1);
  8303. return afterNext !== 60 && afterNext !== 61;
  8304. }
  8305. return false;
  8306. }
  8307. reScan_lt_gt() {
  8308. const {
  8309. type
  8310. } = this.state;
  8311. if (type === 47) {
  8312. this.state.pos -= 1;
  8313. this.readToken_lt();
  8314. } else if (type === 48) {
  8315. this.state.pos -= 1;
  8316. this.readToken_gt();
  8317. }
  8318. }
  8319. reScan_lt() {
  8320. const {
  8321. type
  8322. } = this.state;
  8323. if (type === 51) {
  8324. this.state.pos -= 2;
  8325. this.finishOp(47, 1);
  8326. return 47;
  8327. }
  8328. return type;
  8329. }
  8330. maybeUnwrapTypeCastExpression(node) {
  8331. return node.type === "TypeCastExpression" ? node.expression : node;
  8332. }
  8333. };
  8334. const entities = {
  8335. __proto__: null,
  8336. quot: "\u0022",
  8337. amp: "&",
  8338. apos: "\u0027",
  8339. lt: "<",
  8340. gt: ">",
  8341. nbsp: "\u00A0",
  8342. iexcl: "\u00A1",
  8343. cent: "\u00A2",
  8344. pound: "\u00A3",
  8345. curren: "\u00A4",
  8346. yen: "\u00A5",
  8347. brvbar: "\u00A6",
  8348. sect: "\u00A7",
  8349. uml: "\u00A8",
  8350. copy: "\u00A9",
  8351. ordf: "\u00AA",
  8352. laquo: "\u00AB",
  8353. not: "\u00AC",
  8354. shy: "\u00AD",
  8355. reg: "\u00AE",
  8356. macr: "\u00AF",
  8357. deg: "\u00B0",
  8358. plusmn: "\u00B1",
  8359. sup2: "\u00B2",
  8360. sup3: "\u00B3",
  8361. acute: "\u00B4",
  8362. micro: "\u00B5",
  8363. para: "\u00B6",
  8364. middot: "\u00B7",
  8365. cedil: "\u00B8",
  8366. sup1: "\u00B9",
  8367. ordm: "\u00BA",
  8368. raquo: "\u00BB",
  8369. frac14: "\u00BC",
  8370. frac12: "\u00BD",
  8371. frac34: "\u00BE",
  8372. iquest: "\u00BF",
  8373. Agrave: "\u00C0",
  8374. Aacute: "\u00C1",
  8375. Acirc: "\u00C2",
  8376. Atilde: "\u00C3",
  8377. Auml: "\u00C4",
  8378. Aring: "\u00C5",
  8379. AElig: "\u00C6",
  8380. Ccedil: "\u00C7",
  8381. Egrave: "\u00C8",
  8382. Eacute: "\u00C9",
  8383. Ecirc: "\u00CA",
  8384. Euml: "\u00CB",
  8385. Igrave: "\u00CC",
  8386. Iacute: "\u00CD",
  8387. Icirc: "\u00CE",
  8388. Iuml: "\u00CF",
  8389. ETH: "\u00D0",
  8390. Ntilde: "\u00D1",
  8391. Ograve: "\u00D2",
  8392. Oacute: "\u00D3",
  8393. Ocirc: "\u00D4",
  8394. Otilde: "\u00D5",
  8395. Ouml: "\u00D6",
  8396. times: "\u00D7",
  8397. Oslash: "\u00D8",
  8398. Ugrave: "\u00D9",
  8399. Uacute: "\u00DA",
  8400. Ucirc: "\u00DB",
  8401. Uuml: "\u00DC",
  8402. Yacute: "\u00DD",
  8403. THORN: "\u00DE",
  8404. szlig: "\u00DF",
  8405. agrave: "\u00E0",
  8406. aacute: "\u00E1",
  8407. acirc: "\u00E2",
  8408. atilde: "\u00E3",
  8409. auml: "\u00E4",
  8410. aring: "\u00E5",
  8411. aelig: "\u00E6",
  8412. ccedil: "\u00E7",
  8413. egrave: "\u00E8",
  8414. eacute: "\u00E9",
  8415. ecirc: "\u00EA",
  8416. euml: "\u00EB",
  8417. igrave: "\u00EC",
  8418. iacute: "\u00ED",
  8419. icirc: "\u00EE",
  8420. iuml: "\u00EF",
  8421. eth: "\u00F0",
  8422. ntilde: "\u00F1",
  8423. ograve: "\u00F2",
  8424. oacute: "\u00F3",
  8425. ocirc: "\u00F4",
  8426. otilde: "\u00F5",
  8427. ouml: "\u00F6",
  8428. divide: "\u00F7",
  8429. oslash: "\u00F8",
  8430. ugrave: "\u00F9",
  8431. uacute: "\u00FA",
  8432. ucirc: "\u00FB",
  8433. uuml: "\u00FC",
  8434. yacute: "\u00FD",
  8435. thorn: "\u00FE",
  8436. yuml: "\u00FF",
  8437. OElig: "\u0152",
  8438. oelig: "\u0153",
  8439. Scaron: "\u0160",
  8440. scaron: "\u0161",
  8441. Yuml: "\u0178",
  8442. fnof: "\u0192",
  8443. circ: "\u02C6",
  8444. tilde: "\u02DC",
  8445. Alpha: "\u0391",
  8446. Beta: "\u0392",
  8447. Gamma: "\u0393",
  8448. Delta: "\u0394",
  8449. Epsilon: "\u0395",
  8450. Zeta: "\u0396",
  8451. Eta: "\u0397",
  8452. Theta: "\u0398",
  8453. Iota: "\u0399",
  8454. Kappa: "\u039A",
  8455. Lambda: "\u039B",
  8456. Mu: "\u039C",
  8457. Nu: "\u039D",
  8458. Xi: "\u039E",
  8459. Omicron: "\u039F",
  8460. Pi: "\u03A0",
  8461. Rho: "\u03A1",
  8462. Sigma: "\u03A3",
  8463. Tau: "\u03A4",
  8464. Upsilon: "\u03A5",
  8465. Phi: "\u03A6",
  8466. Chi: "\u03A7",
  8467. Psi: "\u03A8",
  8468. Omega: "\u03A9",
  8469. alpha: "\u03B1",
  8470. beta: "\u03B2",
  8471. gamma: "\u03B3",
  8472. delta: "\u03B4",
  8473. epsilon: "\u03B5",
  8474. zeta: "\u03B6",
  8475. eta: "\u03B7",
  8476. theta: "\u03B8",
  8477. iota: "\u03B9",
  8478. kappa: "\u03BA",
  8479. lambda: "\u03BB",
  8480. mu: "\u03BC",
  8481. nu: "\u03BD",
  8482. xi: "\u03BE",
  8483. omicron: "\u03BF",
  8484. pi: "\u03C0",
  8485. rho: "\u03C1",
  8486. sigmaf: "\u03C2",
  8487. sigma: "\u03C3",
  8488. tau: "\u03C4",
  8489. upsilon: "\u03C5",
  8490. phi: "\u03C6",
  8491. chi: "\u03C7",
  8492. psi: "\u03C8",
  8493. omega: "\u03C9",
  8494. thetasym: "\u03D1",
  8495. upsih: "\u03D2",
  8496. piv: "\u03D6",
  8497. ensp: "\u2002",
  8498. emsp: "\u2003",
  8499. thinsp: "\u2009",
  8500. zwnj: "\u200C",
  8501. zwj: "\u200D",
  8502. lrm: "\u200E",
  8503. rlm: "\u200F",
  8504. ndash: "\u2013",
  8505. mdash: "\u2014",
  8506. lsquo: "\u2018",
  8507. rsquo: "\u2019",
  8508. sbquo: "\u201A",
  8509. ldquo: "\u201C",
  8510. rdquo: "\u201D",
  8511. bdquo: "\u201E",
  8512. dagger: "\u2020",
  8513. Dagger: "\u2021",
  8514. bull: "\u2022",
  8515. hellip: "\u2026",
  8516. permil: "\u2030",
  8517. prime: "\u2032",
  8518. Prime: "\u2033",
  8519. lsaquo: "\u2039",
  8520. rsaquo: "\u203A",
  8521. oline: "\u203E",
  8522. frasl: "\u2044",
  8523. euro: "\u20AC",
  8524. image: "\u2111",
  8525. weierp: "\u2118",
  8526. real: "\u211C",
  8527. trade: "\u2122",
  8528. alefsym: "\u2135",
  8529. larr: "\u2190",
  8530. uarr: "\u2191",
  8531. rarr: "\u2192",
  8532. darr: "\u2193",
  8533. harr: "\u2194",
  8534. crarr: "\u21B5",
  8535. lArr: "\u21D0",
  8536. uArr: "\u21D1",
  8537. rArr: "\u21D2",
  8538. dArr: "\u21D3",
  8539. hArr: "\u21D4",
  8540. forall: "\u2200",
  8541. part: "\u2202",
  8542. exist: "\u2203",
  8543. empty: "\u2205",
  8544. nabla: "\u2207",
  8545. isin: "\u2208",
  8546. notin: "\u2209",
  8547. ni: "\u220B",
  8548. prod: "\u220F",
  8549. sum: "\u2211",
  8550. minus: "\u2212",
  8551. lowast: "\u2217",
  8552. radic: "\u221A",
  8553. prop: "\u221D",
  8554. infin: "\u221E",
  8555. ang: "\u2220",
  8556. and: "\u2227",
  8557. or: "\u2228",
  8558. cap: "\u2229",
  8559. cup: "\u222A",
  8560. int: "\u222B",
  8561. there4: "\u2234",
  8562. sim: "\u223C",
  8563. cong: "\u2245",
  8564. asymp: "\u2248",
  8565. ne: "\u2260",
  8566. equiv: "\u2261",
  8567. le: "\u2264",
  8568. ge: "\u2265",
  8569. sub: "\u2282",
  8570. sup: "\u2283",
  8571. nsub: "\u2284",
  8572. sube: "\u2286",
  8573. supe: "\u2287",
  8574. oplus: "\u2295",
  8575. otimes: "\u2297",
  8576. perp: "\u22A5",
  8577. sdot: "\u22C5",
  8578. lceil: "\u2308",
  8579. rceil: "\u2309",
  8580. lfloor: "\u230A",
  8581. rfloor: "\u230B",
  8582. lang: "\u2329",
  8583. rang: "\u232A",
  8584. loz: "\u25CA",
  8585. spades: "\u2660",
  8586. clubs: "\u2663",
  8587. hearts: "\u2665",
  8588. diams: "\u2666"
  8589. };
  8590. const lineBreak = /\r\n|[\r\n\u2028\u2029]/;
  8591. const lineBreakG = new RegExp(lineBreak.source, "g");
  8592. function isNewLine(code) {
  8593. switch (code) {
  8594. case 10:
  8595. case 13:
  8596. case 8232:
  8597. case 8233:
  8598. return true;
  8599. default:
  8600. return false;
  8601. }
  8602. }
  8603. function hasNewLine(input, start, end) {
  8604. for (let i = start; i < end; i++) {
  8605. if (isNewLine(input.charCodeAt(i))) {
  8606. return true;
  8607. }
  8608. }
  8609. return false;
  8610. }
  8611. const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  8612. const skipWhiteSpaceInLine = /(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/g;
  8613. function isWhitespace(code) {
  8614. switch (code) {
  8615. case 0x0009:
  8616. case 0x000b:
  8617. case 0x000c:
  8618. case 32:
  8619. case 160:
  8620. case 5760:
  8621. case 0x2000:
  8622. case 0x2001:
  8623. case 0x2002:
  8624. case 0x2003:
  8625. case 0x2004:
  8626. case 0x2005:
  8627. case 0x2006:
  8628. case 0x2007:
  8629. case 0x2008:
  8630. case 0x2009:
  8631. case 0x200a:
  8632. case 0x202f:
  8633. case 0x205f:
  8634. case 0x3000:
  8635. case 0xfeff:
  8636. return true;
  8637. default:
  8638. return false;
  8639. }
  8640. }
  8641. const JsxErrors = ParseErrorEnum`jsx`({
  8642. AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression.",
  8643. MissingClosingTagElement: ({
  8644. openingTagName
  8645. }) => `Expected corresponding JSX closing tag for <${openingTagName}>.`,
  8646. MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>.",
  8647. UnexpectedSequenceExpression: "Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",
  8648. UnexpectedToken: ({
  8649. unexpected,
  8650. HTMLEntity
  8651. }) => `Unexpected token \`${unexpected}\`. Did you mean \`${HTMLEntity}\` or \`{'${unexpected}'}\`?`,
  8652. UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text.",
  8653. UnterminatedJsxContent: "Unterminated JSX contents.",
  8654. UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"
  8655. });
  8656. function isFragment(object) {
  8657. return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
  8658. }
  8659. function getQualifiedJSXName(object) {
  8660. if (object.type === "JSXIdentifier") {
  8661. return object.name;
  8662. }
  8663. if (object.type === "JSXNamespacedName") {
  8664. return object.namespace.name + ":" + object.name.name;
  8665. }
  8666. if (object.type === "JSXMemberExpression") {
  8667. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  8668. }
  8669. throw new Error("Node had unexpected type: " + object.type);
  8670. }
  8671. var jsx = superClass => class JSXParserMixin extends superClass {
  8672. jsxReadToken() {
  8673. let out = "";
  8674. let chunkStart = this.state.pos;
  8675. for (;;) {
  8676. if (this.state.pos >= this.length) {
  8677. throw this.raise(JsxErrors.UnterminatedJsxContent, this.state.startLoc);
  8678. }
  8679. const ch = this.input.charCodeAt(this.state.pos);
  8680. switch (ch) {
  8681. case 60:
  8682. case 123:
  8683. if (this.state.pos === this.state.start) {
  8684. if (ch === 60 && this.state.canStartJSXElement) {
  8685. ++this.state.pos;
  8686. this.finishToken(143);
  8687. } else {
  8688. super.getTokenFromCode(ch);
  8689. }
  8690. return;
  8691. }
  8692. out += this.input.slice(chunkStart, this.state.pos);
  8693. this.finishToken(142, out);
  8694. return;
  8695. case 38:
  8696. out += this.input.slice(chunkStart, this.state.pos);
  8697. out += this.jsxReadEntity();
  8698. chunkStart = this.state.pos;
  8699. break;
  8700. case 62:
  8701. case 125:
  8702. default:
  8703. if (isNewLine(ch)) {
  8704. out += this.input.slice(chunkStart, this.state.pos);
  8705. out += this.jsxReadNewLine(true);
  8706. chunkStart = this.state.pos;
  8707. } else {
  8708. ++this.state.pos;
  8709. }
  8710. }
  8711. }
  8712. }
  8713. jsxReadNewLine(normalizeCRLF) {
  8714. const ch = this.input.charCodeAt(this.state.pos);
  8715. let out;
  8716. ++this.state.pos;
  8717. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  8718. ++this.state.pos;
  8719. out = normalizeCRLF ? "\n" : "\r\n";
  8720. } else {
  8721. out = String.fromCharCode(ch);
  8722. }
  8723. ++this.state.curLine;
  8724. this.state.lineStart = this.state.pos;
  8725. return out;
  8726. }
  8727. jsxReadString(quote) {
  8728. let out = "";
  8729. let chunkStart = ++this.state.pos;
  8730. for (;;) {
  8731. if (this.state.pos >= this.length) {
  8732. throw this.raise(Errors.UnterminatedString, this.state.startLoc);
  8733. }
  8734. const ch = this.input.charCodeAt(this.state.pos);
  8735. if (ch === quote) break;
  8736. if (ch === 38) {
  8737. out += this.input.slice(chunkStart, this.state.pos);
  8738. out += this.jsxReadEntity();
  8739. chunkStart = this.state.pos;
  8740. } else if (isNewLine(ch)) {
  8741. out += this.input.slice(chunkStart, this.state.pos);
  8742. out += this.jsxReadNewLine(false);
  8743. chunkStart = this.state.pos;
  8744. } else {
  8745. ++this.state.pos;
  8746. }
  8747. }
  8748. out += this.input.slice(chunkStart, this.state.pos++);
  8749. this.finishToken(134, out);
  8750. }
  8751. jsxReadEntity() {
  8752. const startPos = ++this.state.pos;
  8753. if (this.codePointAtPos(this.state.pos) === 35) {
  8754. ++this.state.pos;
  8755. let radix = 10;
  8756. if (this.codePointAtPos(this.state.pos) === 120) {
  8757. radix = 16;
  8758. ++this.state.pos;
  8759. }
  8760. const codePoint = this.readInt(radix, undefined, false, "bail");
  8761. if (codePoint !== null && this.codePointAtPos(this.state.pos) === 59) {
  8762. ++this.state.pos;
  8763. return String.fromCodePoint(codePoint);
  8764. }
  8765. } else {
  8766. let count = 0;
  8767. let semi = false;
  8768. while (count++ < 10 && this.state.pos < this.length && !(semi = this.codePointAtPos(this.state.pos) === 59)) {
  8769. ++this.state.pos;
  8770. }
  8771. if (semi) {
  8772. const desc = this.input.slice(startPos, this.state.pos);
  8773. const entity = entities[desc];
  8774. ++this.state.pos;
  8775. if (entity) {
  8776. return entity;
  8777. }
  8778. }
  8779. }
  8780. this.state.pos = startPos;
  8781. return "&";
  8782. }
  8783. jsxReadWord() {
  8784. let ch;
  8785. const start = this.state.pos;
  8786. do {
  8787. ch = this.input.charCodeAt(++this.state.pos);
  8788. } while (isIdentifierChar(ch) || ch === 45);
  8789. this.finishToken(141, this.input.slice(start, this.state.pos));
  8790. }
  8791. jsxParseIdentifier() {
  8792. const node = this.startNode();
  8793. if (this.match(141)) {
  8794. node.name = this.state.value;
  8795. } else if (tokenIsKeyword(this.state.type)) {
  8796. node.name = tokenLabelName(this.state.type);
  8797. } else {
  8798. this.unexpected();
  8799. }
  8800. this.next();
  8801. return this.finishNode(node, "JSXIdentifier");
  8802. }
  8803. jsxParseNamespacedName() {
  8804. const startLoc = this.state.startLoc;
  8805. const name = this.jsxParseIdentifier();
  8806. if (!this.eat(14)) return name;
  8807. const node = this.startNodeAt(startLoc);
  8808. node.namespace = name;
  8809. node.name = this.jsxParseIdentifier();
  8810. return this.finishNode(node, "JSXNamespacedName");
  8811. }
  8812. jsxParseElementName() {
  8813. const startLoc = this.state.startLoc;
  8814. let node = this.jsxParseNamespacedName();
  8815. if (node.type === "JSXNamespacedName") {
  8816. return node;
  8817. }
  8818. while (this.eat(16)) {
  8819. const newNode = this.startNodeAt(startLoc);
  8820. newNode.object = node;
  8821. newNode.property = this.jsxParseIdentifier();
  8822. node = this.finishNode(newNode, "JSXMemberExpression");
  8823. }
  8824. return node;
  8825. }
  8826. jsxParseAttributeValue() {
  8827. let node;
  8828. switch (this.state.type) {
  8829. case 5:
  8830. node = this.startNode();
  8831. this.setContext(types.brace);
  8832. this.next();
  8833. node = this.jsxParseExpressionContainer(node, types.j_oTag);
  8834. if (node.expression.type === "JSXEmptyExpression") {
  8835. this.raise(JsxErrors.AttributeIsEmpty, node);
  8836. }
  8837. return node;
  8838. case 143:
  8839. case 134:
  8840. return this.parseExprAtom();
  8841. default:
  8842. throw this.raise(JsxErrors.UnsupportedJsxValue, this.state.startLoc);
  8843. }
  8844. }
  8845. jsxParseEmptyExpression() {
  8846. const node = this.startNodeAt(this.state.lastTokEndLoc);
  8847. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.startLoc);
  8848. }
  8849. jsxParseSpreadChild(node) {
  8850. this.next();
  8851. node.expression = this.parseExpression();
  8852. this.setContext(types.j_expr);
  8853. this.state.canStartJSXElement = true;
  8854. this.expect(8);
  8855. return this.finishNode(node, "JSXSpreadChild");
  8856. }
  8857. jsxParseExpressionContainer(node, previousContext) {
  8858. if (this.match(8)) {
  8859. node.expression = this.jsxParseEmptyExpression();
  8860. } else {
  8861. const expression = this.parseExpression();
  8862. node.expression = expression;
  8863. }
  8864. this.setContext(previousContext);
  8865. this.state.canStartJSXElement = true;
  8866. this.expect(8);
  8867. return this.finishNode(node, "JSXExpressionContainer");
  8868. }
  8869. jsxParseAttribute() {
  8870. const node = this.startNode();
  8871. if (this.match(5)) {
  8872. this.setContext(types.brace);
  8873. this.next();
  8874. this.expect(21);
  8875. node.argument = this.parseMaybeAssignAllowIn();
  8876. this.setContext(types.j_oTag);
  8877. this.state.canStartJSXElement = true;
  8878. this.expect(8);
  8879. return this.finishNode(node, "JSXSpreadAttribute");
  8880. }
  8881. node.name = this.jsxParseNamespacedName();
  8882. node.value = this.eat(29) ? this.jsxParseAttributeValue() : null;
  8883. return this.finishNode(node, "JSXAttribute");
  8884. }
  8885. jsxParseOpeningElementAt(startLoc) {
  8886. const node = this.startNodeAt(startLoc);
  8887. if (this.eat(144)) {
  8888. return this.finishNode(node, "JSXOpeningFragment");
  8889. }
  8890. node.name = this.jsxParseElementName();
  8891. return this.jsxParseOpeningElementAfterName(node);
  8892. }
  8893. jsxParseOpeningElementAfterName(node) {
  8894. const attributes = [];
  8895. while (!this.match(56) && !this.match(144)) {
  8896. attributes.push(this.jsxParseAttribute());
  8897. }
  8898. node.attributes = attributes;
  8899. node.selfClosing = this.eat(56);
  8900. this.expect(144);
  8901. return this.finishNode(node, "JSXOpeningElement");
  8902. }
  8903. jsxParseClosingElementAt(startLoc) {
  8904. const node = this.startNodeAt(startLoc);
  8905. if (this.eat(144)) {
  8906. return this.finishNode(node, "JSXClosingFragment");
  8907. }
  8908. node.name = this.jsxParseElementName();
  8909. this.expect(144);
  8910. return this.finishNode(node, "JSXClosingElement");
  8911. }
  8912. jsxParseElementAt(startLoc) {
  8913. const node = this.startNodeAt(startLoc);
  8914. const children = [];
  8915. const openingElement = this.jsxParseOpeningElementAt(startLoc);
  8916. let closingElement = null;
  8917. if (!openingElement.selfClosing) {
  8918. contents: for (;;) {
  8919. switch (this.state.type) {
  8920. case 143:
  8921. startLoc = this.state.startLoc;
  8922. this.next();
  8923. if (this.eat(56)) {
  8924. closingElement = this.jsxParseClosingElementAt(startLoc);
  8925. break contents;
  8926. }
  8927. children.push(this.jsxParseElementAt(startLoc));
  8928. break;
  8929. case 142:
  8930. children.push(this.parseLiteral(this.state.value, "JSXText"));
  8931. break;
  8932. case 5:
  8933. {
  8934. const node = this.startNode();
  8935. this.setContext(types.brace);
  8936. this.next();
  8937. if (this.match(21)) {
  8938. children.push(this.jsxParseSpreadChild(node));
  8939. } else {
  8940. children.push(this.jsxParseExpressionContainer(node, types.j_expr));
  8941. }
  8942. break;
  8943. }
  8944. default:
  8945. this.unexpected();
  8946. }
  8947. }
  8948. if (isFragment(openingElement) && !isFragment(closingElement) && closingElement !== null) {
  8949. this.raise(JsxErrors.MissingClosingTagFragment, closingElement);
  8950. } else if (!isFragment(openingElement) && isFragment(closingElement)) {
  8951. this.raise(JsxErrors.MissingClosingTagElement, closingElement, {
  8952. openingTagName: getQualifiedJSXName(openingElement.name)
  8953. });
  8954. } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
  8955. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  8956. this.raise(JsxErrors.MissingClosingTagElement, closingElement, {
  8957. openingTagName: getQualifiedJSXName(openingElement.name)
  8958. });
  8959. }
  8960. }
  8961. }
  8962. if (isFragment(openingElement)) {
  8963. node.openingFragment = openingElement;
  8964. node.closingFragment = closingElement;
  8965. } else {
  8966. node.openingElement = openingElement;
  8967. node.closingElement = closingElement;
  8968. }
  8969. node.children = children;
  8970. if (this.match(47)) {
  8971. throw this.raise(JsxErrors.UnwrappedAdjacentJSXElements, this.state.startLoc);
  8972. }
  8973. return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
  8974. }
  8975. jsxParseElement() {
  8976. const startLoc = this.state.startLoc;
  8977. this.next();
  8978. return this.jsxParseElementAt(startLoc);
  8979. }
  8980. setContext(newContext) {
  8981. const {
  8982. context
  8983. } = this.state;
  8984. context[context.length - 1] = newContext;
  8985. }
  8986. parseExprAtom(refExpressionErrors) {
  8987. if (this.match(143)) {
  8988. return this.jsxParseElement();
  8989. } else if (this.match(47) && this.input.charCodeAt(this.state.pos) !== 33) {
  8990. this.replaceToken(143);
  8991. return this.jsxParseElement();
  8992. } else {
  8993. return super.parseExprAtom(refExpressionErrors);
  8994. }
  8995. }
  8996. skipSpace() {
  8997. const curContext = this.curContext();
  8998. if (!curContext.preserveSpace) super.skipSpace();
  8999. }
  9000. getTokenFromCode(code) {
  9001. const context = this.curContext();
  9002. if (context === types.j_expr) {
  9003. this.jsxReadToken();
  9004. return;
  9005. }
  9006. if (context === types.j_oTag || context === types.j_cTag) {
  9007. if (isIdentifierStart(code)) {
  9008. this.jsxReadWord();
  9009. return;
  9010. }
  9011. if (code === 62) {
  9012. ++this.state.pos;
  9013. this.finishToken(144);
  9014. return;
  9015. }
  9016. if ((code === 34 || code === 39) && context === types.j_oTag) {
  9017. this.jsxReadString(code);
  9018. return;
  9019. }
  9020. }
  9021. if (code === 60 && this.state.canStartJSXElement && this.input.charCodeAt(this.state.pos + 1) !== 33) {
  9022. ++this.state.pos;
  9023. this.finishToken(143);
  9024. return;
  9025. }
  9026. super.getTokenFromCode(code);
  9027. }
  9028. updateContext(prevType) {
  9029. const {
  9030. context,
  9031. type
  9032. } = this.state;
  9033. if (type === 56 && prevType === 143) {
  9034. context.splice(-2, 2, types.j_cTag);
  9035. this.state.canStartJSXElement = false;
  9036. } else if (type === 143) {
  9037. context.push(types.j_oTag);
  9038. } else if (type === 144) {
  9039. const out = context[context.length - 1];
  9040. if (out === types.j_oTag && prevType === 56 || out === types.j_cTag) {
  9041. context.pop();
  9042. this.state.canStartJSXElement = context[context.length - 1] === types.j_expr;
  9043. } else {
  9044. this.setContext(types.j_expr);
  9045. this.state.canStartJSXElement = true;
  9046. }
  9047. } else {
  9048. this.state.canStartJSXElement = tokenComesBeforeExpression(type);
  9049. }
  9050. }
  9051. };
  9052. class TypeScriptScope extends Scope {
  9053. constructor(...args) {
  9054. super(...args);
  9055. this.tsNames = new Map();
  9056. }
  9057. }
  9058. class TypeScriptScopeHandler extends ScopeHandler {
  9059. constructor(...args) {
  9060. super(...args);
  9061. this.importsStack = [];
  9062. }
  9063. createScope(flags) {
  9064. this.importsStack.push(new Set());
  9065. return new TypeScriptScope(flags);
  9066. }
  9067. enter(flags) {
  9068. if (flags === 1024) {
  9069. this.importsStack.push(new Set());
  9070. }
  9071. super.enter(flags);
  9072. }
  9073. exit() {
  9074. const flags = super.exit();
  9075. if (flags === 1024) {
  9076. this.importsStack.pop();
  9077. }
  9078. return flags;
  9079. }
  9080. hasImport(name, allowShadow) {
  9081. const len = this.importsStack.length;
  9082. if (this.importsStack[len - 1].has(name)) {
  9083. return true;
  9084. }
  9085. if (!allowShadow && len > 1) {
  9086. for (let i = 0; i < len - 1; i++) {
  9087. if (this.importsStack[i].has(name)) return true;
  9088. }
  9089. }
  9090. return false;
  9091. }
  9092. declareName(name, bindingType, loc) {
  9093. if (bindingType & 4096) {
  9094. if (this.hasImport(name, true)) {
  9095. this.parser.raise(Errors.VarRedeclaration, loc, {
  9096. identifierName: name
  9097. });
  9098. }
  9099. this.importsStack[this.importsStack.length - 1].add(name);
  9100. return;
  9101. }
  9102. const scope = this.currentScope();
  9103. let type = scope.tsNames.get(name) || 0;
  9104. if (bindingType & 1024) {
  9105. this.maybeExportDefined(scope, name);
  9106. scope.tsNames.set(name, type | 16);
  9107. return;
  9108. }
  9109. super.declareName(name, bindingType, loc);
  9110. if (bindingType & 2) {
  9111. if (!(bindingType & 1)) {
  9112. this.checkRedeclarationInScope(scope, name, bindingType, loc);
  9113. this.maybeExportDefined(scope, name);
  9114. }
  9115. type = type | 1;
  9116. }
  9117. if (bindingType & 256) {
  9118. type = type | 2;
  9119. }
  9120. if (bindingType & 512) {
  9121. type = type | 4;
  9122. }
  9123. if (bindingType & 128) {
  9124. type = type | 8;
  9125. }
  9126. if (type) scope.tsNames.set(name, type);
  9127. }
  9128. isRedeclaredInScope(scope, name, bindingType) {
  9129. const type = scope.tsNames.get(name);
  9130. if ((type & 2) > 0) {
  9131. if (bindingType & 256) {
  9132. const isConst = !!(bindingType & 512);
  9133. const wasConst = (type & 4) > 0;
  9134. return isConst !== wasConst;
  9135. }
  9136. return true;
  9137. }
  9138. if (bindingType & 128 && (type & 8) > 0) {
  9139. if (scope.names.get(name) & 2) {
  9140. return !!(bindingType & 1);
  9141. } else {
  9142. return false;
  9143. }
  9144. }
  9145. if (bindingType & 2 && (type & 1) > 0) {
  9146. return true;
  9147. }
  9148. return super.isRedeclaredInScope(scope, name, bindingType);
  9149. }
  9150. checkLocalExport(id) {
  9151. const {
  9152. name
  9153. } = id;
  9154. if (this.hasImport(name)) return;
  9155. const len = this.scopeStack.length;
  9156. for (let i = len - 1; i >= 0; i--) {
  9157. const scope = this.scopeStack[i];
  9158. const type = scope.tsNames.get(name);
  9159. if ((type & 1) > 0 || (type & 16) > 0) {
  9160. return;
  9161. }
  9162. }
  9163. super.checkLocalExport(id);
  9164. }
  9165. }
  9166. class ProductionParameterHandler {
  9167. constructor() {
  9168. this.stacks = [];
  9169. }
  9170. enter(flags) {
  9171. this.stacks.push(flags);
  9172. }
  9173. exit() {
  9174. this.stacks.pop();
  9175. }
  9176. currentFlags() {
  9177. return this.stacks[this.stacks.length - 1];
  9178. }
  9179. get hasAwait() {
  9180. return (this.currentFlags() & 2) > 0;
  9181. }
  9182. get hasYield() {
  9183. return (this.currentFlags() & 1) > 0;
  9184. }
  9185. get hasReturn() {
  9186. return (this.currentFlags() & 4) > 0;
  9187. }
  9188. get hasIn() {
  9189. return (this.currentFlags() & 8) > 0;
  9190. }
  9191. }
  9192. function functionFlags(isAsync, isGenerator) {
  9193. return (isAsync ? 2 : 0) | (isGenerator ? 1 : 0);
  9194. }
  9195. class BaseParser {
  9196. constructor() {
  9197. this.sawUnambiguousESM = false;
  9198. this.ambiguousScriptDifferentAst = false;
  9199. }
  9200. sourceToOffsetPos(sourcePos) {
  9201. return sourcePos + this.startIndex;
  9202. }
  9203. offsetToSourcePos(offsetPos) {
  9204. return offsetPos - this.startIndex;
  9205. }
  9206. hasPlugin(pluginConfig) {
  9207. if (typeof pluginConfig === "string") {
  9208. return this.plugins.has(pluginConfig);
  9209. } else {
  9210. const [pluginName, pluginOptions] = pluginConfig;
  9211. if (!this.hasPlugin(pluginName)) {
  9212. return false;
  9213. }
  9214. const actualOptions = this.plugins.get(pluginName);
  9215. for (const key of Object.keys(pluginOptions)) {
  9216. if ((actualOptions == null ? void 0 : actualOptions[key]) !== pluginOptions[key]) {
  9217. return false;
  9218. }
  9219. }
  9220. return true;
  9221. }
  9222. }
  9223. getPluginOption(plugin, name) {
  9224. var _this$plugins$get;
  9225. return (_this$plugins$get = this.plugins.get(plugin)) == null ? void 0 : _this$plugins$get[name];
  9226. }
  9227. }
  9228. function setTrailingComments(node, comments) {
  9229. if (node.trailingComments === undefined) {
  9230. node.trailingComments = comments;
  9231. } else {
  9232. node.trailingComments.unshift(...comments);
  9233. }
  9234. }
  9235. function setLeadingComments(node, comments) {
  9236. if (node.leadingComments === undefined) {
  9237. node.leadingComments = comments;
  9238. } else {
  9239. node.leadingComments.unshift(...comments);
  9240. }
  9241. }
  9242. function setInnerComments(node, comments) {
  9243. if (node.innerComments === undefined) {
  9244. node.innerComments = comments;
  9245. } else {
  9246. node.innerComments.unshift(...comments);
  9247. }
  9248. }
  9249. function adjustInnerComments(node, elements, commentWS) {
  9250. let lastElement = null;
  9251. let i = elements.length;
  9252. while (lastElement === null && i > 0) {
  9253. lastElement = elements[--i];
  9254. }
  9255. if (lastElement === null || lastElement.start > commentWS.start) {
  9256. setInnerComments(node, commentWS.comments);
  9257. } else {
  9258. setTrailingComments(lastElement, commentWS.comments);
  9259. }
  9260. }
  9261. class CommentsParser extends BaseParser {
  9262. addComment(comment) {
  9263. if (this.filename) comment.loc.filename = this.filename;
  9264. const {
  9265. commentsLen
  9266. } = this.state;
  9267. if (this.comments.length !== commentsLen) {
  9268. this.comments.length = commentsLen;
  9269. }
  9270. this.comments.push(comment);
  9271. this.state.commentsLen++;
  9272. }
  9273. processComment(node) {
  9274. const {
  9275. commentStack
  9276. } = this.state;
  9277. const commentStackLength = commentStack.length;
  9278. if (commentStackLength === 0) return;
  9279. let i = commentStackLength - 1;
  9280. const lastCommentWS = commentStack[i];
  9281. if (lastCommentWS.start === node.end) {
  9282. lastCommentWS.leadingNode = node;
  9283. i--;
  9284. }
  9285. const {
  9286. start: nodeStart
  9287. } = node;
  9288. for (; i >= 0; i--) {
  9289. const commentWS = commentStack[i];
  9290. const commentEnd = commentWS.end;
  9291. if (commentEnd > nodeStart) {
  9292. commentWS.containingNode = node;
  9293. this.finalizeComment(commentWS);
  9294. commentStack.splice(i, 1);
  9295. } else {
  9296. if (commentEnd === nodeStart) {
  9297. commentWS.trailingNode = node;
  9298. }
  9299. break;
  9300. }
  9301. }
  9302. }
  9303. finalizeComment(commentWS) {
  9304. var _node$options;
  9305. const {
  9306. comments
  9307. } = commentWS;
  9308. if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) {
  9309. if (commentWS.leadingNode !== null) {
  9310. setTrailingComments(commentWS.leadingNode, comments);
  9311. }
  9312. if (commentWS.trailingNode !== null) {
  9313. setLeadingComments(commentWS.trailingNode, comments);
  9314. }
  9315. } else {
  9316. const node = commentWS.containingNode;
  9317. const commentStart = commentWS.start;
  9318. if (this.input.charCodeAt(this.offsetToSourcePos(commentStart) - 1) === 44) {
  9319. switch (node.type) {
  9320. case "ObjectExpression":
  9321. case "ObjectPattern":
  9322. adjustInnerComments(node, node.properties, commentWS);
  9323. break;
  9324. case "CallExpression":
  9325. case "NewExpression":
  9326. case "OptionalCallExpression":
  9327. adjustInnerComments(node, node.arguments, commentWS);
  9328. break;
  9329. case "ImportExpression":
  9330. adjustInnerComments(node, [node.source, (_node$options = node.options) != null ? _node$options : null], commentWS);
  9331. break;
  9332. case "FunctionDeclaration":
  9333. case "FunctionExpression":
  9334. case "ArrowFunctionExpression":
  9335. case "ObjectMethod":
  9336. case "ClassMethod":
  9337. case "ClassPrivateMethod":
  9338. case "TSTypeParameterDeclaration":
  9339. adjustInnerComments(node, node.params, commentWS);
  9340. break;
  9341. case "ArrayExpression":
  9342. case "ArrayPattern":
  9343. adjustInnerComments(node, node.elements, commentWS);
  9344. break;
  9345. case "ExportNamedDeclaration":
  9346. case "ImportDeclaration":
  9347. adjustInnerComments(node, node.specifiers, commentWS);
  9348. break;
  9349. case "TSEnumDeclaration":
  9350. adjustInnerComments(node, node.members, commentWS);
  9351. break;
  9352. case "TSEnumBody":
  9353. adjustInnerComments(node, node.members, commentWS);
  9354. break;
  9355. case "TSInterfaceBody":
  9356. adjustInnerComments(node, node.body, commentWS);
  9357. break;
  9358. default:
  9359. {
  9360. if (node.type === "RecordExpression") {
  9361. adjustInnerComments(node, node.properties, commentWS);
  9362. break;
  9363. }
  9364. if (node.type === "TupleExpression") {
  9365. adjustInnerComments(node, node.elements, commentWS);
  9366. break;
  9367. }
  9368. setInnerComments(node, comments);
  9369. }
  9370. }
  9371. } else {
  9372. setInnerComments(node, comments);
  9373. }
  9374. }
  9375. }
  9376. finalizeRemainingComments() {
  9377. const {
  9378. commentStack
  9379. } = this.state;
  9380. for (let i = commentStack.length - 1; i >= 0; i--) {
  9381. this.finalizeComment(commentStack[i]);
  9382. }
  9383. this.state.commentStack = [];
  9384. }
  9385. resetPreviousNodeTrailingComments(node) {
  9386. const {
  9387. commentStack
  9388. } = this.state;
  9389. const {
  9390. length
  9391. } = commentStack;
  9392. if (length === 0) return;
  9393. const commentWS = commentStack[length - 1];
  9394. if (commentWS.leadingNode === node) {
  9395. commentWS.leadingNode = null;
  9396. }
  9397. }
  9398. takeSurroundingComments(node, start, end) {
  9399. const {
  9400. commentStack
  9401. } = this.state;
  9402. const commentStackLength = commentStack.length;
  9403. if (commentStackLength === 0) return;
  9404. let i = commentStackLength - 1;
  9405. for (; i >= 0; i--) {
  9406. const commentWS = commentStack[i];
  9407. const commentEnd = commentWS.end;
  9408. const commentStart = commentWS.start;
  9409. if (commentStart === end) {
  9410. commentWS.leadingNode = node;
  9411. } else if (commentEnd === start) {
  9412. commentWS.trailingNode = node;
  9413. } else if (commentEnd < start) {
  9414. break;
  9415. }
  9416. }
  9417. }
  9418. }
  9419. class State {
  9420. constructor() {
  9421. this.flags = 1024;
  9422. this.startIndex = void 0;
  9423. this.curLine = void 0;
  9424. this.lineStart = void 0;
  9425. this.startLoc = void 0;
  9426. this.endLoc = void 0;
  9427. this.errors = [];
  9428. this.potentialArrowAt = -1;
  9429. this.noArrowAt = [];
  9430. this.noArrowParamsConversionAt = [];
  9431. this.topicContext = {
  9432. maxNumOfResolvableTopics: 0,
  9433. maxTopicIndex: null
  9434. };
  9435. this.labels = [];
  9436. this.commentsLen = 0;
  9437. this.commentStack = [];
  9438. this.pos = 0;
  9439. this.type = 140;
  9440. this.value = null;
  9441. this.start = 0;
  9442. this.end = 0;
  9443. this.lastTokEndLoc = null;
  9444. this.lastTokStartLoc = null;
  9445. this.context = [types.brace];
  9446. this.firstInvalidTemplateEscapePos = null;
  9447. this.strictErrors = new Map();
  9448. this.tokensLength = 0;
  9449. }
  9450. get strict() {
  9451. return (this.flags & 1) > 0;
  9452. }
  9453. set strict(v) {
  9454. if (v) this.flags |= 1;else this.flags &= -2;
  9455. }
  9456. init({
  9457. strictMode,
  9458. sourceType,
  9459. startIndex,
  9460. startLine,
  9461. startColumn
  9462. }) {
  9463. this.strict = strictMode === false ? false : strictMode === true ? true : sourceType === "module";
  9464. this.startIndex = startIndex;
  9465. this.curLine = startLine;
  9466. this.lineStart = -startColumn;
  9467. this.startLoc = this.endLoc = new Position(startLine, startColumn, startIndex);
  9468. }
  9469. get maybeInArrowParameters() {
  9470. return (this.flags & 2) > 0;
  9471. }
  9472. set maybeInArrowParameters(v) {
  9473. if (v) this.flags |= 2;else this.flags &= -3;
  9474. }
  9475. get inType() {
  9476. return (this.flags & 4) > 0;
  9477. }
  9478. set inType(v) {
  9479. if (v) this.flags |= 4;else this.flags &= -5;
  9480. }
  9481. get noAnonFunctionType() {
  9482. return (this.flags & 8) > 0;
  9483. }
  9484. set noAnonFunctionType(v) {
  9485. if (v) this.flags |= 8;else this.flags &= -9;
  9486. }
  9487. get hasFlowComment() {
  9488. return (this.flags & 16) > 0;
  9489. }
  9490. set hasFlowComment(v) {
  9491. if (v) this.flags |= 16;else this.flags &= -17;
  9492. }
  9493. get isAmbientContext() {
  9494. return (this.flags & 32) > 0;
  9495. }
  9496. set isAmbientContext(v) {
  9497. if (v) this.flags |= 32;else this.flags &= -33;
  9498. }
  9499. get inAbstractClass() {
  9500. return (this.flags & 64) > 0;
  9501. }
  9502. set inAbstractClass(v) {
  9503. if (v) this.flags |= 64;else this.flags &= -65;
  9504. }
  9505. get inDisallowConditionalTypesContext() {
  9506. return (this.flags & 128) > 0;
  9507. }
  9508. set inDisallowConditionalTypesContext(v) {
  9509. if (v) this.flags |= 128;else this.flags &= -129;
  9510. }
  9511. get soloAwait() {
  9512. return (this.flags & 256) > 0;
  9513. }
  9514. set soloAwait(v) {
  9515. if (v) this.flags |= 256;else this.flags &= -257;
  9516. }
  9517. get inFSharpPipelineDirectBody() {
  9518. return (this.flags & 512) > 0;
  9519. }
  9520. set inFSharpPipelineDirectBody(v) {
  9521. if (v) this.flags |= 512;else this.flags &= -513;
  9522. }
  9523. get canStartJSXElement() {
  9524. return (this.flags & 1024) > 0;
  9525. }
  9526. set canStartJSXElement(v) {
  9527. if (v) this.flags |= 1024;else this.flags &= -1025;
  9528. }
  9529. get containsEsc() {
  9530. return (this.flags & 2048) > 0;
  9531. }
  9532. set containsEsc(v) {
  9533. if (v) this.flags |= 2048;else this.flags &= -2049;
  9534. }
  9535. get hasTopLevelAwait() {
  9536. return (this.flags & 4096) > 0;
  9537. }
  9538. set hasTopLevelAwait(v) {
  9539. if (v) this.flags |= 4096;else this.flags &= -4097;
  9540. }
  9541. curPosition() {
  9542. return new Position(this.curLine, this.pos - this.lineStart, this.pos + this.startIndex);
  9543. }
  9544. clone() {
  9545. const state = new State();
  9546. state.flags = this.flags;
  9547. state.startIndex = this.startIndex;
  9548. state.curLine = this.curLine;
  9549. state.lineStart = this.lineStart;
  9550. state.startLoc = this.startLoc;
  9551. state.endLoc = this.endLoc;
  9552. state.errors = this.errors.slice();
  9553. state.potentialArrowAt = this.potentialArrowAt;
  9554. state.noArrowAt = this.noArrowAt.slice();
  9555. state.noArrowParamsConversionAt = this.noArrowParamsConversionAt.slice();
  9556. state.topicContext = this.topicContext;
  9557. state.labels = this.labels.slice();
  9558. state.commentsLen = this.commentsLen;
  9559. state.commentStack = this.commentStack.slice();
  9560. state.pos = this.pos;
  9561. state.type = this.type;
  9562. state.value = this.value;
  9563. state.start = this.start;
  9564. state.end = this.end;
  9565. state.lastTokEndLoc = this.lastTokEndLoc;
  9566. state.lastTokStartLoc = this.lastTokStartLoc;
  9567. state.context = this.context.slice();
  9568. state.firstInvalidTemplateEscapePos = this.firstInvalidTemplateEscapePos;
  9569. state.strictErrors = this.strictErrors;
  9570. state.tokensLength = this.tokensLength;
  9571. return state;
  9572. }
  9573. }
  9574. var _isDigit = function isDigit(code) {
  9575. return code >= 48 && code <= 57;
  9576. };
  9577. const forbiddenNumericSeparatorSiblings = {
  9578. decBinOct: new Set([46, 66, 69, 79, 95, 98, 101, 111]),
  9579. hex: new Set([46, 88, 95, 120])
  9580. };
  9581. const isAllowedNumericSeparatorSibling = {
  9582. bin: ch => ch === 48 || ch === 49,
  9583. oct: ch => ch >= 48 && ch <= 55,
  9584. dec: ch => ch >= 48 && ch <= 57,
  9585. hex: ch => ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102
  9586. };
  9587. function readStringContents(type, input, pos, lineStart, curLine, errors) {
  9588. const initialPos = pos;
  9589. const initialLineStart = lineStart;
  9590. const initialCurLine = curLine;
  9591. let out = "";
  9592. let firstInvalidLoc = null;
  9593. let chunkStart = pos;
  9594. const {
  9595. length
  9596. } = input;
  9597. for (;;) {
  9598. if (pos >= length) {
  9599. errors.unterminated(initialPos, initialLineStart, initialCurLine);
  9600. out += input.slice(chunkStart, pos);
  9601. break;
  9602. }
  9603. const ch = input.charCodeAt(pos);
  9604. if (isStringEnd(type, ch, input, pos)) {
  9605. out += input.slice(chunkStart, pos);
  9606. break;
  9607. }
  9608. if (ch === 92) {
  9609. out += input.slice(chunkStart, pos);
  9610. const res = readEscapedChar(input, pos, lineStart, curLine, type === "template", errors);
  9611. if (res.ch === null && !firstInvalidLoc) {
  9612. firstInvalidLoc = {
  9613. pos,
  9614. lineStart,
  9615. curLine
  9616. };
  9617. } else {
  9618. out += res.ch;
  9619. }
  9620. ({
  9621. pos,
  9622. lineStart,
  9623. curLine
  9624. } = res);
  9625. chunkStart = pos;
  9626. } else if (ch === 8232 || ch === 8233) {
  9627. ++pos;
  9628. ++curLine;
  9629. lineStart = pos;
  9630. } else if (ch === 10 || ch === 13) {
  9631. if (type === "template") {
  9632. out += input.slice(chunkStart, pos) + "\n";
  9633. ++pos;
  9634. if (ch === 13 && input.charCodeAt(pos) === 10) {
  9635. ++pos;
  9636. }
  9637. ++curLine;
  9638. chunkStart = lineStart = pos;
  9639. } else {
  9640. errors.unterminated(initialPos, initialLineStart, initialCurLine);
  9641. }
  9642. } else {
  9643. ++pos;
  9644. }
  9645. }
  9646. return {
  9647. pos,
  9648. str: out,
  9649. firstInvalidLoc,
  9650. lineStart,
  9651. curLine,
  9652. containsInvalid: !!firstInvalidLoc
  9653. };
  9654. }
  9655. function isStringEnd(type, ch, input, pos) {
  9656. if (type === "template") {
  9657. return ch === 96 || ch === 36 && input.charCodeAt(pos + 1) === 123;
  9658. }
  9659. return ch === (type === "double" ? 34 : 39);
  9660. }
  9661. function readEscapedChar(input, pos, lineStart, curLine, inTemplate, errors) {
  9662. const throwOnInvalid = !inTemplate;
  9663. pos++;
  9664. const res = ch => ({
  9665. pos,
  9666. ch,
  9667. lineStart,
  9668. curLine
  9669. });
  9670. const ch = input.charCodeAt(pos++);
  9671. switch (ch) {
  9672. case 110:
  9673. return res("\n");
  9674. case 114:
  9675. return res("\r");
  9676. case 120:
  9677. {
  9678. let code;
  9679. ({
  9680. code,
  9681. pos
  9682. } = readHexChar(input, pos, lineStart, curLine, 2, false, throwOnInvalid, errors));
  9683. return res(code === null ? null : String.fromCharCode(code));
  9684. }
  9685. case 117:
  9686. {
  9687. let code;
  9688. ({
  9689. code,
  9690. pos
  9691. } = readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors));
  9692. return res(code === null ? null : String.fromCodePoint(code));
  9693. }
  9694. case 116:
  9695. return res("\t");
  9696. case 98:
  9697. return res("\b");
  9698. case 118:
  9699. return res("\u000b");
  9700. case 102:
  9701. return res("\f");
  9702. case 13:
  9703. if (input.charCodeAt(pos) === 10) {
  9704. ++pos;
  9705. }
  9706. case 10:
  9707. lineStart = pos;
  9708. ++curLine;
  9709. case 8232:
  9710. case 8233:
  9711. return res("");
  9712. case 56:
  9713. case 57:
  9714. if (inTemplate) {
  9715. return res(null);
  9716. } else {
  9717. errors.strictNumericEscape(pos - 1, lineStart, curLine);
  9718. }
  9719. default:
  9720. if (ch >= 48 && ch <= 55) {
  9721. const startPos = pos - 1;
  9722. const match = /^[0-7]+/.exec(input.slice(startPos, pos + 2));
  9723. let octalStr = match[0];
  9724. let octal = parseInt(octalStr, 8);
  9725. if (octal > 255) {
  9726. octalStr = octalStr.slice(0, -1);
  9727. octal = parseInt(octalStr, 8);
  9728. }
  9729. pos += octalStr.length - 1;
  9730. const next = input.charCodeAt(pos);
  9731. if (octalStr !== "0" || next === 56 || next === 57) {
  9732. if (inTemplate) {
  9733. return res(null);
  9734. } else {
  9735. errors.strictNumericEscape(startPos, lineStart, curLine);
  9736. }
  9737. }
  9738. return res(String.fromCharCode(octal));
  9739. }
  9740. return res(String.fromCharCode(ch));
  9741. }
  9742. }
  9743. function readHexChar(input, pos, lineStart, curLine, len, forceLen, throwOnInvalid, errors) {
  9744. const initialPos = pos;
  9745. let n;
  9746. ({
  9747. n,
  9748. pos
  9749. } = readInt(input, pos, lineStart, curLine, 16, len, forceLen, false, errors, !throwOnInvalid));
  9750. if (n === null) {
  9751. if (throwOnInvalid) {
  9752. errors.invalidEscapeSequence(initialPos, lineStart, curLine);
  9753. } else {
  9754. pos = initialPos - 1;
  9755. }
  9756. }
  9757. return {
  9758. code: n,
  9759. pos
  9760. };
  9761. }
  9762. function readInt(input, pos, lineStart, curLine, radix, len, forceLen, allowNumSeparator, errors, bailOnError) {
  9763. const start = pos;
  9764. const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  9765. const isAllowedSibling = radix === 16 ? isAllowedNumericSeparatorSibling.hex : radix === 10 ? isAllowedNumericSeparatorSibling.dec : radix === 8 ? isAllowedNumericSeparatorSibling.oct : isAllowedNumericSeparatorSibling.bin;
  9766. let invalid = false;
  9767. let total = 0;
  9768. for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  9769. const code = input.charCodeAt(pos);
  9770. let val;
  9771. if (code === 95 && allowNumSeparator !== "bail") {
  9772. const prev = input.charCodeAt(pos - 1);
  9773. const next = input.charCodeAt(pos + 1);
  9774. if (!allowNumSeparator) {
  9775. if (bailOnError) return {
  9776. n: null,
  9777. pos
  9778. };
  9779. errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine);
  9780. } else if (Number.isNaN(next) || !isAllowedSibling(next) || forbiddenSiblings.has(prev) || forbiddenSiblings.has(next)) {
  9781. if (bailOnError) return {
  9782. n: null,
  9783. pos
  9784. };
  9785. errors.unexpectedNumericSeparator(pos, lineStart, curLine);
  9786. }
  9787. ++pos;
  9788. continue;
  9789. }
  9790. if (code >= 97) {
  9791. val = code - 97 + 10;
  9792. } else if (code >= 65) {
  9793. val = code - 65 + 10;
  9794. } else if (_isDigit(code)) {
  9795. val = code - 48;
  9796. } else {
  9797. val = Infinity;
  9798. }
  9799. if (val >= radix) {
  9800. if (val <= 9 && bailOnError) {
  9801. return {
  9802. n: null,
  9803. pos
  9804. };
  9805. } else if (val <= 9 && errors.invalidDigit(pos, lineStart, curLine, radix)) {
  9806. val = 0;
  9807. } else if (forceLen) {
  9808. val = 0;
  9809. invalid = true;
  9810. } else {
  9811. break;
  9812. }
  9813. }
  9814. ++pos;
  9815. total = total * radix + val;
  9816. }
  9817. if (pos === start || len != null && pos - start !== len || invalid) {
  9818. return {
  9819. n: null,
  9820. pos
  9821. };
  9822. }
  9823. return {
  9824. n: total,
  9825. pos
  9826. };
  9827. }
  9828. function readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors) {
  9829. const ch = input.charCodeAt(pos);
  9830. let code;
  9831. if (ch === 123) {
  9832. ++pos;
  9833. ({
  9834. code,
  9835. pos
  9836. } = readHexChar(input, pos, lineStart, curLine, input.indexOf("}", pos) - pos, true, throwOnInvalid, errors));
  9837. ++pos;
  9838. if (code !== null && code > 0x10ffff) {
  9839. if (throwOnInvalid) {
  9840. errors.invalidCodePoint(pos, lineStart, curLine);
  9841. } else {
  9842. return {
  9843. code: null,
  9844. pos
  9845. };
  9846. }
  9847. }
  9848. } else {
  9849. ({
  9850. code,
  9851. pos
  9852. } = readHexChar(input, pos, lineStart, curLine, 4, false, throwOnInvalid, errors));
  9853. }
  9854. return {
  9855. code,
  9856. pos
  9857. };
  9858. }
  9859. function buildPosition(pos, lineStart, curLine) {
  9860. return new Position(curLine, pos - lineStart, pos);
  9861. }
  9862. const VALID_REGEX_FLAGS = new Set([103, 109, 115, 105, 121, 117, 100, 118]);
  9863. class Token {
  9864. constructor(state) {
  9865. const startIndex = state.startIndex || 0;
  9866. this.type = state.type;
  9867. this.value = state.value;
  9868. this.start = startIndex + state.start;
  9869. this.end = startIndex + state.end;
  9870. this.loc = new SourceLocation(state.startLoc, state.endLoc);
  9871. }
  9872. }
  9873. class Tokenizer extends CommentsParser {
  9874. constructor(options, input) {
  9875. super();
  9876. this.isLookahead = void 0;
  9877. this.tokens = [];
  9878. this.errorHandlers_readInt = {
  9879. invalidDigit: (pos, lineStart, curLine, radix) => {
  9880. if (!(this.optionFlags & 2048)) return false;
  9881. this.raise(Errors.InvalidDigit, buildPosition(pos, lineStart, curLine), {
  9882. radix
  9883. });
  9884. return true;
  9885. },
  9886. numericSeparatorInEscapeSequence: this.errorBuilder(Errors.NumericSeparatorInEscapeSequence),
  9887. unexpectedNumericSeparator: this.errorBuilder(Errors.UnexpectedNumericSeparator)
  9888. };
  9889. this.errorHandlers_readCodePoint = Object.assign({}, this.errorHandlers_readInt, {
  9890. invalidEscapeSequence: this.errorBuilder(Errors.InvalidEscapeSequence),
  9891. invalidCodePoint: this.errorBuilder(Errors.InvalidCodePoint)
  9892. });
  9893. this.errorHandlers_readStringContents_string = Object.assign({}, this.errorHandlers_readCodePoint, {
  9894. strictNumericEscape: (pos, lineStart, curLine) => {
  9895. this.recordStrictModeErrors(Errors.StrictNumericEscape, buildPosition(pos, lineStart, curLine));
  9896. },
  9897. unterminated: (pos, lineStart, curLine) => {
  9898. throw this.raise(Errors.UnterminatedString, buildPosition(pos - 1, lineStart, curLine));
  9899. }
  9900. });
  9901. this.errorHandlers_readStringContents_template = Object.assign({}, this.errorHandlers_readCodePoint, {
  9902. strictNumericEscape: this.errorBuilder(Errors.StrictNumericEscape),
  9903. unterminated: (pos, lineStart, curLine) => {
  9904. throw this.raise(Errors.UnterminatedTemplate, buildPosition(pos, lineStart, curLine));
  9905. }
  9906. });
  9907. this.state = new State();
  9908. this.state.init(options);
  9909. this.input = input;
  9910. this.length = input.length;
  9911. this.comments = [];
  9912. this.isLookahead = false;
  9913. }
  9914. pushToken(token) {
  9915. this.tokens.length = this.state.tokensLength;
  9916. this.tokens.push(token);
  9917. ++this.state.tokensLength;
  9918. }
  9919. next() {
  9920. this.checkKeywordEscapes();
  9921. if (this.optionFlags & 256) {
  9922. this.pushToken(new Token(this.state));
  9923. }
  9924. this.state.lastTokEndLoc = this.state.endLoc;
  9925. this.state.lastTokStartLoc = this.state.startLoc;
  9926. this.nextToken();
  9927. }
  9928. eat(type) {
  9929. if (this.match(type)) {
  9930. this.next();
  9931. return true;
  9932. } else {
  9933. return false;
  9934. }
  9935. }
  9936. match(type) {
  9937. return this.state.type === type;
  9938. }
  9939. createLookaheadState(state) {
  9940. return {
  9941. pos: state.pos,
  9942. value: null,
  9943. type: state.type,
  9944. start: state.start,
  9945. end: state.end,
  9946. context: [this.curContext()],
  9947. inType: state.inType,
  9948. startLoc: state.startLoc,
  9949. lastTokEndLoc: state.lastTokEndLoc,
  9950. curLine: state.curLine,
  9951. lineStart: state.lineStart,
  9952. curPosition: state.curPosition
  9953. };
  9954. }
  9955. lookahead() {
  9956. const old = this.state;
  9957. this.state = this.createLookaheadState(old);
  9958. this.isLookahead = true;
  9959. this.nextToken();
  9960. this.isLookahead = false;
  9961. const curr = this.state;
  9962. this.state = old;
  9963. return curr;
  9964. }
  9965. nextTokenStart() {
  9966. return this.nextTokenStartSince(this.state.pos);
  9967. }
  9968. nextTokenStartSince(pos) {
  9969. skipWhiteSpace.lastIndex = pos;
  9970. return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos;
  9971. }
  9972. lookaheadCharCode() {
  9973. return this.lookaheadCharCodeSince(this.state.pos);
  9974. }
  9975. lookaheadCharCodeSince(pos) {
  9976. return this.input.charCodeAt(this.nextTokenStartSince(pos));
  9977. }
  9978. nextTokenInLineStart() {
  9979. return this.nextTokenInLineStartSince(this.state.pos);
  9980. }
  9981. nextTokenInLineStartSince(pos) {
  9982. skipWhiteSpaceInLine.lastIndex = pos;
  9983. return skipWhiteSpaceInLine.test(this.input) ? skipWhiteSpaceInLine.lastIndex : pos;
  9984. }
  9985. lookaheadInLineCharCode() {
  9986. return this.input.charCodeAt(this.nextTokenInLineStart());
  9987. }
  9988. codePointAtPos(pos) {
  9989. let cp = this.input.charCodeAt(pos);
  9990. if ((cp & 0xfc00) === 0xd800 && ++pos < this.input.length) {
  9991. const trail = this.input.charCodeAt(pos);
  9992. if ((trail & 0xfc00) === 0xdc00) {
  9993. cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);
  9994. }
  9995. }
  9996. return cp;
  9997. }
  9998. setStrict(strict) {
  9999. this.state.strict = strict;
  10000. if (strict) {
  10001. this.state.strictErrors.forEach(([toParseError, at]) => this.raise(toParseError, at));
  10002. this.state.strictErrors.clear();
  10003. }
  10004. }
  10005. curContext() {
  10006. return this.state.context[this.state.context.length - 1];
  10007. }
  10008. nextToken() {
  10009. this.skipSpace();
  10010. this.state.start = this.state.pos;
  10011. if (!this.isLookahead) this.state.startLoc = this.state.curPosition();
  10012. if (this.state.pos >= this.length) {
  10013. this.finishToken(140);
  10014. return;
  10015. }
  10016. this.getTokenFromCode(this.codePointAtPos(this.state.pos));
  10017. }
  10018. skipBlockComment(commentEnd) {
  10019. let startLoc;
  10020. if (!this.isLookahead) startLoc = this.state.curPosition();
  10021. const start = this.state.pos;
  10022. const end = this.input.indexOf(commentEnd, start + 2);
  10023. if (end === -1) {
  10024. throw this.raise(Errors.UnterminatedComment, this.state.curPosition());
  10025. }
  10026. this.state.pos = end + commentEnd.length;
  10027. lineBreakG.lastIndex = start + 2;
  10028. while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) {
  10029. ++this.state.curLine;
  10030. this.state.lineStart = lineBreakG.lastIndex;
  10031. }
  10032. if (this.isLookahead) return;
  10033. const comment = {
  10034. type: "CommentBlock",
  10035. value: this.input.slice(start + 2, end),
  10036. start: this.sourceToOffsetPos(start),
  10037. end: this.sourceToOffsetPos(end + commentEnd.length),
  10038. loc: new SourceLocation(startLoc, this.state.curPosition())
  10039. };
  10040. if (this.optionFlags & 256) this.pushToken(comment);
  10041. return comment;
  10042. }
  10043. skipLineComment(startSkip) {
  10044. const start = this.state.pos;
  10045. let startLoc;
  10046. if (!this.isLookahead) startLoc = this.state.curPosition();
  10047. let ch = this.input.charCodeAt(this.state.pos += startSkip);
  10048. if (this.state.pos < this.length) {
  10049. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  10050. ch = this.input.charCodeAt(this.state.pos);
  10051. }
  10052. }
  10053. if (this.isLookahead) return;
  10054. const end = this.state.pos;
  10055. const value = this.input.slice(start + startSkip, end);
  10056. const comment = {
  10057. type: "CommentLine",
  10058. value,
  10059. start: this.sourceToOffsetPos(start),
  10060. end: this.sourceToOffsetPos(end),
  10061. loc: new SourceLocation(startLoc, this.state.curPosition())
  10062. };
  10063. if (this.optionFlags & 256) this.pushToken(comment);
  10064. return comment;
  10065. }
  10066. skipSpace() {
  10067. const spaceStart = this.state.pos;
  10068. const comments = this.optionFlags & 4096 ? [] : null;
  10069. loop: while (this.state.pos < this.length) {
  10070. const ch = this.input.charCodeAt(this.state.pos);
  10071. switch (ch) {
  10072. case 32:
  10073. case 160:
  10074. case 9:
  10075. ++this.state.pos;
  10076. break;
  10077. case 13:
  10078. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  10079. ++this.state.pos;
  10080. }
  10081. case 10:
  10082. case 8232:
  10083. case 8233:
  10084. ++this.state.pos;
  10085. ++this.state.curLine;
  10086. this.state.lineStart = this.state.pos;
  10087. break;
  10088. case 47:
  10089. switch (this.input.charCodeAt(this.state.pos + 1)) {
  10090. case 42:
  10091. {
  10092. const comment = this.skipBlockComment("*/");
  10093. if (comment !== undefined) {
  10094. this.addComment(comment);
  10095. comments == null || comments.push(comment);
  10096. }
  10097. break;
  10098. }
  10099. case 47:
  10100. {
  10101. const comment = this.skipLineComment(2);
  10102. if (comment !== undefined) {
  10103. this.addComment(comment);
  10104. comments == null || comments.push(comment);
  10105. }
  10106. break;
  10107. }
  10108. default:
  10109. break loop;
  10110. }
  10111. break;
  10112. default:
  10113. if (isWhitespace(ch)) {
  10114. ++this.state.pos;
  10115. } else if (ch === 45 && !this.inModule && this.optionFlags & 8192) {
  10116. const pos = this.state.pos;
  10117. if (this.input.charCodeAt(pos + 1) === 45 && this.input.charCodeAt(pos + 2) === 62 && (spaceStart === 0 || this.state.lineStart > spaceStart)) {
  10118. const comment = this.skipLineComment(3);
  10119. if (comment !== undefined) {
  10120. this.addComment(comment);
  10121. comments == null || comments.push(comment);
  10122. }
  10123. } else {
  10124. break loop;
  10125. }
  10126. } else if (ch === 60 && !this.inModule && this.optionFlags & 8192) {
  10127. const pos = this.state.pos;
  10128. if (this.input.charCodeAt(pos + 1) === 33 && this.input.charCodeAt(pos + 2) === 45 && this.input.charCodeAt(pos + 3) === 45) {
  10129. const comment = this.skipLineComment(4);
  10130. if (comment !== undefined) {
  10131. this.addComment(comment);
  10132. comments == null || comments.push(comment);
  10133. }
  10134. } else {
  10135. break loop;
  10136. }
  10137. } else {
  10138. break loop;
  10139. }
  10140. }
  10141. }
  10142. if ((comments == null ? void 0 : comments.length) > 0) {
  10143. const end = this.state.pos;
  10144. const commentWhitespace = {
  10145. start: this.sourceToOffsetPos(spaceStart),
  10146. end: this.sourceToOffsetPos(end),
  10147. comments: comments,
  10148. leadingNode: null,
  10149. trailingNode: null,
  10150. containingNode: null
  10151. };
  10152. this.state.commentStack.push(commentWhitespace);
  10153. }
  10154. }
  10155. finishToken(type, val) {
  10156. this.state.end = this.state.pos;
  10157. this.state.endLoc = this.state.curPosition();
  10158. const prevType = this.state.type;
  10159. this.state.type = type;
  10160. this.state.value = val;
  10161. if (!this.isLookahead) {
  10162. this.updateContext(prevType);
  10163. }
  10164. }
  10165. replaceToken(type) {
  10166. this.state.type = type;
  10167. this.updateContext();
  10168. }
  10169. readToken_numberSign() {
  10170. if (this.state.pos === 0 && this.readToken_interpreter()) {
  10171. return;
  10172. }
  10173. const nextPos = this.state.pos + 1;
  10174. const next = this.codePointAtPos(nextPos);
  10175. if (next >= 48 && next <= 57) {
  10176. throw this.raise(Errors.UnexpectedDigitAfterHash, this.state.curPosition());
  10177. }
  10178. if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) {
  10179. this.expectPlugin("recordAndTuple");
  10180. if (this.getPluginOption("recordAndTuple", "syntaxType") === "bar") {
  10181. throw this.raise(next === 123 ? Errors.RecordExpressionHashIncorrectStartSyntaxType : Errors.TupleExpressionHashIncorrectStartSyntaxType, this.state.curPosition());
  10182. }
  10183. this.state.pos += 2;
  10184. if (next === 123) {
  10185. this.finishToken(7);
  10186. } else {
  10187. this.finishToken(1);
  10188. }
  10189. } else if (isIdentifierStart(next)) {
  10190. ++this.state.pos;
  10191. this.finishToken(139, this.readWord1(next));
  10192. } else if (next === 92) {
  10193. ++this.state.pos;
  10194. this.finishToken(139, this.readWord1());
  10195. } else {
  10196. this.finishOp(27, 1);
  10197. }
  10198. }
  10199. readToken_dot() {
  10200. const next = this.input.charCodeAt(this.state.pos + 1);
  10201. if (next >= 48 && next <= 57) {
  10202. this.readNumber(true);
  10203. return;
  10204. }
  10205. if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
  10206. this.state.pos += 3;
  10207. this.finishToken(21);
  10208. } else {
  10209. ++this.state.pos;
  10210. this.finishToken(16);
  10211. }
  10212. }
  10213. readToken_slash() {
  10214. const next = this.input.charCodeAt(this.state.pos + 1);
  10215. if (next === 61) {
  10216. this.finishOp(31, 2);
  10217. } else {
  10218. this.finishOp(56, 1);
  10219. }
  10220. }
  10221. readToken_interpreter() {
  10222. if (this.state.pos !== 0 || this.length < 2) return false;
  10223. let ch = this.input.charCodeAt(this.state.pos + 1);
  10224. if (ch !== 33) return false;
  10225. const start = this.state.pos;
  10226. this.state.pos += 1;
  10227. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  10228. ch = this.input.charCodeAt(this.state.pos);
  10229. }
  10230. const value = this.input.slice(start + 2, this.state.pos);
  10231. this.finishToken(28, value);
  10232. return true;
  10233. }
  10234. readToken_mult_modulo(code) {
  10235. let type = code === 42 ? 55 : 54;
  10236. let width = 1;
  10237. let next = this.input.charCodeAt(this.state.pos + 1);
  10238. if (code === 42 && next === 42) {
  10239. width++;
  10240. next = this.input.charCodeAt(this.state.pos + 2);
  10241. type = 57;
  10242. }
  10243. if (next === 61 && !this.state.inType) {
  10244. width++;
  10245. type = code === 37 ? 33 : 30;
  10246. }
  10247. this.finishOp(type, width);
  10248. }
  10249. readToken_pipe_amp(code) {
  10250. const next = this.input.charCodeAt(this.state.pos + 1);
  10251. if (next === code) {
  10252. if (this.input.charCodeAt(this.state.pos + 2) === 61) {
  10253. this.finishOp(30, 3);
  10254. } else {
  10255. this.finishOp(code === 124 ? 41 : 42, 2);
  10256. }
  10257. return;
  10258. }
  10259. if (code === 124) {
  10260. if (next === 62) {
  10261. this.finishOp(39, 2);
  10262. return;
  10263. }
  10264. if (this.hasPlugin("recordAndTuple") && next === 125) {
  10265. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  10266. throw this.raise(Errors.RecordExpressionBarIncorrectEndSyntaxType, this.state.curPosition());
  10267. }
  10268. this.state.pos += 2;
  10269. this.finishToken(9);
  10270. return;
  10271. }
  10272. if (this.hasPlugin("recordAndTuple") && next === 93) {
  10273. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  10274. throw this.raise(Errors.TupleExpressionBarIncorrectEndSyntaxType, this.state.curPosition());
  10275. }
  10276. this.state.pos += 2;
  10277. this.finishToken(4);
  10278. return;
  10279. }
  10280. }
  10281. if (next === 61) {
  10282. this.finishOp(30, 2);
  10283. return;
  10284. }
  10285. this.finishOp(code === 124 ? 43 : 45, 1);
  10286. }
  10287. readToken_caret() {
  10288. const next = this.input.charCodeAt(this.state.pos + 1);
  10289. if (next === 61 && !this.state.inType) {
  10290. this.finishOp(32, 2);
  10291. } else if (next === 94 && this.hasPlugin(["pipelineOperator", {
  10292. proposal: "hack",
  10293. topicToken: "^^"
  10294. }])) {
  10295. this.finishOp(37, 2);
  10296. const lookaheadCh = this.input.codePointAt(this.state.pos);
  10297. if (lookaheadCh === 94) {
  10298. this.unexpected();
  10299. }
  10300. } else {
  10301. this.finishOp(44, 1);
  10302. }
  10303. }
  10304. readToken_atSign() {
  10305. const next = this.input.charCodeAt(this.state.pos + 1);
  10306. if (next === 64 && this.hasPlugin(["pipelineOperator", {
  10307. proposal: "hack",
  10308. topicToken: "@@"
  10309. }])) {
  10310. this.finishOp(38, 2);
  10311. } else {
  10312. this.finishOp(26, 1);
  10313. }
  10314. }
  10315. readToken_plus_min(code) {
  10316. const next = this.input.charCodeAt(this.state.pos + 1);
  10317. if (next === code) {
  10318. this.finishOp(34, 2);
  10319. return;
  10320. }
  10321. if (next === 61) {
  10322. this.finishOp(30, 2);
  10323. } else {
  10324. this.finishOp(53, 1);
  10325. }
  10326. }
  10327. readToken_lt() {
  10328. const {
  10329. pos
  10330. } = this.state;
  10331. const next = this.input.charCodeAt(pos + 1);
  10332. if (next === 60) {
  10333. if (this.input.charCodeAt(pos + 2) === 61) {
  10334. this.finishOp(30, 3);
  10335. return;
  10336. }
  10337. this.finishOp(51, 2);
  10338. return;
  10339. }
  10340. if (next === 61) {
  10341. this.finishOp(49, 2);
  10342. return;
  10343. }
  10344. this.finishOp(47, 1);
  10345. }
  10346. readToken_gt() {
  10347. const {
  10348. pos
  10349. } = this.state;
  10350. const next = this.input.charCodeAt(pos + 1);
  10351. if (next === 62) {
  10352. const size = this.input.charCodeAt(pos + 2) === 62 ? 3 : 2;
  10353. if (this.input.charCodeAt(pos + size) === 61) {
  10354. this.finishOp(30, size + 1);
  10355. return;
  10356. }
  10357. this.finishOp(52, size);
  10358. return;
  10359. }
  10360. if (next === 61) {
  10361. this.finishOp(49, 2);
  10362. return;
  10363. }
  10364. this.finishOp(48, 1);
  10365. }
  10366. readToken_eq_excl(code) {
  10367. const next = this.input.charCodeAt(this.state.pos + 1);
  10368. if (next === 61) {
  10369. this.finishOp(46, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  10370. return;
  10371. }
  10372. if (code === 61 && next === 62) {
  10373. this.state.pos += 2;
  10374. this.finishToken(19);
  10375. return;
  10376. }
  10377. this.finishOp(code === 61 ? 29 : 35, 1);
  10378. }
  10379. readToken_question() {
  10380. const next = this.input.charCodeAt(this.state.pos + 1);
  10381. const next2 = this.input.charCodeAt(this.state.pos + 2);
  10382. if (next === 63) {
  10383. if (next2 === 61) {
  10384. this.finishOp(30, 3);
  10385. } else {
  10386. this.finishOp(40, 2);
  10387. }
  10388. } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
  10389. this.state.pos += 2;
  10390. this.finishToken(18);
  10391. } else {
  10392. ++this.state.pos;
  10393. this.finishToken(17);
  10394. }
  10395. }
  10396. getTokenFromCode(code) {
  10397. switch (code) {
  10398. case 46:
  10399. this.readToken_dot();
  10400. return;
  10401. case 40:
  10402. ++this.state.pos;
  10403. this.finishToken(10);
  10404. return;
  10405. case 41:
  10406. ++this.state.pos;
  10407. this.finishToken(11);
  10408. return;
  10409. case 59:
  10410. ++this.state.pos;
  10411. this.finishToken(13);
  10412. return;
  10413. case 44:
  10414. ++this.state.pos;
  10415. this.finishToken(12);
  10416. return;
  10417. case 91:
  10418. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  10419. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  10420. throw this.raise(Errors.TupleExpressionBarIncorrectStartSyntaxType, this.state.curPosition());
  10421. }
  10422. this.state.pos += 2;
  10423. this.finishToken(2);
  10424. } else {
  10425. ++this.state.pos;
  10426. this.finishToken(0);
  10427. }
  10428. return;
  10429. case 93:
  10430. ++this.state.pos;
  10431. this.finishToken(3);
  10432. return;
  10433. case 123:
  10434. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  10435. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  10436. throw this.raise(Errors.RecordExpressionBarIncorrectStartSyntaxType, this.state.curPosition());
  10437. }
  10438. this.state.pos += 2;
  10439. this.finishToken(6);
  10440. } else {
  10441. ++this.state.pos;
  10442. this.finishToken(5);
  10443. }
  10444. return;
  10445. case 125:
  10446. ++this.state.pos;
  10447. this.finishToken(8);
  10448. return;
  10449. case 58:
  10450. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  10451. this.finishOp(15, 2);
  10452. } else {
  10453. ++this.state.pos;
  10454. this.finishToken(14);
  10455. }
  10456. return;
  10457. case 63:
  10458. this.readToken_question();
  10459. return;
  10460. case 96:
  10461. this.readTemplateToken();
  10462. return;
  10463. case 48:
  10464. {
  10465. const next = this.input.charCodeAt(this.state.pos + 1);
  10466. if (next === 120 || next === 88) {
  10467. this.readRadixNumber(16);
  10468. return;
  10469. }
  10470. if (next === 111 || next === 79) {
  10471. this.readRadixNumber(8);
  10472. return;
  10473. }
  10474. if (next === 98 || next === 66) {
  10475. this.readRadixNumber(2);
  10476. return;
  10477. }
  10478. }
  10479. case 49:
  10480. case 50:
  10481. case 51:
  10482. case 52:
  10483. case 53:
  10484. case 54:
  10485. case 55:
  10486. case 56:
  10487. case 57:
  10488. this.readNumber(false);
  10489. return;
  10490. case 34:
  10491. case 39:
  10492. this.readString(code);
  10493. return;
  10494. case 47:
  10495. this.readToken_slash();
  10496. return;
  10497. case 37:
  10498. case 42:
  10499. this.readToken_mult_modulo(code);
  10500. return;
  10501. case 124:
  10502. case 38:
  10503. this.readToken_pipe_amp(code);
  10504. return;
  10505. case 94:
  10506. this.readToken_caret();
  10507. return;
  10508. case 43:
  10509. case 45:
  10510. this.readToken_plus_min(code);
  10511. return;
  10512. case 60:
  10513. this.readToken_lt();
  10514. return;
  10515. case 62:
  10516. this.readToken_gt();
  10517. return;
  10518. case 61:
  10519. case 33:
  10520. this.readToken_eq_excl(code);
  10521. return;
  10522. case 126:
  10523. this.finishOp(36, 1);
  10524. return;
  10525. case 64:
  10526. this.readToken_atSign();
  10527. return;
  10528. case 35:
  10529. this.readToken_numberSign();
  10530. return;
  10531. case 92:
  10532. this.readWord();
  10533. return;
  10534. default:
  10535. if (isIdentifierStart(code)) {
  10536. this.readWord(code);
  10537. return;
  10538. }
  10539. }
  10540. throw this.raise(Errors.InvalidOrUnexpectedToken, this.state.curPosition(), {
  10541. unexpected: String.fromCodePoint(code)
  10542. });
  10543. }
  10544. finishOp(type, size) {
  10545. const str = this.input.slice(this.state.pos, this.state.pos + size);
  10546. this.state.pos += size;
  10547. this.finishToken(type, str);
  10548. }
  10549. readRegexp() {
  10550. const startLoc = this.state.startLoc;
  10551. const start = this.state.start + 1;
  10552. let escaped, inClass;
  10553. let {
  10554. pos
  10555. } = this.state;
  10556. for (;; ++pos) {
  10557. if (pos >= this.length) {
  10558. throw this.raise(Errors.UnterminatedRegExp, createPositionWithColumnOffset(startLoc, 1));
  10559. }
  10560. const ch = this.input.charCodeAt(pos);
  10561. if (isNewLine(ch)) {
  10562. throw this.raise(Errors.UnterminatedRegExp, createPositionWithColumnOffset(startLoc, 1));
  10563. }
  10564. if (escaped) {
  10565. escaped = false;
  10566. } else {
  10567. if (ch === 91) {
  10568. inClass = true;
  10569. } else if (ch === 93 && inClass) {
  10570. inClass = false;
  10571. } else if (ch === 47 && !inClass) {
  10572. break;
  10573. }
  10574. escaped = ch === 92;
  10575. }
  10576. }
  10577. const content = this.input.slice(start, pos);
  10578. ++pos;
  10579. let mods = "";
  10580. const nextPos = () => createPositionWithColumnOffset(startLoc, pos + 2 - start);
  10581. while (pos < this.length) {
  10582. const cp = this.codePointAtPos(pos);
  10583. const char = String.fromCharCode(cp);
  10584. if (VALID_REGEX_FLAGS.has(cp)) {
  10585. if (cp === 118) {
  10586. if (mods.includes("u")) {
  10587. this.raise(Errors.IncompatibleRegExpUVFlags, nextPos());
  10588. }
  10589. } else if (cp === 117) {
  10590. if (mods.includes("v")) {
  10591. this.raise(Errors.IncompatibleRegExpUVFlags, nextPos());
  10592. }
  10593. }
  10594. if (mods.includes(char)) {
  10595. this.raise(Errors.DuplicateRegExpFlags, nextPos());
  10596. }
  10597. } else if (isIdentifierChar(cp) || cp === 92) {
  10598. this.raise(Errors.MalformedRegExpFlags, nextPos());
  10599. } else {
  10600. break;
  10601. }
  10602. ++pos;
  10603. mods += char;
  10604. }
  10605. this.state.pos = pos;
  10606. this.finishToken(138, {
  10607. pattern: content,
  10608. flags: mods
  10609. });
  10610. }
  10611. readInt(radix, len, forceLen = false, allowNumSeparator = true) {
  10612. const {
  10613. n,
  10614. pos
  10615. } = readInt(this.input, this.state.pos, this.state.lineStart, this.state.curLine, radix, len, forceLen, allowNumSeparator, this.errorHandlers_readInt, false);
  10616. this.state.pos = pos;
  10617. return n;
  10618. }
  10619. readRadixNumber(radix) {
  10620. const start = this.state.pos;
  10621. const startLoc = this.state.curPosition();
  10622. let isBigInt = false;
  10623. this.state.pos += 2;
  10624. const val = this.readInt(radix);
  10625. if (val == null) {
  10626. this.raise(Errors.InvalidDigit, createPositionWithColumnOffset(startLoc, 2), {
  10627. radix
  10628. });
  10629. }
  10630. const next = this.input.charCodeAt(this.state.pos);
  10631. if (next === 110) {
  10632. ++this.state.pos;
  10633. isBigInt = true;
  10634. } else if (next === 109) {
  10635. throw this.raise(Errors.InvalidDecimal, startLoc);
  10636. }
  10637. if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
  10638. throw this.raise(Errors.NumberIdentifier, this.state.curPosition());
  10639. }
  10640. if (isBigInt) {
  10641. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  10642. this.finishToken(136, str);
  10643. return;
  10644. }
  10645. this.finishToken(135, val);
  10646. }
  10647. readNumber(startsWithDot) {
  10648. const start = this.state.pos;
  10649. const startLoc = this.state.curPosition();
  10650. let isFloat = false;
  10651. let isBigInt = false;
  10652. let hasExponent = false;
  10653. let isOctal = false;
  10654. if (!startsWithDot && this.readInt(10) === null) {
  10655. this.raise(Errors.InvalidNumber, this.state.curPosition());
  10656. }
  10657. const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  10658. if (hasLeadingZero) {
  10659. const integer = this.input.slice(start, this.state.pos);
  10660. this.recordStrictModeErrors(Errors.StrictOctalLiteral, startLoc);
  10661. if (!this.state.strict) {
  10662. const underscorePos = integer.indexOf("_");
  10663. if (underscorePos > 0) {
  10664. this.raise(Errors.ZeroDigitNumericSeparator, createPositionWithColumnOffset(startLoc, underscorePos));
  10665. }
  10666. }
  10667. isOctal = hasLeadingZero && !/[89]/.test(integer);
  10668. }
  10669. let next = this.input.charCodeAt(this.state.pos);
  10670. if (next === 46 && !isOctal) {
  10671. ++this.state.pos;
  10672. this.readInt(10);
  10673. isFloat = true;
  10674. next = this.input.charCodeAt(this.state.pos);
  10675. }
  10676. if ((next === 69 || next === 101) && !isOctal) {
  10677. next = this.input.charCodeAt(++this.state.pos);
  10678. if (next === 43 || next === 45) {
  10679. ++this.state.pos;
  10680. }
  10681. if (this.readInt(10) === null) {
  10682. this.raise(Errors.InvalidOrMissingExponent, startLoc);
  10683. }
  10684. isFloat = true;
  10685. hasExponent = true;
  10686. next = this.input.charCodeAt(this.state.pos);
  10687. }
  10688. if (next === 110) {
  10689. if (isFloat || hasLeadingZero) {
  10690. this.raise(Errors.InvalidBigIntLiteral, startLoc);
  10691. }
  10692. ++this.state.pos;
  10693. isBigInt = true;
  10694. }
  10695. if (next === 109) {
  10696. this.expectPlugin("decimal", this.state.curPosition());
  10697. if (hasExponent || hasLeadingZero) {
  10698. this.raise(Errors.InvalidDecimal, startLoc);
  10699. }
  10700. ++this.state.pos;
  10701. var isDecimal = true;
  10702. }
  10703. if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
  10704. throw this.raise(Errors.NumberIdentifier, this.state.curPosition());
  10705. }
  10706. const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, "");
  10707. if (isBigInt) {
  10708. this.finishToken(136, str);
  10709. return;
  10710. }
  10711. if (isDecimal) {
  10712. this.finishToken(137, str);
  10713. return;
  10714. }
  10715. const val = isOctal ? parseInt(str, 8) : parseFloat(str);
  10716. this.finishToken(135, val);
  10717. }
  10718. readCodePoint(throwOnInvalid) {
  10719. const {
  10720. code,
  10721. pos
  10722. } = readCodePoint(this.input, this.state.pos, this.state.lineStart, this.state.curLine, throwOnInvalid, this.errorHandlers_readCodePoint);
  10723. this.state.pos = pos;
  10724. return code;
  10725. }
  10726. readString(quote) {
  10727. const {
  10728. str,
  10729. pos,
  10730. curLine,
  10731. lineStart
  10732. } = readStringContents(quote === 34 ? "double" : "single", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_string);
  10733. this.state.pos = pos + 1;
  10734. this.state.lineStart = lineStart;
  10735. this.state.curLine = curLine;
  10736. this.finishToken(134, str);
  10737. }
  10738. readTemplateContinuation() {
  10739. if (!this.match(8)) {
  10740. this.unexpected(null, 8);
  10741. }
  10742. this.state.pos--;
  10743. this.readTemplateToken();
  10744. }
  10745. readTemplateToken() {
  10746. const opening = this.input[this.state.pos];
  10747. const {
  10748. str,
  10749. firstInvalidLoc,
  10750. pos,
  10751. curLine,
  10752. lineStart
  10753. } = readStringContents("template", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_template);
  10754. this.state.pos = pos + 1;
  10755. this.state.lineStart = lineStart;
  10756. this.state.curLine = curLine;
  10757. if (firstInvalidLoc) {
  10758. this.state.firstInvalidTemplateEscapePos = new Position(firstInvalidLoc.curLine, firstInvalidLoc.pos - firstInvalidLoc.lineStart, this.sourceToOffsetPos(firstInvalidLoc.pos));
  10759. }
  10760. if (this.input.codePointAt(pos) === 96) {
  10761. this.finishToken(24, firstInvalidLoc ? null : opening + str + "`");
  10762. } else {
  10763. this.state.pos++;
  10764. this.finishToken(25, firstInvalidLoc ? null : opening + str + "${");
  10765. }
  10766. }
  10767. recordStrictModeErrors(toParseError, at) {
  10768. const index = at.index;
  10769. if (this.state.strict && !this.state.strictErrors.has(index)) {
  10770. this.raise(toParseError, at);
  10771. } else {
  10772. this.state.strictErrors.set(index, [toParseError, at]);
  10773. }
  10774. }
  10775. readWord1(firstCode) {
  10776. this.state.containsEsc = false;
  10777. let word = "";
  10778. const start = this.state.pos;
  10779. let chunkStart = this.state.pos;
  10780. if (firstCode !== undefined) {
  10781. this.state.pos += firstCode <= 0xffff ? 1 : 2;
  10782. }
  10783. while (this.state.pos < this.length) {
  10784. const ch = this.codePointAtPos(this.state.pos);
  10785. if (isIdentifierChar(ch)) {
  10786. this.state.pos += ch <= 0xffff ? 1 : 2;
  10787. } else if (ch === 92) {
  10788. this.state.containsEsc = true;
  10789. word += this.input.slice(chunkStart, this.state.pos);
  10790. const escStart = this.state.curPosition();
  10791. const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
  10792. if (this.input.charCodeAt(++this.state.pos) !== 117) {
  10793. this.raise(Errors.MissingUnicodeEscape, this.state.curPosition());
  10794. chunkStart = this.state.pos - 1;
  10795. continue;
  10796. }
  10797. ++this.state.pos;
  10798. const esc = this.readCodePoint(true);
  10799. if (esc !== null) {
  10800. if (!identifierCheck(esc)) {
  10801. this.raise(Errors.EscapedCharNotAnIdentifier, escStart);
  10802. }
  10803. word += String.fromCodePoint(esc);
  10804. }
  10805. chunkStart = this.state.pos;
  10806. } else {
  10807. break;
  10808. }
  10809. }
  10810. return word + this.input.slice(chunkStart, this.state.pos);
  10811. }
  10812. readWord(firstCode) {
  10813. const word = this.readWord1(firstCode);
  10814. const type = keywords$1.get(word);
  10815. if (type !== undefined) {
  10816. this.finishToken(type, tokenLabelName(type));
  10817. } else {
  10818. this.finishToken(132, word);
  10819. }
  10820. }
  10821. checkKeywordEscapes() {
  10822. const {
  10823. type
  10824. } = this.state;
  10825. if (tokenIsKeyword(type) && this.state.containsEsc) {
  10826. this.raise(Errors.InvalidEscapedReservedWord, this.state.startLoc, {
  10827. reservedWord: tokenLabelName(type)
  10828. });
  10829. }
  10830. }
  10831. raise(toParseError, at, details = {}) {
  10832. const loc = at instanceof Position ? at : at.loc.start;
  10833. const error = toParseError(loc, details);
  10834. if (!(this.optionFlags & 2048)) throw error;
  10835. if (!this.isLookahead) this.state.errors.push(error);
  10836. return error;
  10837. }
  10838. raiseOverwrite(toParseError, at, details = {}) {
  10839. const loc = at instanceof Position ? at : at.loc.start;
  10840. const pos = loc.index;
  10841. const errors = this.state.errors;
  10842. for (let i = errors.length - 1; i >= 0; i--) {
  10843. const error = errors[i];
  10844. if (error.loc.index === pos) {
  10845. return errors[i] = toParseError(loc, details);
  10846. }
  10847. if (error.loc.index < pos) break;
  10848. }
  10849. return this.raise(toParseError, at, details);
  10850. }
  10851. updateContext(prevType) {}
  10852. unexpected(loc, type) {
  10853. throw this.raise(Errors.UnexpectedToken, loc != null ? loc : this.state.startLoc, {
  10854. expected: type ? tokenLabelName(type) : null
  10855. });
  10856. }
  10857. expectPlugin(pluginName, loc) {
  10858. if (this.hasPlugin(pluginName)) {
  10859. return true;
  10860. }
  10861. throw this.raise(Errors.MissingPlugin, loc != null ? loc : this.state.startLoc, {
  10862. missingPlugin: [pluginName]
  10863. });
  10864. }
  10865. expectOnePlugin(pluginNames) {
  10866. if (!pluginNames.some(name => this.hasPlugin(name))) {
  10867. throw this.raise(Errors.MissingOneOfPlugins, this.state.startLoc, {
  10868. missingPlugin: pluginNames
  10869. });
  10870. }
  10871. }
  10872. errorBuilder(error) {
  10873. return (pos, lineStart, curLine) => {
  10874. this.raise(error, buildPosition(pos, lineStart, curLine));
  10875. };
  10876. }
  10877. }
  10878. class ClassScope {
  10879. constructor() {
  10880. this.privateNames = new Set();
  10881. this.loneAccessors = new Map();
  10882. this.undefinedPrivateNames = new Map();
  10883. }
  10884. }
  10885. class ClassScopeHandler {
  10886. constructor(parser) {
  10887. this.parser = void 0;
  10888. this.stack = [];
  10889. this.undefinedPrivateNames = new Map();
  10890. this.parser = parser;
  10891. }
  10892. current() {
  10893. return this.stack[this.stack.length - 1];
  10894. }
  10895. enter() {
  10896. this.stack.push(new ClassScope());
  10897. }
  10898. exit() {
  10899. const oldClassScope = this.stack.pop();
  10900. const current = this.current();
  10901. for (const [name, loc] of Array.from(oldClassScope.undefinedPrivateNames)) {
  10902. if (current) {
  10903. if (!current.undefinedPrivateNames.has(name)) {
  10904. current.undefinedPrivateNames.set(name, loc);
  10905. }
  10906. } else {
  10907. this.parser.raise(Errors.InvalidPrivateFieldResolution, loc, {
  10908. identifierName: name
  10909. });
  10910. }
  10911. }
  10912. }
  10913. declarePrivateName(name, elementType, loc) {
  10914. const {
  10915. privateNames,
  10916. loneAccessors,
  10917. undefinedPrivateNames
  10918. } = this.current();
  10919. let redefined = privateNames.has(name);
  10920. if (elementType & 3) {
  10921. const accessor = redefined && loneAccessors.get(name);
  10922. if (accessor) {
  10923. const oldStatic = accessor & 4;
  10924. const newStatic = elementType & 4;
  10925. const oldKind = accessor & 3;
  10926. const newKind = elementType & 3;
  10927. redefined = oldKind === newKind || oldStatic !== newStatic;
  10928. if (!redefined) loneAccessors.delete(name);
  10929. } else if (!redefined) {
  10930. loneAccessors.set(name, elementType);
  10931. }
  10932. }
  10933. if (redefined) {
  10934. this.parser.raise(Errors.PrivateNameRedeclaration, loc, {
  10935. identifierName: name
  10936. });
  10937. }
  10938. privateNames.add(name);
  10939. undefinedPrivateNames.delete(name);
  10940. }
  10941. usePrivateName(name, loc) {
  10942. let classScope;
  10943. for (classScope of this.stack) {
  10944. if (classScope.privateNames.has(name)) return;
  10945. }
  10946. if (classScope) {
  10947. classScope.undefinedPrivateNames.set(name, loc);
  10948. } else {
  10949. this.parser.raise(Errors.InvalidPrivateFieldResolution, loc, {
  10950. identifierName: name
  10951. });
  10952. }
  10953. }
  10954. }
  10955. class ExpressionScope {
  10956. constructor(type = 0) {
  10957. this.type = type;
  10958. }
  10959. canBeArrowParameterDeclaration() {
  10960. return this.type === 2 || this.type === 1;
  10961. }
  10962. isCertainlyParameterDeclaration() {
  10963. return this.type === 3;
  10964. }
  10965. }
  10966. class ArrowHeadParsingScope extends ExpressionScope {
  10967. constructor(type) {
  10968. super(type);
  10969. this.declarationErrors = new Map();
  10970. }
  10971. recordDeclarationError(ParsingErrorClass, at) {
  10972. const index = at.index;
  10973. this.declarationErrors.set(index, [ParsingErrorClass, at]);
  10974. }
  10975. clearDeclarationError(index) {
  10976. this.declarationErrors.delete(index);
  10977. }
  10978. iterateErrors(iterator) {
  10979. this.declarationErrors.forEach(iterator);
  10980. }
  10981. }
  10982. class ExpressionScopeHandler {
  10983. constructor(parser) {
  10984. this.parser = void 0;
  10985. this.stack = [new ExpressionScope()];
  10986. this.parser = parser;
  10987. }
  10988. enter(scope) {
  10989. this.stack.push(scope);
  10990. }
  10991. exit() {
  10992. this.stack.pop();
  10993. }
  10994. recordParameterInitializerError(toParseError, node) {
  10995. const origin = node.loc.start;
  10996. const {
  10997. stack
  10998. } = this;
  10999. let i = stack.length - 1;
  11000. let scope = stack[i];
  11001. while (!scope.isCertainlyParameterDeclaration()) {
  11002. if (scope.canBeArrowParameterDeclaration()) {
  11003. scope.recordDeclarationError(toParseError, origin);
  11004. } else {
  11005. return;
  11006. }
  11007. scope = stack[--i];
  11008. }
  11009. this.parser.raise(toParseError, origin);
  11010. }
  11011. recordArrowParameterBindingError(error, node) {
  11012. const {
  11013. stack
  11014. } = this;
  11015. const scope = stack[stack.length - 1];
  11016. const origin = node.loc.start;
  11017. if (scope.isCertainlyParameterDeclaration()) {
  11018. this.parser.raise(error, origin);
  11019. } else if (scope.canBeArrowParameterDeclaration()) {
  11020. scope.recordDeclarationError(error, origin);
  11021. } else {
  11022. return;
  11023. }
  11024. }
  11025. recordAsyncArrowParametersError(at) {
  11026. const {
  11027. stack
  11028. } = this;
  11029. let i = stack.length - 1;
  11030. let scope = stack[i];
  11031. while (scope.canBeArrowParameterDeclaration()) {
  11032. if (scope.type === 2) {
  11033. scope.recordDeclarationError(Errors.AwaitBindingIdentifier, at);
  11034. }
  11035. scope = stack[--i];
  11036. }
  11037. }
  11038. validateAsPattern() {
  11039. const {
  11040. stack
  11041. } = this;
  11042. const currentScope = stack[stack.length - 1];
  11043. if (!currentScope.canBeArrowParameterDeclaration()) return;
  11044. currentScope.iterateErrors(([toParseError, loc]) => {
  11045. this.parser.raise(toParseError, loc);
  11046. let i = stack.length - 2;
  11047. let scope = stack[i];
  11048. while (scope.canBeArrowParameterDeclaration()) {
  11049. scope.clearDeclarationError(loc.index);
  11050. scope = stack[--i];
  11051. }
  11052. });
  11053. }
  11054. }
  11055. function newParameterDeclarationScope() {
  11056. return new ExpressionScope(3);
  11057. }
  11058. function newArrowHeadScope() {
  11059. return new ArrowHeadParsingScope(1);
  11060. }
  11061. function newAsyncArrowScope() {
  11062. return new ArrowHeadParsingScope(2);
  11063. }
  11064. function newExpressionScope() {
  11065. return new ExpressionScope();
  11066. }
  11067. class UtilParser extends Tokenizer {
  11068. addExtra(node, key, value, enumerable = true) {
  11069. if (!node) return;
  11070. let {
  11071. extra
  11072. } = node;
  11073. if (extra == null) {
  11074. extra = {};
  11075. node.extra = extra;
  11076. }
  11077. if (enumerable) {
  11078. extra[key] = value;
  11079. } else {
  11080. Object.defineProperty(extra, key, {
  11081. enumerable,
  11082. value
  11083. });
  11084. }
  11085. }
  11086. isContextual(token) {
  11087. return this.state.type === token && !this.state.containsEsc;
  11088. }
  11089. isUnparsedContextual(nameStart, name) {
  11090. if (this.input.startsWith(name, nameStart)) {
  11091. const nextCh = this.input.charCodeAt(nameStart + name.length);
  11092. return !(isIdentifierChar(nextCh) || (nextCh & 0xfc00) === 0xd800);
  11093. }
  11094. return false;
  11095. }
  11096. isLookaheadContextual(name) {
  11097. const next = this.nextTokenStart();
  11098. return this.isUnparsedContextual(next, name);
  11099. }
  11100. eatContextual(token) {
  11101. if (this.isContextual(token)) {
  11102. this.next();
  11103. return true;
  11104. }
  11105. return false;
  11106. }
  11107. expectContextual(token, toParseError) {
  11108. if (!this.eatContextual(token)) {
  11109. if (toParseError != null) {
  11110. throw this.raise(toParseError, this.state.startLoc);
  11111. }
  11112. this.unexpected(null, token);
  11113. }
  11114. }
  11115. canInsertSemicolon() {
  11116. return this.match(140) || this.match(8) || this.hasPrecedingLineBreak();
  11117. }
  11118. hasPrecedingLineBreak() {
  11119. return hasNewLine(this.input, this.offsetToSourcePos(this.state.lastTokEndLoc.index), this.state.start);
  11120. }
  11121. hasFollowingLineBreak() {
  11122. return hasNewLine(this.input, this.state.end, this.nextTokenStart());
  11123. }
  11124. isLineTerminator() {
  11125. return this.eat(13) || this.canInsertSemicolon();
  11126. }
  11127. semicolon(allowAsi = true) {
  11128. if (allowAsi ? this.isLineTerminator() : this.eat(13)) return;
  11129. this.raise(Errors.MissingSemicolon, this.state.lastTokEndLoc);
  11130. }
  11131. expect(type, loc) {
  11132. if (!this.eat(type)) {
  11133. this.unexpected(loc, type);
  11134. }
  11135. }
  11136. tryParse(fn, oldState = this.state.clone()) {
  11137. const abortSignal = {
  11138. node: null
  11139. };
  11140. try {
  11141. const node = fn((node = null) => {
  11142. abortSignal.node = node;
  11143. throw abortSignal;
  11144. });
  11145. if (this.state.errors.length > oldState.errors.length) {
  11146. const failState = this.state;
  11147. this.state = oldState;
  11148. this.state.tokensLength = failState.tokensLength;
  11149. return {
  11150. node,
  11151. error: failState.errors[oldState.errors.length],
  11152. thrown: false,
  11153. aborted: false,
  11154. failState
  11155. };
  11156. }
  11157. return {
  11158. node: node,
  11159. error: null,
  11160. thrown: false,
  11161. aborted: false,
  11162. failState: null
  11163. };
  11164. } catch (error) {
  11165. const failState = this.state;
  11166. this.state = oldState;
  11167. if (error instanceof SyntaxError) {
  11168. return {
  11169. node: null,
  11170. error,
  11171. thrown: true,
  11172. aborted: false,
  11173. failState
  11174. };
  11175. }
  11176. if (error === abortSignal) {
  11177. return {
  11178. node: abortSignal.node,
  11179. error: null,
  11180. thrown: false,
  11181. aborted: true,
  11182. failState
  11183. };
  11184. }
  11185. throw error;
  11186. }
  11187. }
  11188. checkExpressionErrors(refExpressionErrors, andThrow) {
  11189. if (!refExpressionErrors) return false;
  11190. const {
  11191. shorthandAssignLoc,
  11192. doubleProtoLoc,
  11193. privateKeyLoc,
  11194. optionalParametersLoc,
  11195. voidPatternLoc
  11196. } = refExpressionErrors;
  11197. const hasErrors = !!shorthandAssignLoc || !!doubleProtoLoc || !!optionalParametersLoc || !!privateKeyLoc || !!voidPatternLoc;
  11198. if (!andThrow) {
  11199. return hasErrors;
  11200. }
  11201. if (shorthandAssignLoc != null) {
  11202. this.raise(Errors.InvalidCoverInitializedName, shorthandAssignLoc);
  11203. }
  11204. if (doubleProtoLoc != null) {
  11205. this.raise(Errors.DuplicateProto, doubleProtoLoc);
  11206. }
  11207. if (privateKeyLoc != null) {
  11208. this.raise(Errors.UnexpectedPrivateField, privateKeyLoc);
  11209. }
  11210. if (optionalParametersLoc != null) {
  11211. this.unexpected(optionalParametersLoc);
  11212. }
  11213. if (voidPatternLoc != null) {
  11214. this.raise(Errors.InvalidCoverDiscardElement, voidPatternLoc);
  11215. }
  11216. }
  11217. isLiteralPropertyName() {
  11218. return tokenIsLiteralPropertyName(this.state.type);
  11219. }
  11220. isPrivateName(node) {
  11221. return node.type === "PrivateName";
  11222. }
  11223. getPrivateNameSV(node) {
  11224. return node.id.name;
  11225. }
  11226. hasPropertyAsPrivateName(node) {
  11227. return (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && this.isPrivateName(node.property);
  11228. }
  11229. isObjectProperty(node) {
  11230. return node.type === "ObjectProperty";
  11231. }
  11232. isObjectMethod(node) {
  11233. return node.type === "ObjectMethod";
  11234. }
  11235. initializeScopes(inModule = this.options.sourceType === "module") {
  11236. const oldLabels = this.state.labels;
  11237. this.state.labels = [];
  11238. const oldExportedIdentifiers = this.exportedIdentifiers;
  11239. this.exportedIdentifiers = new Set();
  11240. const oldInModule = this.inModule;
  11241. this.inModule = inModule;
  11242. const oldScope = this.scope;
  11243. const ScopeHandler = this.getScopeHandler();
  11244. this.scope = new ScopeHandler(this, inModule);
  11245. const oldProdParam = this.prodParam;
  11246. this.prodParam = new ProductionParameterHandler();
  11247. const oldClassScope = this.classScope;
  11248. this.classScope = new ClassScopeHandler(this);
  11249. const oldExpressionScope = this.expressionScope;
  11250. this.expressionScope = new ExpressionScopeHandler(this);
  11251. return () => {
  11252. this.state.labels = oldLabels;
  11253. this.exportedIdentifiers = oldExportedIdentifiers;
  11254. this.inModule = oldInModule;
  11255. this.scope = oldScope;
  11256. this.prodParam = oldProdParam;
  11257. this.classScope = oldClassScope;
  11258. this.expressionScope = oldExpressionScope;
  11259. };
  11260. }
  11261. enterInitialScopes() {
  11262. let paramFlags = 0;
  11263. if (this.inModule || this.optionFlags & 1) {
  11264. paramFlags |= 2;
  11265. }
  11266. if (this.optionFlags & 32) {
  11267. paramFlags |= 1;
  11268. }
  11269. const isCommonJS = !this.inModule && this.options.sourceType === "commonjs";
  11270. if (isCommonJS || this.optionFlags & 2) {
  11271. paramFlags |= 4;
  11272. }
  11273. this.prodParam.enter(paramFlags);
  11274. let scopeFlags = isCommonJS ? 514 : 1;
  11275. if (this.optionFlags & 4) {
  11276. scopeFlags |= 512;
  11277. }
  11278. this.scope.enter(scopeFlags);
  11279. }
  11280. checkDestructuringPrivate(refExpressionErrors) {
  11281. const {
  11282. privateKeyLoc
  11283. } = refExpressionErrors;
  11284. if (privateKeyLoc !== null) {
  11285. this.expectPlugin("destructuringPrivate", privateKeyLoc);
  11286. }
  11287. }
  11288. }
  11289. class ExpressionErrors {
  11290. constructor() {
  11291. this.shorthandAssignLoc = null;
  11292. this.doubleProtoLoc = null;
  11293. this.privateKeyLoc = null;
  11294. this.optionalParametersLoc = null;
  11295. this.voidPatternLoc = null;
  11296. }
  11297. }
  11298. class Node {
  11299. constructor(parser, pos, loc) {
  11300. this.type = "";
  11301. this.start = pos;
  11302. this.end = 0;
  11303. this.loc = new SourceLocation(loc);
  11304. if ((parser == null ? void 0 : parser.optionFlags) & 128) this.range = [pos, 0];
  11305. if (parser != null && parser.filename) this.loc.filename = parser.filename;
  11306. }
  11307. }
  11308. const NodePrototype = Node.prototype;
  11309. NodePrototype.__clone = function () {
  11310. const newNode = new Node(undefined, this.start, this.loc.start);
  11311. const keys = Object.keys(this);
  11312. for (let i = 0, length = keys.length; i < length; i++) {
  11313. const key = keys[i];
  11314. if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
  11315. newNode[key] = this[key];
  11316. }
  11317. }
  11318. return newNode;
  11319. };
  11320. class NodeUtils extends UtilParser {
  11321. startNode() {
  11322. const loc = this.state.startLoc;
  11323. return new Node(this, loc.index, loc);
  11324. }
  11325. startNodeAt(loc) {
  11326. return new Node(this, loc.index, loc);
  11327. }
  11328. startNodeAtNode(type) {
  11329. return this.startNodeAt(type.loc.start);
  11330. }
  11331. finishNode(node, type) {
  11332. return this.finishNodeAt(node, type, this.state.lastTokEndLoc);
  11333. }
  11334. finishNodeAt(node, type, endLoc) {
  11335. node.type = type;
  11336. node.end = endLoc.index;
  11337. node.loc.end = endLoc;
  11338. if (this.optionFlags & 128) node.range[1] = endLoc.index;
  11339. if (this.optionFlags & 4096) {
  11340. this.processComment(node);
  11341. }
  11342. return node;
  11343. }
  11344. resetStartLocation(node, startLoc) {
  11345. node.start = startLoc.index;
  11346. node.loc.start = startLoc;
  11347. if (this.optionFlags & 128) node.range[0] = startLoc.index;
  11348. }
  11349. resetEndLocation(node, endLoc = this.state.lastTokEndLoc) {
  11350. node.end = endLoc.index;
  11351. node.loc.end = endLoc;
  11352. if (this.optionFlags & 128) node.range[1] = endLoc.index;
  11353. }
  11354. resetStartLocationFromNode(node, locationNode) {
  11355. this.resetStartLocation(node, locationNode.loc.start);
  11356. }
  11357. castNodeTo(node, type) {
  11358. node.type = type;
  11359. return node;
  11360. }
  11361. cloneIdentifier(node) {
  11362. const {
  11363. type,
  11364. start,
  11365. end,
  11366. loc,
  11367. range,
  11368. name
  11369. } = node;
  11370. const cloned = Object.create(NodePrototype);
  11371. cloned.type = type;
  11372. cloned.start = start;
  11373. cloned.end = end;
  11374. cloned.loc = loc;
  11375. cloned.range = range;
  11376. cloned.name = name;
  11377. if (node.extra) cloned.extra = node.extra;
  11378. return cloned;
  11379. }
  11380. cloneStringLiteral(node) {
  11381. const {
  11382. type,
  11383. start,
  11384. end,
  11385. loc,
  11386. range,
  11387. extra
  11388. } = node;
  11389. const cloned = Object.create(NodePrototype);
  11390. cloned.type = type;
  11391. cloned.start = start;
  11392. cloned.end = end;
  11393. cloned.loc = loc;
  11394. cloned.range = range;
  11395. cloned.extra = extra;
  11396. cloned.value = node.value;
  11397. return cloned;
  11398. }
  11399. }
  11400. const unwrapParenthesizedExpression = node => {
  11401. return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
  11402. };
  11403. class LValParser extends NodeUtils {
  11404. toAssignable(node, isLHS = false) {
  11405. var _node$extra, _node$extra3;
  11406. let parenthesized = undefined;
  11407. if (node.type === "ParenthesizedExpression" || (_node$extra = node.extra) != null && _node$extra.parenthesized) {
  11408. parenthesized = unwrapParenthesizedExpression(node);
  11409. if (isLHS) {
  11410. if (parenthesized.type === "Identifier") {
  11411. this.expressionScope.recordArrowParameterBindingError(Errors.InvalidParenthesizedAssignment, node);
  11412. } else if (parenthesized.type !== "CallExpression" && parenthesized.type !== "MemberExpression" && !this.isOptionalMemberExpression(parenthesized)) {
  11413. this.raise(Errors.InvalidParenthesizedAssignment, node);
  11414. }
  11415. } else {
  11416. this.raise(Errors.InvalidParenthesizedAssignment, node);
  11417. }
  11418. }
  11419. switch (node.type) {
  11420. case "Identifier":
  11421. case "ObjectPattern":
  11422. case "ArrayPattern":
  11423. case "AssignmentPattern":
  11424. case "RestElement":
  11425. case "VoidPattern":
  11426. break;
  11427. case "ObjectExpression":
  11428. this.castNodeTo(node, "ObjectPattern");
  11429. for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
  11430. var _node$extra2;
  11431. const prop = node.properties[i];
  11432. const isLast = i === last;
  11433. this.toAssignableObjectExpressionProp(prop, isLast, isLHS);
  11434. if (isLast && prop.type === "RestElement" && (_node$extra2 = node.extra) != null && _node$extra2.trailingCommaLoc) {
  11435. this.raise(Errors.RestTrailingComma, node.extra.trailingCommaLoc);
  11436. }
  11437. }
  11438. break;
  11439. case "ObjectProperty":
  11440. {
  11441. const {
  11442. key,
  11443. value
  11444. } = node;
  11445. if (this.isPrivateName(key)) {
  11446. this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start);
  11447. }
  11448. this.toAssignable(value, isLHS);
  11449. break;
  11450. }
  11451. case "SpreadElement":
  11452. {
  11453. throw new Error("Internal @babel/parser error (this is a bug, please report it)." + " SpreadElement should be converted by .toAssignable's caller.");
  11454. }
  11455. case "ArrayExpression":
  11456. this.castNodeTo(node, "ArrayPattern");
  11457. this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingCommaLoc, isLHS);
  11458. break;
  11459. case "AssignmentExpression":
  11460. if (node.operator !== "=") {
  11461. this.raise(Errors.MissingEqInAssignment, node.left.loc.end);
  11462. }
  11463. this.castNodeTo(node, "AssignmentPattern");
  11464. delete node.operator;
  11465. if (node.left.type === "VoidPattern") {
  11466. this.raise(Errors.VoidPatternInitializer, node.left);
  11467. }
  11468. this.toAssignable(node.left, isLHS);
  11469. break;
  11470. case "ParenthesizedExpression":
  11471. this.toAssignable(parenthesized, isLHS);
  11472. break;
  11473. }
  11474. }
  11475. toAssignableObjectExpressionProp(prop, isLast, isLHS) {
  11476. if (prop.type === "ObjectMethod") {
  11477. this.raise(prop.kind === "get" || prop.kind === "set" ? Errors.PatternHasAccessor : Errors.PatternHasMethod, prop.key);
  11478. } else if (prop.type === "SpreadElement") {
  11479. this.castNodeTo(prop, "RestElement");
  11480. const arg = prop.argument;
  11481. this.checkToRestConversion(arg, false);
  11482. this.toAssignable(arg, isLHS);
  11483. if (!isLast) {
  11484. this.raise(Errors.RestTrailingComma, prop);
  11485. }
  11486. } else {
  11487. this.toAssignable(prop, isLHS);
  11488. }
  11489. }
  11490. toAssignableList(exprList, trailingCommaLoc, isLHS) {
  11491. const end = exprList.length - 1;
  11492. for (let i = 0; i <= end; i++) {
  11493. const elt = exprList[i];
  11494. if (!elt) continue;
  11495. this.toAssignableListItem(exprList, i, isLHS);
  11496. if (elt.type === "RestElement") {
  11497. if (i < end) {
  11498. this.raise(Errors.RestTrailingComma, elt);
  11499. } else if (trailingCommaLoc) {
  11500. this.raise(Errors.RestTrailingComma, trailingCommaLoc);
  11501. }
  11502. }
  11503. }
  11504. }
  11505. toAssignableListItem(exprList, index, isLHS) {
  11506. const node = exprList[index];
  11507. if (node.type === "SpreadElement") {
  11508. this.castNodeTo(node, "RestElement");
  11509. const arg = node.argument;
  11510. this.checkToRestConversion(arg, true);
  11511. this.toAssignable(arg, isLHS);
  11512. } else {
  11513. this.toAssignable(node, isLHS);
  11514. }
  11515. }
  11516. isAssignable(node, isBinding) {
  11517. switch (node.type) {
  11518. case "Identifier":
  11519. case "ObjectPattern":
  11520. case "ArrayPattern":
  11521. case "AssignmentPattern":
  11522. case "RestElement":
  11523. case "VoidPattern":
  11524. return true;
  11525. case "ObjectExpression":
  11526. {
  11527. const last = node.properties.length - 1;
  11528. return node.properties.every((prop, i) => {
  11529. return prop.type !== "ObjectMethod" && (i === last || prop.type !== "SpreadElement") && this.isAssignable(prop);
  11530. });
  11531. }
  11532. case "ObjectProperty":
  11533. return this.isAssignable(node.value);
  11534. case "SpreadElement":
  11535. return this.isAssignable(node.argument);
  11536. case "ArrayExpression":
  11537. return node.elements.every(element => element === null || this.isAssignable(element));
  11538. case "AssignmentExpression":
  11539. return node.operator === "=";
  11540. case "ParenthesizedExpression":
  11541. return this.isAssignable(node.expression);
  11542. case "MemberExpression":
  11543. case "OptionalMemberExpression":
  11544. return !isBinding;
  11545. default:
  11546. return false;
  11547. }
  11548. }
  11549. toReferencedList(exprList, isParenthesizedExpr) {
  11550. return exprList;
  11551. }
  11552. toReferencedListDeep(exprList, isParenthesizedExpr) {
  11553. this.toReferencedList(exprList, isParenthesizedExpr);
  11554. for (const expr of exprList) {
  11555. if ((expr == null ? void 0 : expr.type) === "ArrayExpression") {
  11556. this.toReferencedListDeep(expr.elements);
  11557. }
  11558. }
  11559. }
  11560. parseSpread(refExpressionErrors) {
  11561. const node = this.startNode();
  11562. this.next();
  11563. node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined);
  11564. return this.finishNode(node, "SpreadElement");
  11565. }
  11566. parseRestBinding() {
  11567. const node = this.startNode();
  11568. this.next();
  11569. const argument = this.parseBindingAtom();
  11570. if (argument.type === "VoidPattern") {
  11571. this.raise(Errors.UnexpectedVoidPattern, argument);
  11572. }
  11573. node.argument = argument;
  11574. return this.finishNode(node, "RestElement");
  11575. }
  11576. parseBindingAtom() {
  11577. switch (this.state.type) {
  11578. case 0:
  11579. {
  11580. const node = this.startNode();
  11581. this.next();
  11582. node.elements = this.parseBindingList(3, 93, 1);
  11583. return this.finishNode(node, "ArrayPattern");
  11584. }
  11585. case 5:
  11586. return this.parseObjectLike(8, true);
  11587. case 88:
  11588. return this.parseVoidPattern(null);
  11589. }
  11590. return this.parseIdentifier();
  11591. }
  11592. parseBindingList(close, closeCharCode, flags) {
  11593. const allowEmpty = flags & 1;
  11594. const elts = [];
  11595. let first = true;
  11596. while (!this.eat(close)) {
  11597. if (first) {
  11598. first = false;
  11599. } else {
  11600. this.expect(12);
  11601. }
  11602. if (allowEmpty && this.match(12)) {
  11603. elts.push(null);
  11604. } else if (this.eat(close)) {
  11605. break;
  11606. } else if (this.match(21)) {
  11607. let rest = this.parseRestBinding();
  11608. if (this.hasPlugin("flow") || flags & 2) {
  11609. rest = this.parseFunctionParamType(rest);
  11610. }
  11611. elts.push(rest);
  11612. if (!this.checkCommaAfterRest(closeCharCode)) {
  11613. this.expect(close);
  11614. break;
  11615. }
  11616. } else {
  11617. const decorators = [];
  11618. if (flags & 2) {
  11619. if (this.match(26) && this.hasPlugin("decorators")) {
  11620. this.raise(Errors.UnsupportedParameterDecorator, this.state.startLoc);
  11621. }
  11622. while (this.match(26)) {
  11623. decorators.push(this.parseDecorator());
  11624. }
  11625. }
  11626. elts.push(this.parseBindingElement(flags, decorators));
  11627. }
  11628. }
  11629. return elts;
  11630. }
  11631. parseBindingRestProperty(prop) {
  11632. this.next();
  11633. if (this.hasPlugin("discardBinding") && this.match(88)) {
  11634. prop.argument = this.parseVoidPattern(null);
  11635. this.raise(Errors.UnexpectedVoidPattern, prop.argument);
  11636. } else {
  11637. prop.argument = this.parseIdentifier();
  11638. }
  11639. this.checkCommaAfterRest(125);
  11640. return this.finishNode(prop, "RestElement");
  11641. }
  11642. parseBindingProperty() {
  11643. const {
  11644. type,
  11645. startLoc
  11646. } = this.state;
  11647. if (type === 21) {
  11648. return this.parseBindingRestProperty(this.startNode());
  11649. }
  11650. const prop = this.startNode();
  11651. if (type === 139) {
  11652. this.expectPlugin("destructuringPrivate", startLoc);
  11653. this.classScope.usePrivateName(this.state.value, startLoc);
  11654. prop.key = this.parsePrivateName();
  11655. } else {
  11656. this.parsePropertyName(prop);
  11657. }
  11658. prop.method = false;
  11659. return this.parseObjPropValue(prop, startLoc, false, false, true, false);
  11660. }
  11661. parseBindingElement(flags, decorators) {
  11662. const left = this.parseMaybeDefault();
  11663. if (this.hasPlugin("flow") || flags & 2) {
  11664. this.parseFunctionParamType(left);
  11665. }
  11666. if (decorators.length) {
  11667. left.decorators = decorators;
  11668. this.resetStartLocationFromNode(left, decorators[0]);
  11669. }
  11670. const elt = this.parseMaybeDefault(left.loc.start, left);
  11671. return elt;
  11672. }
  11673. parseFunctionParamType(param) {
  11674. return param;
  11675. }
  11676. parseMaybeDefault(startLoc, left) {
  11677. startLoc != null ? startLoc : startLoc = this.state.startLoc;
  11678. left = left != null ? left : this.parseBindingAtom();
  11679. if (!this.eat(29)) return left;
  11680. const node = this.startNodeAt(startLoc);
  11681. if (left.type === "VoidPattern") {
  11682. this.raise(Errors.VoidPatternInitializer, left);
  11683. }
  11684. node.left = left;
  11685. node.right = this.parseMaybeAssignAllowIn();
  11686. return this.finishNode(node, "AssignmentPattern");
  11687. }
  11688. isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding) {
  11689. switch (type) {
  11690. case "AssignmentPattern":
  11691. return "left";
  11692. case "RestElement":
  11693. return "argument";
  11694. case "ObjectProperty":
  11695. return "value";
  11696. case "ParenthesizedExpression":
  11697. return "expression";
  11698. case "ArrayPattern":
  11699. return "elements";
  11700. case "ObjectPattern":
  11701. return "properties";
  11702. case "VoidPattern":
  11703. return true;
  11704. case "CallExpression":
  11705. if (!disallowCallExpression && !this.state.strict && this.optionFlags & 8192) {
  11706. return true;
  11707. }
  11708. }
  11709. return false;
  11710. }
  11711. isOptionalMemberExpression(expression) {
  11712. return expression.type === "OptionalMemberExpression";
  11713. }
  11714. checkLVal(expression, ancestor, binding = 64, checkClashes = false, strictModeChanged = false, hasParenthesizedAncestor = false, disallowCallExpression = false) {
  11715. var _expression$extra;
  11716. const type = expression.type;
  11717. if (this.isObjectMethod(expression)) return;
  11718. const isOptionalMemberExpression = this.isOptionalMemberExpression(expression);
  11719. if (isOptionalMemberExpression || type === "MemberExpression") {
  11720. if (isOptionalMemberExpression) {
  11721. this.expectPlugin("optionalChainingAssign", expression.loc.start);
  11722. if (ancestor.type !== "AssignmentExpression") {
  11723. this.raise(Errors.InvalidLhsOptionalChaining, expression, {
  11724. ancestor
  11725. });
  11726. }
  11727. }
  11728. if (binding !== 64) {
  11729. this.raise(Errors.InvalidPropertyBindingPattern, expression);
  11730. }
  11731. return;
  11732. }
  11733. if (type === "Identifier") {
  11734. this.checkIdentifier(expression, binding, strictModeChanged);
  11735. const {
  11736. name
  11737. } = expression;
  11738. if (checkClashes) {
  11739. if (checkClashes.has(name)) {
  11740. this.raise(Errors.ParamDupe, expression);
  11741. } else {
  11742. checkClashes.add(name);
  11743. }
  11744. }
  11745. return;
  11746. } else if (type === "VoidPattern" && ancestor.type === "CatchClause") {
  11747. this.raise(Errors.VoidPatternCatchClauseParam, expression);
  11748. }
  11749. const unwrappedExpression = unwrapParenthesizedExpression(expression);
  11750. disallowCallExpression || (disallowCallExpression = unwrappedExpression.type === "CallExpression" && (unwrappedExpression.callee.type === "Import" || unwrappedExpression.callee.type === "Super"));
  11751. const validity = this.isValidLVal(type, disallowCallExpression, !(hasParenthesizedAncestor || (_expression$extra = expression.extra) != null && _expression$extra.parenthesized) && ancestor.type === "AssignmentExpression", binding);
  11752. if (validity === true) return;
  11753. if (validity === false) {
  11754. const ParseErrorClass = binding === 64 ? Errors.InvalidLhs : Errors.InvalidLhsBinding;
  11755. this.raise(ParseErrorClass, expression, {
  11756. ancestor
  11757. });
  11758. return;
  11759. }
  11760. let key, isParenthesizedExpression;
  11761. if (typeof validity === "string") {
  11762. key = validity;
  11763. isParenthesizedExpression = type === "ParenthesizedExpression";
  11764. } else {
  11765. [key, isParenthesizedExpression] = validity;
  11766. }
  11767. const nextAncestor = type === "ArrayPattern" || type === "ObjectPattern" ? {
  11768. type
  11769. } : ancestor;
  11770. const val = expression[key];
  11771. if (Array.isArray(val)) {
  11772. for (const child of val) {
  11773. if (child) {
  11774. this.checkLVal(child, nextAncestor, binding, checkClashes, strictModeChanged, isParenthesizedExpression, true);
  11775. }
  11776. }
  11777. } else if (val) {
  11778. this.checkLVal(val, nextAncestor, binding, checkClashes, strictModeChanged, isParenthesizedExpression, disallowCallExpression);
  11779. }
  11780. }
  11781. checkIdentifier(at, bindingType, strictModeChanged = false) {
  11782. if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(at.name, this.inModule) : isStrictBindOnlyReservedWord(at.name))) {
  11783. if (bindingType === 64) {
  11784. this.raise(Errors.StrictEvalArguments, at, {
  11785. referenceName: at.name
  11786. });
  11787. } else {
  11788. this.raise(Errors.StrictEvalArgumentsBinding, at, {
  11789. bindingName: at.name
  11790. });
  11791. }
  11792. }
  11793. if (bindingType & 8192 && at.name === "let") {
  11794. this.raise(Errors.LetInLexicalBinding, at);
  11795. }
  11796. if (!(bindingType & 64)) {
  11797. this.declareNameFromIdentifier(at, bindingType);
  11798. }
  11799. }
  11800. declareNameFromIdentifier(identifier, binding) {
  11801. this.scope.declareName(identifier.name, binding, identifier.loc.start);
  11802. }
  11803. checkToRestConversion(node, allowPattern) {
  11804. switch (node.type) {
  11805. case "ParenthesizedExpression":
  11806. this.checkToRestConversion(node.expression, allowPattern);
  11807. break;
  11808. case "Identifier":
  11809. case "MemberExpression":
  11810. break;
  11811. case "ArrayExpression":
  11812. case "ObjectExpression":
  11813. if (allowPattern) break;
  11814. default:
  11815. this.raise(Errors.InvalidRestAssignmentPattern, node);
  11816. }
  11817. }
  11818. checkCommaAfterRest(close) {
  11819. if (!this.match(12)) {
  11820. return false;
  11821. }
  11822. this.raise(this.lookaheadCharCode() === close ? Errors.RestTrailingComma : Errors.ElementAfterRest, this.state.startLoc);
  11823. return true;
  11824. }
  11825. }
  11826. const keywordAndTSRelationalOperator = /in(?:stanceof)?|as|satisfies/y;
  11827. function nonNull(x) {
  11828. if (x == null) {
  11829. throw new Error(`Unexpected ${x} value.`);
  11830. }
  11831. return x;
  11832. }
  11833. function assert(x) {
  11834. if (!x) {
  11835. throw new Error("Assert fail");
  11836. }
  11837. }
  11838. const TSErrors = ParseErrorEnum`typescript`({
  11839. AbstractMethodHasImplementation: ({
  11840. methodName
  11841. }) => `Method '${methodName}' cannot have an implementation because it is marked abstract.`,
  11842. AbstractPropertyHasInitializer: ({
  11843. propertyName
  11844. }) => `Property '${propertyName}' cannot have an initializer because it is marked abstract.`,
  11845. AccessorCannotBeOptional: "An 'accessor' property cannot be declared optional.",
  11846. AccessorCannotDeclareThisParameter: "'get' and 'set' accessors cannot declare 'this' parameters.",
  11847. AccessorCannotHaveTypeParameters: "An accessor cannot have type parameters.",
  11848. ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier.",
  11849. ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier.",
  11850. ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference: "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.",
  11851. ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.",
  11852. DeclareAccessor: ({
  11853. kind
  11854. }) => `'declare' is not allowed in ${kind}ters.`,
  11855. DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.",
  11856. DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.",
  11857. DuplicateAccessibilityModifier: ({
  11858. modifier
  11859. }) => `Accessibility modifier already seen: '${modifier}'.`,
  11860. DuplicateModifier: ({
  11861. modifier
  11862. }) => `Duplicate modifier: '${modifier}'.`,
  11863. EmptyHeritageClauseType: ({
  11864. token
  11865. }) => `'${token}' list cannot be empty.`,
  11866. EmptyTypeArguments: "Type argument list cannot be empty.",
  11867. EmptyTypeParameters: "Type parameter list cannot be empty.",
  11868. ExpectedAmbientAfterExportDeclare: "'export declare' must be followed by an ambient declaration.",
  11869. ImportAliasHasImportType: "An import alias can not use 'import type'.",
  11870. ImportReflectionHasImportType: "An `import module` declaration can not use `type` modifier",
  11871. IncompatibleModifiers: ({
  11872. modifiers
  11873. }) => `'${modifiers[0]}' modifier cannot be used with '${modifiers[1]}' modifier.`,
  11874. IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier.",
  11875. IndexSignatureHasAccessibility: ({
  11876. modifier
  11877. }) => `Index signatures cannot have an accessibility modifier ('${modifier}').`,
  11878. IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier.",
  11879. IndexSignatureHasOverride: "'override' modifier cannot appear on an index signature.",
  11880. IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier.",
  11881. InitializerNotAllowedInAmbientContext: "Initializers are not allowed in ambient contexts.",
  11882. InvalidHeritageClauseType: ({
  11883. token
  11884. }) => `'${token}' list can only include identifiers or qualified-names with optional type arguments.`,
  11885. InvalidModifierOnAwaitUsingDeclaration: modifier => `'${modifier}' modifier cannot appear on an await using declaration.`,
  11886. InvalidModifierOnTypeMember: ({
  11887. modifier
  11888. }) => `'${modifier}' modifier cannot appear on a type member.`,
  11889. InvalidModifierOnTypeParameter: ({
  11890. modifier
  11891. }) => `'${modifier}' modifier cannot appear on a type parameter.`,
  11892. InvalidModifierOnTypeParameterPositions: ({
  11893. modifier
  11894. }) => `'${modifier}' modifier can only appear on a type parameter of a class, interface or type alias.`,
  11895. InvalidModifierOnUsingDeclaration: modifier => `'${modifier}' modifier cannot appear on a using declaration.`,
  11896. InvalidModifiersOrder: ({
  11897. orderedModifiers
  11898. }) => `'${orderedModifiers[0]}' modifier must precede '${orderedModifiers[1]}' modifier.`,
  11899. InvalidPropertyAccessAfterInstantiationExpression: "Invalid property access after an instantiation expression. " + "You can either wrap the instantiation expression in parentheses, or delete the type arguments.",
  11900. InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.",
  11901. MissingInterfaceName: "'interface' declarations must be followed by an identifier.",
  11902. NonAbstractClassHasAbstractMethod: "Abstract methods can only appear within an abstract class.",
  11903. NonClassMethodPropertyHasAbstractModifier: "'abstract' modifier can only appear on a class, method, or property declaration.",
  11904. OptionalTypeBeforeRequired: "A required element cannot follow an optional element.",
  11905. OverrideNotInSubClass: "This member cannot have an 'override' modifier because its containing class does not extend another class.",
  11906. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  11907. PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.",
  11908. PrivateElementHasAccessibility: ({
  11909. modifier
  11910. }) => `Private elements cannot have an accessibility modifier ('${modifier}').`,
  11911. ReadonlyForMethodSignature: "'readonly' modifier can only appear on a property declaration or index signature.",
  11912. ReservedArrowTypeParam: "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `<T,>() => ...`.",
  11913. ReservedTypeAssertion: "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.",
  11914. SetAccessorCannotHaveOptionalParameter: "A 'set' accessor cannot have an optional parameter.",
  11915. SetAccessorCannotHaveRestParameter: "A 'set' accessor cannot have rest parameter.",
  11916. SetAccessorCannotHaveReturnType: "A 'set' accessor cannot have a return type annotation.",
  11917. SingleTypeParameterWithoutTrailingComma: ({
  11918. typeParameterName
  11919. }) => `Single type parameter ${typeParameterName} should have a trailing comma. Example usage: <${typeParameterName},>.`,
  11920. StaticBlockCannotHaveModifier: "Static class blocks cannot have any modifier.",
  11921. 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?`).",
  11922. TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
  11923. TypeImportCannotSpecifyDefaultAndNamed: "A type-only import can specify a default import or named bindings, but not both.",
  11924. TypeModifierIsUsedInTypeExports: "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.",
  11925. TypeModifierIsUsedInTypeImports: "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.",
  11926. UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.",
  11927. UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.",
  11928. UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
  11929. UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.",
  11930. UnsupportedImportTypeArgument: "Argument in a type import must be a string literal.",
  11931. UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.",
  11932. UnsupportedSignatureParameterKind: ({
  11933. type
  11934. }) => `Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${type}.`,
  11935. UsingDeclarationInAmbientContext: kind => `'${kind}' declarations are not allowed in ambient contexts.`
  11936. });
  11937. function keywordTypeFromName(value) {
  11938. switch (value) {
  11939. case "any":
  11940. return "TSAnyKeyword";
  11941. case "boolean":
  11942. return "TSBooleanKeyword";
  11943. case "bigint":
  11944. return "TSBigIntKeyword";
  11945. case "never":
  11946. return "TSNeverKeyword";
  11947. case "number":
  11948. return "TSNumberKeyword";
  11949. case "object":
  11950. return "TSObjectKeyword";
  11951. case "string":
  11952. return "TSStringKeyword";
  11953. case "symbol":
  11954. return "TSSymbolKeyword";
  11955. case "undefined":
  11956. return "TSUndefinedKeyword";
  11957. case "unknown":
  11958. return "TSUnknownKeyword";
  11959. default:
  11960. return undefined;
  11961. }
  11962. }
  11963. function tsIsAccessModifier(modifier) {
  11964. return modifier === "private" || modifier === "public" || modifier === "protected";
  11965. }
  11966. function tsIsVarianceAnnotations(modifier) {
  11967. return modifier === "in" || modifier === "out";
  11968. }
  11969. var typescript = superClass => class TypeScriptParserMixin extends superClass {
  11970. constructor(...args) {
  11971. super(...args);
  11972. this.tsParseInOutModifiers = this.tsParseModifiers.bind(this, {
  11973. allowedModifiers: ["in", "out"],
  11974. disallowedModifiers: ["const", "public", "private", "protected", "readonly", "declare", "abstract", "override"],
  11975. errorTemplate: TSErrors.InvalidModifierOnTypeParameter
  11976. });
  11977. this.tsParseConstModifier = this.tsParseModifiers.bind(this, {
  11978. allowedModifiers: ["const"],
  11979. disallowedModifiers: ["in", "out"],
  11980. errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions
  11981. });
  11982. this.tsParseInOutConstModifiers = this.tsParseModifiers.bind(this, {
  11983. allowedModifiers: ["in", "out", "const"],
  11984. disallowedModifiers: ["public", "private", "protected", "readonly", "declare", "abstract", "override"],
  11985. errorTemplate: TSErrors.InvalidModifierOnTypeParameter
  11986. });
  11987. }
  11988. getScopeHandler() {
  11989. return TypeScriptScopeHandler;
  11990. }
  11991. tsIsIdentifier() {
  11992. return tokenIsIdentifier(this.state.type);
  11993. }
  11994. tsTokenCanFollowModifier() {
  11995. return this.match(0) || this.match(5) || this.match(55) || this.match(21) || this.match(139) || this.isLiteralPropertyName();
  11996. }
  11997. tsNextTokenOnSameLineAndCanFollowModifier() {
  11998. this.next();
  11999. if (this.hasPrecedingLineBreak()) {
  12000. return false;
  12001. }
  12002. return this.tsTokenCanFollowModifier();
  12003. }
  12004. tsNextTokenCanFollowModifier() {
  12005. if (this.match(106)) {
  12006. this.next();
  12007. return this.tsTokenCanFollowModifier();
  12008. }
  12009. return this.tsNextTokenOnSameLineAndCanFollowModifier();
  12010. }
  12011. tsParseModifier(allowedModifiers, stopOnStartOfClassStaticBlock, hasSeenStaticModifier) {
  12012. if (!tokenIsIdentifier(this.state.type) && this.state.type !== 58 && this.state.type !== 75) {
  12013. return undefined;
  12014. }
  12015. const modifier = this.state.value;
  12016. if (allowedModifiers.includes(modifier)) {
  12017. if (hasSeenStaticModifier && this.match(106)) {
  12018. return undefined;
  12019. }
  12020. if (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) {
  12021. return undefined;
  12022. }
  12023. if (this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
  12024. return modifier;
  12025. }
  12026. }
  12027. return undefined;
  12028. }
  12029. tsParseModifiers({
  12030. allowedModifiers,
  12031. disallowedModifiers,
  12032. stopOnStartOfClassStaticBlock,
  12033. errorTemplate = TSErrors.InvalidModifierOnTypeMember
  12034. }, modified) {
  12035. const enforceOrder = (loc, modifier, before, after) => {
  12036. if (modifier === before && modified[after]) {
  12037. this.raise(TSErrors.InvalidModifiersOrder, loc, {
  12038. orderedModifiers: [before, after]
  12039. });
  12040. }
  12041. };
  12042. const incompatible = (loc, modifier, mod1, mod2) => {
  12043. if (modified[mod1] && modifier === mod2 || modified[mod2] && modifier === mod1) {
  12044. this.raise(TSErrors.IncompatibleModifiers, loc, {
  12045. modifiers: [mod1, mod2]
  12046. });
  12047. }
  12048. };
  12049. for (;;) {
  12050. const {
  12051. startLoc
  12052. } = this.state;
  12053. const modifier = this.tsParseModifier(allowedModifiers.concat(disallowedModifiers != null ? disallowedModifiers : []), stopOnStartOfClassStaticBlock, modified.static);
  12054. if (!modifier) break;
  12055. if (tsIsAccessModifier(modifier)) {
  12056. if (modified.accessibility) {
  12057. this.raise(TSErrors.DuplicateAccessibilityModifier, startLoc, {
  12058. modifier
  12059. });
  12060. } else {
  12061. enforceOrder(startLoc, modifier, modifier, "override");
  12062. enforceOrder(startLoc, modifier, modifier, "static");
  12063. enforceOrder(startLoc, modifier, modifier, "readonly");
  12064. modified.accessibility = modifier;
  12065. }
  12066. } else if (tsIsVarianceAnnotations(modifier)) {
  12067. if (modified[modifier]) {
  12068. this.raise(TSErrors.DuplicateModifier, startLoc, {
  12069. modifier
  12070. });
  12071. }
  12072. modified[modifier] = true;
  12073. enforceOrder(startLoc, modifier, "in", "out");
  12074. } else {
  12075. if (hasOwnProperty.call(modified, modifier)) {
  12076. this.raise(TSErrors.DuplicateModifier, startLoc, {
  12077. modifier
  12078. });
  12079. } else {
  12080. enforceOrder(startLoc, modifier, "static", "readonly");
  12081. enforceOrder(startLoc, modifier, "static", "override");
  12082. enforceOrder(startLoc, modifier, "override", "readonly");
  12083. enforceOrder(startLoc, modifier, "abstract", "override");
  12084. incompatible(startLoc, modifier, "declare", "override");
  12085. incompatible(startLoc, modifier, "static", "abstract");
  12086. }
  12087. modified[modifier] = true;
  12088. }
  12089. if (disallowedModifiers != null && disallowedModifiers.includes(modifier)) {
  12090. this.raise(errorTemplate, startLoc, {
  12091. modifier
  12092. });
  12093. }
  12094. }
  12095. }
  12096. tsIsListTerminator(kind) {
  12097. switch (kind) {
  12098. case "EnumMembers":
  12099. case "TypeMembers":
  12100. return this.match(8);
  12101. case "HeritageClauseElement":
  12102. return this.match(5);
  12103. case "TupleElementTypes":
  12104. return this.match(3);
  12105. case "TypeParametersOrArguments":
  12106. return this.match(48);
  12107. }
  12108. }
  12109. tsParseList(kind, parseElement) {
  12110. const result = [];
  12111. while (!this.tsIsListTerminator(kind)) {
  12112. result.push(parseElement());
  12113. }
  12114. return result;
  12115. }
  12116. tsParseDelimitedList(kind, parseElement, refTrailingCommaPos) {
  12117. return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true, refTrailingCommaPos));
  12118. }
  12119. tsParseDelimitedListWorker(kind, parseElement, expectSuccess, refTrailingCommaPos) {
  12120. const result = [];
  12121. let trailingCommaPos = -1;
  12122. for (;;) {
  12123. if (this.tsIsListTerminator(kind)) {
  12124. break;
  12125. }
  12126. trailingCommaPos = -1;
  12127. const element = parseElement();
  12128. if (element == null) {
  12129. return undefined;
  12130. }
  12131. result.push(element);
  12132. if (this.eat(12)) {
  12133. trailingCommaPos = this.state.lastTokStartLoc.index;
  12134. continue;
  12135. }
  12136. if (this.tsIsListTerminator(kind)) {
  12137. break;
  12138. }
  12139. if (expectSuccess) {
  12140. this.expect(12);
  12141. }
  12142. return undefined;
  12143. }
  12144. if (refTrailingCommaPos) {
  12145. refTrailingCommaPos.value = trailingCommaPos;
  12146. }
  12147. return result;
  12148. }
  12149. tsParseBracketedList(kind, parseElement, bracket, skipFirstToken, refTrailingCommaPos) {
  12150. if (!skipFirstToken) {
  12151. if (bracket) {
  12152. this.expect(0);
  12153. } else {
  12154. this.expect(47);
  12155. }
  12156. }
  12157. const result = this.tsParseDelimitedList(kind, parseElement, refTrailingCommaPos);
  12158. if (bracket) {
  12159. this.expect(3);
  12160. } else {
  12161. this.expect(48);
  12162. }
  12163. return result;
  12164. }
  12165. tsParseImportType() {
  12166. const node = this.startNode();
  12167. this.expect(83);
  12168. this.expect(10);
  12169. if (!this.match(134)) {
  12170. this.raise(TSErrors.UnsupportedImportTypeArgument, this.state.startLoc);
  12171. node.argument = super.parseExprAtom();
  12172. } else {
  12173. node.argument = this.parseStringLiteral(this.state.value);
  12174. }
  12175. if (this.eat(12)) {
  12176. node.options = this.tsParseImportTypeOptions();
  12177. } else {
  12178. node.options = null;
  12179. }
  12180. this.expect(11);
  12181. if (this.eat(16)) {
  12182. node.qualifier = this.tsParseEntityName(1 | 2);
  12183. }
  12184. if (this.match(47)) {
  12185. node.typeParameters = this.tsParseTypeArguments();
  12186. }
  12187. return this.finishNode(node, "TSImportType");
  12188. }
  12189. tsParseImportTypeOptions() {
  12190. const node = this.startNode();
  12191. this.expect(5);
  12192. const withProperty = this.startNode();
  12193. if (this.isContextual(76)) {
  12194. withProperty.method = false;
  12195. withProperty.key = this.parseIdentifier(true);
  12196. withProperty.computed = false;
  12197. withProperty.shorthand = false;
  12198. } else {
  12199. this.unexpected(null, 76);
  12200. }
  12201. this.expect(14);
  12202. withProperty.value = this.tsParseImportTypeWithPropertyValue();
  12203. node.properties = [this.finishObjectProperty(withProperty)];
  12204. this.eat(12);
  12205. this.expect(8);
  12206. return this.finishNode(node, "ObjectExpression");
  12207. }
  12208. tsParseImportTypeWithPropertyValue() {
  12209. const node = this.startNode();
  12210. const properties = [];
  12211. this.expect(5);
  12212. while (!this.match(8)) {
  12213. const type = this.state.type;
  12214. if (tokenIsIdentifier(type) || type === 134) {
  12215. properties.push(super.parsePropertyDefinition(null));
  12216. } else {
  12217. this.unexpected();
  12218. }
  12219. this.eat(12);
  12220. }
  12221. node.properties = properties;
  12222. this.next();
  12223. return this.finishNode(node, "ObjectExpression");
  12224. }
  12225. tsParseEntityName(flags) {
  12226. let entity;
  12227. if (flags & 1 && this.match(78)) {
  12228. if (flags & 2) {
  12229. entity = this.parseIdentifier(true);
  12230. } else {
  12231. const node = this.startNode();
  12232. this.next();
  12233. entity = this.finishNode(node, "ThisExpression");
  12234. }
  12235. } else {
  12236. entity = this.parseIdentifier(!!(flags & 1));
  12237. }
  12238. while (this.eat(16)) {
  12239. const node = this.startNodeAtNode(entity);
  12240. node.left = entity;
  12241. node.right = this.parseIdentifier(!!(flags & 1));
  12242. entity = this.finishNode(node, "TSQualifiedName");
  12243. }
  12244. return entity;
  12245. }
  12246. tsParseTypeReference() {
  12247. const node = this.startNode();
  12248. node.typeName = this.tsParseEntityName(1);
  12249. if (!this.hasPrecedingLineBreak() && this.match(47)) {
  12250. node.typeParameters = this.tsParseTypeArguments();
  12251. }
  12252. return this.finishNode(node, "TSTypeReference");
  12253. }
  12254. tsParseThisTypePredicate(lhs) {
  12255. this.next();
  12256. const node = this.startNodeAtNode(lhs);
  12257. node.parameterName = lhs;
  12258. node.typeAnnotation = this.tsParseTypeAnnotation(false);
  12259. node.asserts = false;
  12260. return this.finishNode(node, "TSTypePredicate");
  12261. }
  12262. tsParseThisTypeNode() {
  12263. const node = this.startNode();
  12264. this.next();
  12265. return this.finishNode(node, "TSThisType");
  12266. }
  12267. tsParseTypeQuery() {
  12268. const node = this.startNode();
  12269. this.expect(87);
  12270. if (this.match(83)) {
  12271. node.exprName = this.tsParseImportType();
  12272. } else {
  12273. node.exprName = this.tsParseEntityName(1 | 2);
  12274. }
  12275. if (!this.hasPrecedingLineBreak() && this.match(47)) {
  12276. node.typeParameters = this.tsParseTypeArguments();
  12277. }
  12278. return this.finishNode(node, "TSTypeQuery");
  12279. }
  12280. tsParseTypeParameter(parseModifiers) {
  12281. const node = this.startNode();
  12282. parseModifiers(node);
  12283. node.name = this.tsParseTypeParameterName();
  12284. node.constraint = this.tsEatThenParseType(81);
  12285. node.default = this.tsEatThenParseType(29);
  12286. return this.finishNode(node, "TSTypeParameter");
  12287. }
  12288. tsTryParseTypeParameters(parseModifiers) {
  12289. if (this.match(47)) {
  12290. return this.tsParseTypeParameters(parseModifiers);
  12291. }
  12292. }
  12293. tsParseTypeParameters(parseModifiers) {
  12294. const node = this.startNode();
  12295. if (this.match(47) || this.match(143)) {
  12296. this.next();
  12297. } else {
  12298. this.unexpected();
  12299. }
  12300. const refTrailingCommaPos = {
  12301. value: -1
  12302. };
  12303. node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this, parseModifiers), false, true, refTrailingCommaPos);
  12304. if (node.params.length === 0) {
  12305. this.raise(TSErrors.EmptyTypeParameters, node);
  12306. }
  12307. if (refTrailingCommaPos.value !== -1) {
  12308. this.addExtra(node, "trailingComma", refTrailingCommaPos.value);
  12309. }
  12310. return this.finishNode(node, "TSTypeParameterDeclaration");
  12311. }
  12312. tsFillSignature(returnToken, signature) {
  12313. const returnTokenRequired = returnToken === 19;
  12314. const paramsKey = "parameters";
  12315. const returnTypeKey = "typeAnnotation";
  12316. signature.typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  12317. this.expect(10);
  12318. signature[paramsKey] = this.tsParseBindingListForSignature();
  12319. if (returnTokenRequired) {
  12320. signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  12321. } else if (this.match(returnToken)) {
  12322. signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  12323. }
  12324. }
  12325. tsParseBindingListForSignature() {
  12326. const list = super.parseBindingList(11, 41, 2);
  12327. for (const pattern of list) {
  12328. const {
  12329. type
  12330. } = pattern;
  12331. if (type === "AssignmentPattern" || type === "TSParameterProperty") {
  12332. this.raise(TSErrors.UnsupportedSignatureParameterKind, pattern, {
  12333. type
  12334. });
  12335. }
  12336. }
  12337. return list;
  12338. }
  12339. tsParseTypeMemberSemicolon() {
  12340. if (!this.eat(12) && !this.isLineTerminator()) {
  12341. this.expect(13);
  12342. }
  12343. }
  12344. tsParseSignatureMember(kind, node) {
  12345. this.tsFillSignature(14, node);
  12346. this.tsParseTypeMemberSemicolon();
  12347. return this.finishNode(node, kind);
  12348. }
  12349. tsIsUnambiguouslyIndexSignature() {
  12350. this.next();
  12351. if (tokenIsIdentifier(this.state.type)) {
  12352. this.next();
  12353. return this.match(14);
  12354. }
  12355. return false;
  12356. }
  12357. tsTryParseIndexSignature(node) {
  12358. if (!(this.match(0) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
  12359. return;
  12360. }
  12361. this.expect(0);
  12362. const id = this.parseIdentifier();
  12363. id.typeAnnotation = this.tsParseTypeAnnotation();
  12364. this.resetEndLocation(id);
  12365. this.expect(3);
  12366. node.parameters = [id];
  12367. const type = this.tsTryParseTypeAnnotation();
  12368. if (type) node.typeAnnotation = type;
  12369. this.tsParseTypeMemberSemicolon();
  12370. return this.finishNode(node, "TSIndexSignature");
  12371. }
  12372. tsParsePropertyOrMethodSignature(node, readonly) {
  12373. if (this.eat(17)) node.optional = true;
  12374. if (this.match(10) || this.match(47)) {
  12375. if (readonly) {
  12376. this.raise(TSErrors.ReadonlyForMethodSignature, node);
  12377. }
  12378. const method = node;
  12379. if (method.kind && this.match(47)) {
  12380. this.raise(TSErrors.AccessorCannotHaveTypeParameters, this.state.curPosition());
  12381. }
  12382. this.tsFillSignature(14, method);
  12383. this.tsParseTypeMemberSemicolon();
  12384. const paramsKey = "parameters";
  12385. const returnTypeKey = "typeAnnotation";
  12386. if (method.kind === "get") {
  12387. if (method[paramsKey].length > 0) {
  12388. this.raise(Errors.BadGetterArity, this.state.curPosition());
  12389. if (this.isThisParam(method[paramsKey][0])) {
  12390. this.raise(TSErrors.AccessorCannotDeclareThisParameter, this.state.curPosition());
  12391. }
  12392. }
  12393. } else if (method.kind === "set") {
  12394. if (method[paramsKey].length !== 1) {
  12395. this.raise(Errors.BadSetterArity, this.state.curPosition());
  12396. } else {
  12397. const firstParameter = method[paramsKey][0];
  12398. if (this.isThisParam(firstParameter)) {
  12399. this.raise(TSErrors.AccessorCannotDeclareThisParameter, this.state.curPosition());
  12400. }
  12401. if (firstParameter.type === "Identifier" && firstParameter.optional) {
  12402. this.raise(TSErrors.SetAccessorCannotHaveOptionalParameter, this.state.curPosition());
  12403. }
  12404. if (firstParameter.type === "RestElement") {
  12405. this.raise(TSErrors.SetAccessorCannotHaveRestParameter, this.state.curPosition());
  12406. }
  12407. }
  12408. if (method[returnTypeKey]) {
  12409. this.raise(TSErrors.SetAccessorCannotHaveReturnType, method[returnTypeKey]);
  12410. }
  12411. } else {
  12412. method.kind = "method";
  12413. }
  12414. return this.finishNode(method, "TSMethodSignature");
  12415. } else {
  12416. const property = node;
  12417. if (readonly) property.readonly = true;
  12418. const type = this.tsTryParseTypeAnnotation();
  12419. if (type) property.typeAnnotation = type;
  12420. this.tsParseTypeMemberSemicolon();
  12421. return this.finishNode(property, "TSPropertySignature");
  12422. }
  12423. }
  12424. tsParseTypeMember() {
  12425. const node = this.startNode();
  12426. if (this.match(10) || this.match(47)) {
  12427. return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
  12428. }
  12429. if (this.match(77)) {
  12430. const id = this.startNode();
  12431. this.next();
  12432. if (this.match(10) || this.match(47)) {
  12433. return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
  12434. } else {
  12435. node.key = this.createIdentifier(id, "new");
  12436. return this.tsParsePropertyOrMethodSignature(node, false);
  12437. }
  12438. }
  12439. this.tsParseModifiers({
  12440. allowedModifiers: ["readonly"],
  12441. disallowedModifiers: ["declare", "abstract", "private", "protected", "public", "static", "override"]
  12442. }, node);
  12443. const idx = this.tsTryParseIndexSignature(node);
  12444. if (idx) {
  12445. return idx;
  12446. }
  12447. super.parsePropertyName(node);
  12448. if (!node.computed && node.key.type === "Identifier" && (node.key.name === "get" || node.key.name === "set") && this.tsTokenCanFollowModifier()) {
  12449. node.kind = node.key.name;
  12450. super.parsePropertyName(node);
  12451. if (!this.match(10) && !this.match(47)) {
  12452. this.unexpected(null, 10);
  12453. }
  12454. }
  12455. return this.tsParsePropertyOrMethodSignature(node, !!node.readonly);
  12456. }
  12457. tsParseTypeLiteral() {
  12458. const node = this.startNode();
  12459. node.members = this.tsParseObjectTypeMembers();
  12460. return this.finishNode(node, "TSTypeLiteral");
  12461. }
  12462. tsParseObjectTypeMembers() {
  12463. this.expect(5);
  12464. const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
  12465. this.expect(8);
  12466. return members;
  12467. }
  12468. tsIsStartOfMappedType() {
  12469. this.next();
  12470. if (this.eat(53)) {
  12471. return this.isContextual(122);
  12472. }
  12473. if (this.isContextual(122)) {
  12474. this.next();
  12475. }
  12476. if (!this.match(0)) {
  12477. return false;
  12478. }
  12479. this.next();
  12480. if (!this.tsIsIdentifier()) {
  12481. return false;
  12482. }
  12483. this.next();
  12484. return this.match(58);
  12485. }
  12486. tsParseMappedType() {
  12487. const node = this.startNode();
  12488. this.expect(5);
  12489. if (this.match(53)) {
  12490. node.readonly = this.state.value;
  12491. this.next();
  12492. this.expectContextual(122);
  12493. } else if (this.eatContextual(122)) {
  12494. node.readonly = true;
  12495. }
  12496. this.expect(0);
  12497. const typeParameter = this.startNode();
  12498. typeParameter.name = this.tsParseTypeParameterName();
  12499. typeParameter.constraint = this.tsExpectThenParseType(58);
  12500. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  12501. node.nameType = this.eatContextual(93) ? this.tsParseType() : null;
  12502. this.expect(3);
  12503. if (this.match(53)) {
  12504. node.optional = this.state.value;
  12505. this.next();
  12506. this.expect(17);
  12507. } else if (this.eat(17)) {
  12508. node.optional = true;
  12509. }
  12510. node.typeAnnotation = this.tsTryParseType();
  12511. this.semicolon();
  12512. this.expect(8);
  12513. return this.finishNode(node, "TSMappedType");
  12514. }
  12515. tsParseTupleType() {
  12516. const node = this.startNode();
  12517. node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
  12518. let seenOptionalElement = false;
  12519. node.elementTypes.forEach(elementNode => {
  12520. const {
  12521. type
  12522. } = elementNode;
  12523. if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) {
  12524. this.raise(TSErrors.OptionalTypeBeforeRequired, elementNode);
  12525. }
  12526. seenOptionalElement || (seenOptionalElement = type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType");
  12527. });
  12528. return this.finishNode(node, "TSTupleType");
  12529. }
  12530. tsParseTupleElementType() {
  12531. const restStartLoc = this.state.startLoc;
  12532. const rest = this.eat(21);
  12533. const {
  12534. startLoc
  12535. } = this.state;
  12536. let labeled;
  12537. let label;
  12538. let optional;
  12539. let type;
  12540. const isWord = tokenIsKeywordOrIdentifier(this.state.type);
  12541. const chAfterWord = isWord ? this.lookaheadCharCode() : null;
  12542. if (chAfterWord === 58) {
  12543. labeled = true;
  12544. optional = false;
  12545. label = this.parseIdentifier(true);
  12546. this.expect(14);
  12547. type = this.tsParseType();
  12548. } else if (chAfterWord === 63) {
  12549. optional = true;
  12550. const wordName = this.state.value;
  12551. const typeOrLabel = this.tsParseNonArrayType();
  12552. if (this.lookaheadCharCode() === 58) {
  12553. labeled = true;
  12554. label = this.createIdentifier(this.startNodeAt(startLoc), wordName);
  12555. this.expect(17);
  12556. this.expect(14);
  12557. type = this.tsParseType();
  12558. } else {
  12559. labeled = false;
  12560. type = typeOrLabel;
  12561. this.expect(17);
  12562. }
  12563. } else {
  12564. type = this.tsParseType();
  12565. optional = this.eat(17);
  12566. labeled = this.eat(14);
  12567. }
  12568. if (labeled) {
  12569. let labeledNode;
  12570. if (label) {
  12571. labeledNode = this.startNodeAt(startLoc);
  12572. labeledNode.optional = optional;
  12573. labeledNode.label = label;
  12574. labeledNode.elementType = type;
  12575. if (this.eat(17)) {
  12576. labeledNode.optional = true;
  12577. this.raise(TSErrors.TupleOptionalAfterType, this.state.lastTokStartLoc);
  12578. }
  12579. } else {
  12580. labeledNode = this.startNodeAt(startLoc);
  12581. labeledNode.optional = optional;
  12582. this.raise(TSErrors.InvalidTupleMemberLabel, type);
  12583. labeledNode.label = type;
  12584. labeledNode.elementType = this.tsParseType();
  12585. }
  12586. type = this.finishNode(labeledNode, "TSNamedTupleMember");
  12587. } else if (optional) {
  12588. const optionalTypeNode = this.startNodeAt(startLoc);
  12589. optionalTypeNode.typeAnnotation = type;
  12590. type = this.finishNode(optionalTypeNode, "TSOptionalType");
  12591. }
  12592. if (rest) {
  12593. const restNode = this.startNodeAt(restStartLoc);
  12594. restNode.typeAnnotation = type;
  12595. type = this.finishNode(restNode, "TSRestType");
  12596. }
  12597. return type;
  12598. }
  12599. tsParseParenthesizedType() {
  12600. const node = this.startNode();
  12601. this.expect(10);
  12602. node.typeAnnotation = this.tsParseType();
  12603. this.expect(11);
  12604. return this.finishNode(node, "TSParenthesizedType");
  12605. }
  12606. tsParseFunctionOrConstructorType(type, abstract) {
  12607. const node = this.startNode();
  12608. if (type === "TSConstructorType") {
  12609. node.abstract = !!abstract;
  12610. if (abstract) this.next();
  12611. this.next();
  12612. }
  12613. this.tsInAllowConditionalTypesContext(() => this.tsFillSignature(19, node));
  12614. return this.finishNode(node, type);
  12615. }
  12616. tsParseLiteralTypeNode() {
  12617. const node = this.startNode();
  12618. switch (this.state.type) {
  12619. case 135:
  12620. case 136:
  12621. case 134:
  12622. case 85:
  12623. case 86:
  12624. node.literal = super.parseExprAtom();
  12625. break;
  12626. default:
  12627. this.unexpected();
  12628. }
  12629. return this.finishNode(node, "TSLiteralType");
  12630. }
  12631. tsParseTemplateLiteralType() {
  12632. const node = this.startNode();
  12633. node.literal = super.parseTemplate(false);
  12634. return this.finishNode(node, "TSLiteralType");
  12635. }
  12636. parseTemplateSubstitution() {
  12637. if (this.state.inType) return this.tsParseType();
  12638. return super.parseTemplateSubstitution();
  12639. }
  12640. tsParseThisTypeOrThisTypePredicate() {
  12641. const thisKeyword = this.tsParseThisTypeNode();
  12642. if (this.isContextual(116) && !this.hasPrecedingLineBreak()) {
  12643. return this.tsParseThisTypePredicate(thisKeyword);
  12644. } else {
  12645. return thisKeyword;
  12646. }
  12647. }
  12648. tsParseNonArrayType() {
  12649. switch (this.state.type) {
  12650. case 134:
  12651. case 135:
  12652. case 136:
  12653. case 85:
  12654. case 86:
  12655. return this.tsParseLiteralTypeNode();
  12656. case 53:
  12657. if (this.state.value === "-") {
  12658. const node = this.startNode();
  12659. const nextToken = this.lookahead();
  12660. if (nextToken.type !== 135 && nextToken.type !== 136) {
  12661. this.unexpected();
  12662. }
  12663. node.literal = this.parseMaybeUnary();
  12664. return this.finishNode(node, "TSLiteralType");
  12665. }
  12666. break;
  12667. case 78:
  12668. return this.tsParseThisTypeOrThisTypePredicate();
  12669. case 87:
  12670. return this.tsParseTypeQuery();
  12671. case 83:
  12672. return this.tsParseImportType();
  12673. case 5:
  12674. return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
  12675. case 0:
  12676. return this.tsParseTupleType();
  12677. case 10:
  12678. return this.tsParseParenthesizedType();
  12679. case 25:
  12680. case 24:
  12681. return this.tsParseTemplateLiteralType();
  12682. default:
  12683. {
  12684. const {
  12685. type
  12686. } = this.state;
  12687. if (tokenIsIdentifier(type) || type === 88 || type === 84) {
  12688. const nodeType = type === 88 ? "TSVoidKeyword" : type === 84 ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
  12689. if (nodeType !== undefined && this.lookaheadCharCode() !== 46) {
  12690. const node = this.startNode();
  12691. this.next();
  12692. return this.finishNode(node, nodeType);
  12693. }
  12694. return this.tsParseTypeReference();
  12695. }
  12696. }
  12697. }
  12698. throw this.unexpected();
  12699. }
  12700. tsParseArrayTypeOrHigher() {
  12701. const {
  12702. startLoc
  12703. } = this.state;
  12704. let type = this.tsParseNonArrayType();
  12705. while (!this.hasPrecedingLineBreak() && this.eat(0)) {
  12706. if (this.match(3)) {
  12707. const node = this.startNodeAt(startLoc);
  12708. node.elementType = type;
  12709. this.expect(3);
  12710. type = this.finishNode(node, "TSArrayType");
  12711. } else {
  12712. const node = this.startNodeAt(startLoc);
  12713. node.objectType = type;
  12714. node.indexType = this.tsParseType();
  12715. this.expect(3);
  12716. type = this.finishNode(node, "TSIndexedAccessType");
  12717. }
  12718. }
  12719. return type;
  12720. }
  12721. tsParseTypeOperator() {
  12722. const node = this.startNode();
  12723. const operator = this.state.value;
  12724. this.next();
  12725. node.operator = operator;
  12726. node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
  12727. if (operator === "readonly") {
  12728. this.tsCheckTypeAnnotationForReadOnly(node);
  12729. }
  12730. return this.finishNode(node, "TSTypeOperator");
  12731. }
  12732. tsCheckTypeAnnotationForReadOnly(node) {
  12733. switch (node.typeAnnotation.type) {
  12734. case "TSTupleType":
  12735. case "TSArrayType":
  12736. return;
  12737. default:
  12738. this.raise(TSErrors.UnexpectedReadonly, node);
  12739. }
  12740. }
  12741. tsParseInferType() {
  12742. const node = this.startNode();
  12743. this.expectContextual(115);
  12744. const typeParameter = this.startNode();
  12745. typeParameter.name = this.tsParseTypeParameterName();
  12746. typeParameter.constraint = this.tsTryParse(() => this.tsParseConstraintForInferType());
  12747. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  12748. return this.finishNode(node, "TSInferType");
  12749. }
  12750. tsParseConstraintForInferType() {
  12751. if (this.eat(81)) {
  12752. const constraint = this.tsInDisallowConditionalTypesContext(() => this.tsParseType());
  12753. if (this.state.inDisallowConditionalTypesContext || !this.match(17)) {
  12754. return constraint;
  12755. }
  12756. }
  12757. }
  12758. tsParseTypeOperatorOrHigher() {
  12759. const isTypeOperator = tokenIsTSTypeOperator(this.state.type) && !this.state.containsEsc;
  12760. return isTypeOperator ? this.tsParseTypeOperator() : this.isContextual(115) ? this.tsParseInferType() : this.tsInAllowConditionalTypesContext(() => this.tsParseArrayTypeOrHigher());
  12761. }
  12762. tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  12763. const node = this.startNode();
  12764. const hasLeadingOperator = this.eat(operator);
  12765. const types = [];
  12766. do {
  12767. types.push(parseConstituentType());
  12768. } while (this.eat(operator));
  12769. if (types.length === 1 && !hasLeadingOperator) {
  12770. return types[0];
  12771. }
  12772. node.types = types;
  12773. return this.finishNode(node, kind);
  12774. }
  12775. tsParseIntersectionTypeOrHigher() {
  12776. return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), 45);
  12777. }
  12778. tsParseUnionTypeOrHigher() {
  12779. return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), 43);
  12780. }
  12781. tsIsStartOfFunctionType() {
  12782. if (this.match(47)) {
  12783. return true;
  12784. }
  12785. return this.match(10) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  12786. }
  12787. tsSkipParameterStart() {
  12788. if (tokenIsIdentifier(this.state.type) || this.match(78)) {
  12789. this.next();
  12790. return true;
  12791. }
  12792. if (this.match(5)) {
  12793. const {
  12794. errors
  12795. } = this.state;
  12796. const previousErrorCount = errors.length;
  12797. try {
  12798. this.parseObjectLike(8, true);
  12799. return errors.length === previousErrorCount;
  12800. } catch (_unused) {
  12801. return false;
  12802. }
  12803. }
  12804. if (this.match(0)) {
  12805. this.next();
  12806. const {
  12807. errors
  12808. } = this.state;
  12809. const previousErrorCount = errors.length;
  12810. try {
  12811. super.parseBindingList(3, 93, 1);
  12812. return errors.length === previousErrorCount;
  12813. } catch (_unused2) {
  12814. return false;
  12815. }
  12816. }
  12817. return false;
  12818. }
  12819. tsIsUnambiguouslyStartOfFunctionType() {
  12820. this.next();
  12821. if (this.match(11) || this.match(21)) {
  12822. return true;
  12823. }
  12824. if (this.tsSkipParameterStart()) {
  12825. if (this.match(14) || this.match(12) || this.match(17) || this.match(29)) {
  12826. return true;
  12827. }
  12828. if (this.match(11)) {
  12829. this.next();
  12830. if (this.match(19)) {
  12831. return true;
  12832. }
  12833. }
  12834. }
  12835. return false;
  12836. }
  12837. tsParseTypeOrTypePredicateAnnotation(returnToken) {
  12838. return this.tsInType(() => {
  12839. const t = this.startNode();
  12840. this.expect(returnToken);
  12841. const node = this.startNode();
  12842. const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
  12843. if (asserts && this.match(78)) {
  12844. let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
  12845. if (thisTypePredicate.type === "TSThisType") {
  12846. node.parameterName = thisTypePredicate;
  12847. node.asserts = true;
  12848. node.typeAnnotation = null;
  12849. thisTypePredicate = this.finishNode(node, "TSTypePredicate");
  12850. } else {
  12851. this.resetStartLocationFromNode(thisTypePredicate, node);
  12852. thisTypePredicate.asserts = true;
  12853. }
  12854. t.typeAnnotation = thisTypePredicate;
  12855. return this.finishNode(t, "TSTypeAnnotation");
  12856. }
  12857. const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
  12858. if (!typePredicateVariable) {
  12859. if (!asserts) {
  12860. return this.tsParseTypeAnnotation(false, t);
  12861. }
  12862. node.parameterName = this.parseIdentifier();
  12863. node.asserts = asserts;
  12864. node.typeAnnotation = null;
  12865. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  12866. return this.finishNode(t, "TSTypeAnnotation");
  12867. }
  12868. const type = this.tsParseTypeAnnotation(false);
  12869. node.parameterName = typePredicateVariable;
  12870. node.typeAnnotation = type;
  12871. node.asserts = asserts;
  12872. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  12873. return this.finishNode(t, "TSTypeAnnotation");
  12874. });
  12875. }
  12876. tsTryParseTypeOrTypePredicateAnnotation() {
  12877. if (this.match(14)) {
  12878. return this.tsParseTypeOrTypePredicateAnnotation(14);
  12879. }
  12880. }
  12881. tsTryParseTypeAnnotation() {
  12882. if (this.match(14)) {
  12883. return this.tsParseTypeAnnotation();
  12884. }
  12885. }
  12886. tsTryParseType() {
  12887. return this.tsEatThenParseType(14);
  12888. }
  12889. tsParseTypePredicatePrefix() {
  12890. const id = this.parseIdentifier();
  12891. if (this.isContextual(116) && !this.hasPrecedingLineBreak()) {
  12892. this.next();
  12893. return id;
  12894. }
  12895. }
  12896. tsParseTypePredicateAsserts() {
  12897. if (this.state.type !== 109) {
  12898. return false;
  12899. }
  12900. const containsEsc = this.state.containsEsc;
  12901. this.next();
  12902. if (!tokenIsIdentifier(this.state.type) && !this.match(78)) {
  12903. return false;
  12904. }
  12905. if (containsEsc) {
  12906. this.raise(Errors.InvalidEscapedReservedWord, this.state.lastTokStartLoc, {
  12907. reservedWord: "asserts"
  12908. });
  12909. }
  12910. return true;
  12911. }
  12912. tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
  12913. this.tsInType(() => {
  12914. if (eatColon) this.expect(14);
  12915. t.typeAnnotation = this.tsParseType();
  12916. });
  12917. return this.finishNode(t, "TSTypeAnnotation");
  12918. }
  12919. tsParseType() {
  12920. assert(this.state.inType);
  12921. const type = this.tsParseNonConditionalType();
  12922. if (this.state.inDisallowConditionalTypesContext || this.hasPrecedingLineBreak() || !this.eat(81)) {
  12923. return type;
  12924. }
  12925. const node = this.startNodeAtNode(type);
  12926. node.checkType = type;
  12927. node.extendsType = this.tsInDisallowConditionalTypesContext(() => this.tsParseNonConditionalType());
  12928. this.expect(17);
  12929. node.trueType = this.tsInAllowConditionalTypesContext(() => this.tsParseType());
  12930. this.expect(14);
  12931. node.falseType = this.tsInAllowConditionalTypesContext(() => this.tsParseType());
  12932. return this.finishNode(node, "TSConditionalType");
  12933. }
  12934. isAbstractConstructorSignature() {
  12935. return this.isContextual(124) && this.isLookaheadContextual("new");
  12936. }
  12937. tsParseNonConditionalType() {
  12938. if (this.tsIsStartOfFunctionType()) {
  12939. return this.tsParseFunctionOrConstructorType("TSFunctionType");
  12940. }
  12941. if (this.match(77)) {
  12942. return this.tsParseFunctionOrConstructorType("TSConstructorType");
  12943. } else if (this.isAbstractConstructorSignature()) {
  12944. return this.tsParseFunctionOrConstructorType("TSConstructorType", true);
  12945. }
  12946. return this.tsParseUnionTypeOrHigher();
  12947. }
  12948. tsParseTypeAssertion() {
  12949. if (this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) {
  12950. this.raise(TSErrors.ReservedTypeAssertion, this.state.startLoc);
  12951. }
  12952. const node = this.startNode();
  12953. node.typeAnnotation = this.tsInType(() => {
  12954. this.next();
  12955. return this.match(75) ? this.tsParseTypeReference() : this.tsParseType();
  12956. });
  12957. this.expect(48);
  12958. node.expression = this.parseMaybeUnary();
  12959. return this.finishNode(node, "TSTypeAssertion");
  12960. }
  12961. tsParseHeritageClause(token) {
  12962. const originalStartLoc = this.state.startLoc;
  12963. const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", () => {
  12964. const node = this.startNode();
  12965. node.expression = this.tsParseEntityName(1 | 2);
  12966. if (this.match(47)) {
  12967. node.typeParameters = this.tsParseTypeArguments();
  12968. }
  12969. return this.finishNode(node, "TSExpressionWithTypeArguments");
  12970. });
  12971. if (!delimitedList.length) {
  12972. this.raise(TSErrors.EmptyHeritageClauseType, originalStartLoc, {
  12973. token
  12974. });
  12975. }
  12976. return delimitedList;
  12977. }
  12978. tsParseInterfaceDeclaration(node, properties = {}) {
  12979. if (this.hasFollowingLineBreak()) return null;
  12980. this.expectContextual(129);
  12981. if (properties.declare) node.declare = true;
  12982. if (tokenIsIdentifier(this.state.type)) {
  12983. node.id = this.parseIdentifier();
  12984. this.checkIdentifier(node.id, 130);
  12985. } else {
  12986. node.id = null;
  12987. this.raise(TSErrors.MissingInterfaceName, this.state.startLoc);
  12988. }
  12989. node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);
  12990. if (this.eat(81)) {
  12991. node.extends = this.tsParseHeritageClause("extends");
  12992. }
  12993. const body = this.startNode();
  12994. body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
  12995. node.body = this.finishNode(body, "TSInterfaceBody");
  12996. return this.finishNode(node, "TSInterfaceDeclaration");
  12997. }
  12998. tsParseTypeAliasDeclaration(node) {
  12999. node.id = this.parseIdentifier();
  13000. this.checkIdentifier(node.id, 2);
  13001. node.typeAnnotation = this.tsInType(() => {
  13002. node.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutModifiers);
  13003. this.expect(29);
  13004. if (this.isContextual(114) && this.lookaheadCharCode() !== 46) {
  13005. const node = this.startNode();
  13006. this.next();
  13007. return this.finishNode(node, "TSIntrinsicKeyword");
  13008. }
  13009. return this.tsParseType();
  13010. });
  13011. this.semicolon();
  13012. return this.finishNode(node, "TSTypeAliasDeclaration");
  13013. }
  13014. tsInTopLevelContext(cb) {
  13015. if (this.curContext() !== types.brace) {
  13016. const oldContext = this.state.context;
  13017. this.state.context = [oldContext[0]];
  13018. try {
  13019. return cb();
  13020. } finally {
  13021. this.state.context = oldContext;
  13022. }
  13023. } else {
  13024. return cb();
  13025. }
  13026. }
  13027. tsInType(cb) {
  13028. const oldInType = this.state.inType;
  13029. this.state.inType = true;
  13030. try {
  13031. return cb();
  13032. } finally {
  13033. this.state.inType = oldInType;
  13034. }
  13035. }
  13036. tsInDisallowConditionalTypesContext(cb) {
  13037. const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext;
  13038. this.state.inDisallowConditionalTypesContext = true;
  13039. try {
  13040. return cb();
  13041. } finally {
  13042. this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext;
  13043. }
  13044. }
  13045. tsInAllowConditionalTypesContext(cb) {
  13046. const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext;
  13047. this.state.inDisallowConditionalTypesContext = false;
  13048. try {
  13049. return cb();
  13050. } finally {
  13051. this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext;
  13052. }
  13053. }
  13054. tsEatThenParseType(token) {
  13055. if (this.match(token)) {
  13056. return this.tsNextThenParseType();
  13057. }
  13058. }
  13059. tsExpectThenParseType(token) {
  13060. return this.tsInType(() => {
  13061. this.expect(token);
  13062. return this.tsParseType();
  13063. });
  13064. }
  13065. tsNextThenParseType() {
  13066. return this.tsInType(() => {
  13067. this.next();
  13068. return this.tsParseType();
  13069. });
  13070. }
  13071. tsParseEnumMember() {
  13072. const node = this.startNode();
  13073. node.id = this.match(134) ? super.parseStringLiteral(this.state.value) : this.parseIdentifier(true);
  13074. if (this.eat(29)) {
  13075. node.initializer = super.parseMaybeAssignAllowIn();
  13076. }
  13077. return this.finishNode(node, "TSEnumMember");
  13078. }
  13079. tsParseEnumDeclaration(node, properties = {}) {
  13080. if (properties.const) node.const = true;
  13081. if (properties.declare) node.declare = true;
  13082. this.expectContextual(126);
  13083. node.id = this.parseIdentifier();
  13084. this.checkIdentifier(node.id, node.const ? 8971 : 8459);
  13085. this.expect(5);
  13086. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  13087. this.expect(8);
  13088. return this.finishNode(node, "TSEnumDeclaration");
  13089. }
  13090. tsParseEnumBody() {
  13091. const node = this.startNode();
  13092. this.expect(5);
  13093. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  13094. this.expect(8);
  13095. return this.finishNode(node, "TSEnumBody");
  13096. }
  13097. tsParseModuleBlock() {
  13098. const node = this.startNode();
  13099. this.scope.enter(0);
  13100. this.expect(5);
  13101. super.parseBlockOrModuleBlockBody(node.body = [], undefined, true, 8);
  13102. this.scope.exit();
  13103. return this.finishNode(node, "TSModuleBlock");
  13104. }
  13105. tsParseModuleOrNamespaceDeclaration(node, nested = false) {
  13106. node.id = this.parseIdentifier();
  13107. if (!nested) {
  13108. this.checkIdentifier(node.id, 1024);
  13109. }
  13110. if (this.eat(16)) {
  13111. const inner = this.startNode();
  13112. this.tsParseModuleOrNamespaceDeclaration(inner, true);
  13113. node.body = inner;
  13114. } else {
  13115. this.scope.enter(1024);
  13116. this.prodParam.enter(0);
  13117. node.body = this.tsParseModuleBlock();
  13118. this.prodParam.exit();
  13119. this.scope.exit();
  13120. }
  13121. return this.finishNode(node, "TSModuleDeclaration");
  13122. }
  13123. tsParseAmbientExternalModuleDeclaration(node) {
  13124. if (this.isContextual(112)) {
  13125. node.kind = "global";
  13126. node.global = true;
  13127. node.id = this.parseIdentifier();
  13128. } else if (this.match(134)) {
  13129. node.kind = "module";
  13130. node.id = super.parseStringLiteral(this.state.value);
  13131. } else {
  13132. this.unexpected();
  13133. }
  13134. if (this.match(5)) {
  13135. this.scope.enter(1024);
  13136. this.prodParam.enter(0);
  13137. node.body = this.tsParseModuleBlock();
  13138. this.prodParam.exit();
  13139. this.scope.exit();
  13140. } else {
  13141. this.semicolon();
  13142. }
  13143. return this.finishNode(node, "TSModuleDeclaration");
  13144. }
  13145. tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier, isExport) {
  13146. node.isExport = isExport || false;
  13147. node.id = maybeDefaultIdentifier || this.parseIdentifier();
  13148. this.checkIdentifier(node.id, 4096);
  13149. this.expect(29);
  13150. const moduleReference = this.tsParseModuleReference();
  13151. if (node.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") {
  13152. this.raise(TSErrors.ImportAliasHasImportType, moduleReference);
  13153. }
  13154. node.moduleReference = moduleReference;
  13155. this.semicolon();
  13156. return this.finishNode(node, "TSImportEqualsDeclaration");
  13157. }
  13158. tsIsExternalModuleReference() {
  13159. return this.isContextual(119) && this.lookaheadCharCode() === 40;
  13160. }
  13161. tsParseModuleReference() {
  13162. return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(0);
  13163. }
  13164. tsParseExternalModuleReference() {
  13165. const node = this.startNode();
  13166. this.expectContextual(119);
  13167. this.expect(10);
  13168. if (!this.match(134)) {
  13169. this.unexpected();
  13170. }
  13171. node.expression = super.parseExprAtom();
  13172. this.expect(11);
  13173. this.sawUnambiguousESM = true;
  13174. return this.finishNode(node, "TSExternalModuleReference");
  13175. }
  13176. tsLookAhead(f) {
  13177. const state = this.state.clone();
  13178. const res = f();
  13179. this.state = state;
  13180. return res;
  13181. }
  13182. tsTryParseAndCatch(f) {
  13183. const result = this.tryParse(abort => f() || abort());
  13184. if (result.aborted || !result.node) return;
  13185. if (result.error) this.state = result.failState;
  13186. return result.node;
  13187. }
  13188. tsTryParse(f) {
  13189. const state = this.state.clone();
  13190. const result = f();
  13191. if (result !== undefined && result !== false) {
  13192. return result;
  13193. }
  13194. this.state = state;
  13195. }
  13196. tsTryParseDeclare(node) {
  13197. if (this.isLineTerminator()) {
  13198. return;
  13199. }
  13200. const startType = this.state.type;
  13201. return this.tsInAmbientContext(() => {
  13202. switch (startType) {
  13203. case 68:
  13204. node.declare = true;
  13205. return super.parseFunctionStatement(node, false, false);
  13206. case 80:
  13207. node.declare = true;
  13208. return this.parseClass(node, true, false);
  13209. case 126:
  13210. return this.tsParseEnumDeclaration(node, {
  13211. declare: true
  13212. });
  13213. case 112:
  13214. return this.tsParseAmbientExternalModuleDeclaration(node);
  13215. case 100:
  13216. if (this.state.containsEsc) {
  13217. return;
  13218. }
  13219. case 75:
  13220. case 74:
  13221. if (!this.match(75) || !this.isLookaheadContextual("enum")) {
  13222. node.declare = true;
  13223. return this.parseVarStatement(node, this.state.value, true);
  13224. }
  13225. this.expect(75);
  13226. return this.tsParseEnumDeclaration(node, {
  13227. const: true,
  13228. declare: true
  13229. });
  13230. case 107:
  13231. if (this.isUsing()) {
  13232. this.raise(TSErrors.InvalidModifierOnUsingDeclaration, this.state.startLoc, "declare");
  13233. node.declare = true;
  13234. return this.parseVarStatement(node, "using", true);
  13235. }
  13236. break;
  13237. case 96:
  13238. if (this.isAwaitUsing()) {
  13239. this.raise(TSErrors.InvalidModifierOnAwaitUsingDeclaration, this.state.startLoc, "declare");
  13240. node.declare = true;
  13241. this.next();
  13242. return this.parseVarStatement(node, "await using", true);
  13243. }
  13244. break;
  13245. case 129:
  13246. {
  13247. const result = this.tsParseInterfaceDeclaration(node, {
  13248. declare: true
  13249. });
  13250. if (result) return result;
  13251. }
  13252. default:
  13253. if (tokenIsIdentifier(startType)) {
  13254. return this.tsParseDeclaration(node, this.state.type, true, null);
  13255. }
  13256. }
  13257. });
  13258. }
  13259. tsTryParseExportDeclaration() {
  13260. return this.tsParseDeclaration(this.startNode(), this.state.type, true, null);
  13261. }
  13262. tsParseDeclaration(node, type, next, decorators) {
  13263. switch (type) {
  13264. case 124:
  13265. if (this.tsCheckLineTerminator(next) && (this.match(80) || tokenIsIdentifier(this.state.type))) {
  13266. return this.tsParseAbstractDeclaration(node, decorators);
  13267. }
  13268. break;
  13269. case 127:
  13270. if (this.tsCheckLineTerminator(next)) {
  13271. if (this.match(134)) {
  13272. return this.tsParseAmbientExternalModuleDeclaration(node);
  13273. } else if (tokenIsIdentifier(this.state.type)) {
  13274. node.kind = "module";
  13275. return this.tsParseModuleOrNamespaceDeclaration(node);
  13276. }
  13277. }
  13278. break;
  13279. case 128:
  13280. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  13281. node.kind = "namespace";
  13282. return this.tsParseModuleOrNamespaceDeclaration(node);
  13283. }
  13284. break;
  13285. case 130:
  13286. if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
  13287. return this.tsParseTypeAliasDeclaration(node);
  13288. }
  13289. break;
  13290. }
  13291. }
  13292. tsCheckLineTerminator(next) {
  13293. if (next) {
  13294. if (this.hasFollowingLineBreak()) return false;
  13295. this.next();
  13296. return true;
  13297. }
  13298. return !this.isLineTerminator();
  13299. }
  13300. tsTryParseGenericAsyncArrowFunction(startLoc) {
  13301. if (!this.match(47)) return;
  13302. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  13303. this.state.maybeInArrowParameters = true;
  13304. const res = this.tsTryParseAndCatch(() => {
  13305. const node = this.startNodeAt(startLoc);
  13306. node.typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier);
  13307. super.parseFunctionParams(node);
  13308. node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
  13309. this.expect(19);
  13310. return node;
  13311. });
  13312. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  13313. if (!res) return;
  13314. return super.parseArrowExpression(res, null, true);
  13315. }
  13316. tsParseTypeArgumentsInExpression() {
  13317. if (this.reScan_lt() !== 47) return;
  13318. return this.tsParseTypeArguments();
  13319. }
  13320. tsParseTypeArguments() {
  13321. const node = this.startNode();
  13322. node.params = this.tsInType(() => this.tsInTopLevelContext(() => {
  13323. this.expect(47);
  13324. return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
  13325. }));
  13326. if (node.params.length === 0) {
  13327. this.raise(TSErrors.EmptyTypeArguments, node);
  13328. } else if (!this.state.inType && this.curContext() === types.brace) {
  13329. this.reScan_lt_gt();
  13330. }
  13331. this.expect(48);
  13332. return this.finishNode(node, "TSTypeParameterInstantiation");
  13333. }
  13334. tsIsDeclarationStart() {
  13335. return tokenIsTSDeclarationStart(this.state.type);
  13336. }
  13337. isExportDefaultSpecifier() {
  13338. if (this.tsIsDeclarationStart()) return false;
  13339. return super.isExportDefaultSpecifier();
  13340. }
  13341. parseBindingElement(flags, decorators) {
  13342. const startLoc = decorators.length ? decorators[0].loc.start : this.state.startLoc;
  13343. const modified = {};
  13344. this.tsParseModifiers({
  13345. allowedModifiers: ["public", "private", "protected", "override", "readonly"]
  13346. }, modified);
  13347. const accessibility = modified.accessibility;
  13348. const override = modified.override;
  13349. const readonly = modified.readonly;
  13350. if (!(flags & 4) && (accessibility || readonly || override)) {
  13351. this.raise(TSErrors.UnexpectedParameterModifier, startLoc);
  13352. }
  13353. const left = this.parseMaybeDefault();
  13354. if (flags & 2) {
  13355. this.parseFunctionParamType(left);
  13356. }
  13357. const elt = this.parseMaybeDefault(left.loc.start, left);
  13358. if (accessibility || readonly || override) {
  13359. const pp = this.startNodeAt(startLoc);
  13360. if (decorators.length) {
  13361. pp.decorators = decorators;
  13362. }
  13363. if (accessibility) pp.accessibility = accessibility;
  13364. if (readonly) pp.readonly = readonly;
  13365. if (override) pp.override = override;
  13366. if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
  13367. this.raise(TSErrors.UnsupportedParameterPropertyKind, pp);
  13368. }
  13369. pp.parameter = elt;
  13370. return this.finishNode(pp, "TSParameterProperty");
  13371. }
  13372. if (decorators.length) {
  13373. left.decorators = decorators;
  13374. }
  13375. return elt;
  13376. }
  13377. isSimpleParameter(node) {
  13378. return node.type === "TSParameterProperty" && super.isSimpleParameter(node.parameter) || super.isSimpleParameter(node);
  13379. }
  13380. tsDisallowOptionalPattern(node) {
  13381. for (const param of node.params) {
  13382. if (param.type !== "Identifier" && param.optional && !this.state.isAmbientContext) {
  13383. this.raise(TSErrors.PatternIsOptional, param);
  13384. }
  13385. }
  13386. }
  13387. setArrowFunctionParameters(node, params, trailingCommaLoc) {
  13388. super.setArrowFunctionParameters(node, params, trailingCommaLoc);
  13389. this.tsDisallowOptionalPattern(node);
  13390. }
  13391. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  13392. if (this.match(14)) {
  13393. node.returnType = this.tsParseTypeOrTypePredicateAnnotation(14);
  13394. }
  13395. const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" || type === "ClassPrivateMethod" ? "TSDeclareMethod" : undefined;
  13396. if (bodilessType && !this.match(5) && this.isLineTerminator()) {
  13397. return this.finishNode(node, bodilessType);
  13398. }
  13399. if (bodilessType === "TSDeclareFunction" && this.state.isAmbientContext) {
  13400. this.raise(TSErrors.DeclareFunctionHasImplementation, node);
  13401. if (node.declare) {
  13402. return super.parseFunctionBodyAndFinish(node, bodilessType, isMethod);
  13403. }
  13404. }
  13405. this.tsDisallowOptionalPattern(node);
  13406. return super.parseFunctionBodyAndFinish(node, type, isMethod);
  13407. }
  13408. registerFunctionStatementId(node) {
  13409. if (!node.body && node.id) {
  13410. this.checkIdentifier(node.id, 1024);
  13411. } else {
  13412. super.registerFunctionStatementId(node);
  13413. }
  13414. }
  13415. tsCheckForInvalidTypeCasts(items) {
  13416. items.forEach(node => {
  13417. if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") {
  13418. this.raise(TSErrors.UnexpectedTypeAnnotation, node.typeAnnotation);
  13419. }
  13420. });
  13421. }
  13422. toReferencedList(exprList, isInParens) {
  13423. this.tsCheckForInvalidTypeCasts(exprList);
  13424. return exprList;
  13425. }
  13426. parseArrayLike(close, isTuple, refExpressionErrors) {
  13427. const node = super.parseArrayLike(close, isTuple, refExpressionErrors);
  13428. if (node.type === "ArrayExpression") {
  13429. this.tsCheckForInvalidTypeCasts(node.elements);
  13430. }
  13431. return node;
  13432. }
  13433. parseSubscript(base, startLoc, noCalls, state) {
  13434. if (!this.hasPrecedingLineBreak() && this.match(35)) {
  13435. this.state.canStartJSXElement = false;
  13436. this.next();
  13437. const nonNullExpression = this.startNodeAt(startLoc);
  13438. nonNullExpression.expression = base;
  13439. return this.finishNode(nonNullExpression, "TSNonNullExpression");
  13440. }
  13441. let isOptionalCall = false;
  13442. if (this.match(18) && this.lookaheadCharCode() === 60) {
  13443. if (noCalls) {
  13444. state.stop = true;
  13445. return base;
  13446. }
  13447. state.optionalChainMember = isOptionalCall = true;
  13448. this.next();
  13449. }
  13450. if (this.match(47) || this.match(51)) {
  13451. let missingParenErrorLoc;
  13452. const result = this.tsTryParseAndCatch(() => {
  13453. if (!noCalls && this.atPossibleAsyncArrow(base)) {
  13454. const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startLoc);
  13455. if (asyncArrowFn) {
  13456. state.stop = true;
  13457. return asyncArrowFn;
  13458. }
  13459. }
  13460. const typeArguments = this.tsParseTypeArgumentsInExpression();
  13461. if (!typeArguments) return;
  13462. if (isOptionalCall && !this.match(10)) {
  13463. missingParenErrorLoc = this.state.curPosition();
  13464. return;
  13465. }
  13466. if (tokenIsTemplate(this.state.type)) {
  13467. const result = super.parseTaggedTemplateExpression(base, startLoc, state);
  13468. result.typeParameters = typeArguments;
  13469. return result;
  13470. }
  13471. if (!noCalls && this.eat(10)) {
  13472. const node = this.startNodeAt(startLoc);
  13473. node.callee = base;
  13474. node.arguments = this.parseCallExpressionArguments();
  13475. this.tsCheckForInvalidTypeCasts(node.arguments);
  13476. node.typeParameters = typeArguments;
  13477. if (state.optionalChainMember) {
  13478. node.optional = isOptionalCall;
  13479. }
  13480. return this.finishCallExpression(node, state.optionalChainMember);
  13481. }
  13482. const tokenType = this.state.type;
  13483. if (tokenType === 48 || tokenType === 52 || tokenType !== 10 && tokenType !== 93 && tokenType !== 120 && tokenCanStartExpression(tokenType) && !this.hasPrecedingLineBreak()) {
  13484. return;
  13485. }
  13486. const node = this.startNodeAt(startLoc);
  13487. node.expression = base;
  13488. node.typeParameters = typeArguments;
  13489. return this.finishNode(node, "TSInstantiationExpression");
  13490. });
  13491. if (missingParenErrorLoc) {
  13492. this.unexpected(missingParenErrorLoc, 10);
  13493. }
  13494. if (result) {
  13495. if (result.type === "TSInstantiationExpression") {
  13496. if (this.match(16) || this.match(18) && this.lookaheadCharCode() !== 40) {
  13497. this.raise(TSErrors.InvalidPropertyAccessAfterInstantiationExpression, this.state.startLoc);
  13498. }
  13499. if (!this.match(16) && !this.match(18)) {
  13500. result.expression = super.stopParseSubscript(base, state);
  13501. }
  13502. }
  13503. return result;
  13504. }
  13505. }
  13506. return super.parseSubscript(base, startLoc, noCalls, state);
  13507. }
  13508. parseNewCallee(node) {
  13509. var _callee$extra;
  13510. super.parseNewCallee(node);
  13511. const {
  13512. callee
  13513. } = node;
  13514. if (callee.type === "TSInstantiationExpression" && !((_callee$extra = callee.extra) != null && _callee$extra.parenthesized)) {
  13515. node.typeParameters = callee.typeParameters;
  13516. node.callee = callee.expression;
  13517. }
  13518. }
  13519. parseExprOp(left, leftStartLoc, minPrec) {
  13520. let isSatisfies;
  13521. if (tokenOperatorPrecedence(58) > minPrec && !this.hasPrecedingLineBreak() && (this.isContextual(93) || (isSatisfies = this.isContextual(120)))) {
  13522. const node = this.startNodeAt(leftStartLoc);
  13523. node.expression = left;
  13524. node.typeAnnotation = this.tsInType(() => {
  13525. this.next();
  13526. if (this.match(75)) {
  13527. if (isSatisfies) {
  13528. this.raise(Errors.UnexpectedKeyword, this.state.startLoc, {
  13529. keyword: "const"
  13530. });
  13531. }
  13532. return this.tsParseTypeReference();
  13533. }
  13534. return this.tsParseType();
  13535. });
  13536. this.finishNode(node, isSatisfies ? "TSSatisfiesExpression" : "TSAsExpression");
  13537. this.reScan_lt_gt();
  13538. return this.parseExprOp(node, leftStartLoc, minPrec);
  13539. }
  13540. return super.parseExprOp(left, leftStartLoc, minPrec);
  13541. }
  13542. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  13543. if (!this.state.isAmbientContext) {
  13544. super.checkReservedWord(word, startLoc, checkKeywords, isBinding);
  13545. }
  13546. }
  13547. checkImportReflection(node) {
  13548. super.checkImportReflection(node);
  13549. if (node.module && node.importKind !== "value") {
  13550. this.raise(TSErrors.ImportReflectionHasImportType, node.specifiers[0].loc.start);
  13551. }
  13552. }
  13553. checkDuplicateExports() {}
  13554. isPotentialImportPhase(isExport) {
  13555. if (super.isPotentialImportPhase(isExport)) return true;
  13556. if (this.isContextual(130)) {
  13557. const ch = this.lookaheadCharCode();
  13558. return isExport ? ch === 123 || ch === 42 : ch !== 61;
  13559. }
  13560. return !isExport && this.isContextual(87);
  13561. }
  13562. applyImportPhase(node, isExport, phase, loc) {
  13563. super.applyImportPhase(node, isExport, phase, loc);
  13564. if (isExport) {
  13565. node.exportKind = phase === "type" ? "type" : "value";
  13566. } else {
  13567. node.importKind = phase === "type" || phase === "typeof" ? phase : "value";
  13568. }
  13569. }
  13570. parseImport(node) {
  13571. if (this.match(134)) {
  13572. node.importKind = "value";
  13573. return super.parseImport(node);
  13574. }
  13575. let importNode;
  13576. if (tokenIsIdentifier(this.state.type) && this.lookaheadCharCode() === 61) {
  13577. node.importKind = "value";
  13578. return this.tsParseImportEqualsDeclaration(node);
  13579. } else if (this.isContextual(130)) {
  13580. const maybeDefaultIdentifier = this.parseMaybeImportPhase(node, false);
  13581. if (this.lookaheadCharCode() === 61) {
  13582. return this.tsParseImportEqualsDeclaration(node, maybeDefaultIdentifier);
  13583. } else {
  13584. importNode = super.parseImportSpecifiersAndAfter(node, maybeDefaultIdentifier);
  13585. }
  13586. } else {
  13587. importNode = super.parseImport(node);
  13588. }
  13589. if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") {
  13590. this.raise(TSErrors.TypeImportCannotSpecifyDefaultAndNamed, importNode);
  13591. }
  13592. return importNode;
  13593. }
  13594. parseExport(node, decorators) {
  13595. if (this.match(83)) {
  13596. const nodeImportEquals = node;
  13597. this.next();
  13598. let maybeDefaultIdentifier = null;
  13599. if (this.isContextual(130) && this.isPotentialImportPhase(false)) {
  13600. maybeDefaultIdentifier = this.parseMaybeImportPhase(nodeImportEquals, false);
  13601. } else {
  13602. nodeImportEquals.importKind = "value";
  13603. }
  13604. const declaration = this.tsParseImportEqualsDeclaration(nodeImportEquals, maybeDefaultIdentifier, true);
  13605. return declaration;
  13606. } else if (this.eat(29)) {
  13607. const assign = node;
  13608. assign.expression = super.parseExpression();
  13609. this.semicolon();
  13610. this.sawUnambiguousESM = true;
  13611. return this.finishNode(assign, "TSExportAssignment");
  13612. } else if (this.eatContextual(93)) {
  13613. const decl = node;
  13614. this.expectContextual(128);
  13615. decl.id = this.parseIdentifier();
  13616. this.semicolon();
  13617. return this.finishNode(decl, "TSNamespaceExportDeclaration");
  13618. } else {
  13619. return super.parseExport(node, decorators);
  13620. }
  13621. }
  13622. isAbstractClass() {
  13623. return this.isContextual(124) && this.isLookaheadContextual("class");
  13624. }
  13625. parseExportDefaultExpression() {
  13626. if (this.isAbstractClass()) {
  13627. const cls = this.startNode();
  13628. this.next();
  13629. cls.abstract = true;
  13630. return this.parseClass(cls, true, true);
  13631. }
  13632. if (this.match(129)) {
  13633. const result = this.tsParseInterfaceDeclaration(this.startNode());
  13634. if (result) return result;
  13635. }
  13636. return super.parseExportDefaultExpression();
  13637. }
  13638. parseVarStatement(node, kind, allowMissingInitializer = false) {
  13639. const {
  13640. isAmbientContext
  13641. } = this.state;
  13642. const declaration = super.parseVarStatement(node, kind, allowMissingInitializer || isAmbientContext);
  13643. if (!isAmbientContext) return declaration;
  13644. if (!node.declare && (kind === "using" || kind === "await using")) {
  13645. this.raiseOverwrite(TSErrors.UsingDeclarationInAmbientContext, node, kind);
  13646. return declaration;
  13647. }
  13648. for (const {
  13649. id,
  13650. init
  13651. } of declaration.declarations) {
  13652. if (!init) continue;
  13653. if (kind === "var" || kind === "let" || !!id.typeAnnotation) {
  13654. this.raise(TSErrors.InitializerNotAllowedInAmbientContext, init);
  13655. } else if (!isValidAmbientConstInitializer(init, this.hasPlugin("estree"))) {
  13656. this.raise(TSErrors.ConstInitializerMustBeStringOrNumericLiteralOrLiteralEnumReference, init);
  13657. }
  13658. }
  13659. return declaration;
  13660. }
  13661. parseStatementContent(flags, decorators) {
  13662. if (!this.state.containsEsc) {
  13663. switch (this.state.type) {
  13664. case 75:
  13665. {
  13666. if (this.isLookaheadContextual("enum")) {
  13667. const node = this.startNode();
  13668. this.expect(75);
  13669. return this.tsParseEnumDeclaration(node, {
  13670. const: true
  13671. });
  13672. }
  13673. break;
  13674. }
  13675. case 124:
  13676. case 125:
  13677. {
  13678. if (this.nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine()) {
  13679. const token = this.state.type;
  13680. const node = this.startNode();
  13681. this.next();
  13682. const declaration = token === 125 ? this.tsTryParseDeclare(node) : this.tsParseAbstractDeclaration(node, decorators);
  13683. if (declaration) {
  13684. if (token === 125) {
  13685. declaration.declare = true;
  13686. }
  13687. return declaration;
  13688. } else {
  13689. node.expression = this.createIdentifier(this.startNodeAt(node.loc.start), token === 125 ? "declare" : "abstract");
  13690. this.semicolon(false);
  13691. return this.finishNode(node, "ExpressionStatement");
  13692. }
  13693. }
  13694. break;
  13695. }
  13696. case 126:
  13697. return this.tsParseEnumDeclaration(this.startNode());
  13698. case 112:
  13699. {
  13700. const nextCh = this.lookaheadCharCode();
  13701. if (nextCh === 123) {
  13702. const node = this.startNode();
  13703. return this.tsParseAmbientExternalModuleDeclaration(node);
  13704. }
  13705. break;
  13706. }
  13707. case 129:
  13708. {
  13709. const result = this.tsParseInterfaceDeclaration(this.startNode());
  13710. if (result) return result;
  13711. break;
  13712. }
  13713. case 127:
  13714. {
  13715. if (this.nextTokenIsIdentifierOrStringLiteralOnSameLine()) {
  13716. const node = this.startNode();
  13717. this.next();
  13718. return this.tsParseDeclaration(node, 127, false, decorators);
  13719. }
  13720. break;
  13721. }
  13722. case 128:
  13723. {
  13724. if (this.nextTokenIsIdentifierOnSameLine()) {
  13725. const node = this.startNode();
  13726. this.next();
  13727. return this.tsParseDeclaration(node, 128, false, decorators);
  13728. }
  13729. break;
  13730. }
  13731. case 130:
  13732. {
  13733. if (this.nextTokenIsIdentifierOnSameLine()) {
  13734. const node = this.startNode();
  13735. this.next();
  13736. return this.tsParseTypeAliasDeclaration(node);
  13737. }
  13738. break;
  13739. }
  13740. }
  13741. }
  13742. return super.parseStatementContent(flags, decorators);
  13743. }
  13744. parseAccessModifier() {
  13745. return this.tsParseModifier(["public", "protected", "private"]);
  13746. }
  13747. tsHasSomeModifiers(member, modifiers) {
  13748. return modifiers.some(modifier => {
  13749. if (tsIsAccessModifier(modifier)) {
  13750. return member.accessibility === modifier;
  13751. }
  13752. return !!member[modifier];
  13753. });
  13754. }
  13755. tsIsStartOfStaticBlocks() {
  13756. return this.isContextual(106) && this.lookaheadCharCode() === 123;
  13757. }
  13758. parseClassMember(classBody, member, state) {
  13759. const modifiers = ["declare", "private", "public", "protected", "override", "abstract", "readonly", "static"];
  13760. this.tsParseModifiers({
  13761. allowedModifiers: modifiers,
  13762. disallowedModifiers: ["in", "out"],
  13763. stopOnStartOfClassStaticBlock: true,
  13764. errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions
  13765. }, member);
  13766. const callParseClassMemberWithIsStatic = () => {
  13767. if (this.tsIsStartOfStaticBlocks()) {
  13768. this.next();
  13769. this.next();
  13770. if (this.tsHasSomeModifiers(member, modifiers)) {
  13771. this.raise(TSErrors.StaticBlockCannotHaveModifier, this.state.curPosition());
  13772. }
  13773. super.parseClassStaticBlock(classBody, member);
  13774. } else {
  13775. this.parseClassMemberWithIsStatic(classBody, member, state, !!member.static);
  13776. }
  13777. };
  13778. if (member.declare) {
  13779. this.tsInAmbientContext(callParseClassMemberWithIsStatic);
  13780. } else {
  13781. callParseClassMemberWithIsStatic();
  13782. }
  13783. }
  13784. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  13785. const idx = this.tsTryParseIndexSignature(member);
  13786. if (idx) {
  13787. classBody.body.push(idx);
  13788. if (member.abstract) {
  13789. this.raise(TSErrors.IndexSignatureHasAbstract, member);
  13790. }
  13791. if (member.accessibility) {
  13792. this.raise(TSErrors.IndexSignatureHasAccessibility, member, {
  13793. modifier: member.accessibility
  13794. });
  13795. }
  13796. if (member.declare) {
  13797. this.raise(TSErrors.IndexSignatureHasDeclare, member);
  13798. }
  13799. if (member.override) {
  13800. this.raise(TSErrors.IndexSignatureHasOverride, member);
  13801. }
  13802. return;
  13803. }
  13804. if (!this.state.inAbstractClass && member.abstract) {
  13805. this.raise(TSErrors.NonAbstractClassHasAbstractMethod, member);
  13806. }
  13807. if (member.override) {
  13808. if (!state.hadSuperClass) {
  13809. this.raise(TSErrors.OverrideNotInSubClass, member);
  13810. }
  13811. }
  13812. super.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  13813. }
  13814. parsePostMemberNameModifiers(methodOrProp) {
  13815. const optional = this.eat(17);
  13816. if (optional) methodOrProp.optional = true;
  13817. if (methodOrProp.readonly && this.match(10)) {
  13818. this.raise(TSErrors.ClassMethodHasReadonly, methodOrProp);
  13819. }
  13820. if (methodOrProp.declare && this.match(10)) {
  13821. this.raise(TSErrors.ClassMethodHasDeclare, methodOrProp);
  13822. }
  13823. }
  13824. shouldParseExportDeclaration() {
  13825. if (this.tsIsDeclarationStart()) return true;
  13826. return super.shouldParseExportDeclaration();
  13827. }
  13828. parseConditional(expr, startLoc, refExpressionErrors) {
  13829. if (!this.match(17)) return expr;
  13830. if (this.state.maybeInArrowParameters) {
  13831. const nextCh = this.lookaheadCharCode();
  13832. if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) {
  13833. this.setOptionalParametersError(refExpressionErrors);
  13834. return expr;
  13835. }
  13836. }
  13837. return super.parseConditional(expr, startLoc, refExpressionErrors);
  13838. }
  13839. parseParenItem(node, startLoc) {
  13840. const newNode = super.parseParenItem(node, startLoc);
  13841. if (this.eat(17)) {
  13842. newNode.optional = true;
  13843. this.resetEndLocation(node);
  13844. }
  13845. if (this.match(14)) {
  13846. const typeCastNode = this.startNodeAt(startLoc);
  13847. typeCastNode.expression = node;
  13848. typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
  13849. return this.finishNode(typeCastNode, "TSTypeCastExpression");
  13850. }
  13851. return node;
  13852. }
  13853. parseExportDeclaration(node) {
  13854. if (!this.state.isAmbientContext && this.isContextual(125)) {
  13855. return this.tsInAmbientContext(() => this.parseExportDeclaration(node));
  13856. }
  13857. const startLoc = this.state.startLoc;
  13858. const isDeclare = this.eatContextual(125);
  13859. if (isDeclare && (this.isContextual(125) || !this.shouldParseExportDeclaration())) {
  13860. throw this.raise(TSErrors.ExpectedAmbientAfterExportDeclare, this.state.startLoc);
  13861. }
  13862. const isIdentifier = tokenIsIdentifier(this.state.type);
  13863. const declaration = isIdentifier && this.tsTryParseExportDeclaration() || super.parseExportDeclaration(node);
  13864. if (!declaration) return null;
  13865. if (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare) {
  13866. node.exportKind = "type";
  13867. }
  13868. if (isDeclare && declaration.type !== "TSImportEqualsDeclaration") {
  13869. this.resetStartLocation(declaration, startLoc);
  13870. declaration.declare = true;
  13871. }
  13872. return declaration;
  13873. }
  13874. parseClassId(node, isStatement, optionalId, bindingType) {
  13875. if ((!isStatement || optionalId) && this.isContextual(113)) {
  13876. return;
  13877. }
  13878. super.parseClassId(node, isStatement, optionalId, node.declare ? 1024 : 8331);
  13879. const typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);
  13880. if (typeParameters) node.typeParameters = typeParameters;
  13881. }
  13882. parseClassPropertyAnnotation(node) {
  13883. if (!node.optional) {
  13884. if (this.eat(35)) {
  13885. node.definite = true;
  13886. } else if (this.eat(17)) {
  13887. node.optional = true;
  13888. }
  13889. }
  13890. const type = this.tsTryParseTypeAnnotation();
  13891. if (type) node.typeAnnotation = type;
  13892. }
  13893. parseClassProperty(node) {
  13894. this.parseClassPropertyAnnotation(node);
  13895. if (this.state.isAmbientContext && !(node.readonly && !node.typeAnnotation) && this.match(29)) {
  13896. this.raise(TSErrors.DeclareClassFieldHasInitializer, this.state.startLoc);
  13897. }
  13898. if (node.abstract && this.match(29)) {
  13899. const {
  13900. key
  13901. } = node;
  13902. this.raise(TSErrors.AbstractPropertyHasInitializer, this.state.startLoc, {
  13903. propertyName: key.type === "Identifier" && !node.computed ? key.name : `[${this.input.slice(this.offsetToSourcePos(key.start), this.offsetToSourcePos(key.end))}]`
  13904. });
  13905. }
  13906. return super.parseClassProperty(node);
  13907. }
  13908. parseClassPrivateProperty(node) {
  13909. if (node.abstract) {
  13910. this.raise(TSErrors.PrivateElementHasAbstract, node);
  13911. }
  13912. if (node.accessibility) {
  13913. this.raise(TSErrors.PrivateElementHasAccessibility, node, {
  13914. modifier: node.accessibility
  13915. });
  13916. }
  13917. this.parseClassPropertyAnnotation(node);
  13918. return super.parseClassPrivateProperty(node);
  13919. }
  13920. parseClassAccessorProperty(node) {
  13921. this.parseClassPropertyAnnotation(node);
  13922. if (node.optional) {
  13923. this.raise(TSErrors.AccessorCannotBeOptional, node);
  13924. }
  13925. return super.parseClassAccessorProperty(node);
  13926. }
  13927. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  13928. const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  13929. if (typeParameters && isConstructor) {
  13930. this.raise(TSErrors.ConstructorHasTypeParameters, typeParameters);
  13931. }
  13932. const {
  13933. declare = false,
  13934. kind
  13935. } = method;
  13936. if (declare && (kind === "get" || kind === "set")) {
  13937. this.raise(TSErrors.DeclareAccessor, method, {
  13938. kind
  13939. });
  13940. }
  13941. if (typeParameters) method.typeParameters = typeParameters;
  13942. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  13943. }
  13944. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  13945. const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  13946. if (typeParameters) method.typeParameters = typeParameters;
  13947. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  13948. }
  13949. declareClassPrivateMethodInScope(node, kind) {
  13950. if (node.type === "TSDeclareMethod") return;
  13951. if (node.type === "MethodDefinition" && node.value.body == null) {
  13952. return;
  13953. }
  13954. super.declareClassPrivateMethodInScope(node, kind);
  13955. }
  13956. parseClassSuper(node) {
  13957. super.parseClassSuper(node);
  13958. if (node.superClass) {
  13959. if (node.superClass.type === "TSInstantiationExpression") {
  13960. const tsInstantiationExpression = node.superClass;
  13961. const superClass = tsInstantiationExpression.expression;
  13962. this.takeSurroundingComments(superClass, superClass.start, superClass.end);
  13963. const superTypeArguments = tsInstantiationExpression.typeParameters;
  13964. this.takeSurroundingComments(superTypeArguments, superTypeArguments.start, superTypeArguments.end);
  13965. node.superClass = superClass;
  13966. node.superTypeParameters = superTypeArguments;
  13967. } else if (this.match(47) || this.match(51)) {
  13968. node.superTypeParameters = this.tsParseTypeArgumentsInExpression();
  13969. }
  13970. }
  13971. if (this.eatContextual(113)) {
  13972. node.implements = this.tsParseHeritageClause("implements");
  13973. }
  13974. }
  13975. parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  13976. const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  13977. if (typeParameters) prop.typeParameters = typeParameters;
  13978. return super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  13979. }
  13980. parseFunctionParams(node, isConstructor) {
  13981. const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
  13982. if (typeParameters) node.typeParameters = typeParameters;
  13983. super.parseFunctionParams(node, isConstructor);
  13984. }
  13985. parseVarId(decl, kind) {
  13986. super.parseVarId(decl, kind);
  13987. if (decl.id.type === "Identifier" && !this.hasPrecedingLineBreak() && this.eat(35)) {
  13988. decl.definite = true;
  13989. }
  13990. const type = this.tsTryParseTypeAnnotation();
  13991. if (type) {
  13992. decl.id.typeAnnotation = type;
  13993. this.resetEndLocation(decl.id);
  13994. }
  13995. }
  13996. parseAsyncArrowFromCallExpression(node, call) {
  13997. if (this.match(14)) {
  13998. node.returnType = this.tsParseTypeAnnotation();
  13999. }
  14000. return super.parseAsyncArrowFromCallExpression(node, call);
  14001. }
  14002. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  14003. var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2;
  14004. let state;
  14005. let jsx;
  14006. let typeCast;
  14007. if (this.hasPlugin("jsx") && (this.match(143) || this.match(47))) {
  14008. state = this.state.clone();
  14009. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  14010. if (!jsx.error) return jsx.node;
  14011. const {
  14012. context
  14013. } = this.state;
  14014. const currentContext = context[context.length - 1];
  14015. if (currentContext === types.j_oTag || currentContext === types.j_expr) {
  14016. context.pop();
  14017. }
  14018. }
  14019. if (!((_jsx = jsx) != null && _jsx.error) && !this.match(47)) {
  14020. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  14021. }
  14022. if (!state || state === this.state) state = this.state.clone();
  14023. let typeParameters;
  14024. const arrow = this.tryParse(abort => {
  14025. var _expr$extra, _typeParameters;
  14026. typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier);
  14027. const expr = super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  14028. if (expr.type !== "ArrowFunctionExpression" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) {
  14029. abort();
  14030. }
  14031. if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) {
  14032. this.resetStartLocationFromNode(expr, typeParameters);
  14033. }
  14034. expr.typeParameters = typeParameters;
  14035. return expr;
  14036. }, state);
  14037. if (!arrow.error && !arrow.aborted) {
  14038. if (typeParameters) this.reportReservedArrowTypeParam(typeParameters);
  14039. return arrow.node;
  14040. }
  14041. if (!jsx) {
  14042. assert(!this.hasPlugin("jsx"));
  14043. typeCast = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
  14044. if (!typeCast.error) return typeCast.node;
  14045. }
  14046. if ((_jsx2 = jsx) != null && _jsx2.node) {
  14047. this.state = jsx.failState;
  14048. return jsx.node;
  14049. }
  14050. if (arrow.node) {
  14051. this.state = arrow.failState;
  14052. if (typeParameters) this.reportReservedArrowTypeParam(typeParameters);
  14053. return arrow.node;
  14054. }
  14055. if ((_typeCast = typeCast) != null && _typeCast.node) {
  14056. this.state = typeCast.failState;
  14057. return typeCast.node;
  14058. }
  14059. throw ((_jsx3 = jsx) == null ? void 0 : _jsx3.error) || arrow.error || ((_typeCast2 = typeCast) == null ? void 0 : _typeCast2.error);
  14060. }
  14061. reportReservedArrowTypeParam(node) {
  14062. var _node$extra2;
  14063. if (node.params.length === 1 && !node.params[0].constraint && !((_node$extra2 = node.extra) != null && _node$extra2.trailingComma) && this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) {
  14064. this.raise(TSErrors.ReservedArrowTypeParam, node);
  14065. }
  14066. }
  14067. parseMaybeUnary(refExpressionErrors, sawUnary) {
  14068. if (!this.hasPlugin("jsx") && this.match(47)) {
  14069. return this.tsParseTypeAssertion();
  14070. }
  14071. return super.parseMaybeUnary(refExpressionErrors, sawUnary);
  14072. }
  14073. parseArrow(node) {
  14074. if (this.match(14)) {
  14075. const result = this.tryParse(abort => {
  14076. const returnType = this.tsParseTypeOrTypePredicateAnnotation(14);
  14077. if (this.canInsertSemicolon() || !this.match(19)) abort();
  14078. return returnType;
  14079. });
  14080. if (result.aborted) return;
  14081. if (!result.thrown) {
  14082. if (result.error) this.state = result.failState;
  14083. node.returnType = result.node;
  14084. }
  14085. }
  14086. return super.parseArrow(node);
  14087. }
  14088. parseFunctionParamType(param) {
  14089. if (this.eat(17)) {
  14090. param.optional = true;
  14091. }
  14092. const type = this.tsTryParseTypeAnnotation();
  14093. if (type) param.typeAnnotation = type;
  14094. this.resetEndLocation(param);
  14095. return param;
  14096. }
  14097. isAssignable(node, isBinding) {
  14098. switch (node.type) {
  14099. case "TSTypeCastExpression":
  14100. return this.isAssignable(node.expression, isBinding);
  14101. case "TSParameterProperty":
  14102. return true;
  14103. default:
  14104. return super.isAssignable(node, isBinding);
  14105. }
  14106. }
  14107. toAssignable(node, isLHS = false) {
  14108. switch (node.type) {
  14109. case "ParenthesizedExpression":
  14110. this.toAssignableParenthesizedExpression(node, isLHS);
  14111. break;
  14112. case "TSAsExpression":
  14113. case "TSSatisfiesExpression":
  14114. case "TSNonNullExpression":
  14115. case "TSTypeAssertion":
  14116. if (isLHS) {
  14117. this.expressionScope.recordArrowParameterBindingError(TSErrors.UnexpectedTypeCastInParameter, node);
  14118. } else {
  14119. this.raise(TSErrors.UnexpectedTypeCastInParameter, node);
  14120. }
  14121. this.toAssignable(node.expression, isLHS);
  14122. break;
  14123. case "AssignmentExpression":
  14124. if (!isLHS && node.left.type === "TSTypeCastExpression") {
  14125. node.left = this.typeCastToParameter(node.left);
  14126. }
  14127. default:
  14128. super.toAssignable(node, isLHS);
  14129. }
  14130. }
  14131. toAssignableParenthesizedExpression(node, isLHS) {
  14132. switch (node.expression.type) {
  14133. case "TSAsExpression":
  14134. case "TSSatisfiesExpression":
  14135. case "TSNonNullExpression":
  14136. case "TSTypeAssertion":
  14137. case "ParenthesizedExpression":
  14138. this.toAssignable(node.expression, isLHS);
  14139. break;
  14140. default:
  14141. super.toAssignable(node, isLHS);
  14142. }
  14143. }
  14144. checkToRestConversion(node, allowPattern) {
  14145. switch (node.type) {
  14146. case "TSAsExpression":
  14147. case "TSSatisfiesExpression":
  14148. case "TSTypeAssertion":
  14149. case "TSNonNullExpression":
  14150. this.checkToRestConversion(node.expression, false);
  14151. break;
  14152. default:
  14153. super.checkToRestConversion(node, allowPattern);
  14154. }
  14155. }
  14156. isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding) {
  14157. switch (type) {
  14158. case "TSTypeCastExpression":
  14159. return true;
  14160. case "TSParameterProperty":
  14161. return "parameter";
  14162. case "TSNonNullExpression":
  14163. return "expression";
  14164. case "TSAsExpression":
  14165. case "TSSatisfiesExpression":
  14166. case "TSTypeAssertion":
  14167. return (binding !== 64 || !isUnparenthesizedInAssign) && ["expression", true];
  14168. default:
  14169. return super.isValidLVal(type, disallowCallExpression, isUnparenthesizedInAssign, binding);
  14170. }
  14171. }
  14172. parseBindingAtom() {
  14173. if (this.state.type === 78) {
  14174. return this.parseIdentifier(true);
  14175. }
  14176. return super.parseBindingAtom();
  14177. }
  14178. parseMaybeDecoratorArguments(expr, startLoc) {
  14179. if (this.match(47) || this.match(51)) {
  14180. const typeArguments = this.tsParseTypeArgumentsInExpression();
  14181. if (this.match(10)) {
  14182. const call = super.parseMaybeDecoratorArguments(expr, startLoc);
  14183. call.typeParameters = typeArguments;
  14184. return call;
  14185. }
  14186. this.unexpected(null, 10);
  14187. }
  14188. return super.parseMaybeDecoratorArguments(expr, startLoc);
  14189. }
  14190. checkCommaAfterRest(close) {
  14191. if (this.state.isAmbientContext && this.match(12) && this.lookaheadCharCode() === close) {
  14192. this.next();
  14193. return false;
  14194. }
  14195. return super.checkCommaAfterRest(close);
  14196. }
  14197. isClassMethod() {
  14198. return this.match(47) || super.isClassMethod();
  14199. }
  14200. isClassProperty() {
  14201. return this.match(35) || this.match(14) || super.isClassProperty();
  14202. }
  14203. parseMaybeDefault(startLoc, left) {
  14204. const node = super.parseMaybeDefault(startLoc, left);
  14205. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  14206. this.raise(TSErrors.TypeAnnotationAfterAssign, node.typeAnnotation);
  14207. }
  14208. return node;
  14209. }
  14210. getTokenFromCode(code) {
  14211. if (this.state.inType) {
  14212. if (code === 62) {
  14213. this.finishOp(48, 1);
  14214. return;
  14215. }
  14216. if (code === 60) {
  14217. this.finishOp(47, 1);
  14218. return;
  14219. }
  14220. }
  14221. super.getTokenFromCode(code);
  14222. }
  14223. reScan_lt_gt() {
  14224. const {
  14225. type
  14226. } = this.state;
  14227. if (type === 47) {
  14228. this.state.pos -= 1;
  14229. this.readToken_lt();
  14230. } else if (type === 48) {
  14231. this.state.pos -= 1;
  14232. this.readToken_gt();
  14233. }
  14234. }
  14235. reScan_lt() {
  14236. const {
  14237. type
  14238. } = this.state;
  14239. if (type === 51) {
  14240. this.state.pos -= 2;
  14241. this.finishOp(47, 1);
  14242. return 47;
  14243. }
  14244. return type;
  14245. }
  14246. toAssignableListItem(exprList, index, isLHS) {
  14247. const node = exprList[index];
  14248. if (node.type === "TSTypeCastExpression") {
  14249. exprList[index] = this.typeCastToParameter(node);
  14250. }
  14251. super.toAssignableListItem(exprList, index, isLHS);
  14252. }
  14253. typeCastToParameter(node) {
  14254. node.expression.typeAnnotation = node.typeAnnotation;
  14255. this.resetEndLocation(node.expression, node.typeAnnotation.loc.end);
  14256. return node.expression;
  14257. }
  14258. shouldParseArrow(params) {
  14259. if (this.match(14)) {
  14260. return params.every(expr => this.isAssignable(expr, true));
  14261. }
  14262. return super.shouldParseArrow(params);
  14263. }
  14264. shouldParseAsyncArrow() {
  14265. return this.match(14) || super.shouldParseAsyncArrow();
  14266. }
  14267. canHaveLeadingDecorator() {
  14268. return super.canHaveLeadingDecorator() || this.isAbstractClass();
  14269. }
  14270. jsxParseOpeningElementAfterName(node) {
  14271. if (this.match(47) || this.match(51)) {
  14272. const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArgumentsInExpression());
  14273. if (typeArguments) {
  14274. node.typeParameters = typeArguments;
  14275. }
  14276. }
  14277. return super.jsxParseOpeningElementAfterName(node);
  14278. }
  14279. getGetterSetterExpectedParamCount(method) {
  14280. const baseCount = super.getGetterSetterExpectedParamCount(method);
  14281. const params = this.getObjectOrClassMethodParams(method);
  14282. const firstParam = params[0];
  14283. const hasContextParam = firstParam && this.isThisParam(firstParam);
  14284. return hasContextParam ? baseCount + 1 : baseCount;
  14285. }
  14286. parseCatchClauseParam() {
  14287. const param = super.parseCatchClauseParam();
  14288. const type = this.tsTryParseTypeAnnotation();
  14289. if (type) {
  14290. param.typeAnnotation = type;
  14291. this.resetEndLocation(param);
  14292. }
  14293. return param;
  14294. }
  14295. tsInAmbientContext(cb) {
  14296. const {
  14297. isAmbientContext: oldIsAmbientContext,
  14298. strict: oldStrict
  14299. } = this.state;
  14300. this.state.isAmbientContext = true;
  14301. this.state.strict = false;
  14302. try {
  14303. return cb();
  14304. } finally {
  14305. this.state.isAmbientContext = oldIsAmbientContext;
  14306. this.state.strict = oldStrict;
  14307. }
  14308. }
  14309. parseClass(node, isStatement, optionalId) {
  14310. const oldInAbstractClass = this.state.inAbstractClass;
  14311. this.state.inAbstractClass = !!node.abstract;
  14312. try {
  14313. return super.parseClass(node, isStatement, optionalId);
  14314. } finally {
  14315. this.state.inAbstractClass = oldInAbstractClass;
  14316. }
  14317. }
  14318. tsParseAbstractDeclaration(node, decorators) {
  14319. if (this.match(80)) {
  14320. node.abstract = true;
  14321. return this.maybeTakeDecorators(decorators, this.parseClass(node, true, false));
  14322. } else if (this.isContextual(129)) {
  14323. if (!this.hasFollowingLineBreak()) {
  14324. node.abstract = true;
  14325. this.raise(TSErrors.NonClassMethodPropertyHasAbstractModifier, node);
  14326. return this.tsParseInterfaceDeclaration(node);
  14327. } else {
  14328. return null;
  14329. }
  14330. }
  14331. throw this.unexpected(null, 80);
  14332. }
  14333. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope) {
  14334. const method = super.parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  14335. if (method.abstract || method.type === "TSAbstractMethodDefinition") {
  14336. const hasEstreePlugin = this.hasPlugin("estree");
  14337. const methodFn = hasEstreePlugin ? method.value : method;
  14338. if (methodFn.body) {
  14339. const {
  14340. key
  14341. } = method;
  14342. this.raise(TSErrors.AbstractMethodHasImplementation, method, {
  14343. methodName: key.type === "Identifier" && !method.computed ? key.name : `[${this.input.slice(this.offsetToSourcePos(key.start), this.offsetToSourcePos(key.end))}]`
  14344. });
  14345. }
  14346. }
  14347. return method;
  14348. }
  14349. tsParseTypeParameterName() {
  14350. const typeName = this.parseIdentifier();
  14351. return typeName.name;
  14352. }
  14353. shouldParseAsAmbientContext() {
  14354. return !!this.getPluginOption("typescript", "dts");
  14355. }
  14356. parse() {
  14357. if (this.shouldParseAsAmbientContext()) {
  14358. this.state.isAmbientContext = true;
  14359. }
  14360. return super.parse();
  14361. }
  14362. getExpression() {
  14363. if (this.shouldParseAsAmbientContext()) {
  14364. this.state.isAmbientContext = true;
  14365. }
  14366. return super.getExpression();
  14367. }
  14368. parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) {
  14369. if (!isString && isMaybeTypeOnly) {
  14370. this.parseTypeOnlyImportExportSpecifier(node, false, isInTypeExport);
  14371. return this.finishNode(node, "ExportSpecifier");
  14372. }
  14373. node.exportKind = "value";
  14374. return super.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly);
  14375. }
  14376. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) {
  14377. if (!importedIsString && isMaybeTypeOnly) {
  14378. this.parseTypeOnlyImportExportSpecifier(specifier, true, isInTypeOnlyImport);
  14379. return this.finishNode(specifier, "ImportSpecifier");
  14380. }
  14381. specifier.importKind = "value";
  14382. return super.parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, isInTypeOnlyImport ? 4098 : 4096);
  14383. }
  14384. parseTypeOnlyImportExportSpecifier(node, isImport, isInTypeOnlyImportExport) {
  14385. const leftOfAsKey = isImport ? "imported" : "local";
  14386. const rightOfAsKey = isImport ? "local" : "exported";
  14387. let leftOfAs = node[leftOfAsKey];
  14388. let rightOfAs;
  14389. let hasTypeSpecifier = false;
  14390. let canParseAsKeyword = true;
  14391. const loc = leftOfAs.loc.start;
  14392. if (this.isContextual(93)) {
  14393. const firstAs = this.parseIdentifier();
  14394. if (this.isContextual(93)) {
  14395. const secondAs = this.parseIdentifier();
  14396. if (tokenIsKeywordOrIdentifier(this.state.type)) {
  14397. hasTypeSpecifier = true;
  14398. leftOfAs = firstAs;
  14399. rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  14400. canParseAsKeyword = false;
  14401. } else {
  14402. rightOfAs = secondAs;
  14403. canParseAsKeyword = false;
  14404. }
  14405. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  14406. canParseAsKeyword = false;
  14407. rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  14408. } else {
  14409. hasTypeSpecifier = true;
  14410. leftOfAs = firstAs;
  14411. }
  14412. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  14413. hasTypeSpecifier = true;
  14414. if (isImport) {
  14415. leftOfAs = this.parseIdentifier(true);
  14416. if (!this.isContextual(93)) {
  14417. this.checkReservedWord(leftOfAs.name, leftOfAs.loc.start, true, true);
  14418. }
  14419. } else {
  14420. leftOfAs = this.parseModuleExportName();
  14421. }
  14422. }
  14423. if (hasTypeSpecifier && isInTypeOnlyImportExport) {
  14424. this.raise(isImport ? TSErrors.TypeModifierIsUsedInTypeImports : TSErrors.TypeModifierIsUsedInTypeExports, loc);
  14425. }
  14426. node[leftOfAsKey] = leftOfAs;
  14427. node[rightOfAsKey] = rightOfAs;
  14428. const kindKey = isImport ? "importKind" : "exportKind";
  14429. node[kindKey] = hasTypeSpecifier ? "type" : "value";
  14430. if (canParseAsKeyword && this.eatContextual(93)) {
  14431. node[rightOfAsKey] = isImport ? this.parseIdentifier() : this.parseModuleExportName();
  14432. }
  14433. if (!node[rightOfAsKey]) {
  14434. node[rightOfAsKey] = this.cloneIdentifier(node[leftOfAsKey]);
  14435. }
  14436. if (isImport) {
  14437. this.checkIdentifier(node[rightOfAsKey], hasTypeSpecifier ? 4098 : 4096);
  14438. }
  14439. }
  14440. fillOptionalPropertiesForTSESLint(node) {
  14441. 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;
  14442. switch (node.type) {
  14443. case "ExpressionStatement":
  14444. (_node$directive = node.directive) != null ? _node$directive : node.directive = undefined;
  14445. return;
  14446. case "RestElement":
  14447. node.value = undefined;
  14448. case "Identifier":
  14449. case "ArrayPattern":
  14450. case "AssignmentPattern":
  14451. case "ObjectPattern":
  14452. (_node$decorators = node.decorators) != null ? _node$decorators : node.decorators = [];
  14453. (_node$optional = node.optional) != null ? _node$optional : node.optional = false;
  14454. (_node$typeAnnotation = node.typeAnnotation) != null ? _node$typeAnnotation : node.typeAnnotation = undefined;
  14455. return;
  14456. case "TSParameterProperty":
  14457. (_node$accessibility = node.accessibility) != null ? _node$accessibility : node.accessibility = undefined;
  14458. (_node$decorators2 = node.decorators) != null ? _node$decorators2 : node.decorators = [];
  14459. (_node$override = node.override) != null ? _node$override : node.override = false;
  14460. (_node$readonly = node.readonly) != null ? _node$readonly : node.readonly = false;
  14461. (_node$static = node.static) != null ? _node$static : node.static = false;
  14462. return;
  14463. case "TSEmptyBodyFunctionExpression":
  14464. node.body = null;
  14465. case "TSDeclareFunction":
  14466. case "FunctionDeclaration":
  14467. case "FunctionExpression":
  14468. case "ClassMethod":
  14469. case "ClassPrivateMethod":
  14470. (_node$declare = node.declare) != null ? _node$declare : node.declare = false;
  14471. (_node$returnType = node.returnType) != null ? _node$returnType : node.returnType = undefined;
  14472. (_node$typeParameters = node.typeParameters) != null ? _node$typeParameters : node.typeParameters = undefined;
  14473. return;
  14474. case "Property":
  14475. (_node$optional2 = node.optional) != null ? _node$optional2 : node.optional = false;
  14476. return;
  14477. case "TSMethodSignature":
  14478. case "TSPropertySignature":
  14479. (_node$optional3 = node.optional) != null ? _node$optional3 : node.optional = false;
  14480. case "TSIndexSignature":
  14481. (_node$accessibility2 = node.accessibility) != null ? _node$accessibility2 : node.accessibility = undefined;
  14482. (_node$readonly2 = node.readonly) != null ? _node$readonly2 : node.readonly = false;
  14483. (_node$static2 = node.static) != null ? _node$static2 : node.static = false;
  14484. return;
  14485. case "TSAbstractPropertyDefinition":
  14486. case "PropertyDefinition":
  14487. case "TSAbstractAccessorProperty":
  14488. case "AccessorProperty":
  14489. (_node$declare2 = node.declare) != null ? _node$declare2 : node.declare = false;
  14490. (_node$definite = node.definite) != null ? _node$definite : node.definite = false;
  14491. (_node$readonly3 = node.readonly) != null ? _node$readonly3 : node.readonly = false;
  14492. (_node$typeAnnotation2 = node.typeAnnotation) != null ? _node$typeAnnotation2 : node.typeAnnotation = undefined;
  14493. case "TSAbstractMethodDefinition":
  14494. case "MethodDefinition":
  14495. (_node$accessibility3 = node.accessibility) != null ? _node$accessibility3 : node.accessibility = undefined;
  14496. (_node$decorators3 = node.decorators) != null ? _node$decorators3 : node.decorators = [];
  14497. (_node$override2 = node.override) != null ? _node$override2 : node.override = false;
  14498. (_node$optional4 = node.optional) != null ? _node$optional4 : node.optional = false;
  14499. return;
  14500. case "ClassExpression":
  14501. (_node$id = node.id) != null ? _node$id : node.id = null;
  14502. case "ClassDeclaration":
  14503. (_node$abstract = node.abstract) != null ? _node$abstract : node.abstract = false;
  14504. (_node$declare3 = node.declare) != null ? _node$declare3 : node.declare = false;
  14505. (_node$decorators4 = node.decorators) != null ? _node$decorators4 : node.decorators = [];
  14506. (_node$implements = node.implements) != null ? _node$implements : node.implements = [];
  14507. (_node$superTypeArgume = node.superTypeArguments) != null ? _node$superTypeArgume : node.superTypeArguments = undefined;
  14508. (_node$typeParameters2 = node.typeParameters) != null ? _node$typeParameters2 : node.typeParameters = undefined;
  14509. return;
  14510. case "TSTypeAliasDeclaration":
  14511. case "VariableDeclaration":
  14512. (_node$declare4 = node.declare) != null ? _node$declare4 : node.declare = false;
  14513. return;
  14514. case "VariableDeclarator":
  14515. (_node$definite2 = node.definite) != null ? _node$definite2 : node.definite = false;
  14516. return;
  14517. case "TSEnumDeclaration":
  14518. (_node$const = node.const) != null ? _node$const : node.const = false;
  14519. (_node$declare5 = node.declare) != null ? _node$declare5 : node.declare = false;
  14520. return;
  14521. case "TSEnumMember":
  14522. (_node$computed = node.computed) != null ? _node$computed : node.computed = false;
  14523. return;
  14524. case "TSImportType":
  14525. (_node$qualifier = node.qualifier) != null ? _node$qualifier : node.qualifier = null;
  14526. (_node$options = node.options) != null ? _node$options : node.options = null;
  14527. return;
  14528. case "TSInterfaceDeclaration":
  14529. (_node$declare6 = node.declare) != null ? _node$declare6 : node.declare = false;
  14530. (_node$extends = node.extends) != null ? _node$extends : node.extends = [];
  14531. return;
  14532. case "TSMappedType":
  14533. (_node$optional5 = node.optional) != null ? _node$optional5 : node.optional = false;
  14534. (_node$readonly4 = node.readonly) != null ? _node$readonly4 : node.readonly = undefined;
  14535. return;
  14536. case "TSModuleDeclaration":
  14537. (_node$declare7 = node.declare) != null ? _node$declare7 : node.declare = false;
  14538. (_node$global = node.global) != null ? _node$global : node.global = node.kind === "global";
  14539. return;
  14540. case "TSTypeParameter":
  14541. (_node$const2 = node.const) != null ? _node$const2 : node.const = false;
  14542. (_node$in = node.in) != null ? _node$in : node.in = false;
  14543. (_node$out = node.out) != null ? _node$out : node.out = false;
  14544. return;
  14545. }
  14546. }
  14547. chStartsBindingIdentifierAndNotRelationalOperator(ch, pos) {
  14548. if (isIdentifierStart(ch)) {
  14549. keywordAndTSRelationalOperator.lastIndex = pos;
  14550. if (keywordAndTSRelationalOperator.test(this.input)) {
  14551. const endCh = this.codePointAtPos(keywordAndTSRelationalOperator.lastIndex);
  14552. if (!isIdentifierChar(endCh) && endCh !== 92) {
  14553. return false;
  14554. }
  14555. }
  14556. return true;
  14557. } else if (ch === 92) {
  14558. return true;
  14559. } else {
  14560. return false;
  14561. }
  14562. }
  14563. nextTokenIsIdentifierAndNotTSRelationalOperatorOnSameLine() {
  14564. const next = this.nextTokenInLineStart();
  14565. const nextCh = this.codePointAtPos(next);
  14566. return this.chStartsBindingIdentifierAndNotRelationalOperator(nextCh, next);
  14567. }
  14568. nextTokenIsIdentifierOrStringLiteralOnSameLine() {
  14569. const next = this.nextTokenInLineStart();
  14570. const nextCh = this.codePointAtPos(next);
  14571. return this.chStartsBindingIdentifier(nextCh, next) || nextCh === 34 || nextCh === 39;
  14572. }
  14573. };
  14574. function isPossiblyLiteralEnum(expression) {
  14575. if (expression.type !== "MemberExpression") return false;
  14576. const {
  14577. computed,
  14578. property
  14579. } = expression;
  14580. if (computed && property.type !== "StringLiteral" && (property.type !== "TemplateLiteral" || property.expressions.length > 0)) {
  14581. return false;
  14582. }
  14583. return isUncomputedMemberExpressionChain(expression.object);
  14584. }
  14585. function isValidAmbientConstInitializer(expression, estree) {
  14586. var _expression$extra;
  14587. const {
  14588. type
  14589. } = expression;
  14590. if ((_expression$extra = expression.extra) != null && _expression$extra.parenthesized) {
  14591. return false;
  14592. }
  14593. if (estree) {
  14594. if (type === "Literal") {
  14595. const {
  14596. value
  14597. } = expression;
  14598. if (typeof value === "string" || typeof value === "boolean") {
  14599. return true;
  14600. }
  14601. }
  14602. } else {
  14603. if (type === "StringLiteral" || type === "BooleanLiteral") {
  14604. return true;
  14605. }
  14606. }
  14607. if (isNumber(expression, estree) || isNegativeNumber(expression, estree)) {
  14608. return true;
  14609. }
  14610. if (type === "TemplateLiteral" && expression.expressions.length === 0) {
  14611. return true;
  14612. }
  14613. if (isPossiblyLiteralEnum(expression)) {
  14614. return true;
  14615. }
  14616. return false;
  14617. }
  14618. function isNumber(expression, estree) {
  14619. if (estree) {
  14620. return expression.type === "Literal" && (typeof expression.value === "number" || "bigint" in expression);
  14621. }
  14622. return expression.type === "NumericLiteral" || expression.type === "BigIntLiteral";
  14623. }
  14624. function isNegativeNumber(expression, estree) {
  14625. if (expression.type === "UnaryExpression") {
  14626. const {
  14627. operator,
  14628. argument
  14629. } = expression;
  14630. if (operator === "-" && isNumber(argument, estree)) {
  14631. return true;
  14632. }
  14633. }
  14634. return false;
  14635. }
  14636. function isUncomputedMemberExpressionChain(expression) {
  14637. if (expression.type === "Identifier") return true;
  14638. if (expression.type !== "MemberExpression" || expression.computed) {
  14639. return false;
  14640. }
  14641. return isUncomputedMemberExpressionChain(expression.object);
  14642. }
  14643. const PlaceholderErrors = ParseErrorEnum`placeholders`({
  14644. ClassNameIsRequired: "A class name is required.",
  14645. UnexpectedSpace: "Unexpected space in placeholder."
  14646. });
  14647. var placeholders = superClass => class PlaceholdersParserMixin extends superClass {
  14648. parsePlaceholder(expectedNode) {
  14649. if (this.match(133)) {
  14650. const node = this.startNode();
  14651. this.next();
  14652. this.assertNoSpace();
  14653. node.name = super.parseIdentifier(true);
  14654. this.assertNoSpace();
  14655. this.expect(133);
  14656. return this.finishPlaceholder(node, expectedNode);
  14657. }
  14658. }
  14659. finishPlaceholder(node, expectedNode) {
  14660. let placeholder = node;
  14661. if (!placeholder.expectedNode || !placeholder.type) {
  14662. placeholder = this.finishNode(placeholder, "Placeholder");
  14663. }
  14664. placeholder.expectedNode = expectedNode;
  14665. return placeholder;
  14666. }
  14667. getTokenFromCode(code) {
  14668. if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
  14669. this.finishOp(133, 2);
  14670. } else {
  14671. super.getTokenFromCode(code);
  14672. }
  14673. }
  14674. parseExprAtom(refExpressionErrors) {
  14675. return this.parsePlaceholder("Expression") || super.parseExprAtom(refExpressionErrors);
  14676. }
  14677. parseIdentifier(liberal) {
  14678. return this.parsePlaceholder("Identifier") || super.parseIdentifier(liberal);
  14679. }
  14680. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  14681. if (word !== undefined) {
  14682. super.checkReservedWord(word, startLoc, checkKeywords, isBinding);
  14683. }
  14684. }
  14685. cloneIdentifier(node) {
  14686. const cloned = super.cloneIdentifier(node);
  14687. if (cloned.type === "Placeholder") {
  14688. cloned.expectedNode = node.expectedNode;
  14689. }
  14690. return cloned;
  14691. }
  14692. cloneStringLiteral(node) {
  14693. if (node.type === "Placeholder") {
  14694. return this.cloneIdentifier(node);
  14695. }
  14696. return super.cloneStringLiteral(node);
  14697. }
  14698. parseBindingAtom() {
  14699. return this.parsePlaceholder("Pattern") || super.parseBindingAtom();
  14700. }
  14701. isValidLVal(type, disallowCallExpression, isParenthesized, binding) {
  14702. return type === "Placeholder" || super.isValidLVal(type, disallowCallExpression, isParenthesized, binding);
  14703. }
  14704. toAssignable(node, isLHS) {
  14705. if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
  14706. node.expectedNode = "Pattern";
  14707. } else {
  14708. super.toAssignable(node, isLHS);
  14709. }
  14710. }
  14711. chStartsBindingIdentifier(ch, pos) {
  14712. if (super.chStartsBindingIdentifier(ch, pos)) {
  14713. return true;
  14714. }
  14715. const next = this.nextTokenStart();
  14716. if (this.input.charCodeAt(next) === 37 && this.input.charCodeAt(next + 1) === 37) {
  14717. return true;
  14718. }
  14719. return false;
  14720. }
  14721. verifyBreakContinue(node, isBreak) {
  14722. var _node$label;
  14723. if (((_node$label = node.label) == null ? void 0 : _node$label.type) === "Placeholder") return;
  14724. super.verifyBreakContinue(node, isBreak);
  14725. }
  14726. parseExpressionStatement(node, expr) {
  14727. var _expr$extra;
  14728. if (expr.type !== "Placeholder" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) {
  14729. return super.parseExpressionStatement(node, expr);
  14730. }
  14731. if (this.match(14)) {
  14732. const stmt = node;
  14733. stmt.label = this.finishPlaceholder(expr, "Identifier");
  14734. this.next();
  14735. stmt.body = super.parseStatementOrSloppyAnnexBFunctionDeclaration();
  14736. return this.finishNode(stmt, "LabeledStatement");
  14737. }
  14738. this.semicolon();
  14739. const stmtPlaceholder = node;
  14740. stmtPlaceholder.name = expr.name;
  14741. return this.finishPlaceholder(stmtPlaceholder, "Statement");
  14742. }
  14743. parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse) {
  14744. return this.parsePlaceholder("BlockStatement") || super.parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse);
  14745. }
  14746. parseFunctionId(requireId) {
  14747. return this.parsePlaceholder("Identifier") || super.parseFunctionId(requireId);
  14748. }
  14749. parseClass(node, isStatement, optionalId) {
  14750. const type = isStatement ? "ClassDeclaration" : "ClassExpression";
  14751. this.next();
  14752. const oldStrict = this.state.strict;
  14753. const placeholder = this.parsePlaceholder("Identifier");
  14754. if (placeholder) {
  14755. if (this.match(81) || this.match(133) || this.match(5)) {
  14756. node.id = placeholder;
  14757. } else if (optionalId || !isStatement) {
  14758. node.id = null;
  14759. node.body = this.finishPlaceholder(placeholder, "ClassBody");
  14760. return this.finishNode(node, type);
  14761. } else {
  14762. throw this.raise(PlaceholderErrors.ClassNameIsRequired, this.state.startLoc);
  14763. }
  14764. } else {
  14765. this.parseClassId(node, isStatement, optionalId);
  14766. }
  14767. super.parseClassSuper(node);
  14768. node.body = this.parsePlaceholder("ClassBody") || super.parseClassBody(!!node.superClass, oldStrict);
  14769. return this.finishNode(node, type);
  14770. }
  14771. parseExport(node, decorators) {
  14772. const placeholder = this.parsePlaceholder("Identifier");
  14773. if (!placeholder) return super.parseExport(node, decorators);
  14774. const node2 = node;
  14775. if (!this.isContextual(98) && !this.match(12)) {
  14776. node2.specifiers = [];
  14777. node2.source = null;
  14778. node2.declaration = this.finishPlaceholder(placeholder, "Declaration");
  14779. return this.finishNode(node2, "ExportNamedDeclaration");
  14780. }
  14781. this.expectPlugin("exportDefaultFrom");
  14782. const specifier = this.startNode();
  14783. specifier.exported = placeholder;
  14784. node2.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  14785. return super.parseExport(node2, decorators);
  14786. }
  14787. isExportDefaultSpecifier() {
  14788. if (this.match(65)) {
  14789. const next = this.nextTokenStart();
  14790. if (this.isUnparsedContextual(next, "from")) {
  14791. if (this.input.startsWith(tokenLabelName(133), this.nextTokenStartSince(next + 4))) {
  14792. return true;
  14793. }
  14794. }
  14795. }
  14796. return super.isExportDefaultSpecifier();
  14797. }
  14798. maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier) {
  14799. var _specifiers;
  14800. if ((_specifiers = node.specifiers) != null && _specifiers.length) {
  14801. return true;
  14802. }
  14803. return super.maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier);
  14804. }
  14805. checkExport(node) {
  14806. const {
  14807. specifiers
  14808. } = node;
  14809. if (specifiers != null && specifiers.length) {
  14810. node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder");
  14811. }
  14812. super.checkExport(node);
  14813. node.specifiers = specifiers;
  14814. }
  14815. parseImport(node) {
  14816. const placeholder = this.parsePlaceholder("Identifier");
  14817. if (!placeholder) return super.parseImport(node);
  14818. node.specifiers = [];
  14819. if (!this.isContextual(98) && !this.match(12)) {
  14820. node.source = this.finishPlaceholder(placeholder, "StringLiteral");
  14821. this.semicolon();
  14822. return this.finishNode(node, "ImportDeclaration");
  14823. }
  14824. const specifier = this.startNodeAtNode(placeholder);
  14825. specifier.local = placeholder;
  14826. node.specifiers.push(this.finishNode(specifier, "ImportDefaultSpecifier"));
  14827. if (this.eat(12)) {
  14828. const hasStarImport = this.maybeParseStarImportSpecifier(node);
  14829. if (!hasStarImport) this.parseNamedImportSpecifiers(node);
  14830. }
  14831. this.expectContextual(98);
  14832. node.source = this.parseImportSource();
  14833. this.semicolon();
  14834. return this.finishNode(node, "ImportDeclaration");
  14835. }
  14836. parseImportSource() {
  14837. return this.parsePlaceholder("StringLiteral") || super.parseImportSource();
  14838. }
  14839. assertNoSpace() {
  14840. if (this.state.start > this.offsetToSourcePos(this.state.lastTokEndLoc.index)) {
  14841. this.raise(PlaceholderErrors.UnexpectedSpace, this.state.lastTokEndLoc);
  14842. }
  14843. }
  14844. };
  14845. var v8intrinsic = superClass => class V8IntrinsicMixin extends superClass {
  14846. parseV8Intrinsic() {
  14847. if (this.match(54)) {
  14848. const v8IntrinsicStartLoc = this.state.startLoc;
  14849. const node = this.startNode();
  14850. this.next();
  14851. if (tokenIsIdentifier(this.state.type)) {
  14852. const name = this.parseIdentifierName();
  14853. const identifier = this.createIdentifier(node, name);
  14854. this.castNodeTo(identifier, "V8IntrinsicIdentifier");
  14855. if (this.match(10)) {
  14856. return identifier;
  14857. }
  14858. }
  14859. this.unexpected(v8IntrinsicStartLoc);
  14860. }
  14861. }
  14862. parseExprAtom(refExpressionErrors) {
  14863. return this.parseV8Intrinsic() || super.parseExprAtom(refExpressionErrors);
  14864. }
  14865. };
  14866. const PIPELINE_PROPOSALS = ["minimal", "fsharp", "hack", "smart"];
  14867. const TOPIC_TOKENS = ["^^", "@@", "^", "%", "#"];
  14868. function validatePlugins(pluginsMap) {
  14869. if (pluginsMap.has("decorators")) {
  14870. if (pluginsMap.has("decorators-legacy")) {
  14871. throw new Error("Cannot use the decorators and decorators-legacy plugin together");
  14872. }
  14873. const decoratorsBeforeExport = pluginsMap.get("decorators").decoratorsBeforeExport;
  14874. if (decoratorsBeforeExport != null && typeof decoratorsBeforeExport !== "boolean") {
  14875. throw new Error("'decoratorsBeforeExport' must be a boolean, if specified.");
  14876. }
  14877. const allowCallParenthesized = pluginsMap.get("decorators").allowCallParenthesized;
  14878. if (allowCallParenthesized != null && typeof allowCallParenthesized !== "boolean") {
  14879. throw new Error("'allowCallParenthesized' must be a boolean.");
  14880. }
  14881. }
  14882. if (pluginsMap.has("flow") && pluginsMap.has("typescript")) {
  14883. throw new Error("Cannot combine flow and typescript plugins.");
  14884. }
  14885. if (pluginsMap.has("placeholders") && pluginsMap.has("v8intrinsic")) {
  14886. throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
  14887. }
  14888. if (pluginsMap.has("pipelineOperator")) {
  14889. var _pluginsMap$get2;
  14890. const proposal = pluginsMap.get("pipelineOperator").proposal;
  14891. if (!PIPELINE_PROPOSALS.includes(proposal)) {
  14892. const proposalList = PIPELINE_PROPOSALS.map(p => `"${p}"`).join(", ");
  14893. throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${proposalList}.`);
  14894. }
  14895. if (proposal === "hack") {
  14896. var _pluginsMap$get;
  14897. if (pluginsMap.has("placeholders")) {
  14898. throw new Error("Cannot combine placeholders plugin and Hack-style pipes.");
  14899. }
  14900. if (pluginsMap.has("v8intrinsic")) {
  14901. throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes.");
  14902. }
  14903. const topicToken = pluginsMap.get("pipelineOperator").topicToken;
  14904. if (!TOPIC_TOKENS.includes(topicToken)) {
  14905. const tokenList = TOPIC_TOKENS.map(t => `"${t}"`).join(", ");
  14906. throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${tokenList}.`);
  14907. }
  14908. if (topicToken === "#" && ((_pluginsMap$get = pluginsMap.get("recordAndTuple")) == null ? void 0 : _pluginsMap$get.syntaxType) === "hash") {
  14909. throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "hack", topicToken: "#" }]\` and \`${JSON.stringify(["recordAndTuple", pluginsMap.get("recordAndTuple")])}\`.`);
  14910. }
  14911. } else if (proposal === "smart" && ((_pluginsMap$get2 = pluginsMap.get("recordAndTuple")) == null ? void 0 : _pluginsMap$get2.syntaxType) === "hash") {
  14912. throw new Error(`Plugin conflict between \`["pipelineOperator", { proposal: "smart" }]\` and \`${JSON.stringify(["recordAndTuple", pluginsMap.get("recordAndTuple")])}\`.`);
  14913. }
  14914. }
  14915. if (pluginsMap.has("moduleAttributes")) {
  14916. if (pluginsMap.has("deprecatedImportAssert") || pluginsMap.has("importAssertions")) {
  14917. throw new Error("Cannot combine importAssertions, deprecatedImportAssert and moduleAttributes plugins.");
  14918. }
  14919. const moduleAttributesVersionPluginOption = pluginsMap.get("moduleAttributes").version;
  14920. if (moduleAttributesVersionPluginOption !== "may-2020") {
  14921. throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'.");
  14922. }
  14923. }
  14924. if (pluginsMap.has("importAssertions")) {
  14925. if (pluginsMap.has("deprecatedImportAssert")) {
  14926. throw new Error("Cannot combine importAssertions and deprecatedImportAssert plugins.");
  14927. }
  14928. }
  14929. if (pluginsMap.has("deprecatedImportAssert")) ;else if (pluginsMap.has("importAttributes") && pluginsMap.get("importAttributes").deprecatedAssertSyntax) {
  14930. pluginsMap.set("deprecatedImportAssert", {});
  14931. }
  14932. if (pluginsMap.has("recordAndTuple")) {
  14933. const syntaxType = pluginsMap.get("recordAndTuple").syntaxType;
  14934. if (syntaxType != null) {
  14935. const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"];
  14936. if (!RECORD_AND_TUPLE_SYNTAX_TYPES.includes(syntaxType)) {
  14937. throw new Error("The 'syntaxType' option of the 'recordAndTuple' plugin must be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", "));
  14938. }
  14939. }
  14940. }
  14941. if (pluginsMap.has("asyncDoExpressions") && !pluginsMap.has("doExpressions")) {
  14942. const error = new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.");
  14943. error.missingPlugins = "doExpressions";
  14944. throw error;
  14945. }
  14946. if (pluginsMap.has("optionalChainingAssign") && pluginsMap.get("optionalChainingAssign").version !== "2023-07") {
  14947. throw new Error("The 'optionalChainingAssign' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is '2023-07'.");
  14948. }
  14949. if (pluginsMap.has("discardBinding") && pluginsMap.get("discardBinding").syntaxType !== "void") {
  14950. throw new Error("The 'discardBinding' plugin requires a 'syntaxType' option. Currently the only supported value is 'void'.");
  14951. }
  14952. }
  14953. const mixinPlugins = {
  14954. estree,
  14955. jsx,
  14956. flow,
  14957. typescript,
  14958. v8intrinsic,
  14959. placeholders
  14960. };
  14961. const mixinPluginNames = Object.keys(mixinPlugins);
  14962. class ExpressionParser extends LValParser {
  14963. checkProto(prop, isRecord, sawProto, refExpressionErrors) {
  14964. if (prop.type === "SpreadElement" || this.isObjectMethod(prop) || prop.computed || prop.shorthand) {
  14965. return sawProto;
  14966. }
  14967. const key = prop.key;
  14968. const name = key.type === "Identifier" ? key.name : key.value;
  14969. if (name === "__proto__") {
  14970. if (isRecord) {
  14971. this.raise(Errors.RecordNoProto, key);
  14972. return true;
  14973. }
  14974. if (sawProto) {
  14975. if (refExpressionErrors) {
  14976. if (refExpressionErrors.doubleProtoLoc === null) {
  14977. refExpressionErrors.doubleProtoLoc = key.loc.start;
  14978. }
  14979. } else {
  14980. this.raise(Errors.DuplicateProto, key);
  14981. }
  14982. }
  14983. return true;
  14984. }
  14985. return sawProto;
  14986. }
  14987. shouldExitDescending(expr, potentialArrowAt) {
  14988. return expr.type === "ArrowFunctionExpression" && this.offsetToSourcePos(expr.start) === potentialArrowAt;
  14989. }
  14990. getExpression() {
  14991. this.enterInitialScopes();
  14992. this.nextToken();
  14993. if (this.match(140)) {
  14994. throw this.raise(Errors.ParseExpressionEmptyInput, this.state.startLoc);
  14995. }
  14996. const expr = this.parseExpression();
  14997. if (!this.match(140)) {
  14998. throw this.raise(Errors.ParseExpressionExpectsEOF, this.state.startLoc, {
  14999. unexpected: this.input.codePointAt(this.state.start)
  15000. });
  15001. }
  15002. this.finalizeRemainingComments();
  15003. expr.comments = this.comments;
  15004. expr.errors = this.state.errors;
  15005. if (this.optionFlags & 256) {
  15006. expr.tokens = this.tokens;
  15007. }
  15008. return expr;
  15009. }
  15010. parseExpression(disallowIn, refExpressionErrors) {
  15011. if (disallowIn) {
  15012. return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  15013. }
  15014. return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  15015. }
  15016. parseExpressionBase(refExpressionErrors) {
  15017. const startLoc = this.state.startLoc;
  15018. const expr = this.parseMaybeAssign(refExpressionErrors);
  15019. if (this.match(12)) {
  15020. const node = this.startNodeAt(startLoc);
  15021. node.expressions = [expr];
  15022. while (this.eat(12)) {
  15023. node.expressions.push(this.parseMaybeAssign(refExpressionErrors));
  15024. }
  15025. this.toReferencedList(node.expressions);
  15026. return this.finishNode(node, "SequenceExpression");
  15027. }
  15028. return expr;
  15029. }
  15030. parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse) {
  15031. return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
  15032. }
  15033. parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse) {
  15034. return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
  15035. }
  15036. setOptionalParametersError(refExpressionErrors) {
  15037. refExpressionErrors.optionalParametersLoc = this.state.startLoc;
  15038. }
  15039. parseMaybeAssign(refExpressionErrors, afterLeftParse) {
  15040. const startLoc = this.state.startLoc;
  15041. const isYield = this.isContextual(108);
  15042. if (isYield) {
  15043. if (this.prodParam.hasYield) {
  15044. this.next();
  15045. let left = this.parseYield(startLoc);
  15046. if (afterLeftParse) {
  15047. left = afterLeftParse.call(this, left, startLoc);
  15048. }
  15049. return left;
  15050. }
  15051. }
  15052. let ownExpressionErrors;
  15053. if (refExpressionErrors) {
  15054. ownExpressionErrors = false;
  15055. } else {
  15056. refExpressionErrors = new ExpressionErrors();
  15057. ownExpressionErrors = true;
  15058. }
  15059. const {
  15060. type
  15061. } = this.state;
  15062. if (type === 10 || tokenIsIdentifier(type)) {
  15063. this.state.potentialArrowAt = this.state.start;
  15064. }
  15065. let left = this.parseMaybeConditional(refExpressionErrors);
  15066. if (afterLeftParse) {
  15067. left = afterLeftParse.call(this, left, startLoc);
  15068. }
  15069. if (tokenIsAssignment(this.state.type)) {
  15070. const node = this.startNodeAt(startLoc);
  15071. const operator = this.state.value;
  15072. node.operator = operator;
  15073. if (this.match(29)) {
  15074. this.toAssignable(left, true);
  15075. node.left = left;
  15076. const startIndex = startLoc.index;
  15077. if (refExpressionErrors.doubleProtoLoc != null && refExpressionErrors.doubleProtoLoc.index >= startIndex) {
  15078. refExpressionErrors.doubleProtoLoc = null;
  15079. }
  15080. if (refExpressionErrors.shorthandAssignLoc != null && refExpressionErrors.shorthandAssignLoc.index >= startIndex) {
  15081. refExpressionErrors.shorthandAssignLoc = null;
  15082. }
  15083. if (refExpressionErrors.privateKeyLoc != null && refExpressionErrors.privateKeyLoc.index >= startIndex) {
  15084. this.checkDestructuringPrivate(refExpressionErrors);
  15085. refExpressionErrors.privateKeyLoc = null;
  15086. }
  15087. if (refExpressionErrors.voidPatternLoc != null && refExpressionErrors.voidPatternLoc.index >= startIndex) {
  15088. refExpressionErrors.voidPatternLoc = null;
  15089. }
  15090. } else {
  15091. node.left = left;
  15092. }
  15093. this.next();
  15094. node.right = this.parseMaybeAssign();
  15095. this.checkLVal(left, this.finishNode(node, "AssignmentExpression"), undefined, undefined, undefined, undefined, operator === "||=" || operator === "&&=" || operator === "??=");
  15096. return node;
  15097. } else if (ownExpressionErrors) {
  15098. this.checkExpressionErrors(refExpressionErrors, true);
  15099. }
  15100. if (isYield) {
  15101. const {
  15102. type
  15103. } = this.state;
  15104. const startsExpr = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(54);
  15105. if (startsExpr && !this.isAmbiguousPrefixOrIdentifier()) {
  15106. this.raiseOverwrite(Errors.YieldNotInGeneratorFunction, startLoc);
  15107. return this.parseYield(startLoc);
  15108. }
  15109. }
  15110. return left;
  15111. }
  15112. parseMaybeConditional(refExpressionErrors) {
  15113. const startLoc = this.state.startLoc;
  15114. const potentialArrowAt = this.state.potentialArrowAt;
  15115. const expr = this.parseExprOps(refExpressionErrors);
  15116. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  15117. return expr;
  15118. }
  15119. return this.parseConditional(expr, startLoc, refExpressionErrors);
  15120. }
  15121. parseConditional(expr, startLoc, refExpressionErrors) {
  15122. if (this.eat(17)) {
  15123. const node = this.startNodeAt(startLoc);
  15124. node.test = expr;
  15125. node.consequent = this.parseMaybeAssignAllowIn();
  15126. this.expect(14);
  15127. node.alternate = this.parseMaybeAssign();
  15128. return this.finishNode(node, "ConditionalExpression");
  15129. }
  15130. return expr;
  15131. }
  15132. parseMaybeUnaryOrPrivate(refExpressionErrors) {
  15133. return this.match(139) ? this.parsePrivateName() : this.parseMaybeUnary(refExpressionErrors);
  15134. }
  15135. parseExprOps(refExpressionErrors) {
  15136. const startLoc = this.state.startLoc;
  15137. const potentialArrowAt = this.state.potentialArrowAt;
  15138. const expr = this.parseMaybeUnaryOrPrivate(refExpressionErrors);
  15139. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  15140. return expr;
  15141. }
  15142. return this.parseExprOp(expr, startLoc, -1);
  15143. }
  15144. parseExprOp(left, leftStartLoc, minPrec) {
  15145. if (this.isPrivateName(left)) {
  15146. const value = this.getPrivateNameSV(left);
  15147. if (minPrec >= tokenOperatorPrecedence(58) || !this.prodParam.hasIn || !this.match(58)) {
  15148. this.raise(Errors.PrivateInExpectedIn, left, {
  15149. identifierName: value
  15150. });
  15151. }
  15152. this.classScope.usePrivateName(value, left.loc.start);
  15153. }
  15154. const op = this.state.type;
  15155. if (tokenIsOperator(op) && (this.prodParam.hasIn || !this.match(58))) {
  15156. let prec = tokenOperatorPrecedence(op);
  15157. if (prec > minPrec) {
  15158. if (op === 39) {
  15159. this.expectPlugin("pipelineOperator");
  15160. if (this.state.inFSharpPipelineDirectBody) {
  15161. return left;
  15162. }
  15163. this.checkPipelineAtInfixOperator(left, leftStartLoc);
  15164. }
  15165. const node = this.startNodeAt(leftStartLoc);
  15166. node.left = left;
  15167. node.operator = this.state.value;
  15168. const logical = op === 41 || op === 42;
  15169. const coalesce = op === 40;
  15170. if (coalesce) {
  15171. prec = tokenOperatorPrecedence(42);
  15172. }
  15173. this.next();
  15174. if (op === 39 && this.hasPlugin(["pipelineOperator", {
  15175. proposal: "minimal"
  15176. }])) {
  15177. if (this.state.type === 96 && this.prodParam.hasAwait) {
  15178. throw this.raise(Errors.UnexpectedAwaitAfterPipelineBody, this.state.startLoc);
  15179. }
  15180. }
  15181. node.right = this.parseExprOpRightExpr(op, prec);
  15182. const finishedNode = this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression");
  15183. const nextOp = this.state.type;
  15184. if (coalesce && (nextOp === 41 || nextOp === 42) || logical && nextOp === 40) {
  15185. throw this.raise(Errors.MixingCoalesceWithLogical, this.state.startLoc);
  15186. }
  15187. return this.parseExprOp(finishedNode, leftStartLoc, minPrec);
  15188. }
  15189. }
  15190. return left;
  15191. }
  15192. parseExprOpRightExpr(op, prec) {
  15193. const startLoc = this.state.startLoc;
  15194. switch (op) {
  15195. case 39:
  15196. switch (this.getPluginOption("pipelineOperator", "proposal")) {
  15197. case "hack":
  15198. return this.withTopicBindingContext(() => {
  15199. return this.parseHackPipeBody();
  15200. });
  15201. case "fsharp":
  15202. return this.withSoloAwaitPermittingContext(() => {
  15203. return this.parseFSharpPipelineBody(prec);
  15204. });
  15205. }
  15206. if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  15207. return this.withTopicBindingContext(() => {
  15208. if (this.prodParam.hasYield && this.isContextual(108)) {
  15209. throw this.raise(Errors.PipeBodyIsTighter, this.state.startLoc);
  15210. }
  15211. return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(op, prec), startLoc);
  15212. });
  15213. }
  15214. default:
  15215. return this.parseExprOpBaseRightExpr(op, prec);
  15216. }
  15217. }
  15218. parseExprOpBaseRightExpr(op, prec) {
  15219. const startLoc = this.state.startLoc;
  15220. return this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, tokenIsRightAssociative(op) ? prec - 1 : prec);
  15221. }
  15222. parseHackPipeBody() {
  15223. var _body$extra;
  15224. const {
  15225. startLoc
  15226. } = this.state;
  15227. const body = this.parseMaybeAssign();
  15228. const requiredParentheses = UnparenthesizedPipeBodyDescriptions.has(body.type);
  15229. if (requiredParentheses && !((_body$extra = body.extra) != null && _body$extra.parenthesized)) {
  15230. this.raise(Errors.PipeUnparenthesizedBody, startLoc, {
  15231. type: body.type
  15232. });
  15233. }
  15234. if (!this.topicReferenceWasUsedInCurrentContext()) {
  15235. this.raise(Errors.PipeTopicUnused, startLoc);
  15236. }
  15237. return body;
  15238. }
  15239. checkExponentialAfterUnary(node) {
  15240. if (this.match(57)) {
  15241. this.raise(Errors.UnexpectedTokenUnaryExponentiation, node.argument);
  15242. }
  15243. }
  15244. parseMaybeUnary(refExpressionErrors, sawUnary) {
  15245. const startLoc = this.state.startLoc;
  15246. const isAwait = this.isContextual(96);
  15247. if (isAwait && this.recordAwaitIfAllowed()) {
  15248. this.next();
  15249. const expr = this.parseAwait(startLoc);
  15250. if (!sawUnary) this.checkExponentialAfterUnary(expr);
  15251. return expr;
  15252. }
  15253. const update = this.match(34);
  15254. const node = this.startNode();
  15255. if (tokenIsPrefix(this.state.type)) {
  15256. node.operator = this.state.value;
  15257. node.prefix = true;
  15258. if (this.match(72)) {
  15259. this.expectPlugin("throwExpressions");
  15260. }
  15261. const isDelete = this.match(89);
  15262. this.next();
  15263. node.argument = this.parseMaybeUnary(null, true);
  15264. this.checkExpressionErrors(refExpressionErrors, true);
  15265. if (this.state.strict && isDelete) {
  15266. const arg = node.argument;
  15267. if (arg.type === "Identifier") {
  15268. this.raise(Errors.StrictDelete, node);
  15269. } else if (this.hasPropertyAsPrivateName(arg)) {
  15270. this.raise(Errors.DeletePrivateField, node);
  15271. }
  15272. }
  15273. if (!update) {
  15274. if (!sawUnary) {
  15275. this.checkExponentialAfterUnary(node);
  15276. }
  15277. return this.finishNode(node, "UnaryExpression");
  15278. }
  15279. }
  15280. const expr = this.parseUpdate(node, update, refExpressionErrors);
  15281. if (isAwait) {
  15282. const {
  15283. type
  15284. } = this.state;
  15285. const startsExpr = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(54);
  15286. if (startsExpr && !this.isAmbiguousPrefixOrIdentifier()) {
  15287. this.raiseOverwrite(Errors.AwaitNotInAsyncContext, startLoc);
  15288. return this.parseAwait(startLoc);
  15289. }
  15290. }
  15291. return expr;
  15292. }
  15293. parseUpdate(node, update, refExpressionErrors) {
  15294. if (update) {
  15295. const updateExpressionNode = node;
  15296. this.checkLVal(updateExpressionNode.argument, this.finishNode(updateExpressionNode, "UpdateExpression"));
  15297. return node;
  15298. }
  15299. const startLoc = this.state.startLoc;
  15300. let expr = this.parseExprSubscripts(refExpressionErrors);
  15301. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  15302. while (tokenIsPostfix(this.state.type) && !this.canInsertSemicolon()) {
  15303. const node = this.startNodeAt(startLoc);
  15304. node.operator = this.state.value;
  15305. node.prefix = false;
  15306. node.argument = expr;
  15307. this.next();
  15308. this.checkLVal(expr, expr = this.finishNode(node, "UpdateExpression"));
  15309. }
  15310. return expr;
  15311. }
  15312. parseExprSubscripts(refExpressionErrors) {
  15313. const startLoc = this.state.startLoc;
  15314. const potentialArrowAt = this.state.potentialArrowAt;
  15315. const expr = this.parseExprAtom(refExpressionErrors);
  15316. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  15317. return expr;
  15318. }
  15319. return this.parseSubscripts(expr, startLoc);
  15320. }
  15321. parseSubscripts(base, startLoc, noCalls) {
  15322. const state = {
  15323. optionalChainMember: false,
  15324. maybeAsyncArrow: this.atPossibleAsyncArrow(base),
  15325. stop: false
  15326. };
  15327. do {
  15328. base = this.parseSubscript(base, startLoc, noCalls, state);
  15329. state.maybeAsyncArrow = false;
  15330. } while (!state.stop);
  15331. return base;
  15332. }
  15333. parseSubscript(base, startLoc, noCalls, state) {
  15334. const {
  15335. type
  15336. } = this.state;
  15337. if (!noCalls && type === 15) {
  15338. return this.parseBind(base, startLoc, state);
  15339. } else if (tokenIsTemplate(type)) {
  15340. return this.parseTaggedTemplateExpression(base, startLoc, state);
  15341. }
  15342. let optional = false;
  15343. if (type === 18) {
  15344. if (noCalls) {
  15345. this.raise(Errors.OptionalChainingNoNew, this.state.startLoc);
  15346. if (this.lookaheadCharCode() === 40) {
  15347. return this.stopParseSubscript(base, state);
  15348. }
  15349. }
  15350. state.optionalChainMember = optional = true;
  15351. this.next();
  15352. }
  15353. if (!noCalls && this.match(10)) {
  15354. return this.parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional);
  15355. } else {
  15356. const computed = this.eat(0);
  15357. if (computed || optional || this.eat(16)) {
  15358. return this.parseMember(base, startLoc, state, computed, optional);
  15359. } else {
  15360. return this.stopParseSubscript(base, state);
  15361. }
  15362. }
  15363. }
  15364. stopParseSubscript(base, state) {
  15365. state.stop = true;
  15366. return base;
  15367. }
  15368. parseMember(base, startLoc, state, computed, optional) {
  15369. const node = this.startNodeAt(startLoc);
  15370. node.object = base;
  15371. node.computed = computed;
  15372. if (computed) {
  15373. node.property = this.parseExpression();
  15374. this.expect(3);
  15375. } else if (this.match(139)) {
  15376. if (base.type === "Super") {
  15377. this.raise(Errors.SuperPrivateField, startLoc);
  15378. }
  15379. this.classScope.usePrivateName(this.state.value, this.state.startLoc);
  15380. node.property = this.parsePrivateName();
  15381. } else {
  15382. node.property = this.parseIdentifier(true);
  15383. }
  15384. if (state.optionalChainMember) {
  15385. node.optional = optional;
  15386. return this.finishNode(node, "OptionalMemberExpression");
  15387. } else {
  15388. return this.finishNode(node, "MemberExpression");
  15389. }
  15390. }
  15391. parseBind(base, startLoc, state) {
  15392. const node = this.startNodeAt(startLoc);
  15393. node.object = base;
  15394. this.next();
  15395. const isImport = this.match(83);
  15396. const callee = this.parseNoCallExpr();
  15397. if (callee.type === "Super" || isImport && callee.type === "ImportExpression" || callee.type === "Import") {
  15398. throw this.raise(Errors.UnsupportedBindRHS, callee);
  15399. }
  15400. node.callee = callee;
  15401. state.stop = true;
  15402. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startLoc, false);
  15403. }
  15404. parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional) {
  15405. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  15406. let refExpressionErrors = null;
  15407. this.state.maybeInArrowParameters = true;
  15408. this.next();
  15409. const node = this.startNodeAt(startLoc);
  15410. node.callee = base;
  15411. const {
  15412. maybeAsyncArrow,
  15413. optionalChainMember
  15414. } = state;
  15415. if (maybeAsyncArrow) {
  15416. this.expressionScope.enter(newAsyncArrowScope());
  15417. refExpressionErrors = new ExpressionErrors();
  15418. }
  15419. if (optionalChainMember) {
  15420. node.optional = optional;
  15421. }
  15422. if (optional) {
  15423. node.arguments = this.parseCallExpressionArguments();
  15424. } else {
  15425. node.arguments = this.parseCallExpressionArguments(base.type !== "Super", node, refExpressionErrors);
  15426. }
  15427. let finishedNode = this.finishCallExpression(node, optionalChainMember);
  15428. if (maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
  15429. state.stop = true;
  15430. this.checkDestructuringPrivate(refExpressionErrors);
  15431. this.expressionScope.validateAsPattern();
  15432. this.expressionScope.exit();
  15433. finishedNode = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startLoc), finishedNode);
  15434. } else {
  15435. if (maybeAsyncArrow) {
  15436. this.checkExpressionErrors(refExpressionErrors, true);
  15437. this.expressionScope.exit();
  15438. }
  15439. this.toReferencedArguments(finishedNode);
  15440. }
  15441. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  15442. return finishedNode;
  15443. }
  15444. toReferencedArguments(node, isParenthesizedExpr) {
  15445. this.toReferencedListDeep(node.arguments, isParenthesizedExpr);
  15446. }
  15447. parseTaggedTemplateExpression(base, startLoc, state) {
  15448. const node = this.startNodeAt(startLoc);
  15449. node.tag = base;
  15450. node.quasi = this.parseTemplate(true);
  15451. if (state.optionalChainMember) {
  15452. this.raise(Errors.OptionalChainingNoTemplate, startLoc);
  15453. }
  15454. return this.finishNode(node, "TaggedTemplateExpression");
  15455. }
  15456. atPossibleAsyncArrow(base) {
  15457. 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;
  15458. }
  15459. finishCallExpression(node, optional) {
  15460. if (node.callee.type === "Import") {
  15461. if (node.arguments.length === 0 || node.arguments.length > 2) {
  15462. this.raise(Errors.ImportCallArity, node);
  15463. } else {
  15464. for (const arg of node.arguments) {
  15465. if (arg.type === "SpreadElement") {
  15466. this.raise(Errors.ImportCallSpreadArgument, arg);
  15467. }
  15468. }
  15469. }
  15470. }
  15471. return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
  15472. }
  15473. parseCallExpressionArguments(allowPlaceholder, nodeForExtra, refExpressionErrors) {
  15474. const elts = [];
  15475. let first = true;
  15476. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  15477. this.state.inFSharpPipelineDirectBody = false;
  15478. while (!this.eat(11)) {
  15479. if (first) {
  15480. first = false;
  15481. } else {
  15482. this.expect(12);
  15483. if (this.match(11)) {
  15484. if (nodeForExtra) {
  15485. this.addTrailingCommaExtraToNode(nodeForExtra);
  15486. }
  15487. this.next();
  15488. break;
  15489. }
  15490. }
  15491. elts.push(this.parseExprListItem(11, false, refExpressionErrors, allowPlaceholder));
  15492. }
  15493. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  15494. return elts;
  15495. }
  15496. shouldParseAsyncArrow() {
  15497. return this.match(19) && !this.canInsertSemicolon();
  15498. }
  15499. parseAsyncArrowFromCallExpression(node, call) {
  15500. var _call$extra;
  15501. this.resetPreviousNodeTrailingComments(call);
  15502. this.expect(19);
  15503. this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingCommaLoc);
  15504. if (call.innerComments) {
  15505. setInnerComments(node, call.innerComments);
  15506. }
  15507. if (call.callee.trailingComments) {
  15508. setInnerComments(node, call.callee.trailingComments);
  15509. }
  15510. return node;
  15511. }
  15512. parseNoCallExpr() {
  15513. const startLoc = this.state.startLoc;
  15514. return this.parseSubscripts(this.parseExprAtom(), startLoc, true);
  15515. }
  15516. parseExprAtom(refExpressionErrors) {
  15517. let node;
  15518. let decorators = null;
  15519. const {
  15520. type
  15521. } = this.state;
  15522. switch (type) {
  15523. case 79:
  15524. return this.parseSuper();
  15525. case 83:
  15526. node = this.startNode();
  15527. this.next();
  15528. if (this.match(16)) {
  15529. return this.parseImportMetaPropertyOrPhaseCall(node);
  15530. }
  15531. if (this.match(10)) {
  15532. if (this.optionFlags & 512) {
  15533. return this.parseImportCall(node);
  15534. } else {
  15535. return this.finishNode(node, "Import");
  15536. }
  15537. } else {
  15538. this.raise(Errors.UnsupportedImport, this.state.lastTokStartLoc);
  15539. return this.finishNode(node, "Import");
  15540. }
  15541. case 78:
  15542. node = this.startNode();
  15543. this.next();
  15544. return this.finishNode(node, "ThisExpression");
  15545. case 90:
  15546. {
  15547. return this.parseDo(this.startNode(), false);
  15548. }
  15549. case 56:
  15550. case 31:
  15551. {
  15552. this.readRegexp();
  15553. return this.parseRegExpLiteral(this.state.value);
  15554. }
  15555. case 135:
  15556. return this.parseNumericLiteral(this.state.value);
  15557. case 136:
  15558. return this.parseBigIntLiteral(this.state.value);
  15559. case 134:
  15560. return this.parseStringLiteral(this.state.value);
  15561. case 84:
  15562. return this.parseNullLiteral();
  15563. case 85:
  15564. return this.parseBooleanLiteral(true);
  15565. case 86:
  15566. return this.parseBooleanLiteral(false);
  15567. case 10:
  15568. {
  15569. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  15570. return this.parseParenAndDistinguishExpression(canBeArrow);
  15571. }
  15572. case 0:
  15573. {
  15574. return this.parseArrayLike(3, false, refExpressionErrors);
  15575. }
  15576. case 5:
  15577. {
  15578. return this.parseObjectLike(8, false, false, refExpressionErrors);
  15579. }
  15580. case 68:
  15581. return this.parseFunctionOrFunctionSent();
  15582. case 26:
  15583. decorators = this.parseDecorators();
  15584. case 80:
  15585. return this.parseClass(this.maybeTakeDecorators(decorators, this.startNode()), false);
  15586. case 77:
  15587. return this.parseNewOrNewTarget();
  15588. case 25:
  15589. case 24:
  15590. return this.parseTemplate(false);
  15591. case 15:
  15592. {
  15593. node = this.startNode();
  15594. this.next();
  15595. node.object = null;
  15596. const callee = node.callee = this.parseNoCallExpr();
  15597. if (callee.type === "MemberExpression") {
  15598. return this.finishNode(node, "BindExpression");
  15599. } else {
  15600. throw this.raise(Errors.UnsupportedBind, callee);
  15601. }
  15602. }
  15603. case 139:
  15604. {
  15605. this.raise(Errors.PrivateInExpectedIn, this.state.startLoc, {
  15606. identifierName: this.state.value
  15607. });
  15608. return this.parsePrivateName();
  15609. }
  15610. case 33:
  15611. {
  15612. return this.parseTopicReferenceThenEqualsSign(54, "%");
  15613. }
  15614. case 32:
  15615. {
  15616. return this.parseTopicReferenceThenEqualsSign(44, "^");
  15617. }
  15618. case 37:
  15619. case 38:
  15620. {
  15621. return this.parseTopicReference("hack");
  15622. }
  15623. case 44:
  15624. case 54:
  15625. case 27:
  15626. {
  15627. const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
  15628. if (pipeProposal) {
  15629. return this.parseTopicReference(pipeProposal);
  15630. }
  15631. throw this.unexpected();
  15632. }
  15633. case 47:
  15634. {
  15635. const lookaheadCh = this.input.codePointAt(this.nextTokenStart());
  15636. if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) {
  15637. throw this.expectOnePlugin(["jsx", "flow", "typescript"]);
  15638. }
  15639. throw this.unexpected();
  15640. }
  15641. default:
  15642. if (type === 137) {
  15643. return this.parseDecimalLiteral(this.state.value);
  15644. } else if (type === 2 || type === 1) {
  15645. return this.parseArrayLike(this.state.type === 2 ? 4 : 3, true);
  15646. } else if (type === 6 || type === 7) {
  15647. return this.parseObjectLike(this.state.type === 6 ? 9 : 8, false, true);
  15648. }
  15649. if (tokenIsIdentifier(type)) {
  15650. if (this.isContextual(127) && this.lookaheadInLineCharCode() === 123) {
  15651. return this.parseModuleExpression();
  15652. }
  15653. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  15654. const containsEsc = this.state.containsEsc;
  15655. const id = this.parseIdentifier();
  15656. if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) {
  15657. const {
  15658. type
  15659. } = this.state;
  15660. if (type === 68) {
  15661. this.resetPreviousNodeTrailingComments(id);
  15662. this.next();
  15663. return this.parseAsyncFunctionExpression(this.startNodeAtNode(id));
  15664. } else if (tokenIsIdentifier(type)) {
  15665. if (canBeArrow && this.lookaheadCharCode() === 61) {
  15666. return this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(id));
  15667. } else {
  15668. return id;
  15669. }
  15670. } else if (type === 90) {
  15671. this.resetPreviousNodeTrailingComments(id);
  15672. return this.parseDo(this.startNodeAtNode(id), true);
  15673. }
  15674. }
  15675. if (canBeArrow && this.match(19) && !this.canInsertSemicolon()) {
  15676. this.next();
  15677. return this.parseArrowExpression(this.startNodeAtNode(id), [id], false);
  15678. }
  15679. return id;
  15680. } else {
  15681. throw this.unexpected();
  15682. }
  15683. }
  15684. }
  15685. parseTopicReferenceThenEqualsSign(topicTokenType, topicTokenValue) {
  15686. const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
  15687. if (pipeProposal) {
  15688. this.state.type = topicTokenType;
  15689. this.state.value = topicTokenValue;
  15690. this.state.pos--;
  15691. this.state.end--;
  15692. this.state.endLoc = createPositionWithColumnOffset(this.state.endLoc, -1);
  15693. return this.parseTopicReference(pipeProposal);
  15694. }
  15695. throw this.unexpected();
  15696. }
  15697. parseTopicReference(pipeProposal) {
  15698. const node = this.startNode();
  15699. const startLoc = this.state.startLoc;
  15700. const tokenType = this.state.type;
  15701. this.next();
  15702. return this.finishTopicReference(node, startLoc, pipeProposal, tokenType);
  15703. }
  15704. finishTopicReference(node, startLoc, pipeProposal, tokenType) {
  15705. if (this.testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType)) {
  15706. if (pipeProposal === "hack") {
  15707. if (!this.topicReferenceIsAllowedInCurrentContext()) {
  15708. this.raise(Errors.PipeTopicUnbound, startLoc);
  15709. }
  15710. this.registerTopicReference();
  15711. return this.finishNode(node, "TopicReference");
  15712. } else {
  15713. if (!this.topicReferenceIsAllowedInCurrentContext()) {
  15714. this.raise(Errors.PrimaryTopicNotAllowed, startLoc);
  15715. }
  15716. this.registerTopicReference();
  15717. return this.finishNode(node, "PipelinePrimaryTopicReference");
  15718. }
  15719. } else {
  15720. throw this.raise(Errors.PipeTopicUnconfiguredToken, startLoc, {
  15721. token: tokenLabelName(tokenType)
  15722. });
  15723. }
  15724. }
  15725. testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType) {
  15726. switch (pipeProposal) {
  15727. case "hack":
  15728. {
  15729. return this.hasPlugin(["pipelineOperator", {
  15730. topicToken: tokenLabelName(tokenType)
  15731. }]);
  15732. }
  15733. case "smart":
  15734. return tokenType === 27;
  15735. default:
  15736. throw this.raise(Errors.PipeTopicRequiresHackPipes, startLoc);
  15737. }
  15738. }
  15739. parseAsyncArrowUnaryFunction(node) {
  15740. this.prodParam.enter(functionFlags(true, this.prodParam.hasYield));
  15741. const params = [this.parseIdentifier()];
  15742. this.prodParam.exit();
  15743. if (this.hasPrecedingLineBreak()) {
  15744. this.raise(Errors.LineTerminatorBeforeArrow, this.state.curPosition());
  15745. }
  15746. this.expect(19);
  15747. return this.parseArrowExpression(node, params, true);
  15748. }
  15749. parseDo(node, isAsync) {
  15750. this.expectPlugin("doExpressions");
  15751. if (isAsync) {
  15752. this.expectPlugin("asyncDoExpressions");
  15753. }
  15754. node.async = isAsync;
  15755. this.next();
  15756. const oldLabels = this.state.labels;
  15757. this.state.labels = [];
  15758. if (isAsync) {
  15759. this.prodParam.enter(2);
  15760. node.body = this.parseBlock();
  15761. this.prodParam.exit();
  15762. } else {
  15763. node.body = this.parseBlock();
  15764. }
  15765. this.state.labels = oldLabels;
  15766. return this.finishNode(node, "DoExpression");
  15767. }
  15768. parseSuper() {
  15769. const node = this.startNode();
  15770. this.next();
  15771. if (this.match(10) && !this.scope.allowDirectSuper) {
  15772. if (!(this.optionFlags & 16)) {
  15773. this.raise(Errors.SuperNotAllowed, node);
  15774. }
  15775. } else if (!this.scope.allowSuper) {
  15776. if (!(this.optionFlags & 16)) {
  15777. this.raise(Errors.UnexpectedSuper, node);
  15778. }
  15779. }
  15780. if (!this.match(10) && !this.match(0) && !this.match(16)) {
  15781. this.raise(Errors.UnsupportedSuper, node);
  15782. }
  15783. return this.finishNode(node, "Super");
  15784. }
  15785. parsePrivateName() {
  15786. const node = this.startNode();
  15787. const id = this.startNodeAt(createPositionWithColumnOffset(this.state.startLoc, 1));
  15788. const name = this.state.value;
  15789. this.next();
  15790. node.id = this.createIdentifier(id, name);
  15791. return this.finishNode(node, "PrivateName");
  15792. }
  15793. parseFunctionOrFunctionSent() {
  15794. const node = this.startNode();
  15795. this.next();
  15796. if (this.prodParam.hasYield && this.match(16)) {
  15797. const meta = this.createIdentifier(this.startNodeAtNode(node), "function");
  15798. this.next();
  15799. if (this.match(103)) {
  15800. this.expectPlugin("functionSent");
  15801. } else if (!this.hasPlugin("functionSent")) {
  15802. this.unexpected();
  15803. }
  15804. return this.parseMetaProperty(node, meta, "sent");
  15805. }
  15806. return this.parseFunction(node);
  15807. }
  15808. parseMetaProperty(node, meta, propertyName) {
  15809. node.meta = meta;
  15810. const containsEsc = this.state.containsEsc;
  15811. node.property = this.parseIdentifier(true);
  15812. if (node.property.name !== propertyName || containsEsc) {
  15813. this.raise(Errors.UnsupportedMetaProperty, node.property, {
  15814. target: meta.name,
  15815. onlyValidPropertyName: propertyName
  15816. });
  15817. }
  15818. return this.finishNode(node, "MetaProperty");
  15819. }
  15820. parseImportMetaPropertyOrPhaseCall(node) {
  15821. this.next();
  15822. if (this.isContextual(105) || this.isContextual(97)) {
  15823. const isSource = this.isContextual(105);
  15824. this.expectPlugin(isSource ? "sourcePhaseImports" : "deferredImportEvaluation");
  15825. this.next();
  15826. node.phase = isSource ? "source" : "defer";
  15827. return this.parseImportCall(node);
  15828. } else {
  15829. const id = this.createIdentifierAt(this.startNodeAtNode(node), "import", this.state.lastTokStartLoc);
  15830. if (this.isContextual(101)) {
  15831. if (!this.inModule) {
  15832. this.raise(Errors.ImportMetaOutsideModule, id);
  15833. }
  15834. this.sawUnambiguousESM = true;
  15835. }
  15836. return this.parseMetaProperty(node, id, "meta");
  15837. }
  15838. }
  15839. parseLiteralAtNode(value, type, node) {
  15840. this.addExtra(node, "rawValue", value);
  15841. this.addExtra(node, "raw", this.input.slice(this.offsetToSourcePos(node.start), this.state.end));
  15842. node.value = value;
  15843. this.next();
  15844. return this.finishNode(node, type);
  15845. }
  15846. parseLiteral(value, type) {
  15847. const node = this.startNode();
  15848. return this.parseLiteralAtNode(value, type, node);
  15849. }
  15850. parseStringLiteral(value) {
  15851. return this.parseLiteral(value, "StringLiteral");
  15852. }
  15853. parseNumericLiteral(value) {
  15854. return this.parseLiteral(value, "NumericLiteral");
  15855. }
  15856. parseBigIntLiteral(value) {
  15857. return this.parseLiteral(value, "BigIntLiteral");
  15858. }
  15859. parseDecimalLiteral(value) {
  15860. return this.parseLiteral(value, "DecimalLiteral");
  15861. }
  15862. parseRegExpLiteral(value) {
  15863. const node = this.startNode();
  15864. this.addExtra(node, "raw", this.input.slice(this.offsetToSourcePos(node.start), this.state.end));
  15865. node.pattern = value.pattern;
  15866. node.flags = value.flags;
  15867. this.next();
  15868. return this.finishNode(node, "RegExpLiteral");
  15869. }
  15870. parseBooleanLiteral(value) {
  15871. const node = this.startNode();
  15872. node.value = value;
  15873. this.next();
  15874. return this.finishNode(node, "BooleanLiteral");
  15875. }
  15876. parseNullLiteral() {
  15877. const node = this.startNode();
  15878. this.next();
  15879. return this.finishNode(node, "NullLiteral");
  15880. }
  15881. parseParenAndDistinguishExpression(canBeArrow) {
  15882. const startLoc = this.state.startLoc;
  15883. let val;
  15884. this.next();
  15885. this.expressionScope.enter(newArrowHeadScope());
  15886. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  15887. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  15888. this.state.maybeInArrowParameters = true;
  15889. this.state.inFSharpPipelineDirectBody = false;
  15890. const innerStartLoc = this.state.startLoc;
  15891. const exprList = [];
  15892. const refExpressionErrors = new ExpressionErrors();
  15893. let first = true;
  15894. let spreadStartLoc;
  15895. let optionalCommaStartLoc;
  15896. while (!this.match(11)) {
  15897. if (first) {
  15898. first = false;
  15899. } else {
  15900. this.expect(12, refExpressionErrors.optionalParametersLoc === null ? null : refExpressionErrors.optionalParametersLoc);
  15901. if (this.match(11)) {
  15902. optionalCommaStartLoc = this.state.startLoc;
  15903. break;
  15904. }
  15905. }
  15906. if (this.match(21)) {
  15907. const spreadNodeStartLoc = this.state.startLoc;
  15908. spreadStartLoc = this.state.startLoc;
  15909. exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartLoc));
  15910. if (!this.checkCommaAfterRest(41)) {
  15911. break;
  15912. }
  15913. } else {
  15914. exprList.push(this.parseMaybeAssignAllowInOrVoidPattern(11, refExpressionErrors, this.parseParenItem));
  15915. }
  15916. }
  15917. const innerEndLoc = this.state.lastTokEndLoc;
  15918. this.expect(11);
  15919. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  15920. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  15921. let arrowNode = this.startNodeAt(startLoc);
  15922. if (canBeArrow && this.shouldParseArrow(exprList) && (arrowNode = this.parseArrow(arrowNode))) {
  15923. this.checkDestructuringPrivate(refExpressionErrors);
  15924. this.expressionScope.validateAsPattern();
  15925. this.expressionScope.exit();
  15926. this.parseArrowExpression(arrowNode, exprList, false);
  15927. return arrowNode;
  15928. }
  15929. this.expressionScope.exit();
  15930. if (!exprList.length) {
  15931. this.unexpected(this.state.lastTokStartLoc);
  15932. }
  15933. if (optionalCommaStartLoc) this.unexpected(optionalCommaStartLoc);
  15934. if (spreadStartLoc) this.unexpected(spreadStartLoc);
  15935. this.checkExpressionErrors(refExpressionErrors, true);
  15936. this.toReferencedListDeep(exprList, true);
  15937. if (exprList.length > 1) {
  15938. val = this.startNodeAt(innerStartLoc);
  15939. val.expressions = exprList;
  15940. this.finishNode(val, "SequenceExpression");
  15941. this.resetEndLocation(val, innerEndLoc);
  15942. } else {
  15943. val = exprList[0];
  15944. }
  15945. return this.wrapParenthesis(startLoc, val);
  15946. }
  15947. wrapParenthesis(startLoc, expression) {
  15948. if (!(this.optionFlags & 1024)) {
  15949. this.addExtra(expression, "parenthesized", true);
  15950. this.addExtra(expression, "parenStart", startLoc.index);
  15951. this.takeSurroundingComments(expression, startLoc.index, this.state.lastTokEndLoc.index);
  15952. return expression;
  15953. }
  15954. const parenExpression = this.startNodeAt(startLoc);
  15955. parenExpression.expression = expression;
  15956. return this.finishNode(parenExpression, "ParenthesizedExpression");
  15957. }
  15958. shouldParseArrow(params) {
  15959. return !this.canInsertSemicolon();
  15960. }
  15961. parseArrow(node) {
  15962. if (this.eat(19)) {
  15963. return node;
  15964. }
  15965. }
  15966. parseParenItem(node, startLoc) {
  15967. return node;
  15968. }
  15969. parseNewOrNewTarget() {
  15970. const node = this.startNode();
  15971. this.next();
  15972. if (this.match(16)) {
  15973. const meta = this.createIdentifier(this.startNodeAtNode(node), "new");
  15974. this.next();
  15975. const metaProp = this.parseMetaProperty(node, meta, "target");
  15976. if (!this.scope.allowNewTarget) {
  15977. this.raise(Errors.UnexpectedNewTarget, metaProp);
  15978. }
  15979. return metaProp;
  15980. }
  15981. return this.parseNew(node);
  15982. }
  15983. parseNew(node) {
  15984. this.parseNewCallee(node);
  15985. if (this.eat(10)) {
  15986. const args = this.parseExprList(11);
  15987. this.toReferencedList(args);
  15988. node.arguments = args;
  15989. } else {
  15990. node.arguments = [];
  15991. }
  15992. return this.finishNode(node, "NewExpression");
  15993. }
  15994. parseNewCallee(node) {
  15995. const isImport = this.match(83);
  15996. const callee = this.parseNoCallExpr();
  15997. node.callee = callee;
  15998. if (isImport && callee.type === "ImportExpression" || callee.type === "Import") {
  15999. this.raise(Errors.ImportCallNotNewExpression, callee);
  16000. }
  16001. if (callee.type === "Super") {
  16002. this.raise(Errors.SuperCallNotNewExpression, callee);
  16003. }
  16004. }
  16005. parseTemplateElement(isTagged) {
  16006. const {
  16007. start,
  16008. startLoc,
  16009. end,
  16010. value
  16011. } = this.state;
  16012. const elemStart = start + 1;
  16013. const elem = this.startNodeAt(createPositionWithColumnOffset(startLoc, 1));
  16014. if (value === null) {
  16015. if (!isTagged) {
  16016. this.raise(Errors.InvalidEscapeSequenceTemplate, createPositionWithColumnOffset(this.state.firstInvalidTemplateEscapePos, 1));
  16017. }
  16018. }
  16019. const isTail = this.match(24);
  16020. const endOffset = isTail ? -1 : -2;
  16021. const elemEnd = end + endOffset;
  16022. elem.value = {
  16023. raw: this.input.slice(elemStart, elemEnd).replace(/\r\n?/g, "\n"),
  16024. cooked: value === null ? null : value.slice(1, endOffset)
  16025. };
  16026. elem.tail = isTail;
  16027. this.next();
  16028. const finishedNode = this.finishNode(elem, "TemplateElement");
  16029. this.resetEndLocation(finishedNode, createPositionWithColumnOffset(this.state.lastTokEndLoc, endOffset));
  16030. return finishedNode;
  16031. }
  16032. parseTemplate(isTagged) {
  16033. const node = this.startNode();
  16034. let curElt = this.parseTemplateElement(isTagged);
  16035. const quasis = [curElt];
  16036. const substitutions = [];
  16037. while (!curElt.tail) {
  16038. substitutions.push(this.parseTemplateSubstitution());
  16039. this.readTemplateContinuation();
  16040. quasis.push(curElt = this.parseTemplateElement(isTagged));
  16041. }
  16042. node.expressions = substitutions;
  16043. node.quasis = quasis;
  16044. return this.finishNode(node, "TemplateLiteral");
  16045. }
  16046. parseTemplateSubstitution() {
  16047. return this.parseExpression();
  16048. }
  16049. parseObjectLike(close, isPattern, isRecord, refExpressionErrors) {
  16050. if (isRecord) {
  16051. this.expectPlugin("recordAndTuple");
  16052. }
  16053. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  16054. this.state.inFSharpPipelineDirectBody = false;
  16055. let sawProto = false;
  16056. let first = true;
  16057. const node = this.startNode();
  16058. node.properties = [];
  16059. this.next();
  16060. while (!this.match(close)) {
  16061. if (first) {
  16062. first = false;
  16063. } else {
  16064. this.expect(12);
  16065. if (this.match(close)) {
  16066. this.addTrailingCommaExtraToNode(node);
  16067. break;
  16068. }
  16069. }
  16070. let prop;
  16071. if (isPattern) {
  16072. prop = this.parseBindingProperty();
  16073. } else {
  16074. prop = this.parsePropertyDefinition(refExpressionErrors);
  16075. sawProto = this.checkProto(prop, isRecord, sawProto, refExpressionErrors);
  16076. }
  16077. if (isRecord && !this.isObjectProperty(prop) && prop.type !== "SpreadElement") {
  16078. this.raise(Errors.InvalidRecordProperty, prop);
  16079. }
  16080. if (prop.shorthand) {
  16081. this.addExtra(prop, "shorthand", true);
  16082. }
  16083. node.properties.push(prop);
  16084. }
  16085. this.next();
  16086. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  16087. let type = "ObjectExpression";
  16088. if (isPattern) {
  16089. type = "ObjectPattern";
  16090. } else if (isRecord) {
  16091. type = "RecordExpression";
  16092. }
  16093. return this.finishNode(node, type);
  16094. }
  16095. addTrailingCommaExtraToNode(node) {
  16096. this.addExtra(node, "trailingComma", this.state.lastTokStartLoc.index);
  16097. this.addExtra(node, "trailingCommaLoc", this.state.lastTokStartLoc, false);
  16098. }
  16099. maybeAsyncOrAccessorProp(prop) {
  16100. return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(0) || this.match(55));
  16101. }
  16102. parsePropertyDefinition(refExpressionErrors) {
  16103. let decorators = [];
  16104. if (this.match(26)) {
  16105. if (this.hasPlugin("decorators")) {
  16106. this.raise(Errors.UnsupportedPropertyDecorator, this.state.startLoc);
  16107. }
  16108. while (this.match(26)) {
  16109. decorators.push(this.parseDecorator());
  16110. }
  16111. }
  16112. const prop = this.startNode();
  16113. let isAsync = false;
  16114. let isAccessor = false;
  16115. let startLoc;
  16116. if (this.match(21)) {
  16117. if (decorators.length) this.unexpected();
  16118. return this.parseSpread();
  16119. }
  16120. if (decorators.length) {
  16121. prop.decorators = decorators;
  16122. decorators = [];
  16123. }
  16124. prop.method = false;
  16125. if (refExpressionErrors) {
  16126. startLoc = this.state.startLoc;
  16127. }
  16128. let isGenerator = this.eat(55);
  16129. this.parsePropertyNamePrefixOperator(prop);
  16130. const containsEsc = this.state.containsEsc;
  16131. this.parsePropertyName(prop, refExpressionErrors);
  16132. if (!isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) {
  16133. const {
  16134. key
  16135. } = prop;
  16136. const keyName = key.name;
  16137. if (keyName === "async" && !this.hasPrecedingLineBreak()) {
  16138. isAsync = true;
  16139. this.resetPreviousNodeTrailingComments(key);
  16140. isGenerator = this.eat(55);
  16141. this.parsePropertyName(prop);
  16142. }
  16143. if (keyName === "get" || keyName === "set") {
  16144. isAccessor = true;
  16145. this.resetPreviousNodeTrailingComments(key);
  16146. prop.kind = keyName;
  16147. if (this.match(55)) {
  16148. isGenerator = true;
  16149. this.raise(Errors.AccessorIsGenerator, this.state.curPosition(), {
  16150. kind: keyName
  16151. });
  16152. this.next();
  16153. }
  16154. this.parsePropertyName(prop);
  16155. }
  16156. }
  16157. return this.parseObjPropValue(prop, startLoc, isGenerator, isAsync, false, isAccessor, refExpressionErrors);
  16158. }
  16159. getGetterSetterExpectedParamCount(method) {
  16160. return method.kind === "get" ? 0 : 1;
  16161. }
  16162. getObjectOrClassMethodParams(method) {
  16163. return method.params;
  16164. }
  16165. checkGetterSetterParams(method) {
  16166. var _params;
  16167. const paramCount = this.getGetterSetterExpectedParamCount(method);
  16168. const params = this.getObjectOrClassMethodParams(method);
  16169. if (params.length !== paramCount) {
  16170. this.raise(method.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, method);
  16171. }
  16172. if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") {
  16173. this.raise(Errors.BadSetterRestParameter, method);
  16174. }
  16175. }
  16176. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  16177. if (isAccessor) {
  16178. const finishedProp = this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod");
  16179. this.checkGetterSetterParams(finishedProp);
  16180. return finishedProp;
  16181. }
  16182. if (isAsync || isGenerator || this.match(10)) {
  16183. if (isPattern) this.unexpected();
  16184. prop.kind = "method";
  16185. prop.method = true;
  16186. return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
  16187. }
  16188. }
  16189. parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) {
  16190. prop.shorthand = false;
  16191. if (this.eat(14)) {
  16192. prop.value = isPattern ? this.parseMaybeDefault(this.state.startLoc) : this.parseMaybeAssignAllowInOrVoidPattern(8, refExpressionErrors);
  16193. return this.finishObjectProperty(prop);
  16194. }
  16195. if (!prop.computed && prop.key.type === "Identifier") {
  16196. this.checkReservedWord(prop.key.name, prop.key.loc.start, true, false);
  16197. if (isPattern) {
  16198. prop.value = this.parseMaybeDefault(startLoc, this.cloneIdentifier(prop.key));
  16199. } else if (this.match(29)) {
  16200. const shorthandAssignLoc = this.state.startLoc;
  16201. if (refExpressionErrors != null) {
  16202. if (refExpressionErrors.shorthandAssignLoc === null) {
  16203. refExpressionErrors.shorthandAssignLoc = shorthandAssignLoc;
  16204. }
  16205. } else {
  16206. this.raise(Errors.InvalidCoverInitializedName, shorthandAssignLoc);
  16207. }
  16208. prop.value = this.parseMaybeDefault(startLoc, this.cloneIdentifier(prop.key));
  16209. } else {
  16210. prop.value = this.cloneIdentifier(prop.key);
  16211. }
  16212. prop.shorthand = true;
  16213. return this.finishObjectProperty(prop);
  16214. }
  16215. }
  16216. finishObjectProperty(node) {
  16217. return this.finishNode(node, "ObjectProperty");
  16218. }
  16219. parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  16220. const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors);
  16221. if (!node) this.unexpected();
  16222. return node;
  16223. }
  16224. parsePropertyName(prop, refExpressionErrors) {
  16225. if (this.eat(0)) {
  16226. prop.computed = true;
  16227. prop.key = this.parseMaybeAssignAllowIn();
  16228. this.expect(3);
  16229. } else {
  16230. const {
  16231. type,
  16232. value
  16233. } = this.state;
  16234. let key;
  16235. if (tokenIsKeywordOrIdentifier(type)) {
  16236. key = this.parseIdentifier(true);
  16237. } else {
  16238. switch (type) {
  16239. case 135:
  16240. key = this.parseNumericLiteral(value);
  16241. break;
  16242. case 134:
  16243. key = this.parseStringLiteral(value);
  16244. break;
  16245. case 136:
  16246. key = this.parseBigIntLiteral(value);
  16247. break;
  16248. case 139:
  16249. {
  16250. const privateKeyLoc = this.state.startLoc;
  16251. if (refExpressionErrors != null) {
  16252. if (refExpressionErrors.privateKeyLoc === null) {
  16253. refExpressionErrors.privateKeyLoc = privateKeyLoc;
  16254. }
  16255. } else {
  16256. this.raise(Errors.UnexpectedPrivateField, privateKeyLoc);
  16257. }
  16258. key = this.parsePrivateName();
  16259. break;
  16260. }
  16261. default:
  16262. if (type === 137) {
  16263. key = this.parseDecimalLiteral(value);
  16264. break;
  16265. }
  16266. this.unexpected();
  16267. }
  16268. }
  16269. prop.key = key;
  16270. if (type !== 139) {
  16271. prop.computed = false;
  16272. }
  16273. }
  16274. }
  16275. initFunction(node, isAsync) {
  16276. node.id = null;
  16277. node.generator = false;
  16278. node.async = isAsync;
  16279. }
  16280. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  16281. this.initFunction(node, isAsync);
  16282. node.generator = isGenerator;
  16283. this.scope.enter(514 | 16 | (inClassScope ? 576 : 0) | (allowDirectSuper ? 32 : 0));
  16284. this.prodParam.enter(functionFlags(isAsync, node.generator));
  16285. this.parseFunctionParams(node, isConstructor);
  16286. const finishedNode = this.parseFunctionBodyAndFinish(node, type, true);
  16287. this.prodParam.exit();
  16288. this.scope.exit();
  16289. return finishedNode;
  16290. }
  16291. parseArrayLike(close, isTuple, refExpressionErrors) {
  16292. if (isTuple) {
  16293. this.expectPlugin("recordAndTuple");
  16294. }
  16295. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  16296. this.state.inFSharpPipelineDirectBody = false;
  16297. const node = this.startNode();
  16298. this.next();
  16299. node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node);
  16300. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  16301. return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression");
  16302. }
  16303. parseArrowExpression(node, params, isAsync, trailingCommaLoc) {
  16304. this.scope.enter(514 | 4);
  16305. let flags = functionFlags(isAsync, false);
  16306. if (!this.match(5) && this.prodParam.hasIn) {
  16307. flags |= 8;
  16308. }
  16309. this.prodParam.enter(flags);
  16310. this.initFunction(node, isAsync);
  16311. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  16312. if (params) {
  16313. this.state.maybeInArrowParameters = true;
  16314. this.setArrowFunctionParameters(node, params, trailingCommaLoc);
  16315. }
  16316. this.state.maybeInArrowParameters = false;
  16317. this.parseFunctionBody(node, true);
  16318. this.prodParam.exit();
  16319. this.scope.exit();
  16320. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  16321. return this.finishNode(node, "ArrowFunctionExpression");
  16322. }
  16323. setArrowFunctionParameters(node, params, trailingCommaLoc) {
  16324. this.toAssignableList(params, trailingCommaLoc, false);
  16325. node.params = params;
  16326. }
  16327. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  16328. this.parseFunctionBody(node, false, isMethod);
  16329. return this.finishNode(node, type);
  16330. }
  16331. parseFunctionBody(node, allowExpression, isMethod = false) {
  16332. const isExpression = allowExpression && !this.match(5);
  16333. this.expressionScope.enter(newExpressionScope());
  16334. if (isExpression) {
  16335. node.body = this.parseMaybeAssign();
  16336. this.checkParams(node, false, allowExpression, false);
  16337. } else {
  16338. const oldStrict = this.state.strict;
  16339. const oldLabels = this.state.labels;
  16340. this.state.labels = [];
  16341. this.prodParam.enter(this.prodParam.currentFlags() | 4);
  16342. node.body = this.parseBlock(true, false, hasStrictModeDirective => {
  16343. const nonSimple = !this.isSimpleParamList(node.params);
  16344. if (hasStrictModeDirective && nonSimple) {
  16345. this.raise(Errors.IllegalLanguageModeDirective, (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.loc.end : node);
  16346. }
  16347. const strictModeChanged = !oldStrict && this.state.strict;
  16348. this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
  16349. if (this.state.strict && node.id) {
  16350. this.checkIdentifier(node.id, 65, strictModeChanged);
  16351. }
  16352. });
  16353. this.prodParam.exit();
  16354. this.state.labels = oldLabels;
  16355. }
  16356. this.expressionScope.exit();
  16357. }
  16358. isSimpleParameter(node) {
  16359. return node.type === "Identifier";
  16360. }
  16361. isSimpleParamList(params) {
  16362. for (let i = 0, len = params.length; i < len; i++) {
  16363. if (!this.isSimpleParameter(params[i])) return false;
  16364. }
  16365. return true;
  16366. }
  16367. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  16368. const checkClashes = !allowDuplicates && new Set();
  16369. const formalParameters = {
  16370. type: "FormalParameters"
  16371. };
  16372. for (const param of node.params) {
  16373. this.checkLVal(param, formalParameters, 5, checkClashes, strictModeChanged);
  16374. }
  16375. }
  16376. parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) {
  16377. const elts = [];
  16378. let first = true;
  16379. while (!this.eat(close)) {
  16380. if (first) {
  16381. first = false;
  16382. } else {
  16383. this.expect(12);
  16384. if (this.match(close)) {
  16385. if (nodeForExtra) {
  16386. this.addTrailingCommaExtraToNode(nodeForExtra);
  16387. }
  16388. this.next();
  16389. break;
  16390. }
  16391. }
  16392. elts.push(this.parseExprListItem(close, allowEmpty, refExpressionErrors));
  16393. }
  16394. return elts;
  16395. }
  16396. parseExprListItem(close, allowEmpty, refExpressionErrors, allowPlaceholder) {
  16397. let elt;
  16398. if (this.match(12)) {
  16399. if (!allowEmpty) {
  16400. this.raise(Errors.UnexpectedToken, this.state.curPosition(), {
  16401. unexpected: ","
  16402. });
  16403. }
  16404. elt = null;
  16405. } else if (this.match(21)) {
  16406. const spreadNodeStartLoc = this.state.startLoc;
  16407. elt = this.parseParenItem(this.parseSpread(refExpressionErrors), spreadNodeStartLoc);
  16408. } else if (this.match(17)) {
  16409. this.expectPlugin("partialApplication");
  16410. if (!allowPlaceholder) {
  16411. this.raise(Errors.UnexpectedArgumentPlaceholder, this.state.startLoc);
  16412. }
  16413. const node = this.startNode();
  16414. this.next();
  16415. elt = this.finishNode(node, "ArgumentPlaceholder");
  16416. } else {
  16417. elt = this.parseMaybeAssignAllowInOrVoidPattern(close, refExpressionErrors, this.parseParenItem);
  16418. }
  16419. return elt;
  16420. }
  16421. parseIdentifier(liberal) {
  16422. const node = this.startNode();
  16423. const name = this.parseIdentifierName(liberal);
  16424. return this.createIdentifier(node, name);
  16425. }
  16426. createIdentifier(node, name) {
  16427. node.name = name;
  16428. node.loc.identifierName = name;
  16429. return this.finishNode(node, "Identifier");
  16430. }
  16431. createIdentifierAt(node, name, endLoc) {
  16432. node.name = name;
  16433. node.loc.identifierName = name;
  16434. return this.finishNodeAt(node, "Identifier", endLoc);
  16435. }
  16436. parseIdentifierName(liberal) {
  16437. let name;
  16438. const {
  16439. startLoc,
  16440. type
  16441. } = this.state;
  16442. if (tokenIsKeywordOrIdentifier(type)) {
  16443. name = this.state.value;
  16444. } else {
  16445. this.unexpected();
  16446. }
  16447. const tokenIsKeyword = tokenKeywordOrIdentifierIsKeyword(type);
  16448. if (liberal) {
  16449. if (tokenIsKeyword) {
  16450. this.replaceToken(132);
  16451. }
  16452. } else {
  16453. this.checkReservedWord(name, startLoc, tokenIsKeyword, false);
  16454. }
  16455. this.next();
  16456. return name;
  16457. }
  16458. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  16459. if (word.length > 10) {
  16460. return;
  16461. }
  16462. if (!canBeReservedWord(word)) {
  16463. return;
  16464. }
  16465. if (checkKeywords && isKeyword(word)) {
  16466. this.raise(Errors.UnexpectedKeyword, startLoc, {
  16467. keyword: word
  16468. });
  16469. return;
  16470. }
  16471. const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
  16472. if (reservedTest(word, this.inModule)) {
  16473. this.raise(Errors.UnexpectedReservedWord, startLoc, {
  16474. reservedWord: word
  16475. });
  16476. return;
  16477. } else if (word === "yield") {
  16478. if (this.prodParam.hasYield) {
  16479. this.raise(Errors.YieldBindingIdentifier, startLoc);
  16480. return;
  16481. }
  16482. } else if (word === "await") {
  16483. if (this.prodParam.hasAwait) {
  16484. this.raise(Errors.AwaitBindingIdentifier, startLoc);
  16485. return;
  16486. }
  16487. if (this.scope.inStaticBlock) {
  16488. this.raise(Errors.AwaitBindingIdentifierInStaticBlock, startLoc);
  16489. return;
  16490. }
  16491. this.expressionScope.recordAsyncArrowParametersError(startLoc);
  16492. } else if (word === "arguments") {
  16493. if (this.scope.inClassAndNotInNonArrowFunction) {
  16494. this.raise(Errors.ArgumentsInClass, startLoc);
  16495. return;
  16496. }
  16497. }
  16498. }
  16499. recordAwaitIfAllowed() {
  16500. const isAwaitAllowed = this.prodParam.hasAwait;
  16501. if (isAwaitAllowed && !this.scope.inFunction) {
  16502. this.state.hasTopLevelAwait = true;
  16503. }
  16504. return isAwaitAllowed;
  16505. }
  16506. parseAwait(startLoc) {
  16507. const node = this.startNodeAt(startLoc);
  16508. this.expressionScope.recordParameterInitializerError(Errors.AwaitExpressionFormalParameter, node);
  16509. if (this.eat(55)) {
  16510. this.raise(Errors.ObsoleteAwaitStar, node);
  16511. }
  16512. if (!this.scope.inFunction && !(this.optionFlags & 1)) {
  16513. if (this.isAmbiguousPrefixOrIdentifier()) {
  16514. this.ambiguousScriptDifferentAst = true;
  16515. } else {
  16516. this.sawUnambiguousESM = true;
  16517. }
  16518. }
  16519. if (!this.state.soloAwait) {
  16520. node.argument = this.parseMaybeUnary(null, true);
  16521. }
  16522. return this.finishNode(node, "AwaitExpression");
  16523. }
  16524. isAmbiguousPrefixOrIdentifier() {
  16525. if (this.hasPrecedingLineBreak()) return true;
  16526. const {
  16527. type
  16528. } = this.state;
  16529. return type === 53 || type === 10 || type === 0 || tokenIsTemplate(type) || type === 102 && !this.state.containsEsc || type === 138 || type === 56 || this.hasPlugin("v8intrinsic") && type === 54;
  16530. }
  16531. parseYield(startLoc) {
  16532. const node = this.startNodeAt(startLoc);
  16533. this.expressionScope.recordParameterInitializerError(Errors.YieldInParameter, node);
  16534. let delegating = false;
  16535. let argument = null;
  16536. if (!this.hasPrecedingLineBreak()) {
  16537. delegating = this.eat(55);
  16538. switch (this.state.type) {
  16539. case 13:
  16540. case 140:
  16541. case 8:
  16542. case 11:
  16543. case 3:
  16544. case 9:
  16545. case 14:
  16546. case 12:
  16547. if (!delegating) break;
  16548. default:
  16549. argument = this.parseMaybeAssign();
  16550. }
  16551. }
  16552. node.delegate = delegating;
  16553. node.argument = argument;
  16554. return this.finishNode(node, "YieldExpression");
  16555. }
  16556. parseImportCall(node) {
  16557. this.next();
  16558. node.source = this.parseMaybeAssignAllowIn();
  16559. node.options = null;
  16560. if (this.eat(12)) {
  16561. if (!this.match(11)) {
  16562. node.options = this.parseMaybeAssignAllowIn();
  16563. if (this.eat(12)) {
  16564. this.addTrailingCommaExtraToNode(node.options);
  16565. if (!this.match(11)) {
  16566. do {
  16567. this.parseMaybeAssignAllowIn();
  16568. } while (this.eat(12) && !this.match(11));
  16569. this.raise(Errors.ImportCallArity, node);
  16570. }
  16571. }
  16572. } else {
  16573. this.addTrailingCommaExtraToNode(node.source);
  16574. }
  16575. }
  16576. this.expect(11);
  16577. return this.finishNode(node, "ImportExpression");
  16578. }
  16579. checkPipelineAtInfixOperator(left, leftStartLoc) {
  16580. if (this.hasPlugin(["pipelineOperator", {
  16581. proposal: "smart"
  16582. }])) {
  16583. if (left.type === "SequenceExpression") {
  16584. this.raise(Errors.PipelineHeadSequenceExpression, leftStartLoc);
  16585. }
  16586. }
  16587. }
  16588. parseSmartPipelineBodyInStyle(childExpr, startLoc) {
  16589. if (this.isSimpleReference(childExpr)) {
  16590. const bodyNode = this.startNodeAt(startLoc);
  16591. bodyNode.callee = childExpr;
  16592. return this.finishNode(bodyNode, "PipelineBareFunction");
  16593. } else {
  16594. const bodyNode = this.startNodeAt(startLoc);
  16595. this.checkSmartPipeTopicBodyEarlyErrors(startLoc);
  16596. bodyNode.expression = childExpr;
  16597. return this.finishNode(bodyNode, "PipelineTopicExpression");
  16598. }
  16599. }
  16600. isSimpleReference(expression) {
  16601. switch (expression.type) {
  16602. case "MemberExpression":
  16603. return !expression.computed && this.isSimpleReference(expression.object);
  16604. case "Identifier":
  16605. return true;
  16606. default:
  16607. return false;
  16608. }
  16609. }
  16610. checkSmartPipeTopicBodyEarlyErrors(startLoc) {
  16611. if (this.match(19)) {
  16612. throw this.raise(Errors.PipelineBodyNoArrow, this.state.startLoc);
  16613. }
  16614. if (!this.topicReferenceWasUsedInCurrentContext()) {
  16615. this.raise(Errors.PipelineTopicUnused, startLoc);
  16616. }
  16617. }
  16618. withTopicBindingContext(callback) {
  16619. const outerContextTopicState = this.state.topicContext;
  16620. this.state.topicContext = {
  16621. maxNumOfResolvableTopics: 1,
  16622. maxTopicIndex: null
  16623. };
  16624. try {
  16625. return callback();
  16626. } finally {
  16627. this.state.topicContext = outerContextTopicState;
  16628. }
  16629. }
  16630. withSmartMixTopicForbiddingContext(callback) {
  16631. if (this.hasPlugin(["pipelineOperator", {
  16632. proposal: "smart"
  16633. }])) {
  16634. const outerContextTopicState = this.state.topicContext;
  16635. this.state.topicContext = {
  16636. maxNumOfResolvableTopics: 0,
  16637. maxTopicIndex: null
  16638. };
  16639. try {
  16640. return callback();
  16641. } finally {
  16642. this.state.topicContext = outerContextTopicState;
  16643. }
  16644. } else {
  16645. return callback();
  16646. }
  16647. }
  16648. withSoloAwaitPermittingContext(callback) {
  16649. const outerContextSoloAwaitState = this.state.soloAwait;
  16650. this.state.soloAwait = true;
  16651. try {
  16652. return callback();
  16653. } finally {
  16654. this.state.soloAwait = outerContextSoloAwaitState;
  16655. }
  16656. }
  16657. allowInAnd(callback) {
  16658. const flags = this.prodParam.currentFlags();
  16659. const prodParamToSet = 8 & ~flags;
  16660. if (prodParamToSet) {
  16661. this.prodParam.enter(flags | 8);
  16662. try {
  16663. return callback();
  16664. } finally {
  16665. this.prodParam.exit();
  16666. }
  16667. }
  16668. return callback();
  16669. }
  16670. disallowInAnd(callback) {
  16671. const flags = this.prodParam.currentFlags();
  16672. const prodParamToClear = 8 & flags;
  16673. if (prodParamToClear) {
  16674. this.prodParam.enter(flags & -9);
  16675. try {
  16676. return callback();
  16677. } finally {
  16678. this.prodParam.exit();
  16679. }
  16680. }
  16681. return callback();
  16682. }
  16683. registerTopicReference() {
  16684. this.state.topicContext.maxTopicIndex = 0;
  16685. }
  16686. topicReferenceIsAllowedInCurrentContext() {
  16687. return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  16688. }
  16689. topicReferenceWasUsedInCurrentContext() {
  16690. return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  16691. }
  16692. parseFSharpPipelineBody(prec) {
  16693. const startLoc = this.state.startLoc;
  16694. this.state.potentialArrowAt = this.state.start;
  16695. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  16696. this.state.inFSharpPipelineDirectBody = true;
  16697. const ret = this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, prec);
  16698. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  16699. return ret;
  16700. }
  16701. parseModuleExpression() {
  16702. this.expectPlugin("moduleBlocks");
  16703. const node = this.startNode();
  16704. this.next();
  16705. if (!this.match(5)) {
  16706. this.unexpected(null, 5);
  16707. }
  16708. const program = this.startNodeAt(this.state.endLoc);
  16709. this.next();
  16710. const revertScopes = this.initializeScopes(true);
  16711. this.enterInitialScopes();
  16712. try {
  16713. node.body = this.parseProgram(program, 8, "module");
  16714. } finally {
  16715. revertScopes();
  16716. }
  16717. return this.finishNode(node, "ModuleExpression");
  16718. }
  16719. parseVoidPattern(refExpressionErrors) {
  16720. this.expectPlugin("discardBinding");
  16721. const node = this.startNode();
  16722. if (refExpressionErrors != null) {
  16723. refExpressionErrors.voidPatternLoc = this.state.startLoc;
  16724. }
  16725. this.next();
  16726. return this.finishNode(node, "VoidPattern");
  16727. }
  16728. parseMaybeAssignAllowInOrVoidPattern(close, refExpressionErrors, afterLeftParse) {
  16729. if (refExpressionErrors != null && this.match(88)) {
  16730. const nextCode = this.lookaheadCharCode();
  16731. if (nextCode === 44 || nextCode === (close === 3 ? 93 : close === 8 ? 125 : 41) || nextCode === 61) {
  16732. return this.parseMaybeDefault(this.state.startLoc, this.parseVoidPattern(refExpressionErrors));
  16733. }
  16734. }
  16735. return this.parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse);
  16736. }
  16737. parsePropertyNamePrefixOperator(prop) {}
  16738. }
  16739. const loopLabel = {
  16740. kind: 1
  16741. },
  16742. switchLabel = {
  16743. kind: 2
  16744. };
  16745. const loneSurrogate = /[\uD800-\uDFFF]/u;
  16746. const keywordRelationalOperator = /in(?:stanceof)?/y;
  16747. function babel7CompatTokens(tokens, input, startIndex) {
  16748. for (let i = 0; i < tokens.length; i++) {
  16749. const token = tokens[i];
  16750. const {
  16751. type
  16752. } = token;
  16753. if (typeof type === "number") {
  16754. if (type === 139) {
  16755. const {
  16756. loc,
  16757. start,
  16758. value,
  16759. end
  16760. } = token;
  16761. const hashEndPos = start + 1;
  16762. const hashEndLoc = createPositionWithColumnOffset(loc.start, 1);
  16763. tokens.splice(i, 1, new Token({
  16764. type: getExportedToken(27),
  16765. value: "#",
  16766. start: start,
  16767. end: hashEndPos,
  16768. startLoc: loc.start,
  16769. endLoc: hashEndLoc
  16770. }), new Token({
  16771. type: getExportedToken(132),
  16772. value: value,
  16773. start: hashEndPos,
  16774. end: end,
  16775. startLoc: hashEndLoc,
  16776. endLoc: loc.end
  16777. }));
  16778. i++;
  16779. continue;
  16780. }
  16781. if (tokenIsTemplate(type)) {
  16782. const {
  16783. loc,
  16784. start,
  16785. value,
  16786. end
  16787. } = token;
  16788. const backquoteEnd = start + 1;
  16789. const backquoteEndLoc = createPositionWithColumnOffset(loc.start, 1);
  16790. let startToken;
  16791. if (input.charCodeAt(start - startIndex) === 96) {
  16792. startToken = new Token({
  16793. type: getExportedToken(22),
  16794. value: "`",
  16795. start: start,
  16796. end: backquoteEnd,
  16797. startLoc: loc.start,
  16798. endLoc: backquoteEndLoc
  16799. });
  16800. } else {
  16801. startToken = new Token({
  16802. type: getExportedToken(8),
  16803. value: "}",
  16804. start: start,
  16805. end: backquoteEnd,
  16806. startLoc: loc.start,
  16807. endLoc: backquoteEndLoc
  16808. });
  16809. }
  16810. let templateValue, templateElementEnd, templateElementEndLoc, endToken;
  16811. if (type === 24) {
  16812. templateElementEnd = end - 1;
  16813. templateElementEndLoc = createPositionWithColumnOffset(loc.end, -1);
  16814. templateValue = value === null ? null : value.slice(1, -1);
  16815. endToken = new Token({
  16816. type: getExportedToken(22),
  16817. value: "`",
  16818. start: templateElementEnd,
  16819. end: end,
  16820. startLoc: templateElementEndLoc,
  16821. endLoc: loc.end
  16822. });
  16823. } else {
  16824. templateElementEnd = end - 2;
  16825. templateElementEndLoc = createPositionWithColumnOffset(loc.end, -2);
  16826. templateValue = value === null ? null : value.slice(1, -2);
  16827. endToken = new Token({
  16828. type: getExportedToken(23),
  16829. value: "${",
  16830. start: templateElementEnd,
  16831. end: end,
  16832. startLoc: templateElementEndLoc,
  16833. endLoc: loc.end
  16834. });
  16835. }
  16836. tokens.splice(i, 1, startToken, new Token({
  16837. type: getExportedToken(20),
  16838. value: templateValue,
  16839. start: backquoteEnd,
  16840. end: templateElementEnd,
  16841. startLoc: backquoteEndLoc,
  16842. endLoc: templateElementEndLoc
  16843. }), endToken);
  16844. i += 2;
  16845. continue;
  16846. }
  16847. token.type = getExportedToken(type);
  16848. }
  16849. }
  16850. return tokens;
  16851. }
  16852. class StatementParser extends ExpressionParser {
  16853. parseTopLevel(file, program) {
  16854. file.program = this.parseProgram(program, 140, this.options.sourceType === "module" ? "module" : "script");
  16855. file.comments = this.comments;
  16856. if (this.optionFlags & 256) {
  16857. file.tokens = babel7CompatTokens(this.tokens, this.input, this.startIndex);
  16858. }
  16859. return this.finishNode(file, "File");
  16860. }
  16861. parseProgram(program, end, sourceType) {
  16862. program.sourceType = sourceType;
  16863. program.interpreter = this.parseInterpreterDirective();
  16864. this.parseBlockBody(program, true, true, end);
  16865. if (this.inModule) {
  16866. if (!(this.optionFlags & 64) && this.scope.undefinedExports.size > 0) {
  16867. for (const [localName, at] of Array.from(this.scope.undefinedExports)) {
  16868. this.raise(Errors.ModuleExportUndefined, at, {
  16869. localName
  16870. });
  16871. }
  16872. }
  16873. this.addExtra(program, "topLevelAwait", this.state.hasTopLevelAwait);
  16874. }
  16875. let finishedProgram;
  16876. if (end === 140) {
  16877. finishedProgram = this.finishNode(program, "Program");
  16878. } else {
  16879. finishedProgram = this.finishNodeAt(program, "Program", createPositionWithColumnOffset(this.state.startLoc, -1));
  16880. }
  16881. return finishedProgram;
  16882. }
  16883. stmtToDirective(stmt) {
  16884. const directive = this.castNodeTo(stmt, "Directive");
  16885. const directiveLiteral = this.castNodeTo(stmt.expression, "DirectiveLiteral");
  16886. const expressionValue = directiveLiteral.value;
  16887. const raw = this.input.slice(this.offsetToSourcePos(directiveLiteral.start), this.offsetToSourcePos(directiveLiteral.end));
  16888. const val = directiveLiteral.value = raw.slice(1, -1);
  16889. this.addExtra(directiveLiteral, "raw", raw);
  16890. this.addExtra(directiveLiteral, "rawValue", val);
  16891. this.addExtra(directiveLiteral, "expressionValue", expressionValue);
  16892. directive.value = directiveLiteral;
  16893. delete stmt.expression;
  16894. return directive;
  16895. }
  16896. parseInterpreterDirective() {
  16897. if (!this.match(28)) {
  16898. return null;
  16899. }
  16900. const node = this.startNode();
  16901. node.value = this.state.value;
  16902. this.next();
  16903. return this.finishNode(node, "InterpreterDirective");
  16904. }
  16905. isLet() {
  16906. if (!this.isContextual(100)) {
  16907. return false;
  16908. }
  16909. return this.hasFollowingBindingAtom();
  16910. }
  16911. isUsing() {
  16912. if (!this.isContextual(107)) {
  16913. return false;
  16914. }
  16915. return this.nextTokenIsIdentifierOnSameLine();
  16916. }
  16917. isForUsing() {
  16918. if (!this.isContextual(107)) {
  16919. return false;
  16920. }
  16921. const next = this.nextTokenInLineStart();
  16922. const nextCh = this.codePointAtPos(next);
  16923. if (this.isUnparsedContextual(next, "of")) {
  16924. const nextCharAfterOf = this.lookaheadCharCodeSince(next + 2);
  16925. if (nextCharAfterOf !== 61 && nextCharAfterOf !== 58 && nextCharAfterOf !== 59) {
  16926. return false;
  16927. }
  16928. }
  16929. if (this.chStartsBindingIdentifier(nextCh, next) || this.isUnparsedContextual(next, "void")) {
  16930. return true;
  16931. }
  16932. return false;
  16933. }
  16934. nextTokenIsIdentifierOnSameLine() {
  16935. const next = this.nextTokenInLineStart();
  16936. const nextCh = this.codePointAtPos(next);
  16937. return this.chStartsBindingIdentifier(nextCh, next);
  16938. }
  16939. isAwaitUsing() {
  16940. if (!this.isContextual(96)) {
  16941. return false;
  16942. }
  16943. let next = this.nextTokenInLineStart();
  16944. if (this.isUnparsedContextual(next, "using")) {
  16945. next = this.nextTokenInLineStartSince(next + 5);
  16946. const nextCh = this.codePointAtPos(next);
  16947. if (this.chStartsBindingIdentifier(nextCh, next)) {
  16948. return true;
  16949. }
  16950. }
  16951. return false;
  16952. }
  16953. chStartsBindingIdentifier(ch, pos) {
  16954. if (isIdentifierStart(ch)) {
  16955. keywordRelationalOperator.lastIndex = pos;
  16956. if (keywordRelationalOperator.test(this.input)) {
  16957. const endCh = this.codePointAtPos(keywordRelationalOperator.lastIndex);
  16958. if (!isIdentifierChar(endCh) && endCh !== 92) {
  16959. return false;
  16960. }
  16961. }
  16962. return true;
  16963. } else if (ch === 92) {
  16964. return true;
  16965. } else {
  16966. return false;
  16967. }
  16968. }
  16969. chStartsBindingPattern(ch) {
  16970. return ch === 91 || ch === 123;
  16971. }
  16972. hasFollowingBindingAtom() {
  16973. const next = this.nextTokenStart();
  16974. const nextCh = this.codePointAtPos(next);
  16975. return this.chStartsBindingPattern(nextCh) || this.chStartsBindingIdentifier(nextCh, next);
  16976. }
  16977. hasInLineFollowingBindingIdentifierOrBrace() {
  16978. const next = this.nextTokenInLineStart();
  16979. const nextCh = this.codePointAtPos(next);
  16980. return nextCh === 123 || this.chStartsBindingIdentifier(nextCh, next);
  16981. }
  16982. allowsUsing() {
  16983. return (this.scope.inModule || !this.scope.inTopLevel) && !this.scope.inBareCaseStatement;
  16984. }
  16985. parseModuleItem() {
  16986. return this.parseStatementLike(1 | 2 | 4 | 8);
  16987. }
  16988. parseStatementListItem() {
  16989. return this.parseStatementLike(2 | 4 | (!this.options.annexB || this.state.strict ? 0 : 8));
  16990. }
  16991. parseStatementOrSloppyAnnexBFunctionDeclaration(allowLabeledFunction = false) {
  16992. let flags = 0;
  16993. if (this.options.annexB && !this.state.strict) {
  16994. flags |= 4;
  16995. if (allowLabeledFunction) {
  16996. flags |= 8;
  16997. }
  16998. }
  16999. return this.parseStatementLike(flags);
  17000. }
  17001. parseStatement() {
  17002. return this.parseStatementLike(0);
  17003. }
  17004. parseStatementLike(flags) {
  17005. let decorators = null;
  17006. if (this.match(26)) {
  17007. decorators = this.parseDecorators(true);
  17008. }
  17009. return this.parseStatementContent(flags, decorators);
  17010. }
  17011. parseStatementContent(flags, decorators) {
  17012. const startType = this.state.type;
  17013. const node = this.startNode();
  17014. const allowDeclaration = !!(flags & 2);
  17015. const allowFunctionDeclaration = !!(flags & 4);
  17016. const topLevel = flags & 1;
  17017. switch (startType) {
  17018. case 60:
  17019. return this.parseBreakContinueStatement(node, true);
  17020. case 63:
  17021. return this.parseBreakContinueStatement(node, false);
  17022. case 64:
  17023. return this.parseDebuggerStatement(node);
  17024. case 90:
  17025. return this.parseDoWhileStatement(node);
  17026. case 91:
  17027. return this.parseForStatement(node);
  17028. case 68:
  17029. if (this.lookaheadCharCode() === 46) break;
  17030. if (!allowFunctionDeclaration) {
  17031. this.raise(this.state.strict ? Errors.StrictFunction : this.options.annexB ? Errors.SloppyFunctionAnnexB : Errors.SloppyFunction, this.state.startLoc);
  17032. }
  17033. return this.parseFunctionStatement(node, false, !allowDeclaration && allowFunctionDeclaration);
  17034. case 80:
  17035. if (!allowDeclaration) this.unexpected();
  17036. return this.parseClass(this.maybeTakeDecorators(decorators, node), true);
  17037. case 69:
  17038. return this.parseIfStatement(node);
  17039. case 70:
  17040. return this.parseReturnStatement(node);
  17041. case 71:
  17042. return this.parseSwitchStatement(node);
  17043. case 72:
  17044. return this.parseThrowStatement(node);
  17045. case 73:
  17046. return this.parseTryStatement(node);
  17047. case 96:
  17048. if (this.isAwaitUsing()) {
  17049. if (!this.allowsUsing()) {
  17050. this.raise(Errors.UnexpectedUsingDeclaration, node);
  17051. } else if (!allowDeclaration) {
  17052. this.raise(Errors.UnexpectedLexicalDeclaration, node);
  17053. } else if (!this.recordAwaitIfAllowed()) {
  17054. this.raise(Errors.AwaitUsingNotInAsyncContext, node);
  17055. }
  17056. this.next();
  17057. return this.parseVarStatement(node, "await using");
  17058. }
  17059. break;
  17060. case 107:
  17061. if (this.state.containsEsc || !this.hasInLineFollowingBindingIdentifierOrBrace()) {
  17062. break;
  17063. }
  17064. if (!this.allowsUsing()) {
  17065. this.raise(Errors.UnexpectedUsingDeclaration, this.state.startLoc);
  17066. } else if (!allowDeclaration) {
  17067. this.raise(Errors.UnexpectedLexicalDeclaration, this.state.startLoc);
  17068. }
  17069. return this.parseVarStatement(node, "using");
  17070. case 100:
  17071. {
  17072. if (this.state.containsEsc) {
  17073. break;
  17074. }
  17075. const next = this.nextTokenStart();
  17076. const nextCh = this.codePointAtPos(next);
  17077. if (nextCh !== 91) {
  17078. if (!allowDeclaration && this.hasFollowingLineBreak()) break;
  17079. if (!this.chStartsBindingIdentifier(nextCh, next) && nextCh !== 123) {
  17080. break;
  17081. }
  17082. }
  17083. }
  17084. case 75:
  17085. {
  17086. if (!allowDeclaration) {
  17087. this.raise(Errors.UnexpectedLexicalDeclaration, this.state.startLoc);
  17088. }
  17089. }
  17090. case 74:
  17091. {
  17092. const kind = this.state.value;
  17093. return this.parseVarStatement(node, kind);
  17094. }
  17095. case 92:
  17096. return this.parseWhileStatement(node);
  17097. case 76:
  17098. return this.parseWithStatement(node);
  17099. case 5:
  17100. return this.parseBlock();
  17101. case 13:
  17102. return this.parseEmptyStatement(node);
  17103. case 83:
  17104. {
  17105. const nextTokenCharCode = this.lookaheadCharCode();
  17106. if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
  17107. break;
  17108. }
  17109. }
  17110. case 82:
  17111. {
  17112. if (!(this.optionFlags & 8) && !topLevel) {
  17113. this.raise(Errors.UnexpectedImportExport, this.state.startLoc);
  17114. }
  17115. this.next();
  17116. let result;
  17117. if (startType === 83) {
  17118. result = this.parseImport(node);
  17119. } else {
  17120. result = this.parseExport(node, decorators);
  17121. }
  17122. this.assertModuleNodeAllowed(result);
  17123. return result;
  17124. }
  17125. default:
  17126. {
  17127. if (this.isAsyncFunction()) {
  17128. if (!allowDeclaration) {
  17129. this.raise(Errors.AsyncFunctionInSingleStatementContext, this.state.startLoc);
  17130. }
  17131. this.next();
  17132. return this.parseFunctionStatement(node, true, !allowDeclaration && allowFunctionDeclaration);
  17133. }
  17134. }
  17135. }
  17136. const maybeName = this.state.value;
  17137. const expr = this.parseExpression();
  17138. if (tokenIsIdentifier(startType) && expr.type === "Identifier" && this.eat(14)) {
  17139. return this.parseLabeledStatement(node, maybeName, expr, flags);
  17140. } else {
  17141. return this.parseExpressionStatement(node, expr, decorators);
  17142. }
  17143. }
  17144. assertModuleNodeAllowed(node) {
  17145. if (!(this.optionFlags & 8) && !this.inModule) {
  17146. this.raise(Errors.ImportOutsideModule, node);
  17147. }
  17148. }
  17149. decoratorsEnabledBeforeExport() {
  17150. if (this.hasPlugin("decorators-legacy")) return true;
  17151. return this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") !== false;
  17152. }
  17153. maybeTakeDecorators(maybeDecorators, classNode, exportNode) {
  17154. if (maybeDecorators) {
  17155. var _classNode$decorators;
  17156. if ((_classNode$decorators = classNode.decorators) != null && _classNode$decorators.length) {
  17157. if (typeof this.getPluginOption("decorators", "decoratorsBeforeExport") !== "boolean") {
  17158. this.raise(Errors.DecoratorsBeforeAfterExport, classNode.decorators[0]);
  17159. }
  17160. classNode.decorators.unshift(...maybeDecorators);
  17161. } else {
  17162. classNode.decorators = maybeDecorators;
  17163. }
  17164. this.resetStartLocationFromNode(classNode, maybeDecorators[0]);
  17165. if (exportNode) this.resetStartLocationFromNode(exportNode, classNode);
  17166. }
  17167. return classNode;
  17168. }
  17169. canHaveLeadingDecorator() {
  17170. return this.match(80);
  17171. }
  17172. parseDecorators(allowExport) {
  17173. const decorators = [];
  17174. do {
  17175. decorators.push(this.parseDecorator());
  17176. } while (this.match(26));
  17177. if (this.match(82)) {
  17178. if (!allowExport) {
  17179. this.unexpected();
  17180. }
  17181. if (!this.decoratorsEnabledBeforeExport()) {
  17182. this.raise(Errors.DecoratorExportClass, this.state.startLoc);
  17183. }
  17184. } else if (!this.canHaveLeadingDecorator()) {
  17185. throw this.raise(Errors.UnexpectedLeadingDecorator, this.state.startLoc);
  17186. }
  17187. return decorators;
  17188. }
  17189. parseDecorator() {
  17190. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  17191. const node = this.startNode();
  17192. this.next();
  17193. if (this.hasPlugin("decorators")) {
  17194. const startLoc = this.state.startLoc;
  17195. let expr;
  17196. if (this.match(10)) {
  17197. const startLoc = this.state.startLoc;
  17198. this.next();
  17199. expr = this.parseExpression();
  17200. this.expect(11);
  17201. expr = this.wrapParenthesis(startLoc, expr);
  17202. const paramsStartLoc = this.state.startLoc;
  17203. node.expression = this.parseMaybeDecoratorArguments(expr, startLoc);
  17204. if (this.getPluginOption("decorators", "allowCallParenthesized") === false && node.expression !== expr) {
  17205. this.raise(Errors.DecoratorArgumentsOutsideParentheses, paramsStartLoc);
  17206. }
  17207. } else {
  17208. expr = this.parseIdentifier(false);
  17209. while (this.eat(16)) {
  17210. const node = this.startNodeAt(startLoc);
  17211. node.object = expr;
  17212. if (this.match(139)) {
  17213. this.classScope.usePrivateName(this.state.value, this.state.startLoc);
  17214. node.property = this.parsePrivateName();
  17215. } else {
  17216. node.property = this.parseIdentifier(true);
  17217. }
  17218. node.computed = false;
  17219. expr = this.finishNode(node, "MemberExpression");
  17220. }
  17221. node.expression = this.parseMaybeDecoratorArguments(expr, startLoc);
  17222. }
  17223. } else {
  17224. node.expression = this.parseExprSubscripts();
  17225. }
  17226. return this.finishNode(node, "Decorator");
  17227. }
  17228. parseMaybeDecoratorArguments(expr, startLoc) {
  17229. if (this.eat(10)) {
  17230. const node = this.startNodeAt(startLoc);
  17231. node.callee = expr;
  17232. node.arguments = this.parseCallExpressionArguments();
  17233. this.toReferencedList(node.arguments);
  17234. return this.finishNode(node, "CallExpression");
  17235. }
  17236. return expr;
  17237. }
  17238. parseBreakContinueStatement(node, isBreak) {
  17239. this.next();
  17240. if (this.isLineTerminator()) {
  17241. node.label = null;
  17242. } else {
  17243. node.label = this.parseIdentifier();
  17244. this.semicolon();
  17245. }
  17246. this.verifyBreakContinue(node, isBreak);
  17247. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  17248. }
  17249. verifyBreakContinue(node, isBreak) {
  17250. let i;
  17251. for (i = 0; i < this.state.labels.length; ++i) {
  17252. const lab = this.state.labels[i];
  17253. if (node.label == null || lab.name === node.label.name) {
  17254. if (lab.kind != null && (isBreak || lab.kind === 1)) {
  17255. break;
  17256. }
  17257. if (node.label && isBreak) break;
  17258. }
  17259. }
  17260. if (i === this.state.labels.length) {
  17261. const type = isBreak ? "BreakStatement" : "ContinueStatement";
  17262. this.raise(Errors.IllegalBreakContinue, node, {
  17263. type
  17264. });
  17265. }
  17266. }
  17267. parseDebuggerStatement(node) {
  17268. this.next();
  17269. this.semicolon();
  17270. return this.finishNode(node, "DebuggerStatement");
  17271. }
  17272. parseHeaderExpression() {
  17273. this.expect(10);
  17274. const val = this.parseExpression();
  17275. this.expect(11);
  17276. return val;
  17277. }
  17278. parseDoWhileStatement(node) {
  17279. this.next();
  17280. this.state.labels.push(loopLabel);
  17281. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  17282. this.state.labels.pop();
  17283. this.expect(92);
  17284. node.test = this.parseHeaderExpression();
  17285. this.eat(13);
  17286. return this.finishNode(node, "DoWhileStatement");
  17287. }
  17288. parseForStatement(node) {
  17289. this.next();
  17290. this.state.labels.push(loopLabel);
  17291. let awaitAt = null;
  17292. if (this.isContextual(96) && this.recordAwaitIfAllowed()) {
  17293. awaitAt = this.state.startLoc;
  17294. this.next();
  17295. }
  17296. this.scope.enter(0);
  17297. this.expect(10);
  17298. if (this.match(13)) {
  17299. if (awaitAt !== null) {
  17300. this.unexpected(awaitAt);
  17301. }
  17302. return this.parseFor(node, null);
  17303. }
  17304. const startsWithLet = this.isContextual(100);
  17305. {
  17306. const startsWithAwaitUsing = this.isAwaitUsing();
  17307. const starsWithUsingDeclaration = startsWithAwaitUsing || this.isForUsing();
  17308. const isLetOrUsing = startsWithLet && this.hasFollowingBindingAtom() || starsWithUsingDeclaration;
  17309. if (this.match(74) || this.match(75) || isLetOrUsing) {
  17310. const initNode = this.startNode();
  17311. let kind;
  17312. if (startsWithAwaitUsing) {
  17313. kind = "await using";
  17314. if (!this.recordAwaitIfAllowed()) {
  17315. this.raise(Errors.AwaitUsingNotInAsyncContext, this.state.startLoc);
  17316. }
  17317. this.next();
  17318. } else {
  17319. kind = this.state.value;
  17320. }
  17321. this.next();
  17322. this.parseVar(initNode, true, kind);
  17323. const init = this.finishNode(initNode, "VariableDeclaration");
  17324. const isForIn = this.match(58);
  17325. if (isForIn && starsWithUsingDeclaration) {
  17326. this.raise(Errors.ForInUsing, init);
  17327. }
  17328. if ((isForIn || this.isContextual(102)) && init.declarations.length === 1) {
  17329. return this.parseForIn(node, init, awaitAt);
  17330. }
  17331. if (awaitAt !== null) {
  17332. this.unexpected(awaitAt);
  17333. }
  17334. return this.parseFor(node, init);
  17335. }
  17336. }
  17337. const startsWithAsync = this.isContextual(95);
  17338. const refExpressionErrors = new ExpressionErrors();
  17339. const init = this.parseExpression(true, refExpressionErrors);
  17340. const isForOf = this.isContextual(102);
  17341. if (isForOf) {
  17342. if (startsWithLet) {
  17343. this.raise(Errors.ForOfLet, init);
  17344. }
  17345. if (awaitAt === null && startsWithAsync && init.type === "Identifier") {
  17346. this.raise(Errors.ForOfAsync, init);
  17347. }
  17348. }
  17349. if (isForOf || this.match(58)) {
  17350. this.checkDestructuringPrivate(refExpressionErrors);
  17351. this.toAssignable(init, true);
  17352. const type = isForOf ? "ForOfStatement" : "ForInStatement";
  17353. this.checkLVal(init, {
  17354. type
  17355. });
  17356. return this.parseForIn(node, init, awaitAt);
  17357. } else {
  17358. this.checkExpressionErrors(refExpressionErrors, true);
  17359. }
  17360. if (awaitAt !== null) {
  17361. this.unexpected(awaitAt);
  17362. }
  17363. return this.parseFor(node, init);
  17364. }
  17365. parseFunctionStatement(node, isAsync, isHangingDeclaration) {
  17366. this.next();
  17367. return this.parseFunction(node, 1 | (isHangingDeclaration ? 2 : 0) | (isAsync ? 8 : 0));
  17368. }
  17369. parseIfStatement(node) {
  17370. this.next();
  17371. node.test = this.parseHeaderExpression();
  17372. node.consequent = this.parseStatementOrSloppyAnnexBFunctionDeclaration();
  17373. node.alternate = this.eat(66) ? this.parseStatementOrSloppyAnnexBFunctionDeclaration() : null;
  17374. return this.finishNode(node, "IfStatement");
  17375. }
  17376. parseReturnStatement(node) {
  17377. if (!this.prodParam.hasReturn) {
  17378. this.raise(Errors.IllegalReturn, this.state.startLoc);
  17379. }
  17380. this.next();
  17381. if (this.isLineTerminator()) {
  17382. node.argument = null;
  17383. } else {
  17384. node.argument = this.parseExpression();
  17385. this.semicolon();
  17386. }
  17387. return this.finishNode(node, "ReturnStatement");
  17388. }
  17389. parseSwitchStatement(node) {
  17390. this.next();
  17391. node.discriminant = this.parseHeaderExpression();
  17392. const cases = node.cases = [];
  17393. this.expect(5);
  17394. this.state.labels.push(switchLabel);
  17395. this.scope.enter(256);
  17396. let cur;
  17397. for (let sawDefault; !this.match(8);) {
  17398. if (this.match(61) || this.match(65)) {
  17399. const isCase = this.match(61);
  17400. if (cur) this.finishNode(cur, "SwitchCase");
  17401. cases.push(cur = this.startNode());
  17402. cur.consequent = [];
  17403. this.next();
  17404. if (isCase) {
  17405. cur.test = this.parseExpression();
  17406. } else {
  17407. if (sawDefault) {
  17408. this.raise(Errors.MultipleDefaultsInSwitch, this.state.lastTokStartLoc);
  17409. }
  17410. sawDefault = true;
  17411. cur.test = null;
  17412. }
  17413. this.expect(14);
  17414. } else {
  17415. if (cur) {
  17416. cur.consequent.push(this.parseStatementListItem());
  17417. } else {
  17418. this.unexpected();
  17419. }
  17420. }
  17421. }
  17422. this.scope.exit();
  17423. if (cur) this.finishNode(cur, "SwitchCase");
  17424. this.next();
  17425. this.state.labels.pop();
  17426. return this.finishNode(node, "SwitchStatement");
  17427. }
  17428. parseThrowStatement(node) {
  17429. this.next();
  17430. if (this.hasPrecedingLineBreak()) {
  17431. this.raise(Errors.NewlineAfterThrow, this.state.lastTokEndLoc);
  17432. }
  17433. node.argument = this.parseExpression();
  17434. this.semicolon();
  17435. return this.finishNode(node, "ThrowStatement");
  17436. }
  17437. parseCatchClauseParam() {
  17438. const param = this.parseBindingAtom();
  17439. this.scope.enter(this.options.annexB && param.type === "Identifier" ? 8 : 0);
  17440. this.checkLVal(param, {
  17441. type: "CatchClause"
  17442. }, 9);
  17443. return param;
  17444. }
  17445. parseTryStatement(node) {
  17446. this.next();
  17447. node.block = this.parseBlock();
  17448. node.handler = null;
  17449. if (this.match(62)) {
  17450. const clause = this.startNode();
  17451. this.next();
  17452. if (this.match(10)) {
  17453. this.expect(10);
  17454. clause.param = this.parseCatchClauseParam();
  17455. this.expect(11);
  17456. } else {
  17457. clause.param = null;
  17458. this.scope.enter(0);
  17459. }
  17460. clause.body = this.withSmartMixTopicForbiddingContext(() => this.parseBlock(false, false));
  17461. this.scope.exit();
  17462. node.handler = this.finishNode(clause, "CatchClause");
  17463. }
  17464. node.finalizer = this.eat(67) ? this.parseBlock() : null;
  17465. if (!node.handler && !node.finalizer) {
  17466. this.raise(Errors.NoCatchOrFinally, node);
  17467. }
  17468. return this.finishNode(node, "TryStatement");
  17469. }
  17470. parseVarStatement(node, kind, allowMissingInitializer = false) {
  17471. this.next();
  17472. this.parseVar(node, false, kind, allowMissingInitializer);
  17473. this.semicolon();
  17474. return this.finishNode(node, "VariableDeclaration");
  17475. }
  17476. parseWhileStatement(node) {
  17477. this.next();
  17478. node.test = this.parseHeaderExpression();
  17479. this.state.labels.push(loopLabel);
  17480. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  17481. this.state.labels.pop();
  17482. return this.finishNode(node, "WhileStatement");
  17483. }
  17484. parseWithStatement(node) {
  17485. if (this.state.strict) {
  17486. this.raise(Errors.StrictWith, this.state.startLoc);
  17487. }
  17488. this.next();
  17489. node.object = this.parseHeaderExpression();
  17490. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  17491. return this.finishNode(node, "WithStatement");
  17492. }
  17493. parseEmptyStatement(node) {
  17494. this.next();
  17495. return this.finishNode(node, "EmptyStatement");
  17496. }
  17497. parseLabeledStatement(node, maybeName, expr, flags) {
  17498. for (const label of this.state.labels) {
  17499. if (label.name === maybeName) {
  17500. this.raise(Errors.LabelRedeclaration, expr, {
  17501. labelName: maybeName
  17502. });
  17503. }
  17504. }
  17505. const kind = tokenIsLoop(this.state.type) ? 1 : this.match(71) ? 2 : null;
  17506. for (let i = this.state.labels.length - 1; i >= 0; i--) {
  17507. const label = this.state.labels[i];
  17508. if (label.statementStart === node.start) {
  17509. label.statementStart = this.sourceToOffsetPos(this.state.start);
  17510. label.kind = kind;
  17511. } else {
  17512. break;
  17513. }
  17514. }
  17515. this.state.labels.push({
  17516. name: maybeName,
  17517. kind: kind,
  17518. statementStart: this.sourceToOffsetPos(this.state.start)
  17519. });
  17520. node.body = flags & 8 ? this.parseStatementOrSloppyAnnexBFunctionDeclaration(true) : this.parseStatement();
  17521. this.state.labels.pop();
  17522. node.label = expr;
  17523. return this.finishNode(node, "LabeledStatement");
  17524. }
  17525. parseExpressionStatement(node, expr, decorators) {
  17526. node.expression = expr;
  17527. this.semicolon();
  17528. return this.finishNode(node, "ExpressionStatement");
  17529. }
  17530. parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) {
  17531. const node = this.startNode();
  17532. if (allowDirectives) {
  17533. this.state.strictErrors.clear();
  17534. }
  17535. this.expect(5);
  17536. if (createNewLexicalScope) {
  17537. this.scope.enter(0);
  17538. }
  17539. this.parseBlockBody(node, allowDirectives, false, 8, afterBlockParse);
  17540. if (createNewLexicalScope) {
  17541. this.scope.exit();
  17542. }
  17543. return this.finishNode(node, "BlockStatement");
  17544. }
  17545. isValidDirective(stmt) {
  17546. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  17547. }
  17548. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  17549. const body = node.body = [];
  17550. const directives = node.directives = [];
  17551. this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse);
  17552. }
  17553. parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) {
  17554. const oldStrict = this.state.strict;
  17555. let hasStrictModeDirective = false;
  17556. let parsedNonDirective = false;
  17557. while (!this.match(end)) {
  17558. const stmt = topLevel ? this.parseModuleItem() : this.parseStatementListItem();
  17559. if (directives && !parsedNonDirective) {
  17560. if (this.isValidDirective(stmt)) {
  17561. const directive = this.stmtToDirective(stmt);
  17562. directives.push(directive);
  17563. if (!hasStrictModeDirective && directive.value.value === "use strict") {
  17564. hasStrictModeDirective = true;
  17565. this.setStrict(true);
  17566. }
  17567. continue;
  17568. }
  17569. parsedNonDirective = true;
  17570. this.state.strictErrors.clear();
  17571. }
  17572. body.push(stmt);
  17573. }
  17574. afterBlockParse == null || afterBlockParse.call(this, hasStrictModeDirective);
  17575. if (!oldStrict) {
  17576. this.setStrict(false);
  17577. }
  17578. this.next();
  17579. }
  17580. parseFor(node, init) {
  17581. node.init = init;
  17582. this.semicolon(false);
  17583. node.test = this.match(13) ? null : this.parseExpression();
  17584. this.semicolon(false);
  17585. node.update = this.match(11) ? null : this.parseExpression();
  17586. this.expect(11);
  17587. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  17588. this.scope.exit();
  17589. this.state.labels.pop();
  17590. return this.finishNode(node, "ForStatement");
  17591. }
  17592. parseForIn(node, init, awaitAt) {
  17593. const isForIn = this.match(58);
  17594. this.next();
  17595. if (isForIn) {
  17596. if (awaitAt !== null) this.unexpected(awaitAt);
  17597. } else {
  17598. node.await = awaitAt !== null;
  17599. }
  17600. 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")) {
  17601. this.raise(Errors.ForInOfLoopInitializer, init, {
  17602. type: isForIn ? "ForInStatement" : "ForOfStatement"
  17603. });
  17604. }
  17605. if (init.type === "AssignmentPattern") {
  17606. this.raise(Errors.InvalidLhs, init, {
  17607. ancestor: {
  17608. type: "ForStatement"
  17609. }
  17610. });
  17611. }
  17612. node.left = init;
  17613. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn();
  17614. this.expect(11);
  17615. node.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
  17616. this.scope.exit();
  17617. this.state.labels.pop();
  17618. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
  17619. }
  17620. parseVar(node, isFor, kind, allowMissingInitializer = false) {
  17621. const declarations = node.declarations = [];
  17622. node.kind = kind;
  17623. for (;;) {
  17624. const decl = this.startNode();
  17625. this.parseVarId(decl, kind);
  17626. decl.init = !this.eat(29) ? null : isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn();
  17627. if (decl.init === null && !allowMissingInitializer) {
  17628. if (decl.id.type !== "Identifier" && !(isFor && (this.match(58) || this.isContextual(102)))) {
  17629. this.raise(Errors.DeclarationMissingInitializer, this.state.lastTokEndLoc, {
  17630. kind: "destructuring"
  17631. });
  17632. } else if ((kind === "const" || kind === "using" || kind === "await using") && !(this.match(58) || this.isContextual(102))) {
  17633. this.raise(Errors.DeclarationMissingInitializer, this.state.lastTokEndLoc, {
  17634. kind
  17635. });
  17636. }
  17637. }
  17638. declarations.push(this.finishNode(decl, "VariableDeclarator"));
  17639. if (!this.eat(12)) break;
  17640. }
  17641. return node;
  17642. }
  17643. parseVarId(decl, kind) {
  17644. const id = this.parseBindingAtom();
  17645. if (kind === "using" || kind === "await using") {
  17646. if (id.type === "ArrayPattern" || id.type === "ObjectPattern") {
  17647. this.raise(Errors.UsingDeclarationHasBindingPattern, id.loc.start);
  17648. }
  17649. } else {
  17650. if (id.type === "VoidPattern") {
  17651. this.raise(Errors.UnexpectedVoidPattern, id.loc.start);
  17652. }
  17653. }
  17654. this.checkLVal(id, {
  17655. type: "VariableDeclarator"
  17656. }, kind === "var" ? 5 : 8201);
  17657. decl.id = id;
  17658. }
  17659. parseAsyncFunctionExpression(node) {
  17660. return this.parseFunction(node, 8);
  17661. }
  17662. parseFunction(node, flags = 0) {
  17663. const hangingDeclaration = flags & 2;
  17664. const isDeclaration = !!(flags & 1);
  17665. const requireId = isDeclaration && !(flags & 4);
  17666. const isAsync = !!(flags & 8);
  17667. this.initFunction(node, isAsync);
  17668. if (this.match(55)) {
  17669. if (hangingDeclaration) {
  17670. this.raise(Errors.GeneratorInSingleStatementContext, this.state.startLoc);
  17671. }
  17672. this.next();
  17673. node.generator = true;
  17674. }
  17675. if (isDeclaration) {
  17676. node.id = this.parseFunctionId(requireId);
  17677. }
  17678. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  17679. this.state.maybeInArrowParameters = false;
  17680. this.scope.enter(514);
  17681. this.prodParam.enter(functionFlags(isAsync, node.generator));
  17682. if (!isDeclaration) {
  17683. node.id = this.parseFunctionId();
  17684. }
  17685. this.parseFunctionParams(node, false);
  17686. this.withSmartMixTopicForbiddingContext(() => {
  17687. this.parseFunctionBodyAndFinish(node, isDeclaration ? "FunctionDeclaration" : "FunctionExpression");
  17688. });
  17689. this.prodParam.exit();
  17690. this.scope.exit();
  17691. if (isDeclaration && !hangingDeclaration) {
  17692. this.registerFunctionStatementId(node);
  17693. }
  17694. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  17695. return node;
  17696. }
  17697. parseFunctionId(requireId) {
  17698. return requireId || tokenIsIdentifier(this.state.type) ? this.parseIdentifier() : null;
  17699. }
  17700. parseFunctionParams(node, isConstructor) {
  17701. this.expect(10);
  17702. this.expressionScope.enter(newParameterDeclarationScope());
  17703. node.params = this.parseBindingList(11, 41, 2 | (isConstructor ? 4 : 0));
  17704. this.expressionScope.exit();
  17705. }
  17706. registerFunctionStatementId(node) {
  17707. if (!node.id) return;
  17708. 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);
  17709. }
  17710. parseClass(node, isStatement, optionalId) {
  17711. this.next();
  17712. const oldStrict = this.state.strict;
  17713. this.state.strict = true;
  17714. this.parseClassId(node, isStatement, optionalId);
  17715. this.parseClassSuper(node);
  17716. node.body = this.parseClassBody(!!node.superClass, oldStrict);
  17717. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  17718. }
  17719. isClassProperty() {
  17720. return this.match(29) || this.match(13) || this.match(8);
  17721. }
  17722. isClassMethod() {
  17723. return this.match(10);
  17724. }
  17725. nameIsConstructor(key) {
  17726. return key.type === "Identifier" && key.name === "constructor" || key.type === "StringLiteral" && key.value === "constructor";
  17727. }
  17728. isNonstaticConstructor(method) {
  17729. return !method.computed && !method.static && this.nameIsConstructor(method.key);
  17730. }
  17731. parseClassBody(hadSuperClass, oldStrict) {
  17732. this.classScope.enter();
  17733. const state = {
  17734. hadConstructor: false,
  17735. hadSuperClass
  17736. };
  17737. let decorators = [];
  17738. const classBody = this.startNode();
  17739. classBody.body = [];
  17740. this.expect(5);
  17741. this.withSmartMixTopicForbiddingContext(() => {
  17742. while (!this.match(8)) {
  17743. if (this.eat(13)) {
  17744. if (decorators.length > 0) {
  17745. throw this.raise(Errors.DecoratorSemicolon, this.state.lastTokEndLoc);
  17746. }
  17747. continue;
  17748. }
  17749. if (this.match(26)) {
  17750. decorators.push(this.parseDecorator());
  17751. continue;
  17752. }
  17753. const member = this.startNode();
  17754. if (decorators.length) {
  17755. member.decorators = decorators;
  17756. this.resetStartLocationFromNode(member, decorators[0]);
  17757. decorators = [];
  17758. }
  17759. this.parseClassMember(classBody, member, state);
  17760. if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
  17761. this.raise(Errors.DecoratorConstructor, member);
  17762. }
  17763. }
  17764. });
  17765. this.state.strict = oldStrict;
  17766. this.next();
  17767. if (decorators.length) {
  17768. throw this.raise(Errors.TrailingDecorator, this.state.startLoc);
  17769. }
  17770. this.classScope.exit();
  17771. return this.finishNode(classBody, "ClassBody");
  17772. }
  17773. parseClassMemberFromModifier(classBody, member) {
  17774. const key = this.parseIdentifier(true);
  17775. if (this.isClassMethod()) {
  17776. const method = member;
  17777. method.kind = "method";
  17778. method.computed = false;
  17779. method.key = key;
  17780. method.static = false;
  17781. this.pushClassMethod(classBody, method, false, false, false, false);
  17782. return true;
  17783. } else if (this.isClassProperty()) {
  17784. const prop = member;
  17785. prop.computed = false;
  17786. prop.key = key;
  17787. prop.static = false;
  17788. classBody.body.push(this.parseClassProperty(prop));
  17789. return true;
  17790. }
  17791. this.resetPreviousNodeTrailingComments(key);
  17792. return false;
  17793. }
  17794. parseClassMember(classBody, member, state) {
  17795. const isStatic = this.isContextual(106);
  17796. if (isStatic) {
  17797. if (this.parseClassMemberFromModifier(classBody, member)) {
  17798. return;
  17799. }
  17800. if (this.eat(5)) {
  17801. this.parseClassStaticBlock(classBody, member);
  17802. return;
  17803. }
  17804. }
  17805. this.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  17806. }
  17807. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  17808. const publicMethod = member;
  17809. const privateMethod = member;
  17810. const publicProp = member;
  17811. const privateProp = member;
  17812. const accessorProp = member;
  17813. const method = publicMethod;
  17814. const publicMember = publicMethod;
  17815. member.static = isStatic;
  17816. this.parsePropertyNamePrefixOperator(member);
  17817. if (this.eat(55)) {
  17818. method.kind = "method";
  17819. const isPrivateName = this.match(139);
  17820. this.parseClassElementName(method);
  17821. this.parsePostMemberNameModifiers(method);
  17822. if (isPrivateName) {
  17823. this.pushClassPrivateMethod(classBody, privateMethod, true, false);
  17824. return;
  17825. }
  17826. if (this.isNonstaticConstructor(publicMethod)) {
  17827. this.raise(Errors.ConstructorIsGenerator, publicMethod.key);
  17828. }
  17829. this.pushClassMethod(classBody, publicMethod, true, false, false, false);
  17830. return;
  17831. }
  17832. const isContextual = !this.state.containsEsc && tokenIsIdentifier(this.state.type);
  17833. const key = this.parseClassElementName(member);
  17834. const maybeContextualKw = isContextual ? key.name : null;
  17835. const isPrivate = this.isPrivateName(key);
  17836. const maybeQuestionTokenStartLoc = this.state.startLoc;
  17837. this.parsePostMemberNameModifiers(publicMember);
  17838. if (this.isClassMethod()) {
  17839. method.kind = "method";
  17840. if (isPrivate) {
  17841. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  17842. return;
  17843. }
  17844. const isConstructor = this.isNonstaticConstructor(publicMethod);
  17845. let allowsDirectSuper = false;
  17846. if (isConstructor) {
  17847. publicMethod.kind = "constructor";
  17848. if (state.hadConstructor && !this.hasPlugin("typescript")) {
  17849. this.raise(Errors.DuplicateConstructor, key);
  17850. }
  17851. if (isConstructor && this.hasPlugin("typescript") && member.override) {
  17852. this.raise(Errors.OverrideOnConstructor, key);
  17853. }
  17854. state.hadConstructor = true;
  17855. allowsDirectSuper = state.hadSuperClass;
  17856. }
  17857. this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
  17858. } else if (this.isClassProperty()) {
  17859. if (isPrivate) {
  17860. this.pushClassPrivateProperty(classBody, privateProp);
  17861. } else {
  17862. this.pushClassProperty(classBody, publicProp);
  17863. }
  17864. } else if (maybeContextualKw === "async" && !this.isLineTerminator()) {
  17865. this.resetPreviousNodeTrailingComments(key);
  17866. const isGenerator = this.eat(55);
  17867. if (publicMember.optional) {
  17868. this.unexpected(maybeQuestionTokenStartLoc);
  17869. }
  17870. method.kind = "method";
  17871. const isPrivate = this.match(139);
  17872. this.parseClassElementName(method);
  17873. this.parsePostMemberNameModifiers(publicMember);
  17874. if (isPrivate) {
  17875. this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
  17876. } else {
  17877. if (this.isNonstaticConstructor(publicMethod)) {
  17878. this.raise(Errors.ConstructorIsAsync, publicMethod.key);
  17879. }
  17880. this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
  17881. }
  17882. } else if ((maybeContextualKw === "get" || maybeContextualKw === "set") && !(this.match(55) && this.isLineTerminator())) {
  17883. this.resetPreviousNodeTrailingComments(key);
  17884. method.kind = maybeContextualKw;
  17885. const isPrivate = this.match(139);
  17886. this.parseClassElementName(publicMethod);
  17887. if (isPrivate) {
  17888. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  17889. } else {
  17890. if (this.isNonstaticConstructor(publicMethod)) {
  17891. this.raise(Errors.ConstructorIsAccessor, publicMethod.key);
  17892. }
  17893. this.pushClassMethod(classBody, publicMethod, false, false, false, false);
  17894. }
  17895. this.checkGetterSetterParams(publicMethod);
  17896. } else if (maybeContextualKw === "accessor" && !this.isLineTerminator()) {
  17897. this.expectPlugin("decoratorAutoAccessors");
  17898. this.resetPreviousNodeTrailingComments(key);
  17899. const isPrivate = this.match(139);
  17900. this.parseClassElementName(publicProp);
  17901. this.pushClassAccessorProperty(classBody, accessorProp, isPrivate);
  17902. } else if (this.isLineTerminator()) {
  17903. if (isPrivate) {
  17904. this.pushClassPrivateProperty(classBody, privateProp);
  17905. } else {
  17906. this.pushClassProperty(classBody, publicProp);
  17907. }
  17908. } else {
  17909. this.unexpected();
  17910. }
  17911. }
  17912. parseClassElementName(member) {
  17913. const {
  17914. type,
  17915. value
  17916. } = this.state;
  17917. if ((type === 132 || type === 134) && member.static && value === "prototype") {
  17918. this.raise(Errors.StaticPrototype, this.state.startLoc);
  17919. }
  17920. if (type === 139) {
  17921. if (value === "constructor") {
  17922. this.raise(Errors.ConstructorClassPrivateField, this.state.startLoc);
  17923. }
  17924. const key = this.parsePrivateName();
  17925. member.key = key;
  17926. return key;
  17927. }
  17928. this.parsePropertyName(member);
  17929. return member.key;
  17930. }
  17931. parseClassStaticBlock(classBody, member) {
  17932. var _member$decorators;
  17933. this.scope.enter(576 | 128 | 16);
  17934. const oldLabels = this.state.labels;
  17935. this.state.labels = [];
  17936. this.prodParam.enter(0);
  17937. const body = member.body = [];
  17938. this.parseBlockOrModuleBlockBody(body, undefined, false, 8);
  17939. this.prodParam.exit();
  17940. this.scope.exit();
  17941. this.state.labels = oldLabels;
  17942. classBody.body.push(this.finishNode(member, "StaticBlock"));
  17943. if ((_member$decorators = member.decorators) != null && _member$decorators.length) {
  17944. this.raise(Errors.DecoratorStaticBlock, member);
  17945. }
  17946. }
  17947. pushClassProperty(classBody, prop) {
  17948. if (!prop.computed && this.nameIsConstructor(prop.key)) {
  17949. this.raise(Errors.ConstructorClassField, prop.key);
  17950. }
  17951. classBody.body.push(this.parseClassProperty(prop));
  17952. }
  17953. pushClassPrivateProperty(classBody, prop) {
  17954. const node = this.parseClassPrivateProperty(prop);
  17955. classBody.body.push(node);
  17956. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 0, node.key.loc.start);
  17957. }
  17958. pushClassAccessorProperty(classBody, prop, isPrivate) {
  17959. if (!isPrivate && !prop.computed && this.nameIsConstructor(prop.key)) {
  17960. this.raise(Errors.ConstructorClassField, prop.key);
  17961. }
  17962. const node = this.parseClassAccessorProperty(prop);
  17963. classBody.body.push(node);
  17964. if (isPrivate) {
  17965. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), 0, node.key.loc.start);
  17966. }
  17967. }
  17968. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  17969. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  17970. }
  17971. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  17972. const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
  17973. classBody.body.push(node);
  17974. const kind = node.kind === "get" ? node.static ? 6 : 2 : node.kind === "set" ? node.static ? 5 : 1 : 0;
  17975. this.declareClassPrivateMethodInScope(node, kind);
  17976. }
  17977. declareClassPrivateMethodInScope(node, kind) {
  17978. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), kind, node.key.loc.start);
  17979. }
  17980. parsePostMemberNameModifiers(methodOrProp) {}
  17981. parseClassPrivateProperty(node) {
  17982. this.parseInitializer(node);
  17983. this.semicolon();
  17984. return this.finishNode(node, "ClassPrivateProperty");
  17985. }
  17986. parseClassProperty(node) {
  17987. this.parseInitializer(node);
  17988. this.semicolon();
  17989. return this.finishNode(node, "ClassProperty");
  17990. }
  17991. parseClassAccessorProperty(node) {
  17992. this.parseInitializer(node);
  17993. this.semicolon();
  17994. return this.finishNode(node, "ClassAccessorProperty");
  17995. }
  17996. parseInitializer(node) {
  17997. this.scope.enter(576 | 16);
  17998. this.expressionScope.enter(newExpressionScope());
  17999. this.prodParam.enter(0);
  18000. node.value = this.eat(29) ? this.parseMaybeAssignAllowIn() : null;
  18001. this.expressionScope.exit();
  18002. this.prodParam.exit();
  18003. this.scope.exit();
  18004. }
  18005. parseClassId(node, isStatement, optionalId, bindingType = 8331) {
  18006. if (tokenIsIdentifier(this.state.type)) {
  18007. node.id = this.parseIdentifier();
  18008. if (isStatement) {
  18009. this.declareNameFromIdentifier(node.id, bindingType);
  18010. }
  18011. } else {
  18012. if (optionalId || !isStatement) {
  18013. node.id = null;
  18014. } else {
  18015. throw this.raise(Errors.MissingClassName, this.state.startLoc);
  18016. }
  18017. }
  18018. }
  18019. parseClassSuper(node) {
  18020. node.superClass = this.eat(81) ? this.parseExprSubscripts() : null;
  18021. }
  18022. parseExport(node, decorators) {
  18023. const maybeDefaultIdentifier = this.parseMaybeImportPhase(node, true);
  18024. const hasDefault = this.maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier);
  18025. const parseAfterDefault = !hasDefault || this.eat(12);
  18026. const hasStar = parseAfterDefault && this.eatExportStar(node);
  18027. const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
  18028. const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(12));
  18029. const isFromRequired = hasDefault || hasStar;
  18030. if (hasStar && !hasNamespace) {
  18031. if (hasDefault) this.unexpected();
  18032. if (decorators) {
  18033. throw this.raise(Errors.UnsupportedDecoratorExport, node);
  18034. }
  18035. this.parseExportFrom(node, true);
  18036. this.sawUnambiguousESM = true;
  18037. return this.finishNode(node, "ExportAllDeclaration");
  18038. }
  18039. const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
  18040. if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers) {
  18041. this.unexpected(null, 5);
  18042. }
  18043. if (hasNamespace && parseAfterNamespace) {
  18044. this.unexpected(null, 98);
  18045. }
  18046. let hasDeclaration;
  18047. if (isFromRequired || hasSpecifiers) {
  18048. hasDeclaration = false;
  18049. if (decorators) {
  18050. throw this.raise(Errors.UnsupportedDecoratorExport, node);
  18051. }
  18052. this.parseExportFrom(node, isFromRequired);
  18053. } else {
  18054. hasDeclaration = this.maybeParseExportDeclaration(node);
  18055. }
  18056. if (isFromRequired || hasSpecifiers || hasDeclaration) {
  18057. var _node2$declaration;
  18058. const node2 = node;
  18059. this.checkExport(node2, true, false, !!node2.source);
  18060. if (((_node2$declaration = node2.declaration) == null ? void 0 : _node2$declaration.type) === "ClassDeclaration") {
  18061. this.maybeTakeDecorators(decorators, node2.declaration, node2);
  18062. } else if (decorators) {
  18063. throw this.raise(Errors.UnsupportedDecoratorExport, node);
  18064. }
  18065. this.sawUnambiguousESM = true;
  18066. return this.finishNode(node2, "ExportNamedDeclaration");
  18067. }
  18068. if (this.eat(65)) {
  18069. const node2 = node;
  18070. const decl = this.parseExportDefaultExpression();
  18071. node2.declaration = decl;
  18072. if (decl.type === "ClassDeclaration") {
  18073. this.maybeTakeDecorators(decorators, decl, node2);
  18074. } else if (decorators) {
  18075. throw this.raise(Errors.UnsupportedDecoratorExport, node);
  18076. }
  18077. this.checkExport(node2, true, true);
  18078. this.sawUnambiguousESM = true;
  18079. return this.finishNode(node2, "ExportDefaultDeclaration");
  18080. }
  18081. throw this.unexpected(null, 5);
  18082. }
  18083. eatExportStar(node) {
  18084. return this.eat(55);
  18085. }
  18086. maybeParseExportDefaultSpecifier(node, maybeDefaultIdentifier) {
  18087. if (maybeDefaultIdentifier || this.isExportDefaultSpecifier()) {
  18088. this.expectPlugin("exportDefaultFrom", maybeDefaultIdentifier == null ? void 0 : maybeDefaultIdentifier.loc.start);
  18089. const id = maybeDefaultIdentifier || this.parseIdentifier(true);
  18090. const specifier = this.startNodeAtNode(id);
  18091. specifier.exported = id;
  18092. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  18093. return true;
  18094. }
  18095. return false;
  18096. }
  18097. maybeParseExportNamespaceSpecifier(node) {
  18098. if (this.isContextual(93)) {
  18099. var _ref, _ref$specifiers;
  18100. (_ref$specifiers = (_ref = node).specifiers) != null ? _ref$specifiers : _ref.specifiers = [];
  18101. const specifier = this.startNodeAt(this.state.lastTokStartLoc);
  18102. this.next();
  18103. specifier.exported = this.parseModuleExportName();
  18104. node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
  18105. return true;
  18106. }
  18107. return false;
  18108. }
  18109. maybeParseExportNamedSpecifiers(node) {
  18110. if (this.match(5)) {
  18111. const node2 = node;
  18112. if (!node2.specifiers) node2.specifiers = [];
  18113. const isTypeExport = node2.exportKind === "type";
  18114. node2.specifiers.push(...this.parseExportSpecifiers(isTypeExport));
  18115. node2.source = null;
  18116. if (this.hasPlugin("importAssertions")) {
  18117. node2.assertions = [];
  18118. } else {
  18119. node2.attributes = [];
  18120. }
  18121. node2.declaration = null;
  18122. return true;
  18123. }
  18124. return false;
  18125. }
  18126. maybeParseExportDeclaration(node) {
  18127. if (this.shouldParseExportDeclaration()) {
  18128. node.specifiers = [];
  18129. node.source = null;
  18130. if (this.hasPlugin("importAssertions")) {
  18131. node.assertions = [];
  18132. } else {
  18133. node.attributes = [];
  18134. }
  18135. node.declaration = this.parseExportDeclaration(node);
  18136. return true;
  18137. }
  18138. return false;
  18139. }
  18140. isAsyncFunction() {
  18141. if (!this.isContextual(95)) return false;
  18142. const next = this.nextTokenInLineStart();
  18143. return this.isUnparsedContextual(next, "function");
  18144. }
  18145. parseExportDefaultExpression() {
  18146. const expr = this.startNode();
  18147. if (this.match(68)) {
  18148. this.next();
  18149. return this.parseFunction(expr, 1 | 4);
  18150. } else if (this.isAsyncFunction()) {
  18151. this.next();
  18152. this.next();
  18153. return this.parseFunction(expr, 1 | 4 | 8);
  18154. }
  18155. if (this.match(80)) {
  18156. return this.parseClass(expr, true, true);
  18157. }
  18158. if (this.match(26)) {
  18159. if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") === true) {
  18160. this.raise(Errors.DecoratorBeforeExport, this.state.startLoc);
  18161. }
  18162. return this.parseClass(this.maybeTakeDecorators(this.parseDecorators(false), this.startNode()), true, true);
  18163. }
  18164. if (this.match(75) || this.match(74) || this.isLet() || this.isUsing() || this.isAwaitUsing()) {
  18165. throw this.raise(Errors.UnsupportedDefaultExport, this.state.startLoc);
  18166. }
  18167. const res = this.parseMaybeAssignAllowIn();
  18168. this.semicolon();
  18169. return res;
  18170. }
  18171. parseExportDeclaration(node) {
  18172. if (this.match(80)) {
  18173. const node = this.parseClass(this.startNode(), true, false);
  18174. return node;
  18175. }
  18176. return this.parseStatementListItem();
  18177. }
  18178. isExportDefaultSpecifier() {
  18179. const {
  18180. type
  18181. } = this.state;
  18182. if (tokenIsIdentifier(type)) {
  18183. if (type === 95 && !this.state.containsEsc || type === 100) {
  18184. return false;
  18185. }
  18186. if ((type === 130 || type === 129) && !this.state.containsEsc) {
  18187. const next = this.nextTokenStart();
  18188. const nextChar = this.input.charCodeAt(next);
  18189. if (nextChar === 123 || this.chStartsBindingIdentifier(nextChar, next) && !this.input.startsWith("from", next)) {
  18190. this.expectOnePlugin(["flow", "typescript"]);
  18191. return false;
  18192. }
  18193. }
  18194. } else if (!this.match(65)) {
  18195. return false;
  18196. }
  18197. const next = this.nextTokenStart();
  18198. const hasFrom = this.isUnparsedContextual(next, "from");
  18199. if (this.input.charCodeAt(next) === 44 || tokenIsIdentifier(this.state.type) && hasFrom) {
  18200. return true;
  18201. }
  18202. if (this.match(65) && hasFrom) {
  18203. const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4));
  18204. return nextAfterFrom === 34 || nextAfterFrom === 39;
  18205. }
  18206. return false;
  18207. }
  18208. parseExportFrom(node, expect) {
  18209. if (this.eatContextual(98)) {
  18210. node.source = this.parseImportSource();
  18211. this.checkExport(node);
  18212. this.maybeParseImportAttributes(node);
  18213. this.checkJSONModuleImport(node);
  18214. } else if (expect) {
  18215. this.unexpected();
  18216. }
  18217. this.semicolon();
  18218. }
  18219. shouldParseExportDeclaration() {
  18220. const {
  18221. type
  18222. } = this.state;
  18223. if (type === 26) {
  18224. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  18225. if (this.hasPlugin("decorators")) {
  18226. if (this.getPluginOption("decorators", "decoratorsBeforeExport") === true) {
  18227. this.raise(Errors.DecoratorBeforeExport, this.state.startLoc);
  18228. }
  18229. return true;
  18230. }
  18231. }
  18232. if (this.isUsing()) {
  18233. this.raise(Errors.UsingDeclarationExport, this.state.startLoc);
  18234. return true;
  18235. }
  18236. if (this.isAwaitUsing()) {
  18237. this.raise(Errors.UsingDeclarationExport, this.state.startLoc);
  18238. return true;
  18239. }
  18240. return type === 74 || type === 75 || type === 68 || type === 80 || this.isLet() || this.isAsyncFunction();
  18241. }
  18242. checkExport(node, checkNames, isDefault, isFrom) {
  18243. if (checkNames) {
  18244. var _node$specifiers;
  18245. if (isDefault) {
  18246. this.checkDuplicateExports(node, "default");
  18247. if (this.hasPlugin("exportDefaultFrom")) {
  18248. var _declaration$extra;
  18249. const declaration = node.declaration;
  18250. if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) != null && _declaration$extra.parenthesized)) {
  18251. this.raise(Errors.ExportDefaultFromAsIdentifier, declaration);
  18252. }
  18253. }
  18254. } else if ((_node$specifiers = node.specifiers) != null && _node$specifiers.length) {
  18255. for (const specifier of node.specifiers) {
  18256. const {
  18257. exported
  18258. } = specifier;
  18259. const exportName = exported.type === "Identifier" ? exported.name : exported.value;
  18260. this.checkDuplicateExports(specifier, exportName);
  18261. if (!isFrom && specifier.local) {
  18262. const {
  18263. local
  18264. } = specifier;
  18265. if (local.type !== "Identifier") {
  18266. this.raise(Errors.ExportBindingIsString, specifier, {
  18267. localName: local.value,
  18268. exportName
  18269. });
  18270. } else {
  18271. this.checkReservedWord(local.name, local.loc.start, true, false);
  18272. this.scope.checkLocalExport(local);
  18273. }
  18274. }
  18275. }
  18276. } else if (node.declaration) {
  18277. const decl = node.declaration;
  18278. if (decl.type === "FunctionDeclaration" || decl.type === "ClassDeclaration") {
  18279. const {
  18280. id
  18281. } = decl;
  18282. if (!id) throw new Error("Assertion failure");
  18283. this.checkDuplicateExports(node, id.name);
  18284. } else if (decl.type === "VariableDeclaration") {
  18285. for (const declaration of decl.declarations) {
  18286. this.checkDeclaration(declaration.id);
  18287. }
  18288. }
  18289. }
  18290. }
  18291. }
  18292. checkDeclaration(node) {
  18293. if (node.type === "Identifier") {
  18294. this.checkDuplicateExports(node, node.name);
  18295. } else if (node.type === "ObjectPattern") {
  18296. for (const prop of node.properties) {
  18297. this.checkDeclaration(prop);
  18298. }
  18299. } else if (node.type === "ArrayPattern") {
  18300. for (const elem of node.elements) {
  18301. if (elem) {
  18302. this.checkDeclaration(elem);
  18303. }
  18304. }
  18305. } else if (node.type === "ObjectProperty") {
  18306. this.checkDeclaration(node.value);
  18307. } else if (node.type === "RestElement") {
  18308. this.checkDeclaration(node.argument);
  18309. } else if (node.type === "AssignmentPattern") {
  18310. this.checkDeclaration(node.left);
  18311. }
  18312. }
  18313. checkDuplicateExports(node, exportName) {
  18314. if (this.exportedIdentifiers.has(exportName)) {
  18315. if (exportName === "default") {
  18316. this.raise(Errors.DuplicateDefaultExport, node);
  18317. } else {
  18318. this.raise(Errors.DuplicateExport, node, {
  18319. exportName
  18320. });
  18321. }
  18322. }
  18323. this.exportedIdentifiers.add(exportName);
  18324. }
  18325. parseExportSpecifiers(isInTypeExport) {
  18326. const nodes = [];
  18327. let first = true;
  18328. this.expect(5);
  18329. while (!this.eat(8)) {
  18330. if (first) {
  18331. first = false;
  18332. } else {
  18333. this.expect(12);
  18334. if (this.eat(8)) break;
  18335. }
  18336. const isMaybeTypeOnly = this.isContextual(130);
  18337. const isString = this.match(134);
  18338. const node = this.startNode();
  18339. node.local = this.parseModuleExportName();
  18340. nodes.push(this.parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly));
  18341. }
  18342. return nodes;
  18343. }
  18344. parseExportSpecifier(node, isString, isInTypeExport, isMaybeTypeOnly) {
  18345. if (this.eatContextual(93)) {
  18346. node.exported = this.parseModuleExportName();
  18347. } else if (isString) {
  18348. node.exported = this.cloneStringLiteral(node.local);
  18349. } else if (!node.exported) {
  18350. node.exported = this.cloneIdentifier(node.local);
  18351. }
  18352. return this.finishNode(node, "ExportSpecifier");
  18353. }
  18354. parseModuleExportName() {
  18355. if (this.match(134)) {
  18356. const result = this.parseStringLiteral(this.state.value);
  18357. const surrogate = loneSurrogate.exec(result.value);
  18358. if (surrogate) {
  18359. this.raise(Errors.ModuleExportNameHasLoneSurrogate, result, {
  18360. surrogateCharCode: surrogate[0].charCodeAt(0)
  18361. });
  18362. }
  18363. return result;
  18364. }
  18365. return this.parseIdentifier(true);
  18366. }
  18367. isJSONModuleImport(node) {
  18368. if (node.assertions != null) {
  18369. return node.assertions.some(({
  18370. key,
  18371. value
  18372. }) => {
  18373. return value.value === "json" && (key.type === "Identifier" ? key.name === "type" : key.value === "type");
  18374. });
  18375. }
  18376. return false;
  18377. }
  18378. checkImportReflection(node) {
  18379. const {
  18380. specifiers
  18381. } = node;
  18382. const singleBindingType = specifiers.length === 1 ? specifiers[0].type : null;
  18383. if (node.phase === "source") {
  18384. if (singleBindingType !== "ImportDefaultSpecifier") {
  18385. this.raise(Errors.SourcePhaseImportRequiresDefault, specifiers[0].loc.start);
  18386. }
  18387. } else if (node.phase === "defer") {
  18388. if (singleBindingType !== "ImportNamespaceSpecifier") {
  18389. this.raise(Errors.DeferImportRequiresNamespace, specifiers[0].loc.start);
  18390. }
  18391. } else if (node.module) {
  18392. var _node$assertions;
  18393. if (singleBindingType !== "ImportDefaultSpecifier") {
  18394. this.raise(Errors.ImportReflectionNotBinding, specifiers[0].loc.start);
  18395. }
  18396. if (((_node$assertions = node.assertions) == null ? void 0 : _node$assertions.length) > 0) {
  18397. this.raise(Errors.ImportReflectionHasAssertion, specifiers[0].loc.start);
  18398. }
  18399. }
  18400. }
  18401. checkJSONModuleImport(node) {
  18402. if (this.isJSONModuleImport(node) && node.type !== "ExportAllDeclaration") {
  18403. const {
  18404. specifiers
  18405. } = node;
  18406. if (specifiers != null) {
  18407. const nonDefaultNamedSpecifier = specifiers.find(specifier => {
  18408. let imported;
  18409. if (specifier.type === "ExportSpecifier") {
  18410. imported = specifier.local;
  18411. } else if (specifier.type === "ImportSpecifier") {
  18412. imported = specifier.imported;
  18413. }
  18414. if (imported !== undefined) {
  18415. return imported.type === "Identifier" ? imported.name !== "default" : imported.value !== "default";
  18416. }
  18417. });
  18418. if (nonDefaultNamedSpecifier !== undefined) {
  18419. this.raise(Errors.ImportJSONBindingNotDefault, nonDefaultNamedSpecifier.loc.start);
  18420. }
  18421. }
  18422. }
  18423. }
  18424. isPotentialImportPhase(isExport) {
  18425. if (isExport) return false;
  18426. return this.isContextual(105) || this.isContextual(97) || this.isContextual(127);
  18427. }
  18428. applyImportPhase(node, isExport, phase, loc) {
  18429. if (isExport) {
  18430. return;
  18431. }
  18432. if (phase === "module") {
  18433. this.expectPlugin("importReflection", loc);
  18434. node.module = true;
  18435. } else if (this.hasPlugin("importReflection")) {
  18436. node.module = false;
  18437. }
  18438. if (phase === "source") {
  18439. this.expectPlugin("sourcePhaseImports", loc);
  18440. node.phase = "source";
  18441. } else if (phase === "defer") {
  18442. this.expectPlugin("deferredImportEvaluation", loc);
  18443. node.phase = "defer";
  18444. } else if (this.hasPlugin("sourcePhaseImports")) {
  18445. node.phase = null;
  18446. }
  18447. }
  18448. parseMaybeImportPhase(node, isExport) {
  18449. if (!this.isPotentialImportPhase(isExport)) {
  18450. this.applyImportPhase(node, isExport, null);
  18451. return null;
  18452. }
  18453. const phaseIdentifier = this.startNode();
  18454. const phaseIdentifierName = this.parseIdentifierName(true);
  18455. const {
  18456. type
  18457. } = this.state;
  18458. const isImportPhase = tokenIsKeywordOrIdentifier(type) ? type !== 98 || this.lookaheadCharCode() === 102 : type !== 12;
  18459. if (isImportPhase) {
  18460. this.applyImportPhase(node, isExport, phaseIdentifierName, phaseIdentifier.loc.start);
  18461. return null;
  18462. } else {
  18463. this.applyImportPhase(node, isExport, null);
  18464. return this.createIdentifier(phaseIdentifier, phaseIdentifierName);
  18465. }
  18466. }
  18467. isPrecedingIdImportPhase(phase) {
  18468. const {
  18469. type
  18470. } = this.state;
  18471. return tokenIsIdentifier(type) ? type !== 98 || this.lookaheadCharCode() === 102 : type !== 12;
  18472. }
  18473. parseImport(node) {
  18474. if (this.match(134)) {
  18475. return this.parseImportSourceAndAttributes(node);
  18476. }
  18477. return this.parseImportSpecifiersAndAfter(node, this.parseMaybeImportPhase(node, false));
  18478. }
  18479. parseImportSpecifiersAndAfter(node, maybeDefaultIdentifier) {
  18480. node.specifiers = [];
  18481. const hasDefault = this.maybeParseDefaultImportSpecifier(node, maybeDefaultIdentifier);
  18482. const parseNext = !hasDefault || this.eat(12);
  18483. const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
  18484. if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
  18485. this.expectContextual(98);
  18486. return this.parseImportSourceAndAttributes(node);
  18487. }
  18488. parseImportSourceAndAttributes(node) {
  18489. var _node$specifiers2;
  18490. (_node$specifiers2 = node.specifiers) != null ? _node$specifiers2 : node.specifiers = [];
  18491. node.source = this.parseImportSource();
  18492. this.maybeParseImportAttributes(node);
  18493. this.checkImportReflection(node);
  18494. this.checkJSONModuleImport(node);
  18495. this.semicolon();
  18496. this.sawUnambiguousESM = true;
  18497. return this.finishNode(node, "ImportDeclaration");
  18498. }
  18499. parseImportSource() {
  18500. if (!this.match(134)) this.unexpected();
  18501. return this.parseExprAtom();
  18502. }
  18503. parseImportSpecifierLocal(node, specifier, type) {
  18504. specifier.local = this.parseIdentifier();
  18505. node.specifiers.push(this.finishImportSpecifier(specifier, type));
  18506. }
  18507. finishImportSpecifier(specifier, type, bindingType = 8201) {
  18508. this.checkLVal(specifier.local, {
  18509. type
  18510. }, bindingType);
  18511. return this.finishNode(specifier, type);
  18512. }
  18513. parseImportAttributes() {
  18514. this.expect(5);
  18515. const attrs = [];
  18516. const attrNames = new Set();
  18517. do {
  18518. if (this.match(8)) {
  18519. break;
  18520. }
  18521. const node = this.startNode();
  18522. const keyName = this.state.value;
  18523. if (attrNames.has(keyName)) {
  18524. this.raise(Errors.ModuleAttributesWithDuplicateKeys, this.state.startLoc, {
  18525. key: keyName
  18526. });
  18527. }
  18528. attrNames.add(keyName);
  18529. if (this.match(134)) {
  18530. node.key = this.parseStringLiteral(keyName);
  18531. } else {
  18532. node.key = this.parseIdentifier(true);
  18533. }
  18534. this.expect(14);
  18535. if (!this.match(134)) {
  18536. throw this.raise(Errors.ModuleAttributeInvalidValue, this.state.startLoc);
  18537. }
  18538. node.value = this.parseStringLiteral(this.state.value);
  18539. attrs.push(this.finishNode(node, "ImportAttribute"));
  18540. } while (this.eat(12));
  18541. this.expect(8);
  18542. return attrs;
  18543. }
  18544. parseModuleAttributes() {
  18545. const attrs = [];
  18546. const attributes = new Set();
  18547. do {
  18548. const node = this.startNode();
  18549. node.key = this.parseIdentifier(true);
  18550. if (node.key.name !== "type") {
  18551. this.raise(Errors.ModuleAttributeDifferentFromType, node.key);
  18552. }
  18553. if (attributes.has(node.key.name)) {
  18554. this.raise(Errors.ModuleAttributesWithDuplicateKeys, node.key, {
  18555. key: node.key.name
  18556. });
  18557. }
  18558. attributes.add(node.key.name);
  18559. this.expect(14);
  18560. if (!this.match(134)) {
  18561. throw this.raise(Errors.ModuleAttributeInvalidValue, this.state.startLoc);
  18562. }
  18563. node.value = this.parseStringLiteral(this.state.value);
  18564. attrs.push(this.finishNode(node, "ImportAttribute"));
  18565. } while (this.eat(12));
  18566. return attrs;
  18567. }
  18568. maybeParseImportAttributes(node) {
  18569. let attributes;
  18570. var useWith = false;
  18571. if (this.match(76)) {
  18572. if (this.hasPrecedingLineBreak() && this.lookaheadCharCode() === 40) {
  18573. return;
  18574. }
  18575. this.next();
  18576. if (this.hasPlugin("moduleAttributes")) {
  18577. attributes = this.parseModuleAttributes();
  18578. this.addExtra(node, "deprecatedWithLegacySyntax", true);
  18579. } else {
  18580. attributes = this.parseImportAttributes();
  18581. }
  18582. useWith = true;
  18583. } else if (this.isContextual(94) && !this.hasPrecedingLineBreak()) {
  18584. if (!this.hasPlugin("deprecatedImportAssert") && !this.hasPlugin("importAssertions")) {
  18585. this.raise(Errors.ImportAttributesUseAssert, this.state.startLoc);
  18586. }
  18587. if (!this.hasPlugin("importAssertions")) {
  18588. this.addExtra(node, "deprecatedAssertSyntax", true);
  18589. }
  18590. this.next();
  18591. attributes = this.parseImportAttributes();
  18592. } else {
  18593. attributes = [];
  18594. }
  18595. if (!useWith && this.hasPlugin("importAssertions")) {
  18596. node.assertions = attributes;
  18597. } else {
  18598. node.attributes = attributes;
  18599. }
  18600. }
  18601. maybeParseDefaultImportSpecifier(node, maybeDefaultIdentifier) {
  18602. if (maybeDefaultIdentifier) {
  18603. const specifier = this.startNodeAtNode(maybeDefaultIdentifier);
  18604. specifier.local = maybeDefaultIdentifier;
  18605. node.specifiers.push(this.finishImportSpecifier(specifier, "ImportDefaultSpecifier"));
  18606. return true;
  18607. } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
  18608. this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier");
  18609. return true;
  18610. }
  18611. return false;
  18612. }
  18613. maybeParseStarImportSpecifier(node) {
  18614. if (this.match(55)) {
  18615. const specifier = this.startNode();
  18616. this.next();
  18617. this.expectContextual(93);
  18618. this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier");
  18619. return true;
  18620. }
  18621. return false;
  18622. }
  18623. parseNamedImportSpecifiers(node) {
  18624. let first = true;
  18625. this.expect(5);
  18626. while (!this.eat(8)) {
  18627. if (first) {
  18628. first = false;
  18629. } else {
  18630. if (this.eat(14)) {
  18631. throw this.raise(Errors.DestructureNamedImport, this.state.startLoc);
  18632. }
  18633. this.expect(12);
  18634. if (this.eat(8)) break;
  18635. }
  18636. const specifier = this.startNode();
  18637. const importedIsString = this.match(134);
  18638. const isMaybeTypeOnly = this.isContextual(130);
  18639. specifier.imported = this.parseModuleExportName();
  18640. const importSpecifier = this.parseImportSpecifier(specifier, importedIsString, node.importKind === "type" || node.importKind === "typeof", isMaybeTypeOnly, undefined);
  18641. node.specifiers.push(importSpecifier);
  18642. }
  18643. }
  18644. parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) {
  18645. if (this.eatContextual(93)) {
  18646. specifier.local = this.parseIdentifier();
  18647. } else {
  18648. const {
  18649. imported
  18650. } = specifier;
  18651. if (importedIsString) {
  18652. throw this.raise(Errors.ImportBindingIsString, specifier, {
  18653. importName: imported.value
  18654. });
  18655. }
  18656. this.checkReservedWord(imported.name, specifier.loc.start, true, true);
  18657. if (!specifier.local) {
  18658. specifier.local = this.cloneIdentifier(imported);
  18659. }
  18660. }
  18661. return this.finishImportSpecifier(specifier, "ImportSpecifier", bindingType);
  18662. }
  18663. isThisParam(param) {
  18664. return param.type === "Identifier" && param.name === "this";
  18665. }
  18666. }
  18667. class Parser extends StatementParser {
  18668. constructor(options, input, pluginsMap) {
  18669. const normalizedOptions = getOptions(options);
  18670. super(normalizedOptions, input);
  18671. this.options = normalizedOptions;
  18672. this.initializeScopes();
  18673. this.plugins = pluginsMap;
  18674. this.filename = normalizedOptions.sourceFilename;
  18675. this.startIndex = normalizedOptions.startIndex;
  18676. let optionFlags = 0;
  18677. if (normalizedOptions.allowAwaitOutsideFunction) {
  18678. optionFlags |= 1;
  18679. }
  18680. if (normalizedOptions.allowReturnOutsideFunction) {
  18681. optionFlags |= 2;
  18682. }
  18683. if (normalizedOptions.allowImportExportEverywhere) {
  18684. optionFlags |= 8;
  18685. }
  18686. if (normalizedOptions.allowSuperOutsideMethod) {
  18687. optionFlags |= 16;
  18688. }
  18689. if (normalizedOptions.allowUndeclaredExports) {
  18690. optionFlags |= 64;
  18691. }
  18692. if (normalizedOptions.allowNewTargetOutsideFunction) {
  18693. optionFlags |= 4;
  18694. }
  18695. if (normalizedOptions.allowYieldOutsideFunction) {
  18696. optionFlags |= 32;
  18697. }
  18698. if (normalizedOptions.ranges) {
  18699. optionFlags |= 128;
  18700. }
  18701. if (normalizedOptions.tokens) {
  18702. optionFlags |= 256;
  18703. }
  18704. if (normalizedOptions.createImportExpressions) {
  18705. optionFlags |= 512;
  18706. }
  18707. if (normalizedOptions.createParenthesizedExpressions) {
  18708. optionFlags |= 1024;
  18709. }
  18710. if (normalizedOptions.errorRecovery) {
  18711. optionFlags |= 2048;
  18712. }
  18713. if (normalizedOptions.attachComment) {
  18714. optionFlags |= 4096;
  18715. }
  18716. if (normalizedOptions.annexB) {
  18717. optionFlags |= 8192;
  18718. }
  18719. this.optionFlags = optionFlags;
  18720. }
  18721. getScopeHandler() {
  18722. return ScopeHandler;
  18723. }
  18724. parse() {
  18725. this.enterInitialScopes();
  18726. const file = this.startNode();
  18727. const program = this.startNode();
  18728. this.nextToken();
  18729. file.errors = null;
  18730. const result = this.parseTopLevel(file, program);
  18731. result.errors = this.state.errors;
  18732. result.comments.length = this.state.commentsLen;
  18733. return result;
  18734. }
  18735. }
  18736. function parse(input, options) {
  18737. var _options;
  18738. if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") {
  18739. options = Object.assign({}, options);
  18740. try {
  18741. options.sourceType = "module";
  18742. const parser = getParser(options, input);
  18743. const ast = parser.parse();
  18744. if (parser.sawUnambiguousESM) {
  18745. return ast;
  18746. }
  18747. if (parser.ambiguousScriptDifferentAst) {
  18748. try {
  18749. options.sourceType = "script";
  18750. return getParser(options, input).parse();
  18751. } catch (_unused) {}
  18752. } else {
  18753. ast.program.sourceType = "script";
  18754. }
  18755. return ast;
  18756. } catch (moduleError) {
  18757. try {
  18758. options.sourceType = "script";
  18759. return getParser(options, input).parse();
  18760. } catch (_unused2) {}
  18761. throw moduleError;
  18762. }
  18763. } else {
  18764. return getParser(options, input).parse();
  18765. }
  18766. }
  18767. function parseExpression(input, options) {
  18768. const parser = getParser(options, input);
  18769. if (parser.options.strictMode) {
  18770. parser.state.strict = true;
  18771. }
  18772. return parser.getExpression();
  18773. }
  18774. function generateExportedTokenTypes(internalTokenTypes) {
  18775. const tokenTypes = {};
  18776. for (const typeName of Object.keys(internalTokenTypes)) {
  18777. tokenTypes[typeName] = getExportedToken(internalTokenTypes[typeName]);
  18778. }
  18779. return tokenTypes;
  18780. }
  18781. const tokTypes = generateExportedTokenTypes(tt);
  18782. function getParser(options, input) {
  18783. let cls = Parser;
  18784. const pluginsMap = new Map();
  18785. if (options != null && options.plugins) {
  18786. for (const plugin of options.plugins) {
  18787. let name, opts;
  18788. if (typeof plugin === "string") {
  18789. name = plugin;
  18790. } else {
  18791. [name, opts] = plugin;
  18792. }
  18793. if (!pluginsMap.has(name)) {
  18794. pluginsMap.set(name, opts || {});
  18795. }
  18796. }
  18797. validatePlugins(pluginsMap);
  18798. cls = getParserClass(pluginsMap);
  18799. }
  18800. return new cls(options, input, pluginsMap);
  18801. }
  18802. const parserClassCache = new Map();
  18803. function getParserClass(pluginsMap) {
  18804. const pluginList = [];
  18805. for (const name of mixinPluginNames) {
  18806. if (pluginsMap.has(name)) {
  18807. pluginList.push(name);
  18808. }
  18809. }
  18810. const key = pluginList.join("|");
  18811. let cls = parserClassCache.get(key);
  18812. if (!cls) {
  18813. cls = Parser;
  18814. for (const plugin of pluginList) {
  18815. cls = mixinPlugins[plugin](cls);
  18816. }
  18817. parserClassCache.set(key, cls);
  18818. }
  18819. return cls;
  18820. }
  18821. lib.parse = parse;
  18822. lib.parseExpression = parseExpression;
  18823. lib.tokTypes = tokTypes;
  18824. return lib;
  18825. }
  18826. var libExports = /*@__PURE__*/ requireLib();
  18827. // @ts-check
  18828. /** @typedef { import('estree').BaseNode} BaseNode */
  18829. /** @typedef {{
  18830. skip: () => void;
  18831. remove: () => void;
  18832. replace: (node: BaseNode) => void;
  18833. }} WalkerContext */
  18834. class WalkerBase {
  18835. constructor() {
  18836. /** @type {boolean} */
  18837. this.should_skip = false;
  18838. /** @type {boolean} */
  18839. this.should_remove = false;
  18840. /** @type {BaseNode | null} */
  18841. this.replacement = null;
  18842. /** @type {WalkerContext} */
  18843. this.context = {
  18844. skip: () => (this.should_skip = true),
  18845. remove: () => (this.should_remove = true),
  18846. replace: (node) => (this.replacement = node)
  18847. };
  18848. }
  18849. /**
  18850. *
  18851. * @param {any} parent
  18852. * @param {string} prop
  18853. * @param {number} index
  18854. * @param {BaseNode} node
  18855. */
  18856. replace(parent, prop, index, node) {
  18857. if (parent) {
  18858. if (index !== null) {
  18859. parent[prop][index] = node;
  18860. } else {
  18861. parent[prop] = node;
  18862. }
  18863. }
  18864. }
  18865. /**
  18866. *
  18867. * @param {any} parent
  18868. * @param {string} prop
  18869. * @param {number} index
  18870. */
  18871. remove(parent, prop, index) {
  18872. if (parent) {
  18873. if (index !== null) {
  18874. parent[prop].splice(index, 1);
  18875. } else {
  18876. delete parent[prop];
  18877. }
  18878. }
  18879. }
  18880. }
  18881. // @ts-check
  18882. /** @typedef { import('estree').BaseNode} BaseNode */
  18883. /** @typedef { import('./walker.js').WalkerContext} WalkerContext */
  18884. /** @typedef {(
  18885. * this: WalkerContext,
  18886. * node: BaseNode,
  18887. * parent: BaseNode,
  18888. * key: string,
  18889. * index: number
  18890. * ) => void} SyncHandler */
  18891. class SyncWalker extends WalkerBase {
  18892. /**
  18893. *
  18894. * @param {SyncHandler} enter
  18895. * @param {SyncHandler} leave
  18896. */
  18897. constructor(enter, leave) {
  18898. super();
  18899. /** @type {SyncHandler} */
  18900. this.enter = enter;
  18901. /** @type {SyncHandler} */
  18902. this.leave = leave;
  18903. }
  18904. /**
  18905. *
  18906. * @param {BaseNode} node
  18907. * @param {BaseNode} parent
  18908. * @param {string} [prop]
  18909. * @param {number} [index]
  18910. * @returns {BaseNode}
  18911. */
  18912. visit(node, parent, prop, index) {
  18913. if (node) {
  18914. if (this.enter) {
  18915. const _should_skip = this.should_skip;
  18916. const _should_remove = this.should_remove;
  18917. const _replacement = this.replacement;
  18918. this.should_skip = false;
  18919. this.should_remove = false;
  18920. this.replacement = null;
  18921. this.enter.call(this.context, node, parent, prop, index);
  18922. if (this.replacement) {
  18923. node = this.replacement;
  18924. this.replace(parent, prop, index, node);
  18925. }
  18926. if (this.should_remove) {
  18927. this.remove(parent, prop, index);
  18928. }
  18929. const skipped = this.should_skip;
  18930. const removed = this.should_remove;
  18931. this.should_skip = _should_skip;
  18932. this.should_remove = _should_remove;
  18933. this.replacement = _replacement;
  18934. if (skipped) return node;
  18935. if (removed) return null;
  18936. }
  18937. for (const key in node) {
  18938. const value = node[key];
  18939. if (typeof value !== "object") {
  18940. continue;
  18941. } else if (Array.isArray(value)) {
  18942. for (let i = 0; i < value.length; i += 1) {
  18943. if (value[i] !== null && typeof value[i].type === 'string') {
  18944. if (!this.visit(value[i], node, key, i)) {
  18945. // removed
  18946. i--;
  18947. }
  18948. }
  18949. }
  18950. } else if (value !== null && typeof value.type === "string") {
  18951. this.visit(value, node, key, null);
  18952. }
  18953. }
  18954. if (this.leave) {
  18955. const _replacement = this.replacement;
  18956. const _should_remove = this.should_remove;
  18957. this.replacement = null;
  18958. this.should_remove = false;
  18959. this.leave.call(this.context, node, parent, prop, index);
  18960. if (this.replacement) {
  18961. node = this.replacement;
  18962. this.replace(parent, prop, index, node);
  18963. }
  18964. if (this.should_remove) {
  18965. this.remove(parent, prop, index);
  18966. }
  18967. const removed = this.should_remove;
  18968. this.replacement = _replacement;
  18969. this.should_remove = _should_remove;
  18970. if (removed) return null;
  18971. }
  18972. }
  18973. return node;
  18974. }
  18975. }
  18976. // @ts-check
  18977. /** @typedef { import('estree').BaseNode} BaseNode */
  18978. /** @typedef { import('./sync.js').SyncHandler} SyncHandler */
  18979. /** @typedef { import('./async.js').AsyncHandler} AsyncHandler */
  18980. /**
  18981. *
  18982. * @param {BaseNode} ast
  18983. * @param {{
  18984. * enter?: SyncHandler
  18985. * leave?: SyncHandler
  18986. * }} walker
  18987. * @returns {BaseNode}
  18988. */
  18989. function walk$2(ast, { enter, leave }) {
  18990. const instance = new SyncWalker(enter, leave);
  18991. return instance.visit(ast, null);
  18992. }
  18993. function walkIdentifiers(root, onIdentifier, includeAll = false, parentStack = [], knownIds = /* @__PURE__ */ Object.create(null)) {
  18994. const rootExp = root.type === "Program" ? root.body[0].type === "ExpressionStatement" && root.body[0].expression : root;
  18995. walk$2(root, {
  18996. enter(node, parent) {
  18997. parent && parentStack.push(parent);
  18998. if (parent && parent.type.startsWith("TS") && !TS_NODE_TYPES.includes(parent.type)) {
  18999. return this.skip();
  19000. }
  19001. if (node.type === "Identifier") {
  19002. const isLocal = !!knownIds[node.name];
  19003. const isRefed = isReferencedIdentifier(node, parent, parentStack);
  19004. if (includeAll || isRefed && !isLocal) {
  19005. onIdentifier(node, parent, parentStack, isRefed, isLocal);
  19006. }
  19007. } else if (node.type === "ObjectProperty" && // eslint-disable-next-line no-restricted-syntax
  19008. (parent == null ? void 0 : parent.type) === "ObjectPattern") {
  19009. node.inPattern = true;
  19010. } else if (isFunctionType(node)) {
  19011. if (node.scopeIds) {
  19012. node.scopeIds.forEach((id) => markKnownIds(id, knownIds));
  19013. } else {
  19014. walkFunctionParams(
  19015. node,
  19016. (id) => markScopeIdentifier(node, id, knownIds)
  19017. );
  19018. }
  19019. } else if (node.type === "BlockStatement") {
  19020. if (node.scopeIds) {
  19021. node.scopeIds.forEach((id) => markKnownIds(id, knownIds));
  19022. } else {
  19023. walkBlockDeclarations(
  19024. node,
  19025. (id) => markScopeIdentifier(node, id, knownIds)
  19026. );
  19027. }
  19028. } else if (node.type === "SwitchStatement") {
  19029. if (node.scopeIds) {
  19030. node.scopeIds.forEach((id) => markKnownIds(id, knownIds));
  19031. } else {
  19032. walkSwitchStatement(
  19033. node,
  19034. false,
  19035. (id) => markScopeIdentifier(node, id, knownIds)
  19036. );
  19037. }
  19038. } else if (node.type === "CatchClause" && node.param) {
  19039. if (node.scopeIds) {
  19040. node.scopeIds.forEach((id) => markKnownIds(id, knownIds));
  19041. } else {
  19042. for (const id of extractIdentifiers$1(node.param)) {
  19043. markScopeIdentifier(node, id, knownIds);
  19044. }
  19045. }
  19046. } else if (isForStatement(node)) {
  19047. if (node.scopeIds) {
  19048. node.scopeIds.forEach((id) => markKnownIds(id, knownIds));
  19049. } else {
  19050. walkForStatement(
  19051. node,
  19052. false,
  19053. (id) => markScopeIdentifier(node, id, knownIds)
  19054. );
  19055. }
  19056. }
  19057. },
  19058. leave(node, parent) {
  19059. parent && parentStack.pop();
  19060. if (node !== rootExp && node.scopeIds) {
  19061. for (const id of node.scopeIds) {
  19062. knownIds[id]--;
  19063. if (knownIds[id] === 0) {
  19064. delete knownIds[id];
  19065. }
  19066. }
  19067. }
  19068. }
  19069. });
  19070. }
  19071. function isReferencedIdentifier(id, parent, parentStack) {
  19072. if (!parent) {
  19073. return true;
  19074. }
  19075. if (id.name === "arguments") {
  19076. return false;
  19077. }
  19078. if (isReferenced(id, parent, parentStack[parentStack.length - 2])) {
  19079. return true;
  19080. }
  19081. switch (parent.type) {
  19082. case "AssignmentExpression":
  19083. case "AssignmentPattern":
  19084. return true;
  19085. case "ObjectProperty":
  19086. return parent.key !== id && isInDestructureAssignment(parent, parentStack);
  19087. case "ArrayPattern":
  19088. return isInDestructureAssignment(parent, parentStack);
  19089. }
  19090. return false;
  19091. }
  19092. function isInDestructureAssignment(parent, parentStack) {
  19093. if (parent && (parent.type === "ObjectProperty" || parent.type === "ArrayPattern")) {
  19094. let i = parentStack.length;
  19095. while (i--) {
  19096. const p = parentStack[i];
  19097. if (p.type === "AssignmentExpression") {
  19098. return true;
  19099. } else if (p.type !== "ObjectProperty" && !p.type.endsWith("Pattern")) {
  19100. break;
  19101. }
  19102. }
  19103. }
  19104. return false;
  19105. }
  19106. function isInNewExpression(parentStack) {
  19107. let i = parentStack.length;
  19108. while (i--) {
  19109. const p = parentStack[i];
  19110. if (p.type === "NewExpression") {
  19111. return true;
  19112. } else if (p.type !== "MemberExpression") {
  19113. break;
  19114. }
  19115. }
  19116. return false;
  19117. }
  19118. function walkFunctionParams(node, onIdent) {
  19119. for (const p of node.params) {
  19120. for (const id of extractIdentifiers$1(p)) {
  19121. onIdent(id);
  19122. }
  19123. }
  19124. }
  19125. function walkBlockDeclarations(block, onIdent) {
  19126. const body = block.type === "SwitchCase" ? block.consequent : block.body;
  19127. for (const stmt of body) {
  19128. if (stmt.type === "VariableDeclaration") {
  19129. if (stmt.declare) continue;
  19130. for (const decl of stmt.declarations) {
  19131. for (const id of extractIdentifiers$1(decl.id)) {
  19132. onIdent(id);
  19133. }
  19134. }
  19135. } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
  19136. if (stmt.declare || !stmt.id) continue;
  19137. onIdent(stmt.id);
  19138. } else if (isForStatement(stmt)) {
  19139. walkForStatement(stmt, true, onIdent);
  19140. } else if (stmt.type === "SwitchStatement") {
  19141. walkSwitchStatement(stmt, true, onIdent);
  19142. }
  19143. }
  19144. }
  19145. function isForStatement(stmt) {
  19146. return stmt.type === "ForOfStatement" || stmt.type === "ForInStatement" || stmt.type === "ForStatement";
  19147. }
  19148. function walkForStatement(stmt, isVar, onIdent) {
  19149. const variable = stmt.type === "ForStatement" ? stmt.init : stmt.left;
  19150. if (variable && variable.type === "VariableDeclaration" && (variable.kind === "var" ? isVar : !isVar)) {
  19151. for (const decl of variable.declarations) {
  19152. for (const id of extractIdentifiers$1(decl.id)) {
  19153. onIdent(id);
  19154. }
  19155. }
  19156. }
  19157. }
  19158. function walkSwitchStatement(stmt, isVar, onIdent) {
  19159. for (const cs of stmt.cases) {
  19160. for (const stmt2 of cs.consequent) {
  19161. if (stmt2.type === "VariableDeclaration" && (stmt2.kind === "var" ? isVar : !isVar)) {
  19162. for (const decl of stmt2.declarations) {
  19163. for (const id of extractIdentifiers$1(decl.id)) {
  19164. onIdent(id);
  19165. }
  19166. }
  19167. }
  19168. }
  19169. walkBlockDeclarations(cs, onIdent);
  19170. }
  19171. }
  19172. function extractIdentifiers$1(param, nodes = []) {
  19173. switch (param.type) {
  19174. case "Identifier":
  19175. nodes.push(param);
  19176. break;
  19177. case "MemberExpression":
  19178. let object = param;
  19179. while (object.type === "MemberExpression") {
  19180. object = object.object;
  19181. }
  19182. nodes.push(object);
  19183. break;
  19184. case "ObjectPattern":
  19185. for (const prop of param.properties) {
  19186. if (prop.type === "RestElement") {
  19187. extractIdentifiers$1(prop.argument, nodes);
  19188. } else {
  19189. extractIdentifiers$1(prop.value, nodes);
  19190. }
  19191. }
  19192. break;
  19193. case "ArrayPattern":
  19194. param.elements.forEach((element) => {
  19195. if (element) extractIdentifiers$1(element, nodes);
  19196. });
  19197. break;
  19198. case "RestElement":
  19199. extractIdentifiers$1(param.argument, nodes);
  19200. break;
  19201. case "AssignmentPattern":
  19202. extractIdentifiers$1(param.left, nodes);
  19203. break;
  19204. }
  19205. return nodes;
  19206. }
  19207. function markKnownIds(name, knownIds) {
  19208. if (name in knownIds) {
  19209. knownIds[name]++;
  19210. } else {
  19211. knownIds[name] = 1;
  19212. }
  19213. }
  19214. function markScopeIdentifier(node, child, knownIds) {
  19215. const { name } = child;
  19216. if (node.scopeIds && node.scopeIds.has(name)) {
  19217. return;
  19218. }
  19219. markKnownIds(name, knownIds);
  19220. (node.scopeIds || (node.scopeIds = /* @__PURE__ */ new Set())).add(name);
  19221. }
  19222. const isFunctionType = (node) => {
  19223. return /Function(?:Expression|Declaration)$|Method$/.test(node.type);
  19224. };
  19225. const isStaticProperty = (node) => node && (node.type === "ObjectProperty" || node.type === "ObjectMethod") && !node.computed;
  19226. const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
  19227. function isReferenced(node, parent, grandparent) {
  19228. switch (parent.type) {
  19229. // yes: PARENT[NODE]
  19230. // yes: NODE.child
  19231. // no: parent.NODE
  19232. case "MemberExpression":
  19233. case "OptionalMemberExpression":
  19234. if (parent.property === node) {
  19235. return !!parent.computed;
  19236. }
  19237. return parent.object === node;
  19238. case "JSXMemberExpression":
  19239. return parent.object === node;
  19240. // no: let NODE = init;
  19241. // yes: let id = NODE;
  19242. case "VariableDeclarator":
  19243. return parent.init === node;
  19244. // yes: () => NODE
  19245. // no: (NODE) => {}
  19246. case "ArrowFunctionExpression":
  19247. return parent.body === node;
  19248. // no: class { #NODE; }
  19249. // no: class { get #NODE() {} }
  19250. // no: class { #NODE() {} }
  19251. // no: class { fn() { return this.#NODE; } }
  19252. case "PrivateName":
  19253. return false;
  19254. // no: class { NODE() {} }
  19255. // yes: class { [NODE]() {} }
  19256. // no: class { foo(NODE) {} }
  19257. case "ClassMethod":
  19258. case "ClassPrivateMethod":
  19259. case "ObjectMethod":
  19260. if (parent.key === node) {
  19261. return !!parent.computed;
  19262. }
  19263. return false;
  19264. // yes: { [NODE]: "" }
  19265. // no: { NODE: "" }
  19266. // depends: { NODE }
  19267. // depends: { key: NODE }
  19268. case "ObjectProperty":
  19269. if (parent.key === node) {
  19270. return !!parent.computed;
  19271. }
  19272. return !grandparent || grandparent.type !== "ObjectPattern";
  19273. // no: class { NODE = value; }
  19274. // yes: class { [NODE] = value; }
  19275. // yes: class { key = NODE; }
  19276. case "ClassProperty":
  19277. if (parent.key === node) {
  19278. return !!parent.computed;
  19279. }
  19280. return true;
  19281. case "ClassPrivateProperty":
  19282. return parent.key !== node;
  19283. // no: class NODE {}
  19284. // yes: class Foo extends NODE {}
  19285. case "ClassDeclaration":
  19286. case "ClassExpression":
  19287. return parent.superClass === node;
  19288. // yes: left = NODE;
  19289. // no: NODE = right;
  19290. case "AssignmentExpression":
  19291. return parent.right === node;
  19292. // no: [NODE = foo] = [];
  19293. // yes: [foo = NODE] = [];
  19294. case "AssignmentPattern":
  19295. return parent.right === node;
  19296. // no: NODE: for (;;) {}
  19297. case "LabeledStatement":
  19298. return false;
  19299. // no: try {} catch (NODE) {}
  19300. case "CatchClause":
  19301. return false;
  19302. // no: function foo(...NODE) {}
  19303. case "RestElement":
  19304. return false;
  19305. case "BreakStatement":
  19306. case "ContinueStatement":
  19307. return false;
  19308. // no: function NODE() {}
  19309. // no: function foo(NODE) {}
  19310. case "FunctionDeclaration":
  19311. case "FunctionExpression":
  19312. return false;
  19313. // no: export NODE from "foo";
  19314. // no: export * as NODE from "foo";
  19315. case "ExportNamespaceSpecifier":
  19316. case "ExportDefaultSpecifier":
  19317. return false;
  19318. // no: export { foo as NODE };
  19319. // yes: export { NODE as foo };
  19320. // no: export { NODE as foo } from "foo";
  19321. case "ExportSpecifier":
  19322. if (grandparent == null ? void 0 : grandparent.source) {
  19323. return false;
  19324. }
  19325. return parent.local === node;
  19326. // no: import NODE from "foo";
  19327. // no: import * as NODE from "foo";
  19328. // no: import { NODE as foo } from "foo";
  19329. // no: import { foo as NODE } from "foo";
  19330. // no: import NODE from "bar";
  19331. case "ImportDefaultSpecifier":
  19332. case "ImportNamespaceSpecifier":
  19333. case "ImportSpecifier":
  19334. return false;
  19335. // no: import "foo" assert { NODE: "json" }
  19336. case "ImportAttribute":
  19337. return false;
  19338. // no: <div NODE="foo" />
  19339. case "JSXAttribute":
  19340. return false;
  19341. // no: [NODE] = [];
  19342. // no: ({ NODE }) = [];
  19343. case "ObjectPattern":
  19344. case "ArrayPattern":
  19345. return false;
  19346. // no: new.NODE
  19347. // no: NODE.target
  19348. case "MetaProperty":
  19349. return false;
  19350. // yes: type X = { someProperty: NODE }
  19351. // no: type X = { NODE: OtherType }
  19352. case "ObjectTypeProperty":
  19353. return parent.key !== node;
  19354. // yes: enum X { Foo = NODE }
  19355. // no: enum X { NODE }
  19356. case "TSEnumMember":
  19357. return parent.id !== node;
  19358. // yes: { [NODE]: value }
  19359. // no: { NODE: value }
  19360. case "TSPropertySignature":
  19361. if (parent.key === node) {
  19362. return !!parent.computed;
  19363. }
  19364. return true;
  19365. }
  19366. return true;
  19367. }
  19368. const TS_NODE_TYPES = [
  19369. "TSAsExpression",
  19370. // foo as number
  19371. "TSTypeAssertion",
  19372. // (<number>foo)
  19373. "TSNonNullExpression",
  19374. // foo!
  19375. "TSInstantiationExpression",
  19376. // foo<string>
  19377. "TSSatisfiesExpression"
  19378. // foo satisfies T
  19379. ];
  19380. function unwrapTSNode(node) {
  19381. if (TS_NODE_TYPES.includes(node.type)) {
  19382. return unwrapTSNode(node.expression);
  19383. } else {
  19384. return node;
  19385. }
  19386. }
  19387. const isStaticExp = (p) => p.type === 4 && p.isStatic;
  19388. function isCoreComponent(tag) {
  19389. switch (tag) {
  19390. case "Teleport":
  19391. case "teleport":
  19392. return TELEPORT;
  19393. case "Suspense":
  19394. case "suspense":
  19395. return SUSPENSE;
  19396. case "KeepAlive":
  19397. case "keep-alive":
  19398. return KEEP_ALIVE;
  19399. case "BaseTransition":
  19400. case "base-transition":
  19401. return BASE_TRANSITION;
  19402. }
  19403. }
  19404. const nonIdentifierRE = /^$|^\d|[^\$\w\xA0-\uFFFF]/;
  19405. const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
  19406. const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
  19407. const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
  19408. const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
  19409. const getExpSource = (exp) => exp.type === 4 ? exp.content : exp.loc.source;
  19410. const isMemberExpressionBrowser = (exp) => {
  19411. const path = getExpSource(exp).trim().replace(whitespaceRE, (s) => s.trim());
  19412. let state = 0 /* inMemberExp */;
  19413. let stateStack = [];
  19414. let currentOpenBracketCount = 0;
  19415. let currentOpenParensCount = 0;
  19416. let currentStringType = null;
  19417. for (let i = 0; i < path.length; i++) {
  19418. const char = path.charAt(i);
  19419. switch (state) {
  19420. case 0 /* inMemberExp */:
  19421. if (char === "[") {
  19422. stateStack.push(state);
  19423. state = 1 /* inBrackets */;
  19424. currentOpenBracketCount++;
  19425. } else if (char === "(") {
  19426. stateStack.push(state);
  19427. state = 2 /* inParens */;
  19428. currentOpenParensCount++;
  19429. } else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
  19430. return false;
  19431. }
  19432. break;
  19433. case 1 /* inBrackets */:
  19434. if (char === `'` || char === `"` || char === "`") {
  19435. stateStack.push(state);
  19436. state = 3 /* inString */;
  19437. currentStringType = char;
  19438. } else if (char === `[`) {
  19439. currentOpenBracketCount++;
  19440. } else if (char === `]`) {
  19441. if (!--currentOpenBracketCount) {
  19442. state = stateStack.pop();
  19443. }
  19444. }
  19445. break;
  19446. case 2 /* inParens */:
  19447. if (char === `'` || char === `"` || char === "`") {
  19448. stateStack.push(state);
  19449. state = 3 /* inString */;
  19450. currentStringType = char;
  19451. } else if (char === `(`) {
  19452. currentOpenParensCount++;
  19453. } else if (char === `)`) {
  19454. if (i === path.length - 1) {
  19455. return false;
  19456. }
  19457. if (!--currentOpenParensCount) {
  19458. state = stateStack.pop();
  19459. }
  19460. }
  19461. break;
  19462. case 3 /* inString */:
  19463. if (char === currentStringType) {
  19464. state = stateStack.pop();
  19465. currentStringType = null;
  19466. }
  19467. break;
  19468. }
  19469. }
  19470. return !currentOpenBracketCount && !currentOpenParensCount;
  19471. };
  19472. const isMemberExpressionNode = (exp, context) => {
  19473. try {
  19474. let ret = exp.ast || libExports.parseExpression(getExpSource(exp), {
  19475. plugins: context.expressionPlugins ? [...context.expressionPlugins, "typescript"] : ["typescript"]
  19476. });
  19477. ret = unwrapTSNode(ret);
  19478. return ret.type === "MemberExpression" || ret.type === "OptionalMemberExpression" || ret.type === "Identifier" && ret.name !== "undefined";
  19479. } catch (e) {
  19480. return false;
  19481. }
  19482. };
  19483. const isMemberExpression = isMemberExpressionNode;
  19484. const fnExpRE = /^\s*(?:async\s*)?(?:\([^)]*?\)|[\w$_]+)\s*(?::[^=]+)?=>|^\s*(?:async\s+)?function(?:\s+[\w$]+)?\s*\(/;
  19485. const isFnExpressionBrowser = (exp) => fnExpRE.test(getExpSource(exp));
  19486. const isFnExpressionNode = (exp, context) => {
  19487. try {
  19488. let ret = exp.ast || libExports.parseExpression(getExpSource(exp), {
  19489. plugins: context.expressionPlugins ? [...context.expressionPlugins, "typescript"] : ["typescript"]
  19490. });
  19491. if (ret.type === "Program") {
  19492. ret = ret.body[0];
  19493. if (ret.type === "ExpressionStatement") {
  19494. ret = ret.expression;
  19495. }
  19496. }
  19497. ret = unwrapTSNode(ret);
  19498. return ret.type === "FunctionExpression" || ret.type === "ArrowFunctionExpression";
  19499. } catch (e) {
  19500. return false;
  19501. }
  19502. };
  19503. const isFnExpression = isFnExpressionNode;
  19504. function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
  19505. return advancePositionWithMutation(
  19506. {
  19507. offset: pos.offset,
  19508. line: pos.line,
  19509. column: pos.column
  19510. },
  19511. source,
  19512. numberOfCharacters
  19513. );
  19514. }
  19515. function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
  19516. let linesCount = 0;
  19517. let lastNewLinePos = -1;
  19518. for (let i = 0; i < numberOfCharacters; i++) {
  19519. if (source.charCodeAt(i) === 10) {
  19520. linesCount++;
  19521. lastNewLinePos = i;
  19522. }
  19523. }
  19524. pos.offset += numberOfCharacters;
  19525. pos.line += linesCount;
  19526. pos.column = lastNewLinePos === -1 ? pos.column + numberOfCharacters : numberOfCharacters - lastNewLinePos;
  19527. return pos;
  19528. }
  19529. function assert(condition, msg) {
  19530. if (!condition) {
  19531. throw new Error(msg || `unexpected compiler condition`);
  19532. }
  19533. }
  19534. function findDir(node, name, allowEmpty = false) {
  19535. for (let i = 0; i < node.props.length; i++) {
  19536. const p = node.props[i];
  19537. if (p.type === 7 && (allowEmpty || p.exp) && (isString$1(name) ? p.name === name : name.test(p.name))) {
  19538. return p;
  19539. }
  19540. }
  19541. }
  19542. function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
  19543. for (let i = 0; i < node.props.length; i++) {
  19544. const p = node.props[i];
  19545. if (p.type === 6) {
  19546. if (dynamicOnly) continue;
  19547. if (p.name === name && (p.value || allowEmpty)) {
  19548. return p;
  19549. }
  19550. } else if (p.name === "bind" && (p.exp || allowEmpty) && isStaticArgOf(p.arg, name)) {
  19551. return p;
  19552. }
  19553. }
  19554. }
  19555. function isStaticArgOf(arg, name) {
  19556. return !!(arg && isStaticExp(arg) && arg.content === name);
  19557. }
  19558. function hasDynamicKeyVBind(node) {
  19559. return node.props.some(
  19560. (p) => p.type === 7 && p.name === "bind" && (!p.arg || // v-bind="obj"
  19561. p.arg.type !== 4 || // v-bind:[_ctx.foo]
  19562. !p.arg.isStatic)
  19563. // v-bind:[foo]
  19564. );
  19565. }
  19566. function isText$1(node) {
  19567. return node.type === 5 || node.type === 2;
  19568. }
  19569. function isVPre(p) {
  19570. return p.type === 7 && p.name === "pre";
  19571. }
  19572. function isVSlot(p) {
  19573. return p.type === 7 && p.name === "slot";
  19574. }
  19575. function isTemplateNode(node) {
  19576. return node.type === 1 && node.tagType === 3;
  19577. }
  19578. function isSlotOutlet(node) {
  19579. return node.type === 1 && node.tagType === 2;
  19580. }
  19581. const propsHelperSet = /* @__PURE__ */ new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
  19582. function getUnnormalizedProps(props, callPath = []) {
  19583. if (props && !isString$1(props) && props.type === 14) {
  19584. const callee = props.callee;
  19585. if (!isString$1(callee) && propsHelperSet.has(callee)) {
  19586. return getUnnormalizedProps(
  19587. props.arguments[0],
  19588. callPath.concat(props)
  19589. );
  19590. }
  19591. }
  19592. return [props, callPath];
  19593. }
  19594. function injectProp(node, prop, context) {
  19595. if (node.type !== 13 && injectSlotKey(node, prop)) {
  19596. return;
  19597. }
  19598. let propsWithInjection;
  19599. let props = node.type === 13 ? node.props : node.arguments[2];
  19600. let callPath = [];
  19601. let parentCall;
  19602. if (props && !isString$1(props) && props.type === 14) {
  19603. const ret = getUnnormalizedProps(props);
  19604. props = ret[0];
  19605. callPath = ret[1];
  19606. parentCall = callPath[callPath.length - 1];
  19607. }
  19608. if (props == null || isString$1(props)) {
  19609. propsWithInjection = createObjectExpression([prop]);
  19610. } else if (props.type === 14) {
  19611. const first = props.arguments[0];
  19612. if (!isString$1(first) && first.type === 15) {
  19613. if (!hasProp(prop, first)) {
  19614. first.properties.unshift(prop);
  19615. }
  19616. } else {
  19617. if (props.callee === TO_HANDLERS) {
  19618. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  19619. createObjectExpression([prop]),
  19620. props
  19621. ]);
  19622. } else {
  19623. props.arguments.unshift(createObjectExpression([prop]));
  19624. }
  19625. }
  19626. !propsWithInjection && (propsWithInjection = props);
  19627. } else if (props.type === 15) {
  19628. if (!hasProp(prop, props)) {
  19629. props.properties.unshift(prop);
  19630. }
  19631. propsWithInjection = props;
  19632. } else {
  19633. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  19634. createObjectExpression([prop]),
  19635. props
  19636. ]);
  19637. if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
  19638. parentCall = callPath[callPath.length - 2];
  19639. }
  19640. }
  19641. if (node.type === 13) {
  19642. if (parentCall) {
  19643. parentCall.arguments[0] = propsWithInjection;
  19644. } else {
  19645. node.props = propsWithInjection;
  19646. }
  19647. } else {
  19648. if (parentCall) {
  19649. parentCall.arguments[0] = propsWithInjection;
  19650. } else {
  19651. node.arguments[2] = propsWithInjection;
  19652. }
  19653. }
  19654. }
  19655. function injectSlotKey(node, prop) {
  19656. var _a, _b, _c;
  19657. if (prop.key.type !== 4 || prop.key.content !== "key") {
  19658. return false;
  19659. }
  19660. const props = node.arguments[2];
  19661. if (props && !isString$1(props)) {
  19662. const [unnormalizedProps] = getUnnormalizedProps(props);
  19663. if (unnormalizedProps && !isString$1(unnormalizedProps) && unnormalizedProps.type === 15 && hasProp(prop, unnormalizedProps)) {
  19664. return true;
  19665. }
  19666. }
  19667. (_a = node.arguments)[2] || (_a[2] = "{}");
  19668. (_b = node.arguments)[3] || (_b[3] = "undefined");
  19669. (_c = node.arguments)[4] || (_c[4] = "undefined");
  19670. node.arguments[5] = prop.value;
  19671. return true;
  19672. }
  19673. function hasProp(prop, props) {
  19674. let result = false;
  19675. if (prop.key.type === 4) {
  19676. const propKeyName = prop.key.content;
  19677. result = props.properties.some(
  19678. (p) => p.key.type === 4 && p.key.content === propKeyName
  19679. );
  19680. }
  19681. return result;
  19682. }
  19683. function toValidAssetId(name, type) {
  19684. return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
  19685. return searchValue === "-" ? "_" : name.charCodeAt(replaceValue).toString();
  19686. })}`;
  19687. }
  19688. function hasScopeRef(node, ids) {
  19689. if (!node || Object.keys(ids).length === 0) {
  19690. return false;
  19691. }
  19692. switch (node.type) {
  19693. case 1:
  19694. for (let i = 0; i < node.props.length; i++) {
  19695. const p = node.props[i];
  19696. if (p.type === 7 && (hasScopeRef(p.arg, ids) || hasScopeRef(p.exp, ids))) {
  19697. return true;
  19698. }
  19699. }
  19700. return node.children.some((c) => hasScopeRef(c, ids));
  19701. case 11:
  19702. if (hasScopeRef(node.source, ids)) {
  19703. return true;
  19704. }
  19705. return node.children.some((c) => hasScopeRef(c, ids));
  19706. case 9:
  19707. return node.branches.some((b) => hasScopeRef(b, ids));
  19708. case 10:
  19709. if (hasScopeRef(node.condition, ids)) {
  19710. return true;
  19711. }
  19712. return node.children.some((c) => hasScopeRef(c, ids));
  19713. case 4:
  19714. return !node.isStatic && isSimpleIdentifier(node.content) && !!ids[node.content];
  19715. case 8:
  19716. return node.children.some((c) => isObject$2(c) && hasScopeRef(c, ids));
  19717. case 5:
  19718. case 12:
  19719. return hasScopeRef(node.content, ids);
  19720. case 2:
  19721. case 3:
  19722. case 20:
  19723. return false;
  19724. default:
  19725. return false;
  19726. }
  19727. }
  19728. function getMemoedVNodeCall(node) {
  19729. if (node.type === 14 && node.callee === WITH_MEMO) {
  19730. return node.arguments[1].returns;
  19731. } else {
  19732. return node;
  19733. }
  19734. }
  19735. const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+(\S[\s\S]*)/;
  19736. function isAllWhitespace(str) {
  19737. for (let i = 0; i < str.length; i++) {
  19738. if (!isWhitespace(str.charCodeAt(i))) {
  19739. return false;
  19740. }
  19741. }
  19742. return true;
  19743. }
  19744. function isWhitespaceText(node) {
  19745. return node.type === 2 && isAllWhitespace(node.content) || node.type === 12 && isWhitespaceText(node.content);
  19746. }
  19747. function isCommentOrWhitespace(node) {
  19748. return node.type === 3 || isWhitespaceText(node);
  19749. }
  19750. const defaultParserOptions = {
  19751. parseMode: "base",
  19752. ns: 0,
  19753. delimiters: [`{{`, `}}`],
  19754. getNamespace: () => 0,
  19755. isVoidTag: NO,
  19756. isPreTag: NO,
  19757. isIgnoreNewlineTag: NO,
  19758. isCustomElement: NO,
  19759. onError: defaultOnError,
  19760. onWarn: defaultOnWarn,
  19761. comments: true,
  19762. prefixIdentifiers: false
  19763. };
  19764. let currentOptions = defaultParserOptions;
  19765. let currentRoot = null;
  19766. let currentInput = "";
  19767. let currentOpenTag = null;
  19768. let currentProp = null;
  19769. let currentAttrValue = "";
  19770. let currentAttrStartIndex = -1;
  19771. let currentAttrEndIndex = -1;
  19772. let inPre = 0;
  19773. let inVPre = false;
  19774. let currentVPreBoundary = null;
  19775. const stack = [];
  19776. const tokenizer = new Tokenizer(stack, {
  19777. onerr: emitError,
  19778. ontext(start, end) {
  19779. onText(getSlice(start, end), start, end);
  19780. },
  19781. ontextentity(char, start, end) {
  19782. onText(char, start, end);
  19783. },
  19784. oninterpolation(start, end) {
  19785. if (inVPre) {
  19786. return onText(getSlice(start, end), start, end);
  19787. }
  19788. let innerStart = start + tokenizer.delimiterOpen.length;
  19789. let innerEnd = end - tokenizer.delimiterClose.length;
  19790. while (isWhitespace(currentInput.charCodeAt(innerStart))) {
  19791. innerStart++;
  19792. }
  19793. while (isWhitespace(currentInput.charCodeAt(innerEnd - 1))) {
  19794. innerEnd--;
  19795. }
  19796. let exp = getSlice(innerStart, innerEnd);
  19797. if (exp.includes("&")) {
  19798. {
  19799. exp = decodeHTML(exp);
  19800. }
  19801. }
  19802. addNode({
  19803. type: 5,
  19804. content: createExp(exp, false, getLoc(innerStart, innerEnd)),
  19805. loc: getLoc(start, end)
  19806. });
  19807. },
  19808. onopentagname(start, end) {
  19809. const name = getSlice(start, end);
  19810. currentOpenTag = {
  19811. type: 1,
  19812. tag: name,
  19813. ns: currentOptions.getNamespace(name, stack[0], currentOptions.ns),
  19814. tagType: 0,
  19815. // will be refined on tag close
  19816. props: [],
  19817. children: [],
  19818. loc: getLoc(start - 1, end),
  19819. codegenNode: void 0
  19820. };
  19821. },
  19822. onopentagend(end) {
  19823. endOpenTag(end);
  19824. },
  19825. onclosetag(start, end) {
  19826. const name = getSlice(start, end);
  19827. if (!currentOptions.isVoidTag(name)) {
  19828. let found = false;
  19829. for (let i = 0; i < stack.length; i++) {
  19830. const e = stack[i];
  19831. if (e.tag.toLowerCase() === name.toLowerCase()) {
  19832. found = true;
  19833. if (i > 0) {
  19834. emitError(24, stack[0].loc.start.offset);
  19835. }
  19836. for (let j = 0; j <= i; j++) {
  19837. const el = stack.shift();
  19838. onCloseTag(el, end, j < i);
  19839. }
  19840. break;
  19841. }
  19842. }
  19843. if (!found) {
  19844. emitError(23, backTrack(start, 60));
  19845. }
  19846. }
  19847. },
  19848. onselfclosingtag(end) {
  19849. const name = currentOpenTag.tag;
  19850. currentOpenTag.isSelfClosing = true;
  19851. endOpenTag(end);
  19852. if (stack[0] && stack[0].tag === name) {
  19853. onCloseTag(stack.shift(), end);
  19854. }
  19855. },
  19856. onattribname(start, end) {
  19857. currentProp = {
  19858. type: 6,
  19859. name: getSlice(start, end),
  19860. nameLoc: getLoc(start, end),
  19861. value: void 0,
  19862. loc: getLoc(start)
  19863. };
  19864. },
  19865. ondirname(start, end) {
  19866. const raw = getSlice(start, end);
  19867. const name = raw === "." || raw === ":" ? "bind" : raw === "@" ? "on" : raw === "#" ? "slot" : raw.slice(2);
  19868. if (!inVPre && name === "") {
  19869. emitError(26, start);
  19870. }
  19871. if (inVPre || name === "") {
  19872. currentProp = {
  19873. type: 6,
  19874. name: raw,
  19875. nameLoc: getLoc(start, end),
  19876. value: void 0,
  19877. loc: getLoc(start)
  19878. };
  19879. } else {
  19880. currentProp = {
  19881. type: 7,
  19882. name,
  19883. rawName: raw,
  19884. exp: void 0,
  19885. arg: void 0,
  19886. modifiers: raw === "." ? [createSimpleExpression("prop")] : [],
  19887. loc: getLoc(start)
  19888. };
  19889. if (name === "pre") {
  19890. inVPre = tokenizer.inVPre = true;
  19891. currentVPreBoundary = currentOpenTag;
  19892. const props = currentOpenTag.props;
  19893. for (let i = 0; i < props.length; i++) {
  19894. if (props[i].type === 7) {
  19895. props[i] = dirToAttr(props[i]);
  19896. }
  19897. }
  19898. }
  19899. }
  19900. },
  19901. ondirarg(start, end) {
  19902. if (start === end) return;
  19903. const arg = getSlice(start, end);
  19904. if (inVPre && !isVPre(currentProp)) {
  19905. currentProp.name += arg;
  19906. setLocEnd(currentProp.nameLoc, end);
  19907. } else {
  19908. const isStatic = arg[0] !== `[`;
  19909. currentProp.arg = createExp(
  19910. isStatic ? arg : arg.slice(1, -1),
  19911. isStatic,
  19912. getLoc(start, end),
  19913. isStatic ? 3 : 0
  19914. );
  19915. }
  19916. },
  19917. ondirmodifier(start, end) {
  19918. const mod = getSlice(start, end);
  19919. if (inVPre && !isVPre(currentProp)) {
  19920. currentProp.name += "." + mod;
  19921. setLocEnd(currentProp.nameLoc, end);
  19922. } else if (currentProp.name === "slot") {
  19923. const arg = currentProp.arg;
  19924. if (arg) {
  19925. arg.content += "." + mod;
  19926. setLocEnd(arg.loc, end);
  19927. }
  19928. } else {
  19929. const exp = createSimpleExpression(mod, true, getLoc(start, end));
  19930. currentProp.modifiers.push(exp);
  19931. }
  19932. },
  19933. onattribdata(start, end) {
  19934. currentAttrValue += getSlice(start, end);
  19935. if (currentAttrStartIndex < 0) currentAttrStartIndex = start;
  19936. currentAttrEndIndex = end;
  19937. },
  19938. onattribentity(char, start, end) {
  19939. currentAttrValue += char;
  19940. if (currentAttrStartIndex < 0) currentAttrStartIndex = start;
  19941. currentAttrEndIndex = end;
  19942. },
  19943. onattribnameend(end) {
  19944. const start = currentProp.loc.start.offset;
  19945. const name = getSlice(start, end);
  19946. if (currentProp.type === 7) {
  19947. currentProp.rawName = name;
  19948. }
  19949. if (currentOpenTag.props.some(
  19950. (p) => (p.type === 7 ? p.rawName : p.name) === name
  19951. )) {
  19952. emitError(2, start);
  19953. }
  19954. },
  19955. onattribend(quote, end) {
  19956. if (currentOpenTag && currentProp) {
  19957. setLocEnd(currentProp.loc, end);
  19958. if (quote !== 0) {
  19959. if (currentProp.type === 6) {
  19960. if (currentProp.name === "class") {
  19961. currentAttrValue = condense(currentAttrValue).trim();
  19962. }
  19963. if (quote === 1 && !currentAttrValue) {
  19964. emitError(13, end);
  19965. }
  19966. currentProp.value = {
  19967. type: 2,
  19968. content: currentAttrValue,
  19969. loc: quote === 1 ? getLoc(currentAttrStartIndex, currentAttrEndIndex) : getLoc(currentAttrStartIndex - 1, currentAttrEndIndex + 1)
  19970. };
  19971. if (tokenizer.inSFCRoot && currentOpenTag.tag === "template" && currentProp.name === "lang" && currentAttrValue && currentAttrValue !== "html") {
  19972. tokenizer.enterRCDATA(toCharCodes(`</template`), 0);
  19973. }
  19974. } else {
  19975. let expParseMode = 0 /* Normal */;
  19976. {
  19977. if (currentProp.name === "for") {
  19978. expParseMode = 3 /* Skip */;
  19979. } else if (currentProp.name === "slot") {
  19980. expParseMode = 1 /* Params */;
  19981. } else if (currentProp.name === "on" && currentAttrValue.includes(";")) {
  19982. expParseMode = 2 /* Statements */;
  19983. }
  19984. }
  19985. currentProp.exp = createExp(
  19986. currentAttrValue,
  19987. false,
  19988. getLoc(currentAttrStartIndex, currentAttrEndIndex),
  19989. 0,
  19990. expParseMode
  19991. );
  19992. if (currentProp.name === "for") {
  19993. currentProp.forParseResult = parseForExpression(currentProp.exp);
  19994. }
  19995. }
  19996. }
  19997. if (currentProp.type !== 7 || currentProp.name !== "pre") {
  19998. currentOpenTag.props.push(currentProp);
  19999. }
  20000. }
  20001. currentAttrValue = "";
  20002. currentAttrStartIndex = currentAttrEndIndex = -1;
  20003. },
  20004. oncomment(start, end) {
  20005. if (currentOptions.comments) {
  20006. addNode({
  20007. type: 3,
  20008. content: getSlice(start, end),
  20009. loc: getLoc(start - 4, end + 3)
  20010. });
  20011. }
  20012. },
  20013. onend() {
  20014. const end = currentInput.length;
  20015. if (tokenizer.state !== 1) {
  20016. switch (tokenizer.state) {
  20017. case 5:
  20018. case 8:
  20019. emitError(5, end);
  20020. break;
  20021. case 3:
  20022. case 4:
  20023. emitError(
  20024. 25,
  20025. tokenizer.sectionStart
  20026. );
  20027. break;
  20028. case 28:
  20029. if (tokenizer.currentSequence === Sequences.CdataEnd) {
  20030. emitError(6, end);
  20031. } else {
  20032. emitError(7, end);
  20033. }
  20034. break;
  20035. case 6:
  20036. case 7:
  20037. case 9:
  20038. case 11:
  20039. case 12:
  20040. case 13:
  20041. case 14:
  20042. case 15:
  20043. case 16:
  20044. case 17:
  20045. case 18:
  20046. case 19:
  20047. // "
  20048. case 20:
  20049. // '
  20050. case 21:
  20051. emitError(9, end);
  20052. break;
  20053. }
  20054. }
  20055. for (let index = 0; index < stack.length; index++) {
  20056. onCloseTag(stack[index], end - 1);
  20057. emitError(24, stack[index].loc.start.offset);
  20058. }
  20059. },
  20060. oncdata(start, end) {
  20061. if ((stack[0] ? stack[0].ns : currentOptions.ns) !== 0) {
  20062. onText(getSlice(start, end), start, end);
  20063. } else {
  20064. emitError(1, start - 9);
  20065. }
  20066. },
  20067. onprocessinginstruction(start) {
  20068. if ((stack[0] ? stack[0].ns : currentOptions.ns) === 0) {
  20069. emitError(
  20070. 21,
  20071. start - 1
  20072. );
  20073. }
  20074. }
  20075. });
  20076. const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
  20077. const stripParensRE = /^\(|\)$/g;
  20078. function parseForExpression(input) {
  20079. const loc = input.loc;
  20080. const exp = input.content;
  20081. const inMatch = exp.match(forAliasRE);
  20082. if (!inMatch) return;
  20083. const [, LHS, RHS] = inMatch;
  20084. const createAliasExpression = (content, offset, asParam = false) => {
  20085. const start = loc.start.offset + offset;
  20086. const end = start + content.length;
  20087. return createExp(
  20088. content,
  20089. false,
  20090. getLoc(start, end),
  20091. 0,
  20092. asParam ? 1 /* Params */ : 0 /* Normal */
  20093. );
  20094. };
  20095. const result = {
  20096. source: createAliasExpression(RHS.trim(), exp.indexOf(RHS, LHS.length)),
  20097. value: void 0,
  20098. key: void 0,
  20099. index: void 0,
  20100. finalized: false
  20101. };
  20102. let valueContent = LHS.trim().replace(stripParensRE, "").trim();
  20103. const trimmedOffset = LHS.indexOf(valueContent);
  20104. const iteratorMatch = valueContent.match(forIteratorRE);
  20105. if (iteratorMatch) {
  20106. valueContent = valueContent.replace(forIteratorRE, "").trim();
  20107. const keyContent = iteratorMatch[1].trim();
  20108. let keyOffset;
  20109. if (keyContent) {
  20110. keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
  20111. result.key = createAliasExpression(keyContent, keyOffset, true);
  20112. }
  20113. if (iteratorMatch[2]) {
  20114. const indexContent = iteratorMatch[2].trim();
  20115. if (indexContent) {
  20116. result.index = createAliasExpression(
  20117. indexContent,
  20118. exp.indexOf(
  20119. indexContent,
  20120. result.key ? keyOffset + keyContent.length : trimmedOffset + valueContent.length
  20121. ),
  20122. true
  20123. );
  20124. }
  20125. }
  20126. }
  20127. if (valueContent) {
  20128. result.value = createAliasExpression(valueContent, trimmedOffset, true);
  20129. }
  20130. return result;
  20131. }
  20132. function getSlice(start, end) {
  20133. return currentInput.slice(start, end);
  20134. }
  20135. function endOpenTag(end) {
  20136. if (tokenizer.inSFCRoot) {
  20137. currentOpenTag.innerLoc = getLoc(end + 1, end + 1);
  20138. }
  20139. addNode(currentOpenTag);
  20140. const { tag, ns } = currentOpenTag;
  20141. if (ns === 0 && currentOptions.isPreTag(tag)) {
  20142. inPre++;
  20143. }
  20144. if (currentOptions.isVoidTag(tag)) {
  20145. onCloseTag(currentOpenTag, end);
  20146. } else {
  20147. stack.unshift(currentOpenTag);
  20148. if (ns === 1 || ns === 2) {
  20149. tokenizer.inXML = true;
  20150. }
  20151. }
  20152. currentOpenTag = null;
  20153. }
  20154. function onText(content, start, end) {
  20155. const parent = stack[0] || currentRoot;
  20156. const lastNode = parent.children[parent.children.length - 1];
  20157. if (lastNode && lastNode.type === 2) {
  20158. lastNode.content += content;
  20159. setLocEnd(lastNode.loc, end);
  20160. } else {
  20161. parent.children.push({
  20162. type: 2,
  20163. content,
  20164. loc: getLoc(start, end)
  20165. });
  20166. }
  20167. }
  20168. function onCloseTag(el, end, isImplied = false) {
  20169. if (isImplied) {
  20170. setLocEnd(el.loc, backTrack(end, 60));
  20171. } else {
  20172. setLocEnd(el.loc, lookAhead(end, 62) + 1);
  20173. }
  20174. if (tokenizer.inSFCRoot) {
  20175. if (el.children.length) {
  20176. el.innerLoc.end = extend({}, el.children[el.children.length - 1].loc.end);
  20177. } else {
  20178. el.innerLoc.end = extend({}, el.innerLoc.start);
  20179. }
  20180. el.innerLoc.source = getSlice(
  20181. el.innerLoc.start.offset,
  20182. el.innerLoc.end.offset
  20183. );
  20184. }
  20185. const { tag, ns, children } = el;
  20186. if (!inVPre) {
  20187. if (tag === "slot") {
  20188. el.tagType = 2;
  20189. } else if (isFragmentTemplate(el)) {
  20190. el.tagType = 3;
  20191. } else if (isComponent(el)) {
  20192. el.tagType = 1;
  20193. }
  20194. }
  20195. if (!tokenizer.inRCDATA) {
  20196. el.children = condenseWhitespace(children);
  20197. }
  20198. if (ns === 0 && currentOptions.isIgnoreNewlineTag(tag)) {
  20199. const first = children[0];
  20200. if (first && first.type === 2) {
  20201. first.content = first.content.replace(/^\r?\n/, "");
  20202. }
  20203. }
  20204. if (ns === 0 && currentOptions.isPreTag(tag)) {
  20205. inPre--;
  20206. }
  20207. if (currentVPreBoundary === el) {
  20208. inVPre = tokenizer.inVPre = false;
  20209. currentVPreBoundary = null;
  20210. }
  20211. if (tokenizer.inXML && (stack[0] ? stack[0].ns : currentOptions.ns) === 0) {
  20212. tokenizer.inXML = false;
  20213. }
  20214. }
  20215. function lookAhead(index, c) {
  20216. let i = index;
  20217. while (currentInput.charCodeAt(i) !== c && i < currentInput.length - 1) i++;
  20218. return i;
  20219. }
  20220. function backTrack(index, c) {
  20221. let i = index;
  20222. while (currentInput.charCodeAt(i) !== c && i >= 0) i--;
  20223. return i;
  20224. }
  20225. const specialTemplateDir = /* @__PURE__ */ new Set(["if", "else", "else-if", "for", "slot"]);
  20226. function isFragmentTemplate({ tag, props }) {
  20227. if (tag === "template") {
  20228. for (let i = 0; i < props.length; i++) {
  20229. if (props[i].type === 7 && specialTemplateDir.has(props[i].name)) {
  20230. return true;
  20231. }
  20232. }
  20233. }
  20234. return false;
  20235. }
  20236. function isComponent({ tag, props }) {
  20237. if (currentOptions.isCustomElement(tag)) {
  20238. return false;
  20239. }
  20240. if (tag === "component" || isUpperCase(tag.charCodeAt(0)) || isCoreComponent(tag) || currentOptions.isBuiltInComponent && currentOptions.isBuiltInComponent(tag) || currentOptions.isNativeTag && !currentOptions.isNativeTag(tag)) {
  20241. return true;
  20242. }
  20243. for (let i = 0; i < props.length; i++) {
  20244. const p = props[i];
  20245. if (p.type === 6) {
  20246. if (p.name === "is" && p.value) {
  20247. if (p.value.content.startsWith("vue:")) {
  20248. return true;
  20249. }
  20250. }
  20251. }
  20252. }
  20253. return false;
  20254. }
  20255. function isUpperCase(c) {
  20256. return c > 64 && c < 91;
  20257. }
  20258. const windowsNewlineRE = /\r\n/g;
  20259. function condenseWhitespace(nodes) {
  20260. const shouldCondense = currentOptions.whitespace !== "preserve";
  20261. let removedWhitespace = false;
  20262. for (let i = 0; i < nodes.length; i++) {
  20263. const node = nodes[i];
  20264. if (node.type === 2) {
  20265. if (!inPre) {
  20266. if (isAllWhitespace(node.content)) {
  20267. const prev = nodes[i - 1] && nodes[i - 1].type;
  20268. const next = nodes[i + 1] && nodes[i + 1].type;
  20269. if (!prev || !next || shouldCondense && (prev === 3 && (next === 3 || next === 1) || prev === 1 && (next === 3 || next === 1 && hasNewlineChar(node.content)))) {
  20270. removedWhitespace = true;
  20271. nodes[i] = null;
  20272. } else {
  20273. node.content = " ";
  20274. }
  20275. } else if (shouldCondense) {
  20276. node.content = condense(node.content);
  20277. }
  20278. } else {
  20279. node.content = node.content.replace(windowsNewlineRE, "\n");
  20280. }
  20281. }
  20282. }
  20283. return removedWhitespace ? nodes.filter(Boolean) : nodes;
  20284. }
  20285. function hasNewlineChar(str) {
  20286. for (let i = 0; i < str.length; i++) {
  20287. const c = str.charCodeAt(i);
  20288. if (c === 10 || c === 13) {
  20289. return true;
  20290. }
  20291. }
  20292. return false;
  20293. }
  20294. function condense(str) {
  20295. let ret = "";
  20296. let prevCharIsWhitespace = false;
  20297. for (let i = 0; i < str.length; i++) {
  20298. if (isWhitespace(str.charCodeAt(i))) {
  20299. if (!prevCharIsWhitespace) {
  20300. ret += " ";
  20301. prevCharIsWhitespace = true;
  20302. }
  20303. } else {
  20304. ret += str[i];
  20305. prevCharIsWhitespace = false;
  20306. }
  20307. }
  20308. return ret;
  20309. }
  20310. function addNode(node) {
  20311. (stack[0] || currentRoot).children.push(node);
  20312. }
  20313. function getLoc(start, end) {
  20314. return {
  20315. start: tokenizer.getPos(start),
  20316. // @ts-expect-error allow late attachment
  20317. end: end == null ? end : tokenizer.getPos(end),
  20318. // @ts-expect-error allow late attachment
  20319. source: end == null ? end : getSlice(start, end)
  20320. };
  20321. }
  20322. function cloneLoc(loc) {
  20323. return getLoc(loc.start.offset, loc.end.offset);
  20324. }
  20325. function setLocEnd(loc, end) {
  20326. loc.end = tokenizer.getPos(end);
  20327. loc.source = getSlice(loc.start.offset, end);
  20328. }
  20329. function dirToAttr(dir) {
  20330. const attr = {
  20331. type: 6,
  20332. name: dir.rawName,
  20333. nameLoc: getLoc(
  20334. dir.loc.start.offset,
  20335. dir.loc.start.offset + dir.rawName.length
  20336. ),
  20337. value: void 0,
  20338. loc: dir.loc
  20339. };
  20340. if (dir.exp) {
  20341. const loc = dir.exp.loc;
  20342. if (loc.end.offset < dir.loc.end.offset) {
  20343. loc.start.offset--;
  20344. loc.start.column--;
  20345. loc.end.offset++;
  20346. loc.end.column++;
  20347. }
  20348. attr.value = {
  20349. type: 2,
  20350. content: dir.exp.content,
  20351. loc
  20352. };
  20353. }
  20354. return attr;
  20355. }
  20356. function createExp(content, isStatic = false, loc, constType = 0, parseMode = 0 /* Normal */) {
  20357. const exp = createSimpleExpression(content, isStatic, loc, constType);
  20358. if (!isStatic && currentOptions.prefixIdentifiers && parseMode !== 3 /* Skip */ && content.trim()) {
  20359. if (isSimpleIdentifier(content)) {
  20360. exp.ast = null;
  20361. return exp;
  20362. }
  20363. try {
  20364. const plugins = currentOptions.expressionPlugins;
  20365. const options = {
  20366. plugins: plugins ? [...plugins, "typescript"] : ["typescript"]
  20367. };
  20368. if (parseMode === 2 /* Statements */) {
  20369. exp.ast = libExports.parse(` ${content} `, options).program;
  20370. } else if (parseMode === 1 /* Params */) {
  20371. exp.ast = libExports.parseExpression(`(${content})=>{}`, options);
  20372. } else {
  20373. exp.ast = libExports.parseExpression(`(${content})`, options);
  20374. }
  20375. } catch (e) {
  20376. exp.ast = false;
  20377. emitError(46, loc.start.offset, e.message);
  20378. }
  20379. }
  20380. return exp;
  20381. }
  20382. function emitError(code, index, message) {
  20383. currentOptions.onError(
  20384. createCompilerError(code, getLoc(index, index), void 0, message)
  20385. );
  20386. }
  20387. function reset() {
  20388. tokenizer.reset();
  20389. currentOpenTag = null;
  20390. currentProp = null;
  20391. currentAttrValue = "";
  20392. currentAttrStartIndex = -1;
  20393. currentAttrEndIndex = -1;
  20394. stack.length = 0;
  20395. }
  20396. function baseParse(input, options) {
  20397. reset();
  20398. currentInput = input;
  20399. currentOptions = extend({}, defaultParserOptions);
  20400. if (options) {
  20401. let key;
  20402. for (key in options) {
  20403. if (options[key] != null) {
  20404. currentOptions[key] = options[key];
  20405. }
  20406. }
  20407. }
  20408. {
  20409. if (currentOptions.decodeEntities) {
  20410. console.warn(
  20411. `[@vue/compiler-core] decodeEntities option is passed but will be ignored in non-browser builds.`
  20412. );
  20413. }
  20414. }
  20415. tokenizer.mode = currentOptions.parseMode === "html" ? 1 : currentOptions.parseMode === "sfc" ? 2 : 0;
  20416. tokenizer.inXML = currentOptions.ns === 1 || currentOptions.ns === 2;
  20417. const delimiters = options && options.delimiters;
  20418. if (delimiters) {
  20419. tokenizer.delimiterOpen = toCharCodes(delimiters[0]);
  20420. tokenizer.delimiterClose = toCharCodes(delimiters[1]);
  20421. }
  20422. const root = currentRoot = createRoot([], input);
  20423. tokenizer.parse(currentInput);
  20424. root.loc = getLoc(0, input.length);
  20425. root.children = condenseWhitespace(root.children);
  20426. currentRoot = null;
  20427. return root;
  20428. }
  20429. function cacheStatic(root, context) {
  20430. walk$1(
  20431. root,
  20432. void 0,
  20433. context,
  20434. // Root node is unfortunately non-hoistable due to potential parent
  20435. // fallthrough attributes.
  20436. !!getSingleElementRoot(root)
  20437. );
  20438. }
  20439. function getSingleElementRoot(root) {
  20440. const children = root.children.filter((x) => x.type !== 3);
  20441. return children.length === 1 && children[0].type === 1 && !isSlotOutlet(children[0]) ? children[0] : null;
  20442. }
  20443. function walk$1(node, parent, context, doNotHoistNode = false, inFor = false) {
  20444. const { children } = node;
  20445. const toCache = [];
  20446. for (let i = 0; i < children.length; i++) {
  20447. const child = children[i];
  20448. if (child.type === 1 && child.tagType === 0) {
  20449. const constantType = doNotHoistNode ? 0 : getConstantType(child, context);
  20450. if (constantType > 0) {
  20451. if (constantType >= 2) {
  20452. child.codegenNode.patchFlag = -1;
  20453. toCache.push(child);
  20454. continue;
  20455. }
  20456. } else {
  20457. const codegenNode = child.codegenNode;
  20458. if (codegenNode.type === 13) {
  20459. const flag = codegenNode.patchFlag;
  20460. if ((flag === void 0 || flag === 512 || flag === 1) && getGeneratedPropsConstantType(child, context) >= 2) {
  20461. const props = getNodeProps(child);
  20462. if (props) {
  20463. codegenNode.props = context.hoist(props);
  20464. }
  20465. }
  20466. if (codegenNode.dynamicProps) {
  20467. codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
  20468. }
  20469. }
  20470. }
  20471. } else if (child.type === 12) {
  20472. const constantType = doNotHoistNode ? 0 : getConstantType(child, context);
  20473. if (constantType >= 2) {
  20474. if (child.codegenNode.type === 14 && child.codegenNode.arguments.length > 0) {
  20475. child.codegenNode.arguments.push(
  20476. -1 + (` /* ${PatchFlagNames[-1]} */` )
  20477. );
  20478. }
  20479. toCache.push(child);
  20480. continue;
  20481. }
  20482. }
  20483. if (child.type === 1) {
  20484. const isComponent = child.tagType === 1;
  20485. if (isComponent) {
  20486. context.scopes.vSlot++;
  20487. }
  20488. walk$1(child, node, context, false, inFor);
  20489. if (isComponent) {
  20490. context.scopes.vSlot--;
  20491. }
  20492. } else if (child.type === 11) {
  20493. walk$1(child, node, context, child.children.length === 1, true);
  20494. } else if (child.type === 9) {
  20495. for (let i2 = 0; i2 < child.branches.length; i2++) {
  20496. walk$1(
  20497. child.branches[i2],
  20498. node,
  20499. context,
  20500. child.branches[i2].children.length === 1,
  20501. inFor
  20502. );
  20503. }
  20504. }
  20505. }
  20506. let cachedAsArray = false;
  20507. if (toCache.length === children.length && node.type === 1) {
  20508. if (node.tagType === 0 && node.codegenNode && node.codegenNode.type === 13 && isArray$3(node.codegenNode.children)) {
  20509. node.codegenNode.children = getCacheExpression(
  20510. createArrayExpression(node.codegenNode.children)
  20511. );
  20512. cachedAsArray = true;
  20513. } else if (node.tagType === 1 && node.codegenNode && node.codegenNode.type === 13 && node.codegenNode.children && !isArray$3(node.codegenNode.children) && node.codegenNode.children.type === 15) {
  20514. const slot = getSlotNode(node.codegenNode, "default");
  20515. if (slot) {
  20516. slot.returns = getCacheExpression(
  20517. createArrayExpression(slot.returns)
  20518. );
  20519. cachedAsArray = true;
  20520. }
  20521. } 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) {
  20522. const slotName = findDir(node, "slot", true);
  20523. const slot = slotName && slotName.arg && getSlotNode(parent.codegenNode, slotName.arg);
  20524. if (slot) {
  20525. slot.returns = getCacheExpression(
  20526. createArrayExpression(slot.returns)
  20527. );
  20528. cachedAsArray = true;
  20529. }
  20530. }
  20531. }
  20532. if (!cachedAsArray) {
  20533. for (const child of toCache) {
  20534. child.codegenNode = context.cache(child.codegenNode);
  20535. }
  20536. }
  20537. function getCacheExpression(value) {
  20538. const exp = context.cache(value);
  20539. exp.needArraySpread = true;
  20540. return exp;
  20541. }
  20542. function getSlotNode(node2, name) {
  20543. if (node2.children && !isArray$3(node2.children) && node2.children.type === 15) {
  20544. const slot = node2.children.properties.find(
  20545. (p) => p.key === name || p.key.content === name
  20546. );
  20547. return slot && slot.value;
  20548. }
  20549. }
  20550. if (toCache.length && context.transformHoist) {
  20551. context.transformHoist(children, context, node);
  20552. }
  20553. }
  20554. function getConstantType(node, context) {
  20555. const { constantCache } = context;
  20556. switch (node.type) {
  20557. case 1:
  20558. if (node.tagType !== 0) {
  20559. return 0;
  20560. }
  20561. const cached = constantCache.get(node);
  20562. if (cached !== void 0) {
  20563. return cached;
  20564. }
  20565. const codegenNode = node.codegenNode;
  20566. if (codegenNode.type !== 13) {
  20567. return 0;
  20568. }
  20569. if (codegenNode.isBlock && node.tag !== "svg" && node.tag !== "foreignObject" && node.tag !== "math") {
  20570. return 0;
  20571. }
  20572. if (codegenNode.patchFlag === void 0) {
  20573. let returnType2 = 3;
  20574. const generatedPropsType = getGeneratedPropsConstantType(node, context);
  20575. if (generatedPropsType === 0) {
  20576. constantCache.set(node, 0);
  20577. return 0;
  20578. }
  20579. if (generatedPropsType < returnType2) {
  20580. returnType2 = generatedPropsType;
  20581. }
  20582. for (let i = 0; i < node.children.length; i++) {
  20583. const childType = getConstantType(node.children[i], context);
  20584. if (childType === 0) {
  20585. constantCache.set(node, 0);
  20586. return 0;
  20587. }
  20588. if (childType < returnType2) {
  20589. returnType2 = childType;
  20590. }
  20591. }
  20592. if (returnType2 > 1) {
  20593. for (let i = 0; i < node.props.length; i++) {
  20594. const p = node.props[i];
  20595. if (p.type === 7 && p.name === "bind" && p.exp) {
  20596. const expType = getConstantType(p.exp, context);
  20597. if (expType === 0) {
  20598. constantCache.set(node, 0);
  20599. return 0;
  20600. }
  20601. if (expType < returnType2) {
  20602. returnType2 = expType;
  20603. }
  20604. }
  20605. }
  20606. }
  20607. if (codegenNode.isBlock) {
  20608. for (let i = 0; i < node.props.length; i++) {
  20609. const p = node.props[i];
  20610. if (p.type === 7) {
  20611. constantCache.set(node, 0);
  20612. return 0;
  20613. }
  20614. }
  20615. context.removeHelper(OPEN_BLOCK);
  20616. context.removeHelper(
  20617. getVNodeBlockHelper(context.inSSR, codegenNode.isComponent)
  20618. );
  20619. codegenNode.isBlock = false;
  20620. context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
  20621. }
  20622. constantCache.set(node, returnType2);
  20623. return returnType2;
  20624. } else {
  20625. constantCache.set(node, 0);
  20626. return 0;
  20627. }
  20628. case 2:
  20629. case 3:
  20630. return 3;
  20631. case 9:
  20632. case 11:
  20633. case 10:
  20634. return 0;
  20635. case 5:
  20636. case 12:
  20637. return getConstantType(node.content, context);
  20638. case 4:
  20639. return node.constType;
  20640. case 8:
  20641. let returnType = 3;
  20642. for (let i = 0; i < node.children.length; i++) {
  20643. const child = node.children[i];
  20644. if (isString$1(child) || isSymbol$1(child)) {
  20645. continue;
  20646. }
  20647. const childType = getConstantType(child, context);
  20648. if (childType === 0) {
  20649. return 0;
  20650. } else if (childType < returnType) {
  20651. returnType = childType;
  20652. }
  20653. }
  20654. return returnType;
  20655. case 20:
  20656. return 2;
  20657. default:
  20658. return 0;
  20659. }
  20660. }
  20661. const allowHoistedHelperSet = /* @__PURE__ */ new Set([
  20662. NORMALIZE_CLASS,
  20663. NORMALIZE_STYLE,
  20664. NORMALIZE_PROPS,
  20665. GUARD_REACTIVE_PROPS
  20666. ]);
  20667. function getConstantTypeOfHelperCall(value, context) {
  20668. if (value.type === 14 && !isString$1(value.callee) && allowHoistedHelperSet.has(value.callee)) {
  20669. const arg = value.arguments[0];
  20670. if (arg.type === 4) {
  20671. return getConstantType(arg, context);
  20672. } else if (arg.type === 14) {
  20673. return getConstantTypeOfHelperCall(arg, context);
  20674. }
  20675. }
  20676. return 0;
  20677. }
  20678. function getGeneratedPropsConstantType(node, context) {
  20679. let returnType = 3;
  20680. const props = getNodeProps(node);
  20681. if (props && props.type === 15) {
  20682. const { properties } = props;
  20683. for (let i = 0; i < properties.length; i++) {
  20684. const { key, value } = properties[i];
  20685. const keyType = getConstantType(key, context);
  20686. if (keyType === 0) {
  20687. return keyType;
  20688. }
  20689. if (keyType < returnType) {
  20690. returnType = keyType;
  20691. }
  20692. let valueType;
  20693. if (value.type === 4) {
  20694. valueType = getConstantType(value, context);
  20695. } else if (value.type === 14) {
  20696. valueType = getConstantTypeOfHelperCall(value, context);
  20697. } else {
  20698. valueType = 0;
  20699. }
  20700. if (valueType === 0) {
  20701. return valueType;
  20702. }
  20703. if (valueType < returnType) {
  20704. returnType = valueType;
  20705. }
  20706. }
  20707. }
  20708. return returnType;
  20709. }
  20710. function getNodeProps(node) {
  20711. const codegenNode = node.codegenNode;
  20712. if (codegenNode.type === 13) {
  20713. return codegenNode.props;
  20714. }
  20715. }
  20716. function createTransformContext(root, {
  20717. filename = "",
  20718. prefixIdentifiers = false,
  20719. hoistStatic = false,
  20720. hmr = false,
  20721. cacheHandlers = false,
  20722. nodeTransforms = [],
  20723. directiveTransforms = {},
  20724. transformHoist = null,
  20725. isBuiltInComponent = NOOP,
  20726. isCustomElement = NOOP,
  20727. expressionPlugins = [],
  20728. scopeId = null,
  20729. slotted = true,
  20730. ssr = false,
  20731. inSSR = false,
  20732. ssrCssVars = ``,
  20733. bindingMetadata = EMPTY_OBJ,
  20734. inline = false,
  20735. isTS = false,
  20736. onError = defaultOnError,
  20737. onWarn = defaultOnWarn,
  20738. compatConfig
  20739. }) {
  20740. const nameMatch = filename.replace(/\?.*$/, "").match(/([^/\\]+)\.\w+$/);
  20741. const context = {
  20742. // options
  20743. filename,
  20744. selfName: nameMatch && capitalize(camelize(nameMatch[1])),
  20745. prefixIdentifiers,
  20746. hoistStatic,
  20747. hmr,
  20748. cacheHandlers,
  20749. nodeTransforms,
  20750. directiveTransforms,
  20751. transformHoist,
  20752. isBuiltInComponent,
  20753. isCustomElement,
  20754. expressionPlugins,
  20755. scopeId,
  20756. slotted,
  20757. ssr,
  20758. inSSR,
  20759. ssrCssVars,
  20760. bindingMetadata,
  20761. inline,
  20762. isTS,
  20763. onError,
  20764. onWarn,
  20765. compatConfig,
  20766. // state
  20767. root,
  20768. helpers: /* @__PURE__ */ new Map(),
  20769. components: /* @__PURE__ */ new Set(),
  20770. directives: /* @__PURE__ */ new Set(),
  20771. hoists: [],
  20772. imports: [],
  20773. cached: [],
  20774. constantCache: /* @__PURE__ */ new WeakMap(),
  20775. vForMemoKeyedNodes: /* @__PURE__ */ new WeakSet(),
  20776. temps: 0,
  20777. identifiers: /* @__PURE__ */ Object.create(null),
  20778. scopes: {
  20779. vFor: 0,
  20780. vSlot: 0,
  20781. vPre: 0,
  20782. vOnce: 0
  20783. },
  20784. parent: null,
  20785. grandParent: null,
  20786. currentNode: root,
  20787. childIndex: 0,
  20788. inVOnce: false,
  20789. // methods
  20790. helper(name) {
  20791. const count = context.helpers.get(name) || 0;
  20792. context.helpers.set(name, count + 1);
  20793. return name;
  20794. },
  20795. removeHelper(name) {
  20796. const count = context.helpers.get(name);
  20797. if (count) {
  20798. const currentCount = count - 1;
  20799. if (!currentCount) {
  20800. context.helpers.delete(name);
  20801. } else {
  20802. context.helpers.set(name, currentCount);
  20803. }
  20804. }
  20805. },
  20806. helperString(name) {
  20807. return `_${helperNameMap[context.helper(name)]}`;
  20808. },
  20809. replaceNode(node) {
  20810. {
  20811. if (!context.currentNode) {
  20812. throw new Error(`Node being replaced is already removed.`);
  20813. }
  20814. if (!context.parent) {
  20815. throw new Error(`Cannot replace root node.`);
  20816. }
  20817. }
  20818. context.parent.children[context.childIndex] = context.currentNode = node;
  20819. },
  20820. removeNode(node) {
  20821. if (!context.parent) {
  20822. throw new Error(`Cannot remove root node.`);
  20823. }
  20824. const list = context.parent.children;
  20825. const removalIndex = node ? list.indexOf(node) : context.currentNode ? context.childIndex : -1;
  20826. if (removalIndex < 0) {
  20827. throw new Error(`node being removed is not a child of current parent`);
  20828. }
  20829. if (!node || node === context.currentNode) {
  20830. context.currentNode = null;
  20831. context.onNodeRemoved();
  20832. } else {
  20833. if (context.childIndex > removalIndex) {
  20834. context.childIndex--;
  20835. context.onNodeRemoved();
  20836. }
  20837. }
  20838. context.parent.children.splice(removalIndex, 1);
  20839. },
  20840. onNodeRemoved: NOOP,
  20841. addIdentifiers(exp) {
  20842. {
  20843. if (isString$1(exp)) {
  20844. addId(exp);
  20845. } else if (exp.identifiers) {
  20846. exp.identifiers.forEach(addId);
  20847. } else if (exp.type === 4) {
  20848. addId(exp.content);
  20849. }
  20850. }
  20851. },
  20852. removeIdentifiers(exp) {
  20853. {
  20854. if (isString$1(exp)) {
  20855. removeId(exp);
  20856. } else if (exp.identifiers) {
  20857. exp.identifiers.forEach(removeId);
  20858. } else if (exp.type === 4) {
  20859. removeId(exp.content);
  20860. }
  20861. }
  20862. },
  20863. hoist(exp) {
  20864. if (isString$1(exp)) exp = createSimpleExpression(exp);
  20865. context.hoists.push(exp);
  20866. const identifier = createSimpleExpression(
  20867. `_hoisted_${context.hoists.length}`,
  20868. false,
  20869. exp.loc,
  20870. 2
  20871. );
  20872. identifier.hoisted = exp;
  20873. return identifier;
  20874. },
  20875. cache(exp, isVNode = false, inVOnce = false) {
  20876. const cacheExp = createCacheExpression(
  20877. context.cached.length,
  20878. exp,
  20879. isVNode,
  20880. inVOnce
  20881. );
  20882. context.cached.push(cacheExp);
  20883. return cacheExp;
  20884. }
  20885. };
  20886. function addId(id) {
  20887. const { identifiers } = context;
  20888. if (identifiers[id] === void 0) {
  20889. identifiers[id] = 0;
  20890. }
  20891. identifiers[id]++;
  20892. }
  20893. function removeId(id) {
  20894. context.identifiers[id]--;
  20895. }
  20896. return context;
  20897. }
  20898. function transform(root, options) {
  20899. const context = createTransformContext(root, options);
  20900. traverseNode(root, context);
  20901. if (options.hoistStatic) {
  20902. cacheStatic(root, context);
  20903. }
  20904. if (!options.ssr) {
  20905. createRootCodegen(root, context);
  20906. }
  20907. root.helpers = /* @__PURE__ */ new Set([...context.helpers.keys()]);
  20908. root.components = [...context.components];
  20909. root.directives = [...context.directives];
  20910. root.imports = context.imports;
  20911. root.hoists = context.hoists;
  20912. root.temps = context.temps;
  20913. root.cached = context.cached;
  20914. root.transformed = true;
  20915. }
  20916. function createRootCodegen(root, context) {
  20917. const { helper } = context;
  20918. const { children } = root;
  20919. if (children.length === 1) {
  20920. const singleElementRootChild = getSingleElementRoot(root);
  20921. if (singleElementRootChild && singleElementRootChild.codegenNode) {
  20922. const codegenNode = singleElementRootChild.codegenNode;
  20923. if (codegenNode.type === 13) {
  20924. convertToBlock(codegenNode, context);
  20925. }
  20926. root.codegenNode = codegenNode;
  20927. } else {
  20928. root.codegenNode = children[0];
  20929. }
  20930. } else if (children.length > 1) {
  20931. let patchFlag = 64;
  20932. if (children.filter((c) => c.type !== 3).length === 1) {
  20933. patchFlag |= 2048;
  20934. }
  20935. root.codegenNode = createVNodeCall(
  20936. context,
  20937. helper(FRAGMENT),
  20938. void 0,
  20939. root.children,
  20940. patchFlag,
  20941. void 0,
  20942. void 0,
  20943. true,
  20944. void 0,
  20945. false
  20946. );
  20947. } else ;
  20948. }
  20949. function traverseChildren(parent, context) {
  20950. let i = 0;
  20951. const nodeRemoved = () => {
  20952. i--;
  20953. };
  20954. for (; i < parent.children.length; i++) {
  20955. const child = parent.children[i];
  20956. if (isString$1(child)) continue;
  20957. context.grandParent = context.parent;
  20958. context.parent = parent;
  20959. context.childIndex = i;
  20960. context.onNodeRemoved = nodeRemoved;
  20961. traverseNode(child, context);
  20962. }
  20963. }
  20964. function traverseNode(node, context) {
  20965. context.currentNode = node;
  20966. const { nodeTransforms } = context;
  20967. const exitFns = [];
  20968. for (let i2 = 0; i2 < nodeTransforms.length; i2++) {
  20969. const onExit = nodeTransforms[i2](node, context);
  20970. if (onExit) {
  20971. if (isArray$3(onExit)) {
  20972. exitFns.push(...onExit);
  20973. } else {
  20974. exitFns.push(onExit);
  20975. }
  20976. }
  20977. if (!context.currentNode) {
  20978. return;
  20979. } else {
  20980. node = context.currentNode;
  20981. }
  20982. }
  20983. switch (node.type) {
  20984. case 3:
  20985. if (!context.ssr) {
  20986. context.helper(CREATE_COMMENT);
  20987. }
  20988. break;
  20989. case 5:
  20990. if (!context.ssr) {
  20991. context.helper(TO_DISPLAY_STRING);
  20992. }
  20993. break;
  20994. // for container types, further traverse downwards
  20995. case 9:
  20996. for (let i2 = 0; i2 < node.branches.length; i2++) {
  20997. traverseNode(node.branches[i2], context);
  20998. }
  20999. break;
  21000. case 10:
  21001. case 11:
  21002. case 1:
  21003. case 0:
  21004. traverseChildren(node, context);
  21005. break;
  21006. }
  21007. context.currentNode = node;
  21008. let i = exitFns.length;
  21009. while (i--) {
  21010. exitFns[i]();
  21011. }
  21012. }
  21013. function createStructuralDirectiveTransform(name, fn) {
  21014. const matches = isString$1(name) ? (n) => n === name : (n) => name.test(n);
  21015. return (node, context) => {
  21016. if (node.type === 1) {
  21017. const { props } = node;
  21018. if (node.tagType === 3 && props.some(isVSlot)) {
  21019. return;
  21020. }
  21021. const exitFns = [];
  21022. for (let i = 0; i < props.length; i++) {
  21023. const prop = props[i];
  21024. if (prop.type === 7 && matches(prop.name)) {
  21025. props.splice(i, 1);
  21026. i--;
  21027. const onExit = fn(node, prop, context);
  21028. if (onExit) exitFns.push(onExit);
  21029. }
  21030. }
  21031. return exitFns;
  21032. }
  21033. };
  21034. }
  21035. var sourceMap$1 = {};
  21036. var sourceMapGenerator$1 = {};
  21037. var base64Vlq$1 = {};
  21038. var base64$1 = {};
  21039. /* -*- Mode: js; js-indent-level: 2; -*- */
  21040. var hasRequiredBase64$1;
  21041. function requireBase64$1 () {
  21042. if (hasRequiredBase64$1) return base64$1;
  21043. hasRequiredBase64$1 = 1;
  21044. /*
  21045. * Copyright 2011 Mozilla Foundation and contributors
  21046. * Licensed under the New BSD license. See LICENSE or:
  21047. * http://opensource.org/licenses/BSD-3-Clause
  21048. */
  21049. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  21050. /**
  21051. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  21052. */
  21053. base64$1.encode = function (number) {
  21054. if (0 <= number && number < intToCharMap.length) {
  21055. return intToCharMap[number];
  21056. }
  21057. throw new TypeError("Must be between 0 and 63: " + number);
  21058. };
  21059. /**
  21060. * Decode a single base 64 character code digit to an integer. Returns -1 on
  21061. * failure.
  21062. */
  21063. base64$1.decode = function (charCode) {
  21064. var bigA = 65; // 'A'
  21065. var bigZ = 90; // 'Z'
  21066. var littleA = 97; // 'a'
  21067. var littleZ = 122; // 'z'
  21068. var zero = 48; // '0'
  21069. var nine = 57; // '9'
  21070. var plus = 43; // '+'
  21071. var slash = 47; // '/'
  21072. var littleOffset = 26;
  21073. var numberOffset = 52;
  21074. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  21075. if (bigA <= charCode && charCode <= bigZ) {
  21076. return (charCode - bigA);
  21077. }
  21078. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  21079. if (littleA <= charCode && charCode <= littleZ) {
  21080. return (charCode - littleA + littleOffset);
  21081. }
  21082. // 52 - 61: 0123456789
  21083. if (zero <= charCode && charCode <= nine) {
  21084. return (charCode - zero + numberOffset);
  21085. }
  21086. // 62: +
  21087. if (charCode == plus) {
  21088. return 62;
  21089. }
  21090. // 63: /
  21091. if (charCode == slash) {
  21092. return 63;
  21093. }
  21094. // Invalid base64 digit.
  21095. return -1;
  21096. };
  21097. return base64$1;
  21098. }
  21099. /* -*- Mode: js; js-indent-level: 2; -*- */
  21100. var hasRequiredBase64Vlq$1;
  21101. function requireBase64Vlq$1 () {
  21102. if (hasRequiredBase64Vlq$1) return base64Vlq$1;
  21103. hasRequiredBase64Vlq$1 = 1;
  21104. /*
  21105. * Copyright 2011 Mozilla Foundation and contributors
  21106. * Licensed under the New BSD license. See LICENSE or:
  21107. * http://opensource.org/licenses/BSD-3-Clause
  21108. *
  21109. * Based on the Base 64 VLQ implementation in Closure Compiler:
  21110. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  21111. *
  21112. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  21113. * Redistribution and use in source and binary forms, with or without
  21114. * modification, are permitted provided that the following conditions are
  21115. * met:
  21116. *
  21117. * * Redistributions of source code must retain the above copyright
  21118. * notice, this list of conditions and the following disclaimer.
  21119. * * Redistributions in binary form must reproduce the above
  21120. * copyright notice, this list of conditions and the following
  21121. * disclaimer in the documentation and/or other materials provided
  21122. * with the distribution.
  21123. * * Neither the name of Google Inc. nor the names of its
  21124. * contributors may be used to endorse or promote products derived
  21125. * from this software without specific prior written permission.
  21126. *
  21127. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21128. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21129. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21130. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  21131. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  21132. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  21133. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  21134. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  21135. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  21136. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  21137. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  21138. */
  21139. var base64 = /*@__PURE__*/ requireBase64$1();
  21140. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  21141. // length quantities we use in the source map spec, the first bit is the sign,
  21142. // the next four bits are the actual value, and the 6th bit is the
  21143. // continuation bit. The continuation bit tells us whether there are more
  21144. // digits in this value following this digit.
  21145. //
  21146. // Continuation
  21147. // | Sign
  21148. // | |
  21149. // V V
  21150. // 101011
  21151. var VLQ_BASE_SHIFT = 5;
  21152. // binary: 100000
  21153. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  21154. // binary: 011111
  21155. var VLQ_BASE_MASK = VLQ_BASE - 1;
  21156. // binary: 100000
  21157. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  21158. /**
  21159. * Converts from a two-complement value to a value where the sign bit is
  21160. * placed in the least significant bit. For example, as decimals:
  21161. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  21162. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  21163. */
  21164. function toVLQSigned(aValue) {
  21165. return aValue < 0
  21166. ? ((-aValue) << 1) + 1
  21167. : (aValue << 1) + 0;
  21168. }
  21169. /**
  21170. * Converts to a two-complement value from a value where the sign bit is
  21171. * placed in the least significant bit. For example, as decimals:
  21172. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  21173. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  21174. */
  21175. function fromVLQSigned(aValue) {
  21176. var isNegative = (aValue & 1) === 1;
  21177. var shifted = aValue >> 1;
  21178. return isNegative
  21179. ? -shifted
  21180. : shifted;
  21181. }
  21182. /**
  21183. * Returns the base 64 VLQ encoded value.
  21184. */
  21185. base64Vlq$1.encode = function base64VLQ_encode(aValue) {
  21186. var encoded = "";
  21187. var digit;
  21188. var vlq = toVLQSigned(aValue);
  21189. do {
  21190. digit = vlq & VLQ_BASE_MASK;
  21191. vlq >>>= VLQ_BASE_SHIFT;
  21192. if (vlq > 0) {
  21193. // There are still more digits in this value, so we must make sure the
  21194. // continuation bit is marked.
  21195. digit |= VLQ_CONTINUATION_BIT;
  21196. }
  21197. encoded += base64.encode(digit);
  21198. } while (vlq > 0);
  21199. return encoded;
  21200. };
  21201. /**
  21202. * Decodes the next base 64 VLQ value from the given string and returns the
  21203. * value and the rest of the string via the out parameter.
  21204. */
  21205. base64Vlq$1.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  21206. var strLen = aStr.length;
  21207. var result = 0;
  21208. var shift = 0;
  21209. var continuation, digit;
  21210. do {
  21211. if (aIndex >= strLen) {
  21212. throw new Error("Expected more digits in base 64 VLQ value.");
  21213. }
  21214. digit = base64.decode(aStr.charCodeAt(aIndex++));
  21215. if (digit === -1) {
  21216. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  21217. }
  21218. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  21219. digit &= VLQ_BASE_MASK;
  21220. result = result + (digit << shift);
  21221. shift += VLQ_BASE_SHIFT;
  21222. } while (continuation);
  21223. aOutParam.value = fromVLQSigned(result);
  21224. aOutParam.rest = aIndex;
  21225. };
  21226. return base64Vlq$1;
  21227. }
  21228. var util$2 = {};
  21229. /* -*- Mode: js; js-indent-level: 2; -*- */
  21230. var hasRequiredUtil$2;
  21231. function requireUtil$2 () {
  21232. if (hasRequiredUtil$2) return util$2;
  21233. hasRequiredUtil$2 = 1;
  21234. (function (exports) {
  21235. /*
  21236. * Copyright 2011 Mozilla Foundation and contributors
  21237. * Licensed under the New BSD license. See LICENSE or:
  21238. * http://opensource.org/licenses/BSD-3-Clause
  21239. */
  21240. /**
  21241. * This is a helper function for getting values from parameter/options
  21242. * objects.
  21243. *
  21244. * @param args The object we are extracting values from
  21245. * @param name The name of the property we are getting.
  21246. * @param defaultValue An optional value to return if the property is missing
  21247. * from the object. If this is not specified and the property is missing, an
  21248. * error will be thrown.
  21249. */
  21250. function getArg(aArgs, aName, aDefaultValue) {
  21251. if (aName in aArgs) {
  21252. return aArgs[aName];
  21253. } else if (arguments.length === 3) {
  21254. return aDefaultValue;
  21255. } else {
  21256. throw new Error('"' + aName + '" is a required argument.');
  21257. }
  21258. }
  21259. exports.getArg = getArg;
  21260. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  21261. var dataUrlRegexp = /^data:.+\,.+$/;
  21262. function urlParse(aUrl) {
  21263. var match = aUrl.match(urlRegexp);
  21264. if (!match) {
  21265. return null;
  21266. }
  21267. return {
  21268. scheme: match[1],
  21269. auth: match[2],
  21270. host: match[3],
  21271. port: match[4],
  21272. path: match[5]
  21273. };
  21274. }
  21275. exports.urlParse = urlParse;
  21276. function urlGenerate(aParsedUrl) {
  21277. var url = '';
  21278. if (aParsedUrl.scheme) {
  21279. url += aParsedUrl.scheme + ':';
  21280. }
  21281. url += '//';
  21282. if (aParsedUrl.auth) {
  21283. url += aParsedUrl.auth + '@';
  21284. }
  21285. if (aParsedUrl.host) {
  21286. url += aParsedUrl.host;
  21287. }
  21288. if (aParsedUrl.port) {
  21289. url += ":" + aParsedUrl.port;
  21290. }
  21291. if (aParsedUrl.path) {
  21292. url += aParsedUrl.path;
  21293. }
  21294. return url;
  21295. }
  21296. exports.urlGenerate = urlGenerate;
  21297. var MAX_CACHED_INPUTS = 32;
  21298. /**
  21299. * Takes some function `f(input) -> result` and returns a memoized version of
  21300. * `f`.
  21301. *
  21302. * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The
  21303. * memoization is a dumb-simple, linear least-recently-used cache.
  21304. */
  21305. function lruMemoize(f) {
  21306. var cache = [];
  21307. return function(input) {
  21308. for (var i = 0; i < cache.length; i++) {
  21309. if (cache[i].input === input) {
  21310. var temp = cache[0];
  21311. cache[0] = cache[i];
  21312. cache[i] = temp;
  21313. return cache[0].result;
  21314. }
  21315. }
  21316. var result = f(input);
  21317. cache.unshift({
  21318. input,
  21319. result,
  21320. });
  21321. if (cache.length > MAX_CACHED_INPUTS) {
  21322. cache.pop();
  21323. }
  21324. return result;
  21325. };
  21326. }
  21327. /**
  21328. * Normalizes a path, or the path portion of a URL:
  21329. *
  21330. * - Replaces consecutive slashes with one slash.
  21331. * - Removes unnecessary '.' parts.
  21332. * - Removes unnecessary '<dir>/..' parts.
  21333. *
  21334. * Based on code in the Node.js 'path' core module.
  21335. *
  21336. * @param aPath The path or url to normalize.
  21337. */
  21338. var normalize = lruMemoize(function normalize(aPath) {
  21339. var path = aPath;
  21340. var url = urlParse(aPath);
  21341. if (url) {
  21342. if (!url.path) {
  21343. return aPath;
  21344. }
  21345. path = url.path;
  21346. }
  21347. var isAbsolute = exports.isAbsolute(path);
  21348. // Split the path into parts between `/` characters. This is much faster than
  21349. // using `.split(/\/+/g)`.
  21350. var parts = [];
  21351. var start = 0;
  21352. var i = 0;
  21353. while (true) {
  21354. start = i;
  21355. i = path.indexOf("/", start);
  21356. if (i === -1) {
  21357. parts.push(path.slice(start));
  21358. break;
  21359. } else {
  21360. parts.push(path.slice(start, i));
  21361. while (i < path.length && path[i] === "/") {
  21362. i++;
  21363. }
  21364. }
  21365. }
  21366. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  21367. part = parts[i];
  21368. if (part === '.') {
  21369. parts.splice(i, 1);
  21370. } else if (part === '..') {
  21371. up++;
  21372. } else if (up > 0) {
  21373. if (part === '') {
  21374. // The first part is blank if the path is absolute. Trying to go
  21375. // above the root is a no-op. Therefore we can remove all '..' parts
  21376. // directly after the root.
  21377. parts.splice(i + 1, up);
  21378. up = 0;
  21379. } else {
  21380. parts.splice(i, 2);
  21381. up--;
  21382. }
  21383. }
  21384. }
  21385. path = parts.join('/');
  21386. if (path === '') {
  21387. path = isAbsolute ? '/' : '.';
  21388. }
  21389. if (url) {
  21390. url.path = path;
  21391. return urlGenerate(url);
  21392. }
  21393. return path;
  21394. });
  21395. exports.normalize = normalize;
  21396. /**
  21397. * Joins two paths/URLs.
  21398. *
  21399. * @param aRoot The root path or URL.
  21400. * @param aPath The path or URL to be joined with the root.
  21401. *
  21402. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  21403. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  21404. * first.
  21405. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  21406. * is updated with the result and aRoot is returned. Otherwise the result
  21407. * is returned.
  21408. * - If aPath is absolute, the result is aPath.
  21409. * - Otherwise the two paths are joined with a slash.
  21410. * - Joining for example 'http://' and 'www.example.com' is also supported.
  21411. */
  21412. function join(aRoot, aPath) {
  21413. if (aRoot === "") {
  21414. aRoot = ".";
  21415. }
  21416. if (aPath === "") {
  21417. aPath = ".";
  21418. }
  21419. var aPathUrl = urlParse(aPath);
  21420. var aRootUrl = urlParse(aRoot);
  21421. if (aRootUrl) {
  21422. aRoot = aRootUrl.path || '/';
  21423. }
  21424. // `join(foo, '//www.example.org')`
  21425. if (aPathUrl && !aPathUrl.scheme) {
  21426. if (aRootUrl) {
  21427. aPathUrl.scheme = aRootUrl.scheme;
  21428. }
  21429. return urlGenerate(aPathUrl);
  21430. }
  21431. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  21432. return aPath;
  21433. }
  21434. // `join('http://', 'www.example.com')`
  21435. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  21436. aRootUrl.host = aPath;
  21437. return urlGenerate(aRootUrl);
  21438. }
  21439. var joined = aPath.charAt(0) === '/'
  21440. ? aPath
  21441. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  21442. if (aRootUrl) {
  21443. aRootUrl.path = joined;
  21444. return urlGenerate(aRootUrl);
  21445. }
  21446. return joined;
  21447. }
  21448. exports.join = join;
  21449. exports.isAbsolute = function (aPath) {
  21450. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  21451. };
  21452. /**
  21453. * Make a path relative to a URL or another path.
  21454. *
  21455. * @param aRoot The root path or URL.
  21456. * @param aPath The path or URL to be made relative to aRoot.
  21457. */
  21458. function relative(aRoot, aPath) {
  21459. if (aRoot === "") {
  21460. aRoot = ".";
  21461. }
  21462. aRoot = aRoot.replace(/\/$/, '');
  21463. // It is possible for the path to be above the root. In this case, simply
  21464. // checking whether the root is a prefix of the path won't work. Instead, we
  21465. // need to remove components from the root one by one, until either we find
  21466. // a prefix that fits, or we run out of components to remove.
  21467. var level = 0;
  21468. while (aPath.indexOf(aRoot + '/') !== 0) {
  21469. var index = aRoot.lastIndexOf("/");
  21470. if (index < 0) {
  21471. return aPath;
  21472. }
  21473. // If the only part of the root that is left is the scheme (i.e. http://,
  21474. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  21475. // have exhausted all components, so the path is not relative to the root.
  21476. aRoot = aRoot.slice(0, index);
  21477. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  21478. return aPath;
  21479. }
  21480. ++level;
  21481. }
  21482. // Make sure we add a "../" for each component we removed from the root.
  21483. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  21484. }
  21485. exports.relative = relative;
  21486. var supportsNullProto = (function () {
  21487. var obj = Object.create(null);
  21488. return !('__proto__' in obj);
  21489. }());
  21490. function identity (s) {
  21491. return s;
  21492. }
  21493. /**
  21494. * Because behavior goes wacky when you set `__proto__` on objects, we
  21495. * have to prefix all the strings in our set with an arbitrary character.
  21496. *
  21497. * See https://github.com/mozilla/source-map/pull/31 and
  21498. * https://github.com/mozilla/source-map/issues/30
  21499. *
  21500. * @param String aStr
  21501. */
  21502. function toSetString(aStr) {
  21503. if (isProtoString(aStr)) {
  21504. return '$' + aStr;
  21505. }
  21506. return aStr;
  21507. }
  21508. exports.toSetString = supportsNullProto ? identity : toSetString;
  21509. function fromSetString(aStr) {
  21510. if (isProtoString(aStr)) {
  21511. return aStr.slice(1);
  21512. }
  21513. return aStr;
  21514. }
  21515. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  21516. function isProtoString(s) {
  21517. if (!s) {
  21518. return false;
  21519. }
  21520. var length = s.length;
  21521. if (length < 9 /* "__proto__".length */) {
  21522. return false;
  21523. }
  21524. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  21525. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  21526. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  21527. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  21528. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  21529. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  21530. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  21531. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  21532. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  21533. return false;
  21534. }
  21535. for (var i = length - 10; i >= 0; i--) {
  21536. if (s.charCodeAt(i) !== 36 /* '$' */) {
  21537. return false;
  21538. }
  21539. }
  21540. return true;
  21541. }
  21542. /**
  21543. * Comparator between two mappings where the original positions are compared.
  21544. *
  21545. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  21546. * mappings with the same original source/line/column, but different generated
  21547. * line and column the same. Useful when searching for a mapping with a
  21548. * stubbed out mapping.
  21549. */
  21550. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  21551. var cmp = strcmp(mappingA.source, mappingB.source);
  21552. if (cmp !== 0) {
  21553. return cmp;
  21554. }
  21555. cmp = mappingA.originalLine - mappingB.originalLine;
  21556. if (cmp !== 0) {
  21557. return cmp;
  21558. }
  21559. cmp = mappingA.originalColumn - mappingB.originalColumn;
  21560. if (cmp !== 0 || onlyCompareOriginal) {
  21561. return cmp;
  21562. }
  21563. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  21564. if (cmp !== 0) {
  21565. return cmp;
  21566. }
  21567. cmp = mappingA.generatedLine - mappingB.generatedLine;
  21568. if (cmp !== 0) {
  21569. return cmp;
  21570. }
  21571. return strcmp(mappingA.name, mappingB.name);
  21572. }
  21573. exports.compareByOriginalPositions = compareByOriginalPositions;
  21574. function compareByOriginalPositionsNoSource(mappingA, mappingB, onlyCompareOriginal) {
  21575. var cmp;
  21576. cmp = mappingA.originalLine - mappingB.originalLine;
  21577. if (cmp !== 0) {
  21578. return cmp;
  21579. }
  21580. cmp = mappingA.originalColumn - mappingB.originalColumn;
  21581. if (cmp !== 0 || onlyCompareOriginal) {
  21582. return cmp;
  21583. }
  21584. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  21585. if (cmp !== 0) {
  21586. return cmp;
  21587. }
  21588. cmp = mappingA.generatedLine - mappingB.generatedLine;
  21589. if (cmp !== 0) {
  21590. return cmp;
  21591. }
  21592. return strcmp(mappingA.name, mappingB.name);
  21593. }
  21594. exports.compareByOriginalPositionsNoSource = compareByOriginalPositionsNoSource;
  21595. /**
  21596. * Comparator between two mappings with deflated source and name indices where
  21597. * the generated positions are compared.
  21598. *
  21599. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  21600. * mappings with the same generated line and column, but different
  21601. * source/name/original line and column the same. Useful when searching for a
  21602. * mapping with a stubbed out mapping.
  21603. */
  21604. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  21605. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  21606. if (cmp !== 0) {
  21607. return cmp;
  21608. }
  21609. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  21610. if (cmp !== 0 || onlyCompareGenerated) {
  21611. return cmp;
  21612. }
  21613. cmp = strcmp(mappingA.source, mappingB.source);
  21614. if (cmp !== 0) {
  21615. return cmp;
  21616. }
  21617. cmp = mappingA.originalLine - mappingB.originalLine;
  21618. if (cmp !== 0) {
  21619. return cmp;
  21620. }
  21621. cmp = mappingA.originalColumn - mappingB.originalColumn;
  21622. if (cmp !== 0) {
  21623. return cmp;
  21624. }
  21625. return strcmp(mappingA.name, mappingB.name);
  21626. }
  21627. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  21628. function compareByGeneratedPositionsDeflatedNoLine(mappingA, mappingB, onlyCompareGenerated) {
  21629. var cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  21630. if (cmp !== 0 || onlyCompareGenerated) {
  21631. return cmp;
  21632. }
  21633. cmp = strcmp(mappingA.source, mappingB.source);
  21634. if (cmp !== 0) {
  21635. return cmp;
  21636. }
  21637. cmp = mappingA.originalLine - mappingB.originalLine;
  21638. if (cmp !== 0) {
  21639. return cmp;
  21640. }
  21641. cmp = mappingA.originalColumn - mappingB.originalColumn;
  21642. if (cmp !== 0) {
  21643. return cmp;
  21644. }
  21645. return strcmp(mappingA.name, mappingB.name);
  21646. }
  21647. exports.compareByGeneratedPositionsDeflatedNoLine = compareByGeneratedPositionsDeflatedNoLine;
  21648. function strcmp(aStr1, aStr2) {
  21649. if (aStr1 === aStr2) {
  21650. return 0;
  21651. }
  21652. if (aStr1 === null) {
  21653. return 1; // aStr2 !== null
  21654. }
  21655. if (aStr2 === null) {
  21656. return -1; // aStr1 !== null
  21657. }
  21658. if (aStr1 > aStr2) {
  21659. return 1;
  21660. }
  21661. return -1;
  21662. }
  21663. /**
  21664. * Comparator between two mappings with inflated source and name strings where
  21665. * the generated positions are compared.
  21666. */
  21667. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  21668. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  21669. if (cmp !== 0) {
  21670. return cmp;
  21671. }
  21672. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  21673. if (cmp !== 0) {
  21674. return cmp;
  21675. }
  21676. cmp = strcmp(mappingA.source, mappingB.source);
  21677. if (cmp !== 0) {
  21678. return cmp;
  21679. }
  21680. cmp = mappingA.originalLine - mappingB.originalLine;
  21681. if (cmp !== 0) {
  21682. return cmp;
  21683. }
  21684. cmp = mappingA.originalColumn - mappingB.originalColumn;
  21685. if (cmp !== 0) {
  21686. return cmp;
  21687. }
  21688. return strcmp(mappingA.name, mappingB.name);
  21689. }
  21690. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  21691. /**
  21692. * Strip any JSON XSSI avoidance prefix from the string (as documented
  21693. * in the source maps specification), and then parse the string as
  21694. * JSON.
  21695. */
  21696. function parseSourceMapInput(str) {
  21697. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  21698. }
  21699. exports.parseSourceMapInput = parseSourceMapInput;
  21700. /**
  21701. * Compute the URL of a source given the the source root, the source's
  21702. * URL, and the source map's URL.
  21703. */
  21704. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  21705. sourceURL = sourceURL || '';
  21706. if (sourceRoot) {
  21707. // This follows what Chrome does.
  21708. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  21709. sourceRoot += '/';
  21710. }
  21711. // The spec says:
  21712. // Line 4: An optional source root, useful for relocating source
  21713. // files on a server or removing repeated values in the
  21714. // “sources” entry. This value is prepended to the individual
  21715. // entries in the “source” field.
  21716. sourceURL = sourceRoot + sourceURL;
  21717. }
  21718. // Historically, SourceMapConsumer did not take the sourceMapURL as
  21719. // a parameter. This mode is still somewhat supported, which is why
  21720. // this code block is conditional. However, it's preferable to pass
  21721. // the source map URL to SourceMapConsumer, so that this function
  21722. // can implement the source URL resolution algorithm as outlined in
  21723. // the spec. This block is basically the equivalent of:
  21724. // new URL(sourceURL, sourceMapURL).toString()
  21725. // ... except it avoids using URL, which wasn't available in the
  21726. // older releases of node still supported by this library.
  21727. //
  21728. // The spec says:
  21729. // If the sources are not absolute URLs after prepending of the
  21730. // “sourceRoot”, the sources are resolved relative to the
  21731. // SourceMap (like resolving script src in a html document).
  21732. if (sourceMapURL) {
  21733. var parsed = urlParse(sourceMapURL);
  21734. if (!parsed) {
  21735. throw new Error("sourceMapURL could not be parsed");
  21736. }
  21737. if (parsed.path) {
  21738. // Strip the last path component, but keep the "/".
  21739. var index = parsed.path.lastIndexOf('/');
  21740. if (index >= 0) {
  21741. parsed.path = parsed.path.substring(0, index + 1);
  21742. }
  21743. }
  21744. sourceURL = join(urlGenerate(parsed), sourceURL);
  21745. }
  21746. return normalize(sourceURL);
  21747. }
  21748. exports.computeSourceURL = computeSourceURL;
  21749. } (util$2));
  21750. return util$2;
  21751. }
  21752. var arraySet$1 = {};
  21753. /* -*- Mode: js; js-indent-level: 2; -*- */
  21754. var hasRequiredArraySet$1;
  21755. function requireArraySet$1 () {
  21756. if (hasRequiredArraySet$1) return arraySet$1;
  21757. hasRequiredArraySet$1 = 1;
  21758. /*
  21759. * Copyright 2011 Mozilla Foundation and contributors
  21760. * Licensed under the New BSD license. See LICENSE or:
  21761. * http://opensource.org/licenses/BSD-3-Clause
  21762. */
  21763. var util = /*@__PURE__*/ requireUtil$2();
  21764. var has = Object.prototype.hasOwnProperty;
  21765. var hasNativeMap = typeof Map !== "undefined";
  21766. /**
  21767. * A data structure which is a combination of an array and a set. Adding a new
  21768. * member is O(1), testing for membership is O(1), and finding the index of an
  21769. * element is O(1). Removing elements from the set is not supported. Only
  21770. * strings are supported for membership.
  21771. */
  21772. function ArraySet() {
  21773. this._array = [];
  21774. this._set = hasNativeMap ? new Map() : Object.create(null);
  21775. }
  21776. /**
  21777. * Static method for creating ArraySet instances from an existing array.
  21778. */
  21779. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  21780. var set = new ArraySet();
  21781. for (var i = 0, len = aArray.length; i < len; i++) {
  21782. set.add(aArray[i], aAllowDuplicates);
  21783. }
  21784. return set;
  21785. };
  21786. /**
  21787. * Return how many unique items are in this ArraySet. If duplicates have been
  21788. * added, than those do not count towards the size.
  21789. *
  21790. * @returns Number
  21791. */
  21792. ArraySet.prototype.size = function ArraySet_size() {
  21793. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  21794. };
  21795. /**
  21796. * Add the given string to this set.
  21797. *
  21798. * @param String aStr
  21799. */
  21800. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  21801. var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
  21802. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  21803. var idx = this._array.length;
  21804. if (!isDuplicate || aAllowDuplicates) {
  21805. this._array.push(aStr);
  21806. }
  21807. if (!isDuplicate) {
  21808. if (hasNativeMap) {
  21809. this._set.set(aStr, idx);
  21810. } else {
  21811. this._set[sStr] = idx;
  21812. }
  21813. }
  21814. };
  21815. /**
  21816. * Is the given string a member of this set?
  21817. *
  21818. * @param String aStr
  21819. */
  21820. ArraySet.prototype.has = function ArraySet_has(aStr) {
  21821. if (hasNativeMap) {
  21822. return this._set.has(aStr);
  21823. } else {
  21824. var sStr = util.toSetString(aStr);
  21825. return has.call(this._set, sStr);
  21826. }
  21827. };
  21828. /**
  21829. * What is the index of the given string in the array?
  21830. *
  21831. * @param String aStr
  21832. */
  21833. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  21834. if (hasNativeMap) {
  21835. var idx = this._set.get(aStr);
  21836. if (idx >= 0) {
  21837. return idx;
  21838. }
  21839. } else {
  21840. var sStr = util.toSetString(aStr);
  21841. if (has.call(this._set, sStr)) {
  21842. return this._set[sStr];
  21843. }
  21844. }
  21845. throw new Error('"' + aStr + '" is not in the set.');
  21846. };
  21847. /**
  21848. * What is the element at the given index?
  21849. *
  21850. * @param Number aIdx
  21851. */
  21852. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  21853. if (aIdx >= 0 && aIdx < this._array.length) {
  21854. return this._array[aIdx];
  21855. }
  21856. throw new Error('No element indexed by ' + aIdx);
  21857. };
  21858. /**
  21859. * Returns the array representation of this set (which has the proper indices
  21860. * indicated by indexOf). Note that this is a copy of the internal array used
  21861. * for storing the members so that no one can mess with internal state.
  21862. */
  21863. ArraySet.prototype.toArray = function ArraySet_toArray() {
  21864. return this._array.slice();
  21865. };
  21866. arraySet$1.ArraySet = ArraySet;
  21867. return arraySet$1;
  21868. }
  21869. var mappingList$1 = {};
  21870. /* -*- Mode: js; js-indent-level: 2; -*- */
  21871. var hasRequiredMappingList$1;
  21872. function requireMappingList$1 () {
  21873. if (hasRequiredMappingList$1) return mappingList$1;
  21874. hasRequiredMappingList$1 = 1;
  21875. /*
  21876. * Copyright 2014 Mozilla Foundation and contributors
  21877. * Licensed under the New BSD license. See LICENSE or:
  21878. * http://opensource.org/licenses/BSD-3-Clause
  21879. */
  21880. var util = /*@__PURE__*/ requireUtil$2();
  21881. /**
  21882. * Determine whether mappingB is after mappingA with respect to generated
  21883. * position.
  21884. */
  21885. function generatedPositionAfter(mappingA, mappingB) {
  21886. // Optimized for most common case
  21887. var lineA = mappingA.generatedLine;
  21888. var lineB = mappingB.generatedLine;
  21889. var columnA = mappingA.generatedColumn;
  21890. var columnB = mappingB.generatedColumn;
  21891. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  21892. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  21893. }
  21894. /**
  21895. * A data structure to provide a sorted view of accumulated mappings in a
  21896. * performance conscious manner. It trades a neglibable overhead in general
  21897. * case for a large speedup in case of mappings being added in order.
  21898. */
  21899. function MappingList() {
  21900. this._array = [];
  21901. this._sorted = true;
  21902. // Serves as infimum
  21903. this._last = {generatedLine: -1, generatedColumn: 0};
  21904. }
  21905. /**
  21906. * Iterate through internal items. This method takes the same arguments that
  21907. * `Array.prototype.forEach` takes.
  21908. *
  21909. * NOTE: The order of the mappings is NOT guaranteed.
  21910. */
  21911. MappingList.prototype.unsortedForEach =
  21912. function MappingList_forEach(aCallback, aThisArg) {
  21913. this._array.forEach(aCallback, aThisArg);
  21914. };
  21915. /**
  21916. * Add the given source mapping.
  21917. *
  21918. * @param Object aMapping
  21919. */
  21920. MappingList.prototype.add = function MappingList_add(aMapping) {
  21921. if (generatedPositionAfter(this._last, aMapping)) {
  21922. this._last = aMapping;
  21923. this._array.push(aMapping);
  21924. } else {
  21925. this._sorted = false;
  21926. this._array.push(aMapping);
  21927. }
  21928. };
  21929. /**
  21930. * Returns the flat, sorted array of mappings. The mappings are sorted by
  21931. * generated position.
  21932. *
  21933. * WARNING: This method returns internal data without copying, for
  21934. * performance. The return value must NOT be mutated, and should be treated as
  21935. * an immutable borrow. If you want to take ownership, you must make your own
  21936. * copy.
  21937. */
  21938. MappingList.prototype.toArray = function MappingList_toArray() {
  21939. if (!this._sorted) {
  21940. this._array.sort(util.compareByGeneratedPositionsInflated);
  21941. this._sorted = true;
  21942. }
  21943. return this._array;
  21944. };
  21945. mappingList$1.MappingList = MappingList;
  21946. return mappingList$1;
  21947. }
  21948. /* -*- Mode: js; js-indent-level: 2; -*- */
  21949. var hasRequiredSourceMapGenerator$1;
  21950. function requireSourceMapGenerator$1 () {
  21951. if (hasRequiredSourceMapGenerator$1) return sourceMapGenerator$1;
  21952. hasRequiredSourceMapGenerator$1 = 1;
  21953. /*
  21954. * Copyright 2011 Mozilla Foundation and contributors
  21955. * Licensed under the New BSD license. See LICENSE or:
  21956. * http://opensource.org/licenses/BSD-3-Clause
  21957. */
  21958. var base64VLQ = /*@__PURE__*/ requireBase64Vlq$1();
  21959. var util = /*@__PURE__*/ requireUtil$2();
  21960. var ArraySet = /*@__PURE__*/ requireArraySet$1().ArraySet;
  21961. var MappingList = /*@__PURE__*/ requireMappingList$1().MappingList;
  21962. /**
  21963. * An instance of the SourceMapGenerator represents a source map which is
  21964. * being built incrementally. You may pass an object with the following
  21965. * properties:
  21966. *
  21967. * - file: The filename of the generated source.
  21968. * - sourceRoot: A root for all relative URLs in this source map.
  21969. */
  21970. function SourceMapGenerator(aArgs) {
  21971. if (!aArgs) {
  21972. aArgs = {};
  21973. }
  21974. this._file = util.getArg(aArgs, 'file', null);
  21975. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  21976. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  21977. this._ignoreInvalidMapping = util.getArg(aArgs, 'ignoreInvalidMapping', false);
  21978. this._sources = new ArraySet();
  21979. this._names = new ArraySet();
  21980. this._mappings = new MappingList();
  21981. this._sourcesContents = null;
  21982. }
  21983. SourceMapGenerator.prototype._version = 3;
  21984. /**
  21985. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  21986. *
  21987. * @param aSourceMapConsumer The SourceMap.
  21988. */
  21989. SourceMapGenerator.fromSourceMap =
  21990. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer, generatorOps) {
  21991. var sourceRoot = aSourceMapConsumer.sourceRoot;
  21992. var generator = new SourceMapGenerator(Object.assign(generatorOps || {}, {
  21993. file: aSourceMapConsumer.file,
  21994. sourceRoot: sourceRoot
  21995. }));
  21996. aSourceMapConsumer.eachMapping(function (mapping) {
  21997. var newMapping = {
  21998. generated: {
  21999. line: mapping.generatedLine,
  22000. column: mapping.generatedColumn
  22001. }
  22002. };
  22003. if (mapping.source != null) {
  22004. newMapping.source = mapping.source;
  22005. if (sourceRoot != null) {
  22006. newMapping.source = util.relative(sourceRoot, newMapping.source);
  22007. }
  22008. newMapping.original = {
  22009. line: mapping.originalLine,
  22010. column: mapping.originalColumn
  22011. };
  22012. if (mapping.name != null) {
  22013. newMapping.name = mapping.name;
  22014. }
  22015. }
  22016. generator.addMapping(newMapping);
  22017. });
  22018. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  22019. var sourceRelative = sourceFile;
  22020. if (sourceRoot !== null) {
  22021. sourceRelative = util.relative(sourceRoot, sourceFile);
  22022. }
  22023. if (!generator._sources.has(sourceRelative)) {
  22024. generator._sources.add(sourceRelative);
  22025. }
  22026. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  22027. if (content != null) {
  22028. generator.setSourceContent(sourceFile, content);
  22029. }
  22030. });
  22031. return generator;
  22032. };
  22033. /**
  22034. * Add a single mapping from original source line and column to the generated
  22035. * source's line and column for this source map being created. The mapping
  22036. * object should have the following properties:
  22037. *
  22038. * - generated: An object with the generated line and column positions.
  22039. * - original: An object with the original line and column positions.
  22040. * - source: The original source file (relative to the sourceRoot).
  22041. * - name: An optional original token name for this mapping.
  22042. */
  22043. SourceMapGenerator.prototype.addMapping =
  22044. function SourceMapGenerator_addMapping(aArgs) {
  22045. var generated = util.getArg(aArgs, 'generated');
  22046. var original = util.getArg(aArgs, 'original', null);
  22047. var source = util.getArg(aArgs, 'source', null);
  22048. var name = util.getArg(aArgs, 'name', null);
  22049. if (!this._skipValidation) {
  22050. if (this._validateMapping(generated, original, source, name) === false) {
  22051. return;
  22052. }
  22053. }
  22054. if (source != null) {
  22055. source = String(source);
  22056. if (!this._sources.has(source)) {
  22057. this._sources.add(source);
  22058. }
  22059. }
  22060. if (name != null) {
  22061. name = String(name);
  22062. if (!this._names.has(name)) {
  22063. this._names.add(name);
  22064. }
  22065. }
  22066. this._mappings.add({
  22067. generatedLine: generated.line,
  22068. generatedColumn: generated.column,
  22069. originalLine: original != null && original.line,
  22070. originalColumn: original != null && original.column,
  22071. source: source,
  22072. name: name
  22073. });
  22074. };
  22075. /**
  22076. * Set the source content for a source file.
  22077. */
  22078. SourceMapGenerator.prototype.setSourceContent =
  22079. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  22080. var source = aSourceFile;
  22081. if (this._sourceRoot != null) {
  22082. source = util.relative(this._sourceRoot, source);
  22083. }
  22084. if (aSourceContent != null) {
  22085. // Add the source content to the _sourcesContents map.
  22086. // Create a new _sourcesContents map if the property is null.
  22087. if (!this._sourcesContents) {
  22088. this._sourcesContents = Object.create(null);
  22089. }
  22090. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  22091. } else if (this._sourcesContents) {
  22092. // Remove the source file from the _sourcesContents map.
  22093. // If the _sourcesContents map is empty, set the property to null.
  22094. delete this._sourcesContents[util.toSetString(source)];
  22095. if (Object.keys(this._sourcesContents).length === 0) {
  22096. this._sourcesContents = null;
  22097. }
  22098. }
  22099. };
  22100. /**
  22101. * Applies the mappings of a sub-source-map for a specific source file to the
  22102. * source map being generated. Each mapping to the supplied source file is
  22103. * rewritten using the supplied source map. Note: The resolution for the
  22104. * resulting mappings is the minimium of this map and the supplied map.
  22105. *
  22106. * @param aSourceMapConsumer The source map to be applied.
  22107. * @param aSourceFile Optional. The filename of the source file.
  22108. * If omitted, SourceMapConsumer's file property will be used.
  22109. * @param aSourceMapPath Optional. The dirname of the path to the source map
  22110. * to be applied. If relative, it is relative to the SourceMapConsumer.
  22111. * This parameter is needed when the two source maps aren't in the same
  22112. * directory, and the source map to be applied contains relative source
  22113. * paths. If so, those relative source paths need to be rewritten
  22114. * relative to the SourceMapGenerator.
  22115. */
  22116. SourceMapGenerator.prototype.applySourceMap =
  22117. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  22118. var sourceFile = aSourceFile;
  22119. // If aSourceFile is omitted, we will use the file property of the SourceMap
  22120. if (aSourceFile == null) {
  22121. if (aSourceMapConsumer.file == null) {
  22122. throw new Error(
  22123. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  22124. 'or the source map\'s "file" property. Both were omitted.'
  22125. );
  22126. }
  22127. sourceFile = aSourceMapConsumer.file;
  22128. }
  22129. var sourceRoot = this._sourceRoot;
  22130. // Make "sourceFile" relative if an absolute Url is passed.
  22131. if (sourceRoot != null) {
  22132. sourceFile = util.relative(sourceRoot, sourceFile);
  22133. }
  22134. // Applying the SourceMap can add and remove items from the sources and
  22135. // the names array.
  22136. var newSources = new ArraySet();
  22137. var newNames = new ArraySet();
  22138. // Find mappings for the "sourceFile"
  22139. this._mappings.unsortedForEach(function (mapping) {
  22140. if (mapping.source === sourceFile && mapping.originalLine != null) {
  22141. // Check if it can be mapped by the source map, then update the mapping.
  22142. var original = aSourceMapConsumer.originalPositionFor({
  22143. line: mapping.originalLine,
  22144. column: mapping.originalColumn
  22145. });
  22146. if (original.source != null) {
  22147. // Copy mapping
  22148. mapping.source = original.source;
  22149. if (aSourceMapPath != null) {
  22150. mapping.source = util.join(aSourceMapPath, mapping.source);
  22151. }
  22152. if (sourceRoot != null) {
  22153. mapping.source = util.relative(sourceRoot, mapping.source);
  22154. }
  22155. mapping.originalLine = original.line;
  22156. mapping.originalColumn = original.column;
  22157. if (original.name != null) {
  22158. mapping.name = original.name;
  22159. }
  22160. }
  22161. }
  22162. var source = mapping.source;
  22163. if (source != null && !newSources.has(source)) {
  22164. newSources.add(source);
  22165. }
  22166. var name = mapping.name;
  22167. if (name != null && !newNames.has(name)) {
  22168. newNames.add(name);
  22169. }
  22170. }, this);
  22171. this._sources = newSources;
  22172. this._names = newNames;
  22173. // Copy sourcesContents of applied map.
  22174. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  22175. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  22176. if (content != null) {
  22177. if (aSourceMapPath != null) {
  22178. sourceFile = util.join(aSourceMapPath, sourceFile);
  22179. }
  22180. if (sourceRoot != null) {
  22181. sourceFile = util.relative(sourceRoot, sourceFile);
  22182. }
  22183. this.setSourceContent(sourceFile, content);
  22184. }
  22185. }, this);
  22186. };
  22187. /**
  22188. * A mapping can have one of the three levels of data:
  22189. *
  22190. * 1. Just the generated position.
  22191. * 2. The Generated position, original position, and original source.
  22192. * 3. Generated and original position, original source, as well as a name
  22193. * token.
  22194. *
  22195. * To maintain consistency, we validate that any new mapping being added falls
  22196. * in to one of these categories.
  22197. */
  22198. SourceMapGenerator.prototype._validateMapping =
  22199. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  22200. aName) {
  22201. // When aOriginal is truthy but has empty values for .line and .column,
  22202. // it is most likely a programmer error. In this case we throw a very
  22203. // specific error message to try to guide them the right way.
  22204. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  22205. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  22206. var message = 'original.line and original.column are not numbers -- you probably meant to omit ' +
  22207. 'the original mapping entirely and only map the generated position. If so, pass ' +
  22208. 'null for the original mapping instead of an object with empty or null values.';
  22209. if (this._ignoreInvalidMapping) {
  22210. if (typeof console !== 'undefined' && console.warn) {
  22211. console.warn(message);
  22212. }
  22213. return false;
  22214. } else {
  22215. throw new Error(message);
  22216. }
  22217. }
  22218. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  22219. && aGenerated.line > 0 && aGenerated.column >= 0
  22220. && !aOriginal && !aSource && !aName) {
  22221. // Case 1.
  22222. return;
  22223. }
  22224. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  22225. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  22226. && aGenerated.line > 0 && aGenerated.column >= 0
  22227. && aOriginal.line > 0 && aOriginal.column >= 0
  22228. && aSource) {
  22229. // Cases 2 and 3.
  22230. return;
  22231. }
  22232. else {
  22233. var message = 'Invalid mapping: ' + JSON.stringify({
  22234. generated: aGenerated,
  22235. source: aSource,
  22236. original: aOriginal,
  22237. name: aName
  22238. });
  22239. if (this._ignoreInvalidMapping) {
  22240. if (typeof console !== 'undefined' && console.warn) {
  22241. console.warn(message);
  22242. }
  22243. return false;
  22244. } else {
  22245. throw new Error(message)
  22246. }
  22247. }
  22248. };
  22249. /**
  22250. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  22251. * specified by the source map format.
  22252. */
  22253. SourceMapGenerator.prototype._serializeMappings =
  22254. function SourceMapGenerator_serializeMappings() {
  22255. var previousGeneratedColumn = 0;
  22256. var previousGeneratedLine = 1;
  22257. var previousOriginalColumn = 0;
  22258. var previousOriginalLine = 0;
  22259. var previousName = 0;
  22260. var previousSource = 0;
  22261. var result = '';
  22262. var next;
  22263. var mapping;
  22264. var nameIdx;
  22265. var sourceIdx;
  22266. var mappings = this._mappings.toArray();
  22267. for (var i = 0, len = mappings.length; i < len; i++) {
  22268. mapping = mappings[i];
  22269. next = '';
  22270. if (mapping.generatedLine !== previousGeneratedLine) {
  22271. previousGeneratedColumn = 0;
  22272. while (mapping.generatedLine !== previousGeneratedLine) {
  22273. next += ';';
  22274. previousGeneratedLine++;
  22275. }
  22276. }
  22277. else {
  22278. if (i > 0) {
  22279. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  22280. continue;
  22281. }
  22282. next += ',';
  22283. }
  22284. }
  22285. next += base64VLQ.encode(mapping.generatedColumn
  22286. - previousGeneratedColumn);
  22287. previousGeneratedColumn = mapping.generatedColumn;
  22288. if (mapping.source != null) {
  22289. sourceIdx = this._sources.indexOf(mapping.source);
  22290. next += base64VLQ.encode(sourceIdx - previousSource);
  22291. previousSource = sourceIdx;
  22292. // lines are stored 0-based in SourceMap spec version 3
  22293. next += base64VLQ.encode(mapping.originalLine - 1
  22294. - previousOriginalLine);
  22295. previousOriginalLine = mapping.originalLine - 1;
  22296. next += base64VLQ.encode(mapping.originalColumn
  22297. - previousOriginalColumn);
  22298. previousOriginalColumn = mapping.originalColumn;
  22299. if (mapping.name != null) {
  22300. nameIdx = this._names.indexOf(mapping.name);
  22301. next += base64VLQ.encode(nameIdx - previousName);
  22302. previousName = nameIdx;
  22303. }
  22304. }
  22305. result += next;
  22306. }
  22307. return result;
  22308. };
  22309. SourceMapGenerator.prototype._generateSourcesContent =
  22310. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  22311. return aSources.map(function (source) {
  22312. if (!this._sourcesContents) {
  22313. return null;
  22314. }
  22315. if (aSourceRoot != null) {
  22316. source = util.relative(aSourceRoot, source);
  22317. }
  22318. var key = util.toSetString(source);
  22319. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  22320. ? this._sourcesContents[key]
  22321. : null;
  22322. }, this);
  22323. };
  22324. /**
  22325. * Externalize the source map.
  22326. */
  22327. SourceMapGenerator.prototype.toJSON =
  22328. function SourceMapGenerator_toJSON() {
  22329. var map = {
  22330. version: this._version,
  22331. sources: this._sources.toArray(),
  22332. names: this._names.toArray(),
  22333. mappings: this._serializeMappings()
  22334. };
  22335. if (this._file != null) {
  22336. map.file = this._file;
  22337. }
  22338. if (this._sourceRoot != null) {
  22339. map.sourceRoot = this._sourceRoot;
  22340. }
  22341. if (this._sourcesContents) {
  22342. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  22343. }
  22344. return map;
  22345. };
  22346. /**
  22347. * Render the source map being generated to a string.
  22348. */
  22349. SourceMapGenerator.prototype.toString =
  22350. function SourceMapGenerator_toString() {
  22351. return JSON.stringify(this.toJSON());
  22352. };
  22353. sourceMapGenerator$1.SourceMapGenerator = SourceMapGenerator;
  22354. return sourceMapGenerator$1;
  22355. }
  22356. var sourceMapConsumer$1 = {};
  22357. var binarySearch$1 = {};
  22358. /* -*- Mode: js; js-indent-level: 2; -*- */
  22359. var hasRequiredBinarySearch$1;
  22360. function requireBinarySearch$1 () {
  22361. if (hasRequiredBinarySearch$1) return binarySearch$1;
  22362. hasRequiredBinarySearch$1 = 1;
  22363. (function (exports) {
  22364. /*
  22365. * Copyright 2011 Mozilla Foundation and contributors
  22366. * Licensed under the New BSD license. See LICENSE or:
  22367. * http://opensource.org/licenses/BSD-3-Clause
  22368. */
  22369. exports.GREATEST_LOWER_BOUND = 1;
  22370. exports.LEAST_UPPER_BOUND = 2;
  22371. /**
  22372. * Recursive implementation of binary search.
  22373. *
  22374. * @param aLow Indices here and lower do not contain the needle.
  22375. * @param aHigh Indices here and higher do not contain the needle.
  22376. * @param aNeedle The element being searched for.
  22377. * @param aHaystack The non-empty array being searched.
  22378. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  22379. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  22380. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  22381. * closest element that is smaller than or greater than the one we are
  22382. * searching for, respectively, if the exact element cannot be found.
  22383. */
  22384. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  22385. // This function terminates when one of the following is true:
  22386. //
  22387. // 1. We find the exact element we are looking for.
  22388. //
  22389. // 2. We did not find the exact element, but we can return the index of
  22390. // the next-closest element.
  22391. //
  22392. // 3. We did not find the exact element, and there is no next-closest
  22393. // element than the one we are searching for, so we return -1.
  22394. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  22395. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  22396. if (cmp === 0) {
  22397. // Found the element we are looking for.
  22398. return mid;
  22399. }
  22400. else if (cmp > 0) {
  22401. // Our needle is greater than aHaystack[mid].
  22402. if (aHigh - mid > 1) {
  22403. // The element is in the upper half.
  22404. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  22405. }
  22406. // The exact needle element was not found in this haystack. Determine if
  22407. // we are in termination case (3) or (2) and return the appropriate thing.
  22408. if (aBias == exports.LEAST_UPPER_BOUND) {
  22409. return aHigh < aHaystack.length ? aHigh : -1;
  22410. } else {
  22411. return mid;
  22412. }
  22413. }
  22414. else {
  22415. // Our needle is less than aHaystack[mid].
  22416. if (mid - aLow > 1) {
  22417. // The element is in the lower half.
  22418. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  22419. }
  22420. // we are in termination case (3) or (2) and return the appropriate thing.
  22421. if (aBias == exports.LEAST_UPPER_BOUND) {
  22422. return mid;
  22423. } else {
  22424. return aLow < 0 ? -1 : aLow;
  22425. }
  22426. }
  22427. }
  22428. /**
  22429. * This is an implementation of binary search which will always try and return
  22430. * the index of the closest element if there is no exact hit. This is because
  22431. * mappings between original and generated line/col pairs are single points,
  22432. * and there is an implicit region between each of them, so a miss just means
  22433. * that you aren't on the very start of a region.
  22434. *
  22435. * @param aNeedle The element you are looking for.
  22436. * @param aHaystack The array that is being searched.
  22437. * @param aCompare A function which takes the needle and an element in the
  22438. * array and returns -1, 0, or 1 depending on whether the needle is less
  22439. * than, equal to, or greater than the element, respectively.
  22440. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  22441. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  22442. * closest element that is smaller than or greater than the one we are
  22443. * searching for, respectively, if the exact element cannot be found.
  22444. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  22445. */
  22446. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  22447. if (aHaystack.length === 0) {
  22448. return -1;
  22449. }
  22450. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  22451. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  22452. if (index < 0) {
  22453. return -1;
  22454. }
  22455. // We have found either the exact element, or the next-closest element than
  22456. // the one we are searching for. However, there may be more than one such
  22457. // element. Make sure we always return the smallest of these.
  22458. while (index - 1 >= 0) {
  22459. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  22460. break;
  22461. }
  22462. --index;
  22463. }
  22464. return index;
  22465. };
  22466. } (binarySearch$1));
  22467. return binarySearch$1;
  22468. }
  22469. var quickSort$1 = {};
  22470. /* -*- Mode: js; js-indent-level: 2; -*- */
  22471. var hasRequiredQuickSort$1;
  22472. function requireQuickSort$1 () {
  22473. if (hasRequiredQuickSort$1) return quickSort$1;
  22474. hasRequiredQuickSort$1 = 1;
  22475. /*
  22476. * Copyright 2011 Mozilla Foundation and contributors
  22477. * Licensed under the New BSD license. See LICENSE or:
  22478. * http://opensource.org/licenses/BSD-3-Clause
  22479. */
  22480. // It turns out that some (most?) JavaScript engines don't self-host
  22481. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  22482. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  22483. // custom comparator function, calling back and forth between the VM's C++ and
  22484. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  22485. // worse generated code for the comparator function than would be optimal. In
  22486. // fact, when sorting with a comparator, these costs outweigh the benefits of
  22487. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  22488. // a ~3500ms mean speed-up in `bench/bench.html`.
  22489. function SortTemplate(comparator) {
  22490. /**
  22491. * Swap the elements indexed by `x` and `y` in the array `ary`.
  22492. *
  22493. * @param {Array} ary
  22494. * The array.
  22495. * @param {Number} x
  22496. * The index of the first item.
  22497. * @param {Number} y
  22498. * The index of the second item.
  22499. */
  22500. function swap(ary, x, y) {
  22501. var temp = ary[x];
  22502. ary[x] = ary[y];
  22503. ary[y] = temp;
  22504. }
  22505. /**
  22506. * Returns a random integer within the range `low .. high` inclusive.
  22507. *
  22508. * @param {Number} low
  22509. * The lower bound on the range.
  22510. * @param {Number} high
  22511. * The upper bound on the range.
  22512. */
  22513. function randomIntInRange(low, high) {
  22514. return Math.round(low + (Math.random() * (high - low)));
  22515. }
  22516. /**
  22517. * The Quick Sort algorithm.
  22518. *
  22519. * @param {Array} ary
  22520. * An array to sort.
  22521. * @param {function} comparator
  22522. * Function to use to compare two items.
  22523. * @param {Number} p
  22524. * Start index of the array
  22525. * @param {Number} r
  22526. * End index of the array
  22527. */
  22528. function doQuickSort(ary, comparator, p, r) {
  22529. // If our lower bound is less than our upper bound, we (1) partition the
  22530. // array into two pieces and (2) recurse on each half. If it is not, this is
  22531. // the empty array and our base case.
  22532. if (p < r) {
  22533. // (1) Partitioning.
  22534. //
  22535. // The partitioning chooses a pivot between `p` and `r` and moves all
  22536. // elements that are less than or equal to the pivot to the before it, and
  22537. // all the elements that are greater than it after it. The effect is that
  22538. // once partition is done, the pivot is in the exact place it will be when
  22539. // the array is put in sorted order, and it will not need to be moved
  22540. // again. This runs in O(n) time.
  22541. // Always choose a random pivot so that an input array which is reverse
  22542. // sorted does not cause O(n^2) running time.
  22543. var pivotIndex = randomIntInRange(p, r);
  22544. var i = p - 1;
  22545. swap(ary, pivotIndex, r);
  22546. var pivot = ary[r];
  22547. // Immediately after `j` is incremented in this loop, the following hold
  22548. // true:
  22549. //
  22550. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  22551. //
  22552. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  22553. for (var j = p; j < r; j++) {
  22554. if (comparator(ary[j], pivot, false) <= 0) {
  22555. i += 1;
  22556. swap(ary, i, j);
  22557. }
  22558. }
  22559. swap(ary, i + 1, j);
  22560. var q = i + 1;
  22561. // (2) Recurse on each half.
  22562. doQuickSort(ary, comparator, p, q - 1);
  22563. doQuickSort(ary, comparator, q + 1, r);
  22564. }
  22565. }
  22566. return doQuickSort;
  22567. }
  22568. function cloneSort(comparator) {
  22569. let template = SortTemplate.toString();
  22570. let templateFn = new Function(`return ${template}`)();
  22571. return templateFn(comparator);
  22572. }
  22573. /**
  22574. * Sort the given array in-place with the given comparator function.
  22575. *
  22576. * @param {Array} ary
  22577. * An array to sort.
  22578. * @param {function} comparator
  22579. * Function to use to compare two items.
  22580. */
  22581. let sortCache = new WeakMap();
  22582. quickSort$1.quickSort = function (ary, comparator, start = 0) {
  22583. let doQuickSort = sortCache.get(comparator);
  22584. if (doQuickSort === void 0) {
  22585. doQuickSort = cloneSort(comparator);
  22586. sortCache.set(comparator, doQuickSort);
  22587. }
  22588. doQuickSort(ary, comparator, start, ary.length - 1);
  22589. };
  22590. return quickSort$1;
  22591. }
  22592. /* -*- Mode: js; js-indent-level: 2; -*- */
  22593. var hasRequiredSourceMapConsumer$1;
  22594. function requireSourceMapConsumer$1 () {
  22595. if (hasRequiredSourceMapConsumer$1) return sourceMapConsumer$1;
  22596. hasRequiredSourceMapConsumer$1 = 1;
  22597. /*
  22598. * Copyright 2011 Mozilla Foundation and contributors
  22599. * Licensed under the New BSD license. See LICENSE or:
  22600. * http://opensource.org/licenses/BSD-3-Clause
  22601. */
  22602. var util = /*@__PURE__*/ requireUtil$2();
  22603. var binarySearch = /*@__PURE__*/ requireBinarySearch$1();
  22604. var ArraySet = /*@__PURE__*/ requireArraySet$1().ArraySet;
  22605. var base64VLQ = /*@__PURE__*/ requireBase64Vlq$1();
  22606. var quickSort = /*@__PURE__*/ requireQuickSort$1().quickSort;
  22607. function SourceMapConsumer(aSourceMap, aSourceMapURL) {
  22608. var sourceMap = aSourceMap;
  22609. if (typeof aSourceMap === 'string') {
  22610. sourceMap = util.parseSourceMapInput(aSourceMap);
  22611. }
  22612. return sourceMap.sections != null
  22613. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  22614. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  22615. }
  22616. SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  22617. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  22618. };
  22619. /**
  22620. * The version of the source mapping spec that we are consuming.
  22621. */
  22622. SourceMapConsumer.prototype._version = 3;
  22623. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  22624. // parsed mapping coordinates from the source map's "mappings" attribute. They
  22625. // are lazily instantiated, accessed via the `_generatedMappings` and
  22626. // `_originalMappings` getters respectively, and we only parse the mappings
  22627. // and create these arrays once queried for a source location. We jump through
  22628. // these hoops because there can be many thousands of mappings, and parsing
  22629. // them is expensive, so we only want to do it if we must.
  22630. //
  22631. // Each object in the arrays is of the form:
  22632. //
  22633. // {
  22634. // generatedLine: The line number in the generated code,
  22635. // generatedColumn: The column number in the generated code,
  22636. // source: The path to the original source file that generated this
  22637. // chunk of code,
  22638. // originalLine: The line number in the original source that
  22639. // corresponds to this chunk of generated code,
  22640. // originalColumn: The column number in the original source that
  22641. // corresponds to this chunk of generated code,
  22642. // name: The name of the original symbol which generated this chunk of
  22643. // code.
  22644. // }
  22645. //
  22646. // All properties except for `generatedLine` and `generatedColumn` can be
  22647. // `null`.
  22648. //
  22649. // `_generatedMappings` is ordered by the generated positions.
  22650. //
  22651. // `_originalMappings` is ordered by the original positions.
  22652. SourceMapConsumer.prototype.__generatedMappings = null;
  22653. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  22654. configurable: true,
  22655. enumerable: true,
  22656. get: function () {
  22657. if (!this.__generatedMappings) {
  22658. this._parseMappings(this._mappings, this.sourceRoot);
  22659. }
  22660. return this.__generatedMappings;
  22661. }
  22662. });
  22663. SourceMapConsumer.prototype.__originalMappings = null;
  22664. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  22665. configurable: true,
  22666. enumerable: true,
  22667. get: function () {
  22668. if (!this.__originalMappings) {
  22669. this._parseMappings(this._mappings, this.sourceRoot);
  22670. }
  22671. return this.__originalMappings;
  22672. }
  22673. });
  22674. SourceMapConsumer.prototype._charIsMappingSeparator =
  22675. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  22676. var c = aStr.charAt(index);
  22677. return c === ";" || c === ",";
  22678. };
  22679. /**
  22680. * Parse the mappings in a string in to a data structure which we can easily
  22681. * query (the ordered arrays in the `this.__generatedMappings` and
  22682. * `this.__originalMappings` properties).
  22683. */
  22684. SourceMapConsumer.prototype._parseMappings =
  22685. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  22686. throw new Error("Subclasses must implement _parseMappings");
  22687. };
  22688. SourceMapConsumer.GENERATED_ORDER = 1;
  22689. SourceMapConsumer.ORIGINAL_ORDER = 2;
  22690. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  22691. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  22692. /**
  22693. * Iterate over each mapping between an original source/line/column and a
  22694. * generated line/column in this source map.
  22695. *
  22696. * @param Function aCallback
  22697. * The function that is called with each mapping.
  22698. * @param Object aContext
  22699. * Optional. If specified, this object will be the value of `this` every
  22700. * time that `aCallback` is called.
  22701. * @param aOrder
  22702. * Either `SourceMapConsumer.GENERATED_ORDER` or
  22703. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  22704. * iterate over the mappings sorted by the generated file's line/column
  22705. * order or the original's source/line/column order, respectively. Defaults to
  22706. * `SourceMapConsumer.GENERATED_ORDER`.
  22707. */
  22708. SourceMapConsumer.prototype.eachMapping =
  22709. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  22710. var context = aContext || null;
  22711. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  22712. var mappings;
  22713. switch (order) {
  22714. case SourceMapConsumer.GENERATED_ORDER:
  22715. mappings = this._generatedMappings;
  22716. break;
  22717. case SourceMapConsumer.ORIGINAL_ORDER:
  22718. mappings = this._originalMappings;
  22719. break;
  22720. default:
  22721. throw new Error("Unknown order of iteration.");
  22722. }
  22723. var sourceRoot = this.sourceRoot;
  22724. var boundCallback = aCallback.bind(context);
  22725. var names = this._names;
  22726. var sources = this._sources;
  22727. var sourceMapURL = this._sourceMapURL;
  22728. for (var i = 0, n = mappings.length; i < n; i++) {
  22729. var mapping = mappings[i];
  22730. var source = mapping.source === null ? null : sources.at(mapping.source);
  22731. if(source !== null) {
  22732. source = util.computeSourceURL(sourceRoot, source, sourceMapURL);
  22733. }
  22734. boundCallback({
  22735. source: source,
  22736. generatedLine: mapping.generatedLine,
  22737. generatedColumn: mapping.generatedColumn,
  22738. originalLine: mapping.originalLine,
  22739. originalColumn: mapping.originalColumn,
  22740. name: mapping.name === null ? null : names.at(mapping.name)
  22741. });
  22742. }
  22743. };
  22744. /**
  22745. * Returns all generated line and column information for the original source,
  22746. * line, and column provided. If no column is provided, returns all mappings
  22747. * corresponding to a either the line we are searching for or the next
  22748. * closest line that has any mappings. Otherwise, returns all mappings
  22749. * corresponding to the given line and either the column we are searching for
  22750. * or the next closest column that has any offsets.
  22751. *
  22752. * The only argument is an object with the following properties:
  22753. *
  22754. * - source: The filename of the original source.
  22755. * - line: The line number in the original source. The line number is 1-based.
  22756. * - column: Optional. the column number in the original source.
  22757. * The column number is 0-based.
  22758. *
  22759. * and an array of objects is returned, each with the following properties:
  22760. *
  22761. * - line: The line number in the generated source, or null. The
  22762. * line number is 1-based.
  22763. * - column: The column number in the generated source, or null.
  22764. * The column number is 0-based.
  22765. */
  22766. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  22767. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  22768. var line = util.getArg(aArgs, 'line');
  22769. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  22770. // returns the index of the closest mapping less than the needle. By
  22771. // setting needle.originalColumn to 0, we thus find the last mapping for
  22772. // the given line, provided such a mapping exists.
  22773. var needle = {
  22774. source: util.getArg(aArgs, 'source'),
  22775. originalLine: line,
  22776. originalColumn: util.getArg(aArgs, 'column', 0)
  22777. };
  22778. needle.source = this._findSourceIndex(needle.source);
  22779. if (needle.source < 0) {
  22780. return [];
  22781. }
  22782. var mappings = [];
  22783. var index = this._findMapping(needle,
  22784. this._originalMappings,
  22785. "originalLine",
  22786. "originalColumn",
  22787. util.compareByOriginalPositions,
  22788. binarySearch.LEAST_UPPER_BOUND);
  22789. if (index >= 0) {
  22790. var mapping = this._originalMappings[index];
  22791. if (aArgs.column === undefined) {
  22792. var originalLine = mapping.originalLine;
  22793. // Iterate until either we run out of mappings, or we run into
  22794. // a mapping for a different line than the one we found. Since
  22795. // mappings are sorted, this is guaranteed to find all mappings for
  22796. // the line we found.
  22797. while (mapping && mapping.originalLine === originalLine) {
  22798. mappings.push({
  22799. line: util.getArg(mapping, 'generatedLine', null),
  22800. column: util.getArg(mapping, 'generatedColumn', null),
  22801. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  22802. });
  22803. mapping = this._originalMappings[++index];
  22804. }
  22805. } else {
  22806. var originalColumn = mapping.originalColumn;
  22807. // Iterate until either we run out of mappings, or we run into
  22808. // a mapping for a different line than the one we were searching for.
  22809. // Since mappings are sorted, this is guaranteed to find all mappings for
  22810. // the line we are searching for.
  22811. while (mapping &&
  22812. mapping.originalLine === line &&
  22813. mapping.originalColumn == originalColumn) {
  22814. mappings.push({
  22815. line: util.getArg(mapping, 'generatedLine', null),
  22816. column: util.getArg(mapping, 'generatedColumn', null),
  22817. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  22818. });
  22819. mapping = this._originalMappings[++index];
  22820. }
  22821. }
  22822. }
  22823. return mappings;
  22824. };
  22825. sourceMapConsumer$1.SourceMapConsumer = SourceMapConsumer;
  22826. /**
  22827. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  22828. * query for information about the original file positions by giving it a file
  22829. * position in the generated source.
  22830. *
  22831. * The first parameter is the raw source map (either as a JSON string, or
  22832. * already parsed to an object). According to the spec, source maps have the
  22833. * following attributes:
  22834. *
  22835. * - version: Which version of the source map spec this map is following.
  22836. * - sources: An array of URLs to the original source files.
  22837. * - names: An array of identifiers which can be referrenced by individual mappings.
  22838. * - sourceRoot: Optional. The URL root from which all sources are relative.
  22839. * - sourcesContent: Optional. An array of contents of the original source files.
  22840. * - mappings: A string of base64 VLQs which contain the actual mappings.
  22841. * - file: Optional. The generated file this source map is associated with.
  22842. *
  22843. * Here is an example source map, taken from the source map spec[0]:
  22844. *
  22845. * {
  22846. * version : 3,
  22847. * file: "out.js",
  22848. * sourceRoot : "",
  22849. * sources: ["foo.js", "bar.js"],
  22850. * names: ["src", "maps", "are", "fun"],
  22851. * mappings: "AA,AB;;ABCDE;"
  22852. * }
  22853. *
  22854. * The second parameter, if given, is a string whose value is the URL
  22855. * at which the source map was found. This URL is used to compute the
  22856. * sources array.
  22857. *
  22858. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  22859. */
  22860. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  22861. var sourceMap = aSourceMap;
  22862. if (typeof aSourceMap === 'string') {
  22863. sourceMap = util.parseSourceMapInput(aSourceMap);
  22864. }
  22865. var version = util.getArg(sourceMap, 'version');
  22866. var sources = util.getArg(sourceMap, 'sources');
  22867. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  22868. // requires the array) to play nice here.
  22869. var names = util.getArg(sourceMap, 'names', []);
  22870. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  22871. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  22872. var mappings = util.getArg(sourceMap, 'mappings');
  22873. var file = util.getArg(sourceMap, 'file', null);
  22874. // Once again, Sass deviates from the spec and supplies the version as a
  22875. // string rather than a number, so we use loose equality checking here.
  22876. if (version != this._version) {
  22877. throw new Error('Unsupported version: ' + version);
  22878. }
  22879. if (sourceRoot) {
  22880. sourceRoot = util.normalize(sourceRoot);
  22881. }
  22882. sources = sources
  22883. .map(String)
  22884. // Some source maps produce relative source paths like "./foo.js" instead of
  22885. // "foo.js". Normalize these first so that future comparisons will succeed.
  22886. // See bugzil.la/1090768.
  22887. .map(util.normalize)
  22888. // Always ensure that absolute sources are internally stored relative to
  22889. // the source root, if the source root is absolute. Not doing this would
  22890. // be particularly problematic when the source root is a prefix of the
  22891. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  22892. .map(function (source) {
  22893. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  22894. ? util.relative(sourceRoot, source)
  22895. : source;
  22896. });
  22897. // Pass `true` below to allow duplicate names and sources. While source maps
  22898. // are intended to be compressed and deduplicated, the TypeScript compiler
  22899. // sometimes generates source maps with duplicates in them. See Github issue
  22900. // #72 and bugzil.la/889492.
  22901. this._names = ArraySet.fromArray(names.map(String), true);
  22902. this._sources = ArraySet.fromArray(sources, true);
  22903. this._absoluteSources = this._sources.toArray().map(function (s) {
  22904. return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
  22905. });
  22906. this.sourceRoot = sourceRoot;
  22907. this.sourcesContent = sourcesContent;
  22908. this._mappings = mappings;
  22909. this._sourceMapURL = aSourceMapURL;
  22910. this.file = file;
  22911. }
  22912. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  22913. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  22914. /**
  22915. * Utility function to find the index of a source. Returns -1 if not
  22916. * found.
  22917. */
  22918. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  22919. var relativeSource = aSource;
  22920. if (this.sourceRoot != null) {
  22921. relativeSource = util.relative(this.sourceRoot, relativeSource);
  22922. }
  22923. if (this._sources.has(relativeSource)) {
  22924. return this._sources.indexOf(relativeSource);
  22925. }
  22926. // Maybe aSource is an absolute URL as returned by |sources|. In
  22927. // this case we can't simply undo the transform.
  22928. var i;
  22929. for (i = 0; i < this._absoluteSources.length; ++i) {
  22930. if (this._absoluteSources[i] == aSource) {
  22931. return i;
  22932. }
  22933. }
  22934. return -1;
  22935. };
  22936. /**
  22937. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  22938. *
  22939. * @param SourceMapGenerator aSourceMap
  22940. * The source map that will be consumed.
  22941. * @param String aSourceMapURL
  22942. * The URL at which the source map can be found (optional)
  22943. * @returns BasicSourceMapConsumer
  22944. */
  22945. BasicSourceMapConsumer.fromSourceMap =
  22946. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  22947. var smc = Object.create(BasicSourceMapConsumer.prototype);
  22948. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  22949. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  22950. smc.sourceRoot = aSourceMap._sourceRoot;
  22951. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  22952. smc.sourceRoot);
  22953. smc.file = aSourceMap._file;
  22954. smc._sourceMapURL = aSourceMapURL;
  22955. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  22956. return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  22957. });
  22958. // Because we are modifying the entries (by converting string sources and
  22959. // names to indices into the sources and names ArraySets), we have to make
  22960. // a copy of the entry or else bad things happen. Shared mutable state
  22961. // strikes again! See github issue #191.
  22962. var generatedMappings = aSourceMap._mappings.toArray().slice();
  22963. var destGeneratedMappings = smc.__generatedMappings = [];
  22964. var destOriginalMappings = smc.__originalMappings = [];
  22965. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  22966. var srcMapping = generatedMappings[i];
  22967. var destMapping = new Mapping;
  22968. destMapping.generatedLine = srcMapping.generatedLine;
  22969. destMapping.generatedColumn = srcMapping.generatedColumn;
  22970. if (srcMapping.source) {
  22971. destMapping.source = sources.indexOf(srcMapping.source);
  22972. destMapping.originalLine = srcMapping.originalLine;
  22973. destMapping.originalColumn = srcMapping.originalColumn;
  22974. if (srcMapping.name) {
  22975. destMapping.name = names.indexOf(srcMapping.name);
  22976. }
  22977. destOriginalMappings.push(destMapping);
  22978. }
  22979. destGeneratedMappings.push(destMapping);
  22980. }
  22981. quickSort(smc.__originalMappings, util.compareByOriginalPositions);
  22982. return smc;
  22983. };
  22984. /**
  22985. * The version of the source mapping spec that we are consuming.
  22986. */
  22987. BasicSourceMapConsumer.prototype._version = 3;
  22988. /**
  22989. * The list of original sources.
  22990. */
  22991. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  22992. get: function () {
  22993. return this._absoluteSources.slice();
  22994. }
  22995. });
  22996. /**
  22997. * Provide the JIT with a nice shape / hidden class.
  22998. */
  22999. function Mapping() {
  23000. this.generatedLine = 0;
  23001. this.generatedColumn = 0;
  23002. this.source = null;
  23003. this.originalLine = null;
  23004. this.originalColumn = null;
  23005. this.name = null;
  23006. }
  23007. /**
  23008. * Parse the mappings in a string in to a data structure which we can easily
  23009. * query (the ordered arrays in the `this.__generatedMappings` and
  23010. * `this.__originalMappings` properties).
  23011. */
  23012. const compareGenerated = util.compareByGeneratedPositionsDeflatedNoLine;
  23013. function sortGenerated(array, start) {
  23014. let l = array.length;
  23015. let n = array.length - start;
  23016. if (n <= 1) {
  23017. return;
  23018. } else if (n == 2) {
  23019. let a = array[start];
  23020. let b = array[start + 1];
  23021. if (compareGenerated(a, b) > 0) {
  23022. array[start] = b;
  23023. array[start + 1] = a;
  23024. }
  23025. } else if (n < 20) {
  23026. for (let i = start; i < l; i++) {
  23027. for (let j = i; j > start; j--) {
  23028. let a = array[j - 1];
  23029. let b = array[j];
  23030. if (compareGenerated(a, b) <= 0) {
  23031. break;
  23032. }
  23033. array[j - 1] = b;
  23034. array[j] = a;
  23035. }
  23036. }
  23037. } else {
  23038. quickSort(array, compareGenerated, start);
  23039. }
  23040. }
  23041. BasicSourceMapConsumer.prototype._parseMappings =
  23042. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  23043. var generatedLine = 1;
  23044. var previousGeneratedColumn = 0;
  23045. var previousOriginalLine = 0;
  23046. var previousOriginalColumn = 0;
  23047. var previousSource = 0;
  23048. var previousName = 0;
  23049. var length = aStr.length;
  23050. var index = 0;
  23051. var temp = {};
  23052. var originalMappings = [];
  23053. var generatedMappings = [];
  23054. var mapping, segment, end, value;
  23055. let subarrayStart = 0;
  23056. while (index < length) {
  23057. if (aStr.charAt(index) === ';') {
  23058. generatedLine++;
  23059. index++;
  23060. previousGeneratedColumn = 0;
  23061. sortGenerated(generatedMappings, subarrayStart);
  23062. subarrayStart = generatedMappings.length;
  23063. }
  23064. else if (aStr.charAt(index) === ',') {
  23065. index++;
  23066. }
  23067. else {
  23068. mapping = new Mapping();
  23069. mapping.generatedLine = generatedLine;
  23070. for (end = index; end < length; end++) {
  23071. if (this._charIsMappingSeparator(aStr, end)) {
  23072. break;
  23073. }
  23074. }
  23075. aStr.slice(index, end);
  23076. segment = [];
  23077. while (index < end) {
  23078. base64VLQ.decode(aStr, index, temp);
  23079. value = temp.value;
  23080. index = temp.rest;
  23081. segment.push(value);
  23082. }
  23083. if (segment.length === 2) {
  23084. throw new Error('Found a source, but no line and column');
  23085. }
  23086. if (segment.length === 3) {
  23087. throw new Error('Found a source and line, but no column');
  23088. }
  23089. // Generated column.
  23090. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  23091. previousGeneratedColumn = mapping.generatedColumn;
  23092. if (segment.length > 1) {
  23093. // Original source.
  23094. mapping.source = previousSource + segment[1];
  23095. previousSource += segment[1];
  23096. // Original line.
  23097. mapping.originalLine = previousOriginalLine + segment[2];
  23098. previousOriginalLine = mapping.originalLine;
  23099. // Lines are stored 0-based
  23100. mapping.originalLine += 1;
  23101. // Original column.
  23102. mapping.originalColumn = previousOriginalColumn + segment[3];
  23103. previousOriginalColumn = mapping.originalColumn;
  23104. if (segment.length > 4) {
  23105. // Original name.
  23106. mapping.name = previousName + segment[4];
  23107. previousName += segment[4];
  23108. }
  23109. }
  23110. generatedMappings.push(mapping);
  23111. if (typeof mapping.originalLine === 'number') {
  23112. let currentSource = mapping.source;
  23113. while (originalMappings.length <= currentSource) {
  23114. originalMappings.push(null);
  23115. }
  23116. if (originalMappings[currentSource] === null) {
  23117. originalMappings[currentSource] = [];
  23118. }
  23119. originalMappings[currentSource].push(mapping);
  23120. }
  23121. }
  23122. }
  23123. sortGenerated(generatedMappings, subarrayStart);
  23124. this.__generatedMappings = generatedMappings;
  23125. for (var i = 0; i < originalMappings.length; i++) {
  23126. if (originalMappings[i] != null) {
  23127. quickSort(originalMappings[i], util.compareByOriginalPositionsNoSource);
  23128. }
  23129. }
  23130. this.__originalMappings = [].concat(...originalMappings);
  23131. };
  23132. /**
  23133. * Find the mapping that best matches the hypothetical "needle" mapping that
  23134. * we are searching for in the given "haystack" of mappings.
  23135. */
  23136. BasicSourceMapConsumer.prototype._findMapping =
  23137. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  23138. aColumnName, aComparator, aBias) {
  23139. // To return the position we are searching for, we must first find the
  23140. // mapping for the given position and then return the opposite position it
  23141. // points to. Because the mappings are sorted, we can use binary search to
  23142. // find the best mapping.
  23143. if (aNeedle[aLineName] <= 0) {
  23144. throw new TypeError('Line must be greater than or equal to 1, got '
  23145. + aNeedle[aLineName]);
  23146. }
  23147. if (aNeedle[aColumnName] < 0) {
  23148. throw new TypeError('Column must be greater than or equal to 0, got '
  23149. + aNeedle[aColumnName]);
  23150. }
  23151. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  23152. };
  23153. /**
  23154. * Compute the last column for each generated mapping. The last column is
  23155. * inclusive.
  23156. */
  23157. BasicSourceMapConsumer.prototype.computeColumnSpans =
  23158. function SourceMapConsumer_computeColumnSpans() {
  23159. for (var index = 0; index < this._generatedMappings.length; ++index) {
  23160. var mapping = this._generatedMappings[index];
  23161. // Mappings do not contain a field for the last generated columnt. We
  23162. // can come up with an optimistic estimate, however, by assuming that
  23163. // mappings are contiguous (i.e. given two consecutive mappings, the
  23164. // first mapping ends where the second one starts).
  23165. if (index + 1 < this._generatedMappings.length) {
  23166. var nextMapping = this._generatedMappings[index + 1];
  23167. if (mapping.generatedLine === nextMapping.generatedLine) {
  23168. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  23169. continue;
  23170. }
  23171. }
  23172. // The last mapping for each line spans the entire line.
  23173. mapping.lastGeneratedColumn = Infinity;
  23174. }
  23175. };
  23176. /**
  23177. * Returns the original source, line, and column information for the generated
  23178. * source's line and column positions provided. The only argument is an object
  23179. * with the following properties:
  23180. *
  23181. * - line: The line number in the generated source. The line number
  23182. * is 1-based.
  23183. * - column: The column number in the generated source. The column
  23184. * number is 0-based.
  23185. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  23186. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  23187. * closest element that is smaller than or greater than the one we are
  23188. * searching for, respectively, if the exact element cannot be found.
  23189. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  23190. *
  23191. * and an object is returned with the following properties:
  23192. *
  23193. * - source: The original source file, or null.
  23194. * - line: The line number in the original source, or null. The
  23195. * line number is 1-based.
  23196. * - column: The column number in the original source, or null. The
  23197. * column number is 0-based.
  23198. * - name: The original identifier, or null.
  23199. */
  23200. BasicSourceMapConsumer.prototype.originalPositionFor =
  23201. function SourceMapConsumer_originalPositionFor(aArgs) {
  23202. var needle = {
  23203. generatedLine: util.getArg(aArgs, 'line'),
  23204. generatedColumn: util.getArg(aArgs, 'column')
  23205. };
  23206. var index = this._findMapping(
  23207. needle,
  23208. this._generatedMappings,
  23209. "generatedLine",
  23210. "generatedColumn",
  23211. util.compareByGeneratedPositionsDeflated,
  23212. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  23213. );
  23214. if (index >= 0) {
  23215. var mapping = this._generatedMappings[index];
  23216. if (mapping.generatedLine === needle.generatedLine) {
  23217. var source = util.getArg(mapping, 'source', null);
  23218. if (source !== null) {
  23219. source = this._sources.at(source);
  23220. source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  23221. }
  23222. var name = util.getArg(mapping, 'name', null);
  23223. if (name !== null) {
  23224. name = this._names.at(name);
  23225. }
  23226. return {
  23227. source: source,
  23228. line: util.getArg(mapping, 'originalLine', null),
  23229. column: util.getArg(mapping, 'originalColumn', null),
  23230. name: name
  23231. };
  23232. }
  23233. }
  23234. return {
  23235. source: null,
  23236. line: null,
  23237. column: null,
  23238. name: null
  23239. };
  23240. };
  23241. /**
  23242. * Return true if we have the source content for every source in the source
  23243. * map, false otherwise.
  23244. */
  23245. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  23246. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  23247. if (!this.sourcesContent) {
  23248. return false;
  23249. }
  23250. return this.sourcesContent.length >= this._sources.size() &&
  23251. !this.sourcesContent.some(function (sc) { return sc == null; });
  23252. };
  23253. /**
  23254. * Returns the original source content. The only argument is the url of the
  23255. * original source file. Returns null if no original source content is
  23256. * available.
  23257. */
  23258. BasicSourceMapConsumer.prototype.sourceContentFor =
  23259. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  23260. if (!this.sourcesContent) {
  23261. return null;
  23262. }
  23263. var index = this._findSourceIndex(aSource);
  23264. if (index >= 0) {
  23265. return this.sourcesContent[index];
  23266. }
  23267. var relativeSource = aSource;
  23268. if (this.sourceRoot != null) {
  23269. relativeSource = util.relative(this.sourceRoot, relativeSource);
  23270. }
  23271. var url;
  23272. if (this.sourceRoot != null
  23273. && (url = util.urlParse(this.sourceRoot))) {
  23274. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  23275. // many users. We can help them out when they expect file:// URIs to
  23276. // behave like it would if they were running a local HTTP server. See
  23277. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  23278. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  23279. if (url.scheme == "file"
  23280. && this._sources.has(fileUriAbsPath)) {
  23281. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  23282. }
  23283. if ((!url.path || url.path == "/")
  23284. && this._sources.has("/" + relativeSource)) {
  23285. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  23286. }
  23287. }
  23288. // This function is used recursively from
  23289. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  23290. // don't want to throw if we can't find the source - we just want to
  23291. // return null, so we provide a flag to exit gracefully.
  23292. if (nullOnMissing) {
  23293. return null;
  23294. }
  23295. else {
  23296. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  23297. }
  23298. };
  23299. /**
  23300. * Returns the generated line and column information for the original source,
  23301. * line, and column positions provided. The only argument is an object with
  23302. * the following properties:
  23303. *
  23304. * - source: The filename of the original source.
  23305. * - line: The line number in the original source. The line number
  23306. * is 1-based.
  23307. * - column: The column number in the original source. The column
  23308. * number is 0-based.
  23309. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  23310. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  23311. * closest element that is smaller than or greater than the one we are
  23312. * searching for, respectively, if the exact element cannot be found.
  23313. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  23314. *
  23315. * and an object is returned with the following properties:
  23316. *
  23317. * - line: The line number in the generated source, or null. The
  23318. * line number is 1-based.
  23319. * - column: The column number in the generated source, or null.
  23320. * The column number is 0-based.
  23321. */
  23322. BasicSourceMapConsumer.prototype.generatedPositionFor =
  23323. function SourceMapConsumer_generatedPositionFor(aArgs) {
  23324. var source = util.getArg(aArgs, 'source');
  23325. source = this._findSourceIndex(source);
  23326. if (source < 0) {
  23327. return {
  23328. line: null,
  23329. column: null,
  23330. lastColumn: null
  23331. };
  23332. }
  23333. var needle = {
  23334. source: source,
  23335. originalLine: util.getArg(aArgs, 'line'),
  23336. originalColumn: util.getArg(aArgs, 'column')
  23337. };
  23338. var index = this._findMapping(
  23339. needle,
  23340. this._originalMappings,
  23341. "originalLine",
  23342. "originalColumn",
  23343. util.compareByOriginalPositions,
  23344. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  23345. );
  23346. if (index >= 0) {
  23347. var mapping = this._originalMappings[index];
  23348. if (mapping.source === needle.source) {
  23349. return {
  23350. line: util.getArg(mapping, 'generatedLine', null),
  23351. column: util.getArg(mapping, 'generatedColumn', null),
  23352. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  23353. };
  23354. }
  23355. }
  23356. return {
  23357. line: null,
  23358. column: null,
  23359. lastColumn: null
  23360. };
  23361. };
  23362. sourceMapConsumer$1.BasicSourceMapConsumer = BasicSourceMapConsumer;
  23363. /**
  23364. * An IndexedSourceMapConsumer instance represents a parsed source map which
  23365. * we can query for information. It differs from BasicSourceMapConsumer in
  23366. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  23367. * input.
  23368. *
  23369. * The first parameter is a raw source map (either as a JSON string, or already
  23370. * parsed to an object). According to the spec for indexed source maps, they
  23371. * have the following attributes:
  23372. *
  23373. * - version: Which version of the source map spec this map is following.
  23374. * - file: Optional. The generated file this source map is associated with.
  23375. * - sections: A list of section definitions.
  23376. *
  23377. * Each value under the "sections" field has two fields:
  23378. * - offset: The offset into the original specified at which this section
  23379. * begins to apply, defined as an object with a "line" and "column"
  23380. * field.
  23381. * - map: A source map definition. This source map could also be indexed,
  23382. * but doesn't have to be.
  23383. *
  23384. * Instead of the "map" field, it's also possible to have a "url" field
  23385. * specifying a URL to retrieve a source map from, but that's currently
  23386. * unsupported.
  23387. *
  23388. * Here's an example source map, taken from the source map spec[0], but
  23389. * modified to omit a section which uses the "url" field.
  23390. *
  23391. * {
  23392. * version : 3,
  23393. * file: "app.js",
  23394. * sections: [{
  23395. * offset: {line:100, column:10},
  23396. * map: {
  23397. * version : 3,
  23398. * file: "section.js",
  23399. * sources: ["foo.js", "bar.js"],
  23400. * names: ["src", "maps", "are", "fun"],
  23401. * mappings: "AAAA,E;;ABCDE;"
  23402. * }
  23403. * }],
  23404. * }
  23405. *
  23406. * The second parameter, if given, is a string whose value is the URL
  23407. * at which the source map was found. This URL is used to compute the
  23408. * sources array.
  23409. *
  23410. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  23411. */
  23412. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  23413. var sourceMap = aSourceMap;
  23414. if (typeof aSourceMap === 'string') {
  23415. sourceMap = util.parseSourceMapInput(aSourceMap);
  23416. }
  23417. var version = util.getArg(sourceMap, 'version');
  23418. var sections = util.getArg(sourceMap, 'sections');
  23419. if (version != this._version) {
  23420. throw new Error('Unsupported version: ' + version);
  23421. }
  23422. this._sources = new ArraySet();
  23423. this._names = new ArraySet();
  23424. var lastOffset = {
  23425. line: -1,
  23426. column: 0
  23427. };
  23428. this._sections = sections.map(function (s) {
  23429. if (s.url) {
  23430. // The url field will require support for asynchronicity.
  23431. // See https://github.com/mozilla/source-map/issues/16
  23432. throw new Error('Support for url field in sections not implemented.');
  23433. }
  23434. var offset = util.getArg(s, 'offset');
  23435. var offsetLine = util.getArg(offset, 'line');
  23436. var offsetColumn = util.getArg(offset, 'column');
  23437. if (offsetLine < lastOffset.line ||
  23438. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  23439. throw new Error('Section offsets must be ordered and non-overlapping.');
  23440. }
  23441. lastOffset = offset;
  23442. return {
  23443. generatedOffset: {
  23444. // The offset fields are 0-based, but we use 1-based indices when
  23445. // encoding/decoding from VLQ.
  23446. generatedLine: offsetLine + 1,
  23447. generatedColumn: offsetColumn + 1
  23448. },
  23449. consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
  23450. }
  23451. });
  23452. }
  23453. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  23454. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  23455. /**
  23456. * The version of the source mapping spec that we are consuming.
  23457. */
  23458. IndexedSourceMapConsumer.prototype._version = 3;
  23459. /**
  23460. * The list of original sources.
  23461. */
  23462. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  23463. get: function () {
  23464. var sources = [];
  23465. for (var i = 0; i < this._sections.length; i++) {
  23466. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  23467. sources.push(this._sections[i].consumer.sources[j]);
  23468. }
  23469. }
  23470. return sources;
  23471. }
  23472. });
  23473. /**
  23474. * Returns the original source, line, and column information for the generated
  23475. * source's line and column positions provided. The only argument is an object
  23476. * with the following properties:
  23477. *
  23478. * - line: The line number in the generated source. The line number
  23479. * is 1-based.
  23480. * - column: The column number in the generated source. The column
  23481. * number is 0-based.
  23482. *
  23483. * and an object is returned with the following properties:
  23484. *
  23485. * - source: The original source file, or null.
  23486. * - line: The line number in the original source, or null. The
  23487. * line number is 1-based.
  23488. * - column: The column number in the original source, or null. The
  23489. * column number is 0-based.
  23490. * - name: The original identifier, or null.
  23491. */
  23492. IndexedSourceMapConsumer.prototype.originalPositionFor =
  23493. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  23494. var needle = {
  23495. generatedLine: util.getArg(aArgs, 'line'),
  23496. generatedColumn: util.getArg(aArgs, 'column')
  23497. };
  23498. // Find the section containing the generated position we're trying to map
  23499. // to an original position.
  23500. var sectionIndex = binarySearch.search(needle, this._sections,
  23501. function(needle, section) {
  23502. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  23503. if (cmp) {
  23504. return cmp;
  23505. }
  23506. return (needle.generatedColumn -
  23507. section.generatedOffset.generatedColumn);
  23508. });
  23509. var section = this._sections[sectionIndex];
  23510. if (!section) {
  23511. return {
  23512. source: null,
  23513. line: null,
  23514. column: null,
  23515. name: null
  23516. };
  23517. }
  23518. return section.consumer.originalPositionFor({
  23519. line: needle.generatedLine -
  23520. (section.generatedOffset.generatedLine - 1),
  23521. column: needle.generatedColumn -
  23522. (section.generatedOffset.generatedLine === needle.generatedLine
  23523. ? section.generatedOffset.generatedColumn - 1
  23524. : 0),
  23525. bias: aArgs.bias
  23526. });
  23527. };
  23528. /**
  23529. * Return true if we have the source content for every source in the source
  23530. * map, false otherwise.
  23531. */
  23532. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  23533. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  23534. return this._sections.every(function (s) {
  23535. return s.consumer.hasContentsOfAllSources();
  23536. });
  23537. };
  23538. /**
  23539. * Returns the original source content. The only argument is the url of the
  23540. * original source file. Returns null if no original source content is
  23541. * available.
  23542. */
  23543. IndexedSourceMapConsumer.prototype.sourceContentFor =
  23544. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  23545. for (var i = 0; i < this._sections.length; i++) {
  23546. var section = this._sections[i];
  23547. var content = section.consumer.sourceContentFor(aSource, true);
  23548. if (content || content === '') {
  23549. return content;
  23550. }
  23551. }
  23552. if (nullOnMissing) {
  23553. return null;
  23554. }
  23555. else {
  23556. throw new Error('"' + aSource + '" is not in the SourceMap.');
  23557. }
  23558. };
  23559. /**
  23560. * Returns the generated line and column information for the original source,
  23561. * line, and column positions provided. The only argument is an object with
  23562. * the following properties:
  23563. *
  23564. * - source: The filename of the original source.
  23565. * - line: The line number in the original source. The line number
  23566. * is 1-based.
  23567. * - column: The column number in the original source. The column
  23568. * number is 0-based.
  23569. *
  23570. * and an object is returned with the following properties:
  23571. *
  23572. * - line: The line number in the generated source, or null. The
  23573. * line number is 1-based.
  23574. * - column: The column number in the generated source, or null.
  23575. * The column number is 0-based.
  23576. */
  23577. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  23578. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  23579. for (var i = 0; i < this._sections.length; i++) {
  23580. var section = this._sections[i];
  23581. // Only consider this section if the requested source is in the list of
  23582. // sources of the consumer.
  23583. if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
  23584. continue;
  23585. }
  23586. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  23587. if (generatedPosition) {
  23588. var ret = {
  23589. line: generatedPosition.line +
  23590. (section.generatedOffset.generatedLine - 1),
  23591. column: generatedPosition.column +
  23592. (section.generatedOffset.generatedLine === generatedPosition.line
  23593. ? section.generatedOffset.generatedColumn - 1
  23594. : 0)
  23595. };
  23596. return ret;
  23597. }
  23598. }
  23599. return {
  23600. line: null,
  23601. column: null
  23602. };
  23603. };
  23604. /**
  23605. * Parse the mappings in a string in to a data structure which we can easily
  23606. * query (the ordered arrays in the `this.__generatedMappings` and
  23607. * `this.__originalMappings` properties).
  23608. */
  23609. IndexedSourceMapConsumer.prototype._parseMappings =
  23610. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  23611. this.__generatedMappings = [];
  23612. this.__originalMappings = [];
  23613. for (var i = 0; i < this._sections.length; i++) {
  23614. var section = this._sections[i];
  23615. var sectionMappings = section.consumer._generatedMappings;
  23616. for (var j = 0; j < sectionMappings.length; j++) {
  23617. var mapping = sectionMappings[j];
  23618. var source = section.consumer._sources.at(mapping.source);
  23619. if(source !== null) {
  23620. source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  23621. }
  23622. this._sources.add(source);
  23623. source = this._sources.indexOf(source);
  23624. var name = null;
  23625. if (mapping.name) {
  23626. name = section.consumer._names.at(mapping.name);
  23627. this._names.add(name);
  23628. name = this._names.indexOf(name);
  23629. }
  23630. // The mappings coming from the consumer for the section have
  23631. // generated positions relative to the start of the section, so we
  23632. // need to offset them to be relative to the start of the concatenated
  23633. // generated file.
  23634. var adjustedMapping = {
  23635. source: source,
  23636. generatedLine: mapping.generatedLine +
  23637. (section.generatedOffset.generatedLine - 1),
  23638. generatedColumn: mapping.generatedColumn +
  23639. (section.generatedOffset.generatedLine === mapping.generatedLine
  23640. ? section.generatedOffset.generatedColumn - 1
  23641. : 0),
  23642. originalLine: mapping.originalLine,
  23643. originalColumn: mapping.originalColumn,
  23644. name: name
  23645. };
  23646. this.__generatedMappings.push(adjustedMapping);
  23647. if (typeof adjustedMapping.originalLine === 'number') {
  23648. this.__originalMappings.push(adjustedMapping);
  23649. }
  23650. }
  23651. }
  23652. quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  23653. quickSort(this.__originalMappings, util.compareByOriginalPositions);
  23654. };
  23655. sourceMapConsumer$1.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  23656. return sourceMapConsumer$1;
  23657. }
  23658. var sourceNode$1 = {};
  23659. /* -*- Mode: js; js-indent-level: 2; -*- */
  23660. var hasRequiredSourceNode$1;
  23661. function requireSourceNode$1 () {
  23662. if (hasRequiredSourceNode$1) return sourceNode$1;
  23663. hasRequiredSourceNode$1 = 1;
  23664. /*
  23665. * Copyright 2011 Mozilla Foundation and contributors
  23666. * Licensed under the New BSD license. See LICENSE or:
  23667. * http://opensource.org/licenses/BSD-3-Clause
  23668. */
  23669. var SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator$1().SourceMapGenerator;
  23670. var util = /*@__PURE__*/ requireUtil$2();
  23671. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  23672. // operating systems these days (capturing the result).
  23673. var REGEX_NEWLINE = /(\r?\n)/;
  23674. // Newline character code for charCodeAt() comparisons
  23675. var NEWLINE_CODE = 10;
  23676. // Private symbol for identifying `SourceNode`s when multiple versions of
  23677. // the source-map library are loaded. This MUST NOT CHANGE across
  23678. // versions!
  23679. var isSourceNode = "$$$isSourceNode$$$";
  23680. /**
  23681. * SourceNodes provide a way to abstract over interpolating/concatenating
  23682. * snippets of generated JavaScript source code while maintaining the line and
  23683. * column information associated with the original source code.
  23684. *
  23685. * @param aLine The original line number.
  23686. * @param aColumn The original column number.
  23687. * @param aSource The original source's filename.
  23688. * @param aChunks Optional. An array of strings which are snippets of
  23689. * generated JS, or other SourceNodes.
  23690. * @param aName The original identifier.
  23691. */
  23692. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  23693. this.children = [];
  23694. this.sourceContents = {};
  23695. this.line = aLine == null ? null : aLine;
  23696. this.column = aColumn == null ? null : aColumn;
  23697. this.source = aSource == null ? null : aSource;
  23698. this.name = aName == null ? null : aName;
  23699. this[isSourceNode] = true;
  23700. if (aChunks != null) this.add(aChunks);
  23701. }
  23702. /**
  23703. * Creates a SourceNode from generated code and a SourceMapConsumer.
  23704. *
  23705. * @param aGeneratedCode The generated code
  23706. * @param aSourceMapConsumer The SourceMap for the generated code
  23707. * @param aRelativePath Optional. The path that relative sources in the
  23708. * SourceMapConsumer should be relative to.
  23709. */
  23710. SourceNode.fromStringWithSourceMap =
  23711. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  23712. // The SourceNode we want to fill with the generated code
  23713. // and the SourceMap
  23714. var node = new SourceNode();
  23715. // All even indices of this array are one line of the generated code,
  23716. // while all odd indices are the newlines between two adjacent lines
  23717. // (since `REGEX_NEWLINE` captures its match).
  23718. // Processed fragments are accessed by calling `shiftNextLine`.
  23719. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  23720. var remainingLinesIndex = 0;
  23721. var shiftNextLine = function() {
  23722. var lineContents = getNextLine();
  23723. // The last line of a file might not have a newline.
  23724. var newLine = getNextLine() || "";
  23725. return lineContents + newLine;
  23726. function getNextLine() {
  23727. return remainingLinesIndex < remainingLines.length ?
  23728. remainingLines[remainingLinesIndex++] : undefined;
  23729. }
  23730. };
  23731. // We need to remember the position of "remainingLines"
  23732. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  23733. // The generate SourceNodes we need a code range.
  23734. // To extract it current and last mapping is used.
  23735. // Here we store the last mapping.
  23736. var lastMapping = null;
  23737. aSourceMapConsumer.eachMapping(function (mapping) {
  23738. if (lastMapping !== null) {
  23739. // We add the code from "lastMapping" to "mapping":
  23740. // First check if there is a new line in between.
  23741. if (lastGeneratedLine < mapping.generatedLine) {
  23742. // Associate first line with "lastMapping"
  23743. addMappingWithCode(lastMapping, shiftNextLine());
  23744. lastGeneratedLine++;
  23745. lastGeneratedColumn = 0;
  23746. // The remaining code is added without mapping
  23747. } else {
  23748. // There is no new line in between.
  23749. // Associate the code between "lastGeneratedColumn" and
  23750. // "mapping.generatedColumn" with "lastMapping"
  23751. var nextLine = remainingLines[remainingLinesIndex] || '';
  23752. var code = nextLine.substr(0, mapping.generatedColumn -
  23753. lastGeneratedColumn);
  23754. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  23755. lastGeneratedColumn);
  23756. lastGeneratedColumn = mapping.generatedColumn;
  23757. addMappingWithCode(lastMapping, code);
  23758. // No more remaining code, continue
  23759. lastMapping = mapping;
  23760. return;
  23761. }
  23762. }
  23763. // We add the generated code until the first mapping
  23764. // to the SourceNode without any mapping.
  23765. // Each line is added as separate string.
  23766. while (lastGeneratedLine < mapping.generatedLine) {
  23767. node.add(shiftNextLine());
  23768. lastGeneratedLine++;
  23769. }
  23770. if (lastGeneratedColumn < mapping.generatedColumn) {
  23771. var nextLine = remainingLines[remainingLinesIndex] || '';
  23772. node.add(nextLine.substr(0, mapping.generatedColumn));
  23773. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  23774. lastGeneratedColumn = mapping.generatedColumn;
  23775. }
  23776. lastMapping = mapping;
  23777. }, this);
  23778. // We have processed all mappings.
  23779. if (remainingLinesIndex < remainingLines.length) {
  23780. if (lastMapping) {
  23781. // Associate the remaining code in the current line with "lastMapping"
  23782. addMappingWithCode(lastMapping, shiftNextLine());
  23783. }
  23784. // and add the remaining lines without any mapping
  23785. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  23786. }
  23787. // Copy sourcesContent into SourceNode
  23788. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  23789. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  23790. if (content != null) {
  23791. if (aRelativePath != null) {
  23792. sourceFile = util.join(aRelativePath, sourceFile);
  23793. }
  23794. node.setSourceContent(sourceFile, content);
  23795. }
  23796. });
  23797. return node;
  23798. function addMappingWithCode(mapping, code) {
  23799. if (mapping === null || mapping.source === undefined) {
  23800. node.add(code);
  23801. } else {
  23802. var source = aRelativePath
  23803. ? util.join(aRelativePath, mapping.source)
  23804. : mapping.source;
  23805. node.add(new SourceNode(mapping.originalLine,
  23806. mapping.originalColumn,
  23807. source,
  23808. code,
  23809. mapping.name));
  23810. }
  23811. }
  23812. };
  23813. /**
  23814. * Add a chunk of generated JS to this source node.
  23815. *
  23816. * @param aChunk A string snippet of generated JS code, another instance of
  23817. * SourceNode, or an array where each member is one of those things.
  23818. */
  23819. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  23820. if (Array.isArray(aChunk)) {
  23821. aChunk.forEach(function (chunk) {
  23822. this.add(chunk);
  23823. }, this);
  23824. }
  23825. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  23826. if (aChunk) {
  23827. this.children.push(aChunk);
  23828. }
  23829. }
  23830. else {
  23831. throw new TypeError(
  23832. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  23833. );
  23834. }
  23835. return this;
  23836. };
  23837. /**
  23838. * Add a chunk of generated JS to the beginning of this source node.
  23839. *
  23840. * @param aChunk A string snippet of generated JS code, another instance of
  23841. * SourceNode, or an array where each member is one of those things.
  23842. */
  23843. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  23844. if (Array.isArray(aChunk)) {
  23845. for (var i = aChunk.length-1; i >= 0; i--) {
  23846. this.prepend(aChunk[i]);
  23847. }
  23848. }
  23849. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  23850. this.children.unshift(aChunk);
  23851. }
  23852. else {
  23853. throw new TypeError(
  23854. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  23855. );
  23856. }
  23857. return this;
  23858. };
  23859. /**
  23860. * Walk over the tree of JS snippets in this node and its children. The
  23861. * walking function is called once for each snippet of JS and is passed that
  23862. * snippet and the its original associated source's line/column location.
  23863. *
  23864. * @param aFn The traversal function.
  23865. */
  23866. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  23867. var chunk;
  23868. for (var i = 0, len = this.children.length; i < len; i++) {
  23869. chunk = this.children[i];
  23870. if (chunk[isSourceNode]) {
  23871. chunk.walk(aFn);
  23872. }
  23873. else {
  23874. if (chunk !== '') {
  23875. aFn(chunk, { source: this.source,
  23876. line: this.line,
  23877. column: this.column,
  23878. name: this.name });
  23879. }
  23880. }
  23881. }
  23882. };
  23883. /**
  23884. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  23885. * each of `this.children`.
  23886. *
  23887. * @param aSep The separator.
  23888. */
  23889. SourceNode.prototype.join = function SourceNode_join(aSep) {
  23890. var newChildren;
  23891. var i;
  23892. var len = this.children.length;
  23893. if (len > 0) {
  23894. newChildren = [];
  23895. for (i = 0; i < len-1; i++) {
  23896. newChildren.push(this.children[i]);
  23897. newChildren.push(aSep);
  23898. }
  23899. newChildren.push(this.children[i]);
  23900. this.children = newChildren;
  23901. }
  23902. return this;
  23903. };
  23904. /**
  23905. * Call String.prototype.replace on the very right-most source snippet. Useful
  23906. * for trimming whitespace from the end of a source node, etc.
  23907. *
  23908. * @param aPattern The pattern to replace.
  23909. * @param aReplacement The thing to replace the pattern with.
  23910. */
  23911. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  23912. var lastChild = this.children[this.children.length - 1];
  23913. if (lastChild[isSourceNode]) {
  23914. lastChild.replaceRight(aPattern, aReplacement);
  23915. }
  23916. else if (typeof lastChild === 'string') {
  23917. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  23918. }
  23919. else {
  23920. this.children.push(''.replace(aPattern, aReplacement));
  23921. }
  23922. return this;
  23923. };
  23924. /**
  23925. * Set the source content for a source file. This will be added to the SourceMapGenerator
  23926. * in the sourcesContent field.
  23927. *
  23928. * @param aSourceFile The filename of the source file
  23929. * @param aSourceContent The content of the source file
  23930. */
  23931. SourceNode.prototype.setSourceContent =
  23932. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  23933. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  23934. };
  23935. /**
  23936. * Walk over the tree of SourceNodes. The walking function is called for each
  23937. * source file content and is passed the filename and source content.
  23938. *
  23939. * @param aFn The traversal function.
  23940. */
  23941. SourceNode.prototype.walkSourceContents =
  23942. function SourceNode_walkSourceContents(aFn) {
  23943. for (var i = 0, len = this.children.length; i < len; i++) {
  23944. if (this.children[i][isSourceNode]) {
  23945. this.children[i].walkSourceContents(aFn);
  23946. }
  23947. }
  23948. var sources = Object.keys(this.sourceContents);
  23949. for (var i = 0, len = sources.length; i < len; i++) {
  23950. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  23951. }
  23952. };
  23953. /**
  23954. * Return the string representation of this source node. Walks over the tree
  23955. * and concatenates all the various snippets together to one string.
  23956. */
  23957. SourceNode.prototype.toString = function SourceNode_toString() {
  23958. var str = "";
  23959. this.walk(function (chunk) {
  23960. str += chunk;
  23961. });
  23962. return str;
  23963. };
  23964. /**
  23965. * Returns the string representation of this source node along with a source
  23966. * map.
  23967. */
  23968. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  23969. var generated = {
  23970. code: "",
  23971. line: 1,
  23972. column: 0
  23973. };
  23974. var map = new SourceMapGenerator(aArgs);
  23975. var sourceMappingActive = false;
  23976. var lastOriginalSource = null;
  23977. var lastOriginalLine = null;
  23978. var lastOriginalColumn = null;
  23979. var lastOriginalName = null;
  23980. this.walk(function (chunk, original) {
  23981. generated.code += chunk;
  23982. if (original.source !== null
  23983. && original.line !== null
  23984. && original.column !== null) {
  23985. if(lastOriginalSource !== original.source
  23986. || lastOriginalLine !== original.line
  23987. || lastOriginalColumn !== original.column
  23988. || lastOriginalName !== original.name) {
  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. lastOriginalSource = original.source;
  24003. lastOriginalLine = original.line;
  24004. lastOriginalColumn = original.column;
  24005. lastOriginalName = original.name;
  24006. sourceMappingActive = true;
  24007. } else if (sourceMappingActive) {
  24008. map.addMapping({
  24009. generated: {
  24010. line: generated.line,
  24011. column: generated.column
  24012. }
  24013. });
  24014. lastOriginalSource = null;
  24015. sourceMappingActive = false;
  24016. }
  24017. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  24018. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  24019. generated.line++;
  24020. generated.column = 0;
  24021. // Mappings end at eol
  24022. if (idx + 1 === length) {
  24023. lastOriginalSource = null;
  24024. sourceMappingActive = false;
  24025. } else if (sourceMappingActive) {
  24026. map.addMapping({
  24027. source: original.source,
  24028. original: {
  24029. line: original.line,
  24030. column: original.column
  24031. },
  24032. generated: {
  24033. line: generated.line,
  24034. column: generated.column
  24035. },
  24036. name: original.name
  24037. });
  24038. }
  24039. } else {
  24040. generated.column++;
  24041. }
  24042. }
  24043. });
  24044. this.walkSourceContents(function (sourceFile, sourceContent) {
  24045. map.setSourceContent(sourceFile, sourceContent);
  24046. });
  24047. return { code: generated.code, map: map };
  24048. };
  24049. sourceNode$1.SourceNode = SourceNode;
  24050. return sourceNode$1;
  24051. }
  24052. /*
  24053. * Copyright 2009-2011 Mozilla Foundation and contributors
  24054. * Licensed under the New BSD license. See LICENSE.txt or:
  24055. * http://opensource.org/licenses/BSD-3-Clause
  24056. */
  24057. var hasRequiredSourceMap$1;
  24058. function requireSourceMap$1 () {
  24059. if (hasRequiredSourceMap$1) return sourceMap$1;
  24060. hasRequiredSourceMap$1 = 1;
  24061. sourceMap$1.SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator$1().SourceMapGenerator;
  24062. sourceMap$1.SourceMapConsumer = /*@__PURE__*/ requireSourceMapConsumer$1().SourceMapConsumer;
  24063. sourceMap$1.SourceNode = /*@__PURE__*/ requireSourceNode$1().SourceNode;
  24064. return sourceMap$1;
  24065. }
  24066. var sourceMapExports = /*@__PURE__*/ requireSourceMap$1();
  24067. const PURE_ANNOTATION = `/*@__PURE__*/`;
  24068. const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
  24069. function createCodegenContext(ast, {
  24070. mode = "function",
  24071. prefixIdentifiers = mode === "module",
  24072. sourceMap = false,
  24073. filename = `template.vue.html`,
  24074. scopeId = null,
  24075. optimizeImports = false,
  24076. runtimeGlobalName = `Vue`,
  24077. runtimeModuleName = `vue`,
  24078. ssrRuntimeModuleName = "vue/server-renderer",
  24079. ssr = false,
  24080. isTS = false,
  24081. inSSR = false
  24082. }) {
  24083. const context = {
  24084. mode,
  24085. prefixIdentifiers,
  24086. sourceMap,
  24087. filename,
  24088. scopeId,
  24089. optimizeImports,
  24090. runtimeGlobalName,
  24091. runtimeModuleName,
  24092. ssrRuntimeModuleName,
  24093. ssr,
  24094. isTS,
  24095. inSSR,
  24096. source: ast.source,
  24097. code: ``,
  24098. column: 1,
  24099. line: 1,
  24100. offset: 0,
  24101. indentLevel: 0,
  24102. pure: false,
  24103. map: void 0,
  24104. helper(key) {
  24105. return `_${helperNameMap[key]}`;
  24106. },
  24107. push(code, newlineIndex = -2 /* None */, node) {
  24108. context.code += code;
  24109. if (context.map) {
  24110. if (node) {
  24111. let name;
  24112. if (node.type === 4 && !node.isStatic) {
  24113. const content = node.content.replace(/^_ctx\./, "");
  24114. if (content !== node.content && isSimpleIdentifier(content)) {
  24115. name = content;
  24116. }
  24117. }
  24118. if (node.loc.source) {
  24119. addMapping(node.loc.start, name);
  24120. }
  24121. }
  24122. if (newlineIndex === -3 /* Unknown */) {
  24123. advancePositionWithMutation(context, code);
  24124. } else {
  24125. context.offset += code.length;
  24126. if (newlineIndex === -2 /* None */) {
  24127. context.column += code.length;
  24128. } else {
  24129. if (newlineIndex === -1 /* End */) {
  24130. newlineIndex = code.length - 1;
  24131. }
  24132. context.line++;
  24133. context.column = code.length - newlineIndex;
  24134. }
  24135. }
  24136. if (node && node.loc !== locStub && node.loc.source) {
  24137. addMapping(node.loc.end);
  24138. }
  24139. }
  24140. },
  24141. indent() {
  24142. newline(++context.indentLevel);
  24143. },
  24144. deindent(withoutNewLine = false) {
  24145. if (withoutNewLine) {
  24146. --context.indentLevel;
  24147. } else {
  24148. newline(--context.indentLevel);
  24149. }
  24150. },
  24151. newline() {
  24152. newline(context.indentLevel);
  24153. }
  24154. };
  24155. function newline(n) {
  24156. context.push("\n" + ` `.repeat(n), 0 /* Start */);
  24157. }
  24158. function addMapping(loc, name = null) {
  24159. const { _names, _mappings } = context.map;
  24160. if (name !== null && !_names.has(name)) _names.add(name);
  24161. _mappings.add({
  24162. originalLine: loc.line,
  24163. originalColumn: loc.column - 1,
  24164. // source-map column is 0 based
  24165. generatedLine: context.line,
  24166. generatedColumn: context.column - 1,
  24167. source: filename,
  24168. name
  24169. });
  24170. }
  24171. if (sourceMap) {
  24172. context.map = new sourceMapExports.SourceMapGenerator();
  24173. context.map.setSourceContent(filename, context.source);
  24174. context.map._sources.add(filename);
  24175. }
  24176. return context;
  24177. }
  24178. function generate(ast, options = {}) {
  24179. const context = createCodegenContext(ast, options);
  24180. if (options.onContextCreated) options.onContextCreated(context);
  24181. const {
  24182. mode,
  24183. push,
  24184. prefixIdentifiers,
  24185. indent,
  24186. deindent,
  24187. newline,
  24188. scopeId,
  24189. ssr
  24190. } = context;
  24191. const helpers = Array.from(ast.helpers);
  24192. const hasHelpers = helpers.length > 0;
  24193. const useWithBlock = !prefixIdentifiers && mode !== "module";
  24194. const genScopeId = scopeId != null && mode === "module";
  24195. const isSetupInlined = !!options.inline;
  24196. const preambleContext = isSetupInlined ? createCodegenContext(ast, options) : context;
  24197. if (mode === "module") {
  24198. genModulePreamble(ast, preambleContext, genScopeId, isSetupInlined);
  24199. } else {
  24200. genFunctionPreamble(ast, preambleContext);
  24201. }
  24202. const functionName = ssr ? `ssrRender` : `render`;
  24203. const args = ssr ? ["_ctx", "_push", "_parent", "_attrs"] : ["_ctx", "_cache"];
  24204. if (options.bindingMetadata && !options.inline) {
  24205. args.push("$props", "$setup", "$data", "$options");
  24206. }
  24207. const signature = options.isTS ? args.map((arg) => `${arg}: any`).join(",") : args.join(", ");
  24208. if (isSetupInlined) {
  24209. push(`(${signature}) => {`);
  24210. } else {
  24211. push(`function ${functionName}(${signature}) {`);
  24212. }
  24213. indent();
  24214. if (useWithBlock) {
  24215. push(`with (_ctx) {`);
  24216. indent();
  24217. if (hasHelpers) {
  24218. push(
  24219. `const { ${helpers.map(aliasHelper).join(", ")} } = _Vue
  24220. `,
  24221. -1 /* End */
  24222. );
  24223. newline();
  24224. }
  24225. }
  24226. if (ast.components.length) {
  24227. genAssets(ast.components, "component", context);
  24228. if (ast.directives.length || ast.temps > 0) {
  24229. newline();
  24230. }
  24231. }
  24232. if (ast.directives.length) {
  24233. genAssets(ast.directives, "directive", context);
  24234. if (ast.temps > 0) {
  24235. newline();
  24236. }
  24237. }
  24238. if (ast.temps > 0) {
  24239. push(`let `);
  24240. for (let i = 0; i < ast.temps; i++) {
  24241. push(`${i > 0 ? `, ` : ``}_temp${i}`);
  24242. }
  24243. }
  24244. if (ast.components.length || ast.directives.length || ast.temps) {
  24245. push(`
  24246. `, 0 /* Start */);
  24247. newline();
  24248. }
  24249. if (!ssr) {
  24250. push(`return `);
  24251. }
  24252. if (ast.codegenNode) {
  24253. genNode(ast.codegenNode, context);
  24254. } else {
  24255. push(`null`);
  24256. }
  24257. if (useWithBlock) {
  24258. deindent();
  24259. push(`}`);
  24260. }
  24261. deindent();
  24262. push(`}`);
  24263. return {
  24264. ast,
  24265. code: context.code,
  24266. preamble: isSetupInlined ? preambleContext.code : ``,
  24267. map: context.map ? context.map.toJSON() : void 0
  24268. };
  24269. }
  24270. function genFunctionPreamble(ast, context) {
  24271. const {
  24272. ssr,
  24273. prefixIdentifiers,
  24274. push,
  24275. newline,
  24276. runtimeModuleName,
  24277. runtimeGlobalName,
  24278. ssrRuntimeModuleName
  24279. } = context;
  24280. const VueBinding = ssr ? `require(${JSON.stringify(runtimeModuleName)})` : runtimeGlobalName;
  24281. const helpers = Array.from(ast.helpers);
  24282. if (helpers.length > 0) {
  24283. if (prefixIdentifiers) {
  24284. push(
  24285. `const { ${helpers.map(aliasHelper).join(", ")} } = ${VueBinding}
  24286. `,
  24287. -1 /* End */
  24288. );
  24289. } else {
  24290. push(`const _Vue = ${VueBinding}
  24291. `, -1 /* End */);
  24292. if (ast.hoists.length) {
  24293. const staticHelpers = [
  24294. CREATE_VNODE,
  24295. CREATE_ELEMENT_VNODE,
  24296. CREATE_COMMENT,
  24297. CREATE_TEXT,
  24298. CREATE_STATIC
  24299. ].filter((helper) => helpers.includes(helper)).map(aliasHelper).join(", ");
  24300. push(`const { ${staticHelpers} } = _Vue
  24301. `, -1 /* End */);
  24302. }
  24303. }
  24304. }
  24305. if (ast.ssrHelpers && ast.ssrHelpers.length) {
  24306. push(
  24307. `const { ${ast.ssrHelpers.map(aliasHelper).join(", ")} } = require("${ssrRuntimeModuleName}")
  24308. `,
  24309. -1 /* End */
  24310. );
  24311. }
  24312. genHoists(ast.hoists, context);
  24313. newline();
  24314. push(`return `);
  24315. }
  24316. function genModulePreamble(ast, context, genScopeId, inline) {
  24317. const {
  24318. push,
  24319. newline,
  24320. optimizeImports,
  24321. runtimeModuleName,
  24322. ssrRuntimeModuleName
  24323. } = context;
  24324. if (ast.helpers.size) {
  24325. const helpers = Array.from(ast.helpers);
  24326. if (optimizeImports) {
  24327. push(
  24328. `import { ${helpers.map((s) => helperNameMap[s]).join(", ")} } from ${JSON.stringify(runtimeModuleName)}
  24329. `,
  24330. -1 /* End */
  24331. );
  24332. push(
  24333. `
  24334. // Binding optimization for webpack code-split
  24335. const ${helpers.map((s) => `_${helperNameMap[s]} = ${helperNameMap[s]}`).join(", ")}
  24336. `,
  24337. -1 /* End */
  24338. );
  24339. } else {
  24340. push(
  24341. `import { ${helpers.map((s) => `${helperNameMap[s]} as _${helperNameMap[s]}`).join(", ")} } from ${JSON.stringify(runtimeModuleName)}
  24342. `,
  24343. -1 /* End */
  24344. );
  24345. }
  24346. }
  24347. if (ast.ssrHelpers && ast.ssrHelpers.length) {
  24348. push(
  24349. `import { ${ast.ssrHelpers.map((s) => `${helperNameMap[s]} as _${helperNameMap[s]}`).join(", ")} } from "${ssrRuntimeModuleName}"
  24350. `,
  24351. -1 /* End */
  24352. );
  24353. }
  24354. if (ast.imports.length) {
  24355. genImports(ast.imports, context);
  24356. newline();
  24357. }
  24358. genHoists(ast.hoists, context);
  24359. newline();
  24360. if (!inline) {
  24361. push(`export `);
  24362. }
  24363. }
  24364. function genAssets(assets, type, { helper, push, newline, isTS }) {
  24365. const resolver = helper(
  24366. type === "component" ? RESOLVE_COMPONENT : RESOLVE_DIRECTIVE
  24367. );
  24368. for (let i = 0; i < assets.length; i++) {
  24369. let id = assets[i];
  24370. const maybeSelfReference = id.endsWith("__self");
  24371. if (maybeSelfReference) {
  24372. id = id.slice(0, -6);
  24373. }
  24374. push(
  24375. `const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`
  24376. );
  24377. if (i < assets.length - 1) {
  24378. newline();
  24379. }
  24380. }
  24381. }
  24382. function genHoists(hoists, context) {
  24383. if (!hoists.length) {
  24384. return;
  24385. }
  24386. context.pure = true;
  24387. const { push, newline } = context;
  24388. newline();
  24389. for (let i = 0; i < hoists.length; i++) {
  24390. const exp = hoists[i];
  24391. if (exp) {
  24392. push(`const _hoisted_${i + 1} = `);
  24393. genNode(exp, context);
  24394. newline();
  24395. }
  24396. }
  24397. context.pure = false;
  24398. }
  24399. function genImports(importsOptions, context) {
  24400. if (!importsOptions.length) {
  24401. return;
  24402. }
  24403. importsOptions.forEach((imports) => {
  24404. context.push(`import `);
  24405. genNode(imports.exp, context);
  24406. context.push(` from '${imports.path}'`);
  24407. context.newline();
  24408. });
  24409. }
  24410. function isText(n) {
  24411. return isString$1(n) || n.type === 4 || n.type === 2 || n.type === 5 || n.type === 8;
  24412. }
  24413. function genNodeListAsArray(nodes, context) {
  24414. const multilines = nodes.length > 3 || nodes.some((n) => isArray$3(n) || !isText(n));
  24415. context.push(`[`);
  24416. multilines && context.indent();
  24417. genNodeList(nodes, context, multilines);
  24418. multilines && context.deindent();
  24419. context.push(`]`);
  24420. }
  24421. function genNodeList(nodes, context, multilines = false, comma = true) {
  24422. const { push, newline } = context;
  24423. for (let i = 0; i < nodes.length; i++) {
  24424. const node = nodes[i];
  24425. if (isString$1(node)) {
  24426. push(node, -3 /* Unknown */);
  24427. } else if (isArray$3(node)) {
  24428. genNodeListAsArray(node, context);
  24429. } else {
  24430. genNode(node, context);
  24431. }
  24432. if (i < nodes.length - 1) {
  24433. if (multilines) {
  24434. comma && push(",");
  24435. newline();
  24436. } else {
  24437. comma && push(", ");
  24438. }
  24439. }
  24440. }
  24441. }
  24442. function genNode(node, context) {
  24443. if (isString$1(node)) {
  24444. context.push(node, -3 /* Unknown */);
  24445. return;
  24446. }
  24447. if (isSymbol$1(node)) {
  24448. context.push(context.helper(node));
  24449. return;
  24450. }
  24451. switch (node.type) {
  24452. case 1:
  24453. case 9:
  24454. case 11:
  24455. assert(
  24456. node.codegenNode != null,
  24457. `Codegen node is missing for element/if/for node. Apply appropriate transforms first.`
  24458. );
  24459. genNode(node.codegenNode, context);
  24460. break;
  24461. case 2:
  24462. genText(node, context);
  24463. break;
  24464. case 4:
  24465. genExpression(node, context);
  24466. break;
  24467. case 5:
  24468. genInterpolation(node, context);
  24469. break;
  24470. case 12:
  24471. genNode(node.codegenNode, context);
  24472. break;
  24473. case 8:
  24474. genCompoundExpression(node, context);
  24475. break;
  24476. case 3:
  24477. genComment(node, context);
  24478. break;
  24479. case 13:
  24480. genVNodeCall(node, context);
  24481. break;
  24482. case 14:
  24483. genCallExpression(node, context);
  24484. break;
  24485. case 15:
  24486. genObjectExpression(node, context);
  24487. break;
  24488. case 17:
  24489. genArrayExpression(node, context);
  24490. break;
  24491. case 18:
  24492. genFunctionExpression(node, context);
  24493. break;
  24494. case 19:
  24495. genConditionalExpression(node, context);
  24496. break;
  24497. case 20:
  24498. genCacheExpression(node, context);
  24499. break;
  24500. case 21:
  24501. genNodeList(node.body, context, true, false);
  24502. break;
  24503. // SSR only types
  24504. case 22:
  24505. genTemplateLiteral(node, context);
  24506. break;
  24507. case 23:
  24508. genIfStatement(node, context);
  24509. break;
  24510. case 24:
  24511. genAssignmentExpression(node, context);
  24512. break;
  24513. case 25:
  24514. genSequenceExpression(node, context);
  24515. break;
  24516. case 26:
  24517. genReturnStatement(node, context);
  24518. break;
  24519. /* v8 ignore start */
  24520. case 10:
  24521. break;
  24522. default:
  24523. {
  24524. assert(false, `unhandled codegen node type: ${node.type}`);
  24525. const exhaustiveCheck = node;
  24526. return exhaustiveCheck;
  24527. }
  24528. }
  24529. }
  24530. function genText(node, context) {
  24531. context.push(JSON.stringify(node.content), -3 /* Unknown */, node);
  24532. }
  24533. function genExpression(node, context) {
  24534. const { content, isStatic } = node;
  24535. context.push(
  24536. isStatic ? JSON.stringify(content) : content,
  24537. -3 /* Unknown */,
  24538. node
  24539. );
  24540. }
  24541. function genInterpolation(node, context) {
  24542. const { push, helper, pure } = context;
  24543. if (pure) push(PURE_ANNOTATION);
  24544. push(`${helper(TO_DISPLAY_STRING)}(`);
  24545. genNode(node.content, context);
  24546. push(`)`);
  24547. }
  24548. function genCompoundExpression(node, context) {
  24549. for (let i = 0; i < node.children.length; i++) {
  24550. const child = node.children[i];
  24551. if (isString$1(child)) {
  24552. context.push(child, -3 /* Unknown */);
  24553. } else {
  24554. genNode(child, context);
  24555. }
  24556. }
  24557. }
  24558. function genExpressionAsPropertyKey(node, context) {
  24559. const { push } = context;
  24560. if (node.type === 8) {
  24561. push(`[`);
  24562. genCompoundExpression(node, context);
  24563. push(`]`);
  24564. } else if (node.isStatic) {
  24565. const text = isSimpleIdentifier(node.content) ? node.content : JSON.stringify(node.content);
  24566. push(text, -2 /* None */, node);
  24567. } else {
  24568. push(`[${node.content}]`, -3 /* Unknown */, node);
  24569. }
  24570. }
  24571. function genComment(node, context) {
  24572. const { push, helper, pure } = context;
  24573. if (pure) {
  24574. push(PURE_ANNOTATION);
  24575. }
  24576. push(
  24577. `${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`,
  24578. -3 /* Unknown */,
  24579. node
  24580. );
  24581. }
  24582. function genVNodeCall(node, context) {
  24583. const { push, helper, pure } = context;
  24584. const {
  24585. tag,
  24586. props,
  24587. children,
  24588. patchFlag,
  24589. dynamicProps,
  24590. directives,
  24591. isBlock,
  24592. disableTracking,
  24593. isComponent
  24594. } = node;
  24595. let patchFlagString;
  24596. if (patchFlag) {
  24597. {
  24598. if (patchFlag < 0) {
  24599. patchFlagString = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
  24600. } else {
  24601. const flagNames = Object.keys(PatchFlagNames).map(Number).filter((n) => n > 0 && patchFlag & n).map((n) => PatchFlagNames[n]).join(`, `);
  24602. patchFlagString = patchFlag + ` /* ${flagNames} */`;
  24603. }
  24604. }
  24605. }
  24606. if (directives) {
  24607. push(helper(WITH_DIRECTIVES) + `(`);
  24608. }
  24609. if (isBlock) {
  24610. push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
  24611. }
  24612. if (pure) {
  24613. push(PURE_ANNOTATION);
  24614. }
  24615. const callHelper = isBlock ? getVNodeBlockHelper(context.inSSR, isComponent) : getVNodeHelper(context.inSSR, isComponent);
  24616. push(helper(callHelper) + `(`, -2 /* None */, node);
  24617. genNodeList(
  24618. genNullableArgs([tag, props, children, patchFlagString, dynamicProps]),
  24619. context
  24620. );
  24621. push(`)`);
  24622. if (isBlock) {
  24623. push(`)`);
  24624. }
  24625. if (directives) {
  24626. push(`, `);
  24627. genNode(directives, context);
  24628. push(`)`);
  24629. }
  24630. }
  24631. function genNullableArgs(args) {
  24632. let i = args.length;
  24633. while (i--) {
  24634. if (args[i] != null) break;
  24635. }
  24636. return args.slice(0, i + 1).map((arg) => arg || `null`);
  24637. }
  24638. function genCallExpression(node, context) {
  24639. const { push, helper, pure } = context;
  24640. const callee = isString$1(node.callee) ? node.callee : helper(node.callee);
  24641. if (pure) {
  24642. push(PURE_ANNOTATION);
  24643. }
  24644. push(callee + `(`, -2 /* None */, node);
  24645. genNodeList(node.arguments, context);
  24646. push(`)`);
  24647. }
  24648. function genObjectExpression(node, context) {
  24649. const { push, indent, deindent, newline } = context;
  24650. const { properties } = node;
  24651. if (!properties.length) {
  24652. push(`{}`, -2 /* None */, node);
  24653. return;
  24654. }
  24655. const multilines = properties.length > 1 || properties.some((p) => p.value.type !== 4);
  24656. push(multilines ? `{` : `{ `);
  24657. multilines && indent();
  24658. for (let i = 0; i < properties.length; i++) {
  24659. const { key, value } = properties[i];
  24660. genExpressionAsPropertyKey(key, context);
  24661. push(`: `);
  24662. genNode(value, context);
  24663. if (i < properties.length - 1) {
  24664. push(`,`);
  24665. newline();
  24666. }
  24667. }
  24668. multilines && deindent();
  24669. push(multilines ? `}` : ` }`);
  24670. }
  24671. function genArrayExpression(node, context) {
  24672. genNodeListAsArray(node.elements, context);
  24673. }
  24674. function genFunctionExpression(node, context) {
  24675. const { push, indent, deindent } = context;
  24676. const { params, returns, body, newline, isSlot } = node;
  24677. if (isSlot) {
  24678. push(`_${helperNameMap[WITH_CTX]}(`);
  24679. }
  24680. push(`(`, -2 /* None */, node);
  24681. if (isArray$3(params)) {
  24682. genNodeList(params, context);
  24683. } else if (params) {
  24684. genNode(params, context);
  24685. }
  24686. push(`) => `);
  24687. if (newline || body) {
  24688. push(`{`);
  24689. indent();
  24690. }
  24691. if (returns) {
  24692. if (newline) {
  24693. push(`return `);
  24694. }
  24695. if (isArray$3(returns)) {
  24696. genNodeListAsArray(returns, context);
  24697. } else {
  24698. genNode(returns, context);
  24699. }
  24700. } else if (body) {
  24701. genNode(body, context);
  24702. }
  24703. if (newline || body) {
  24704. deindent();
  24705. push(`}`);
  24706. }
  24707. if (isSlot) {
  24708. push(`)`);
  24709. }
  24710. }
  24711. function genConditionalExpression(node, context) {
  24712. const { test, consequent, alternate, newline: needNewline } = node;
  24713. const { push, indent, deindent, newline } = context;
  24714. if (test.type === 4) {
  24715. const needsParens = !isSimpleIdentifier(test.content);
  24716. needsParens && push(`(`);
  24717. genExpression(test, context);
  24718. needsParens && push(`)`);
  24719. } else {
  24720. push(`(`);
  24721. genNode(test, context);
  24722. push(`)`);
  24723. }
  24724. needNewline && indent();
  24725. context.indentLevel++;
  24726. needNewline || push(` `);
  24727. push(`? `);
  24728. genNode(consequent, context);
  24729. context.indentLevel--;
  24730. needNewline && newline();
  24731. needNewline || push(` `);
  24732. push(`: `);
  24733. const isNested = alternate.type === 19;
  24734. if (!isNested) {
  24735. context.indentLevel++;
  24736. }
  24737. genNode(alternate, context);
  24738. if (!isNested) {
  24739. context.indentLevel--;
  24740. }
  24741. needNewline && deindent(
  24742. true
  24743. /* without newline */
  24744. );
  24745. }
  24746. function genCacheExpression(node, context) {
  24747. const { push, helper, indent, deindent, newline } = context;
  24748. const { needPauseTracking, needArraySpread } = node;
  24749. if (needArraySpread) {
  24750. push(`[...(`);
  24751. }
  24752. push(`_cache[${node.index}] || (`);
  24753. if (needPauseTracking) {
  24754. indent();
  24755. push(`${helper(SET_BLOCK_TRACKING)}(-1`);
  24756. if (node.inVOnce) push(`, true`);
  24757. push(`),`);
  24758. newline();
  24759. push(`(`);
  24760. }
  24761. push(`_cache[${node.index}] = `);
  24762. genNode(node.value, context);
  24763. if (needPauseTracking) {
  24764. push(`).cacheIndex = ${node.index},`);
  24765. newline();
  24766. push(`${helper(SET_BLOCK_TRACKING)}(1),`);
  24767. newline();
  24768. push(`_cache[${node.index}]`);
  24769. deindent();
  24770. }
  24771. push(`)`);
  24772. if (needArraySpread) {
  24773. push(`)]`);
  24774. }
  24775. }
  24776. function genTemplateLiteral(node, context) {
  24777. const { push, indent, deindent } = context;
  24778. push("`");
  24779. const l = node.elements.length;
  24780. const multilines = l > 3;
  24781. for (let i = 0; i < l; i++) {
  24782. const e = node.elements[i];
  24783. if (isString$1(e)) {
  24784. push(e.replace(/(`|\$|\\)/g, "\\$1"), -3 /* Unknown */);
  24785. } else {
  24786. push("${");
  24787. if (multilines) indent();
  24788. genNode(e, context);
  24789. if (multilines) deindent();
  24790. push("}");
  24791. }
  24792. }
  24793. push("`");
  24794. }
  24795. function genIfStatement(node, context) {
  24796. const { push, indent, deindent } = context;
  24797. const { test, consequent, alternate } = node;
  24798. push(`if (`);
  24799. genNode(test, context);
  24800. push(`) {`);
  24801. indent();
  24802. genNode(consequent, context);
  24803. deindent();
  24804. push(`}`);
  24805. if (alternate) {
  24806. push(` else `);
  24807. if (alternate.type === 23) {
  24808. genIfStatement(alternate, context);
  24809. } else {
  24810. push(`{`);
  24811. indent();
  24812. genNode(alternate, context);
  24813. deindent();
  24814. push(`}`);
  24815. }
  24816. }
  24817. }
  24818. function genAssignmentExpression(node, context) {
  24819. genNode(node.left, context);
  24820. context.push(` = `);
  24821. genNode(node.right, context);
  24822. }
  24823. function genSequenceExpression(node, context) {
  24824. context.push(`(`);
  24825. genNodeList(node.expressions, context);
  24826. context.push(`)`);
  24827. }
  24828. function genReturnStatement({ returns }, context) {
  24829. context.push(`return `);
  24830. if (isArray$3(returns)) {
  24831. genNodeListAsArray(returns, context);
  24832. } else {
  24833. genNode(returns, context);
  24834. }
  24835. }
  24836. const isLiteralWhitelisted = /* @__PURE__ */ makeMap("true,false,null,this");
  24837. const transformExpression = (node, context) => {
  24838. if (node.type === 5) {
  24839. node.content = processExpression(
  24840. node.content,
  24841. context
  24842. );
  24843. } else if (node.type === 1) {
  24844. const memo = findDir(node, "memo");
  24845. for (let i = 0; i < node.props.length; i++) {
  24846. const dir = node.props[i];
  24847. if (dir.type === 7 && dir.name !== "for") {
  24848. const exp = dir.exp;
  24849. const arg = dir.arg;
  24850. if (exp && exp.type === 4 && !(dir.name === "on" && arg) && // key has been processed in transformFor(vMemo + vFor)
  24851. !(memo && context.vForMemoKeyedNodes.has(node) && arg && arg.type === 4 && arg.content === "key")) {
  24852. dir.exp = processExpression(
  24853. exp,
  24854. context,
  24855. // slot args must be processed as function params
  24856. dir.name === "slot"
  24857. );
  24858. }
  24859. if (arg && arg.type === 4 && !arg.isStatic) {
  24860. dir.arg = processExpression(arg, context);
  24861. }
  24862. }
  24863. }
  24864. }
  24865. };
  24866. function processExpression(node, context, asParams = false, asRawStatements = false, localVars = Object.create(context.identifiers)) {
  24867. if (!context.prefixIdentifiers || !node.content.trim()) {
  24868. return node;
  24869. }
  24870. const { inline, bindingMetadata } = context;
  24871. const rewriteIdentifier = (raw, parent, id) => {
  24872. const type = hasOwn(bindingMetadata, raw) && bindingMetadata[raw];
  24873. if (inline) {
  24874. const isAssignmentLVal = parent && parent.type === "AssignmentExpression" && parent.left === id;
  24875. const isUpdateArg = parent && parent.type === "UpdateExpression" && parent.argument === id;
  24876. const isDestructureAssignment = parent && isInDestructureAssignment(parent, parentStack);
  24877. const isNewExpression = parent && isInNewExpression(parentStack);
  24878. const wrapWithUnref = (raw2) => {
  24879. const wrapped = `${context.helperString(UNREF)}(${raw2})`;
  24880. return isNewExpression ? `(${wrapped})` : wrapped;
  24881. };
  24882. if (isConst(type) || type === "setup-reactive-const" || localVars[raw]) {
  24883. return raw;
  24884. } else if (type === "setup-ref") {
  24885. return `${raw}.value`;
  24886. } else if (type === "setup-maybe-ref") {
  24887. return isAssignmentLVal || isUpdateArg || isDestructureAssignment ? `${raw}.value` : wrapWithUnref(raw);
  24888. } else if (type === "setup-let") {
  24889. if (isAssignmentLVal) {
  24890. const { right: rVal, operator } = parent;
  24891. const rExp = rawExp.slice(rVal.start - 1, rVal.end - 1);
  24892. const rExpString = stringifyExpression(
  24893. processExpression(
  24894. createSimpleExpression(rExp, false),
  24895. context,
  24896. false,
  24897. false,
  24898. knownIds
  24899. )
  24900. );
  24901. return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore
  24902. ` : ``} ? ${raw}.value ${operator} ${rExpString} : ${raw}`;
  24903. } else if (isUpdateArg) {
  24904. id.start = parent.start;
  24905. id.end = parent.end;
  24906. const { prefix: isPrefix, operator } = parent;
  24907. const prefix = isPrefix ? operator : ``;
  24908. const postfix = isPrefix ? `` : operator;
  24909. return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore
  24910. ` : ``} ? ${prefix}${raw}.value${postfix} : ${prefix}${raw}${postfix}`;
  24911. } else if (isDestructureAssignment) {
  24912. return raw;
  24913. } else {
  24914. return wrapWithUnref(raw);
  24915. }
  24916. } else if (type === "props") {
  24917. return genPropsAccessExp(raw);
  24918. } else if (type === "props-aliased") {
  24919. return genPropsAccessExp(bindingMetadata.__propsAliases[raw]);
  24920. }
  24921. } else {
  24922. if (type && type.startsWith("setup") || type === "literal-const") {
  24923. return `$setup.${raw}`;
  24924. } else if (type === "props-aliased") {
  24925. return `$props['${bindingMetadata.__propsAliases[raw]}']`;
  24926. } else if (type) {
  24927. return `$${type}.${raw}`;
  24928. }
  24929. }
  24930. return `_ctx.${raw}`;
  24931. };
  24932. const rawExp = node.content;
  24933. let ast = node.ast;
  24934. if (ast === false) {
  24935. return node;
  24936. }
  24937. if (ast === null || !ast && isSimpleIdentifier(rawExp)) {
  24938. const isScopeVarReference = context.identifiers[rawExp];
  24939. const isAllowedGlobal = isGloballyAllowed(rawExp);
  24940. const isLiteral = isLiteralWhitelisted(rawExp);
  24941. if (!asParams && !isScopeVarReference && !isLiteral && (!isAllowedGlobal || bindingMetadata[rawExp])) {
  24942. if (isConst(bindingMetadata[rawExp])) {
  24943. node.constType = 1;
  24944. }
  24945. node.content = rewriteIdentifier(rawExp);
  24946. } else if (!isScopeVarReference) {
  24947. if (isLiteral) {
  24948. node.constType = 3;
  24949. } else {
  24950. node.constType = 2;
  24951. }
  24952. }
  24953. return node;
  24954. }
  24955. if (!ast) {
  24956. const source = asRawStatements ? ` ${rawExp} ` : `(${rawExp})${asParams ? `=>{}` : ``}`;
  24957. try {
  24958. ast = libExports.parseExpression(source, {
  24959. sourceType: "module",
  24960. plugins: context.expressionPlugins
  24961. });
  24962. } catch (e) {
  24963. context.onError(
  24964. createCompilerError(
  24965. 46,
  24966. node.loc,
  24967. void 0,
  24968. e.message
  24969. )
  24970. );
  24971. return node;
  24972. }
  24973. }
  24974. const ids = [];
  24975. const parentStack = [];
  24976. const knownIds = Object.create(context.identifiers);
  24977. walkIdentifiers(
  24978. ast,
  24979. (node2, parent, _, isReferenced, isLocal) => {
  24980. if (isStaticPropertyKey(node2, parent)) {
  24981. return;
  24982. }
  24983. const needPrefix = isReferenced && canPrefix(node2);
  24984. if (needPrefix && !isLocal) {
  24985. if (isStaticProperty(parent) && parent.shorthand) {
  24986. node2.prefix = `${node2.name}: `;
  24987. }
  24988. node2.name = rewriteIdentifier(node2.name, parent, node2);
  24989. ids.push(node2);
  24990. } else {
  24991. if (!(needPrefix && isLocal) && (!parent || parent.type !== "CallExpression" && parent.type !== "NewExpression" && parent.type !== "MemberExpression")) {
  24992. node2.isConstant = true;
  24993. }
  24994. ids.push(node2);
  24995. }
  24996. },
  24997. true,
  24998. // invoke on ALL identifiers
  24999. parentStack,
  25000. knownIds
  25001. );
  25002. const children = [];
  25003. ids.sort((a, b) => a.start - b.start);
  25004. ids.forEach((id, i) => {
  25005. const start = id.start - 1;
  25006. const end = id.end - 1;
  25007. const last = ids[i - 1];
  25008. const leadingText = rawExp.slice(last ? last.end - 1 : 0, start);
  25009. if (leadingText.length || id.prefix) {
  25010. children.push(leadingText + (id.prefix || ``));
  25011. }
  25012. const source = rawExp.slice(start, end);
  25013. children.push(
  25014. createSimpleExpression(
  25015. id.name,
  25016. false,
  25017. {
  25018. start: advancePositionWithClone(node.loc.start, source, start),
  25019. end: advancePositionWithClone(node.loc.start, source, end),
  25020. source
  25021. },
  25022. id.isConstant ? 3 : 0
  25023. )
  25024. );
  25025. if (i === ids.length - 1 && end < rawExp.length) {
  25026. children.push(rawExp.slice(end));
  25027. }
  25028. });
  25029. let ret;
  25030. if (children.length) {
  25031. ret = createCompoundExpression(children, node.loc);
  25032. ret.ast = ast;
  25033. } else {
  25034. ret = node;
  25035. ret.constType = 3;
  25036. }
  25037. ret.identifiers = Object.keys(knownIds);
  25038. return ret;
  25039. }
  25040. function canPrefix(id) {
  25041. if (isGloballyAllowed(id.name)) {
  25042. return false;
  25043. }
  25044. if (id.name === "require") {
  25045. return false;
  25046. }
  25047. return true;
  25048. }
  25049. function stringifyExpression(exp) {
  25050. if (isString$1(exp)) {
  25051. return exp;
  25052. } else if (exp.type === 4) {
  25053. return exp.content;
  25054. } else {
  25055. return exp.children.map(stringifyExpression).join("");
  25056. }
  25057. }
  25058. function isConst(type) {
  25059. return type === "setup-const" || type === "literal-const";
  25060. }
  25061. const transformIf = createStructuralDirectiveTransform(
  25062. /^(?:if|else|else-if)$/,
  25063. (node, dir, context) => {
  25064. return processIf(node, dir, context, (ifNode, branch, isRoot) => {
  25065. const siblings = context.parent.children;
  25066. let i = siblings.indexOf(ifNode);
  25067. let key = 0;
  25068. while (i-- >= 0) {
  25069. const sibling = siblings[i];
  25070. if (sibling && sibling.type === 9) {
  25071. key += sibling.branches.length;
  25072. }
  25073. }
  25074. return () => {
  25075. if (isRoot) {
  25076. ifNode.codegenNode = createCodegenNodeForBranch(
  25077. branch,
  25078. key,
  25079. context
  25080. );
  25081. } else {
  25082. const parentCondition = getParentCondition(ifNode.codegenNode);
  25083. parentCondition.alternate = createCodegenNodeForBranch(
  25084. branch,
  25085. key + ifNode.branches.length - 1,
  25086. context
  25087. );
  25088. }
  25089. };
  25090. });
  25091. }
  25092. );
  25093. function processIf(node, dir, context, processCodegen) {
  25094. if (dir.name !== "else" && (!dir.exp || !dir.exp.content.trim())) {
  25095. const loc = dir.exp ? dir.exp.loc : node.loc;
  25096. context.onError(
  25097. createCompilerError(28, dir.loc)
  25098. );
  25099. dir.exp = createSimpleExpression(`true`, false, loc);
  25100. }
  25101. if (context.prefixIdentifiers && dir.exp) {
  25102. dir.exp = processExpression(dir.exp, context);
  25103. }
  25104. if (dir.name === "if") {
  25105. const branch = createIfBranch(node, dir);
  25106. const ifNode = {
  25107. type: 9,
  25108. loc: cloneLoc(node.loc),
  25109. branches: [branch]
  25110. };
  25111. context.replaceNode(ifNode);
  25112. if (processCodegen) {
  25113. return processCodegen(ifNode, branch, true);
  25114. }
  25115. } else {
  25116. const siblings = context.parent.children;
  25117. const comments = [];
  25118. let i = siblings.indexOf(node);
  25119. while (i-- >= -1) {
  25120. const sibling = siblings[i];
  25121. if (sibling && isCommentOrWhitespace(sibling)) {
  25122. context.removeNode(sibling);
  25123. if (sibling.type === 3) {
  25124. comments.unshift(sibling);
  25125. }
  25126. continue;
  25127. }
  25128. if (sibling && sibling.type === 9) {
  25129. if ((dir.name === "else-if" || dir.name === "else") && sibling.branches[sibling.branches.length - 1].condition === void 0) {
  25130. context.onError(
  25131. createCompilerError(30, node.loc)
  25132. );
  25133. }
  25134. context.removeNode();
  25135. const branch = createIfBranch(node, dir);
  25136. if (comments.length && // #3619 ignore comments if the v-if is direct child of <transition>
  25137. !(context.parent && context.parent.type === 1 && (context.parent.tag === "transition" || context.parent.tag === "Transition"))) {
  25138. branch.children = [...comments, ...branch.children];
  25139. }
  25140. {
  25141. const key = branch.userKey;
  25142. if (key) {
  25143. sibling.branches.forEach(({ userKey }) => {
  25144. if (isSameKey(userKey, key)) {
  25145. context.onError(
  25146. createCompilerError(
  25147. 29,
  25148. branch.userKey.loc
  25149. )
  25150. );
  25151. }
  25152. });
  25153. }
  25154. }
  25155. sibling.branches.push(branch);
  25156. const onExit = processCodegen && processCodegen(sibling, branch, false);
  25157. traverseNode(branch, context);
  25158. if (onExit) onExit();
  25159. context.currentNode = null;
  25160. } else {
  25161. context.onError(
  25162. createCompilerError(30, node.loc)
  25163. );
  25164. }
  25165. break;
  25166. }
  25167. }
  25168. }
  25169. function createIfBranch(node, dir) {
  25170. const isTemplateIf = node.tagType === 3;
  25171. return {
  25172. type: 10,
  25173. loc: node.loc,
  25174. condition: dir.name === "else" ? void 0 : dir.exp,
  25175. children: isTemplateIf && !findDir(node, "for") ? node.children : [node],
  25176. userKey: findProp(node, `key`),
  25177. isTemplateIf
  25178. };
  25179. }
  25180. function createCodegenNodeForBranch(branch, keyIndex, context) {
  25181. if (branch.condition) {
  25182. return createConditionalExpression(
  25183. branch.condition,
  25184. createChildrenCodegenNode(branch, keyIndex, context),
  25185. // make sure to pass in asBlock: true so that the comment node call
  25186. // closes the current block.
  25187. createCallExpression(context.helper(CREATE_COMMENT), [
  25188. '"v-if"' ,
  25189. "true"
  25190. ])
  25191. );
  25192. } else {
  25193. return createChildrenCodegenNode(branch, keyIndex, context);
  25194. }
  25195. }
  25196. function createChildrenCodegenNode(branch, keyIndex, context) {
  25197. const { helper } = context;
  25198. const keyProperty = createObjectProperty(
  25199. `key`,
  25200. createSimpleExpression(
  25201. `${keyIndex}`,
  25202. false,
  25203. locStub,
  25204. 2
  25205. )
  25206. );
  25207. const { children } = branch;
  25208. const firstChild = children[0];
  25209. const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1;
  25210. if (needFragmentWrapper) {
  25211. if (children.length === 1 && firstChild.type === 11) {
  25212. const vnodeCall = firstChild.codegenNode;
  25213. injectProp(vnodeCall, keyProperty, context);
  25214. return vnodeCall;
  25215. } else {
  25216. let patchFlag = 64;
  25217. if (!branch.isTemplateIf && children.filter((c) => c.type !== 3).length === 1) {
  25218. patchFlag |= 2048;
  25219. }
  25220. return createVNodeCall(
  25221. context,
  25222. helper(FRAGMENT),
  25223. createObjectExpression([keyProperty]),
  25224. children,
  25225. patchFlag,
  25226. void 0,
  25227. void 0,
  25228. true,
  25229. false,
  25230. false,
  25231. branch.loc
  25232. );
  25233. }
  25234. } else {
  25235. const ret = firstChild.codegenNode;
  25236. const vnodeCall = getMemoedVNodeCall(ret);
  25237. if (vnodeCall.type === 13) {
  25238. convertToBlock(vnodeCall, context);
  25239. }
  25240. injectProp(vnodeCall, keyProperty, context);
  25241. return ret;
  25242. }
  25243. }
  25244. function isSameKey(a, b) {
  25245. if (!a || a.type !== b.type) {
  25246. return false;
  25247. }
  25248. if (a.type === 6) {
  25249. if (a.value.content !== b.value.content) {
  25250. return false;
  25251. }
  25252. } else {
  25253. const exp = a.exp;
  25254. const branchExp = b.exp;
  25255. if (exp.type !== branchExp.type) {
  25256. return false;
  25257. }
  25258. if (exp.type !== 4 || exp.isStatic !== branchExp.isStatic || exp.content !== branchExp.content) {
  25259. return false;
  25260. }
  25261. }
  25262. return true;
  25263. }
  25264. function getParentCondition(node) {
  25265. while (true) {
  25266. if (node.type === 19) {
  25267. if (node.alternate.type === 19) {
  25268. node = node.alternate;
  25269. } else {
  25270. return node;
  25271. }
  25272. } else if (node.type === 20) {
  25273. node = node.value;
  25274. }
  25275. }
  25276. }
  25277. const transformFor = createStructuralDirectiveTransform(
  25278. "for",
  25279. (node, dir, context) => {
  25280. const { helper, removeHelper } = context;
  25281. return processFor(node, dir, context, (forNode) => {
  25282. const renderExp = createCallExpression(helper(RENDER_LIST), [
  25283. forNode.source
  25284. ]);
  25285. const isTemplate = isTemplateNode(node);
  25286. const memo = findDir(node, "memo");
  25287. const keyProp = findProp(node, `key`, false, true);
  25288. const isDirKey = keyProp && keyProp.type === 7;
  25289. let keyExp = keyProp && (keyProp.type === 6 ? keyProp.value ? createSimpleExpression(keyProp.value.content, true) : void 0 : keyProp.exp);
  25290. const keyProperty = keyExp ? createObjectProperty(`key`, keyExp) : null;
  25291. {
  25292. if (isTemplate && memo) {
  25293. memo.exp = processExpression(
  25294. memo.exp,
  25295. context
  25296. );
  25297. }
  25298. if ((isTemplate || memo) && keyProperty && isDirKey) {
  25299. keyExp = keyProp.exp = keyProperty.value = processExpression(
  25300. keyProperty.value,
  25301. context
  25302. );
  25303. if (memo) {
  25304. context.vForMemoKeyedNodes.add(node);
  25305. }
  25306. }
  25307. }
  25308. const isStableFragment = forNode.source.type === 4 && forNode.source.constType > 0;
  25309. const fragmentFlag = isStableFragment ? 64 : keyProp ? 128 : 256;
  25310. forNode.codegenNode = createVNodeCall(
  25311. context,
  25312. helper(FRAGMENT),
  25313. void 0,
  25314. renderExp,
  25315. fragmentFlag,
  25316. void 0,
  25317. void 0,
  25318. true,
  25319. !isStableFragment,
  25320. false,
  25321. node.loc
  25322. );
  25323. return () => {
  25324. var _a;
  25325. let childBlock;
  25326. const { children } = forNode;
  25327. if (isTemplate) {
  25328. node.children.some((c) => {
  25329. if (c.type === 1) {
  25330. const key = findProp(c, "key");
  25331. if (key) {
  25332. context.onError(
  25333. createCompilerError(
  25334. 33,
  25335. key.loc
  25336. )
  25337. );
  25338. return true;
  25339. }
  25340. }
  25341. });
  25342. }
  25343. const needFragmentWrapper = children.length !== 1 || children[0].type !== 1;
  25344. const slotOutlet = isSlotOutlet(node) ? node : isTemplate && node.children.length === 1 && isSlotOutlet(node.children[0]) ? node.children[0] : null;
  25345. if (slotOutlet) {
  25346. childBlock = slotOutlet.codegenNode;
  25347. if (isTemplate && keyProperty) {
  25348. injectProp(childBlock, keyProperty, context);
  25349. }
  25350. } else if (needFragmentWrapper) {
  25351. childBlock = createVNodeCall(
  25352. context,
  25353. helper(FRAGMENT),
  25354. keyProperty ? createObjectExpression([keyProperty]) : void 0,
  25355. node.children,
  25356. 64,
  25357. void 0,
  25358. void 0,
  25359. true,
  25360. void 0,
  25361. false
  25362. );
  25363. } else {
  25364. childBlock = children[0].codegenNode;
  25365. if (isTemplate && keyProperty) {
  25366. injectProp(childBlock, keyProperty, context);
  25367. }
  25368. const shouldUseBlock = !isStableFragment || childBlock.isBlockRequired === true;
  25369. if (childBlock.isBlock !== shouldUseBlock) {
  25370. if (childBlock.isBlock) {
  25371. removeHelper(OPEN_BLOCK);
  25372. removeHelper(
  25373. getVNodeBlockHelper(context.inSSR, childBlock.isComponent)
  25374. );
  25375. } else {
  25376. removeHelper(
  25377. getVNodeHelper(context.inSSR, childBlock.isComponent)
  25378. );
  25379. }
  25380. }
  25381. childBlock.isBlock = shouldUseBlock;
  25382. if (childBlock.isBlock) {
  25383. helper(OPEN_BLOCK);
  25384. helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  25385. } else {
  25386. helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  25387. if (childBlock.needsPatch) {
  25388. childBlock.patchFlag = ((_a = childBlock.patchFlag) != null ? _a : 0) | 512;
  25389. }
  25390. }
  25391. }
  25392. if (memo) {
  25393. const loop = createFunctionExpression(
  25394. createForLoopParams(forNode.parseResult, [
  25395. createSimpleExpression(`_cached`)
  25396. ])
  25397. );
  25398. loop.body = createBlockStatement([
  25399. createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
  25400. createCompoundExpression([
  25401. `if (_cached && _cached.el`,
  25402. ...keyExp ? [` && _cached.key === `, keyExp] : [],
  25403. ` && ${context.helperString(
  25404. IS_MEMO_SAME
  25405. )}(_cached, _memo)) return _cached`
  25406. ]),
  25407. createCompoundExpression([`const _item = `, childBlock]),
  25408. createSimpleExpression(`_item.memo = _memo`),
  25409. createSimpleExpression(`return _item`)
  25410. ]);
  25411. renderExp.arguments.push(
  25412. loop,
  25413. createSimpleExpression(`_cache`),
  25414. createSimpleExpression(String(context.cached.length))
  25415. );
  25416. context.cached.push(null);
  25417. } else {
  25418. renderExp.arguments.push(
  25419. createFunctionExpression(
  25420. createForLoopParams(forNode.parseResult),
  25421. childBlock,
  25422. true
  25423. )
  25424. );
  25425. }
  25426. };
  25427. });
  25428. }
  25429. );
  25430. function processFor(node, dir, context, processCodegen) {
  25431. if (!dir.exp) {
  25432. context.onError(
  25433. createCompilerError(31, dir.loc)
  25434. );
  25435. return;
  25436. }
  25437. const parseResult = dir.forParseResult;
  25438. if (!parseResult) {
  25439. context.onError(
  25440. createCompilerError(32, dir.loc)
  25441. );
  25442. return;
  25443. }
  25444. finalizeForParseResult(parseResult, context);
  25445. const { addIdentifiers, removeIdentifiers, scopes } = context;
  25446. const { source, value, key, index } = parseResult;
  25447. const forNode = {
  25448. type: 11,
  25449. loc: dir.loc,
  25450. source,
  25451. valueAlias: value,
  25452. keyAlias: key,
  25453. objectIndexAlias: index,
  25454. parseResult,
  25455. children: isTemplateNode(node) ? node.children : [node]
  25456. };
  25457. context.replaceNode(forNode);
  25458. scopes.vFor++;
  25459. if (context.prefixIdentifiers) {
  25460. value && addIdentifiers(value);
  25461. key && addIdentifiers(key);
  25462. index && addIdentifiers(index);
  25463. }
  25464. const onExit = processCodegen && processCodegen(forNode);
  25465. return () => {
  25466. scopes.vFor--;
  25467. if (context.prefixIdentifiers) {
  25468. value && removeIdentifiers(value);
  25469. key && removeIdentifiers(key);
  25470. index && removeIdentifiers(index);
  25471. }
  25472. if (onExit) onExit();
  25473. };
  25474. }
  25475. function finalizeForParseResult(result, context) {
  25476. if (result.finalized) return;
  25477. if (context.prefixIdentifiers) {
  25478. result.source = processExpression(
  25479. result.source,
  25480. context
  25481. );
  25482. if (result.key) {
  25483. result.key = processExpression(
  25484. result.key,
  25485. context,
  25486. true
  25487. );
  25488. }
  25489. if (result.index) {
  25490. result.index = processExpression(
  25491. result.index,
  25492. context,
  25493. true
  25494. );
  25495. }
  25496. if (result.value) {
  25497. result.value = processExpression(
  25498. result.value,
  25499. context,
  25500. true
  25501. );
  25502. }
  25503. }
  25504. result.finalized = true;
  25505. }
  25506. function createForLoopParams({ value, key, index }, memoArgs = []) {
  25507. return createParamsList([value, key, index, ...memoArgs]);
  25508. }
  25509. function createParamsList(args) {
  25510. let i = args.length;
  25511. while (i--) {
  25512. if (args[i]) break;
  25513. }
  25514. return args.slice(0, i + 1).map((arg, i2) => arg || createSimpleExpression(`_`.repeat(i2 + 1), false));
  25515. }
  25516. const defaultFallback = createSimpleExpression(`undefined`, false);
  25517. const trackSlotScopes = (node, context) => {
  25518. if (node.type === 1 && (node.tagType === 1 || node.tagType === 3)) {
  25519. const vSlot = findDir(node, "slot");
  25520. if (vSlot) {
  25521. const slotProps = vSlot.exp;
  25522. if (context.prefixIdentifiers) {
  25523. slotProps && context.addIdentifiers(slotProps);
  25524. }
  25525. context.scopes.vSlot++;
  25526. return () => {
  25527. if (context.prefixIdentifiers) {
  25528. slotProps && context.removeIdentifiers(slotProps);
  25529. }
  25530. context.scopes.vSlot--;
  25531. };
  25532. }
  25533. }
  25534. };
  25535. const trackVForSlotScopes = (node, context) => {
  25536. let vFor;
  25537. if (isTemplateNode(node) && node.props.some(isVSlot) && (vFor = findDir(node, "for"))) {
  25538. const result = vFor.forParseResult;
  25539. if (result) {
  25540. finalizeForParseResult(result, context);
  25541. const { value, key, index } = result;
  25542. const { addIdentifiers, removeIdentifiers } = context;
  25543. value && addIdentifiers(value);
  25544. key && addIdentifiers(key);
  25545. index && addIdentifiers(index);
  25546. return () => {
  25547. value && removeIdentifiers(value);
  25548. key && removeIdentifiers(key);
  25549. index && removeIdentifiers(index);
  25550. };
  25551. }
  25552. }
  25553. };
  25554. const buildClientSlotFn = (props, _vForExp, children, loc) => createFunctionExpression(
  25555. props,
  25556. children,
  25557. false,
  25558. true,
  25559. children.length ? children[0].loc : loc
  25560. );
  25561. function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
  25562. context.helper(WITH_CTX);
  25563. const { children, loc } = node;
  25564. const slotsProperties = [];
  25565. const dynamicSlots = [];
  25566. let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
  25567. if (!context.ssr && context.prefixIdentifiers) {
  25568. hasDynamicSlots = node.props.some(
  25569. (prop) => isVSlot(prop) && (hasScopeRef(prop.arg, context.identifiers) || hasScopeRef(prop.exp, context.identifiers))
  25570. ) || children.some((child) => hasScopeRef(child, context.identifiers));
  25571. }
  25572. const onComponentSlot = findDir(node, "slot", true);
  25573. if (onComponentSlot) {
  25574. const { arg, exp } = onComponentSlot;
  25575. if (arg && !isStaticExp(arg)) {
  25576. hasDynamicSlots = true;
  25577. }
  25578. slotsProperties.push(
  25579. createObjectProperty(
  25580. arg || createSimpleExpression("default", true),
  25581. buildSlotFn(exp, void 0, children, loc)
  25582. )
  25583. );
  25584. }
  25585. let hasTemplateSlots = false;
  25586. let hasNamedDefaultSlot = false;
  25587. const implicitDefaultChildren = [];
  25588. const seenSlotNames = /* @__PURE__ */ new Set();
  25589. let conditionalBranchIndex = 0;
  25590. for (let i = 0; i < children.length; i++) {
  25591. const slotElement = children[i];
  25592. let slotDir;
  25593. if (!isTemplateNode(slotElement) || !(slotDir = findDir(slotElement, "slot", true))) {
  25594. if (slotElement.type !== 3) {
  25595. implicitDefaultChildren.push(slotElement);
  25596. }
  25597. continue;
  25598. }
  25599. if (onComponentSlot) {
  25600. context.onError(
  25601. createCompilerError(37, slotDir.loc)
  25602. );
  25603. break;
  25604. }
  25605. hasTemplateSlots = true;
  25606. const { children: slotChildren, loc: slotLoc } = slotElement;
  25607. const {
  25608. arg: slotName = createSimpleExpression(`default`, true),
  25609. exp: slotProps,
  25610. loc: dirLoc
  25611. } = slotDir;
  25612. let staticSlotName;
  25613. if (isStaticExp(slotName)) {
  25614. staticSlotName = slotName ? slotName.content : `default`;
  25615. } else {
  25616. hasDynamicSlots = true;
  25617. }
  25618. const vFor = findDir(slotElement, "for");
  25619. const slotFunction = buildSlotFn(slotProps, vFor, slotChildren, slotLoc);
  25620. let vIf;
  25621. let vElse;
  25622. if (vIf = findDir(slotElement, "if")) {
  25623. hasDynamicSlots = true;
  25624. dynamicSlots.push(
  25625. createConditionalExpression(
  25626. vIf.exp,
  25627. buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++),
  25628. defaultFallback
  25629. )
  25630. );
  25631. } else if (vElse = findDir(
  25632. slotElement,
  25633. /^else(?:-if)?$/,
  25634. true
  25635. /* allowEmpty */
  25636. )) {
  25637. let j = i;
  25638. let prev;
  25639. while (j--) {
  25640. prev = children[j];
  25641. if (!isCommentOrWhitespace(prev)) {
  25642. break;
  25643. }
  25644. }
  25645. if (prev && isTemplateNode(prev) && findDir(prev, /^(?:else-)?if$/)) {
  25646. let conditional = dynamicSlots[dynamicSlots.length - 1];
  25647. while (conditional.alternate.type === 19) {
  25648. conditional = conditional.alternate;
  25649. }
  25650. conditional.alternate = vElse.exp ? createConditionalExpression(
  25651. vElse.exp,
  25652. buildDynamicSlot(
  25653. slotName,
  25654. slotFunction,
  25655. conditionalBranchIndex++
  25656. ),
  25657. defaultFallback
  25658. ) : buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++);
  25659. } else {
  25660. context.onError(
  25661. createCompilerError(30, vElse.loc)
  25662. );
  25663. }
  25664. } else if (vFor) {
  25665. hasDynamicSlots = true;
  25666. const parseResult = vFor.forParseResult;
  25667. if (parseResult) {
  25668. finalizeForParseResult(parseResult, context);
  25669. dynamicSlots.push(
  25670. createCallExpression(context.helper(RENDER_LIST), [
  25671. parseResult.source,
  25672. createFunctionExpression(
  25673. createForLoopParams(parseResult),
  25674. buildDynamicSlot(slotName, slotFunction),
  25675. true
  25676. )
  25677. ])
  25678. );
  25679. } else {
  25680. context.onError(
  25681. createCompilerError(
  25682. 32,
  25683. vFor.loc
  25684. )
  25685. );
  25686. }
  25687. } else {
  25688. if (staticSlotName) {
  25689. if (seenSlotNames.has(staticSlotName)) {
  25690. context.onError(
  25691. createCompilerError(
  25692. 38,
  25693. dirLoc
  25694. )
  25695. );
  25696. continue;
  25697. }
  25698. seenSlotNames.add(staticSlotName);
  25699. if (staticSlotName === "default") {
  25700. hasNamedDefaultSlot = true;
  25701. }
  25702. }
  25703. slotsProperties.push(createObjectProperty(slotName, slotFunction));
  25704. }
  25705. }
  25706. if (!onComponentSlot) {
  25707. const buildDefaultSlotProperty = (props, children2) => {
  25708. const fn = buildSlotFn(props, void 0, children2, loc);
  25709. return createObjectProperty(`default`, fn);
  25710. };
  25711. if (!hasTemplateSlots) {
  25712. slotsProperties.push(buildDefaultSlotProperty(void 0, children));
  25713. } else if (implicitDefaultChildren.length && // #3766
  25714. // with whitespace: 'preserve', whitespaces between slots will end up in
  25715. // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
  25716. !implicitDefaultChildren.every(isWhitespaceText)) {
  25717. if (hasNamedDefaultSlot) {
  25718. context.onError(
  25719. createCompilerError(
  25720. 39,
  25721. implicitDefaultChildren[0].loc
  25722. )
  25723. );
  25724. } else {
  25725. slotsProperties.push(
  25726. buildDefaultSlotProperty(void 0, implicitDefaultChildren)
  25727. );
  25728. }
  25729. }
  25730. }
  25731. const slotFlag = hasDynamicSlots ? 2 : hasForwardedSlots(node.children) ? 3 : 1;
  25732. let slots = createObjectExpression(
  25733. slotsProperties.concat(
  25734. createObjectProperty(
  25735. `_`,
  25736. // 2 = compiled but dynamic = can skip normalization, but must run diff
  25737. // 1 = compiled and static = can skip normalization AND diff as optimized
  25738. createSimpleExpression(
  25739. slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ),
  25740. false
  25741. )
  25742. )
  25743. ),
  25744. loc
  25745. );
  25746. if (dynamicSlots.length) {
  25747. slots = createCallExpression(context.helper(CREATE_SLOTS), [
  25748. slots,
  25749. createArrayExpression(dynamicSlots)
  25750. ]);
  25751. }
  25752. return {
  25753. slots,
  25754. hasDynamicSlots
  25755. };
  25756. }
  25757. function buildDynamicSlot(name, fn, index) {
  25758. const props = [
  25759. createObjectProperty(`name`, name),
  25760. createObjectProperty(`fn`, fn)
  25761. ];
  25762. if (index != null) {
  25763. props.push(
  25764. createObjectProperty(`key`, createSimpleExpression(String(index), true))
  25765. );
  25766. }
  25767. return createObjectExpression(props);
  25768. }
  25769. function hasForwardedSlots(children) {
  25770. for (let i = 0; i < children.length; i++) {
  25771. const child = children[i];
  25772. switch (child.type) {
  25773. case 1:
  25774. if (child.tagType === 2 || hasForwardedSlots(child.children)) {
  25775. return true;
  25776. }
  25777. break;
  25778. case 9:
  25779. if (hasForwardedSlots(child.branches)) return true;
  25780. break;
  25781. case 10:
  25782. case 11:
  25783. if (hasForwardedSlots(child.children)) return true;
  25784. break;
  25785. }
  25786. }
  25787. return false;
  25788. }
  25789. const directiveImportMap = /* @__PURE__ */ new WeakMap();
  25790. const transformElement = (node, context) => {
  25791. return function postTransformElement() {
  25792. node = context.currentNode;
  25793. if (!(node.type === 1 && (node.tagType === 0 || node.tagType === 1))) {
  25794. return;
  25795. }
  25796. const { tag, props } = node;
  25797. const isComponent = node.tagType === 1;
  25798. let vnodeTag = isComponent ? resolveComponentType(node, context) : `"${tag}"`;
  25799. const isDynamicComponent = isObject$2(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
  25800. let vnodeProps;
  25801. let vnodeChildren;
  25802. let patchFlag = 0;
  25803. let vnodeDynamicProps;
  25804. let dynamicPropNames;
  25805. let vnodeDirectives;
  25806. let needsPatch = false;
  25807. let isBlockRequired = false;
  25808. let shouldUseBlock = (
  25809. // dynamic component may resolve to plain elements
  25810. isDynamicComponent || vnodeTag === TELEPORT || vnodeTag === SUSPENSE || !isComponent && // <svg> and <foreignObject> must be forced into blocks so that block
  25811. // updates inside get proper isSVG flag at runtime. (#639, #643)
  25812. // This is technically web-specific, but splitting the logic out of core
  25813. // leads to too much unnecessary complexity.
  25814. (tag === "svg" || tag === "foreignObject" || tag === "math")
  25815. );
  25816. if (props.length > 0) {
  25817. const propsBuildResult = buildProps(
  25818. node,
  25819. context,
  25820. void 0,
  25821. isComponent,
  25822. isDynamicComponent
  25823. );
  25824. vnodeProps = propsBuildResult.props;
  25825. patchFlag = propsBuildResult.patchFlag;
  25826. dynamicPropNames = propsBuildResult.dynamicPropNames;
  25827. needsPatch = propsBuildResult.needsPatch;
  25828. isBlockRequired = propsBuildResult.isBlockRequired;
  25829. const directives = propsBuildResult.directives;
  25830. vnodeDirectives = directives && directives.length ? createArrayExpression(
  25831. directives.map((dir) => buildDirectiveArgs(dir, context))
  25832. ) : void 0;
  25833. if (propsBuildResult.shouldUseBlock) {
  25834. shouldUseBlock = true;
  25835. }
  25836. }
  25837. if (node.children.length > 0) {
  25838. if (vnodeTag === KEEP_ALIVE) {
  25839. shouldUseBlock = true;
  25840. patchFlag |= 1024;
  25841. if (node.children.length > 1) {
  25842. context.onError(
  25843. createCompilerError(47, {
  25844. start: node.children[0].loc.start,
  25845. end: node.children[node.children.length - 1].loc.end,
  25846. source: ""
  25847. })
  25848. );
  25849. }
  25850. }
  25851. const shouldBuildAsSlots = isComponent && // Teleport is not a real component and has dedicated runtime handling
  25852. vnodeTag !== TELEPORT && // explained above.
  25853. vnodeTag !== KEEP_ALIVE;
  25854. if (shouldBuildAsSlots) {
  25855. const { slots, hasDynamicSlots } = buildSlots(node, context);
  25856. vnodeChildren = slots;
  25857. if (hasDynamicSlots) {
  25858. patchFlag |= 1024;
  25859. }
  25860. } else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
  25861. const child = node.children[0];
  25862. const type = child.type;
  25863. const hasDynamicTextChild = type === 5 || type === 8;
  25864. if (hasDynamicTextChild && getConstantType(child, context) === 0) {
  25865. patchFlag |= 1;
  25866. }
  25867. if (hasDynamicTextChild || type === 2) {
  25868. vnodeChildren = child;
  25869. } else {
  25870. vnodeChildren = node.children;
  25871. }
  25872. } else {
  25873. vnodeChildren = node.children;
  25874. }
  25875. }
  25876. if (dynamicPropNames && dynamicPropNames.length) {
  25877. vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
  25878. }
  25879. const vnodeCall = node.codegenNode = createVNodeCall(
  25880. context,
  25881. vnodeTag,
  25882. vnodeProps,
  25883. vnodeChildren,
  25884. patchFlag === 0 ? void 0 : patchFlag,
  25885. vnodeDynamicProps,
  25886. vnodeDirectives,
  25887. !!shouldUseBlock,
  25888. false,
  25889. isComponent,
  25890. node.loc
  25891. );
  25892. needsPatch = needsPatch && (patchFlag === 0 || patchFlag === 32);
  25893. if (needsPatch) {
  25894. vnodeCall.needsPatch = true;
  25895. }
  25896. if (isBlockRequired) {
  25897. vnodeCall.isBlockRequired = true;
  25898. }
  25899. };
  25900. };
  25901. function resolveComponentType(node, context, ssr = false) {
  25902. let { tag } = node;
  25903. const isExplicitDynamic = isComponentTag(tag);
  25904. const isProp = findProp(
  25905. node,
  25906. "is",
  25907. false,
  25908. true
  25909. /* allow empty */
  25910. );
  25911. if (isProp) {
  25912. if (isExplicitDynamic || false) {
  25913. let exp;
  25914. if (isProp.type === 6) {
  25915. exp = isProp.value && createSimpleExpression(isProp.value.content, true);
  25916. } else {
  25917. exp = isProp.exp;
  25918. if (!exp) {
  25919. exp = createSimpleExpression(`is`, false, isProp.arg.loc);
  25920. {
  25921. exp = isProp.exp = processExpression(exp, context);
  25922. }
  25923. }
  25924. }
  25925. if (exp) {
  25926. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  25927. exp
  25928. ]);
  25929. }
  25930. } else if (isProp.type === 6 && isProp.value.content.startsWith("vue:")) {
  25931. tag = isProp.value.content.slice(4);
  25932. }
  25933. }
  25934. const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
  25935. if (builtIn) {
  25936. if (!ssr) context.helper(builtIn);
  25937. return builtIn;
  25938. }
  25939. {
  25940. const fromSetup = resolveSetupReference(tag, context);
  25941. if (fromSetup) {
  25942. return fromSetup;
  25943. }
  25944. const dotIndex = tag.indexOf(".");
  25945. if (dotIndex > 0) {
  25946. const ns = resolveSetupReference(tag.slice(0, dotIndex), context);
  25947. if (ns) {
  25948. return ns + tag.slice(dotIndex);
  25949. }
  25950. }
  25951. }
  25952. if (context.selfName && capitalize(camelize(tag)) === context.selfName) {
  25953. context.helper(RESOLVE_COMPONENT);
  25954. context.components.add(tag + `__self`);
  25955. return toValidAssetId(tag, `component`);
  25956. }
  25957. context.helper(RESOLVE_COMPONENT);
  25958. context.components.add(tag);
  25959. return toValidAssetId(tag, `component`);
  25960. }
  25961. function resolveSetupReference(name, context) {
  25962. const bindings = context.bindingMetadata;
  25963. if (!bindings || bindings.__isScriptSetup === false) {
  25964. return;
  25965. }
  25966. const camelName = camelize(name);
  25967. const PascalName = capitalize(camelName);
  25968. const checkType = (type) => {
  25969. if (bindings[name] === type) {
  25970. return name;
  25971. }
  25972. if (bindings[camelName] === type) {
  25973. return camelName;
  25974. }
  25975. if (bindings[PascalName] === type) {
  25976. return PascalName;
  25977. }
  25978. };
  25979. const fromConst = checkType("setup-const") || checkType("setup-reactive-const") || checkType("literal-const");
  25980. if (fromConst) {
  25981. return context.inline ? (
  25982. // in inline mode, const setup bindings (e.g. imports) can be used as-is
  25983. fromConst
  25984. ) : `$setup[${JSON.stringify(fromConst)}]`;
  25985. }
  25986. const fromMaybeRef = checkType("setup-let") || checkType("setup-ref") || checkType("setup-maybe-ref");
  25987. if (fromMaybeRef) {
  25988. return context.inline ? (
  25989. // setup scope bindings that may be refs need to be unrefed
  25990. `${context.helperString(UNREF)}(${fromMaybeRef})`
  25991. ) : `$setup[${JSON.stringify(fromMaybeRef)}]`;
  25992. }
  25993. const fromProps = checkType("props");
  25994. if (fromProps) {
  25995. return `${context.helperString(UNREF)}(${context.inline ? "__props" : "$props"}[${JSON.stringify(fromProps)}])`;
  25996. }
  25997. }
  25998. function buildProps(node, context, props = node.props, isComponent, isDynamicComponent, ssr = false) {
  25999. const { tag, loc: elementLoc, children } = node;
  26000. let properties = [];
  26001. const mergeArgs = [];
  26002. const runtimeDirectives = [];
  26003. const hasChildren = children.length > 0;
  26004. let shouldUseBlock = false;
  26005. let isBlockRequired = false;
  26006. let patchFlag = 0;
  26007. let hasRef = false;
  26008. let hasClassBinding = false;
  26009. let hasStyleBinding = false;
  26010. let hasHydrationEventBinding = false;
  26011. let hasDynamicKeys = false;
  26012. let hasVnodeHook = false;
  26013. const dynamicPropNames = [];
  26014. const pushMergeArg = (arg) => {
  26015. if (properties.length) {
  26016. mergeArgs.push(
  26017. createObjectExpression(dedupeProperties(properties), elementLoc)
  26018. );
  26019. properties = [];
  26020. }
  26021. if (arg) mergeArgs.push(arg);
  26022. };
  26023. const pushRefVForMarker = () => {
  26024. if (context.scopes.vFor > 0) {
  26025. properties.push(
  26026. createObjectProperty(
  26027. createSimpleExpression("ref_for", true),
  26028. createSimpleExpression("true")
  26029. )
  26030. );
  26031. }
  26032. };
  26033. const analyzePatchFlag = ({ key, value }) => {
  26034. if (isStaticExp(key)) {
  26035. const name = key.content;
  26036. const isEventHandler = isOn(name);
  26037. if (isEventHandler && (!isComponent || isDynamicComponent) && // omit the flag for click handlers because hydration gives click
  26038. // dedicated fast path.
  26039. name.toLowerCase() !== "onclick" && // omit v-model handlers
  26040. name !== "onUpdate:modelValue" && // omit onVnodeXXX hooks
  26041. !isReservedProp(name)) {
  26042. hasHydrationEventBinding = true;
  26043. }
  26044. if (isEventHandler && isReservedProp(name)) {
  26045. hasVnodeHook = true;
  26046. }
  26047. if (name === "ref") {
  26048. hasRef = true;
  26049. }
  26050. if (isEventHandler && value.type === 14) {
  26051. value = value.arguments[0];
  26052. }
  26053. if (value.type === 20 || (value.type === 4 || value.type === 8) && getConstantType(value, context) > 0) {
  26054. return;
  26055. }
  26056. if (name === "class") {
  26057. hasClassBinding = true;
  26058. } else if (name === "style") {
  26059. hasStyleBinding = true;
  26060. } else if (name !== "ref" && name !== "key" && !dynamicPropNames.includes(name)) {
  26061. dynamicPropNames.push(name);
  26062. }
  26063. if (isComponent && (name === "class" || name === "style") && !dynamicPropNames.includes(name)) {
  26064. dynamicPropNames.push(name);
  26065. }
  26066. } else {
  26067. hasDynamicKeys = true;
  26068. }
  26069. };
  26070. for (let i = 0; i < props.length; i++) {
  26071. const prop = props[i];
  26072. if (prop.type === 6) {
  26073. const { loc, name, nameLoc, value } = prop;
  26074. let isStatic = true;
  26075. if (name === "ref") {
  26076. hasRef = true;
  26077. pushRefVForMarker();
  26078. if (value && context.inline) {
  26079. const binding = context.bindingMetadata[value.content];
  26080. if (binding === "setup-let" || binding === "setup-ref" || binding === "setup-maybe-ref") {
  26081. isStatic = false;
  26082. properties.push(
  26083. createObjectProperty(
  26084. createSimpleExpression("ref_key", true),
  26085. createSimpleExpression(value.content, true, value.loc)
  26086. )
  26087. );
  26088. }
  26089. }
  26090. }
  26091. if (name === "is" && (isComponentTag(tag) || value && value.content.startsWith("vue:") || false)) {
  26092. continue;
  26093. }
  26094. properties.push(
  26095. createObjectProperty(
  26096. createSimpleExpression(name, true, nameLoc),
  26097. createSimpleExpression(
  26098. value ? value.content : "",
  26099. isStatic,
  26100. value ? value.loc : loc
  26101. )
  26102. )
  26103. );
  26104. } else {
  26105. const { name, arg, exp, loc, modifiers } = prop;
  26106. const isVBind = name === "bind";
  26107. const isVOn = name === "on";
  26108. if (name === "slot") {
  26109. if (!isComponent) {
  26110. context.onError(
  26111. createCompilerError(40, loc)
  26112. );
  26113. }
  26114. continue;
  26115. }
  26116. if (name === "once" || name === "memo") {
  26117. continue;
  26118. }
  26119. if (name === "is" || isVBind && isStaticArgOf(arg, "is") && (isComponentTag(tag) || false)) {
  26120. continue;
  26121. }
  26122. if (isVOn && ssr) {
  26123. continue;
  26124. }
  26125. if (isVBind && isStaticArgOf(arg, "key")) {
  26126. shouldUseBlock = true;
  26127. }
  26128. if (isVOn && hasChildren && arg && isStaticExp(arg) && camelize(arg.content) === "vue:beforeUpdate") {
  26129. shouldUseBlock = true;
  26130. isBlockRequired = true;
  26131. }
  26132. if (isVBind && isStaticArgOf(arg, "ref")) {
  26133. pushRefVForMarker();
  26134. }
  26135. if (!arg && (isVBind || isVOn)) {
  26136. hasDynamicKeys = true;
  26137. if (exp) {
  26138. if (isVBind) {
  26139. pushRefVForMarker();
  26140. pushMergeArg();
  26141. mergeArgs.push(exp);
  26142. } else {
  26143. pushMergeArg({
  26144. type: 14,
  26145. loc,
  26146. callee: context.helper(TO_HANDLERS),
  26147. arguments: isComponent ? [exp] : [exp, `true`]
  26148. });
  26149. }
  26150. } else {
  26151. context.onError(
  26152. createCompilerError(
  26153. isVBind ? 34 : 35,
  26154. loc
  26155. )
  26156. );
  26157. }
  26158. continue;
  26159. }
  26160. if (isVBind && modifiers.some((mod) => mod.content === "prop")) {
  26161. patchFlag |= 32;
  26162. }
  26163. const directiveTransform = context.directiveTransforms[name];
  26164. if (directiveTransform) {
  26165. const { props: props2, needRuntime } = directiveTransform(prop, node, context);
  26166. !ssr && props2.forEach(analyzePatchFlag);
  26167. if (isVOn && arg && !isStaticExp(arg)) {
  26168. pushMergeArg(createObjectExpression(props2, elementLoc));
  26169. } else {
  26170. properties.push(...props2);
  26171. }
  26172. if (needRuntime) {
  26173. runtimeDirectives.push(prop);
  26174. if (isSymbol$1(needRuntime)) {
  26175. directiveImportMap.set(prop, needRuntime);
  26176. }
  26177. }
  26178. } else if (!isBuiltInDirective(name)) {
  26179. runtimeDirectives.push(prop);
  26180. if (hasChildren) {
  26181. shouldUseBlock = true;
  26182. isBlockRequired = true;
  26183. }
  26184. }
  26185. }
  26186. }
  26187. let propsExpression = void 0;
  26188. if (mergeArgs.length) {
  26189. pushMergeArg();
  26190. if (mergeArgs.length > 1) {
  26191. propsExpression = createCallExpression(
  26192. context.helper(MERGE_PROPS),
  26193. mergeArgs,
  26194. elementLoc
  26195. );
  26196. } else {
  26197. propsExpression = mergeArgs[0];
  26198. }
  26199. } else if (properties.length) {
  26200. propsExpression = createObjectExpression(
  26201. dedupeProperties(properties),
  26202. elementLoc
  26203. );
  26204. }
  26205. if (hasDynamicKeys) {
  26206. patchFlag |= 16;
  26207. } else {
  26208. if (hasClassBinding && !isComponent) {
  26209. patchFlag |= 2;
  26210. }
  26211. if (hasStyleBinding && !isComponent) {
  26212. patchFlag |= 4;
  26213. }
  26214. if (dynamicPropNames.length) {
  26215. patchFlag |= 8;
  26216. }
  26217. if (hasHydrationEventBinding) {
  26218. patchFlag |= 32;
  26219. }
  26220. }
  26221. const needsPatch = (patchFlag === 0 || patchFlag === 32) && (hasRef || hasVnodeHook || runtimeDirectives.length > 0);
  26222. if (!shouldUseBlock && needsPatch) {
  26223. patchFlag |= 512;
  26224. }
  26225. if (!context.inSSR && propsExpression) {
  26226. switch (propsExpression.type) {
  26227. case 15:
  26228. let classKeyIndex = -1;
  26229. let styleKeyIndex = -1;
  26230. let hasDynamicKey = false;
  26231. for (let i = 0; i < propsExpression.properties.length; i++) {
  26232. const key = propsExpression.properties[i].key;
  26233. if (isStaticExp(key)) {
  26234. if (key.content === "class") {
  26235. classKeyIndex = i;
  26236. } else if (key.content === "style") {
  26237. styleKeyIndex = i;
  26238. }
  26239. } else if (!key.isHandlerKey) {
  26240. hasDynamicKey = true;
  26241. }
  26242. }
  26243. const classProp = propsExpression.properties[classKeyIndex];
  26244. const styleProp = propsExpression.properties[styleKeyIndex];
  26245. if (!hasDynamicKey) {
  26246. if (classProp && !isStaticExp(classProp.value)) {
  26247. classProp.value = createCallExpression(
  26248. context.helper(NORMALIZE_CLASS),
  26249. [classProp.value]
  26250. );
  26251. }
  26252. if (styleProp && // the static style is compiled into an object,
  26253. // so use `hasStyleBinding` to ensure that it is a dynamic style binding
  26254. (hasStyleBinding || styleProp.value.type === 4 && styleProp.value.content.trim()[0] === `[` || // v-bind:style and style both exist,
  26255. // v-bind:style with static literal object
  26256. styleProp.value.type === 17)) {
  26257. styleProp.value = createCallExpression(
  26258. context.helper(NORMALIZE_STYLE),
  26259. [styleProp.value]
  26260. );
  26261. }
  26262. } else {
  26263. propsExpression = createCallExpression(
  26264. context.helper(NORMALIZE_PROPS),
  26265. [propsExpression]
  26266. );
  26267. }
  26268. break;
  26269. case 14:
  26270. break;
  26271. default:
  26272. propsExpression = createCallExpression(
  26273. context.helper(NORMALIZE_PROPS),
  26274. [
  26275. createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
  26276. propsExpression
  26277. ])
  26278. ]
  26279. );
  26280. break;
  26281. }
  26282. }
  26283. return {
  26284. props: propsExpression,
  26285. directives: runtimeDirectives,
  26286. patchFlag,
  26287. dynamicPropNames,
  26288. shouldUseBlock,
  26289. needsPatch,
  26290. isBlockRequired
  26291. };
  26292. }
  26293. function dedupeProperties(properties) {
  26294. const knownProps = /* @__PURE__ */ new Map();
  26295. const deduped = [];
  26296. for (let i = 0; i < properties.length; i++) {
  26297. const prop = properties[i];
  26298. if (prop.key.type === 8 || !prop.key.isStatic) {
  26299. deduped.push(prop);
  26300. continue;
  26301. }
  26302. const name = prop.key.content;
  26303. const existing = knownProps.get(name);
  26304. if (existing) {
  26305. if (name === "style" || name === "class" || isOn(name)) {
  26306. mergeAsArray(existing, prop);
  26307. }
  26308. } else {
  26309. knownProps.set(name, prop);
  26310. deduped.push(prop);
  26311. }
  26312. }
  26313. return deduped;
  26314. }
  26315. function mergeAsArray(existing, incoming) {
  26316. if (existing.value.type === 17) {
  26317. existing.value.elements.push(incoming.value);
  26318. } else {
  26319. existing.value = createArrayExpression(
  26320. [existing.value, incoming.value],
  26321. existing.loc
  26322. );
  26323. }
  26324. }
  26325. function buildDirectiveArgs(dir, context) {
  26326. const dirArgs = [];
  26327. const runtime = directiveImportMap.get(dir);
  26328. if (runtime) {
  26329. dirArgs.push(context.helperString(runtime));
  26330. } else {
  26331. const fromSetup = resolveSetupReference("v-" + dir.name, context);
  26332. if (fromSetup) {
  26333. dirArgs.push(fromSetup);
  26334. } else {
  26335. context.helper(RESOLVE_DIRECTIVE);
  26336. context.directives.add(dir.name);
  26337. dirArgs.push(toValidAssetId(dir.name, `directive`));
  26338. }
  26339. }
  26340. const { loc } = dir;
  26341. if (dir.exp) dirArgs.push(dir.exp);
  26342. if (dir.arg) {
  26343. if (!dir.exp) {
  26344. dirArgs.push(`void 0`);
  26345. }
  26346. dirArgs.push(dir.arg);
  26347. }
  26348. if (Object.keys(dir.modifiers).length) {
  26349. if (!dir.arg) {
  26350. if (!dir.exp) {
  26351. dirArgs.push(`void 0`);
  26352. }
  26353. dirArgs.push(`void 0`);
  26354. }
  26355. const trueExpression = createSimpleExpression(`true`, false, loc);
  26356. dirArgs.push(
  26357. createObjectExpression(
  26358. dir.modifiers.map(
  26359. (modifier) => createObjectProperty(modifier, trueExpression)
  26360. ),
  26361. loc
  26362. )
  26363. );
  26364. }
  26365. return createArrayExpression(dirArgs, dir.loc);
  26366. }
  26367. function stringifyDynamicPropNames(props) {
  26368. let propsNamesString = `[`;
  26369. for (let i = 0, l = props.length; i < l; i++) {
  26370. propsNamesString += JSON.stringify(props[i]);
  26371. if (i < l - 1) propsNamesString += ", ";
  26372. }
  26373. return propsNamesString + `]`;
  26374. }
  26375. function isComponentTag(tag) {
  26376. return tag === "component" || tag === "Component";
  26377. }
  26378. const transformSlotOutlet = (node, context) => {
  26379. if (isSlotOutlet(node)) {
  26380. const { children, loc } = node;
  26381. const { slotName, slotProps } = processSlotOutlet(node, context);
  26382. const slotArgs = [
  26383. context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
  26384. slotName,
  26385. "{}",
  26386. "undefined",
  26387. "true"
  26388. ];
  26389. let expectedLen = 2;
  26390. if (slotProps) {
  26391. slotArgs[2] = slotProps;
  26392. expectedLen = 3;
  26393. }
  26394. if (children.length) {
  26395. slotArgs[3] = createFunctionExpression([], children, false, false, loc);
  26396. expectedLen = 4;
  26397. }
  26398. if (context.scopeId && !context.slotted) {
  26399. expectedLen = 5;
  26400. }
  26401. slotArgs.splice(expectedLen);
  26402. node.codegenNode = createCallExpression(
  26403. context.helper(RENDER_SLOT),
  26404. slotArgs,
  26405. loc
  26406. );
  26407. }
  26408. };
  26409. function processSlotOutlet(node, context) {
  26410. let slotName = `"default"`;
  26411. let slotProps = void 0;
  26412. const nonNameProps = [];
  26413. for (let i = 0; i < node.props.length; i++) {
  26414. const p = node.props[i];
  26415. if (p.type === 6) {
  26416. if (p.value) {
  26417. if (p.name === "name") {
  26418. slotName = JSON.stringify(p.value.content);
  26419. } else {
  26420. p.name = camelize(p.name);
  26421. nonNameProps.push(p);
  26422. }
  26423. }
  26424. } else {
  26425. if (p.name === "bind" && isStaticArgOf(p.arg, "name")) {
  26426. if (p.exp) {
  26427. slotName = p.exp;
  26428. } else if (p.arg && p.arg.type === 4) {
  26429. const name = camelize(p.arg.content);
  26430. slotName = p.exp = createSimpleExpression(name, false, p.arg.loc);
  26431. {
  26432. slotName = p.exp = processExpression(p.exp, context);
  26433. }
  26434. }
  26435. } else {
  26436. if (p.name === "bind" && p.arg && isStaticExp(p.arg)) {
  26437. p.arg.content = camelize(p.arg.content);
  26438. }
  26439. nonNameProps.push(p);
  26440. }
  26441. }
  26442. }
  26443. if (nonNameProps.length > 0) {
  26444. const { props, directives } = buildProps(
  26445. node,
  26446. context,
  26447. nonNameProps,
  26448. false,
  26449. false
  26450. );
  26451. slotProps = props;
  26452. if (directives.length) {
  26453. context.onError(
  26454. createCompilerError(
  26455. 36,
  26456. directives[0].loc
  26457. )
  26458. );
  26459. }
  26460. }
  26461. return {
  26462. slotName,
  26463. slotProps
  26464. };
  26465. }
  26466. const transformOn$1 = (dir, node, context, augmentor) => {
  26467. const { loc, modifiers, arg } = dir;
  26468. if (!dir.exp && !modifiers.length) {
  26469. context.onError(createCompilerError(35, loc));
  26470. }
  26471. let eventName;
  26472. if (arg.type === 4) {
  26473. if (arg.isStatic) {
  26474. let rawName = arg.content;
  26475. if (rawName.startsWith("vnode")) {
  26476. context.onError(createCompilerError(52, arg.loc));
  26477. }
  26478. if (rawName.startsWith("vue:")) {
  26479. rawName = `vnode-${rawName.slice(4)}`;
  26480. }
  26481. const eventString = node.tagType !== 0 || rawName.startsWith("vnode") || !/[A-Z]/.test(rawName) ? (
  26482. // for non-element and vnode lifecycle event listeners, auto convert
  26483. // it to camelCase. See issue #2249
  26484. toHandlerKey(camelize(rawName))
  26485. ) : (
  26486. // preserve case for plain element listeners that have uppercase
  26487. // letters, as these may be custom elements' custom events
  26488. `on:${rawName}`
  26489. );
  26490. eventName = createSimpleExpression(eventString, true, arg.loc);
  26491. } else {
  26492. eventName = createCompoundExpression([
  26493. `${context.helperString(TO_HANDLER_KEY)}(`,
  26494. arg,
  26495. `)`
  26496. ]);
  26497. }
  26498. } else {
  26499. eventName = arg;
  26500. eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
  26501. eventName.children.push(`)`);
  26502. }
  26503. let exp = dir.exp;
  26504. if (exp && !exp.content.trim()) {
  26505. exp = void 0;
  26506. }
  26507. let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;
  26508. if (exp) {
  26509. const isMemberExp = isMemberExpression(exp, context);
  26510. const isInlineStatement = !(isMemberExp || isFnExpression(exp, context));
  26511. const hasMultipleStatements = exp.content.includes(`;`);
  26512. if (context.prefixIdentifiers) {
  26513. isInlineStatement && context.addIdentifiers(`$event`);
  26514. exp = dir.exp = processExpression(
  26515. exp,
  26516. context,
  26517. false,
  26518. hasMultipleStatements
  26519. );
  26520. isInlineStatement && context.removeIdentifiers(`$event`);
  26521. shouldCache = context.cacheHandlers && // unnecessary to cache inside v-once
  26522. !context.inVOnce && // runtime constants don't need to be cached
  26523. // (this is analyzed by compileScript in SFC <script setup>)
  26524. !(exp.type === 4 && exp.constType > 0) && // #1541 bail if this is a member exp handler passed to a component -
  26525. // we need to use the original function to preserve arity,
  26526. // e.g. <transition> relies on checking cb.length to determine
  26527. // transition end handling. Inline function is ok since its arity
  26528. // is preserved even when cached.
  26529. !(isMemberExp && node.tagType === 1) && // bail if the function references closure variables (v-for, v-slot)
  26530. // it must be passed fresh to avoid stale values.
  26531. !hasScopeRef(exp, context.identifiers);
  26532. if (shouldCache && isMemberExp) {
  26533. if (exp.type === 4) {
  26534. exp.content = `${exp.content} && ${exp.content}(...args)`;
  26535. } else {
  26536. exp.children = [...exp.children, ` && `, ...exp.children, `(...args)`];
  26537. }
  26538. }
  26539. }
  26540. if (isInlineStatement || shouldCache && isMemberExp) {
  26541. exp = createCompoundExpression([
  26542. `${isInlineStatement ? context.isTS ? `($event: any)` : `$event` : `${context.isTS ? `
  26543. //@ts-ignore
  26544. ` : ``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
  26545. exp,
  26546. hasMultipleStatements ? `}` : `)`
  26547. ]);
  26548. }
  26549. }
  26550. let ret = {
  26551. props: [
  26552. createObjectProperty(
  26553. eventName,
  26554. exp || createSimpleExpression(`() => {}`, false, loc)
  26555. )
  26556. ]
  26557. };
  26558. if (augmentor) {
  26559. ret = augmentor(ret);
  26560. }
  26561. if (shouldCache) {
  26562. ret.props[0].value = context.cache(ret.props[0].value);
  26563. }
  26564. ret.props.forEach((p) => p.key.isHandlerKey = true);
  26565. return ret;
  26566. };
  26567. const transformBind = (dir, _node, context) => {
  26568. const { modifiers, loc } = dir;
  26569. const arg = dir.arg;
  26570. let { exp } = dir;
  26571. if (exp && exp.type === 4 && !exp.content.trim()) {
  26572. {
  26573. context.onError(
  26574. createCompilerError(34, loc)
  26575. );
  26576. return {
  26577. props: [
  26578. createObjectProperty(arg, createSimpleExpression("", true, loc))
  26579. ]
  26580. };
  26581. }
  26582. }
  26583. if (arg.type !== 4) {
  26584. arg.children.unshift(`(`);
  26585. arg.children.push(`) || ""`);
  26586. } else if (!arg.isStatic) {
  26587. arg.content = arg.content ? `${arg.content} || ""` : `""`;
  26588. }
  26589. if (modifiers.some((mod) => mod.content === "camel")) {
  26590. if (arg.type === 4) {
  26591. if (arg.isStatic) {
  26592. arg.content = camelize(arg.content);
  26593. } else {
  26594. arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
  26595. }
  26596. } else {
  26597. arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
  26598. arg.children.push(`)`);
  26599. }
  26600. }
  26601. if (!context.inSSR) {
  26602. if (modifiers.some((mod) => mod.content === "prop")) {
  26603. injectPrefix(arg, ".");
  26604. }
  26605. if (modifiers.some((mod) => mod.content === "attr")) {
  26606. injectPrefix(arg, "^");
  26607. }
  26608. }
  26609. return {
  26610. props: [createObjectProperty(arg, exp)]
  26611. };
  26612. };
  26613. const injectPrefix = (arg, prefix) => {
  26614. if (arg.type === 4) {
  26615. if (arg.isStatic) {
  26616. arg.content = prefix + arg.content;
  26617. } else {
  26618. arg.content = `\`${prefix}\${${arg.content}}\``;
  26619. }
  26620. } else {
  26621. arg.children.unshift(`'${prefix}' + (`);
  26622. arg.children.push(`)`);
  26623. }
  26624. };
  26625. const transformText = (node, context) => {
  26626. if (node.type === 0 || node.type === 1 || node.type === 11 || node.type === 10) {
  26627. return () => {
  26628. const children = node.children;
  26629. let currentContainer = void 0;
  26630. let hasText = false;
  26631. for (let i = 0; i < children.length; i++) {
  26632. const child = children[i];
  26633. if (isText$1(child)) {
  26634. hasText = true;
  26635. for (let j = i + 1; j < children.length; j++) {
  26636. const next = children[j];
  26637. if (isText$1(next)) {
  26638. if (!currentContainer) {
  26639. currentContainer = children[i] = createCompoundExpression(
  26640. [child],
  26641. child.loc
  26642. );
  26643. }
  26644. currentContainer.children.push(` + `, next);
  26645. children.splice(j, 1);
  26646. j--;
  26647. } else {
  26648. currentContainer = void 0;
  26649. break;
  26650. }
  26651. }
  26652. }
  26653. }
  26654. if (!hasText || // if this is a plain element with a single text child, leave it
  26655. // as-is since the runtime has dedicated fast path for this by directly
  26656. // setting textContent of the element.
  26657. // for component root it's always normalized anyway.
  26658. children.length === 1 && (node.type === 0 || node.type === 1 && node.tagType === 0 && // #3756
  26659. // custom directives can potentially add DOM elements arbitrarily,
  26660. // we need to avoid setting textContent of the element at runtime
  26661. // to avoid accidentally overwriting the DOM elements added
  26662. // by the user through custom directives.
  26663. !node.props.find(
  26664. (p) => p.type === 7 && !context.directiveTransforms[p.name]
  26665. ) && // in compat mode, <template> tags with no special directives
  26666. // will be rendered as a fragment so its children must be
  26667. // converted into vnodes.
  26668. true)) {
  26669. return;
  26670. }
  26671. for (let i = 0; i < children.length; i++) {
  26672. const child = children[i];
  26673. if (isText$1(child) || child.type === 8) {
  26674. const callArgs = [];
  26675. if (child.type !== 2 || child.content !== " ") {
  26676. callArgs.push(child);
  26677. }
  26678. if (!context.ssr && getConstantType(child, context) === 0) {
  26679. callArgs.push(
  26680. 1 + (` /* ${PatchFlagNames[1]} */` )
  26681. );
  26682. }
  26683. children[i] = {
  26684. type: 12,
  26685. content: child,
  26686. loc: child.loc,
  26687. codegenNode: createCallExpression(
  26688. context.helper(CREATE_TEXT),
  26689. callArgs
  26690. )
  26691. };
  26692. }
  26693. }
  26694. };
  26695. }
  26696. };
  26697. const seen$1 = /* @__PURE__ */ new WeakSet();
  26698. const transformOnce = (node, context) => {
  26699. if (node.type === 1 && findDir(node, "once", true)) {
  26700. if (seen$1.has(node) || context.inVOnce || context.inSSR) {
  26701. return;
  26702. }
  26703. seen$1.add(node);
  26704. context.inVOnce = true;
  26705. context.helper(SET_BLOCK_TRACKING);
  26706. return () => {
  26707. context.inVOnce = false;
  26708. const cur = context.currentNode;
  26709. if (cur.codegenNode) {
  26710. cur.codegenNode = context.cache(
  26711. cur.codegenNode,
  26712. true,
  26713. true
  26714. );
  26715. }
  26716. };
  26717. }
  26718. };
  26719. const transformModel$1 = (dir, node, context) => {
  26720. const { exp, arg } = dir;
  26721. if (!exp) {
  26722. context.onError(
  26723. createCompilerError(41, dir.loc)
  26724. );
  26725. return createTransformProps();
  26726. }
  26727. const rawExp = exp.loc.source.trim();
  26728. const expString = exp.type === 4 ? exp.content : rawExp;
  26729. const bindingType = context.bindingMetadata[rawExp];
  26730. if (bindingType === "props" || bindingType === "props-aliased") {
  26731. context.onError(createCompilerError(44, exp.loc));
  26732. return createTransformProps();
  26733. }
  26734. if (bindingType === "literal-const" || bindingType === "setup-const") {
  26735. context.onError(createCompilerError(45, exp.loc));
  26736. return createTransformProps();
  26737. }
  26738. const maybeRef = context.inline && (bindingType === "setup-let" || bindingType === "setup-ref" || bindingType === "setup-maybe-ref");
  26739. if (!expString.trim() || !isMemberExpression(exp, context) && !maybeRef) {
  26740. context.onError(
  26741. createCompilerError(42, exp.loc)
  26742. );
  26743. return createTransformProps();
  26744. }
  26745. if (context.prefixIdentifiers && isSimpleIdentifier(expString) && context.identifiers[expString]) {
  26746. context.onError(
  26747. createCompilerError(43, exp.loc)
  26748. );
  26749. return createTransformProps();
  26750. }
  26751. const propName = arg ? arg : createSimpleExpression("modelValue", true);
  26752. const eventName = arg ? isStaticExp(arg) ? `onUpdate:${camelize(arg.content)}` : createCompoundExpression(['"onUpdate:" + ', arg]) : `onUpdate:modelValue`;
  26753. let assignmentExp;
  26754. const eventArg = context.isTS ? `($event: any)` : `$event`;
  26755. if (maybeRef) {
  26756. if (bindingType === "setup-ref") {
  26757. assignmentExp = createCompoundExpression([
  26758. `${eventArg} => ((`,
  26759. createSimpleExpression(rawExp, false, exp.loc),
  26760. `).value = $event)`
  26761. ]);
  26762. } else {
  26763. const altAssignment = bindingType === "setup-let" ? `${rawExp} = $event` : `null`;
  26764. assignmentExp = createCompoundExpression([
  26765. `${eventArg} => (${context.helperString(IS_REF)}(${rawExp}) ? (`,
  26766. createSimpleExpression(rawExp, false, exp.loc),
  26767. `).value = $event : ${altAssignment})`
  26768. ]);
  26769. }
  26770. } else {
  26771. assignmentExp = createCompoundExpression([
  26772. `${eventArg} => ((`,
  26773. exp,
  26774. `) = $event)`
  26775. ]);
  26776. }
  26777. const props = [
  26778. // modelValue: foo
  26779. createObjectProperty(propName, dir.exp),
  26780. // "onUpdate:modelValue": $event => (foo = $event)
  26781. createObjectProperty(eventName, assignmentExp)
  26782. ];
  26783. if (context.prefixIdentifiers && !context.inVOnce && context.cacheHandlers && !hasScopeRef(exp, context.identifiers)) {
  26784. props[1].value = context.cache(props[1].value);
  26785. }
  26786. if (dir.modifiers.length && node.tagType === 1) {
  26787. const modifiers = dir.modifiers.map((m) => m.content).map((m) => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`).join(`, `);
  26788. const modifiersKey = arg ? isStaticExp(arg) ? `${arg.content}Modifiers` : createCompoundExpression([arg, ' + "Modifiers"']) : `modelModifiers`;
  26789. props.push(
  26790. createObjectProperty(
  26791. modifiersKey,
  26792. createSimpleExpression(
  26793. `{ ${modifiers} }`,
  26794. false,
  26795. dir.loc,
  26796. 2
  26797. )
  26798. )
  26799. );
  26800. }
  26801. return createTransformProps(props);
  26802. };
  26803. function createTransformProps(props = []) {
  26804. return { props };
  26805. }
  26806. const seen = /* @__PURE__ */ new WeakSet();
  26807. const transformMemo = (node, context) => {
  26808. if (node.type === 1) {
  26809. const dir = findDir(node, "memo");
  26810. if (!dir || seen.has(node) || context.inSSR) {
  26811. return;
  26812. }
  26813. seen.add(node);
  26814. return () => {
  26815. const codegenNode = node.codegenNode || context.currentNode.codegenNode;
  26816. if (codegenNode && codegenNode.type === 13) {
  26817. if (node.tagType !== 1) {
  26818. convertToBlock(codegenNode, context);
  26819. }
  26820. node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
  26821. dir.exp,
  26822. createFunctionExpression(void 0, codegenNode),
  26823. `_cache`,
  26824. String(context.cached.length)
  26825. ]);
  26826. context.cached.push(null);
  26827. }
  26828. };
  26829. }
  26830. };
  26831. const transformVBindShorthand = (node, context) => {
  26832. if (node.type === 1) {
  26833. for (const prop of node.props) {
  26834. if (prop.type === 7 && prop.name === "bind" && (!prop.exp || // #13930 :foo in in-DOM templates will be parsed into :foo="" by browser
  26835. false) && prop.arg) {
  26836. const arg = prop.arg;
  26837. if (arg.type !== 4 || !arg.isStatic) {
  26838. context.onError(
  26839. createCompilerError(
  26840. 53,
  26841. arg.loc
  26842. )
  26843. );
  26844. prop.exp = createSimpleExpression("", true, arg.loc);
  26845. } else {
  26846. const propName = camelize(arg.content);
  26847. if (validFirstIdentCharRE.test(propName[0]) || // allow hyphen first char for https://github.com/vuejs/language-tools/pull/3424
  26848. propName[0] === "-") {
  26849. prop.exp = createSimpleExpression(propName, false, arg.loc);
  26850. }
  26851. }
  26852. }
  26853. }
  26854. }
  26855. };
  26856. function getBaseTransformPreset(prefixIdentifiers) {
  26857. return [
  26858. [
  26859. transformVBindShorthand,
  26860. transformOnce,
  26861. transformIf,
  26862. transformMemo,
  26863. transformFor,
  26864. ...[],
  26865. ...prefixIdentifiers ? [
  26866. // order is important
  26867. trackVForSlotScopes,
  26868. transformExpression
  26869. ] : [],
  26870. transformSlotOutlet,
  26871. transformElement,
  26872. trackSlotScopes,
  26873. transformText
  26874. ],
  26875. {
  26876. on: transformOn$1,
  26877. bind: transformBind,
  26878. model: transformModel$1
  26879. }
  26880. ];
  26881. }
  26882. function baseCompile(source, options = {}) {
  26883. const onError = options.onError || defaultOnError;
  26884. const isModuleMode = options.mode === "module";
  26885. const prefixIdentifiers = options.prefixIdentifiers === true || isModuleMode;
  26886. if (!prefixIdentifiers && options.cacheHandlers) {
  26887. onError(createCompilerError(50));
  26888. }
  26889. if (options.scopeId && !isModuleMode) {
  26890. onError(createCompilerError(51));
  26891. }
  26892. const resolvedOptions = extend({}, options, {
  26893. prefixIdentifiers
  26894. });
  26895. const ast = isString$1(source) ? baseParse(source, resolvedOptions) : source;
  26896. const [nodeTransforms, directiveTransforms] = getBaseTransformPreset(prefixIdentifiers);
  26897. if (options.isTS) {
  26898. const { expressionPlugins } = options;
  26899. if (!expressionPlugins || !expressionPlugins.includes("typescript")) {
  26900. options.expressionPlugins = [...expressionPlugins || [], "typescript"];
  26901. }
  26902. }
  26903. transform(
  26904. ast,
  26905. extend({}, resolvedOptions, {
  26906. nodeTransforms: [
  26907. ...nodeTransforms,
  26908. ...options.nodeTransforms || []
  26909. // user transforms
  26910. ],
  26911. directiveTransforms: extend(
  26912. {},
  26913. directiveTransforms,
  26914. options.directiveTransforms || {}
  26915. // user transforms
  26916. )
  26917. })
  26918. );
  26919. return generate(ast, resolvedOptions);
  26920. }
  26921. const BindingTypes = {
  26922. "DATA": "data",
  26923. "PROPS": "props",
  26924. "PROPS_ALIASED": "props-aliased",
  26925. "SETUP_LET": "setup-let",
  26926. "SETUP_CONST": "setup-const",
  26927. "SETUP_REACTIVE_CONST": "setup-reactive-const",
  26928. "SETUP_MAYBE_REF": "setup-maybe-ref",
  26929. "SETUP_REF": "setup-ref",
  26930. "OPTIONS": "options",
  26931. "LITERAL_CONST": "literal-const"
  26932. };
  26933. const noopDirectiveTransform = () => ({ props: [] });
  26934. const V_MODEL_RADIO = /* @__PURE__ */ Symbol(`vModelRadio` );
  26935. const V_MODEL_CHECKBOX = /* @__PURE__ */ Symbol(
  26936. `vModelCheckbox`
  26937. );
  26938. const V_MODEL_TEXT = /* @__PURE__ */ Symbol(`vModelText` );
  26939. const V_MODEL_SELECT = /* @__PURE__ */ Symbol(
  26940. `vModelSelect`
  26941. );
  26942. const V_MODEL_DYNAMIC = /* @__PURE__ */ Symbol(
  26943. `vModelDynamic`
  26944. );
  26945. const V_ON_WITH_MODIFIERS = /* @__PURE__ */ Symbol(
  26946. `vOnModifiersGuard`
  26947. );
  26948. const V_ON_WITH_KEYS = /* @__PURE__ */ Symbol(
  26949. `vOnKeysGuard`
  26950. );
  26951. const V_SHOW = /* @__PURE__ */ Symbol(`vShow` );
  26952. const TRANSITION = /* @__PURE__ */ Symbol(`Transition` );
  26953. const TRANSITION_GROUP = /* @__PURE__ */ Symbol(
  26954. `TransitionGroup`
  26955. );
  26956. registerRuntimeHelpers({
  26957. [V_MODEL_RADIO]: `vModelRadio`,
  26958. [V_MODEL_CHECKBOX]: `vModelCheckbox`,
  26959. [V_MODEL_TEXT]: `vModelText`,
  26960. [V_MODEL_SELECT]: `vModelSelect`,
  26961. [V_MODEL_DYNAMIC]: `vModelDynamic`,
  26962. [V_ON_WITH_MODIFIERS]: `withModifiers`,
  26963. [V_ON_WITH_KEYS]: `withKeys`,
  26964. [V_SHOW]: `vShow`,
  26965. [TRANSITION]: `Transition`,
  26966. [TRANSITION_GROUP]: `TransitionGroup`
  26967. });
  26968. const parserOptions = {
  26969. parseMode: "html",
  26970. isVoidTag,
  26971. isNativeTag: (tag) => isHTMLTag(tag) || isSVGTag(tag) || isMathMLTag(tag),
  26972. isPreTag: (tag) => tag === "pre",
  26973. isIgnoreNewlineTag: (tag) => tag === "pre" || tag === "textarea",
  26974. decodeEntities: void 0,
  26975. isBuiltInComponent: (tag) => {
  26976. if (tag === "Transition" || tag === "transition") {
  26977. return TRANSITION;
  26978. } else if (tag === "TransitionGroup" || tag === "transition-group") {
  26979. return TRANSITION_GROUP;
  26980. }
  26981. },
  26982. // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
  26983. getNamespace(tag, parent, rootNamespace) {
  26984. let ns = parent ? parent.ns : rootNamespace;
  26985. if (parent && ns === 2) {
  26986. if (parent.tag === "annotation-xml") {
  26987. if (tag === "svg") {
  26988. return 1;
  26989. }
  26990. if (parent.props.some(
  26991. (a) => a.type === 6 && a.name === "encoding" && a.value != null && (a.value.content === "text/html" || a.value.content === "application/xhtml+xml")
  26992. )) {
  26993. ns = 0;
  26994. }
  26995. } else if (/^m(?:[ions]|text)$/.test(parent.tag) && tag !== "mglyph" && tag !== "malignmark") {
  26996. ns = 0;
  26997. }
  26998. } else if (parent && ns === 1) {
  26999. if (parent.tag === "foreignObject" || parent.tag === "desc" || parent.tag === "title") {
  27000. ns = 0;
  27001. }
  27002. }
  27003. if (ns === 0) {
  27004. if (tag === "svg") {
  27005. return 1;
  27006. }
  27007. if (tag === "math") {
  27008. return 2;
  27009. }
  27010. }
  27011. return ns;
  27012. }
  27013. };
  27014. const transformStyle = (node) => {
  27015. if (node.type === 1) {
  27016. node.props.forEach((p, i) => {
  27017. if (p.type === 6 && p.name === "style" && p.value) {
  27018. node.props[i] = {
  27019. type: 7,
  27020. name: `bind`,
  27021. arg: createSimpleExpression(`style`, true, p.loc),
  27022. exp: parseInlineCSS(p.value.content, p.loc),
  27023. modifiers: [],
  27024. loc: p.loc
  27025. };
  27026. }
  27027. });
  27028. }
  27029. };
  27030. const parseInlineCSS = (cssText, loc) => {
  27031. const normalized = parseStringStyle(cssText);
  27032. return createSimpleExpression(
  27033. JSON.stringify(normalized),
  27034. false,
  27035. loc,
  27036. 3
  27037. );
  27038. };
  27039. function createDOMCompilerError(code, loc) {
  27040. return createCompilerError(
  27041. code,
  27042. loc,
  27043. DOMErrorMessages
  27044. );
  27045. }
  27046. const DOMErrorCodes = {
  27047. "X_V_HTML_NO_EXPRESSION": 54,
  27048. "54": "X_V_HTML_NO_EXPRESSION",
  27049. "X_V_HTML_WITH_CHILDREN": 55,
  27050. "55": "X_V_HTML_WITH_CHILDREN",
  27051. "X_V_TEXT_NO_EXPRESSION": 56,
  27052. "56": "X_V_TEXT_NO_EXPRESSION",
  27053. "X_V_TEXT_WITH_CHILDREN": 57,
  27054. "57": "X_V_TEXT_WITH_CHILDREN",
  27055. "X_V_MODEL_ON_INVALID_ELEMENT": 58,
  27056. "58": "X_V_MODEL_ON_INVALID_ELEMENT",
  27057. "X_V_MODEL_ARG_ON_ELEMENT": 59,
  27058. "59": "X_V_MODEL_ARG_ON_ELEMENT",
  27059. "X_V_MODEL_ON_FILE_INPUT_ELEMENT": 60,
  27060. "60": "X_V_MODEL_ON_FILE_INPUT_ELEMENT",
  27061. "X_V_MODEL_UNNECESSARY_VALUE": 61,
  27062. "61": "X_V_MODEL_UNNECESSARY_VALUE",
  27063. "X_V_SHOW_NO_EXPRESSION": 62,
  27064. "62": "X_V_SHOW_NO_EXPRESSION",
  27065. "X_TRANSITION_INVALID_CHILDREN": 63,
  27066. "63": "X_TRANSITION_INVALID_CHILDREN",
  27067. "X_IGNORED_SIDE_EFFECT_TAG": 64,
  27068. "64": "X_IGNORED_SIDE_EFFECT_TAG",
  27069. "__EXTEND_POINT__": 65,
  27070. "65": "__EXTEND_POINT__"
  27071. };
  27072. const DOMErrorMessages = {
  27073. [54]: `v-html is missing expression.`,
  27074. [55]: `v-html will override element children.`,
  27075. [56]: `v-text is missing expression.`,
  27076. [57]: `v-text will override element children.`,
  27077. [58]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
  27078. [59]: `v-model argument is not supported on plain elements.`,
  27079. [60]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`,
  27080. [61]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
  27081. [62]: `v-show is missing expression.`,
  27082. [63]: `<Transition> expects exactly one child element or component.`,
  27083. [64]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
  27084. };
  27085. const transformVHtml = (dir, node, context) => {
  27086. const { exp, loc } = dir;
  27087. if (!exp) {
  27088. context.onError(
  27089. createDOMCompilerError(54, loc)
  27090. );
  27091. }
  27092. if (node.children.length) {
  27093. context.onError(
  27094. createDOMCompilerError(55, loc)
  27095. );
  27096. node.children.length = 0;
  27097. }
  27098. return {
  27099. props: [
  27100. createObjectProperty(
  27101. createSimpleExpression(`innerHTML`, true, loc),
  27102. exp || createSimpleExpression("", true)
  27103. )
  27104. ]
  27105. };
  27106. };
  27107. const transformVText = (dir, node, context) => {
  27108. const { exp, loc } = dir;
  27109. if (!exp) {
  27110. context.onError(
  27111. createDOMCompilerError(56, loc)
  27112. );
  27113. }
  27114. if (node.children.length) {
  27115. context.onError(
  27116. createDOMCompilerError(57, loc)
  27117. );
  27118. node.children.length = 0;
  27119. }
  27120. return {
  27121. props: [
  27122. createObjectProperty(
  27123. createSimpleExpression(`textContent`, true),
  27124. exp ? getConstantType(exp, context) > 0 ? exp : createCallExpression(
  27125. context.helperString(TO_DISPLAY_STRING),
  27126. [exp],
  27127. loc
  27128. ) : createSimpleExpression("", true)
  27129. )
  27130. ]
  27131. };
  27132. };
  27133. const transformModel = (dir, node, context) => {
  27134. const baseResult = transformModel$1(dir, node, context);
  27135. if (!baseResult.props.length || node.tagType === 1) {
  27136. return baseResult;
  27137. }
  27138. if (dir.arg) {
  27139. context.onError(
  27140. createDOMCompilerError(
  27141. 59,
  27142. dir.arg.loc
  27143. )
  27144. );
  27145. }
  27146. function checkDuplicatedValue() {
  27147. const value = findDir(node, "bind");
  27148. if (value && isStaticArgOf(value.arg, "value")) {
  27149. context.onError(
  27150. createDOMCompilerError(
  27151. 61,
  27152. value.loc
  27153. )
  27154. );
  27155. }
  27156. }
  27157. const { tag } = node;
  27158. const isCustomElement = context.isCustomElement(tag);
  27159. if (tag === "input" || tag === "textarea" || tag === "select" || isCustomElement) {
  27160. let directiveToUse = V_MODEL_TEXT;
  27161. let isInvalidType = false;
  27162. if (tag === "input" || isCustomElement) {
  27163. const type = findProp(node, `type`);
  27164. if (type) {
  27165. if (type.type === 7) {
  27166. directiveToUse = V_MODEL_DYNAMIC;
  27167. } else if (type.value) {
  27168. switch (type.value.content) {
  27169. case "radio":
  27170. directiveToUse = V_MODEL_RADIO;
  27171. break;
  27172. case "checkbox":
  27173. directiveToUse = V_MODEL_CHECKBOX;
  27174. break;
  27175. case "file":
  27176. isInvalidType = true;
  27177. context.onError(
  27178. createDOMCompilerError(
  27179. 60,
  27180. dir.loc
  27181. )
  27182. );
  27183. break;
  27184. default:
  27185. checkDuplicatedValue();
  27186. break;
  27187. }
  27188. }
  27189. } else if (hasDynamicKeyVBind(node)) {
  27190. directiveToUse = V_MODEL_DYNAMIC;
  27191. } else {
  27192. checkDuplicatedValue();
  27193. }
  27194. } else if (tag === "select") {
  27195. directiveToUse = V_MODEL_SELECT;
  27196. } else {
  27197. checkDuplicatedValue();
  27198. }
  27199. if (!isInvalidType) {
  27200. baseResult.needRuntime = context.helper(directiveToUse);
  27201. }
  27202. } else {
  27203. context.onError(
  27204. createDOMCompilerError(
  27205. 58,
  27206. dir.loc
  27207. )
  27208. );
  27209. }
  27210. baseResult.props = baseResult.props.filter(
  27211. (p) => !(p.key.type === 4 && p.key.content === "modelValue")
  27212. );
  27213. return baseResult;
  27214. };
  27215. const isEventOptionModifier = /* @__PURE__ */ makeMap(`passive,once,capture`);
  27216. const isNonKeyModifier = /* @__PURE__ */ makeMap(
  27217. // event propagation management
  27218. `stop,prevent,self,ctrl,shift,alt,meta,exact,middle`
  27219. );
  27220. const maybeKeyModifier = /* @__PURE__ */ makeMap("left,right");
  27221. const isKeyboardEvent = /* @__PURE__ */ makeMap(`onkeyup,onkeydown,onkeypress`);
  27222. const resolveModifiers = (key, modifiers, context, loc) => {
  27223. const keyModifiers = [];
  27224. const nonKeyModifiers = [];
  27225. const eventOptionModifiers = [];
  27226. for (let i = 0; i < modifiers.length; i++) {
  27227. const modifier = modifiers[i].content;
  27228. if (isEventOptionModifier(modifier)) {
  27229. eventOptionModifiers.push(modifier);
  27230. } else {
  27231. if (maybeKeyModifier(modifier)) {
  27232. if (isStaticExp(key)) {
  27233. if (isKeyboardEvent(key.content.toLowerCase())) {
  27234. keyModifiers.push(modifier);
  27235. } else {
  27236. nonKeyModifiers.push(modifier);
  27237. }
  27238. } else {
  27239. keyModifiers.push(modifier);
  27240. nonKeyModifiers.push(modifier);
  27241. }
  27242. } else {
  27243. if (isNonKeyModifier(modifier)) {
  27244. nonKeyModifiers.push(modifier);
  27245. } else {
  27246. keyModifiers.push(modifier);
  27247. }
  27248. }
  27249. }
  27250. }
  27251. return {
  27252. keyModifiers,
  27253. nonKeyModifiers,
  27254. eventOptionModifiers
  27255. };
  27256. };
  27257. const transformClick = (key, event) => {
  27258. const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === "onclick";
  27259. return isStaticClick ? createSimpleExpression(event, true) : key.type !== 4 ? createCompoundExpression([
  27260. `(`,
  27261. key,
  27262. `) === "onClick" ? "${event}" : (`,
  27263. key,
  27264. `)`
  27265. ]) : key;
  27266. };
  27267. const transformOn = (dir, node, context) => {
  27268. return transformOn$1(dir, node, context, (baseResult) => {
  27269. const { modifiers } = dir;
  27270. if (!modifiers.length) return baseResult;
  27271. let { key, value: handlerExp } = baseResult.props[0];
  27272. const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
  27273. if (nonKeyModifiers.includes("right")) {
  27274. key = transformClick(key, `onContextmenu`);
  27275. }
  27276. if (nonKeyModifiers.includes("middle")) {
  27277. key = transformClick(key, `onMouseup`);
  27278. }
  27279. if (nonKeyModifiers.length) {
  27280. handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
  27281. handlerExp,
  27282. JSON.stringify(nonKeyModifiers)
  27283. ]);
  27284. }
  27285. if (keyModifiers.length && // if event name is dynamic, always wrap with keys guard
  27286. (!isStaticExp(key) || isKeyboardEvent(key.content.toLowerCase()))) {
  27287. handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
  27288. handlerExp,
  27289. JSON.stringify(keyModifiers)
  27290. ]);
  27291. }
  27292. if (eventOptionModifiers.length) {
  27293. const modifierPostfix = eventOptionModifiers.map(capitalize).join("");
  27294. key = isStaticExp(key) ? createSimpleExpression(`${key.content}${modifierPostfix}`, true) : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
  27295. }
  27296. return {
  27297. props: [createObjectProperty(key, handlerExp)]
  27298. };
  27299. });
  27300. };
  27301. const transformShow = (dir, node, context) => {
  27302. const { exp, loc } = dir;
  27303. if (!exp) {
  27304. context.onError(
  27305. createDOMCompilerError(62, loc)
  27306. );
  27307. }
  27308. return {
  27309. props: [],
  27310. needRuntime: context.helper(V_SHOW)
  27311. };
  27312. };
  27313. const transformTransition = (node, context) => {
  27314. if (node.type === 1 && node.tagType === 1) {
  27315. const component = context.isBuiltInComponent(node.tag);
  27316. if (component === TRANSITION) {
  27317. return () => {
  27318. if (!node.children.length) {
  27319. return;
  27320. }
  27321. if (hasMultipleChildren(node)) {
  27322. context.onError(
  27323. createDOMCompilerError(
  27324. 63,
  27325. {
  27326. start: node.children[0].loc.start,
  27327. end: node.children[node.children.length - 1].loc.end,
  27328. source: ""
  27329. }
  27330. )
  27331. );
  27332. }
  27333. const child = node.children[0];
  27334. if (child.type === 1) {
  27335. for (const p of child.props) {
  27336. if (p.type === 7 && p.name === "show") {
  27337. node.props.push({
  27338. type: 6,
  27339. name: "persisted",
  27340. nameLoc: node.loc,
  27341. value: void 0,
  27342. loc: node.loc
  27343. });
  27344. }
  27345. }
  27346. }
  27347. };
  27348. }
  27349. }
  27350. };
  27351. function hasMultipleChildren(node) {
  27352. const children = node.children = node.children.filter(
  27353. (c) => !isCommentOrWhitespace(c)
  27354. );
  27355. const child = children[0];
  27356. return children.length !== 1 || child.type === 11 || child.type === 9 && child.branches.some(hasMultipleChildren);
  27357. }
  27358. const expReplaceRE = /__VUE_EXP_START__(.*?)__VUE_EXP_END__/g;
  27359. const stringifyStatic = (children, context, parent) => {
  27360. if (context.scopes.vSlot > 0) {
  27361. return;
  27362. }
  27363. const isParentCached = parent.type === 1 && parent.codegenNode && parent.codegenNode.type === 13 && parent.codegenNode.children && !isArray$3(parent.codegenNode.children) && parent.codegenNode.children.type === 20;
  27364. let nc = 0;
  27365. let ec = 0;
  27366. const currentChunk = [];
  27367. const stringifyCurrentChunk = (currentIndex) => {
  27368. if (nc >= 20 || ec >= 5) {
  27369. const staticCall = createCallExpression(context.helper(CREATE_STATIC), [
  27370. JSON.stringify(
  27371. currentChunk.map((node) => stringifyNode(node, context)).join("")
  27372. ).replace(expReplaceRE, `" + $1 + "`),
  27373. // the 2nd argument indicates the number of DOM nodes this static vnode
  27374. // will insert / hydrate
  27375. String(currentChunk.length)
  27376. ]);
  27377. const deleteCount = currentChunk.length - 1;
  27378. if (isParentCached) {
  27379. children.splice(
  27380. currentIndex - currentChunk.length,
  27381. currentChunk.length,
  27382. // @ts-expect-error
  27383. staticCall
  27384. );
  27385. } else {
  27386. currentChunk[0].codegenNode.value = staticCall;
  27387. if (currentChunk.length > 1) {
  27388. children.splice(currentIndex - currentChunk.length + 1, deleteCount);
  27389. const cacheIndex = context.cached.indexOf(
  27390. currentChunk[currentChunk.length - 1].codegenNode
  27391. );
  27392. if (cacheIndex > -1) {
  27393. for (let i2 = cacheIndex; i2 < context.cached.length; i2++) {
  27394. const c = context.cached[i2];
  27395. if (c) c.index -= deleteCount;
  27396. }
  27397. context.cached.splice(cacheIndex - deleteCount + 1, deleteCount);
  27398. }
  27399. }
  27400. }
  27401. return deleteCount;
  27402. }
  27403. return 0;
  27404. };
  27405. let i = 0;
  27406. for (; i < children.length; i++) {
  27407. const child = children[i];
  27408. const isCached = isParentCached || getCachedNode(child);
  27409. if (isCached) {
  27410. const result = analyzeNode(child);
  27411. if (result) {
  27412. nc += result[0];
  27413. ec += result[1];
  27414. currentChunk.push(child);
  27415. continue;
  27416. }
  27417. }
  27418. i -= stringifyCurrentChunk(i);
  27419. nc = 0;
  27420. ec = 0;
  27421. currentChunk.length = 0;
  27422. }
  27423. stringifyCurrentChunk(i);
  27424. };
  27425. const getCachedNode = (node) => {
  27426. if ((node.type === 1 && node.tagType === 0 || node.type === 12) && node.codegenNode && node.codegenNode.type === 20) {
  27427. return node.codegenNode;
  27428. }
  27429. };
  27430. const dataAriaRE = /^(?:data|aria)-/;
  27431. const isStringifiableAttr = (name, ns) => {
  27432. return (ns === 0 ? isKnownHtmlAttr(name) : ns === 1 ? isKnownSvgAttr(name) : ns === 2 ? isKnownMathMLAttr(name) : false) || dataAriaRE.test(name);
  27433. };
  27434. const isNonStringifiable = /* @__PURE__ */ makeMap(
  27435. `caption,thead,tr,th,tbody,td,tfoot,colgroup,col`
  27436. );
  27437. function analyzeNode(node) {
  27438. if (node.type === 1 && isNonStringifiable(node.tag)) {
  27439. return false;
  27440. }
  27441. if (node.type === 1 && findDir(node, "once", true)) {
  27442. return false;
  27443. }
  27444. if (node.type === 12) {
  27445. return [1, 0];
  27446. }
  27447. let nc = 1;
  27448. let ec = node.props.length > 0 ? 1 : 0;
  27449. let bailed = false;
  27450. const bail = () => {
  27451. bailed = true;
  27452. return false;
  27453. };
  27454. function walk(node2) {
  27455. const isOptionTag = node2.tag === "option" && node2.ns === 0;
  27456. for (let i = 0; i < node2.props.length; i++) {
  27457. const p = node2.props[i];
  27458. if (p.type === 6 && !isStringifiableAttr(p.name, node2.ns)) {
  27459. return bail();
  27460. }
  27461. if (p.type === 7 && p.name === "bind") {
  27462. if (p.arg && (p.arg.type === 8 || p.arg.isStatic && !isStringifiableAttr(p.arg.content, node2.ns))) {
  27463. return bail();
  27464. }
  27465. if (p.exp && (p.exp.type === 8 || p.exp.constType < 3)) {
  27466. return bail();
  27467. }
  27468. if (isOptionTag && isStaticArgOf(p.arg, "value") && p.exp && !p.exp.isStatic) {
  27469. return bail();
  27470. }
  27471. }
  27472. }
  27473. for (let i = 0; i < node2.children.length; i++) {
  27474. nc++;
  27475. const child = node2.children[i];
  27476. if (child.type === 1) {
  27477. if (child.props.length > 0) {
  27478. ec++;
  27479. }
  27480. walk(child);
  27481. if (bailed) {
  27482. return false;
  27483. }
  27484. }
  27485. }
  27486. return true;
  27487. }
  27488. return walk(node) ? [nc, ec] : false;
  27489. }
  27490. function stringifyNode(node, context) {
  27491. if (isString$1(node)) {
  27492. return node;
  27493. }
  27494. if (isSymbol$1(node)) {
  27495. return ``;
  27496. }
  27497. switch (node.type) {
  27498. case 1:
  27499. return stringifyElement(node, context);
  27500. case 2:
  27501. return escapeHtml(node.content);
  27502. case 3:
  27503. return `<!--${escapeHtml(node.content)}-->`;
  27504. case 5:
  27505. return escapeHtml(toDisplayString(evaluateConstant(node.content)));
  27506. case 8:
  27507. return escapeHtml(evaluateConstant(node));
  27508. case 12:
  27509. return stringifyNode(node.content, context);
  27510. default:
  27511. return "";
  27512. }
  27513. }
  27514. function stringifyElement(node, context) {
  27515. let res = `<${node.tag}`;
  27516. let innerHTML = "";
  27517. for (let i = 0; i < node.props.length; i++) {
  27518. const p = node.props[i];
  27519. if (p.type === 6) {
  27520. res += ` ${p.name}`;
  27521. if (p.value) {
  27522. res += `="${escapeHtml(p.value.content)}"`;
  27523. }
  27524. } else if (p.type === 7) {
  27525. if (p.name === "bind") {
  27526. const exp = p.exp;
  27527. if (exp.content[0] === "_") {
  27528. res += ` ${p.arg.content}="__VUE_EXP_START__${exp.content}__VUE_EXP_END__"`;
  27529. continue;
  27530. }
  27531. if ((isBooleanAttr(p.arg.content) || p.arg.content === "hidden") && exp.content === "false") {
  27532. continue;
  27533. }
  27534. let evaluated = evaluateConstant(exp);
  27535. if (evaluated != null) {
  27536. const arg = p.arg && p.arg.content;
  27537. if (arg === "hidden" && typeof evaluated === "number" && !includeBooleanAttr(evaluated)) {
  27538. continue;
  27539. }
  27540. if (arg === "class") {
  27541. evaluated = normalizeClass(evaluated);
  27542. } else if (arg === "style") {
  27543. evaluated = stringifyStyle(normalizeStyle(evaluated));
  27544. }
  27545. res += ` ${p.arg.content}="${escapeHtml(
  27546. evaluated
  27547. )}"`;
  27548. }
  27549. } else if (p.name === "html") {
  27550. innerHTML = evaluateConstant(p.exp);
  27551. } else if (p.name === "text") {
  27552. innerHTML = escapeHtml(
  27553. toDisplayString(evaluateConstant(p.exp))
  27554. );
  27555. }
  27556. }
  27557. }
  27558. if (context.scopeId) {
  27559. res += ` ${context.scopeId}`;
  27560. }
  27561. res += `>`;
  27562. if (innerHTML) {
  27563. res += innerHTML;
  27564. } else {
  27565. for (let i = 0; i < node.children.length; i++) {
  27566. res += stringifyNode(node.children[i], context);
  27567. }
  27568. }
  27569. if (!isVoidTag(node.tag)) {
  27570. res += `</${node.tag}>`;
  27571. }
  27572. return res;
  27573. }
  27574. function evaluateConstant(exp) {
  27575. if (exp.type === 4) {
  27576. return new Function(`return (${exp.content})`)();
  27577. } else {
  27578. let res = ``;
  27579. exp.children.forEach((c) => {
  27580. if (isString$1(c) || isSymbol$1(c)) {
  27581. return;
  27582. }
  27583. if (c.type === 2) {
  27584. res += c.content;
  27585. } else if (c.type === 5) {
  27586. res += toDisplayString(evaluateConstant(c.content));
  27587. } else {
  27588. res += evaluateConstant(c);
  27589. }
  27590. });
  27591. return res;
  27592. }
  27593. }
  27594. const ignoreSideEffectTags = (node, context) => {
  27595. if (node.type === 1 && node.tagType === 0 && (node.tag === "script" || node.tag === "style")) {
  27596. context.onError(
  27597. createDOMCompilerError(
  27598. 64,
  27599. node.loc
  27600. )
  27601. );
  27602. context.removeNode();
  27603. }
  27604. };
  27605. function isValidHTMLNesting(parent, child) {
  27606. if (parent === "template") {
  27607. return true;
  27608. }
  27609. if (parent in onlyValidChildren) {
  27610. return onlyValidChildren[parent].has(child);
  27611. }
  27612. if (child in onlyValidParents) {
  27613. return onlyValidParents[child].has(parent);
  27614. }
  27615. if (parent in knownInvalidChildren) {
  27616. if (knownInvalidChildren[parent].has(child)) return false;
  27617. }
  27618. if (child in knownInvalidParents) {
  27619. if (knownInvalidParents[child].has(parent)) return false;
  27620. }
  27621. return true;
  27622. }
  27623. const headings = /* @__PURE__ */ new Set(["h1", "h2", "h3", "h4", "h5", "h6"]);
  27624. const emptySet = /* @__PURE__ */ new Set([]);
  27625. const onlyValidChildren = {
  27626. head: /* @__PURE__ */ new Set([
  27627. "base",
  27628. "basefront",
  27629. "bgsound",
  27630. "link",
  27631. "meta",
  27632. "title",
  27633. "noscript",
  27634. "noframes",
  27635. "style",
  27636. "script",
  27637. "template"
  27638. ]),
  27639. optgroup: /* @__PURE__ */ new Set(["option"]),
  27640. select: /* @__PURE__ */ new Set(["optgroup", "option", "hr"]),
  27641. // table
  27642. table: /* @__PURE__ */ new Set(["caption", "colgroup", "tbody", "tfoot", "thead"]),
  27643. tr: /* @__PURE__ */ new Set(["td", "th"]),
  27644. colgroup: /* @__PURE__ */ new Set(["col"]),
  27645. tbody: /* @__PURE__ */ new Set(["tr"]),
  27646. thead: /* @__PURE__ */ new Set(["tr"]),
  27647. tfoot: /* @__PURE__ */ new Set(["tr"]),
  27648. // these elements can not have any children elements
  27649. script: emptySet,
  27650. iframe: emptySet,
  27651. option: emptySet,
  27652. textarea: emptySet,
  27653. style: emptySet,
  27654. title: emptySet
  27655. };
  27656. const onlyValidParents = {
  27657. // sections
  27658. html: emptySet,
  27659. body: /* @__PURE__ */ new Set(["html"]),
  27660. head: /* @__PURE__ */ new Set(["html"]),
  27661. // table
  27662. td: /* @__PURE__ */ new Set(["tr"]),
  27663. colgroup: /* @__PURE__ */ new Set(["table"]),
  27664. caption: /* @__PURE__ */ new Set(["table"]),
  27665. tbody: /* @__PURE__ */ new Set(["table"]),
  27666. tfoot: /* @__PURE__ */ new Set(["table"]),
  27667. col: /* @__PURE__ */ new Set(["colgroup"]),
  27668. th: /* @__PURE__ */ new Set(["tr"]),
  27669. thead: /* @__PURE__ */ new Set(["table"]),
  27670. tr: /* @__PURE__ */ new Set(["tbody", "thead", "tfoot"]),
  27671. // data list
  27672. dd: /* @__PURE__ */ new Set(["dl", "div"]),
  27673. dt: /* @__PURE__ */ new Set(["dl", "div"]),
  27674. // other
  27675. figcaption: /* @__PURE__ */ new Set(["figure"]),
  27676. // li: new Set(["ul", "ol"]),
  27677. summary: /* @__PURE__ */ new Set(["details"]),
  27678. area: /* @__PURE__ */ new Set(["map"])
  27679. };
  27680. const knownInvalidChildren = {
  27681. p: /* @__PURE__ */ new Set([
  27682. "address",
  27683. "article",
  27684. "aside",
  27685. "blockquote",
  27686. "center",
  27687. "details",
  27688. "dialog",
  27689. "dir",
  27690. "div",
  27691. "dl",
  27692. "fieldset",
  27693. "figure",
  27694. "footer",
  27695. "form",
  27696. "h1",
  27697. "h2",
  27698. "h3",
  27699. "h4",
  27700. "h5",
  27701. "h6",
  27702. "header",
  27703. "hgroup",
  27704. "hr",
  27705. "li",
  27706. "main",
  27707. "nav",
  27708. "menu",
  27709. "ol",
  27710. "p",
  27711. "pre",
  27712. "section",
  27713. "table",
  27714. "ul"
  27715. ]),
  27716. svg: /* @__PURE__ */ new Set([
  27717. "b",
  27718. "blockquote",
  27719. "br",
  27720. "code",
  27721. "dd",
  27722. "div",
  27723. "dl",
  27724. "dt",
  27725. "em",
  27726. "embed",
  27727. "h1",
  27728. "h2",
  27729. "h3",
  27730. "h4",
  27731. "h5",
  27732. "h6",
  27733. "hr",
  27734. "i",
  27735. "img",
  27736. "li",
  27737. "menu",
  27738. "meta",
  27739. "ol",
  27740. "p",
  27741. "pre",
  27742. "ruby",
  27743. "s",
  27744. "small",
  27745. "span",
  27746. "strong",
  27747. "sub",
  27748. "sup",
  27749. "table",
  27750. "u",
  27751. "ul",
  27752. "var"
  27753. ])
  27754. };
  27755. const knownInvalidParents = {
  27756. a: /* @__PURE__ */ new Set(["a"]),
  27757. button: /* @__PURE__ */ new Set(["button"]),
  27758. dd: /* @__PURE__ */ new Set(["dd", "dt"]),
  27759. dt: /* @__PURE__ */ new Set(["dd", "dt"]),
  27760. form: /* @__PURE__ */ new Set(["form"]),
  27761. li: /* @__PURE__ */ new Set(["li"]),
  27762. h1: headings,
  27763. h2: headings,
  27764. h3: headings,
  27765. h4: headings,
  27766. h5: headings,
  27767. h6: headings
  27768. };
  27769. const validateHtmlNesting = (node, context) => {
  27770. if (node.type === 1 && node.tagType === 0 && context.parent && context.parent.type === 1 && context.parent.tagType === 0 && !isValidHTMLNesting(context.parent.tag, node.tag)) {
  27771. const error = new SyntaxError(
  27772. `<${node.tag}> cannot be child of <${context.parent.tag}>, according to HTML specifications. This can cause hydration errors or potentially disrupt future functionality.`
  27773. );
  27774. error.loc = node.loc;
  27775. context.onWarn(error);
  27776. }
  27777. };
  27778. const DOMNodeTransforms = [
  27779. transformStyle,
  27780. ...[transformTransition, validateHtmlNesting]
  27781. ];
  27782. const DOMDirectiveTransforms = {
  27783. cloak: noopDirectiveTransform,
  27784. html: transformVHtml,
  27785. text: transformVText,
  27786. model: transformModel,
  27787. // override compiler-core
  27788. on: transformOn,
  27789. // override compiler-core
  27790. show: transformShow
  27791. };
  27792. function compile$1(src, options = {}) {
  27793. return baseCompile(
  27794. src,
  27795. extend({}, parserOptions, options, {
  27796. nodeTransforms: [
  27797. // ignore <script> and <tag>
  27798. // this is not put inside DOMNodeTransforms because that list is used
  27799. // by compiler-ssr to generate vnode fallback branches
  27800. ignoreSideEffectTags,
  27801. ...DOMNodeTransforms,
  27802. ...options.nodeTransforms || []
  27803. ],
  27804. directiveTransforms: extend(
  27805. {},
  27806. DOMDirectiveTransforms,
  27807. options.directiveTransforms || {}
  27808. ),
  27809. transformHoist: stringifyStatic
  27810. })
  27811. );
  27812. }
  27813. function parse$3(template, options = {}) {
  27814. return baseParse(template, extend({}, parserOptions, options));
  27815. }
  27816. var CompilerDOM = /*#__PURE__*/Object.freeze({
  27817. __proto__: null,
  27818. BASE_TRANSITION: BASE_TRANSITION,
  27819. BindingTypes: BindingTypes,
  27820. CAMELIZE: CAMELIZE,
  27821. CAPITALIZE: CAPITALIZE,
  27822. CREATE_BLOCK: CREATE_BLOCK,
  27823. CREATE_COMMENT: CREATE_COMMENT,
  27824. CREATE_ELEMENT_BLOCK: CREATE_ELEMENT_BLOCK,
  27825. CREATE_ELEMENT_VNODE: CREATE_ELEMENT_VNODE,
  27826. CREATE_SLOTS: CREATE_SLOTS,
  27827. CREATE_STATIC: CREATE_STATIC,
  27828. CREATE_TEXT: CREATE_TEXT,
  27829. CREATE_VNODE: CREATE_VNODE,
  27830. CompilerDeprecationTypes: CompilerDeprecationTypes,
  27831. ConstantTypes: ConstantTypes,
  27832. DOMDirectiveTransforms: DOMDirectiveTransforms,
  27833. DOMErrorCodes: DOMErrorCodes,
  27834. DOMErrorMessages: DOMErrorMessages,
  27835. DOMNodeTransforms: DOMNodeTransforms,
  27836. ElementTypes: ElementTypes,
  27837. ErrorCodes: ErrorCodes,
  27838. FRAGMENT: FRAGMENT,
  27839. GUARD_REACTIVE_PROPS: GUARD_REACTIVE_PROPS,
  27840. IS_MEMO_SAME: IS_MEMO_SAME,
  27841. IS_REF: IS_REF,
  27842. KEEP_ALIVE: KEEP_ALIVE,
  27843. MERGE_PROPS: MERGE_PROPS,
  27844. NORMALIZE_CLASS: NORMALIZE_CLASS,
  27845. NORMALIZE_PROPS: NORMALIZE_PROPS,
  27846. NORMALIZE_STYLE: NORMALIZE_STYLE,
  27847. Namespaces: Namespaces,
  27848. NodeTypes: NodeTypes,
  27849. OPEN_BLOCK: OPEN_BLOCK,
  27850. POP_SCOPE_ID: POP_SCOPE_ID,
  27851. PUSH_SCOPE_ID: PUSH_SCOPE_ID,
  27852. RENDER_LIST: RENDER_LIST,
  27853. RENDER_SLOT: RENDER_SLOT,
  27854. RESOLVE_COMPONENT: RESOLVE_COMPONENT,
  27855. RESOLVE_DIRECTIVE: RESOLVE_DIRECTIVE,
  27856. RESOLVE_DYNAMIC_COMPONENT: RESOLVE_DYNAMIC_COMPONENT,
  27857. RESOLVE_FILTER: RESOLVE_FILTER,
  27858. SET_BLOCK_TRACKING: SET_BLOCK_TRACKING,
  27859. SUSPENSE: SUSPENSE,
  27860. TELEPORT: TELEPORT,
  27861. TO_DISPLAY_STRING: TO_DISPLAY_STRING,
  27862. TO_HANDLERS: TO_HANDLERS,
  27863. TO_HANDLER_KEY: TO_HANDLER_KEY,
  27864. TRANSITION: TRANSITION,
  27865. TRANSITION_GROUP: TRANSITION_GROUP,
  27866. TS_NODE_TYPES: TS_NODE_TYPES,
  27867. UNREF: UNREF,
  27868. V_MODEL_CHECKBOX: V_MODEL_CHECKBOX,
  27869. V_MODEL_DYNAMIC: V_MODEL_DYNAMIC,
  27870. V_MODEL_RADIO: V_MODEL_RADIO,
  27871. V_MODEL_SELECT: V_MODEL_SELECT,
  27872. V_MODEL_TEXT: V_MODEL_TEXT,
  27873. V_ON_WITH_KEYS: V_ON_WITH_KEYS,
  27874. V_ON_WITH_MODIFIERS: V_ON_WITH_MODIFIERS,
  27875. V_SHOW: V_SHOW,
  27876. WITH_CTX: WITH_CTX,
  27877. WITH_DIRECTIVES: WITH_DIRECTIVES,
  27878. WITH_MEMO: WITH_MEMO,
  27879. advancePositionWithClone: advancePositionWithClone,
  27880. advancePositionWithMutation: advancePositionWithMutation,
  27881. assert: assert,
  27882. baseCompile: baseCompile,
  27883. baseParse: baseParse,
  27884. buildDirectiveArgs: buildDirectiveArgs,
  27885. buildProps: buildProps,
  27886. buildSlots: buildSlots,
  27887. checkCompatEnabled: checkCompatEnabled,
  27888. compile: compile$1,
  27889. convertToBlock: convertToBlock,
  27890. createArrayExpression: createArrayExpression,
  27891. createAssignmentExpression: createAssignmentExpression,
  27892. createBlockStatement: createBlockStatement,
  27893. createCacheExpression: createCacheExpression,
  27894. createCallExpression: createCallExpression,
  27895. createCompilerError: createCompilerError,
  27896. createCompoundExpression: createCompoundExpression,
  27897. createConditionalExpression: createConditionalExpression,
  27898. createDOMCompilerError: createDOMCompilerError,
  27899. createForLoopParams: createForLoopParams,
  27900. createFunctionExpression: createFunctionExpression,
  27901. createIfStatement: createIfStatement,
  27902. createInterpolation: createInterpolation,
  27903. createObjectExpression: createObjectExpression,
  27904. createObjectProperty: createObjectProperty,
  27905. createReturnStatement: createReturnStatement,
  27906. createRoot: createRoot,
  27907. createSequenceExpression: createSequenceExpression,
  27908. createSimpleExpression: createSimpleExpression,
  27909. createStructuralDirectiveTransform: createStructuralDirectiveTransform,
  27910. createTemplateLiteral: createTemplateLiteral,
  27911. createTransformContext: createTransformContext,
  27912. createVNodeCall: createVNodeCall,
  27913. errorMessages: errorMessages$1,
  27914. extractIdentifiers: extractIdentifiers$1,
  27915. findDir: findDir,
  27916. findProp: findProp,
  27917. forAliasRE: forAliasRE,
  27918. generate: generate,
  27919. generateCodeFrame: generateCodeFrame,
  27920. getBaseTransformPreset: getBaseTransformPreset,
  27921. getConstantType: getConstantType,
  27922. getMemoedVNodeCall: getMemoedVNodeCall,
  27923. getVNodeBlockHelper: getVNodeBlockHelper,
  27924. getVNodeHelper: getVNodeHelper,
  27925. hasDynamicKeyVBind: hasDynamicKeyVBind,
  27926. hasScopeRef: hasScopeRef,
  27927. helperNameMap: helperNameMap,
  27928. injectProp: injectProp,
  27929. isAllWhitespace: isAllWhitespace,
  27930. isCommentOrWhitespace: isCommentOrWhitespace,
  27931. isCoreComponent: isCoreComponent,
  27932. isFnExpression: isFnExpression,
  27933. isFnExpressionBrowser: isFnExpressionBrowser,
  27934. isFnExpressionNode: isFnExpressionNode,
  27935. isFunctionType: isFunctionType,
  27936. isInDestructureAssignment: isInDestructureAssignment,
  27937. isInNewExpression: isInNewExpression,
  27938. isMemberExpression: isMemberExpression,
  27939. isMemberExpressionBrowser: isMemberExpressionBrowser,
  27940. isMemberExpressionNode: isMemberExpressionNode,
  27941. isReferencedIdentifier: isReferencedIdentifier,
  27942. isSimpleIdentifier: isSimpleIdentifier,
  27943. isSlotOutlet: isSlotOutlet,
  27944. isStaticArgOf: isStaticArgOf,
  27945. isStaticExp: isStaticExp,
  27946. isStaticProperty: isStaticProperty,
  27947. isStaticPropertyKey: isStaticPropertyKey,
  27948. isTemplateNode: isTemplateNode,
  27949. isText: isText$1,
  27950. isVPre: isVPre,
  27951. isVSlot: isVSlot,
  27952. isWhitespaceText: isWhitespaceText,
  27953. locStub: locStub,
  27954. noopDirectiveTransform: noopDirectiveTransform,
  27955. parse: parse$3,
  27956. parserOptions: parserOptions,
  27957. processExpression: processExpression,
  27958. processFor: processFor,
  27959. processIf: processIf,
  27960. processSlotOutlet: processSlotOutlet,
  27961. registerRuntimeHelpers: registerRuntimeHelpers,
  27962. resolveComponentType: resolveComponentType,
  27963. stringifyExpression: stringifyExpression,
  27964. toValidAssetId: toValidAssetId,
  27965. trackSlotScopes: trackSlotScopes,
  27966. trackVForSlotScopes: trackVForSlotScopes,
  27967. transform: transform,
  27968. transformBind: transformBind,
  27969. transformElement: transformElement,
  27970. transformExpression: transformExpression,
  27971. transformModel: transformModel$1,
  27972. transformOn: transformOn$1,
  27973. transformStyle: transformStyle,
  27974. transformVBindShorthand: transformVBindShorthand,
  27975. traverseNode: traverseNode,
  27976. unwrapTSNode: unwrapTSNode,
  27977. validFirstIdentCharRE: validFirstIdentCharRE,
  27978. walkBlockDeclarations: walkBlockDeclarations,
  27979. walkFunctionParams: walkFunctionParams,
  27980. walkIdentifiers: walkIdentifiers,
  27981. warnDeprecation: warnDeprecation
  27982. });
  27983. var hashSum;
  27984. var hasRequiredHashSum;
  27985. function requireHashSum () {
  27986. if (hasRequiredHashSum) return hashSum;
  27987. hasRequiredHashSum = 1;
  27988. function pad (hash, len) {
  27989. while (hash.length < len) {
  27990. hash = '0' + hash;
  27991. }
  27992. return hash;
  27993. }
  27994. function fold (hash, text) {
  27995. var i;
  27996. var chr;
  27997. var len;
  27998. if (text.length === 0) {
  27999. return hash;
  28000. }
  28001. for (i = 0, len = text.length; i < len; i++) {
  28002. chr = text.charCodeAt(i);
  28003. hash = ((hash << 5) - hash) + chr;
  28004. hash |= 0;
  28005. }
  28006. return hash < 0 ? hash * -2 : hash;
  28007. }
  28008. function foldObject (hash, o, seen) {
  28009. return Object.keys(o).sort().reduce(foldKey, hash);
  28010. function foldKey (hash, key) {
  28011. return foldValue(hash, o[key], key, seen);
  28012. }
  28013. }
  28014. function foldValue (input, value, key, seen) {
  28015. var hash = fold(fold(fold(input, key), toString(value)), typeof value);
  28016. if (value === null) {
  28017. return fold(hash, 'null');
  28018. }
  28019. if (value === undefined) {
  28020. return fold(hash, 'undefined');
  28021. }
  28022. if (typeof value === 'object' || typeof value === 'function') {
  28023. if (seen.indexOf(value) !== -1) {
  28024. return fold(hash, '[Circular]' + key);
  28025. }
  28026. seen.push(value);
  28027. var objHash = foldObject(hash, value, seen);
  28028. if (!('valueOf' in value) || typeof value.valueOf !== 'function') {
  28029. return objHash;
  28030. }
  28031. try {
  28032. return fold(objHash, String(value.valueOf()))
  28033. } catch (err) {
  28034. return fold(objHash, '[valueOf exception]' + (err.stack || err.message))
  28035. }
  28036. }
  28037. return fold(hash, value.toString());
  28038. }
  28039. function toString (o) {
  28040. return Object.prototype.toString.call(o);
  28041. }
  28042. function sum (o) {
  28043. return pad(foldValue(0, o, '', []).toString(16), 8);
  28044. }
  28045. hashSum = sum;
  28046. return hashSum;
  28047. }
  28048. var hashSumExports = /*@__PURE__*/ requireHashSum();
  28049. var hash = /*@__PURE__*/getDefaultExportFromCjs(hashSumExports);
  28050. const CSS_VARS_HELPER = `useCssVars`;
  28051. function genCssVarsFromList(vars, id, isProd, isSSR = false) {
  28052. return `{
  28053. ${vars.map(
  28054. (key) => (
  28055. // The `:` prefix here is used in `ssrRenderStyle` to distinguish whether
  28056. // a custom property comes from `ssrCssVars`. If it does, we need to reset
  28057. // its value to `initial` on the component instance to avoid unintentionally
  28058. // inheriting the same property value from a different instance of the same
  28059. // component in the outer scope.
  28060. `"${isSSR ? `:--` : ``}${genVarName(id, key, isProd, isSSR)}": (${key})`
  28061. )
  28062. ).join(",\n ")}
  28063. }`;
  28064. }
  28065. function genVarName(id, raw, isProd, isSSR = false) {
  28066. if (isProd) {
  28067. return hash(id + raw).replace(/^\d/, (r) => `v${r}`);
  28068. } else {
  28069. return `${id}-${getEscapedCssVarName(raw, isSSR)}`;
  28070. }
  28071. }
  28072. function normalizeExpression(exp) {
  28073. exp = exp.trim();
  28074. if (exp[0] === `'` && exp[exp.length - 1] === `'` || exp[0] === `"` && exp[exp.length - 1] === `"`) {
  28075. return exp.slice(1, -1);
  28076. }
  28077. return exp;
  28078. }
  28079. const vBindRE = /v-bind\s*\(/g;
  28080. function parseCssVars(sfc) {
  28081. const vars = [];
  28082. sfc.styles.forEach((style) => {
  28083. let match;
  28084. const content = style.content.replace(/\/\*([\s\S]*?)\*\/|\/\/.*/g, "");
  28085. while (match = vBindRE.exec(content)) {
  28086. const start = match.index + match[0].length;
  28087. const end = lexBinding(content, start);
  28088. if (end !== null) {
  28089. const variable = normalizeExpression(content.slice(start, end));
  28090. if (!vars.includes(variable)) {
  28091. vars.push(variable);
  28092. }
  28093. }
  28094. }
  28095. });
  28096. return vars;
  28097. }
  28098. function lexBinding(content, start) {
  28099. let state = 0 /* inParens */;
  28100. let parenDepth = 0;
  28101. for (let i = start; i < content.length; i++) {
  28102. const char = content.charAt(i);
  28103. switch (state) {
  28104. case 0 /* inParens */:
  28105. if (char === `'`) {
  28106. state = 1 /* inSingleQuoteString */;
  28107. } else if (char === `"`) {
  28108. state = 2 /* inDoubleQuoteString */;
  28109. } else if (char === `(`) {
  28110. parenDepth++;
  28111. } else if (char === `)`) {
  28112. if (parenDepth > 0) {
  28113. parenDepth--;
  28114. } else {
  28115. return i;
  28116. }
  28117. }
  28118. break;
  28119. case 1 /* inSingleQuoteString */:
  28120. if (char === `'`) {
  28121. state = 0 /* inParens */;
  28122. }
  28123. break;
  28124. case 2 /* inDoubleQuoteString */:
  28125. if (char === `"`) {
  28126. state = 0 /* inParens */;
  28127. }
  28128. break;
  28129. }
  28130. }
  28131. return null;
  28132. }
  28133. const cssVarsPlugin = (opts) => {
  28134. const { id, isProd } = opts;
  28135. return {
  28136. postcssPlugin: "vue-sfc-vars",
  28137. Declaration(decl) {
  28138. const value = decl.value;
  28139. if (vBindRE.test(value)) {
  28140. vBindRE.lastIndex = 0;
  28141. let transformed = "";
  28142. let lastIndex = 0;
  28143. let match;
  28144. while (match = vBindRE.exec(value)) {
  28145. const start = match.index + match[0].length;
  28146. const end = lexBinding(value, start);
  28147. if (end !== null) {
  28148. const variable = normalizeExpression(value.slice(start, end));
  28149. transformed += value.slice(lastIndex, match.index) + `var(--${genVarName(id, variable, isProd)})`;
  28150. lastIndex = end + 1;
  28151. }
  28152. }
  28153. decl.value = transformed + value.slice(lastIndex);
  28154. }
  28155. }
  28156. };
  28157. };
  28158. cssVarsPlugin.postcss = true;
  28159. function genCssVarsCode(vars, bindings, id, isProd) {
  28160. const varsExp = genCssVarsFromList(vars, id, isProd);
  28161. const exp = createSimpleExpression(varsExp, false);
  28162. const context = createTransformContext(createRoot([]), {
  28163. prefixIdentifiers: true,
  28164. inline: true,
  28165. bindingMetadata: bindings.__isScriptSetup === false ? void 0 : bindings
  28166. });
  28167. const transformed = processExpression(exp, context);
  28168. const transformedString = transformed.type === 4 ? transformed.content : transformed.children.map((c) => {
  28169. return typeof c === "string" ? c : c.content;
  28170. }).join("");
  28171. return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`;
  28172. }
  28173. function genNormalScriptCssVarsCode(cssVars, bindings, id, isProd, defaultVar) {
  28174. return `
  28175. import { ${CSS_VARS_HELPER} as _${CSS_VARS_HELPER} } from 'vue'
  28176. const __injectCSSVars__ = () => {
  28177. ${genCssVarsCode(
  28178. cssVars,
  28179. bindings,
  28180. id,
  28181. isProd
  28182. )}}
  28183. const __setup__ = ${defaultVar}.setup
  28184. ${defaultVar}.setup = __setup__
  28185. ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }
  28186. : __injectCSSVars__
  28187. `;
  28188. }
  28189. // shim for using process in browser
  28190. // based off https://github.com/defunctzombie/node-process/blob/master/browser.js
  28191. function defaultSetTimout() {
  28192. throw new Error('setTimeout has not been defined');
  28193. }
  28194. function defaultClearTimeout () {
  28195. throw new Error('clearTimeout has not been defined');
  28196. }
  28197. var cachedSetTimeout = defaultSetTimout;
  28198. var cachedClearTimeout = defaultClearTimeout;
  28199. if (typeof global$1.setTimeout === 'function') {
  28200. cachedSetTimeout = setTimeout;
  28201. }
  28202. if (typeof global$1.clearTimeout === 'function') {
  28203. cachedClearTimeout = clearTimeout;
  28204. }
  28205. function runTimeout(fun) {
  28206. if (cachedSetTimeout === setTimeout) {
  28207. //normal enviroments in sane situations
  28208. return setTimeout(fun, 0);
  28209. }
  28210. // if setTimeout wasn't available but was latter defined
  28211. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  28212. cachedSetTimeout = setTimeout;
  28213. return setTimeout(fun, 0);
  28214. }
  28215. try {
  28216. // when when somebody has screwed with setTimeout but no I.E. maddness
  28217. return cachedSetTimeout(fun, 0);
  28218. } catch(e){
  28219. try {
  28220. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  28221. return cachedSetTimeout.call(null, fun, 0);
  28222. } catch(e){
  28223. // 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
  28224. return cachedSetTimeout.call(this, fun, 0);
  28225. }
  28226. }
  28227. }
  28228. function runClearTimeout(marker) {
  28229. if (cachedClearTimeout === clearTimeout) {
  28230. //normal enviroments in sane situations
  28231. return clearTimeout(marker);
  28232. }
  28233. // if clearTimeout wasn't available but was latter defined
  28234. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  28235. cachedClearTimeout = clearTimeout;
  28236. return clearTimeout(marker);
  28237. }
  28238. try {
  28239. // when when somebody has screwed with setTimeout but no I.E. maddness
  28240. return cachedClearTimeout(marker);
  28241. } catch (e){
  28242. try {
  28243. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  28244. return cachedClearTimeout.call(null, marker);
  28245. } catch (e){
  28246. // 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.
  28247. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  28248. return cachedClearTimeout.call(this, marker);
  28249. }
  28250. }
  28251. }
  28252. var queue = [];
  28253. var draining = false;
  28254. var currentQueue;
  28255. var queueIndex = -1;
  28256. function cleanUpNextTick() {
  28257. if (!draining || !currentQueue) {
  28258. return;
  28259. }
  28260. draining = false;
  28261. if (currentQueue.length) {
  28262. queue = currentQueue.concat(queue);
  28263. } else {
  28264. queueIndex = -1;
  28265. }
  28266. if (queue.length) {
  28267. drainQueue();
  28268. }
  28269. }
  28270. function drainQueue() {
  28271. if (draining) {
  28272. return;
  28273. }
  28274. var timeout = runTimeout(cleanUpNextTick);
  28275. draining = true;
  28276. var len = queue.length;
  28277. while(len) {
  28278. currentQueue = queue;
  28279. queue = [];
  28280. while (++queueIndex < len) {
  28281. if (currentQueue) {
  28282. currentQueue[queueIndex].run();
  28283. }
  28284. }
  28285. queueIndex = -1;
  28286. len = queue.length;
  28287. }
  28288. currentQueue = null;
  28289. draining = false;
  28290. runClearTimeout(timeout);
  28291. }
  28292. function nextTick(fun) {
  28293. var args = new Array(arguments.length - 1);
  28294. if (arguments.length > 1) {
  28295. for (var i = 1; i < arguments.length; i++) {
  28296. args[i - 1] = arguments[i];
  28297. }
  28298. }
  28299. queue.push(new Item(fun, args));
  28300. if (queue.length === 1 && !draining) {
  28301. runTimeout(drainQueue);
  28302. }
  28303. }
  28304. // v8 likes predictible objects
  28305. function Item(fun, array) {
  28306. this.fun = fun;
  28307. this.array = array;
  28308. }
  28309. Item.prototype.run = function () {
  28310. this.fun.apply(null, this.array);
  28311. };
  28312. var title = 'browser';
  28313. var platform = 'browser';
  28314. var browser = true;
  28315. var env = {};
  28316. var argv = [];
  28317. var version$1 = ''; // empty string to avoid regexp issues
  28318. var versions = {};
  28319. var release = {};
  28320. var config = {};
  28321. function noop() {}
  28322. var on = noop;
  28323. var addListener = noop;
  28324. var once = noop;
  28325. var off = noop;
  28326. var removeListener = noop;
  28327. var removeAllListeners = noop;
  28328. var emit = noop;
  28329. function binding(name) {
  28330. throw new Error('process.binding is not supported');
  28331. }
  28332. function cwd () { return '/' }
  28333. function chdir (dir) {
  28334. throw new Error('process.chdir is not supported');
  28335. }function umask() { return 0; }
  28336. // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
  28337. var performance = global$1.performance || {};
  28338. var performanceNow =
  28339. performance.now ||
  28340. performance.mozNow ||
  28341. performance.msNow ||
  28342. performance.oNow ||
  28343. performance.webkitNow ||
  28344. function(){ return (new Date()).getTime() };
  28345. // generate timestamp or delta
  28346. // see http://nodejs.org/api/process.html#process_process_hrtime
  28347. function hrtime(previousTimestamp){
  28348. var clocktime = performanceNow.call(performance)*1e-3;
  28349. var seconds = Math.floor(clocktime);
  28350. var nanoseconds = Math.floor((clocktime%1)*1e9);
  28351. if (previousTimestamp) {
  28352. seconds = seconds - previousTimestamp[0];
  28353. nanoseconds = nanoseconds - previousTimestamp[1];
  28354. if (nanoseconds<0) {
  28355. seconds--;
  28356. nanoseconds += 1e9;
  28357. }
  28358. }
  28359. return [seconds,nanoseconds]
  28360. }
  28361. var startTime = new Date();
  28362. function uptime() {
  28363. var currentTime = new Date();
  28364. var dif = currentTime - startTime;
  28365. return dif / 1000;
  28366. }
  28367. var browser$1 = {
  28368. nextTick: nextTick,
  28369. title: title,
  28370. browser: browser,
  28371. env: env,
  28372. argv: argv,
  28373. version: version$1,
  28374. versions: versions,
  28375. on: on,
  28376. addListener: addListener,
  28377. once: once,
  28378. off: off,
  28379. removeListener: removeListener,
  28380. removeAllListeners: removeAllListeners,
  28381. emit: emit,
  28382. binding: binding,
  28383. cwd: cwd,
  28384. chdir: chdir,
  28385. umask: umask,
  28386. hrtime: hrtime,
  28387. platform: platform,
  28388. release: release,
  28389. config: config,
  28390. uptime: uptime
  28391. };
  28392. function createCache(max = 500) {
  28393. {
  28394. return /* @__PURE__ */ new Map();
  28395. }
  28396. }
  28397. var __defProp$b = Object.defineProperty;
  28398. var __defProps$a = Object.defineProperties;
  28399. var __getOwnPropDescs$a = Object.getOwnPropertyDescriptors;
  28400. var __getOwnPropSymbols$b = Object.getOwnPropertySymbols;
  28401. var __hasOwnProp$b = Object.prototype.hasOwnProperty;
  28402. var __propIsEnum$b = Object.prototype.propertyIsEnumerable;
  28403. var __defNormalProp$b = (obj, key, value) => key in obj ? __defProp$b(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  28404. var __spreadValues$b = (a, b) => {
  28405. for (var prop in b || (b = {}))
  28406. if (__hasOwnProp$b.call(b, prop))
  28407. __defNormalProp$b(a, prop, b[prop]);
  28408. if (__getOwnPropSymbols$b)
  28409. for (var prop of __getOwnPropSymbols$b(b)) {
  28410. if (__propIsEnum$b.call(b, prop))
  28411. __defNormalProp$b(a, prop, b[prop]);
  28412. }
  28413. return a;
  28414. };
  28415. var __spreadProps$a = (a, b) => __defProps$a(a, __getOwnPropDescs$a(b));
  28416. function resolveTemplateAST(inAST, options) {
  28417. if (!(inAST == null ? void 0 : inAST.transformed)) {
  28418. return inAST;
  28419. }
  28420. const { compiler = CompilerDOM, compilerOptions, ssr, onError } = options;
  28421. const newAST = (ssr ? CompilerDOM : compiler).parse(inAST.source, __spreadProps$a(__spreadValues$b({
  28422. prefixIdentifiers: true
  28423. }, compilerOptions), {
  28424. parseMode: "sfc",
  28425. onError
  28426. }));
  28427. const template = newAST.children.find(
  28428. (node) => node.type === 1 && node.tag === "template"
  28429. );
  28430. return createRoot(template.children, inAST.source);
  28431. }
  28432. function isImportUsed(local, sfc, options) {
  28433. return resolveTemplateUsedIdentifiers(sfc, options).has(local);
  28434. }
  28435. const templateAnalysisCache = createCache();
  28436. function resolveTemplateVModelIdentifiers(sfc, options) {
  28437. return resolveTemplateAnalysisResult(sfc, false, options).vModelIds;
  28438. }
  28439. function resolveTemplateUsedIdentifiers(sfc, options) {
  28440. return resolveTemplateAnalysisResult(sfc, true, options).usedIds;
  28441. }
  28442. function resolveTemplateAnalysisResult(sfc, collectUsedIds = true, options) {
  28443. const { content, ast } = sfc.template;
  28444. const cached = templateAnalysisCache.get(content);
  28445. if (cached && (!collectUsedIds || cached.usedIds)) {
  28446. return cached;
  28447. }
  28448. const ids = collectUsedIds ? /* @__PURE__ */ new Set() : void 0;
  28449. const vModelIds = /* @__PURE__ */ new Set();
  28450. const root = resolveTemplateAST(ast, {
  28451. compiler: options == null ? void 0 : options.compiler,
  28452. compilerOptions: options == null ? void 0 : options.compilerOptions,
  28453. ssr: options == null ? void 0 : options.ssr,
  28454. // ignore errors since they were already reported by the SFC parser
  28455. onError: () => {
  28456. }
  28457. });
  28458. root.children.forEach(walk);
  28459. function walk(node) {
  28460. var _a;
  28461. switch (node.type) {
  28462. case 1:
  28463. let tag = node.tag;
  28464. if (tag.includes(".")) tag = tag.split(".")[0].trim();
  28465. if (!parserOptions.isNativeTag(tag) && !parserOptions.isBuiltInComponent(tag)) {
  28466. if (ids) {
  28467. ids.add(camelize(tag));
  28468. ids.add(capitalize(camelize(tag)));
  28469. }
  28470. }
  28471. for (let i = 0; i < node.props.length; i++) {
  28472. const prop = node.props[i];
  28473. if (prop.type === 7) {
  28474. if (ids) {
  28475. if (!isBuiltInDirective(prop.name)) {
  28476. ids.add(`v${capitalize(camelize(prop.name))}`);
  28477. }
  28478. }
  28479. if (prop.name === "model") {
  28480. const exp = prop.exp;
  28481. if (exp && exp.type === 4) {
  28482. const expString = exp.content.trim();
  28483. if (isSimpleIdentifier(expString) && expString !== "undefined") {
  28484. vModelIds.add(expString);
  28485. }
  28486. }
  28487. }
  28488. if (ids && prop.arg && !prop.arg.isStatic) {
  28489. extractIdentifiers(ids, prop.arg);
  28490. }
  28491. if (ids) {
  28492. if (prop.name === "for") {
  28493. extractIdentifiers(ids, prop.forParseResult.source);
  28494. } else if (prop.exp) {
  28495. extractIdentifiers(ids, prop.exp);
  28496. } else if (prop.name === "bind" && !prop.exp) {
  28497. ids.add(camelize(prop.arg.content));
  28498. }
  28499. }
  28500. }
  28501. if (ids && prop.type === 6 && prop.name === "ref" && ((_a = prop.value) == null ? void 0 : _a.content)) {
  28502. ids.add(prop.value.content);
  28503. }
  28504. }
  28505. node.children.forEach(walk);
  28506. break;
  28507. case 5:
  28508. if (ids) extractIdentifiers(ids, node.content);
  28509. break;
  28510. }
  28511. }
  28512. const result = { usedIds: ids, vModelIds };
  28513. templateAnalysisCache.set(content, result);
  28514. return result;
  28515. }
  28516. function extractIdentifiers(ids, node) {
  28517. if (node.ast) {
  28518. walkIdentifiers(node.ast, (n) => ids.add(n.name));
  28519. } else if (node.ast === null) {
  28520. ids.add(node.content);
  28521. }
  28522. }
  28523. var __defProp$a = Object.defineProperty;
  28524. var __defProps$9 = Object.defineProperties;
  28525. var __getOwnPropDescs$9 = Object.getOwnPropertyDescriptors;
  28526. var __getOwnPropSymbols$a = Object.getOwnPropertySymbols;
  28527. var __hasOwnProp$a = Object.prototype.hasOwnProperty;
  28528. var __propIsEnum$a = Object.prototype.propertyIsEnumerable;
  28529. var __defNormalProp$a = (obj, key, value) => key in obj ? __defProp$a(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  28530. var __spreadValues$a = (a, b) => {
  28531. for (var prop in b || (b = {}))
  28532. if (__hasOwnProp$a.call(b, prop))
  28533. __defNormalProp$a(a, prop, b[prop]);
  28534. if (__getOwnPropSymbols$a)
  28535. for (var prop of __getOwnPropSymbols$a(b)) {
  28536. if (__propIsEnum$a.call(b, prop))
  28537. __defNormalProp$a(a, prop, b[prop]);
  28538. }
  28539. return a;
  28540. };
  28541. var __spreadProps$9 = (a, b) => __defProps$9(a, __getOwnPropDescs$9(b));
  28542. const DEFAULT_FILENAME = "anonymous.vue";
  28543. const parseCache$1 = createCache();
  28544. function parse$2(source, options = {}) {
  28545. var _a;
  28546. const sourceKey = genCacheKey(source, __spreadProps$9(__spreadValues$a({}, options), {
  28547. compiler: { parse: (_a = options.compiler) == null ? void 0 : _a.parse }
  28548. }));
  28549. const cache = parseCache$1.get(sourceKey);
  28550. if (cache) {
  28551. return cache;
  28552. }
  28553. const {
  28554. sourceMap = true,
  28555. filename = DEFAULT_FILENAME,
  28556. sourceRoot = "",
  28557. pad = false,
  28558. ignoreEmpty = true,
  28559. compiler = CompilerDOM,
  28560. templateParseOptions = {}
  28561. } = options;
  28562. const descriptor = {
  28563. filename,
  28564. source,
  28565. template: null,
  28566. script: null,
  28567. scriptSetup: null,
  28568. styles: [],
  28569. customBlocks: [],
  28570. cssVars: [],
  28571. slotted: false,
  28572. shouldForceReload: (prevImports) => hmrShouldReload(prevImports, descriptor)
  28573. };
  28574. const errors = [];
  28575. const ast = compiler.parse(source, __spreadProps$9(__spreadValues$a({
  28576. parseMode: "sfc",
  28577. prefixIdentifiers: true
  28578. }, templateParseOptions), {
  28579. onError: (e) => {
  28580. errors.push(e);
  28581. }
  28582. }));
  28583. ast.children.forEach((node) => {
  28584. if (node.type !== 1) {
  28585. return;
  28586. }
  28587. if (ignoreEmpty && node.tag !== "template" && isEmpty(node) && !hasSrc(node)) {
  28588. return;
  28589. }
  28590. switch (node.tag) {
  28591. case "template":
  28592. if (!descriptor.template) {
  28593. const templateBlock = descriptor.template = createBlock(
  28594. node,
  28595. source,
  28596. false
  28597. );
  28598. if (!templateBlock.attrs.src) {
  28599. templateBlock.ast = createRoot(node.children, source);
  28600. }
  28601. if (templateBlock.attrs.functional) {
  28602. const err = new SyntaxError(
  28603. `<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.`
  28604. );
  28605. err.loc = node.props.find(
  28606. (p) => p.type === 6 && p.name === "functional"
  28607. ).loc;
  28608. errors.push(err);
  28609. }
  28610. } else {
  28611. errors.push(createDuplicateBlockError(node));
  28612. }
  28613. break;
  28614. case "script":
  28615. const scriptBlock = createBlock(node, source, pad);
  28616. const isSetup = !!scriptBlock.attrs.setup;
  28617. if (isSetup && !descriptor.scriptSetup) {
  28618. descriptor.scriptSetup = scriptBlock;
  28619. break;
  28620. }
  28621. if (!isSetup && !descriptor.script) {
  28622. descriptor.script = scriptBlock;
  28623. break;
  28624. }
  28625. errors.push(createDuplicateBlockError(node, isSetup));
  28626. break;
  28627. case "style":
  28628. const styleBlock = createBlock(node, source, pad);
  28629. if (styleBlock.attrs.vars) {
  28630. errors.push(
  28631. new SyntaxError(
  28632. `<style vars> has been replaced by a new proposal: https://github.com/vuejs/rfcs/pull/231`
  28633. )
  28634. );
  28635. }
  28636. descriptor.styles.push(styleBlock);
  28637. break;
  28638. default:
  28639. descriptor.customBlocks.push(createBlock(node, source, pad));
  28640. break;
  28641. }
  28642. });
  28643. if (!descriptor.template && !descriptor.script && !descriptor.scriptSetup) {
  28644. errors.push(
  28645. new SyntaxError(
  28646. `At least one <template> or <script> is required in a single file component. ${descriptor.filename}`
  28647. )
  28648. );
  28649. }
  28650. if (descriptor.scriptSetup) {
  28651. if (descriptor.scriptSetup.src) {
  28652. errors.push(
  28653. new SyntaxError(
  28654. `<script setup> cannot use the "src" attribute because its syntax will be ambiguous outside of the component.`
  28655. )
  28656. );
  28657. descriptor.scriptSetup = null;
  28658. }
  28659. if (descriptor.script && descriptor.script.src) {
  28660. errors.push(
  28661. new SyntaxError(
  28662. `<script> cannot use the "src" attribute when <script setup> is also present because they must be processed together.`
  28663. )
  28664. );
  28665. descriptor.script = null;
  28666. }
  28667. }
  28668. let templateColumnOffset = 0;
  28669. if (descriptor.template && (descriptor.template.lang === "pug" || descriptor.template.lang === "jade")) {
  28670. [descriptor.template.content, templateColumnOffset] = dedent(
  28671. descriptor.template.content
  28672. );
  28673. }
  28674. if (sourceMap) {
  28675. const genMap = (block, columnOffset = 0) => {
  28676. if (block && !block.src) {
  28677. block.map = generateSourceMap(
  28678. filename,
  28679. source,
  28680. block.content,
  28681. sourceRoot,
  28682. !pad || block.type === "template" ? block.loc.start.line - 1 : 0,
  28683. columnOffset
  28684. );
  28685. }
  28686. };
  28687. genMap(descriptor.template, templateColumnOffset);
  28688. genMap(descriptor.script);
  28689. descriptor.styles.forEach((s) => genMap(s));
  28690. descriptor.customBlocks.forEach((s) => genMap(s));
  28691. }
  28692. descriptor.cssVars = parseCssVars(descriptor);
  28693. const slottedRE = /(?:::v-|:)slotted\(/;
  28694. descriptor.slotted = descriptor.styles.some(
  28695. (s) => s.scoped && slottedRE.test(s.content)
  28696. );
  28697. const result = {
  28698. descriptor,
  28699. errors
  28700. };
  28701. parseCache$1.set(sourceKey, result);
  28702. return result;
  28703. }
  28704. function createDuplicateBlockError(node, isScriptSetup = false) {
  28705. const err = new SyntaxError(
  28706. `Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element`
  28707. );
  28708. err.loc = node.loc;
  28709. return err;
  28710. }
  28711. function createBlock(node, source, pad) {
  28712. const type = node.tag;
  28713. const loc = node.innerLoc;
  28714. const attrs = {};
  28715. const block = {
  28716. type,
  28717. content: source.slice(loc.start.offset, loc.end.offset),
  28718. loc,
  28719. attrs
  28720. };
  28721. if (pad) {
  28722. block.content = padContent(source, block, pad) + block.content;
  28723. }
  28724. node.props.forEach((p) => {
  28725. if (p.type === 6) {
  28726. const name = p.name;
  28727. attrs[name] = p.value ? p.value.content || true : true;
  28728. if (name === "lang") {
  28729. block.lang = p.value && p.value.content;
  28730. } else if (name === "src") {
  28731. block.src = p.value && p.value.content;
  28732. } else if (type === "style") {
  28733. if (name === "scoped") {
  28734. block.scoped = true;
  28735. } else if (name === "module") {
  28736. block.module = attrs[name];
  28737. }
  28738. } else if (type === "script" && name === "setup") {
  28739. block.setup = attrs.setup;
  28740. }
  28741. }
  28742. });
  28743. return block;
  28744. }
  28745. const splitRE = /\r?\n/g;
  28746. const emptyRE = /^(?:\/\/)?\s*$/;
  28747. const replaceRE = /./g;
  28748. function generateSourceMap(filename, source, generated, sourceRoot, lineOffset, columnOffset) {
  28749. const map = new sourceMapExports.SourceMapGenerator({
  28750. file: filename.replace(/\\/g, "/"),
  28751. sourceRoot: sourceRoot.replace(/\\/g, "/")
  28752. });
  28753. map.setSourceContent(filename, source);
  28754. map._sources.add(filename);
  28755. generated.split(splitRE).forEach((line, index) => {
  28756. if (!emptyRE.test(line)) {
  28757. const originalLine = index + 1 + lineOffset;
  28758. const generatedLine = index + 1;
  28759. for (let i = 0; i < line.length; i++) {
  28760. if (!/\s/.test(line[i])) {
  28761. map._mappings.add({
  28762. originalLine,
  28763. originalColumn: i + columnOffset,
  28764. generatedLine,
  28765. generatedColumn: i,
  28766. source: filename,
  28767. name: null
  28768. });
  28769. }
  28770. }
  28771. }
  28772. });
  28773. return map.toJSON();
  28774. }
  28775. function padContent(content, block, pad) {
  28776. content = content.slice(0, block.loc.start.offset);
  28777. if (pad === "space") {
  28778. return content.replace(replaceRE, " ");
  28779. } else {
  28780. const offset = content.split(splitRE).length;
  28781. const padChar = block.type === "script" && !block.lang ? "//\n" : "\n";
  28782. return Array(offset).join(padChar);
  28783. }
  28784. }
  28785. function hasSrc(node) {
  28786. return node.props.some((p) => {
  28787. if (p.type !== 6) {
  28788. return false;
  28789. }
  28790. return p.name === "src";
  28791. });
  28792. }
  28793. function isEmpty(node) {
  28794. for (let i = 0; i < node.children.length; i++) {
  28795. const child = node.children[i];
  28796. if (child.type !== 2 || child.content.trim() !== "") {
  28797. return false;
  28798. }
  28799. }
  28800. return true;
  28801. }
  28802. function hmrShouldReload(prevImports, next) {
  28803. if (!next.scriptSetup || next.scriptSetup.lang !== "ts" && next.scriptSetup.lang !== "tsx") {
  28804. return false;
  28805. }
  28806. for (const key in prevImports) {
  28807. if (!prevImports[key].isUsedInTemplate && isImportUsed(key, next)) {
  28808. return true;
  28809. }
  28810. }
  28811. return false;
  28812. }
  28813. function dedent(s) {
  28814. const lines = s.split("\n");
  28815. const minIndent = lines.reduce(function(minIndent2, line) {
  28816. var _a, _b;
  28817. if (line.trim() === "") {
  28818. return minIndent2;
  28819. }
  28820. const indent = ((_b = (_a = line.match(/^\s*/)) == null ? void 0 : _a[0]) == null ? void 0 : _b.length) || 0;
  28821. return Math.min(indent, minIndent2);
  28822. }, Infinity);
  28823. if (minIndent === 0) {
  28824. return [s, minIndent];
  28825. }
  28826. return [
  28827. lines.map(function(line) {
  28828. return line.slice(minIndent);
  28829. }).join("\n"),
  28830. minIndent
  28831. ];
  28832. }
  28833. // Copyright Joyent, Inc. and other Node contributors.
  28834. //
  28835. // Permission is hereby granted, free of charge, to any person obtaining a
  28836. // copy of this software and associated documentation files (the
  28837. // "Software"), to deal in the Software without restriction, including
  28838. // without limitation the rights to use, copy, modify, merge, publish,
  28839. // distribute, sublicense, and/or sell copies of the Software, and to permit
  28840. // persons to whom the Software is furnished to do so, subject to the
  28841. // following conditions:
  28842. //
  28843. // The above copyright notice and this permission notice shall be included
  28844. // in all copies or substantial portions of the Software.
  28845. //
  28846. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  28847. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  28848. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  28849. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  28850. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  28851. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  28852. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  28853. // resolves . and .. elements in a path array with directory names there
  28854. // must be no slashes, empty elements, or device names (c:\) in the array
  28855. // (so also no leading and trailing slashes - it does not distinguish
  28856. // relative and absolute paths)
  28857. function normalizeArray(parts, allowAboveRoot) {
  28858. // if the path tries to go above the root, `up` ends up > 0
  28859. var up = 0;
  28860. for (var i = parts.length - 1; i >= 0; i--) {
  28861. var last = parts[i];
  28862. if (last === '.') {
  28863. parts.splice(i, 1);
  28864. } else if (last === '..') {
  28865. parts.splice(i, 1);
  28866. up++;
  28867. } else if (up) {
  28868. parts.splice(i, 1);
  28869. up--;
  28870. }
  28871. }
  28872. // if the path is allowed to go above the root, restore leading ..s
  28873. if (allowAboveRoot) {
  28874. for (; up--; up) {
  28875. parts.unshift('..');
  28876. }
  28877. }
  28878. return parts;
  28879. }
  28880. // Split a filename into [root, dir, basename, ext], unix version
  28881. // 'root' is just a slash, or nothing.
  28882. var splitPathRe =
  28883. /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
  28884. var splitPath = function(filename) {
  28885. return splitPathRe.exec(filename).slice(1);
  28886. };
  28887. // path.resolve([from ...], to)
  28888. // posix version
  28889. function resolve() {
  28890. var resolvedPath = '',
  28891. resolvedAbsolute = false;
  28892. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  28893. var path = (i >= 0) ? arguments[i] : '/';
  28894. // Skip empty and invalid entries
  28895. if (typeof path !== 'string') {
  28896. throw new TypeError('Arguments to path.resolve must be strings');
  28897. } else if (!path) {
  28898. continue;
  28899. }
  28900. resolvedPath = path + '/' + resolvedPath;
  28901. resolvedAbsolute = path.charAt(0) === '/';
  28902. }
  28903. // At this point the path should be resolved to a full absolute path, but
  28904. // handle relative paths to be safe (might happen when process.cwd() fails)
  28905. // Normalize the path
  28906. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  28907. return !!p;
  28908. }), !resolvedAbsolute).join('/');
  28909. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  28910. }
  28911. // path.normalize(path)
  28912. // posix version
  28913. function normalize$1(path) {
  28914. var isPathAbsolute = isAbsolute(path),
  28915. trailingSlash = substr(path, -1) === '/';
  28916. // Normalize the path
  28917. path = normalizeArray(filter(path.split('/'), function(p) {
  28918. return !!p;
  28919. }), !isPathAbsolute).join('/');
  28920. if (!path && !isPathAbsolute) {
  28921. path = '.';
  28922. }
  28923. if (path && trailingSlash) {
  28924. path += '/';
  28925. }
  28926. return (isPathAbsolute ? '/' : '') + path;
  28927. }
  28928. // posix version
  28929. function isAbsolute(path) {
  28930. return path.charAt(0) === '/';
  28931. }
  28932. // posix version
  28933. function join() {
  28934. var paths = Array.prototype.slice.call(arguments, 0);
  28935. return normalize$1(filter(paths, function(p, index) {
  28936. if (typeof p !== 'string') {
  28937. throw new TypeError('Arguments to path.join must be strings');
  28938. }
  28939. return p;
  28940. }).join('/'));
  28941. }
  28942. // path.relative(from, to)
  28943. // posix version
  28944. function relative(from, to) {
  28945. from = resolve(from).substr(1);
  28946. to = resolve(to).substr(1);
  28947. function trim(arr) {
  28948. var start = 0;
  28949. for (; start < arr.length; start++) {
  28950. if (arr[start] !== '') break;
  28951. }
  28952. var end = arr.length - 1;
  28953. for (; end >= 0; end--) {
  28954. if (arr[end] !== '') break;
  28955. }
  28956. if (start > end) return [];
  28957. return arr.slice(start, end - start + 1);
  28958. }
  28959. var fromParts = trim(from.split('/'));
  28960. var toParts = trim(to.split('/'));
  28961. var length = Math.min(fromParts.length, toParts.length);
  28962. var samePartsLength = length;
  28963. for (var i = 0; i < length; i++) {
  28964. if (fromParts[i] !== toParts[i]) {
  28965. samePartsLength = i;
  28966. break;
  28967. }
  28968. }
  28969. var outputParts = [];
  28970. for (var i = samePartsLength; i < fromParts.length; i++) {
  28971. outputParts.push('..');
  28972. }
  28973. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  28974. return outputParts.join('/');
  28975. }
  28976. var sep = '/';
  28977. var delimiter$1 = ':';
  28978. function dirname(path) {
  28979. var result = splitPath(path),
  28980. root = result[0],
  28981. dir = result[1];
  28982. if (!root && !dir) {
  28983. // No dirname whatsoever
  28984. return '.';
  28985. }
  28986. if (dir) {
  28987. // It has a dirname, strip trailing slash
  28988. dir = dir.substr(0, dir.length - 1);
  28989. }
  28990. return root + dir;
  28991. }
  28992. function basename(path, ext) {
  28993. var f = splitPath(path)[2];
  28994. // TODO: make this comparison case-insensitive on windows?
  28995. if (ext && f.substr(-1 * ext.length) === ext) {
  28996. f = f.substr(0, f.length - ext.length);
  28997. }
  28998. return f;
  28999. }
  29000. function extname(path) {
  29001. return splitPath(path)[3];
  29002. }
  29003. var path = {
  29004. extname: extname,
  29005. basename: basename,
  29006. dirname: dirname,
  29007. sep: sep,
  29008. delimiter: delimiter$1,
  29009. relative: relative,
  29010. join: join,
  29011. isAbsolute: isAbsolute,
  29012. normalize: normalize$1,
  29013. resolve: resolve
  29014. };
  29015. function filter (xs, f) {
  29016. if (xs.filter) return xs.filter(f);
  29017. var res = [];
  29018. for (var i = 0; i < xs.length; i++) {
  29019. if (f(xs[i], i, xs)) res.push(xs[i]);
  29020. }
  29021. return res;
  29022. }
  29023. // String.prototype.substr - negative index don't work in IE8
  29024. var substr = 'ab'.substr(-1) === 'b' ?
  29025. function (str, start, len) { return str.substr(start, len) } :
  29026. function (str, start, len) {
  29027. if (start < 0) start = str.length + start;
  29028. return str.substr(start, len);
  29029. }
  29030. ;
  29031. var _polyfillNode_path = /*#__PURE__*/Object.freeze({
  29032. __proto__: null,
  29033. basename: basename,
  29034. default: path,
  29035. delimiter: delimiter$1,
  29036. dirname: dirname,
  29037. extname: extname,
  29038. isAbsolute: isAbsolute,
  29039. join: join,
  29040. normalize: normalize$1,
  29041. relative: relative,
  29042. resolve: resolve,
  29043. sep: sep
  29044. });
  29045. /*! https://mths.be/punycode v1.4.1 by @mathias */
  29046. /** Highest positive signed 32-bit float value */
  29047. var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
  29048. /** Bootstring parameters */
  29049. var base = 36;
  29050. var tMin = 1;
  29051. var tMax = 26;
  29052. var skew = 38;
  29053. var damp = 700;
  29054. var initialBias = 72;
  29055. var initialN = 128; // 0x80
  29056. var delimiter = '-'; // '\x2D'
  29057. var regexNonASCII = /[^\x20-\x7E]/; // unprintable ASCII chars + non-ASCII chars
  29058. var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
  29059. /** Error messages */
  29060. var errors = {
  29061. 'overflow': 'Overflow: input needs wider integers to process',
  29062. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  29063. 'invalid-input': 'Invalid input'
  29064. };
  29065. /** Convenience shortcuts */
  29066. var baseMinusTMin = base - tMin;
  29067. var floor = Math.floor;
  29068. var stringFromCharCode = String.fromCharCode;
  29069. /*--------------------------------------------------------------------------*/
  29070. /**
  29071. * A generic error utility function.
  29072. * @private
  29073. * @param {String} type The error type.
  29074. * @returns {Error} Throws a `RangeError` with the applicable error message.
  29075. */
  29076. function error(type) {
  29077. throw new RangeError(errors[type]);
  29078. }
  29079. /**
  29080. * A generic `Array#map` utility function.
  29081. * @private
  29082. * @param {Array} array The array to iterate over.
  29083. * @param {Function} callback The function that gets called for every array
  29084. * item.
  29085. * @returns {Array} A new array of values returned by the callback function.
  29086. */
  29087. function map$1(array, fn) {
  29088. var length = array.length;
  29089. var result = [];
  29090. while (length--) {
  29091. result[length] = fn(array[length]);
  29092. }
  29093. return result;
  29094. }
  29095. /**
  29096. * A simple `Array#map`-like wrapper to work with domain name strings or email
  29097. * addresses.
  29098. * @private
  29099. * @param {String} domain The domain name or email address.
  29100. * @param {Function} callback The function that gets called for every
  29101. * character.
  29102. * @returns {Array} A new string of characters returned by the callback
  29103. * function.
  29104. */
  29105. function mapDomain(string, fn) {
  29106. var parts = string.split('@');
  29107. var result = '';
  29108. if (parts.length > 1) {
  29109. // In email addresses, only the domain name should be punycoded. Leave
  29110. // the local part (i.e. everything up to `@`) intact.
  29111. result = parts[0] + '@';
  29112. string = parts[1];
  29113. }
  29114. // Avoid `split(regex)` for IE8 compatibility. See #17.
  29115. string = string.replace(regexSeparators, '\x2E');
  29116. var labels = string.split('.');
  29117. var encoded = map$1(labels, fn).join('.');
  29118. return result + encoded;
  29119. }
  29120. /**
  29121. * Creates an array containing the numeric code points of each Unicode
  29122. * character in the string. While JavaScript uses UCS-2 internally,
  29123. * this function will convert a pair of surrogate halves (each of which
  29124. * UCS-2 exposes as separate characters) into a single code point,
  29125. * matching UTF-16.
  29126. * @see `punycode.ucs2.encode`
  29127. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  29128. * @memberOf punycode.ucs2
  29129. * @name decode
  29130. * @param {String} string The Unicode input string (UCS-2).
  29131. * @returns {Array} The new array of code points.
  29132. */
  29133. function ucs2decode(string) {
  29134. var output = [],
  29135. counter = 0,
  29136. length = string.length,
  29137. value,
  29138. extra;
  29139. while (counter < length) {
  29140. value = string.charCodeAt(counter++);
  29141. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  29142. // high surrogate, and there is a next character
  29143. extra = string.charCodeAt(counter++);
  29144. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  29145. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  29146. } else {
  29147. // unmatched surrogate; only append this code unit, in case the next
  29148. // code unit is the high surrogate of a surrogate pair
  29149. output.push(value);
  29150. counter--;
  29151. }
  29152. } else {
  29153. output.push(value);
  29154. }
  29155. }
  29156. return output;
  29157. }
  29158. /**
  29159. * Converts a digit/integer into a basic code point.
  29160. * @see `basicToDigit()`
  29161. * @private
  29162. * @param {Number} digit The numeric value of a basic code point.
  29163. * @returns {Number} The basic code point whose value (when used for
  29164. * representing integers) is `digit`, which needs to be in the range
  29165. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  29166. * used; else, the lowercase form is used. The behavior is undefined
  29167. * if `flag` is non-zero and `digit` has no uppercase form.
  29168. */
  29169. function digitToBasic(digit, flag) {
  29170. // 0..25 map to ASCII a..z or A..Z
  29171. // 26..35 map to ASCII 0..9
  29172. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  29173. }
  29174. /**
  29175. * Bias adaptation function as per section 3.4 of RFC 3492.
  29176. * https://tools.ietf.org/html/rfc3492#section-3.4
  29177. * @private
  29178. */
  29179. function adapt(delta, numPoints, firstTime) {
  29180. var k = 0;
  29181. delta = firstTime ? floor(delta / damp) : delta >> 1;
  29182. delta += floor(delta / numPoints);
  29183. for ( /* no initialization */ ; delta > baseMinusTMin * tMax >> 1; k += base) {
  29184. delta = floor(delta / baseMinusTMin);
  29185. }
  29186. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  29187. }
  29188. /**
  29189. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  29190. * Punycode string of ASCII-only symbols.
  29191. * @memberOf punycode
  29192. * @param {String} input The string of Unicode symbols.
  29193. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  29194. */
  29195. function encode$1(input) {
  29196. var n,
  29197. delta,
  29198. handledCPCount,
  29199. basicLength,
  29200. bias,
  29201. j,
  29202. m,
  29203. q,
  29204. k,
  29205. t,
  29206. currentValue,
  29207. output = [],
  29208. /** `inputLength` will hold the number of code points in `input`. */
  29209. inputLength,
  29210. /** Cached calculation results */
  29211. handledCPCountPlusOne,
  29212. baseMinusT,
  29213. qMinusT;
  29214. // Convert the input in UCS-2 to Unicode
  29215. input = ucs2decode(input);
  29216. // Cache the length
  29217. inputLength = input.length;
  29218. // Initialize the state
  29219. n = initialN;
  29220. delta = 0;
  29221. bias = initialBias;
  29222. // Handle the basic code points
  29223. for (j = 0; j < inputLength; ++j) {
  29224. currentValue = input[j];
  29225. if (currentValue < 0x80) {
  29226. output.push(stringFromCharCode(currentValue));
  29227. }
  29228. }
  29229. handledCPCount = basicLength = output.length;
  29230. // `handledCPCount` is the number of code points that have been handled;
  29231. // `basicLength` is the number of basic code points.
  29232. // Finish the basic string - if it is not empty - with a delimiter
  29233. if (basicLength) {
  29234. output.push(delimiter);
  29235. }
  29236. // Main encoding loop:
  29237. while (handledCPCount < inputLength) {
  29238. // All non-basic code points < n have been handled already. Find the next
  29239. // larger one:
  29240. for (m = maxInt, j = 0; j < inputLength; ++j) {
  29241. currentValue = input[j];
  29242. if (currentValue >= n && currentValue < m) {
  29243. m = currentValue;
  29244. }
  29245. }
  29246. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  29247. // but guard against overflow
  29248. handledCPCountPlusOne = handledCPCount + 1;
  29249. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  29250. error('overflow');
  29251. }
  29252. delta += (m - n) * handledCPCountPlusOne;
  29253. n = m;
  29254. for (j = 0; j < inputLength; ++j) {
  29255. currentValue = input[j];
  29256. if (currentValue < n && ++delta > maxInt) {
  29257. error('overflow');
  29258. }
  29259. if (currentValue == n) {
  29260. // Represent delta as a generalized variable-length integer
  29261. for (q = delta, k = base; /* no condition */ ; k += base) {
  29262. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  29263. if (q < t) {
  29264. break;
  29265. }
  29266. qMinusT = q - t;
  29267. baseMinusT = base - t;
  29268. output.push(
  29269. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  29270. );
  29271. q = floor(qMinusT / baseMinusT);
  29272. }
  29273. output.push(stringFromCharCode(digitToBasic(q, 0)));
  29274. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  29275. delta = 0;
  29276. ++handledCPCount;
  29277. }
  29278. }
  29279. ++delta;
  29280. ++n;
  29281. }
  29282. return output.join('');
  29283. }
  29284. /**
  29285. * Converts a Unicode string representing a domain name or an email address to
  29286. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  29287. * i.e. it doesn't matter if you call it with a domain that's already in
  29288. * ASCII.
  29289. * @memberOf punycode
  29290. * @param {String} input The domain name or email address to convert, as a
  29291. * Unicode string.
  29292. * @returns {String} The Punycode representation of the given domain name or
  29293. * email address.
  29294. */
  29295. function toASCII(input) {
  29296. return mapDomain(input, function(string) {
  29297. return regexNonASCII.test(string) ?
  29298. 'xn--' + encode$1(string) :
  29299. string;
  29300. });
  29301. }
  29302. var inherits;
  29303. if (typeof Object.create === 'function'){
  29304. inherits = function inherits(ctor, superCtor) {
  29305. // implementation from standard node.js 'util' module
  29306. ctor.super_ = superCtor;
  29307. ctor.prototype = Object.create(superCtor.prototype, {
  29308. constructor: {
  29309. value: ctor,
  29310. enumerable: false,
  29311. writable: true,
  29312. configurable: true
  29313. }
  29314. });
  29315. };
  29316. } else {
  29317. inherits = function inherits(ctor, superCtor) {
  29318. ctor.super_ = superCtor;
  29319. var TempCtor = function () {};
  29320. TempCtor.prototype = superCtor.prototype;
  29321. ctor.prototype = new TempCtor();
  29322. ctor.prototype.constructor = ctor;
  29323. };
  29324. }
  29325. var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||
  29326. function getOwnPropertyDescriptors(obj) {
  29327. var keys = Object.keys(obj);
  29328. var descriptors = {};
  29329. for (var i = 0; i < keys.length; i++) {
  29330. descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);
  29331. }
  29332. return descriptors;
  29333. };
  29334. var formatRegExp = /%[sdj%]/g;
  29335. function format$1(f) {
  29336. if (!isString(f)) {
  29337. var objects = [];
  29338. for (var i = 0; i < arguments.length; i++) {
  29339. objects.push(inspect(arguments[i]));
  29340. }
  29341. return objects.join(' ');
  29342. }
  29343. var i = 1;
  29344. var args = arguments;
  29345. var len = args.length;
  29346. var str = String(f).replace(formatRegExp, function(x) {
  29347. if (x === '%%') return '%';
  29348. if (i >= len) return x;
  29349. switch (x) {
  29350. case '%s': return String(args[i++]);
  29351. case '%d': return Number(args[i++]);
  29352. case '%j':
  29353. try {
  29354. return JSON.stringify(args[i++]);
  29355. } catch (_) {
  29356. return '[Circular]';
  29357. }
  29358. default:
  29359. return x;
  29360. }
  29361. });
  29362. for (var x = args[i]; i < len; x = args[++i]) {
  29363. if (isNull(x) || !isObject$1(x)) {
  29364. str += ' ' + x;
  29365. } else {
  29366. str += ' ' + inspect(x);
  29367. }
  29368. }
  29369. return str;
  29370. }
  29371. // Mark that a method should not be used.
  29372. // Returns a modified function which warns once by default.
  29373. // If --no-deprecation is set, then it is a no-op.
  29374. function deprecate(fn, msg) {
  29375. // Allow for deprecating things in the process of starting up.
  29376. if (isUndefined(global$1.process)) {
  29377. return function() {
  29378. return deprecate(fn, msg).apply(this, arguments);
  29379. };
  29380. }
  29381. if (browser$1.noDeprecation === true) {
  29382. return fn;
  29383. }
  29384. var warned = false;
  29385. function deprecated() {
  29386. if (!warned) {
  29387. if (browser$1.throwDeprecation) {
  29388. throw new Error(msg);
  29389. } else if (browser$1.traceDeprecation) {
  29390. console.trace(msg);
  29391. } else {
  29392. console.error(msg);
  29393. }
  29394. warned = true;
  29395. }
  29396. return fn.apply(this, arguments);
  29397. }
  29398. return deprecated;
  29399. }
  29400. var debugs = {};
  29401. var debugEnviron;
  29402. function debuglog(set) {
  29403. if (isUndefined(debugEnviron))
  29404. debugEnviron = browser$1.env.NODE_DEBUG || '';
  29405. set = set.toUpperCase();
  29406. if (!debugs[set]) {
  29407. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  29408. var pid = 0;
  29409. debugs[set] = function() {
  29410. var msg = format$1.apply(null, arguments);
  29411. console.error('%s %d: %s', set, pid, msg);
  29412. };
  29413. } else {
  29414. debugs[set] = function() {};
  29415. }
  29416. }
  29417. return debugs[set];
  29418. }
  29419. /**
  29420. * Echos the value of a value. Trys to print the value out
  29421. * in the best way possible given the different types.
  29422. *
  29423. * @param {Object} obj The object to print out.
  29424. * @param {Object} opts Optional options object that alters the output.
  29425. */
  29426. /* legacy: obj, showHidden, depth, colors*/
  29427. function inspect(obj, opts) {
  29428. // default options
  29429. var ctx = {
  29430. seen: [],
  29431. stylize: stylizeNoColor
  29432. };
  29433. // legacy...
  29434. if (arguments.length >= 3) ctx.depth = arguments[2];
  29435. if (arguments.length >= 4) ctx.colors = arguments[3];
  29436. if (isBoolean(opts)) {
  29437. // legacy...
  29438. ctx.showHidden = opts;
  29439. } else if (opts) {
  29440. // got an "options" object
  29441. _extend(ctx, opts);
  29442. }
  29443. // set default options
  29444. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  29445. if (isUndefined(ctx.depth)) ctx.depth = 2;
  29446. if (isUndefined(ctx.colors)) ctx.colors = false;
  29447. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  29448. if (ctx.colors) ctx.stylize = stylizeWithColor;
  29449. return formatValue(ctx, obj, ctx.depth);
  29450. }
  29451. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  29452. inspect.colors = {
  29453. 'bold' : [1, 22],
  29454. 'italic' : [3, 23],
  29455. 'underline' : [4, 24],
  29456. 'inverse' : [7, 27],
  29457. 'white' : [37, 39],
  29458. 'grey' : [90, 39],
  29459. 'black' : [30, 39],
  29460. 'blue' : [34, 39],
  29461. 'cyan' : [36, 39],
  29462. 'green' : [32, 39],
  29463. 'magenta' : [35, 39],
  29464. 'red' : [31, 39],
  29465. 'yellow' : [33, 39]
  29466. };
  29467. // Don't use 'blue' not visible on cmd.exe
  29468. inspect.styles = {
  29469. 'special': 'cyan',
  29470. 'number': 'yellow',
  29471. 'boolean': 'yellow',
  29472. 'undefined': 'grey',
  29473. 'null': 'bold',
  29474. 'string': 'green',
  29475. 'date': 'magenta',
  29476. // "name": intentionally not styling
  29477. 'regexp': 'red'
  29478. };
  29479. function stylizeWithColor(str, styleType) {
  29480. var style = inspect.styles[styleType];
  29481. if (style) {
  29482. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  29483. '\u001b[' + inspect.colors[style][1] + 'm';
  29484. } else {
  29485. return str;
  29486. }
  29487. }
  29488. function stylizeNoColor(str, styleType) {
  29489. return str;
  29490. }
  29491. function arrayToHash(array) {
  29492. var hash = {};
  29493. array.forEach(function(val, idx) {
  29494. hash[val] = true;
  29495. });
  29496. return hash;
  29497. }
  29498. function formatValue(ctx, value, recurseTimes) {
  29499. // Provide a hook for user-specified inspect functions.
  29500. // Check that value is an object with an inspect function on it
  29501. if (ctx.customInspect &&
  29502. value &&
  29503. isFunction(value.inspect) &&
  29504. // Filter out the util module, it's inspect function is special
  29505. value.inspect !== inspect &&
  29506. // Also filter out any prototype objects using the circular check.
  29507. !(value.constructor && value.constructor.prototype === value)) {
  29508. var ret = value.inspect(recurseTimes, ctx);
  29509. if (!isString(ret)) {
  29510. ret = formatValue(ctx, ret, recurseTimes);
  29511. }
  29512. return ret;
  29513. }
  29514. // Primitive types cannot have properties
  29515. var primitive = formatPrimitive(ctx, value);
  29516. if (primitive) {
  29517. return primitive;
  29518. }
  29519. // Look up the keys of the object.
  29520. var keys = Object.keys(value);
  29521. var visibleKeys = arrayToHash(keys);
  29522. if (ctx.showHidden) {
  29523. keys = Object.getOwnPropertyNames(value);
  29524. }
  29525. // IE doesn't make error fields non-enumerable
  29526. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  29527. if (isError(value)
  29528. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  29529. return formatError(value);
  29530. }
  29531. // Some type of object without properties can be shortcutted.
  29532. if (keys.length === 0) {
  29533. if (isFunction(value)) {
  29534. var name = value.name ? ': ' + value.name : '';
  29535. return ctx.stylize('[Function' + name + ']', 'special');
  29536. }
  29537. if (isRegExp(value)) {
  29538. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  29539. }
  29540. if (isDate(value)) {
  29541. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  29542. }
  29543. if (isError(value)) {
  29544. return formatError(value);
  29545. }
  29546. }
  29547. var base = '', array = false, braces = ['{', '}'];
  29548. // Make Array say that they are Array
  29549. if (isArray$1(value)) {
  29550. array = true;
  29551. braces = ['[', ']'];
  29552. }
  29553. // Make functions say that they are functions
  29554. if (isFunction(value)) {
  29555. var n = value.name ? ': ' + value.name : '';
  29556. base = ' [Function' + n + ']';
  29557. }
  29558. // Make RegExps say that they are RegExps
  29559. if (isRegExp(value)) {
  29560. base = ' ' + RegExp.prototype.toString.call(value);
  29561. }
  29562. // Make dates with properties first say the date
  29563. if (isDate(value)) {
  29564. base = ' ' + Date.prototype.toUTCString.call(value);
  29565. }
  29566. // Make error with message first say the error
  29567. if (isError(value)) {
  29568. base = ' ' + formatError(value);
  29569. }
  29570. if (keys.length === 0 && (!array || value.length == 0)) {
  29571. return braces[0] + base + braces[1];
  29572. }
  29573. if (recurseTimes < 0) {
  29574. if (isRegExp(value)) {
  29575. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  29576. } else {
  29577. return ctx.stylize('[Object]', 'special');
  29578. }
  29579. }
  29580. ctx.seen.push(value);
  29581. var output;
  29582. if (array) {
  29583. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  29584. } else {
  29585. output = keys.map(function(key) {
  29586. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  29587. });
  29588. }
  29589. ctx.seen.pop();
  29590. return reduceToSingleString(output, base, braces);
  29591. }
  29592. function formatPrimitive(ctx, value) {
  29593. if (isUndefined(value))
  29594. return ctx.stylize('undefined', 'undefined');
  29595. if (isString(value)) {
  29596. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  29597. .replace(/'/g, "\\'")
  29598. .replace(/\\"/g, '"') + '\'';
  29599. return ctx.stylize(simple, 'string');
  29600. }
  29601. if (isNumber(value))
  29602. return ctx.stylize('' + value, 'number');
  29603. if (isBoolean(value))
  29604. return ctx.stylize('' + value, 'boolean');
  29605. // For some reason typeof null is "object", so special case here.
  29606. if (isNull(value))
  29607. return ctx.stylize('null', 'null');
  29608. }
  29609. function formatError(value) {
  29610. return '[' + Error.prototype.toString.call(value) + ']';
  29611. }
  29612. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  29613. var output = [];
  29614. for (var i = 0, l = value.length; i < l; ++i) {
  29615. if (hasOwnProperty$2(value, String(i))) {
  29616. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  29617. String(i), true));
  29618. } else {
  29619. output.push('');
  29620. }
  29621. }
  29622. keys.forEach(function(key) {
  29623. if (!key.match(/^\d+$/)) {
  29624. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  29625. key, true));
  29626. }
  29627. });
  29628. return output;
  29629. }
  29630. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  29631. var name, str, desc;
  29632. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  29633. if (desc.get) {
  29634. if (desc.set) {
  29635. str = ctx.stylize('[Getter/Setter]', 'special');
  29636. } else {
  29637. str = ctx.stylize('[Getter]', 'special');
  29638. }
  29639. } else {
  29640. if (desc.set) {
  29641. str = ctx.stylize('[Setter]', 'special');
  29642. }
  29643. }
  29644. if (!hasOwnProperty$2(visibleKeys, key)) {
  29645. name = '[' + key + ']';
  29646. }
  29647. if (!str) {
  29648. if (ctx.seen.indexOf(desc.value) < 0) {
  29649. if (isNull(recurseTimes)) {
  29650. str = formatValue(ctx, desc.value, null);
  29651. } else {
  29652. str = formatValue(ctx, desc.value, recurseTimes - 1);
  29653. }
  29654. if (str.indexOf('\n') > -1) {
  29655. if (array) {
  29656. str = str.split('\n').map(function(line) {
  29657. return ' ' + line;
  29658. }).join('\n').substr(2);
  29659. } else {
  29660. str = '\n' + str.split('\n').map(function(line) {
  29661. return ' ' + line;
  29662. }).join('\n');
  29663. }
  29664. }
  29665. } else {
  29666. str = ctx.stylize('[Circular]', 'special');
  29667. }
  29668. }
  29669. if (isUndefined(name)) {
  29670. if (array && key.match(/^\d+$/)) {
  29671. return str;
  29672. }
  29673. name = JSON.stringify('' + key);
  29674. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  29675. name = name.substr(1, name.length - 2);
  29676. name = ctx.stylize(name, 'name');
  29677. } else {
  29678. name = name.replace(/'/g, "\\'")
  29679. .replace(/\\"/g, '"')
  29680. .replace(/(^"|"$)/g, "'");
  29681. name = ctx.stylize(name, 'string');
  29682. }
  29683. }
  29684. return name + ': ' + str;
  29685. }
  29686. function reduceToSingleString(output, base, braces) {
  29687. var length = output.reduce(function(prev, cur) {
  29688. if (cur.indexOf('\n') >= 0) ;
  29689. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  29690. }, 0);
  29691. if (length > 60) {
  29692. return braces[0] +
  29693. (base === '' ? '' : base + '\n ') +
  29694. ' ' +
  29695. output.join(',\n ') +
  29696. ' ' +
  29697. braces[1];
  29698. }
  29699. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  29700. }
  29701. // NOTE: These type checking functions intentionally don't use `instanceof`
  29702. // because it is fragile and can be easily faked with `Object.create()`.
  29703. function isArray$1(ar) {
  29704. return Array.isArray(ar);
  29705. }
  29706. function isBoolean(arg) {
  29707. return typeof arg === 'boolean';
  29708. }
  29709. function isNull(arg) {
  29710. return arg === null;
  29711. }
  29712. function isNullOrUndefined(arg) {
  29713. return arg == null;
  29714. }
  29715. function isNumber(arg) {
  29716. return typeof arg === 'number';
  29717. }
  29718. function isString(arg) {
  29719. return typeof arg === 'string';
  29720. }
  29721. function isSymbol(arg) {
  29722. return typeof arg === 'symbol';
  29723. }
  29724. function isUndefined(arg) {
  29725. return arg === void 0;
  29726. }
  29727. function isRegExp(re) {
  29728. return isObject$1(re) && objectToString(re) === '[object RegExp]';
  29729. }
  29730. function isObject$1(arg) {
  29731. return typeof arg === 'object' && arg !== null;
  29732. }
  29733. function isDate(d) {
  29734. return isObject$1(d) && objectToString(d) === '[object Date]';
  29735. }
  29736. function isError(e) {
  29737. return isObject$1(e) &&
  29738. (objectToString(e) === '[object Error]' || e instanceof Error);
  29739. }
  29740. function isFunction(arg) {
  29741. return typeof arg === 'function';
  29742. }
  29743. function isPrimitive(arg) {
  29744. return arg === null ||
  29745. typeof arg === 'boolean' ||
  29746. typeof arg === 'number' ||
  29747. typeof arg === 'string' ||
  29748. typeof arg === 'symbol' || // ES6 symbol
  29749. typeof arg === 'undefined';
  29750. }
  29751. function isBuffer(maybeBuf) {
  29752. return Buffer$1.isBuffer(maybeBuf);
  29753. }
  29754. function objectToString(o) {
  29755. return Object.prototype.toString.call(o);
  29756. }
  29757. function pad(n) {
  29758. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  29759. }
  29760. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  29761. 'Oct', 'Nov', 'Dec'];
  29762. // 26 Feb 16:19:34
  29763. function timestamp() {
  29764. var d = new Date();
  29765. var time = [pad(d.getHours()),
  29766. pad(d.getMinutes()),
  29767. pad(d.getSeconds())].join(':');
  29768. return [d.getDate(), months[d.getMonth()], time].join(' ');
  29769. }
  29770. // log is just a thin wrapper to console.log that prepends a timestamp
  29771. function log() {
  29772. console.log('%s - %s', timestamp(), format$1.apply(null, arguments));
  29773. }
  29774. function _extend(origin, add) {
  29775. // Don't do anything if add isn't an object
  29776. if (!add || !isObject$1(add)) return origin;
  29777. var keys = Object.keys(add);
  29778. var i = keys.length;
  29779. while (i--) {
  29780. origin[keys[i]] = add[keys[i]];
  29781. }
  29782. return origin;
  29783. }
  29784. function hasOwnProperty$2(obj, prop) {
  29785. return Object.prototype.hasOwnProperty.call(obj, prop);
  29786. }
  29787. var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;
  29788. function promisify(original) {
  29789. if (typeof original !== 'function')
  29790. throw new TypeError('The "original" argument must be of type Function');
  29791. if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {
  29792. var fn = original[kCustomPromisifiedSymbol];
  29793. if (typeof fn !== 'function') {
  29794. throw new TypeError('The "util.promisify.custom" argument must be of type Function');
  29795. }
  29796. Object.defineProperty(fn, kCustomPromisifiedSymbol, {
  29797. value: fn, enumerable: false, writable: false, configurable: true
  29798. });
  29799. return fn;
  29800. }
  29801. function fn() {
  29802. var promiseResolve, promiseReject;
  29803. var promise = new Promise(function (resolve, reject) {
  29804. promiseResolve = resolve;
  29805. promiseReject = reject;
  29806. });
  29807. var args = [];
  29808. for (var i = 0; i < arguments.length; i++) {
  29809. args.push(arguments[i]);
  29810. }
  29811. args.push(function (err, value) {
  29812. if (err) {
  29813. promiseReject(err);
  29814. } else {
  29815. promiseResolve(value);
  29816. }
  29817. });
  29818. try {
  29819. original.apply(this, args);
  29820. } catch (err) {
  29821. promiseReject(err);
  29822. }
  29823. return promise;
  29824. }
  29825. Object.setPrototypeOf(fn, Object.getPrototypeOf(original));
  29826. if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {
  29827. value: fn, enumerable: false, writable: false, configurable: true
  29828. });
  29829. return Object.defineProperties(
  29830. fn,
  29831. getOwnPropertyDescriptors(original)
  29832. );
  29833. }
  29834. promisify.custom = kCustomPromisifiedSymbol;
  29835. function callbackifyOnRejected(reason, cb) {
  29836. // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).
  29837. // Because `null` is a special error value in callbacks which means "no error
  29838. // occurred", we error-wrap so the callback consumer can distinguish between
  29839. // "the promise rejected with null" or "the promise fulfilled with undefined".
  29840. if (!reason) {
  29841. var newReason = new Error('Promise was rejected with a falsy value');
  29842. newReason.reason = reason;
  29843. reason = newReason;
  29844. }
  29845. return cb(reason);
  29846. }
  29847. function callbackify(original) {
  29848. if (typeof original !== 'function') {
  29849. throw new TypeError('The "original" argument must be of type Function');
  29850. }
  29851. // We DO NOT return the promise as it gives the user a false sense that
  29852. // the promise is actually somehow related to the callback's execution
  29853. // and that the callback throwing will reject the promise.
  29854. function callbackified() {
  29855. var args = [];
  29856. for (var i = 0; i < arguments.length; i++) {
  29857. args.push(arguments[i]);
  29858. }
  29859. var maybeCb = args.pop();
  29860. if (typeof maybeCb !== 'function') {
  29861. throw new TypeError('The last argument must be of type Function');
  29862. }
  29863. var self = this;
  29864. var cb = function() {
  29865. return maybeCb.apply(self, arguments);
  29866. };
  29867. // In true node style we process the callback on `nextTick` with all the
  29868. // implications (stack, `uncaughtException`, `async_hooks`)
  29869. original.apply(this, args)
  29870. .then(function(ret) { browser$1.nextTick(cb.bind(null, null, ret)); },
  29871. function(rej) { browser$1.nextTick(callbackifyOnRejected.bind(null, rej, cb)); });
  29872. }
  29873. Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));
  29874. Object.defineProperties(callbackified, getOwnPropertyDescriptors(original));
  29875. return callbackified;
  29876. }
  29877. var _polyfillNode_util = {
  29878. inherits: inherits,
  29879. _extend: _extend,
  29880. log: log,
  29881. isBuffer: isBuffer,
  29882. isPrimitive: isPrimitive,
  29883. isFunction: isFunction,
  29884. isError: isError,
  29885. isDate: isDate,
  29886. isObject: isObject$1,
  29887. isRegExp: isRegExp,
  29888. isUndefined: isUndefined,
  29889. isSymbol: isSymbol,
  29890. isString: isString,
  29891. isNumber: isNumber,
  29892. isNullOrUndefined: isNullOrUndefined,
  29893. isNull: isNull,
  29894. isBoolean: isBoolean,
  29895. isArray: isArray$1,
  29896. inspect: inspect,
  29897. deprecate: deprecate,
  29898. format: format$1,
  29899. debuglog: debuglog,
  29900. promisify: promisify,
  29901. callbackify: callbackify,
  29902. };
  29903. var _polyfillNode_util$1 = /*#__PURE__*/Object.freeze({
  29904. __proto__: null,
  29905. _extend: _extend,
  29906. callbackify: callbackify,
  29907. debuglog: debuglog,
  29908. default: _polyfillNode_util,
  29909. deprecate: deprecate,
  29910. format: format$1,
  29911. inherits: inherits,
  29912. inspect: inspect,
  29913. isArray: isArray$1,
  29914. isBoolean: isBoolean,
  29915. isBuffer: isBuffer,
  29916. isDate: isDate,
  29917. isError: isError,
  29918. isFunction: isFunction,
  29919. isNull: isNull,
  29920. isNullOrUndefined: isNullOrUndefined,
  29921. isNumber: isNumber,
  29922. isObject: isObject$1,
  29923. isPrimitive: isPrimitive,
  29924. isRegExp: isRegExp,
  29925. isString: isString,
  29926. isSymbol: isSymbol,
  29927. isUndefined: isUndefined,
  29928. log: log,
  29929. promisify: promisify
  29930. });
  29931. // Copyright Joyent, Inc. and other Node contributors.
  29932. //
  29933. // Permission is hereby granted, free of charge, to any person obtaining a
  29934. // copy of this software and associated documentation files (the
  29935. // "Software"), to deal in the Software without restriction, including
  29936. // without limitation the rights to use, copy, modify, merge, publish,
  29937. // distribute, sublicense, and/or sell copies of the Software, and to permit
  29938. // persons to whom the Software is furnished to do so, subject to the
  29939. // following conditions:
  29940. //
  29941. // The above copyright notice and this permission notice shall be included
  29942. // in all copies or substantial portions of the Software.
  29943. //
  29944. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  29945. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  29946. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  29947. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  29948. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  29949. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  29950. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  29951. // If obj.hasOwnProperty has been overridden, then calling
  29952. // obj.hasOwnProperty(prop) will break.
  29953. // See: https://github.com/joyent/node/issues/1707
  29954. function hasOwnProperty$1(obj, prop) {
  29955. return Object.prototype.hasOwnProperty.call(obj, prop);
  29956. }
  29957. var isArray = Array.isArray || function (xs) {
  29958. return Object.prototype.toString.call(xs) === '[object Array]';
  29959. };
  29960. function stringifyPrimitive(v) {
  29961. switch (typeof v) {
  29962. case 'string':
  29963. return v;
  29964. case 'boolean':
  29965. return v ? 'true' : 'false';
  29966. case 'number':
  29967. return isFinite(v) ? v : '';
  29968. default:
  29969. return '';
  29970. }
  29971. }
  29972. function stringify (obj, sep, eq, name) {
  29973. sep = sep || '&';
  29974. eq = eq || '=';
  29975. if (obj === null) {
  29976. obj = undefined;
  29977. }
  29978. if (typeof obj === 'object') {
  29979. return map(objectKeys(obj), function(k) {
  29980. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  29981. if (isArray(obj[k])) {
  29982. return map(obj[k], function(v) {
  29983. return ks + encodeURIComponent(stringifyPrimitive(v));
  29984. }).join(sep);
  29985. } else {
  29986. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  29987. }
  29988. }).join(sep);
  29989. }
  29990. if (!name) return '';
  29991. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  29992. encodeURIComponent(stringifyPrimitive(obj));
  29993. }
  29994. function map (xs, f) {
  29995. if (xs.map) return xs.map(f);
  29996. var res = [];
  29997. for (var i = 0; i < xs.length; i++) {
  29998. res.push(f(xs[i], i));
  29999. }
  30000. return res;
  30001. }
  30002. var objectKeys = Object.keys || function (obj) {
  30003. var res = [];
  30004. for (var key in obj) {
  30005. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  30006. }
  30007. return res;
  30008. };
  30009. function parse$1(qs, sep, eq, options) {
  30010. sep = sep || '&';
  30011. eq = eq || '=';
  30012. var obj = {};
  30013. if (typeof qs !== 'string' || qs.length === 0) {
  30014. return obj;
  30015. }
  30016. var regexp = /\+/g;
  30017. qs = qs.split(sep);
  30018. var maxKeys = 1000;
  30019. if (options && typeof options.maxKeys === 'number') {
  30020. maxKeys = options.maxKeys;
  30021. }
  30022. var len = qs.length;
  30023. // maxKeys <= 0 means that we should not limit keys count
  30024. if (maxKeys > 0 && len > maxKeys) {
  30025. len = maxKeys;
  30026. }
  30027. for (var i = 0; i < len; ++i) {
  30028. var x = qs[i].replace(regexp, '%20'),
  30029. idx = x.indexOf(eq),
  30030. kstr, vstr, k, v;
  30031. if (idx >= 0) {
  30032. kstr = x.substr(0, idx);
  30033. vstr = x.substr(idx + 1);
  30034. } else {
  30035. kstr = x;
  30036. vstr = '';
  30037. }
  30038. k = decodeURIComponent(kstr);
  30039. v = decodeURIComponent(vstr);
  30040. if (!hasOwnProperty$1(obj, k)) {
  30041. obj[k] = v;
  30042. } else if (isArray(obj[k])) {
  30043. obj[k].push(v);
  30044. } else {
  30045. obj[k] = [obj[k], v];
  30046. }
  30047. }
  30048. return obj;
  30049. }
  30050. // WHATWG API
  30051. const URL$1 = global$1.URL;
  30052. const URLSearchParams = global$1.URLSearchParams;
  30053. var _polyfillNode_url = {
  30054. parse: urlParse,
  30055. resolve: urlResolve,
  30056. resolveObject: urlResolveObject,
  30057. fileURLToPath: urlFileURLToPath,
  30058. format: urlFormat,
  30059. Url: Url,
  30060. // WHATWG API
  30061. URL: URL$1,
  30062. URLSearchParams,
  30063. };
  30064. function Url() {
  30065. this.protocol = null;
  30066. this.slashes = null;
  30067. this.auth = null;
  30068. this.host = null;
  30069. this.port = null;
  30070. this.hostname = null;
  30071. this.hash = null;
  30072. this.search = null;
  30073. this.query = null;
  30074. this.pathname = null;
  30075. this.path = null;
  30076. this.href = null;
  30077. }
  30078. // Reference: RFC 3986, RFC 1808, RFC 2396
  30079. // define these here so at least they only have to be
  30080. // compiled once on the first module load.
  30081. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  30082. portPattern = /:[0-9]*$/,
  30083. // Special case for a simple path URL
  30084. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  30085. // RFC 2396: characters reserved for delimiting URLs.
  30086. // We actually just auto-escape these.
  30087. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  30088. // RFC 2396: characters not allowed for various reasons.
  30089. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  30090. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  30091. autoEscape = ['\''].concat(unwise),
  30092. // Characters that are never ever allowed in a hostname.
  30093. // Note that any invalid chars are also handled, but these
  30094. // are the ones that are *expected* to be seen, so we fast-path
  30095. // them.
  30096. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  30097. hostEndingChars = ['/', '?', '#'],
  30098. hostnameMaxLen = 255,
  30099. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  30100. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  30101. // protocols that can allow "unsafe" and "unwise" chars.
  30102. unsafeProtocol = {
  30103. 'javascript': true,
  30104. 'javascript:': true
  30105. },
  30106. // protocols that never have a hostname.
  30107. hostlessProtocol = {
  30108. 'javascript': true,
  30109. 'javascript:': true
  30110. },
  30111. // protocols that always contain a // bit.
  30112. slashedProtocol = {
  30113. 'http': true,
  30114. 'https': true,
  30115. 'ftp': true,
  30116. 'gopher': true,
  30117. 'file': true,
  30118. 'http:': true,
  30119. 'https:': true,
  30120. 'ftp:': true,
  30121. 'gopher:': true,
  30122. 'file:': true
  30123. };
  30124. function urlParse(url, parseQueryString, slashesDenoteHost) {
  30125. if (url && isObject$1(url) && url instanceof Url) return url;
  30126. var u = new Url;
  30127. u.parse(url, parseQueryString, slashesDenoteHost);
  30128. return u;
  30129. }
  30130. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  30131. return parse(this, url, parseQueryString, slashesDenoteHost);
  30132. };
  30133. function parse(self, url, parseQueryString, slashesDenoteHost) {
  30134. if (!isString(url)) {
  30135. throw new TypeError('Parameter \'url\' must be a string, not ' + typeof url);
  30136. }
  30137. // Copy chrome, IE, opera backslash-handling behavior.
  30138. // Back slashes before the query string get converted to forward slashes
  30139. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  30140. var queryIndex = url.indexOf('?'),
  30141. splitter =
  30142. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  30143. uSplit = url.split(splitter),
  30144. slashRegex = /\\/g;
  30145. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  30146. url = uSplit.join(splitter);
  30147. var rest = url;
  30148. // trim before proceeding.
  30149. // This is to support parse stuff like " http://foo.com \n"
  30150. rest = rest.trim();
  30151. if (!slashesDenoteHost && url.split('#').length === 1) {
  30152. // Try fast path regexp
  30153. var simplePath = simplePathPattern.exec(rest);
  30154. if (simplePath) {
  30155. self.path = rest;
  30156. self.href = rest;
  30157. self.pathname = simplePath[1];
  30158. if (simplePath[2]) {
  30159. self.search = simplePath[2];
  30160. if (parseQueryString) {
  30161. self.query = parse$1(self.search.substr(1));
  30162. } else {
  30163. self.query = self.search.substr(1);
  30164. }
  30165. } else if (parseQueryString) {
  30166. self.search = '';
  30167. self.query = {};
  30168. }
  30169. return self;
  30170. }
  30171. }
  30172. var proto = protocolPattern.exec(rest);
  30173. if (proto) {
  30174. proto = proto[0];
  30175. var lowerProto = proto.toLowerCase();
  30176. self.protocol = lowerProto;
  30177. rest = rest.substr(proto.length);
  30178. }
  30179. // figure out if it's got a host
  30180. // user@server is *always* interpreted as a hostname, and url
  30181. // resolution will treat //foo/bar as host=foo,path=bar because that's
  30182. // how the browser resolves relative URLs.
  30183. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  30184. var slashes = rest.substr(0, 2) === '//';
  30185. if (slashes && !(proto && hostlessProtocol[proto])) {
  30186. rest = rest.substr(2);
  30187. self.slashes = true;
  30188. }
  30189. }
  30190. var i, hec, l, p;
  30191. if (!hostlessProtocol[proto] &&
  30192. (slashes || (proto && !slashedProtocol[proto]))) {
  30193. // there's a hostname.
  30194. // the first instance of /, ?, ;, or # ends the host.
  30195. //
  30196. // If there is an @ in the hostname, then non-host chars *are* allowed
  30197. // to the left of the last @ sign, unless some host-ending character
  30198. // comes *before* the @-sign.
  30199. // URLs are obnoxious.
  30200. //
  30201. // ex:
  30202. // http://a@b@c/ => user:a@b host:c
  30203. // http://a@b?@c => user:a host:c path:/?@c
  30204. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  30205. // Review our test case against browsers more comprehensively.
  30206. // find the first instance of any hostEndingChars
  30207. var hostEnd = -1;
  30208. for (i = 0; i < hostEndingChars.length; i++) {
  30209. hec = rest.indexOf(hostEndingChars[i]);
  30210. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  30211. hostEnd = hec;
  30212. }
  30213. // at this point, either we have an explicit point where the
  30214. // auth portion cannot go past, or the last @ char is the decider.
  30215. var auth, atSign;
  30216. if (hostEnd === -1) {
  30217. // atSign can be anywhere.
  30218. atSign = rest.lastIndexOf('@');
  30219. } else {
  30220. // atSign must be in auth portion.
  30221. // http://a@b/c@d => host:b auth:a path:/c@d
  30222. atSign = rest.lastIndexOf('@', hostEnd);
  30223. }
  30224. // Now we have a portion which is definitely the auth.
  30225. // Pull that off.
  30226. if (atSign !== -1) {
  30227. auth = rest.slice(0, atSign);
  30228. rest = rest.slice(atSign + 1);
  30229. self.auth = decodeURIComponent(auth);
  30230. }
  30231. // the host is the remaining to the left of the first non-host char
  30232. hostEnd = -1;
  30233. for (i = 0; i < nonHostChars.length; i++) {
  30234. hec = rest.indexOf(nonHostChars[i]);
  30235. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  30236. hostEnd = hec;
  30237. }
  30238. // if we still have not hit it, then the entire thing is a host.
  30239. if (hostEnd === -1)
  30240. hostEnd = rest.length;
  30241. self.host = rest.slice(0, hostEnd);
  30242. rest = rest.slice(hostEnd);
  30243. // pull out port.
  30244. parseHost(self);
  30245. // we've indicated that there is a hostname,
  30246. // so even if it's empty, it has to be present.
  30247. self.hostname = self.hostname || '';
  30248. // if hostname begins with [ and ends with ]
  30249. // assume that it's an IPv6 address.
  30250. var ipv6Hostname = self.hostname[0] === '[' &&
  30251. self.hostname[self.hostname.length - 1] === ']';
  30252. // validate a little.
  30253. if (!ipv6Hostname) {
  30254. var hostparts = self.hostname.split(/\./);
  30255. for (i = 0, l = hostparts.length; i < l; i++) {
  30256. var part = hostparts[i];
  30257. if (!part) continue;
  30258. if (!part.match(hostnamePartPattern)) {
  30259. var newpart = '';
  30260. for (var j = 0, k = part.length; j < k; j++) {
  30261. if (part.charCodeAt(j) > 127) {
  30262. // we replace non-ASCII char with a temporary placeholder
  30263. // we need this to make sure size of hostname is not
  30264. // broken by replacing non-ASCII by nothing
  30265. newpart += 'x';
  30266. } else {
  30267. newpart += part[j];
  30268. }
  30269. }
  30270. // we test again with ASCII char only
  30271. if (!newpart.match(hostnamePartPattern)) {
  30272. var validParts = hostparts.slice(0, i);
  30273. var notHost = hostparts.slice(i + 1);
  30274. var bit = part.match(hostnamePartStart);
  30275. if (bit) {
  30276. validParts.push(bit[1]);
  30277. notHost.unshift(bit[2]);
  30278. }
  30279. if (notHost.length) {
  30280. rest = '/' + notHost.join('.') + rest;
  30281. }
  30282. self.hostname = validParts.join('.');
  30283. break;
  30284. }
  30285. }
  30286. }
  30287. }
  30288. if (self.hostname.length > hostnameMaxLen) {
  30289. self.hostname = '';
  30290. } else {
  30291. // hostnames are always lower case.
  30292. self.hostname = self.hostname.toLowerCase();
  30293. }
  30294. if (!ipv6Hostname) {
  30295. // IDNA Support: Returns a punycoded representation of "domain".
  30296. // It only converts parts of the domain name that
  30297. // have non-ASCII characters, i.e. it doesn't matter if
  30298. // you call it with a domain that already is ASCII-only.
  30299. self.hostname = toASCII(self.hostname);
  30300. }
  30301. p = self.port ? ':' + self.port : '';
  30302. var h = self.hostname || '';
  30303. self.host = h + p;
  30304. self.href += self.host;
  30305. // strip [ and ] from the hostname
  30306. // the host field still retains them, though
  30307. if (ipv6Hostname) {
  30308. self.hostname = self.hostname.substr(1, self.hostname.length - 2);
  30309. if (rest[0] !== '/') {
  30310. rest = '/' + rest;
  30311. }
  30312. }
  30313. }
  30314. // now rest is set to the post-host stuff.
  30315. // chop off any delim chars.
  30316. if (!unsafeProtocol[lowerProto]) {
  30317. // First, make 100% sure that any "autoEscape" chars get
  30318. // escaped, even if encodeURIComponent doesn't think they
  30319. // need to be.
  30320. for (i = 0, l = autoEscape.length; i < l; i++) {
  30321. var ae = autoEscape[i];
  30322. if (rest.indexOf(ae) === -1)
  30323. continue;
  30324. var esc = encodeURIComponent(ae);
  30325. if (esc === ae) {
  30326. esc = escape(ae);
  30327. }
  30328. rest = rest.split(ae).join(esc);
  30329. }
  30330. }
  30331. // chop off from the tail first.
  30332. var hash = rest.indexOf('#');
  30333. if (hash !== -1) {
  30334. // got a fragment string.
  30335. self.hash = rest.substr(hash);
  30336. rest = rest.slice(0, hash);
  30337. }
  30338. var qm = rest.indexOf('?');
  30339. if (qm !== -1) {
  30340. self.search = rest.substr(qm);
  30341. self.query = rest.substr(qm + 1);
  30342. if (parseQueryString) {
  30343. self.query = parse$1(self.query);
  30344. }
  30345. rest = rest.slice(0, qm);
  30346. } else if (parseQueryString) {
  30347. // no query string, but parseQueryString still requested
  30348. self.search = '';
  30349. self.query = {};
  30350. }
  30351. if (rest) self.pathname = rest;
  30352. if (slashedProtocol[lowerProto] &&
  30353. self.hostname && !self.pathname) {
  30354. self.pathname = '/';
  30355. }
  30356. //to support http.request
  30357. if (self.pathname || self.search) {
  30358. p = self.pathname || '';
  30359. var s = self.search || '';
  30360. self.path = p + s;
  30361. }
  30362. // finally, reconstruct the href based on what has been validated.
  30363. self.href = format(self);
  30364. return self;
  30365. }
  30366. function urlFileURLToPath(path) {
  30367. if (typeof path === 'string')
  30368. path = new Url().parse(path);
  30369. else if (!(path instanceof Url))
  30370. throw new TypeError('The "path" argument must be of type string or an instance of URL. Received type ' + (typeof path) + String(path));
  30371. if (path.protocol !== 'file:')
  30372. throw new TypeError('The URL must be of scheme file');
  30373. return getPathFromURLPosix(path);
  30374. }
  30375. function getPathFromURLPosix(url) {
  30376. const pathname = url.pathname;
  30377. for (let n = 0; n < pathname.length; n++) {
  30378. if (pathname[n] === '%') {
  30379. const third = pathname.codePointAt(n + 2) | 0x20;
  30380. if (pathname[n + 1] === '2' && third === 102) {
  30381. throw new TypeError(
  30382. 'must not include encoded / characters'
  30383. );
  30384. }
  30385. }
  30386. }
  30387. return decodeURIComponent(pathname);
  30388. }
  30389. // format a parsed object into a url string
  30390. function urlFormat(obj) {
  30391. // ensure it's an object, and not a string url.
  30392. // If it's an obj, this is a no-op.
  30393. // this way, you can call url_format() on strings
  30394. // to clean up potentially wonky urls.
  30395. if (isString(obj)) obj = parse({}, obj);
  30396. return format(obj);
  30397. }
  30398. function format(self) {
  30399. var auth = self.auth || '';
  30400. if (auth) {
  30401. auth = encodeURIComponent(auth);
  30402. auth = auth.replace(/%3A/i, ':');
  30403. auth += '@';
  30404. }
  30405. var protocol = self.protocol || '',
  30406. pathname = self.pathname || '',
  30407. hash = self.hash || '',
  30408. host = false,
  30409. query = '';
  30410. if (self.host) {
  30411. host = auth + self.host;
  30412. } else if (self.hostname) {
  30413. host = auth + (self.hostname.indexOf(':') === -1 ?
  30414. self.hostname :
  30415. '[' + this.hostname + ']');
  30416. if (self.port) {
  30417. host += ':' + self.port;
  30418. }
  30419. }
  30420. if (self.query &&
  30421. isObject$1(self.query) &&
  30422. Object.keys(self.query).length) {
  30423. query = stringify(self.query);
  30424. }
  30425. var search = self.search || (query && ('?' + query)) || '';
  30426. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  30427. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  30428. // unless they had them to begin with.
  30429. if (self.slashes ||
  30430. (!protocol || slashedProtocol[protocol]) && host !== false) {
  30431. host = '//' + (host || '');
  30432. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  30433. } else if (!host) {
  30434. host = '';
  30435. }
  30436. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  30437. if (search && search.charAt(0) !== '?') search = '?' + search;
  30438. pathname = pathname.replace(/[?#]/g, function(match) {
  30439. return encodeURIComponent(match);
  30440. });
  30441. search = search.replace('#', '%23');
  30442. return protocol + host + pathname + search + hash;
  30443. }
  30444. Url.prototype.format = function() {
  30445. return format(this);
  30446. };
  30447. function urlResolve(source, relative) {
  30448. return urlParse(source, false, true).resolve(relative);
  30449. }
  30450. Url.prototype.resolve = function(relative) {
  30451. return this.resolveObject(urlParse(relative, false, true)).format();
  30452. };
  30453. function urlResolveObject(source, relative) {
  30454. if (!source) return relative;
  30455. return urlParse(source, false, true).resolveObject(relative);
  30456. }
  30457. Url.prototype.resolveObject = function(relative) {
  30458. if (isString(relative)) {
  30459. var rel = new Url();
  30460. rel.parse(relative, false, true);
  30461. relative = rel;
  30462. }
  30463. var result = new Url();
  30464. var tkeys = Object.keys(this);
  30465. for (var tk = 0; tk < tkeys.length; tk++) {
  30466. var tkey = tkeys[tk];
  30467. result[tkey] = this[tkey];
  30468. }
  30469. // hash is always overridden, no matter what.
  30470. // even href="" will remove it.
  30471. result.hash = relative.hash;
  30472. // if the relative url is empty, then there's nothing left to do here.
  30473. if (relative.href === '') {
  30474. result.href = result.format();
  30475. return result;
  30476. }
  30477. // hrefs like //foo/bar always cut to the protocol.
  30478. if (relative.slashes && !relative.protocol) {
  30479. // take everything except the protocol from relative
  30480. var rkeys = Object.keys(relative);
  30481. for (var rk = 0; rk < rkeys.length; rk++) {
  30482. var rkey = rkeys[rk];
  30483. if (rkey !== 'protocol')
  30484. result[rkey] = relative[rkey];
  30485. }
  30486. //urlParse appends trailing / to urls like http://www.example.com
  30487. if (slashedProtocol[result.protocol] &&
  30488. result.hostname && !result.pathname) {
  30489. result.path = result.pathname = '/';
  30490. }
  30491. result.href = result.format();
  30492. return result;
  30493. }
  30494. var relPath;
  30495. if (relative.protocol && relative.protocol !== result.protocol) {
  30496. // if it's a known url protocol, then changing
  30497. // the protocol does weird things
  30498. // first, if it's not file:, then we MUST have a host,
  30499. // and if there was a path
  30500. // to begin with, then we MUST have a path.
  30501. // if it is file:, then the host is dropped,
  30502. // because that's known to be hostless.
  30503. // anything else is assumed to be absolute.
  30504. if (!slashedProtocol[relative.protocol]) {
  30505. var keys = Object.keys(relative);
  30506. for (var v = 0; v < keys.length; v++) {
  30507. var k = keys[v];
  30508. result[k] = relative[k];
  30509. }
  30510. result.href = result.format();
  30511. return result;
  30512. }
  30513. result.protocol = relative.protocol;
  30514. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  30515. relPath = (relative.pathname || '').split('/');
  30516. while (relPath.length && !(relative.host = relPath.shift()));
  30517. if (!relative.host) relative.host = '';
  30518. if (!relative.hostname) relative.hostname = '';
  30519. if (relPath[0] !== '') relPath.unshift('');
  30520. if (relPath.length < 2) relPath.unshift('');
  30521. result.pathname = relPath.join('/');
  30522. } else {
  30523. result.pathname = relative.pathname;
  30524. }
  30525. result.search = relative.search;
  30526. result.query = relative.query;
  30527. result.host = relative.host || '';
  30528. result.auth = relative.auth;
  30529. result.hostname = relative.hostname || relative.host;
  30530. result.port = relative.port;
  30531. // to support http.request
  30532. if (result.pathname || result.search) {
  30533. var p = result.pathname || '';
  30534. var s = result.search || '';
  30535. result.path = p + s;
  30536. }
  30537. result.slashes = result.slashes || relative.slashes;
  30538. result.href = result.format();
  30539. return result;
  30540. }
  30541. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  30542. isRelAbs = (
  30543. relative.host ||
  30544. relative.pathname && relative.pathname.charAt(0) === '/'
  30545. ),
  30546. mustEndAbs = (isRelAbs || isSourceAbs ||
  30547. (result.host && relative.pathname)),
  30548. removeAllDots = mustEndAbs,
  30549. srcPath = result.pathname && result.pathname.split('/') || [],
  30550. psychotic = result.protocol && !slashedProtocol[result.protocol];
  30551. relPath = relative.pathname && relative.pathname.split('/') || [];
  30552. // if the url is a non-slashed url, then relative
  30553. // links like ../.. should be able
  30554. // to crawl up to the hostname, as well. This is strange.
  30555. // result.protocol has already been set by now.
  30556. // Later on, put the first path part into the host field.
  30557. if (psychotic) {
  30558. result.hostname = '';
  30559. result.port = null;
  30560. if (result.host) {
  30561. if (srcPath[0] === '') srcPath[0] = result.host;
  30562. else srcPath.unshift(result.host);
  30563. }
  30564. result.host = '';
  30565. if (relative.protocol) {
  30566. relative.hostname = null;
  30567. relative.port = null;
  30568. if (relative.host) {
  30569. if (relPath[0] === '') relPath[0] = relative.host;
  30570. else relPath.unshift(relative.host);
  30571. }
  30572. relative.host = null;
  30573. }
  30574. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  30575. }
  30576. var authInHost;
  30577. if (isRelAbs) {
  30578. // it's absolute.
  30579. result.host = (relative.host || relative.host === '') ?
  30580. relative.host : result.host;
  30581. result.hostname = (relative.hostname || relative.hostname === '') ?
  30582. relative.hostname : result.hostname;
  30583. result.search = relative.search;
  30584. result.query = relative.query;
  30585. srcPath = relPath;
  30586. // fall through to the dot-handling below.
  30587. } else if (relPath.length) {
  30588. // it's relative
  30589. // throw away the existing file, and take the new path instead.
  30590. if (!srcPath) srcPath = [];
  30591. srcPath.pop();
  30592. srcPath = srcPath.concat(relPath);
  30593. result.search = relative.search;
  30594. result.query = relative.query;
  30595. } else if (!isNullOrUndefined(relative.search)) {
  30596. // just pull out the search.
  30597. // like href='?foo'.
  30598. // Put this after the other two cases because it simplifies the booleans
  30599. if (psychotic) {
  30600. result.hostname = result.host = srcPath.shift();
  30601. //occationaly the auth can get stuck only in host
  30602. //this especially happens in cases like
  30603. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  30604. authInHost = result.host && result.host.indexOf('@') > 0 ?
  30605. result.host.split('@') : false;
  30606. if (authInHost) {
  30607. result.auth = authInHost.shift();
  30608. result.host = result.hostname = authInHost.shift();
  30609. }
  30610. }
  30611. result.search = relative.search;
  30612. result.query = relative.query;
  30613. //to support http.request
  30614. if (!isNull(result.pathname) || !isNull(result.search)) {
  30615. result.path = (result.pathname ? result.pathname : '') +
  30616. (result.search ? result.search : '');
  30617. }
  30618. result.href = result.format();
  30619. return result;
  30620. }
  30621. if (!srcPath.length) {
  30622. // no path at all. easy.
  30623. // we've already handled the other stuff above.
  30624. result.pathname = null;
  30625. //to support http.request
  30626. if (result.search) {
  30627. result.path = '/' + result.search;
  30628. } else {
  30629. result.path = null;
  30630. }
  30631. result.href = result.format();
  30632. return result;
  30633. }
  30634. // if a url ENDs in . or .., then it must get a trailing slash.
  30635. // however, if it ends in anything else non-slashy,
  30636. // then it must NOT get a trailing slash.
  30637. var last = srcPath.slice(-1)[0];
  30638. var hasTrailingSlash = (
  30639. (result.host || relative.host || srcPath.length > 1) &&
  30640. (last === '.' || last === '..') || last === '');
  30641. // strip single dots, resolve double dots to parent dir
  30642. // if the path tries to go above the root, `up` ends up > 0
  30643. var up = 0;
  30644. for (var i = srcPath.length; i >= 0; i--) {
  30645. last = srcPath[i];
  30646. if (last === '.') {
  30647. srcPath.splice(i, 1);
  30648. } else if (last === '..') {
  30649. srcPath.splice(i, 1);
  30650. up++;
  30651. } else if (up) {
  30652. srcPath.splice(i, 1);
  30653. up--;
  30654. }
  30655. }
  30656. // if the path is allowed to go above the root, restore leading ..s
  30657. if (!mustEndAbs && !removeAllDots) {
  30658. for (; up--; up) {
  30659. srcPath.unshift('..');
  30660. }
  30661. }
  30662. if (mustEndAbs && srcPath[0] !== '' &&
  30663. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  30664. srcPath.unshift('');
  30665. }
  30666. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  30667. srcPath.push('');
  30668. }
  30669. var isAbsolute = srcPath[0] === '' ||
  30670. (srcPath[0] && srcPath[0].charAt(0) === '/');
  30671. // put the host back
  30672. if (psychotic) {
  30673. result.hostname = result.host = isAbsolute ? '' :
  30674. srcPath.length ? srcPath.shift() : '';
  30675. //occationaly the auth can get stuck only in host
  30676. //this especially happens in cases like
  30677. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  30678. authInHost = result.host && result.host.indexOf('@') > 0 ?
  30679. result.host.split('@') : false;
  30680. if (authInHost) {
  30681. result.auth = authInHost.shift();
  30682. result.host = result.hostname = authInHost.shift();
  30683. }
  30684. }
  30685. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  30686. if (mustEndAbs && !isAbsolute) {
  30687. srcPath.unshift('');
  30688. }
  30689. if (!srcPath.length) {
  30690. result.pathname = null;
  30691. result.path = null;
  30692. } else {
  30693. result.pathname = srcPath.join('/');
  30694. }
  30695. //to support request.http
  30696. if (!isNull(result.pathname) || !isNull(result.search)) {
  30697. result.path = (result.pathname ? result.pathname : '') +
  30698. (result.search ? result.search : '');
  30699. }
  30700. result.auth = relative.auth || result.auth;
  30701. result.slashes = result.slashes || relative.slashes;
  30702. result.href = result.format();
  30703. return result;
  30704. };
  30705. Url.prototype.parseHost = function() {
  30706. return parseHost(this);
  30707. };
  30708. function parseHost(self) {
  30709. var host = self.host;
  30710. var port = portPattern.exec(host);
  30711. if (port) {
  30712. port = port[0];
  30713. if (port !== ':') {
  30714. self.port = port.substr(1);
  30715. }
  30716. host = host.substr(0, host.length - port.length);
  30717. }
  30718. if (host) self.hostname = host;
  30719. }
  30720. var _polyfillNode_url$1 = /*#__PURE__*/Object.freeze({
  30721. __proto__: null,
  30722. URL: URL$1,
  30723. URLSearchParams: URLSearchParams,
  30724. Url: Url,
  30725. default: _polyfillNode_url,
  30726. fileURLToPath: urlFileURLToPath,
  30727. format: urlFormat,
  30728. parse: urlParse,
  30729. resolve: urlResolve,
  30730. resolveObject: urlResolveObject
  30731. });
  30732. function isRelativeUrl(url) {
  30733. const firstChar = url.charAt(0);
  30734. return firstChar === "." || firstChar === "~" || firstChar === "@" || firstChar === "#";
  30735. }
  30736. const externalRE = /^(?:https?:)?\/\//;
  30737. function isExternalUrl(url) {
  30738. return externalRE.test(url);
  30739. }
  30740. const dataUrlRE = /^\s*data:/i;
  30741. function isDataUrl(url) {
  30742. return dataUrlRE.test(url);
  30743. }
  30744. function normalizeDecodedImportPath(source) {
  30745. try {
  30746. return decodeURIComponent(source);
  30747. } catch (e) {
  30748. return source;
  30749. }
  30750. }
  30751. function parseUrl(url) {
  30752. const firstChar = url.charAt(0);
  30753. if (firstChar === "~") {
  30754. const secondChar = url.charAt(1);
  30755. url = url.slice(secondChar === "/" ? 2 : 1);
  30756. }
  30757. return parseUriParts(url);
  30758. }
  30759. function parseUriParts(urlString) {
  30760. return urlParse(isString$1(urlString) ? urlString : "", false, true);
  30761. }
  30762. var __defProp$9 = Object.defineProperty;
  30763. var __defProps$8 = Object.defineProperties;
  30764. var __getOwnPropDescs$8 = Object.getOwnPropertyDescriptors;
  30765. var __getOwnPropSymbols$9 = Object.getOwnPropertySymbols;
  30766. var __hasOwnProp$9 = Object.prototype.hasOwnProperty;
  30767. var __propIsEnum$9 = Object.prototype.propertyIsEnumerable;
  30768. var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  30769. var __spreadValues$9 = (a, b) => {
  30770. for (var prop in b || (b = {}))
  30771. if (__hasOwnProp$9.call(b, prop))
  30772. __defNormalProp$9(a, prop, b[prop]);
  30773. if (__getOwnPropSymbols$9)
  30774. for (var prop of __getOwnPropSymbols$9(b)) {
  30775. if (__propIsEnum$9.call(b, prop))
  30776. __defNormalProp$9(a, prop, b[prop]);
  30777. }
  30778. return a;
  30779. };
  30780. var __spreadProps$8 = (a, b) => __defProps$8(a, __getOwnPropDescs$8(b));
  30781. const resourceUrlTagConfig = {
  30782. video: ["src", "poster"],
  30783. source: ["src"],
  30784. img: ["src"]
  30785. };
  30786. const defaultAssetUrlOptions = {
  30787. base: null,
  30788. includeAbsolute: false,
  30789. tags: __spreadProps$8(__spreadValues$9({}, resourceUrlTagConfig), {
  30790. image: ["xlink:href", "href"],
  30791. use: ["xlink:href", "href"]
  30792. })
  30793. };
  30794. const normalizeOptions = (options) => {
  30795. if (Object.keys(options).some((key) => isArray$3(options[key]))) {
  30796. return __spreadProps$8(__spreadValues$9({}, defaultAssetUrlOptions), {
  30797. tags: options
  30798. });
  30799. }
  30800. return __spreadValues$9(__spreadValues$9({}, defaultAssetUrlOptions), options);
  30801. };
  30802. const createAssetUrlTransformWithOptions = (options) => {
  30803. return (node, context) => transformAssetUrl(node, context, options);
  30804. };
  30805. function canTransformHashImport(tag, attrName) {
  30806. var _a;
  30807. return !!((_a = resourceUrlTagConfig[tag]) == null ? void 0 : _a.includes(attrName));
  30808. }
  30809. const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
  30810. if (node.type === 1) {
  30811. if (!node.props.length) {
  30812. return;
  30813. }
  30814. const tags = options.tags || defaultAssetUrlOptions.tags;
  30815. const attrs = tags[node.tag];
  30816. const wildCardAttrs = tags["*"];
  30817. if (!attrs && !wildCardAttrs) {
  30818. return;
  30819. }
  30820. const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
  30821. node.props.forEach((attr, index) => {
  30822. if (attr.type !== 6 || !assetAttrs.includes(attr.name) || !attr.value) {
  30823. return;
  30824. }
  30825. const urlValue = attr.value.content;
  30826. const isHashOnlyValue = urlValue[0] === "#";
  30827. if (isExternalUrl(urlValue) || isDataUrl(urlValue) || // a bare `#` is never a valid import specifier
  30828. urlValue === "#" || isHashOnlyValue && !canTransformHashImport(node.tag, attr.name) || !options.includeAbsolute && !isRelativeUrl(urlValue)) {
  30829. return;
  30830. }
  30831. const url = parseUrl(urlValue);
  30832. if (options.base && urlValue[0] === ".") {
  30833. const base = parseUrl(options.base);
  30834. const protocol = base.protocol || "";
  30835. const host = base.host ? protocol + "//" + base.host : "";
  30836. const basePath = base.path || "/";
  30837. attr.value.content = host + (path.posix || path).join(basePath, url.path + (url.hash || ""));
  30838. return;
  30839. }
  30840. const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
  30841. node.props[index] = {
  30842. type: 7,
  30843. name: "bind",
  30844. arg: createSimpleExpression(attr.name, true, attr.loc),
  30845. exp,
  30846. modifiers: [],
  30847. loc: attr.loc
  30848. };
  30849. });
  30850. }
  30851. };
  30852. function resolveOrRegisterImport(source, loc, context) {
  30853. const normalizedSource = normalizeDecodedImportPath(source);
  30854. const existingIndex = context.imports.findIndex(
  30855. (i) => i.path === normalizedSource
  30856. );
  30857. if (existingIndex > -1) {
  30858. return {
  30859. name: `_imports_${existingIndex}`,
  30860. exp: context.imports[existingIndex].exp
  30861. };
  30862. }
  30863. const name = `_imports_${context.imports.length}`;
  30864. const exp = createSimpleExpression(
  30865. name,
  30866. false,
  30867. loc,
  30868. 3
  30869. );
  30870. context.imports.push({
  30871. exp,
  30872. path: normalizedSource
  30873. });
  30874. return { name, exp };
  30875. }
  30876. function getImportsExpressionExp(path2, hash, loc, context) {
  30877. if (!path2 && !hash) {
  30878. return createSimpleExpression(`''`, false, loc, 3);
  30879. }
  30880. if (!path2 && hash) {
  30881. const { exp } = resolveOrRegisterImport(hash, loc, context);
  30882. return exp;
  30883. }
  30884. if (path2 && !hash) {
  30885. const { exp } = resolveOrRegisterImport(path2, loc, context);
  30886. return exp;
  30887. }
  30888. const { name } = resolveOrRegisterImport(path2, loc, context);
  30889. const hashExp = `${name} + '${hash}'`;
  30890. const finalExp = createSimpleExpression(
  30891. hashExp,
  30892. false,
  30893. loc,
  30894. 3
  30895. );
  30896. if (!context.hoistStatic) {
  30897. return finalExp;
  30898. }
  30899. const existingHoistIndex = context.hoists.findIndex((h) => {
  30900. return h && h.type === 4 && !h.isStatic && h.content === hashExp;
  30901. });
  30902. if (existingHoistIndex > -1) {
  30903. return createSimpleExpression(
  30904. `_hoisted_${existingHoistIndex + 1}`,
  30905. false,
  30906. loc,
  30907. 3
  30908. );
  30909. }
  30910. return context.hoist(finalExp);
  30911. }
  30912. const srcsetTags = ["img", "source"];
  30913. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  30914. const createSrcsetTransformWithOptions = (options) => {
  30915. return (node, context) => transformSrcset(node, context, options);
  30916. };
  30917. const transformSrcset = (node, context, options = defaultAssetUrlOptions) => {
  30918. if (node.type === 1) {
  30919. if (srcsetTags.includes(node.tag) && node.props.length) {
  30920. node.props.forEach((attr, index) => {
  30921. if (attr.name === "srcset" && attr.type === 6) {
  30922. if (!attr.value) return;
  30923. const value = attr.value.content;
  30924. if (!value) return;
  30925. const imageCandidates = value.split(",").map((s) => {
  30926. const [url, descriptor] = s.replace(escapedSpaceCharacters, " ").trim().split(" ", 2);
  30927. return { url, descriptor };
  30928. });
  30929. for (let i = 0; i < imageCandidates.length; i++) {
  30930. const { url } = imageCandidates[i];
  30931. if (isDataUrl(url)) {
  30932. imageCandidates[i + 1].url = url + "," + imageCandidates[i + 1].url;
  30933. imageCandidates.splice(i, 1);
  30934. }
  30935. }
  30936. const shouldProcessUrl = (url) => {
  30937. return url && !isExternalUrl(url) && !isDataUrl(url) && (options.includeAbsolute || isRelativeUrl(url));
  30938. };
  30939. if (!imageCandidates.some(({ url }) => shouldProcessUrl(url))) {
  30940. return;
  30941. }
  30942. if (options.base) {
  30943. const base = options.base;
  30944. const set = [];
  30945. let needImportTransform = false;
  30946. imageCandidates.forEach((candidate) => {
  30947. let { url, descriptor } = candidate;
  30948. descriptor = descriptor ? ` ${descriptor}` : ``;
  30949. if (url[0] === ".") {
  30950. candidate.url = (path.posix || path).join(base, url);
  30951. set.push(candidate.url + descriptor);
  30952. } else if (shouldProcessUrl(url)) {
  30953. needImportTransform = true;
  30954. } else {
  30955. set.push(url + descriptor);
  30956. }
  30957. });
  30958. if (!needImportTransform) {
  30959. attr.value.content = set.join(", ");
  30960. return;
  30961. }
  30962. }
  30963. const compoundExpression = createCompoundExpression([], attr.loc);
  30964. imageCandidates.forEach(({ url, descriptor }, index2) => {
  30965. if (shouldProcessUrl(url)) {
  30966. const { path: path2, hash } = parseUrl(url);
  30967. const source = path2 ? path2 : hash;
  30968. if (source) {
  30969. const normalizedSource = normalizeDecodedImportPath(source);
  30970. const existingImportsIndex = context.imports.findIndex(
  30971. (i) => i.path === normalizedSource
  30972. );
  30973. let exp2;
  30974. if (existingImportsIndex > -1) {
  30975. exp2 = createSimpleExpression(
  30976. `_imports_${existingImportsIndex}`,
  30977. false,
  30978. attr.loc,
  30979. 3
  30980. );
  30981. } else {
  30982. exp2 = createSimpleExpression(
  30983. `_imports_${context.imports.length}`,
  30984. false,
  30985. attr.loc,
  30986. 3
  30987. );
  30988. context.imports.push({ exp: exp2, path: normalizedSource });
  30989. }
  30990. if (path2 && hash) {
  30991. exp2 = createSimpleExpression(
  30992. `${exp2.content} + '${hash}'`,
  30993. false,
  30994. attr.loc,
  30995. 3
  30996. );
  30997. }
  30998. compoundExpression.children.push(exp2);
  30999. }
  31000. } else {
  31001. const exp2 = createSimpleExpression(
  31002. `"${url}"`,
  31003. false,
  31004. attr.loc,
  31005. 3
  31006. );
  31007. compoundExpression.children.push(exp2);
  31008. }
  31009. const isNotLast = imageCandidates.length - 1 > index2;
  31010. if (descriptor && isNotLast) {
  31011. compoundExpression.children.push(` + ' ${descriptor}, ' + `);
  31012. } else if (descriptor) {
  31013. compoundExpression.children.push(` + ' ${descriptor}'`);
  31014. } else if (isNotLast) {
  31015. compoundExpression.children.push(` + ', ' + `);
  31016. }
  31017. });
  31018. let exp = compoundExpression;
  31019. if (context.hoistStatic) {
  31020. exp = context.hoist(compoundExpression);
  31021. exp.constType = 3;
  31022. }
  31023. node.props[index] = {
  31024. type: 7,
  31025. name: "bind",
  31026. arg: createSimpleExpression("srcset", true, attr.loc),
  31027. exp,
  31028. modifiers: [],
  31029. loc: attr.loc
  31030. };
  31031. }
  31032. });
  31033. }
  31034. }
  31035. };
  31036. const SSR_INTERPOLATE = /* @__PURE__ */ Symbol(`ssrInterpolate`);
  31037. const SSR_RENDER_VNODE = /* @__PURE__ */ Symbol(`ssrRenderVNode`);
  31038. const SSR_RENDER_COMPONENT = /* @__PURE__ */ Symbol(`ssrRenderComponent`);
  31039. const SSR_RENDER_SLOT = /* @__PURE__ */ Symbol(`ssrRenderSlot`);
  31040. const SSR_RENDER_SLOT_INNER = /* @__PURE__ */ Symbol(`ssrRenderSlotInner`);
  31041. const SSR_RENDER_CLASS = /* @__PURE__ */ Symbol(`ssrRenderClass`);
  31042. const SSR_RENDER_STYLE = /* @__PURE__ */ Symbol(`ssrRenderStyle`);
  31043. const SSR_RENDER_ATTRS = /* @__PURE__ */ Symbol(`ssrRenderAttrs`);
  31044. const SSR_RENDER_ATTR = /* @__PURE__ */ Symbol(`ssrRenderAttr`);
  31045. const SSR_RENDER_DYNAMIC_ATTR = /* @__PURE__ */ Symbol(`ssrRenderDynamicAttr`);
  31046. const SSR_RENDER_LIST = /* @__PURE__ */ Symbol(`ssrRenderList`);
  31047. const SSR_INCLUDE_BOOLEAN_ATTR = /* @__PURE__ */ Symbol(
  31048. `ssrIncludeBooleanAttr`
  31049. );
  31050. const SSR_LOOSE_EQUAL = /* @__PURE__ */ Symbol(`ssrLooseEqual`);
  31051. const SSR_LOOSE_CONTAIN = /* @__PURE__ */ Symbol(`ssrLooseContain`);
  31052. const SSR_RENDER_DYNAMIC_MODEL = /* @__PURE__ */ Symbol(
  31053. `ssrRenderDynamicModel`
  31054. );
  31055. const SSR_GET_DYNAMIC_MODEL_PROPS = /* @__PURE__ */ Symbol(
  31056. `ssrGetDynamicModelProps`
  31057. );
  31058. const SSR_RENDER_TELEPORT = /* @__PURE__ */ Symbol(`ssrRenderTeleport`);
  31059. const SSR_RENDER_SUSPENSE = /* @__PURE__ */ Symbol(`ssrRenderSuspense`);
  31060. const SSR_GET_DIRECTIVE_PROPS = /* @__PURE__ */ Symbol(`ssrGetDirectiveProps`);
  31061. const ssrHelpers = {
  31062. [SSR_INTERPOLATE]: `ssrInterpolate`,
  31063. [SSR_RENDER_VNODE]: `ssrRenderVNode`,
  31064. [SSR_RENDER_COMPONENT]: `ssrRenderComponent`,
  31065. [SSR_RENDER_SLOT]: `ssrRenderSlot`,
  31066. [SSR_RENDER_SLOT_INNER]: `ssrRenderSlotInner`,
  31067. [SSR_RENDER_CLASS]: `ssrRenderClass`,
  31068. [SSR_RENDER_STYLE]: `ssrRenderStyle`,
  31069. [SSR_RENDER_ATTRS]: `ssrRenderAttrs`,
  31070. [SSR_RENDER_ATTR]: `ssrRenderAttr`,
  31071. [SSR_RENDER_DYNAMIC_ATTR]: `ssrRenderDynamicAttr`,
  31072. [SSR_RENDER_LIST]: `ssrRenderList`,
  31073. [SSR_INCLUDE_BOOLEAN_ATTR]: `ssrIncludeBooleanAttr`,
  31074. [SSR_LOOSE_EQUAL]: `ssrLooseEqual`,
  31075. [SSR_LOOSE_CONTAIN]: `ssrLooseContain`,
  31076. [SSR_RENDER_DYNAMIC_MODEL]: `ssrRenderDynamicModel`,
  31077. [SSR_GET_DYNAMIC_MODEL_PROPS]: `ssrGetDynamicModelProps`,
  31078. [SSR_RENDER_TELEPORT]: `ssrRenderTeleport`,
  31079. [SSR_RENDER_SUSPENSE]: `ssrRenderSuspense`,
  31080. [SSR_GET_DIRECTIVE_PROPS]: `ssrGetDirectiveProps`
  31081. };
  31082. registerRuntimeHelpers(ssrHelpers);
  31083. const ssrTransformIf = createStructuralDirectiveTransform(
  31084. /^(?:if|else|else-if)$/,
  31085. processIf
  31086. );
  31087. function ssrProcessIf(node, context, disableNestedFragments = false, disableComment = false) {
  31088. const [rootBranch] = node.branches;
  31089. const ifStatement = createIfStatement(
  31090. rootBranch.condition,
  31091. processIfBranch(rootBranch, context, disableNestedFragments)
  31092. );
  31093. context.pushStatement(ifStatement);
  31094. let currentIf = ifStatement;
  31095. for (let i = 1; i < node.branches.length; i++) {
  31096. const branch = node.branches[i];
  31097. const branchBlockStatement = processIfBranch(
  31098. branch,
  31099. context,
  31100. disableNestedFragments
  31101. );
  31102. if (branch.condition) {
  31103. currentIf = currentIf.alternate = createIfStatement(
  31104. branch.condition,
  31105. branchBlockStatement
  31106. );
  31107. } else {
  31108. currentIf.alternate = branchBlockStatement;
  31109. }
  31110. }
  31111. if (!currentIf.alternate && !disableComment) {
  31112. currentIf.alternate = createBlockStatement([
  31113. createCallExpression(`_push`, ["`<!---->`"])
  31114. ]);
  31115. }
  31116. }
  31117. function processIfBranch(branch, context, disableNestedFragments = false) {
  31118. const { children } = branch;
  31119. const needFragmentWrapper = !disableNestedFragments && (children.length !== 1 || children[0].type !== 1) && // optimize away nested fragments when the only child is a ForNode
  31120. !(children.length === 1 && children[0].type === 11);
  31121. return processChildrenAsStatement(branch, context, needFragmentWrapper);
  31122. }
  31123. const ssrTransformFor = createStructuralDirectiveTransform("for", processFor);
  31124. function ssrProcessFor(node, context, disableNestedFragments = false) {
  31125. const needFragmentWrapper = !disableNestedFragments && (node.children.length !== 1 || node.children[0].type !== 1);
  31126. const renderLoop = createFunctionExpression(
  31127. createForLoopParams(node.parseResult)
  31128. );
  31129. renderLoop.body = processChildrenAsStatement(
  31130. node,
  31131. context,
  31132. needFragmentWrapper
  31133. );
  31134. if (!disableNestedFragments) {
  31135. context.pushStringPart(`<!--[-->`);
  31136. }
  31137. context.pushStatement(
  31138. createCallExpression(context.helper(SSR_RENDER_LIST), [
  31139. node.source,
  31140. renderLoop
  31141. ])
  31142. );
  31143. if (!disableNestedFragments) {
  31144. context.pushStringPart(`<!--]-->`);
  31145. }
  31146. }
  31147. const ssrTransformSlotOutlet = (node, context) => {
  31148. if (isSlotOutlet(node)) {
  31149. const { slotName, slotProps } = processSlotOutlet(node, context);
  31150. const args = [
  31151. `_ctx.$slots`,
  31152. slotName,
  31153. slotProps || `{}`,
  31154. // fallback content placeholder. will be replaced in the process phase
  31155. `null`,
  31156. `_push`,
  31157. `_parent`
  31158. ];
  31159. if (context.scopeId && context.slotted !== false) {
  31160. args.push(`"${context.scopeId}-s"`);
  31161. }
  31162. let method = SSR_RENDER_SLOT;
  31163. let parent = context.parent;
  31164. if (parent) {
  31165. const children = parent.children;
  31166. if (parent.type === 10) {
  31167. parent = context.grandParent;
  31168. }
  31169. let componentType;
  31170. if (parent.type === 1 && parent.tagType === 1 && ((componentType = resolveComponentType(parent, context, true)) === TRANSITION || componentType === TRANSITION_GROUP) && children.filter((c) => c.type === 1).length === 1) {
  31171. method = SSR_RENDER_SLOT_INNER;
  31172. if (!(context.scopeId && context.slotted !== false)) {
  31173. args.push("null");
  31174. }
  31175. args.push("true");
  31176. }
  31177. }
  31178. node.ssrCodegenNode = createCallExpression(context.helper(method), args);
  31179. }
  31180. };
  31181. function ssrProcessSlotOutlet(node, context) {
  31182. const renderCall = node.ssrCodegenNode;
  31183. if (node.children.length) {
  31184. const fallbackRenderFn = createFunctionExpression([]);
  31185. fallbackRenderFn.body = processChildrenAsStatement(node, context);
  31186. renderCall.arguments[3] = fallbackRenderFn;
  31187. }
  31188. if (context.withSlotScopeId) {
  31189. const slotScopeId = renderCall.arguments[6];
  31190. renderCall.arguments[6] = slotScopeId ? `${slotScopeId} + _scopeId` : `_scopeId`;
  31191. }
  31192. context.pushStatement(node.ssrCodegenNode);
  31193. }
  31194. function createSSRCompilerError(code, loc) {
  31195. return createCompilerError(code, loc, SSRErrorMessages);
  31196. }
  31197. const SSRErrorMessages = {
  31198. [65]: `Unsafe attribute name for SSR.`,
  31199. [66]: `Missing the 'to' prop on teleport element.`,
  31200. [67]: `Invalid AST node during SSR transform.`
  31201. };
  31202. function ssrProcessTeleport(node, context) {
  31203. const targetProp = findProp(node, "to");
  31204. if (!targetProp) {
  31205. context.onError(
  31206. createSSRCompilerError(66, node.loc)
  31207. );
  31208. return;
  31209. }
  31210. let target;
  31211. if (targetProp.type === 6) {
  31212. target = targetProp.value && createSimpleExpression(targetProp.value.content, true);
  31213. } else {
  31214. target = targetProp.exp;
  31215. }
  31216. if (!target) {
  31217. context.onError(
  31218. createSSRCompilerError(
  31219. 66,
  31220. targetProp.loc
  31221. )
  31222. );
  31223. return;
  31224. }
  31225. const disabledProp = findProp(
  31226. node,
  31227. "disabled",
  31228. false,
  31229. true
  31230. /* allow empty */
  31231. );
  31232. const disabled = disabledProp ? disabledProp.type === 6 ? `true` : disabledProp.exp || `false` : `false`;
  31233. const contentRenderFn = createFunctionExpression(
  31234. [`_push`],
  31235. void 0,
  31236. // Body is added later
  31237. true,
  31238. // newline
  31239. false,
  31240. // isSlot
  31241. node.loc
  31242. );
  31243. contentRenderFn.body = processChildrenAsStatement(node, context);
  31244. context.pushStatement(
  31245. createCallExpression(context.helper(SSR_RENDER_TELEPORT), [
  31246. `_push`,
  31247. contentRenderFn,
  31248. target,
  31249. disabled,
  31250. `_parent`
  31251. ])
  31252. );
  31253. }
  31254. const wipMap$3 = /* @__PURE__ */ new WeakMap();
  31255. function ssrTransformSuspense(node, context) {
  31256. return () => {
  31257. if (node.children.length) {
  31258. const wipEntry = {
  31259. slotsExp: null,
  31260. // to be immediately set
  31261. wipSlots: []
  31262. };
  31263. wipMap$3.set(node, wipEntry);
  31264. wipEntry.slotsExp = buildSlots(
  31265. node,
  31266. context,
  31267. (_props, _vForExp, children, loc) => {
  31268. const fn = createFunctionExpression(
  31269. [],
  31270. void 0,
  31271. // no return, assign body later
  31272. true,
  31273. // newline
  31274. false,
  31275. // suspense slots are not treated as normal slots
  31276. loc
  31277. );
  31278. wipEntry.wipSlots.push({
  31279. fn,
  31280. children
  31281. });
  31282. return fn;
  31283. }
  31284. ).slots;
  31285. }
  31286. };
  31287. }
  31288. function ssrProcessSuspense(node, context) {
  31289. const wipEntry = wipMap$3.get(node);
  31290. if (!wipEntry) {
  31291. return;
  31292. }
  31293. const { slotsExp, wipSlots } = wipEntry;
  31294. for (let i = 0; i < wipSlots.length; i++) {
  31295. const slot = wipSlots[i];
  31296. slot.fn.body = processChildrenAsStatement(slot, context);
  31297. }
  31298. context.pushStatement(
  31299. createCallExpression(context.helper(SSR_RENDER_SUSPENSE), [
  31300. `_push`,
  31301. slotsExp
  31302. ])
  31303. );
  31304. }
  31305. const rawChildrenMap = /* @__PURE__ */ new WeakMap();
  31306. const ssrTransformElement = (node, context) => {
  31307. if (node.type !== 1 || node.tagType !== 0) {
  31308. return;
  31309. }
  31310. return function ssrPostTransformElement() {
  31311. const openTag = [`<${node.tag}`];
  31312. const needTagForRuntime = node.tag === "textarea" || node.tag.indexOf("-") > 0;
  31313. const hasDynamicVBind = hasDynamicKeyVBind(node);
  31314. const hasCustomDir = node.props.some(
  31315. (p) => p.type === 7 && !isBuiltInDirective(p.name)
  31316. );
  31317. const vShowPropIndex = node.props.findIndex(
  31318. (i) => i.type === 7 && i.name === "show"
  31319. );
  31320. if (vShowPropIndex !== -1) {
  31321. const vShowProp = node.props[vShowPropIndex];
  31322. node.props.splice(vShowPropIndex, 1);
  31323. node.props.push(vShowProp);
  31324. }
  31325. const needMergeProps = hasDynamicVBind || hasCustomDir;
  31326. if (needMergeProps) {
  31327. const { props, directives } = buildProps(
  31328. node,
  31329. context,
  31330. node.props,
  31331. false,
  31332. false,
  31333. true
  31334. );
  31335. if (props || directives.length) {
  31336. const mergedProps = buildSSRProps(props, directives, context);
  31337. const propsExp = createCallExpression(
  31338. context.helper(SSR_RENDER_ATTRS),
  31339. [mergedProps]
  31340. );
  31341. if (node.tag === "textarea") {
  31342. const existingText = node.children[0];
  31343. if (!hasContentOverrideDirective(node) && (!existingText || existingText.type !== 5)) {
  31344. const tempId = `_temp${context.temps++}`;
  31345. propsExp.arguments = [
  31346. createAssignmentExpression(
  31347. createSimpleExpression(tempId, false),
  31348. mergedProps
  31349. )
  31350. ];
  31351. rawChildrenMap.set(
  31352. node,
  31353. createCallExpression(context.helper(SSR_INTERPOLATE), [
  31354. createConditionalExpression(
  31355. createSimpleExpression(`"value" in ${tempId}`, false),
  31356. createSimpleExpression(`${tempId}.value`, false),
  31357. createSimpleExpression(
  31358. existingText ? existingText.content : ``,
  31359. true
  31360. ),
  31361. false
  31362. )
  31363. ])
  31364. );
  31365. }
  31366. } else if (node.tag === "input") {
  31367. const vModel = findVModel(node);
  31368. if (vModel) {
  31369. const tempId = `_temp${context.temps++}`;
  31370. const tempExp = createSimpleExpression(tempId, false);
  31371. propsExp.arguments = [
  31372. createSequenceExpression([
  31373. createAssignmentExpression(tempExp, mergedProps),
  31374. createCallExpression(context.helper(MERGE_PROPS), [
  31375. tempExp,
  31376. createCallExpression(
  31377. context.helper(SSR_GET_DYNAMIC_MODEL_PROPS),
  31378. [
  31379. tempExp,
  31380. // existing props
  31381. vModel.exp
  31382. // model
  31383. ]
  31384. )
  31385. ])
  31386. ])
  31387. ];
  31388. }
  31389. } else if (directives.length && !node.children.length) {
  31390. if (!hasContentOverrideDirective(node)) {
  31391. const tempId = `_temp${context.temps++}`;
  31392. propsExp.arguments = [
  31393. createAssignmentExpression(
  31394. createSimpleExpression(tempId, false),
  31395. mergedProps
  31396. )
  31397. ];
  31398. rawChildrenMap.set(
  31399. node,
  31400. createConditionalExpression(
  31401. createSimpleExpression(`"textContent" in ${tempId}`, false),
  31402. createCallExpression(context.helper(SSR_INTERPOLATE), [
  31403. createSimpleExpression(`${tempId}.textContent`, false)
  31404. ]),
  31405. createSimpleExpression(`${tempId}.innerHTML ?? ''`, false),
  31406. false
  31407. )
  31408. );
  31409. }
  31410. }
  31411. if (needTagForRuntime) {
  31412. propsExp.arguments.push(`"${node.tag}"`);
  31413. }
  31414. openTag.push(propsExp);
  31415. }
  31416. }
  31417. let dynamicClassBinding = void 0;
  31418. let staticClassBinding = void 0;
  31419. let dynamicStyleBinding = void 0;
  31420. for (let i = 0; i < node.props.length; i++) {
  31421. const prop = node.props[i];
  31422. if (node.tag === "input" && isTrueFalseValue(prop)) {
  31423. continue;
  31424. }
  31425. if (prop.type === 7) {
  31426. if (prop.name === "html" && prop.exp) {
  31427. rawChildrenMap.set(
  31428. node,
  31429. createCompoundExpression([`(`, prop.exp, `) ?? ''`])
  31430. );
  31431. } else if (prop.name === "text" && prop.exp) {
  31432. node.children = [createInterpolation(prop.exp, prop.loc)];
  31433. } else if (prop.name === "slot") {
  31434. context.onError(
  31435. createCompilerError(40, prop.loc)
  31436. );
  31437. } else if (isTextareaWithValue(node, prop) && prop.exp) {
  31438. if (!needMergeProps) {
  31439. node.children = [createInterpolation(prop.exp, prop.loc)];
  31440. }
  31441. } else if (!needMergeProps && prop.name !== "on") {
  31442. const directiveTransform = context.directiveTransforms[prop.name];
  31443. if (directiveTransform) {
  31444. const { props, ssrTagParts } = directiveTransform(
  31445. prop,
  31446. node,
  31447. context
  31448. );
  31449. if (ssrTagParts) {
  31450. openTag.push(...ssrTagParts);
  31451. }
  31452. for (let j = 0; j < props.length; j++) {
  31453. const { key, value } = props[j];
  31454. if (isStaticExp(key)) {
  31455. let attrName = key.content;
  31456. if (attrName === "key" || attrName === "ref") {
  31457. continue;
  31458. }
  31459. if (attrName === "class") {
  31460. openTag.push(
  31461. ` class="`,
  31462. dynamicClassBinding = createCallExpression(
  31463. context.helper(SSR_RENDER_CLASS),
  31464. [value]
  31465. ),
  31466. `"`
  31467. );
  31468. } else if (attrName === "style") {
  31469. if (dynamicStyleBinding) {
  31470. mergeCall(dynamicStyleBinding, value);
  31471. } else {
  31472. openTag.push(
  31473. ` style="`,
  31474. dynamicStyleBinding = createCallExpression(
  31475. context.helper(SSR_RENDER_STYLE),
  31476. [value]
  31477. ),
  31478. `"`
  31479. );
  31480. }
  31481. } else {
  31482. attrName = node.tag.indexOf("-") > 0 ? attrName : propsToAttrMap[attrName] || attrName.toLowerCase();
  31483. if (isBooleanAttr(attrName)) {
  31484. openTag.push(
  31485. createConditionalExpression(
  31486. createCallExpression(
  31487. context.helper(SSR_INCLUDE_BOOLEAN_ATTR),
  31488. [value]
  31489. ),
  31490. createSimpleExpression(" " + attrName, true),
  31491. createSimpleExpression("", true),
  31492. false
  31493. )
  31494. );
  31495. } else if (attrName === "hidden") {
  31496. openTag.push(
  31497. createCallExpression(
  31498. context.helper(SSR_RENDER_DYNAMIC_ATTR),
  31499. [key, value]
  31500. )
  31501. );
  31502. } else if (isSSRSafeAttrName(attrName)) {
  31503. openTag.push(
  31504. createCallExpression(context.helper(SSR_RENDER_ATTR), [
  31505. key,
  31506. value
  31507. ])
  31508. );
  31509. } else {
  31510. context.onError(
  31511. createSSRCompilerError(
  31512. 65,
  31513. key.loc
  31514. )
  31515. );
  31516. }
  31517. }
  31518. } else {
  31519. const args = [key, value];
  31520. if (needTagForRuntime) {
  31521. args.push(`"${node.tag}"`);
  31522. }
  31523. openTag.push(
  31524. createCallExpression(
  31525. context.helper(SSR_RENDER_DYNAMIC_ATTR),
  31526. args
  31527. )
  31528. );
  31529. }
  31530. }
  31531. }
  31532. }
  31533. } else {
  31534. const name = prop.name;
  31535. if (node.tag === "textarea" && name === "value" && prop.value) {
  31536. rawChildrenMap.set(node, escapeHtml(prop.value.content));
  31537. } else if (!needMergeProps) {
  31538. if (name === "key" || name === "ref") {
  31539. continue;
  31540. }
  31541. if (name === "class" && prop.value) {
  31542. staticClassBinding = JSON.stringify(prop.value.content);
  31543. }
  31544. openTag.push(
  31545. ` ${prop.name}` + (prop.value ? `="${escapeHtml(prop.value.content)}"` : ``)
  31546. );
  31547. }
  31548. }
  31549. }
  31550. if (dynamicClassBinding && staticClassBinding) {
  31551. mergeCall(dynamicClassBinding, staticClassBinding);
  31552. removeStaticBinding(openTag, "class");
  31553. }
  31554. if (context.scopeId) {
  31555. openTag.push(` ${context.scopeId}`);
  31556. }
  31557. node.ssrCodegenNode = createTemplateLiteral(openTag);
  31558. };
  31559. };
  31560. function buildSSRProps(props, directives, context) {
  31561. let mergePropsArgs = [];
  31562. if (props) {
  31563. if (props.type === 14) {
  31564. mergePropsArgs = props.arguments;
  31565. } else {
  31566. mergePropsArgs.push(props);
  31567. }
  31568. }
  31569. if (directives.length) {
  31570. for (const dir of directives) {
  31571. mergePropsArgs.push(
  31572. createCallExpression(context.helper(SSR_GET_DIRECTIVE_PROPS), [
  31573. `_ctx`,
  31574. ...buildDirectiveArgs(dir, context).elements
  31575. ])
  31576. );
  31577. }
  31578. }
  31579. return mergePropsArgs.length > 1 ? createCallExpression(context.helper(MERGE_PROPS), mergePropsArgs) : mergePropsArgs[0];
  31580. }
  31581. function isTrueFalseValue(prop) {
  31582. if (prop.type === 7) {
  31583. return prop.name === "bind" && prop.arg && isStaticExp(prop.arg) && (prop.arg.content === "true-value" || prop.arg.content === "false-value");
  31584. } else {
  31585. return prop.name === "true-value" || prop.name === "false-value";
  31586. }
  31587. }
  31588. function isTextareaWithValue(node, prop) {
  31589. return !!(node.tag === "textarea" && prop.name === "bind" && isStaticArgOf(prop.arg, "value"));
  31590. }
  31591. function mergeCall(call, arg) {
  31592. const existing = call.arguments[0];
  31593. if (existing.type === 17) {
  31594. existing.elements.push(arg);
  31595. } else {
  31596. call.arguments[0] = createArrayExpression([existing, arg]);
  31597. }
  31598. }
  31599. function removeStaticBinding(tag, binding) {
  31600. const regExp = new RegExp(`^ ${binding}=".+"$`);
  31601. const i = tag.findIndex((e) => typeof e === "string" && regExp.test(e));
  31602. if (i > -1) {
  31603. tag.splice(i, 1);
  31604. }
  31605. }
  31606. function findVModel(node) {
  31607. return node.props.find(
  31608. (p) => p.type === 7 && p.name === "model" && p.exp
  31609. );
  31610. }
  31611. function hasContentOverrideDirective(node) {
  31612. return !!findDir(node, "text") || !!findDir(node, "html");
  31613. }
  31614. function ssrProcessElement(node, context) {
  31615. const isVoidTag = context.options.isVoidTag || NO;
  31616. const elementsToAdd = node.ssrCodegenNode.elements;
  31617. for (let j = 0; j < elementsToAdd.length; j++) {
  31618. context.pushStringPart(elementsToAdd[j]);
  31619. }
  31620. if (context.withSlotScopeId) {
  31621. context.pushStringPart(createSimpleExpression(`_scopeId`, false));
  31622. }
  31623. context.pushStringPart(`>`);
  31624. const rawChildren = rawChildrenMap.get(node);
  31625. if (rawChildren) {
  31626. context.pushStringPart(rawChildren);
  31627. } else if (node.children.length) {
  31628. processChildren(node, context);
  31629. }
  31630. if (!isVoidTag(node.tag)) {
  31631. context.pushStringPart(`</${node.tag}>`);
  31632. }
  31633. }
  31634. const wipMap$2 = /* @__PURE__ */ new WeakMap();
  31635. function ssrTransformTransitionGroup(node, context) {
  31636. return () => {
  31637. const tag = findProp(node, "tag");
  31638. if (tag) {
  31639. const otherProps = node.props.filter((p) => p !== tag);
  31640. const { props, directives } = buildProps(
  31641. node,
  31642. context,
  31643. otherProps,
  31644. true,
  31645. false,
  31646. true
  31647. );
  31648. let propsExp = null;
  31649. if (props || directives.length) {
  31650. propsExp = createCallExpression(context.helper(SSR_RENDER_ATTRS), [
  31651. buildSSRProps(props, directives, context)
  31652. ]);
  31653. }
  31654. wipMap$2.set(node, {
  31655. tag,
  31656. propsExp,
  31657. scopeId: context.scopeId || null
  31658. });
  31659. }
  31660. };
  31661. }
  31662. function ssrProcessTransitionGroup(node, context) {
  31663. const entry = wipMap$2.get(node);
  31664. if (entry) {
  31665. const { tag, propsExp, scopeId } = entry;
  31666. if (tag.type === 7) {
  31667. context.pushStringPart(`<`);
  31668. context.pushStringPart(tag.exp);
  31669. if (propsExp) {
  31670. context.pushStringPart(propsExp);
  31671. }
  31672. if (scopeId) {
  31673. context.pushStringPart(` ${scopeId}`);
  31674. }
  31675. context.pushStringPart(`>`);
  31676. processChildren(
  31677. node,
  31678. context,
  31679. false,
  31680. /**
  31681. * TransitionGroup has the special runtime behavior of flattening and
  31682. * concatenating all children into a single fragment (in order for them to
  31683. * be patched using the same key map) so we need to account for that here
  31684. * by disabling nested fragment wrappers from being generated.
  31685. */
  31686. true,
  31687. /**
  31688. * TransitionGroup filters out comment children at runtime and thus
  31689. * doesn't expect comments to be present during hydration. We need to
  31690. * account for that by disabling the empty comment that is otherwise
  31691. * rendered for a falsy v-if that has no v-else specified. (#6715)
  31692. */
  31693. true
  31694. );
  31695. context.pushStringPart(`</`);
  31696. context.pushStringPart(tag.exp);
  31697. context.pushStringPart(`>`);
  31698. } else {
  31699. context.pushStringPart(`<${tag.value.content}`);
  31700. if (propsExp) {
  31701. context.pushStringPart(propsExp);
  31702. }
  31703. if (scopeId) {
  31704. context.pushStringPart(` ${scopeId}`);
  31705. }
  31706. context.pushStringPart(`>`);
  31707. processChildren(node, context, false, true, true);
  31708. context.pushStringPart(`</${tag.value.content}>`);
  31709. }
  31710. } else {
  31711. processChildren(node, context, true, true, true);
  31712. }
  31713. }
  31714. const wipMap$1 = /* @__PURE__ */ new WeakMap();
  31715. function ssrTransformTransition(node, context) {
  31716. return () => {
  31717. const appear = findProp(node, "appear", false, true);
  31718. wipMap$1.set(node, !!appear);
  31719. };
  31720. }
  31721. function ssrProcessTransition(node, context) {
  31722. node.children = node.children.filter((c) => c.type !== 3);
  31723. const appear = wipMap$1.get(node);
  31724. if (appear) {
  31725. context.pushStringPart(`<template>`);
  31726. processChildren(node, context, false, true);
  31727. context.pushStringPart(`</template>`);
  31728. } else {
  31729. processChildren(node, context, false, true);
  31730. }
  31731. }
  31732. var __defProp$8 = Object.defineProperty;
  31733. var __defProps$7 = Object.defineProperties;
  31734. var __getOwnPropDescs$7 = Object.getOwnPropertyDescriptors;
  31735. var __getOwnPropSymbols$8 = Object.getOwnPropertySymbols;
  31736. var __hasOwnProp$8 = Object.prototype.hasOwnProperty;
  31737. var __propIsEnum$8 = Object.prototype.propertyIsEnumerable;
  31738. var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  31739. var __spreadValues$8 = (a, b) => {
  31740. for (var prop in b || (b = {}))
  31741. if (__hasOwnProp$8.call(b, prop))
  31742. __defNormalProp$8(a, prop, b[prop]);
  31743. if (__getOwnPropSymbols$8)
  31744. for (var prop of __getOwnPropSymbols$8(b)) {
  31745. if (__propIsEnum$8.call(b, prop))
  31746. __defNormalProp$8(a, prop, b[prop]);
  31747. }
  31748. return a;
  31749. };
  31750. var __spreadProps$7 = (a, b) => __defProps$7(a, __getOwnPropDescs$7(b));
  31751. const wipMap = /* @__PURE__ */ new WeakMap();
  31752. const WIP_SLOT = /* @__PURE__ */ Symbol();
  31753. const componentTypeMap = /* @__PURE__ */ new WeakMap();
  31754. const ssrTransformComponent = (node, context) => {
  31755. if (node.type !== 1 || node.tagType !== 1) {
  31756. return;
  31757. }
  31758. const component = resolveComponentType(
  31759. node,
  31760. context,
  31761. true
  31762. /* ssr */
  31763. );
  31764. const isDynamicComponent = isObject$2(component) && component.callee === RESOLVE_DYNAMIC_COMPONENT;
  31765. componentTypeMap.set(node, component);
  31766. if (isSymbol$1(component)) {
  31767. if (component === SUSPENSE) {
  31768. return ssrTransformSuspense(node, context);
  31769. } else if (component === TRANSITION_GROUP) {
  31770. return ssrTransformTransitionGroup(node, context);
  31771. } else if (component === TRANSITION) {
  31772. return ssrTransformTransition(node);
  31773. }
  31774. return;
  31775. }
  31776. const vnodeBranches = [];
  31777. const clonedNode = clone(node);
  31778. return function ssrPostTransformComponent() {
  31779. if (clonedNode.children.length) {
  31780. buildSlots(clonedNode, context, (props, vFor, children) => {
  31781. vnodeBranches.push(
  31782. createVNodeSlotBranch(props, vFor, children, context)
  31783. );
  31784. return createFunctionExpression(void 0);
  31785. });
  31786. }
  31787. let propsExp = `null`;
  31788. if (node.props.length) {
  31789. const { props, directives } = buildProps(
  31790. node,
  31791. context,
  31792. void 0,
  31793. true,
  31794. isDynamicComponent
  31795. );
  31796. if (props || directives.length) {
  31797. propsExp = buildSSRProps(props, directives, context);
  31798. }
  31799. }
  31800. const wipEntries = [];
  31801. wipMap.set(node, wipEntries);
  31802. const buildSSRSlotFn = (props, _vForExp, children, loc) => {
  31803. const param0 = props && stringifyExpression(props) || `_`;
  31804. const fn = createFunctionExpression(
  31805. [param0, `_push`, `_parent`, `_scopeId`],
  31806. void 0,
  31807. // no return, assign body later
  31808. true,
  31809. // newline
  31810. true,
  31811. // isSlot
  31812. loc
  31813. );
  31814. wipEntries.push({
  31815. type: WIP_SLOT,
  31816. fn,
  31817. children,
  31818. // also collect the corresponding vnode branch built earlier
  31819. vnodeBranch: vnodeBranches[wipEntries.length]
  31820. });
  31821. return fn;
  31822. };
  31823. const slots = node.children.length ? buildSlots(node, context, buildSSRSlotFn).slots : `null`;
  31824. if (typeof component !== "string") {
  31825. node.ssrCodegenNode = createCallExpression(
  31826. context.helper(SSR_RENDER_VNODE),
  31827. [
  31828. `_push`,
  31829. createCallExpression(context.helper(CREATE_VNODE), [
  31830. component,
  31831. propsExp,
  31832. slots
  31833. ]),
  31834. `_parent`
  31835. ]
  31836. );
  31837. } else {
  31838. node.ssrCodegenNode = createCallExpression(
  31839. context.helper(SSR_RENDER_COMPONENT),
  31840. [component, propsExp, slots, `_parent`]
  31841. );
  31842. }
  31843. };
  31844. };
  31845. function ssrProcessComponent(node, context, parent) {
  31846. const component = componentTypeMap.get(node);
  31847. if (!node.ssrCodegenNode) {
  31848. if (component === TELEPORT) {
  31849. return ssrProcessTeleport(node, context);
  31850. } else if (component === SUSPENSE) {
  31851. return ssrProcessSuspense(node, context);
  31852. } else if (component === TRANSITION_GROUP) {
  31853. return ssrProcessTransitionGroup(node, context);
  31854. } else {
  31855. if (parent.type === WIP_SLOT) {
  31856. context.pushStringPart(``);
  31857. }
  31858. if (component === TRANSITION) {
  31859. return ssrProcessTransition(node, context);
  31860. }
  31861. processChildren(node, context);
  31862. }
  31863. } else {
  31864. const wipEntries = wipMap.get(node) || [];
  31865. for (let i = 0; i < wipEntries.length; i++) {
  31866. const { fn, vnodeBranch } = wipEntries[i];
  31867. fn.body = createIfStatement(
  31868. createSimpleExpression(`_push`, false),
  31869. processChildrenAsStatement(
  31870. wipEntries[i],
  31871. context,
  31872. false,
  31873. true
  31874. ),
  31875. vnodeBranch
  31876. );
  31877. }
  31878. if (context.withSlotScopeId) {
  31879. node.ssrCodegenNode.arguments.push(`_scopeId`);
  31880. }
  31881. if (typeof component === "string") {
  31882. context.pushStatement(
  31883. createCallExpression(`_push`, [node.ssrCodegenNode])
  31884. );
  31885. } else {
  31886. context.pushStatement(node.ssrCodegenNode);
  31887. }
  31888. }
  31889. }
  31890. const rawOptionsMap = /* @__PURE__ */ new WeakMap();
  31891. const [baseNodeTransforms, baseDirectiveTransforms] = getBaseTransformPreset(true);
  31892. const vnodeNodeTransforms = [...baseNodeTransforms, ...DOMNodeTransforms];
  31893. const vnodeDirectiveTransforms = __spreadValues$8(__spreadValues$8({}, baseDirectiveTransforms), DOMDirectiveTransforms);
  31894. function createVNodeSlotBranch(slotProps, vFor, children, parentContext) {
  31895. const rawOptions = rawOptionsMap.get(parentContext.root);
  31896. const subOptions = __spreadProps$7(__spreadValues$8({}, rawOptions), {
  31897. // overwrite with vnode-based transforms
  31898. nodeTransforms: [
  31899. ...vnodeNodeTransforms,
  31900. ...rawOptions.nodeTransforms || []
  31901. ],
  31902. directiveTransforms: __spreadValues$8(__spreadValues$8({}, vnodeDirectiveTransforms), rawOptions.directiveTransforms || {})
  31903. });
  31904. const wrapperProps = [];
  31905. if (slotProps) {
  31906. wrapperProps.push({
  31907. type: 7,
  31908. name: "slot",
  31909. exp: slotProps,
  31910. arg: void 0,
  31911. modifiers: [],
  31912. loc: locStub
  31913. });
  31914. }
  31915. if (vFor) {
  31916. wrapperProps.push(extend({}, vFor));
  31917. }
  31918. const wrapperNode = {
  31919. type: 1,
  31920. ns: 0,
  31921. tag: "template",
  31922. tagType: 3,
  31923. props: wrapperProps,
  31924. children,
  31925. loc: locStub,
  31926. codegenNode: void 0
  31927. };
  31928. subTransform(wrapperNode, subOptions, parentContext);
  31929. return createReturnStatement(children);
  31930. }
  31931. function subTransform(node, options, parentContext) {
  31932. const childRoot = createRoot([node]);
  31933. const childContext = createTransformContext(childRoot, options);
  31934. childContext.ssr = false;
  31935. childContext.scopes = __spreadValues$8({}, parentContext.scopes);
  31936. childContext.identifiers = __spreadValues$8({}, parentContext.identifiers);
  31937. childContext.imports = parentContext.imports;
  31938. traverseNode(childRoot, childContext);
  31939. ["helpers", "components", "directives"].forEach((key) => {
  31940. childContext[key].forEach((value, helperKey) => {
  31941. if (key === "helpers") {
  31942. const parentCount = parentContext.helpers.get(helperKey);
  31943. if (parentCount === void 0) {
  31944. parentContext.helpers.set(helperKey, value);
  31945. } else {
  31946. parentContext.helpers.set(helperKey, value + parentCount);
  31947. }
  31948. } else {
  31949. parentContext[key].add(value);
  31950. }
  31951. });
  31952. });
  31953. }
  31954. function clone(v) {
  31955. if (isArray$3(v)) {
  31956. return v.map(clone);
  31957. } else if (isPlainObject(v)) {
  31958. const res = {};
  31959. for (const key in v) {
  31960. res[key] = clone(v[key]);
  31961. }
  31962. return res;
  31963. } else {
  31964. return v;
  31965. }
  31966. }
  31967. function ssrCodegenTransform(ast, options) {
  31968. const context = createSSRTransformContext(ast, options);
  31969. if (options.ssrCssVars) {
  31970. const cssContext = createTransformContext(createRoot([]), options);
  31971. const varsExp = processExpression(
  31972. createSimpleExpression(options.ssrCssVars, false),
  31973. cssContext
  31974. );
  31975. context.body.push(
  31976. createCompoundExpression([`const _cssVars = { style: `, varsExp, `}`])
  31977. );
  31978. Array.from(cssContext.helpers.keys()).forEach((helper) => {
  31979. ast.helpers.add(helper);
  31980. });
  31981. }
  31982. const isFragment = ast.children.length > 1 && ast.children.some((c) => !isText$1(c));
  31983. processChildren(ast, context, isFragment);
  31984. ast.codegenNode = createBlockStatement(context.body);
  31985. ast.ssrHelpers = Array.from(
  31986. /* @__PURE__ */ new Set([
  31987. ...Array.from(ast.helpers).filter((h) => h in ssrHelpers),
  31988. ...context.helpers
  31989. ])
  31990. );
  31991. ast.helpers = new Set(Array.from(ast.helpers).filter((h) => !(h in ssrHelpers)));
  31992. }
  31993. function createSSRTransformContext(root, options, helpers = /* @__PURE__ */ new Set(), withSlotScopeId = false) {
  31994. const body = [];
  31995. let currentString = null;
  31996. return {
  31997. root,
  31998. options,
  31999. body,
  32000. helpers,
  32001. withSlotScopeId,
  32002. onError: options.onError || ((e) => {
  32003. throw e;
  32004. }),
  32005. helper(name) {
  32006. helpers.add(name);
  32007. return name;
  32008. },
  32009. pushStringPart(part) {
  32010. if (!currentString) {
  32011. const currentCall = createCallExpression(`_push`);
  32012. body.push(currentCall);
  32013. currentString = createTemplateLiteral([]);
  32014. currentCall.arguments.push(currentString);
  32015. }
  32016. const bufferedElements = currentString.elements;
  32017. const lastItem = bufferedElements[bufferedElements.length - 1];
  32018. if (isString$1(part) && isString$1(lastItem)) {
  32019. bufferedElements[bufferedElements.length - 1] += part;
  32020. } else {
  32021. bufferedElements.push(part);
  32022. }
  32023. },
  32024. pushStatement(statement) {
  32025. currentString = null;
  32026. body.push(statement);
  32027. }
  32028. };
  32029. }
  32030. function createChildContext(parent, withSlotScopeId = parent.withSlotScopeId) {
  32031. return createSSRTransformContext(
  32032. parent.root,
  32033. parent.options,
  32034. parent.helpers,
  32035. withSlotScopeId
  32036. );
  32037. }
  32038. function processChildren(parent, context, asFragment = false, disableNestedFragments = false, disableComment = false) {
  32039. if (asFragment) {
  32040. context.pushStringPart(`<!--[-->`);
  32041. }
  32042. const { children } = parent;
  32043. for (let i = 0; i < children.length; i++) {
  32044. const child = children[i];
  32045. switch (child.type) {
  32046. case 1:
  32047. switch (child.tagType) {
  32048. case 0:
  32049. ssrProcessElement(child, context);
  32050. break;
  32051. case 1:
  32052. ssrProcessComponent(child, context, parent);
  32053. break;
  32054. case 2:
  32055. ssrProcessSlotOutlet(child, context);
  32056. break;
  32057. case 3:
  32058. break;
  32059. default:
  32060. context.onError(
  32061. createSSRCompilerError(
  32062. 67,
  32063. child.loc
  32064. )
  32065. );
  32066. const exhaustiveCheck2 = child;
  32067. return exhaustiveCheck2;
  32068. }
  32069. break;
  32070. case 2:
  32071. context.pushStringPart(escapeHtml(child.content));
  32072. break;
  32073. case 3:
  32074. if (!disableComment) {
  32075. context.pushStringPart(`<!--${child.content}-->`);
  32076. }
  32077. break;
  32078. case 5:
  32079. context.pushStringPart(
  32080. createCallExpression(context.helper(SSR_INTERPOLATE), [
  32081. child.content
  32082. ])
  32083. );
  32084. break;
  32085. case 9:
  32086. ssrProcessIf(child, context, disableNestedFragments, disableComment);
  32087. break;
  32088. case 11:
  32089. ssrProcessFor(child, context, disableNestedFragments);
  32090. break;
  32091. case 10:
  32092. break;
  32093. case 12:
  32094. case 8:
  32095. break;
  32096. default:
  32097. context.onError(
  32098. createSSRCompilerError(
  32099. 67,
  32100. child.loc
  32101. )
  32102. );
  32103. const exhaustiveCheck = child;
  32104. return exhaustiveCheck;
  32105. }
  32106. }
  32107. if (asFragment) {
  32108. context.pushStringPart(`<!--]-->`);
  32109. }
  32110. }
  32111. function processChildrenAsStatement(parent, parentContext, asFragment = false, withSlotScopeId = parentContext.withSlotScopeId) {
  32112. const childContext = createChildContext(parentContext, withSlotScopeId);
  32113. processChildren(parent, childContext, asFragment);
  32114. return createBlockStatement(childContext.body);
  32115. }
  32116. const ssrTransformModel = (dir, node, context) => {
  32117. const model = dir.exp;
  32118. function checkDuplicatedValue() {
  32119. const value = findProp(node, "value");
  32120. if (value) {
  32121. context.onError(
  32122. createDOMCompilerError(
  32123. 61,
  32124. value.loc
  32125. )
  32126. );
  32127. }
  32128. }
  32129. const processSelectChildren = (children) => {
  32130. children.forEach((child) => {
  32131. if (child.type === 1) {
  32132. processOption(child);
  32133. } else if (child.type === 11) {
  32134. processSelectChildren(child.children);
  32135. } else if (child.type === 9) {
  32136. child.branches.forEach((b) => processSelectChildren(b.children));
  32137. }
  32138. });
  32139. };
  32140. function processOption(plainNode) {
  32141. if (plainNode.tag === "option") {
  32142. if (plainNode.props.findIndex((p) => p.name === "selected") === -1) {
  32143. const value = findValueBinding(plainNode);
  32144. plainNode.ssrCodegenNode.elements.push(
  32145. createConditionalExpression(
  32146. createCallExpression(context.helper(SSR_INCLUDE_BOOLEAN_ATTR), [
  32147. createConditionalExpression(
  32148. createCallExpression(`Array.isArray`, [model]),
  32149. createCallExpression(context.helper(SSR_LOOSE_CONTAIN), [
  32150. model,
  32151. value
  32152. ]),
  32153. createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
  32154. model,
  32155. value
  32156. ])
  32157. )
  32158. ]),
  32159. createSimpleExpression(" selected", true),
  32160. createSimpleExpression("", true),
  32161. false
  32162. )
  32163. );
  32164. }
  32165. } else if (plainNode.tag === "optgroup") {
  32166. processSelectChildren(plainNode.children);
  32167. }
  32168. }
  32169. if (node.tagType === 0) {
  32170. const res = { props: [] };
  32171. if (node.tag === "input") {
  32172. const defaultProps = [
  32173. // default value binding for text type inputs
  32174. createObjectProperty(`value`, model)
  32175. ];
  32176. const type = findProp(node, "type");
  32177. if (type) {
  32178. const value = findValueBinding(node);
  32179. if (type.type === 7) {
  32180. res.ssrTagParts = [
  32181. createCallExpression(context.helper(SSR_RENDER_DYNAMIC_MODEL), [
  32182. type.exp,
  32183. model,
  32184. value
  32185. ])
  32186. ];
  32187. } else if (type.value) {
  32188. switch (type.value.content) {
  32189. case "radio":
  32190. res.props = [
  32191. createObjectProperty(
  32192. `checked`,
  32193. createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
  32194. model,
  32195. value
  32196. ])
  32197. )
  32198. ];
  32199. break;
  32200. case "checkbox":
  32201. const trueValueBinding = findProp(node, "true-value");
  32202. if (trueValueBinding) {
  32203. const trueValue = trueValueBinding.type === 6 ? JSON.stringify(trueValueBinding.value.content) : trueValueBinding.exp;
  32204. res.props = [
  32205. createObjectProperty(
  32206. `checked`,
  32207. createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
  32208. model,
  32209. trueValue
  32210. ])
  32211. )
  32212. ];
  32213. } else {
  32214. res.props = [
  32215. createObjectProperty(
  32216. `checked`,
  32217. createConditionalExpression(
  32218. createCallExpression(`Array.isArray`, [model]),
  32219. createCallExpression(context.helper(SSR_LOOSE_CONTAIN), [
  32220. model,
  32221. value
  32222. ]),
  32223. model
  32224. )
  32225. )
  32226. ];
  32227. }
  32228. break;
  32229. case "file":
  32230. context.onError(
  32231. createDOMCompilerError(
  32232. 60,
  32233. dir.loc
  32234. )
  32235. );
  32236. break;
  32237. default:
  32238. checkDuplicatedValue();
  32239. res.props = defaultProps;
  32240. break;
  32241. }
  32242. }
  32243. } else if (hasDynamicKeyVBind(node)) ; else {
  32244. checkDuplicatedValue();
  32245. res.props = defaultProps;
  32246. }
  32247. } else if (node.tag === "textarea") {
  32248. checkDuplicatedValue();
  32249. node.children = [createInterpolation(model, model.loc)];
  32250. } else if (node.tag === "select") {
  32251. processSelectChildren(node.children);
  32252. } else {
  32253. context.onError(
  32254. createDOMCompilerError(
  32255. 58,
  32256. dir.loc
  32257. )
  32258. );
  32259. }
  32260. return res;
  32261. } else {
  32262. return transformModel$1(dir, node, context);
  32263. }
  32264. };
  32265. function findValueBinding(node) {
  32266. const valueBinding = findProp(node, "value");
  32267. return valueBinding ? valueBinding.type === 7 ? valueBinding.exp : createSimpleExpression(valueBinding.value.content, true) : createSimpleExpression(`null`, false);
  32268. }
  32269. const ssrTransformShow = (dir, node, context) => {
  32270. if (!dir.exp) {
  32271. context.onError(
  32272. createDOMCompilerError(62)
  32273. );
  32274. }
  32275. return {
  32276. props: [
  32277. createObjectProperty(
  32278. `style`,
  32279. createConditionalExpression(
  32280. dir.exp,
  32281. createSimpleExpression(`null`, false),
  32282. createObjectExpression([
  32283. createObjectProperty(
  32284. `display`,
  32285. createSimpleExpression(`none`, true)
  32286. )
  32287. ]),
  32288. false
  32289. )
  32290. )
  32291. ]
  32292. };
  32293. };
  32294. const filterChild = (node) => node.children.filter((n) => !isCommentOrWhitespace(n));
  32295. const hasSingleChild = (node) => filterChild(node).length === 1;
  32296. const ssrInjectFallthroughAttrs = (node, context) => {
  32297. if (node.type === 0) {
  32298. context.identifiers._attrs = 1;
  32299. }
  32300. if (node.type === 1 && node.tagType === 1 && (node.tag === "transition" || node.tag === "Transition" || node.tag === "KeepAlive" || node.tag === "keep-alive")) {
  32301. const rootChildren = filterChild(context.root);
  32302. if (rootChildren.length === 1 && rootChildren[0] === node) {
  32303. if (hasSingleChild(node)) {
  32304. injectFallthroughAttrs(node.children[0]);
  32305. }
  32306. return;
  32307. }
  32308. }
  32309. const parent = context.parent;
  32310. if (!parent || parent.type !== 0) {
  32311. return;
  32312. }
  32313. if (node.type === 10 && hasSingleChild(node)) {
  32314. let hasEncounteredIf = false;
  32315. for (const c of filterChild(parent)) {
  32316. if (c.type === 9 || c.type === 1 && findDir(c, "if")) {
  32317. if (hasEncounteredIf) return;
  32318. hasEncounteredIf = true;
  32319. } else if (
  32320. // node before v-if
  32321. !hasEncounteredIf || // non else nodes
  32322. !(c.type === 1 && findDir(c, /else/, true))
  32323. ) {
  32324. return;
  32325. }
  32326. }
  32327. injectFallthroughAttrs(node.children[0]);
  32328. } else if (hasSingleChild(parent)) {
  32329. injectFallthroughAttrs(node);
  32330. }
  32331. };
  32332. function injectFallthroughAttrs(node) {
  32333. if (node.type === 1 && (node.tagType === 0 || node.tagType === 1) && !findDir(node, "for")) {
  32334. node.props.push({
  32335. type: 7,
  32336. name: "bind",
  32337. arg: void 0,
  32338. exp: createSimpleExpression(`_attrs`, false),
  32339. modifiers: [],
  32340. loc: locStub
  32341. });
  32342. }
  32343. }
  32344. const ssrInjectCssVars = (node, context) => {
  32345. if (!context.ssrCssVars) {
  32346. return;
  32347. }
  32348. if (node.type === 0) {
  32349. context.identifiers._cssVars = 1;
  32350. }
  32351. const parent = context.parent;
  32352. if (!parent || parent.type !== 0) {
  32353. return;
  32354. }
  32355. if (node.type === 10) {
  32356. for (const child of node.children) {
  32357. injectCssVars(child);
  32358. }
  32359. } else {
  32360. injectCssVars(node);
  32361. }
  32362. };
  32363. function injectCssVars(node) {
  32364. if (node.type === 1 && (node.tagType === 0 || node.tagType === 1) && !findDir(node, "for")) {
  32365. if (node.tag === "suspense" || node.tag === "Suspense") {
  32366. for (const child of node.children) {
  32367. if (child.type === 1 && child.tagType === 3) {
  32368. child.children.forEach(injectCssVars);
  32369. } else {
  32370. injectCssVars(child);
  32371. }
  32372. }
  32373. } else {
  32374. node.props.push({
  32375. type: 7,
  32376. name: "bind",
  32377. arg: void 0,
  32378. exp: createSimpleExpression(`_cssVars`, false),
  32379. modifiers: [],
  32380. loc: locStub
  32381. });
  32382. }
  32383. }
  32384. }
  32385. var __defProp$7 = Object.defineProperty;
  32386. var __defProps$6 = Object.defineProperties;
  32387. var __getOwnPropDescs$6 = Object.getOwnPropertyDescriptors;
  32388. var __getOwnPropSymbols$7 = Object.getOwnPropertySymbols;
  32389. var __hasOwnProp$7 = Object.prototype.hasOwnProperty;
  32390. var __propIsEnum$7 = Object.prototype.propertyIsEnumerable;
  32391. var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  32392. var __spreadValues$7 = (a, b) => {
  32393. for (var prop in b || (b = {}))
  32394. if (__hasOwnProp$7.call(b, prop))
  32395. __defNormalProp$7(a, prop, b[prop]);
  32396. if (__getOwnPropSymbols$7)
  32397. for (var prop of __getOwnPropSymbols$7(b)) {
  32398. if (__propIsEnum$7.call(b, prop))
  32399. __defNormalProp$7(a, prop, b[prop]);
  32400. }
  32401. return a;
  32402. };
  32403. var __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b));
  32404. function compile(source, options = {}) {
  32405. options = __spreadProps$6(__spreadValues$7(__spreadValues$7({}, options), parserOptions), {
  32406. ssr: true,
  32407. inSSR: true,
  32408. scopeId: options.mode === "function" ? null : options.scopeId,
  32409. // always prefix since compiler-ssr doesn't have size concern
  32410. prefixIdentifiers: true,
  32411. // disable optimizations that are unnecessary for ssr
  32412. cacheHandlers: false,
  32413. hoistStatic: false
  32414. });
  32415. const ast = typeof source === "string" ? baseParse(source, options) : source;
  32416. rawOptionsMap.set(ast, options);
  32417. transform(ast, __spreadProps$6(__spreadValues$7({}, options), {
  32418. hoistStatic: false,
  32419. nodeTransforms: [
  32420. transformVBindShorthand,
  32421. ssrTransformIf,
  32422. ssrTransformFor,
  32423. trackVForSlotScopes,
  32424. transformExpression,
  32425. ssrTransformSlotOutlet,
  32426. ssrInjectFallthroughAttrs,
  32427. ssrInjectCssVars,
  32428. ssrTransformElement,
  32429. ssrTransformComponent,
  32430. trackSlotScopes,
  32431. transformStyle,
  32432. ...options.nodeTransforms || []
  32433. // user transforms
  32434. ],
  32435. directiveTransforms: __spreadValues$7({
  32436. // reusing core v-bind
  32437. bind: transformBind,
  32438. on: transformOn$1,
  32439. // model and show have dedicated SSR handling
  32440. model: ssrTransformModel,
  32441. show: ssrTransformShow,
  32442. // the following are ignored during SSR
  32443. // on: noopDirectiveTransform,
  32444. cloak: noopDirectiveTransform,
  32445. once: noopDirectiveTransform,
  32446. memo: noopDirectiveTransform
  32447. }, options.directiveTransforms || {})
  32448. }));
  32449. ssrCodegenTransform(ast, options);
  32450. return generate(ast, options);
  32451. }
  32452. var CompilerSSR = /*#__PURE__*/Object.freeze({
  32453. __proto__: null,
  32454. compile: compile
  32455. });
  32456. var _polyfillNode_fs = {};
  32457. var _polyfillNode_fs$1 = /*#__PURE__*/Object.freeze({
  32458. __proto__: null,
  32459. default: _polyfillNode_fs
  32460. });
  32461. var require$$0$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_fs$1);
  32462. var require$$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_path);
  32463. var require$$0 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_util$1);
  32464. const hasWarned = {};
  32465. function warnOnce$1(msg) {
  32466. const isNodeProd = typeof process !== "undefined" && process.env.NODE_ENV === "production";
  32467. if (!isNodeProd && true && !hasWarned[msg]) {
  32468. hasWarned[msg] = true;
  32469. warn(msg);
  32470. }
  32471. }
  32472. function warn(msg) {
  32473. console.warn(
  32474. `\x1B[1m\x1B[33m[@vue/compiler-sfc]\x1B[0m\x1B[33m ${msg}\x1B[0m
  32475. `
  32476. );
  32477. }
  32478. var __defProp$6 = Object.defineProperty;
  32479. var __defProps$5 = Object.defineProperties;
  32480. var __getOwnPropDescs$5 = Object.getOwnPropertyDescriptors;
  32481. var __getOwnPropSymbols$6 = Object.getOwnPropertySymbols;
  32482. var __hasOwnProp$6 = Object.prototype.hasOwnProperty;
  32483. var __propIsEnum$6 = Object.prototype.propertyIsEnumerable;
  32484. var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  32485. var __spreadValues$6 = (a, b) => {
  32486. for (var prop in b || (b = {}))
  32487. if (__hasOwnProp$6.call(b, prop))
  32488. __defNormalProp$6(a, prop, b[prop]);
  32489. if (__getOwnPropSymbols$6)
  32490. for (var prop of __getOwnPropSymbols$6(b)) {
  32491. if (__propIsEnum$6.call(b, prop))
  32492. __defNormalProp$6(a, prop, b[prop]);
  32493. }
  32494. return a;
  32495. };
  32496. var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
  32497. function preprocess$1({ source, filename, preprocessOptions }, preprocessor) {
  32498. let res = "";
  32499. let err = null;
  32500. preprocessor.render(
  32501. source,
  32502. __spreadValues$6({ filename }, preprocessOptions),
  32503. (_err, _res) => {
  32504. if (_err) err = _err;
  32505. res = _res;
  32506. }
  32507. );
  32508. if (err) throw err;
  32509. return res;
  32510. }
  32511. function compileTemplate(options) {
  32512. const { preprocessLang, preprocessCustomRequire } = options;
  32513. if (preprocessLang && !preprocessCustomRequire) {
  32514. throw new Error(
  32515. `[@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 }.`
  32516. );
  32517. }
  32518. const preprocessor = preprocessLang ? preprocessCustomRequire ? preprocessCustomRequire(preprocessLang) : void 0 : false;
  32519. if (preprocessor) {
  32520. try {
  32521. return doCompileTemplate(__spreadProps$5(__spreadValues$6({}, options), {
  32522. source: preprocess$1(options, preprocessor),
  32523. ast: void 0
  32524. // invalidate AST if template goes through preprocessor
  32525. }));
  32526. } catch (e) {
  32527. return {
  32528. code: `export default function render() {}`,
  32529. source: options.source,
  32530. tips: [],
  32531. errors: [e]
  32532. };
  32533. }
  32534. } else if (preprocessLang) {
  32535. return {
  32536. code: `export default function render() {}`,
  32537. source: options.source,
  32538. tips: [
  32539. `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
  32540. ],
  32541. errors: [
  32542. `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
  32543. ]
  32544. };
  32545. } else {
  32546. return doCompileTemplate(options);
  32547. }
  32548. }
  32549. function doCompileTemplate({
  32550. filename,
  32551. id,
  32552. scoped,
  32553. slotted,
  32554. inMap,
  32555. source,
  32556. ast: inAST,
  32557. ssr = false,
  32558. ssrCssVars,
  32559. isProd = false,
  32560. compiler,
  32561. compilerOptions = {},
  32562. transformAssetUrls
  32563. }) {
  32564. const errors = [];
  32565. const warnings = [];
  32566. let nodeTransforms = [];
  32567. if (isObject$2(transformAssetUrls)) {
  32568. const assetOptions = normalizeOptions(transformAssetUrls);
  32569. nodeTransforms = [
  32570. createAssetUrlTransformWithOptions(assetOptions),
  32571. createSrcsetTransformWithOptions(assetOptions)
  32572. ];
  32573. } else if (transformAssetUrls !== false) {
  32574. nodeTransforms = [transformAssetUrl, transformSrcset];
  32575. }
  32576. if (ssr && !ssrCssVars) {
  32577. warnOnce$1(
  32578. `compileTemplate is called with \`ssr: true\` but no corresponding \`cssVars\` option.`
  32579. );
  32580. }
  32581. if (!id) {
  32582. warnOnce$1(`compileTemplate now requires the \`id\` option.`);
  32583. id = "";
  32584. }
  32585. const shortId = id.replace(/^data-v-/, "");
  32586. const longId = `data-v-${shortId}`;
  32587. const defaultCompiler = ssr ? CompilerSSR : CompilerDOM;
  32588. compiler = compiler || defaultCompiler;
  32589. if (compiler !== defaultCompiler) {
  32590. inAST = void 0;
  32591. }
  32592. inAST = resolveTemplateAST(inAST, {
  32593. compiler,
  32594. compilerOptions,
  32595. ssr,
  32596. onError: (e) => errors.push(e)
  32597. });
  32598. let { code, ast, preamble, map } = compiler.compile(inAST || source, __spreadProps$5(__spreadValues$6({
  32599. mode: "module",
  32600. prefixIdentifiers: true,
  32601. hoistStatic: true,
  32602. cacheHandlers: true,
  32603. ssrCssVars: ssr && ssrCssVars && ssrCssVars.length ? genCssVarsFromList(ssrCssVars, shortId, isProd, true) : "",
  32604. scopeId: scoped ? longId : void 0,
  32605. slotted,
  32606. sourceMap: true
  32607. }, compilerOptions), {
  32608. hmr: !isProd,
  32609. nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []),
  32610. filename,
  32611. onError: (e) => errors.push(e),
  32612. onWarn: (w) => warnings.push(w)
  32613. }));
  32614. if (inMap && !inAST) {
  32615. if (map) {
  32616. map = mapLines(inMap, map);
  32617. }
  32618. if (errors.length) {
  32619. patchErrors(errors, source, inMap);
  32620. }
  32621. }
  32622. const tips = warnings.map((w) => {
  32623. let msg = w.message;
  32624. if (w.loc) {
  32625. msg += `
  32626. ${generateCodeFrame(
  32627. (inAST == null ? void 0 : inAST.source) || source,
  32628. w.loc.start.offset,
  32629. w.loc.end.offset
  32630. )}`;
  32631. }
  32632. return msg;
  32633. });
  32634. return { code, ast, preamble, source, errors, tips, map };
  32635. }
  32636. function mapLines(oldMap, newMap) {
  32637. if (!oldMap) return newMap;
  32638. if (!newMap) return oldMap;
  32639. const oldMapConsumer = new sourceMapExports.SourceMapConsumer(oldMap);
  32640. const newMapConsumer = new sourceMapExports.SourceMapConsumer(newMap);
  32641. const mergedMapGenerator = new sourceMapExports.SourceMapGenerator();
  32642. newMapConsumer.eachMapping((m) => {
  32643. if (m.originalLine == null) {
  32644. return;
  32645. }
  32646. const origPosInOldMap = oldMapConsumer.originalPositionFor({
  32647. line: m.originalLine,
  32648. column: m.originalColumn
  32649. });
  32650. if (origPosInOldMap.source == null) {
  32651. return;
  32652. }
  32653. mergedMapGenerator.addMapping({
  32654. generated: {
  32655. line: m.generatedLine,
  32656. column: m.generatedColumn
  32657. },
  32658. original: {
  32659. line: origPosInOldMap.line,
  32660. // map line
  32661. // use current column, since the oldMap produced by @vue/compiler-sfc
  32662. // does not
  32663. column: m.originalColumn
  32664. },
  32665. source: origPosInOldMap.source,
  32666. name: origPosInOldMap.name
  32667. });
  32668. });
  32669. const generator = mergedMapGenerator;
  32670. oldMapConsumer.sources.forEach((sourceFile) => {
  32671. generator._sources.add(sourceFile);
  32672. const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
  32673. if (sourceContent != null) {
  32674. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  32675. }
  32676. });
  32677. generator._sourceRoot = oldMap.sourceRoot;
  32678. generator._file = oldMap.file;
  32679. return generator.toJSON();
  32680. }
  32681. function patchErrors(errors, source, inMap) {
  32682. const originalSource = inMap.sourcesContent[0];
  32683. const offset = originalSource.indexOf(source);
  32684. const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
  32685. errors.forEach((err) => {
  32686. if (err.loc) {
  32687. err.loc.start.line += lineOffset;
  32688. err.loc.start.offset += offset;
  32689. if (err.loc.end !== err.loc.start) {
  32690. err.loc.end.line += lineOffset;
  32691. err.loc.end.offset += offset;
  32692. }
  32693. }
  32694. });
  32695. }
  32696. var picocolors = {exports: {}};
  32697. var hasRequiredPicocolors;
  32698. function requirePicocolors () {
  32699. if (hasRequiredPicocolors) return picocolors.exports;
  32700. hasRequiredPicocolors = 1;
  32701. let p = browser$1 || {}, argv = p.argv || [], env = p.env || {};
  32702. let isColorSupported =
  32703. !(!!env.NO_COLOR || argv.includes("--no-color")) &&
  32704. (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI);
  32705. let formatter = (open, close, replace = open) =>
  32706. input => {
  32707. let string = "" + input, index = string.indexOf(close, open.length);
  32708. return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close
  32709. };
  32710. let replaceClose = (string, close, replace, index) => {
  32711. let result = "", cursor = 0;
  32712. do {
  32713. result += string.substring(cursor, index) + replace;
  32714. cursor = index + close.length;
  32715. index = string.indexOf(close, cursor);
  32716. } while (~index)
  32717. return result + string.substring(cursor)
  32718. };
  32719. let createColors = (enabled = isColorSupported) => {
  32720. let f = enabled ? formatter : () => String;
  32721. return {
  32722. isColorSupported: enabled,
  32723. reset: f("\x1b[0m", "\x1b[0m"),
  32724. bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
  32725. dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
  32726. italic: f("\x1b[3m", "\x1b[23m"),
  32727. underline: f("\x1b[4m", "\x1b[24m"),
  32728. inverse: f("\x1b[7m", "\x1b[27m"),
  32729. hidden: f("\x1b[8m", "\x1b[28m"),
  32730. strikethrough: f("\x1b[9m", "\x1b[29m"),
  32731. black: f("\x1b[30m", "\x1b[39m"),
  32732. red: f("\x1b[31m", "\x1b[39m"),
  32733. green: f("\x1b[32m", "\x1b[39m"),
  32734. yellow: f("\x1b[33m", "\x1b[39m"),
  32735. blue: f("\x1b[34m", "\x1b[39m"),
  32736. magenta: f("\x1b[35m", "\x1b[39m"),
  32737. cyan: f("\x1b[36m", "\x1b[39m"),
  32738. white: f("\x1b[37m", "\x1b[39m"),
  32739. gray: f("\x1b[90m", "\x1b[39m"),
  32740. bgBlack: f("\x1b[40m", "\x1b[49m"),
  32741. bgRed: f("\x1b[41m", "\x1b[49m"),
  32742. bgGreen: f("\x1b[42m", "\x1b[49m"),
  32743. bgYellow: f("\x1b[43m", "\x1b[49m"),
  32744. bgBlue: f("\x1b[44m", "\x1b[49m"),
  32745. bgMagenta: f("\x1b[45m", "\x1b[49m"),
  32746. bgCyan: f("\x1b[46m", "\x1b[49m"),
  32747. bgWhite: f("\x1b[47m", "\x1b[49m"),
  32748. blackBright: f("\x1b[90m", "\x1b[39m"),
  32749. redBright: f("\x1b[91m", "\x1b[39m"),
  32750. greenBright: f("\x1b[92m", "\x1b[39m"),
  32751. yellowBright: f("\x1b[93m", "\x1b[39m"),
  32752. blueBright: f("\x1b[94m", "\x1b[39m"),
  32753. magentaBright: f("\x1b[95m", "\x1b[39m"),
  32754. cyanBright: f("\x1b[96m", "\x1b[39m"),
  32755. whiteBright: f("\x1b[97m", "\x1b[39m"),
  32756. bgBlackBright: f("\x1b[100m", "\x1b[49m"),
  32757. bgRedBright: f("\x1b[101m", "\x1b[49m"),
  32758. bgGreenBright: f("\x1b[102m", "\x1b[49m"),
  32759. bgYellowBright: f("\x1b[103m", "\x1b[49m"),
  32760. bgBlueBright: f("\x1b[104m", "\x1b[49m"),
  32761. bgMagentaBright: f("\x1b[105m", "\x1b[49m"),
  32762. bgCyanBright: f("\x1b[106m", "\x1b[49m"),
  32763. bgWhiteBright: f("\x1b[107m", "\x1b[49m"),
  32764. }
  32765. };
  32766. picocolors.exports = createColors();
  32767. picocolors.exports.createColors = createColors;
  32768. return picocolors.exports;
  32769. }
  32770. var tokenize$1;
  32771. var hasRequiredTokenize$1;
  32772. function requireTokenize$1 () {
  32773. if (hasRequiredTokenize$1) return tokenize$1;
  32774. hasRequiredTokenize$1 = 1;
  32775. const SINGLE_QUOTE = "'".charCodeAt(0);
  32776. const DOUBLE_QUOTE = '"'.charCodeAt(0);
  32777. const BACKSLASH = '\\'.charCodeAt(0);
  32778. const SLASH = '/'.charCodeAt(0);
  32779. const NEWLINE = '\n'.charCodeAt(0);
  32780. const SPACE = ' '.charCodeAt(0);
  32781. const FEED = '\f'.charCodeAt(0);
  32782. const TAB = '\t'.charCodeAt(0);
  32783. const CR = '\r'.charCodeAt(0);
  32784. const OPEN_SQUARE = '['.charCodeAt(0);
  32785. const CLOSE_SQUARE = ']'.charCodeAt(0);
  32786. const OPEN_PARENTHESES = '('.charCodeAt(0);
  32787. const CLOSE_PARENTHESES = ')'.charCodeAt(0);
  32788. const OPEN_CURLY = '{'.charCodeAt(0);
  32789. const CLOSE_CURLY = '}'.charCodeAt(0);
  32790. const SEMICOLON = ';'.charCodeAt(0);
  32791. const ASTERISK = '*'.charCodeAt(0);
  32792. const COLON = ':'.charCodeAt(0);
  32793. const AT = '@'.charCodeAt(0);
  32794. const RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g;
  32795. const RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g;
  32796. const RE_BAD_BRACKET = /.[\r\n"'(/\\]/;
  32797. const RE_HEX_ESCAPE = /[\da-f]/i;
  32798. tokenize$1 = function tokenizer(input, options = {}) {
  32799. let css = input.css.valueOf();
  32800. let ignore = options.ignoreErrors;
  32801. let code, content, escape, next, quote;
  32802. let currentToken, escaped, escapePos, n, prev;
  32803. let length = css.length;
  32804. let pos = 0;
  32805. let buffer = [];
  32806. let returned = [];
  32807. let lastBadParen = -1;
  32808. function position() {
  32809. return pos
  32810. }
  32811. function unclosed(what) {
  32812. throw input.error('Unclosed ' + what, pos)
  32813. }
  32814. function endOfFile() {
  32815. return returned.length === 0 && pos >= length
  32816. }
  32817. function nextToken(opts) {
  32818. if (returned.length) return returned.pop()
  32819. if (pos >= length) return
  32820. let ignoreUnclosed = opts ? opts.ignoreUnclosed : false;
  32821. code = css.charCodeAt(pos);
  32822. switch (code) {
  32823. case NEWLINE:
  32824. case SPACE:
  32825. case TAB:
  32826. case CR:
  32827. case FEED: {
  32828. next = pos;
  32829. do {
  32830. next += 1;
  32831. code = css.charCodeAt(next);
  32832. } while (
  32833. code === SPACE ||
  32834. code === NEWLINE ||
  32835. code === TAB ||
  32836. code === CR ||
  32837. code === FEED
  32838. )
  32839. currentToken = ['space', css.slice(pos, next)];
  32840. pos = next - 1;
  32841. break
  32842. }
  32843. case OPEN_SQUARE:
  32844. case CLOSE_SQUARE:
  32845. case OPEN_CURLY:
  32846. case CLOSE_CURLY:
  32847. case COLON:
  32848. case SEMICOLON:
  32849. case CLOSE_PARENTHESES: {
  32850. let controlChar = String.fromCharCode(code);
  32851. currentToken = [controlChar, controlChar, pos];
  32852. break
  32853. }
  32854. case OPEN_PARENTHESES: {
  32855. prev = buffer.length ? buffer.pop()[1] : '';
  32856. n = css.charCodeAt(pos + 1);
  32857. if (
  32858. prev === 'url' &&
  32859. n !== SINGLE_QUOTE &&
  32860. n !== DOUBLE_QUOTE &&
  32861. n !== SPACE &&
  32862. n !== NEWLINE &&
  32863. n !== TAB &&
  32864. n !== FEED &&
  32865. n !== CR
  32866. ) {
  32867. next = pos;
  32868. do {
  32869. escaped = false;
  32870. next = css.indexOf(')', next + 1);
  32871. if (next === -1) {
  32872. if (ignore || ignoreUnclosed) {
  32873. next = pos;
  32874. break
  32875. } else {
  32876. unclosed('bracket');
  32877. }
  32878. }
  32879. escapePos = next;
  32880. while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
  32881. escapePos -= 1;
  32882. escaped = !escaped;
  32883. }
  32884. } while (escaped)
  32885. currentToken = ['brackets', css.slice(pos, next + 1), pos, next];
  32886. pos = next;
  32887. } else if (pos <= lastBadParen) {
  32888. currentToken = ['(', '(', pos];
  32889. } else {
  32890. next = css.indexOf(')', pos + 1);
  32891. content = css.slice(pos, next + 1);
  32892. if (next === -1 || RE_BAD_BRACKET.test(content)) {
  32893. lastBadParen = next === -1 ? length : next;
  32894. currentToken = ['(', '(', pos];
  32895. } else {
  32896. currentToken = ['brackets', content, pos, next];
  32897. pos = next;
  32898. }
  32899. }
  32900. break
  32901. }
  32902. case SINGLE_QUOTE:
  32903. case DOUBLE_QUOTE: {
  32904. quote = code === SINGLE_QUOTE ? "'" : '"';
  32905. next = pos;
  32906. do {
  32907. escaped = false;
  32908. next = css.indexOf(quote, next + 1);
  32909. if (next === -1) {
  32910. if (ignore || ignoreUnclosed) {
  32911. next = pos + 1;
  32912. break
  32913. } else {
  32914. unclosed('string');
  32915. }
  32916. }
  32917. escapePos = next;
  32918. while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
  32919. escapePos -= 1;
  32920. escaped = !escaped;
  32921. }
  32922. } while (escaped)
  32923. currentToken = ['string', css.slice(pos, next + 1), pos, next];
  32924. pos = next;
  32925. break
  32926. }
  32927. case AT: {
  32928. RE_AT_END.lastIndex = pos + 1;
  32929. RE_AT_END.test(css);
  32930. if (RE_AT_END.lastIndex === 0) {
  32931. next = css.length - 1;
  32932. } else {
  32933. next = RE_AT_END.lastIndex - 2;
  32934. }
  32935. currentToken = ['at-word', css.slice(pos, next + 1), pos, next];
  32936. pos = next;
  32937. break
  32938. }
  32939. case BACKSLASH: {
  32940. next = pos;
  32941. escape = true;
  32942. while (css.charCodeAt(next + 1) === BACKSLASH) {
  32943. next += 1;
  32944. escape = !escape;
  32945. }
  32946. code = css.charCodeAt(next + 1);
  32947. if (
  32948. escape &&
  32949. code !== SLASH &&
  32950. code !== SPACE &&
  32951. code !== NEWLINE &&
  32952. code !== TAB &&
  32953. code !== CR &&
  32954. code !== FEED
  32955. ) {
  32956. next += 1;
  32957. if (RE_HEX_ESCAPE.test(css.charAt(next))) {
  32958. while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) {
  32959. next += 1;
  32960. }
  32961. if (css.charCodeAt(next + 1) === SPACE) {
  32962. next += 1;
  32963. }
  32964. }
  32965. }
  32966. currentToken = ['word', css.slice(pos, next + 1), pos, next];
  32967. pos = next;
  32968. break
  32969. }
  32970. default: {
  32971. if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
  32972. next = css.indexOf('*/', pos + 2) + 1;
  32973. if (next === 0) {
  32974. if (ignore || ignoreUnclosed) {
  32975. next = css.length;
  32976. } else {
  32977. unclosed('comment');
  32978. }
  32979. }
  32980. currentToken = ['comment', css.slice(pos, next + 1), pos, next];
  32981. pos = next;
  32982. } else {
  32983. RE_WORD_END.lastIndex = pos + 1;
  32984. RE_WORD_END.test(css);
  32985. if (RE_WORD_END.lastIndex === 0) {
  32986. next = css.length - 1;
  32987. } else {
  32988. next = RE_WORD_END.lastIndex - 2;
  32989. }
  32990. currentToken = ['word', css.slice(pos, next + 1), pos, next];
  32991. buffer.push(currentToken);
  32992. pos = next;
  32993. }
  32994. break
  32995. }
  32996. }
  32997. pos++;
  32998. return currentToken
  32999. }
  33000. function back(token) {
  33001. returned.push(token);
  33002. }
  33003. return {
  33004. back,
  33005. endOfFile,
  33006. nextToken,
  33007. position
  33008. }
  33009. };
  33010. return tokenize$1;
  33011. }
  33012. var terminalHighlight_1;
  33013. var hasRequiredTerminalHighlight;
  33014. function requireTerminalHighlight () {
  33015. if (hasRequiredTerminalHighlight) return terminalHighlight_1;
  33016. hasRequiredTerminalHighlight = 1;
  33017. let pico = /*@__PURE__*/ requirePicocolors();
  33018. let tokenizer = /*@__PURE__*/ requireTokenize$1();
  33019. let Input;
  33020. function registerInput(dependant) {
  33021. Input = dependant;
  33022. }
  33023. const HIGHLIGHT_THEME = {
  33024. ';': pico.yellow,
  33025. ':': pico.yellow,
  33026. '(': pico.cyan,
  33027. ')': pico.cyan,
  33028. '[': pico.yellow,
  33029. ']': pico.yellow,
  33030. '{': pico.yellow,
  33031. '}': pico.yellow,
  33032. 'at-word': pico.cyan,
  33033. 'brackets': pico.cyan,
  33034. 'call': pico.cyan,
  33035. 'class': pico.yellow,
  33036. 'comment': pico.gray,
  33037. 'hash': pico.magenta,
  33038. 'string': pico.green
  33039. };
  33040. function getTokenType([type, value], processor) {
  33041. if (type === 'word') {
  33042. if (value[0] === '.') {
  33043. return 'class'
  33044. }
  33045. if (value[0] === '#') {
  33046. return 'hash'
  33047. }
  33048. }
  33049. if (!processor.endOfFile()) {
  33050. let next = processor.nextToken();
  33051. processor.back(next);
  33052. if (next[0] === 'brackets' || next[0] === '(') return 'call'
  33053. }
  33054. return type
  33055. }
  33056. function terminalHighlight(css) {
  33057. let processor = tokenizer(new Input(css), { ignoreErrors: true });
  33058. let result = '';
  33059. while (!processor.endOfFile()) {
  33060. let token = processor.nextToken();
  33061. let color = HIGHLIGHT_THEME[getTokenType(token, processor)];
  33062. if (color) {
  33063. result += token[1]
  33064. .split(/\r?\n/)
  33065. .map(i => color(i))
  33066. .join('\n');
  33067. } else {
  33068. result += token[1];
  33069. }
  33070. }
  33071. return result
  33072. }
  33073. terminalHighlight.registerInput = registerInput;
  33074. terminalHighlight_1 = terminalHighlight;
  33075. return terminalHighlight_1;
  33076. }
  33077. var cssSyntaxError;
  33078. var hasRequiredCssSyntaxError;
  33079. function requireCssSyntaxError () {
  33080. if (hasRequiredCssSyntaxError) return cssSyntaxError;
  33081. hasRequiredCssSyntaxError = 1;
  33082. let pico = /*@__PURE__*/ requirePicocolors();
  33083. let terminalHighlight = /*@__PURE__*/ requireTerminalHighlight();
  33084. class CssSyntaxError extends Error {
  33085. constructor(message, line, column, source, file, plugin) {
  33086. super(message);
  33087. this.name = 'CssSyntaxError';
  33088. this.reason = message;
  33089. if (file) {
  33090. this.file = file;
  33091. }
  33092. if (source) {
  33093. this.source = source;
  33094. }
  33095. if (plugin) {
  33096. this.plugin = plugin;
  33097. }
  33098. if (typeof line !== 'undefined' && typeof column !== 'undefined') {
  33099. if (typeof line === 'number') {
  33100. this.line = line;
  33101. this.column = column;
  33102. } else {
  33103. this.line = line.line;
  33104. this.column = line.column;
  33105. this.endLine = column.line;
  33106. this.endColumn = column.column;
  33107. }
  33108. }
  33109. this.setMessage();
  33110. if (Error.captureStackTrace) {
  33111. Error.captureStackTrace(this, CssSyntaxError);
  33112. }
  33113. }
  33114. setMessage() {
  33115. this.message = this.plugin ? this.plugin + ': ' : '';
  33116. this.message += this.file ? this.file : '<css input>';
  33117. if (typeof this.line !== 'undefined') {
  33118. this.message += ':' + this.line + ':' + this.column;
  33119. }
  33120. this.message += ': ' + this.reason;
  33121. }
  33122. showSourceCode(color) {
  33123. if (!this.source) return ''
  33124. let css = this.source;
  33125. if (color == null) color = pico.isColorSupported;
  33126. let aside = text => text;
  33127. let mark = text => text;
  33128. let highlight = text => text;
  33129. if (color) {
  33130. let { bold, gray, red } = pico.createColors(true);
  33131. mark = text => bold(red(text));
  33132. aside = text => gray(text);
  33133. if (terminalHighlight) {
  33134. highlight = text => terminalHighlight(text);
  33135. }
  33136. }
  33137. let lines = css.split(/\r?\n/);
  33138. let start = Math.max(this.line - 3, 0);
  33139. let end = Math.min(this.line + 2, lines.length);
  33140. let maxWidth = String(end).length;
  33141. return lines
  33142. .slice(start, end)
  33143. .map((line, index) => {
  33144. let number = start + 1 + index;
  33145. let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | ';
  33146. if (number === this.line) {
  33147. if (line.length > 160) {
  33148. let padding = 20;
  33149. let subLineStart = Math.max(0, this.column - padding);
  33150. let subLineEnd = Math.max(
  33151. this.column + padding,
  33152. this.endColumn + padding
  33153. );
  33154. let subLine = line.slice(subLineStart, subLineEnd);
  33155. let spacing =
  33156. aside(gutter.replace(/\d/g, ' ')) +
  33157. line
  33158. .slice(0, Math.min(this.column - 1, padding - 1))
  33159. .replace(/[^\t]/g, ' ');
  33160. return (
  33161. mark('>') +
  33162. aside(gutter) +
  33163. highlight(subLine) +
  33164. '\n ' +
  33165. spacing +
  33166. mark('^')
  33167. )
  33168. }
  33169. let spacing =
  33170. aside(gutter.replace(/\d/g, ' ')) +
  33171. line.slice(0, this.column - 1).replace(/[^\t]/g, ' ');
  33172. return (
  33173. mark('>') +
  33174. aside(gutter) +
  33175. highlight(line) +
  33176. '\n ' +
  33177. spacing +
  33178. mark('^')
  33179. )
  33180. }
  33181. return ' ' + aside(gutter) + highlight(line)
  33182. })
  33183. .join('\n')
  33184. }
  33185. toString() {
  33186. let code = this.showSourceCode();
  33187. if (code) {
  33188. code = '\n\n' + code + '\n';
  33189. }
  33190. return this.name + ': ' + this.message + code
  33191. }
  33192. }
  33193. cssSyntaxError = CssSyntaxError;
  33194. CssSyntaxError.default = CssSyntaxError;
  33195. return cssSyntaxError;
  33196. }
  33197. var stringifier;
  33198. var hasRequiredStringifier;
  33199. function requireStringifier () {
  33200. if (hasRequiredStringifier) return stringifier;
  33201. hasRequiredStringifier = 1;
  33202. // Escapes sequences that could break out of an HTML <style> context.
  33203. // Uses CSS unicode escaping (\3c = '<') which is valid CSS and parsed
  33204. // correctly by all compliant CSS consumers.
  33205. const STYLE_TAG = /(<)(\/?style\b)/gi;
  33206. const COMMENT_OPEN = /(<)(!--)/g;
  33207. // Characters that end an at-rule name, mirroring RE_AT_END in the tokenizer.
  33208. // Params starting with anything else need a space to stay separate tokens.
  33209. const AT_NAME_END = /[\t\n\f\r "#'()/;[\\\]{}]/;
  33210. function escapeHTMLInCSS(str) {
  33211. if (typeof str !== 'string') return str
  33212. if (!str.includes('<')) return str
  33213. return str.replace(STYLE_TAG, '\\3c $2').replace(COMMENT_OPEN, '\\3c $2')
  33214. }
  33215. const DEFAULT_RAW = {
  33216. after: '\n',
  33217. beforeClose: '\n',
  33218. beforeComment: '\n',
  33219. beforeDecl: '\n',
  33220. beforeOpen: ' ',
  33221. beforeRule: '\n',
  33222. colon: ': ',
  33223. commentLeft: ' ',
  33224. commentRight: ' ',
  33225. emptyBody: '',
  33226. indent: ' ',
  33227. semicolon: false
  33228. };
  33229. function capitalize(str) {
  33230. return str[0].toUpperCase() + str.slice(1)
  33231. }
  33232. function atruleStart(str, node) {
  33233. let name = '@' + node.name;
  33234. let params = node.params ? str.rawValue(node, 'params') : '';
  33235. let afterName = node.raws.afterName;
  33236. if (typeof afterName === 'undefined') {
  33237. afterName = params ? ' ' : '';
  33238. } else if (afterName === '' && params && !AT_NAME_END.test(params[0])) {
  33239. afterName = ' ';
  33240. }
  33241. return name + afterName + params
  33242. }
  33243. function pushBody(str, stack, node) {
  33244. let nodes = node.nodes;
  33245. let last = nodes.length - 1;
  33246. while (last > 0) {
  33247. if (nodes[last].type !== 'comment') break
  33248. last -= 1;
  33249. }
  33250. let semicolon = str.raw(node, 'semicolon');
  33251. let isDocument = node.type === 'document';
  33252. for (let i = nodes.length - 1; i >= 0; i--) {
  33253. let child = nodes[i];
  33254. let childSemicolon = last !== i || semicolon;
  33255. // A childless at-rule or a custom property declaration that still has
  33256. // following siblings must be terminated. Without the semicolon those
  33257. // trailing comments are folded into the at-rule's prelude or the custom
  33258. // property's value and disappear when the output is re-parsed.
  33259. if (
  33260. !childSemicolon &&
  33261. i < nodes.length - 1 &&
  33262. ((child.type === 'atrule' && !child.nodes) ||
  33263. (child.type === 'decl' && child.prop.startsWith('--')))
  33264. ) {
  33265. childSemicolon = true;
  33266. }
  33267. stack.push({
  33268. document: isDocument,
  33269. node: child,
  33270. semicolon: childSemicolon
  33271. });
  33272. }
  33273. }
  33274. function pushBlock(str, stack, node, start) {
  33275. let between = str.raw(node, 'between', 'beforeOpen');
  33276. str.builder(escapeHTMLInCSS(start + between) + '{', node, 'start');
  33277. let hasNodes = node.nodes && node.nodes.length;
  33278. let close = () => {
  33279. let after = hasNodes
  33280. ? str.raw(node, 'after')
  33281. : str.raw(node, 'after', 'emptyBody');
  33282. if (after) str.builder(escapeHTMLInCSS(after));
  33283. str.builder('}', node, 'end');
  33284. if (node.type === 'rule' && node.raws.ownSemicolon) {
  33285. str.builder(escapeHTMLInCSS(node.raws.ownSemicolon), node, 'end');
  33286. }
  33287. };
  33288. if (hasNodes) {
  33289. stack.push(close);
  33290. pushBody(str, stack, node);
  33291. } else {
  33292. close();
  33293. }
  33294. }
  33295. class Stringifier {
  33296. constructor(builder) {
  33297. this.builder = builder;
  33298. }
  33299. atrule(node, semicolon) {
  33300. let start = atruleStart(this, node);
  33301. if (node.nodes) {
  33302. this.block(node, start);
  33303. } else {
  33304. let end = (node.raws.between || '') + (semicolon ? ';' : '');
  33305. this.builder(escapeHTMLInCSS(start + end), node);
  33306. }
  33307. }
  33308. beforeAfter(node, detect) {
  33309. let value;
  33310. if (node.type === 'decl') {
  33311. value = this.raw(node, null, 'beforeDecl');
  33312. } else if (node.type === 'comment') {
  33313. value = this.raw(node, null, 'beforeComment');
  33314. } else if (detect === 'before') {
  33315. value = this.raw(node, null, 'beforeRule');
  33316. } else {
  33317. value = this.raw(node, null, 'beforeClose');
  33318. }
  33319. let buf = node.parent;
  33320. let depth = 0;
  33321. while (buf && buf.type !== 'root') {
  33322. depth += 1;
  33323. buf = buf.parent;
  33324. }
  33325. if (value.includes('\n')) {
  33326. let indent = this.raw(node, null, 'indent');
  33327. if (indent.length) {
  33328. for (let step = 0; step < depth; step++) value += indent;
  33329. }
  33330. }
  33331. return value
  33332. }
  33333. block(node, start) {
  33334. let between = this.raw(node, 'between', 'beforeOpen');
  33335. this.builder(escapeHTMLInCSS(start + between) + '{', node, 'start');
  33336. let after;
  33337. if (node.nodes && node.nodes.length) {
  33338. this.body(node);
  33339. after = this.raw(node, 'after');
  33340. } else {
  33341. after = this.raw(node, 'after', 'emptyBody');
  33342. }
  33343. if (after) this.builder(escapeHTMLInCSS(after));
  33344. this.builder('}', node, 'end');
  33345. }
  33346. body(node) {
  33347. // Rules and at-rules are expanded into an explicit stack instead of
  33348. // recursive `stringify()` calls to survive deeply nested trees.
  33349. // If a subclass changes the traversal methods, its children go
  33350. // through `stringify()` to keep the override in charge.
  33351. let proto = Stringifier.prototype;
  33352. let expandable = ['atrule', 'block', 'body', 'rule', 'stringify'].every(
  33353. method => this[method] === proto[method]
  33354. );
  33355. let stack = [];
  33356. pushBody(this, stack, node);
  33357. while (stack.length > 0) {
  33358. let entry = stack.pop();
  33359. if (typeof entry === 'function') {
  33360. entry();
  33361. continue
  33362. }
  33363. let child = entry.node;
  33364. let before = this.raw(child, 'before');
  33365. if (before) {
  33366. this.builder(entry.document ? before : escapeHTMLInCSS(before));
  33367. }
  33368. if (expandable && child.type === 'rule') {
  33369. pushBlock(this, stack, child, this.rawValue(child, 'selector'));
  33370. } else if (expandable && child.type === 'atrule' && child.nodes) {
  33371. pushBlock(this, stack, child, atruleStart(this, child));
  33372. } else {
  33373. this.stringify(child, entry.semicolon);
  33374. }
  33375. }
  33376. }
  33377. comment(node) {
  33378. let left = this.raw(node, 'left', 'commentLeft');
  33379. let right = this.raw(node, 'right', 'commentRight');
  33380. this.builder(escapeHTMLInCSS('/*' + left + node.text + right + '*/'), node);
  33381. }
  33382. decl(node, semicolon) {
  33383. let raws = node.raws;
  33384. let between = this.raw(node, 'between', 'colon');
  33385. let string = node.prop + between + this.rawValue(node, 'value');
  33386. if (node.important) {
  33387. string += raws.important || ' !important';
  33388. }
  33389. if (semicolon) string += ';';
  33390. this.builder(escapeHTMLInCSS(string), node);
  33391. }
  33392. document(node) {
  33393. this.body(node);
  33394. }
  33395. raw(node, own, detect) {
  33396. let value;
  33397. if (!detect) detect = own;
  33398. // Already had
  33399. if (own) {
  33400. value = node.raws[own];
  33401. if (typeof value !== 'undefined') return value
  33402. }
  33403. let parent = node.parent;
  33404. if (detect === 'before') {
  33405. // Hack for first rule in CSS
  33406. if (!parent || (parent.type === 'root' && parent.first === node)) {
  33407. return ''
  33408. }
  33409. // `root` nodes in `document` should use only their own raws
  33410. if (parent && parent.type === 'document') {
  33411. return ''
  33412. }
  33413. }
  33414. // Floating child without parent
  33415. if (!parent) return DEFAULT_RAW[detect]
  33416. // Detect style by other nodes
  33417. let root = node.root();
  33418. let cache = root.rawCache || (root.rawCache = {});
  33419. if (typeof cache[detect] !== 'undefined') {
  33420. return cache[detect]
  33421. }
  33422. if (detect === 'before' || detect === 'after') {
  33423. return this.beforeAfter(node, detect)
  33424. } else {
  33425. let method = 'raw' + capitalize(detect);
  33426. if (this[method]) {
  33427. value = this[method](root, node);
  33428. } else {
  33429. root.walk(i => {
  33430. value = i.raws[own];
  33431. if (typeof value !== 'undefined') return false
  33432. });
  33433. }
  33434. }
  33435. if (typeof value === 'undefined') value = DEFAULT_RAW[detect];
  33436. cache[detect] = value;
  33437. return value
  33438. }
  33439. rawBeforeClose(root) {
  33440. let value;
  33441. root.walk(i => {
  33442. if (i.nodes && i.nodes.length > 0) {
  33443. if (typeof i.raws.after !== 'undefined') {
  33444. value = i.raws.after;
  33445. if (value.includes('\n')) {
  33446. value = value.replace(/[^\n]+$/, '');
  33447. }
  33448. return false
  33449. }
  33450. }
  33451. });
  33452. if (value) value = value.replace(/\S/g, '');
  33453. return value
  33454. }
  33455. rawBeforeComment(root, node) {
  33456. let value;
  33457. root.walkComments(i => {
  33458. if (typeof i.raws.before !== 'undefined') {
  33459. value = i.raws.before;
  33460. if (value.includes('\n')) {
  33461. value = value.replace(/[^\n]+$/, '');
  33462. }
  33463. return false
  33464. }
  33465. });
  33466. if (typeof value === 'undefined') {
  33467. value = this.raw(node, null, 'beforeDecl');
  33468. } else if (value) {
  33469. value = value.replace(/\S/g, '');
  33470. }
  33471. return value
  33472. }
  33473. rawBeforeDecl(root, node) {
  33474. let value;
  33475. root.walkDecls(i => {
  33476. if (typeof i.raws.before !== 'undefined') {
  33477. value = i.raws.before;
  33478. if (value.includes('\n')) {
  33479. value = value.replace(/[^\n]+$/, '');
  33480. }
  33481. return false
  33482. }
  33483. });
  33484. if (typeof value === 'undefined') {
  33485. value = this.raw(node, null, 'beforeRule');
  33486. } else if (value) {
  33487. value = value.replace(/\S/g, '');
  33488. }
  33489. return value
  33490. }
  33491. rawBeforeOpen(root) {
  33492. let value;
  33493. root.walk(i => {
  33494. if (i.type !== 'decl') {
  33495. value = i.raws.between;
  33496. if (typeof value !== 'undefined') return false
  33497. }
  33498. });
  33499. return value
  33500. }
  33501. rawBeforeRule(root) {
  33502. let value;
  33503. root.walk(i => {
  33504. if (i.nodes && (i.parent !== root || root.first !== i)) {
  33505. if (typeof i.raws.before !== 'undefined') {
  33506. value = i.raws.before;
  33507. if (value.includes('\n')) {
  33508. value = value.replace(/[^\n]+$/, '');
  33509. }
  33510. return false
  33511. }
  33512. }
  33513. });
  33514. if (value) value = value.replace(/\S/g, '');
  33515. return value
  33516. }
  33517. rawColon(root) {
  33518. let value;
  33519. root.walkDecls(i => {
  33520. if (typeof i.raws.between !== 'undefined') {
  33521. value = i.raws.between.replace(/[^\s:]/g, '');
  33522. return false
  33523. }
  33524. });
  33525. return value
  33526. }
  33527. rawEmptyBody(root) {
  33528. let value;
  33529. root.walk(i => {
  33530. if (i.nodes && i.nodes.length === 0) {
  33531. value = i.raws.after;
  33532. if (typeof value !== 'undefined') return false
  33533. }
  33534. });
  33535. return value
  33536. }
  33537. rawIndent(root) {
  33538. if (root.raws.indent) return root.raws.indent
  33539. let value;
  33540. root.walk(i => {
  33541. let p = i.parent;
  33542. if (p && p !== root && p.parent && p.parent === root) {
  33543. if (typeof i.raws.before !== 'undefined') {
  33544. let parts = i.raws.before.split('\n');
  33545. value = parts[parts.length - 1];
  33546. value = value.replace(/\S/g, '');
  33547. return false
  33548. }
  33549. }
  33550. });
  33551. return value
  33552. }
  33553. rawSemicolon(root) {
  33554. let value;
  33555. root.walk(i => {
  33556. if (i.nodes && i.nodes.length && i.last.type === 'decl') {
  33557. value = i.raws.semicolon;
  33558. if (typeof value !== 'undefined') return false
  33559. }
  33560. });
  33561. return value
  33562. }
  33563. rawValue(node, prop) {
  33564. let value = node[prop];
  33565. let raw = node.raws[prop];
  33566. if (raw && raw.value === value) {
  33567. return raw.raw
  33568. }
  33569. return value
  33570. }
  33571. root(node) {
  33572. this.body(node);
  33573. if (node.raws.after) {
  33574. let after = node.raws.after;
  33575. let isDocument = node.parent && node.parent.type === 'document';
  33576. this.builder(isDocument ? after : escapeHTMLInCSS(after));
  33577. }
  33578. }
  33579. rule(node) {
  33580. this.block(node, this.rawValue(node, 'selector'));
  33581. if (node.raws.ownSemicolon) {
  33582. this.builder(escapeHTMLInCSS(node.raws.ownSemicolon), node, 'end');
  33583. }
  33584. }
  33585. stringify(node, semicolon) {
  33586. /* c8 ignore start */
  33587. if (!this[node.type]) {
  33588. throw new Error(
  33589. 'Unknown AST node type ' +
  33590. node.type +
  33591. '. ' +
  33592. 'Maybe you need to change PostCSS stringifier.'
  33593. )
  33594. }
  33595. /* c8 ignore stop */
  33596. this[node.type](node, semicolon);
  33597. }
  33598. }
  33599. stringifier = Stringifier;
  33600. Stringifier.default = Stringifier;
  33601. return stringifier;
  33602. }
  33603. var stringify_1;
  33604. var hasRequiredStringify;
  33605. function requireStringify () {
  33606. if (hasRequiredStringify) return stringify_1;
  33607. hasRequiredStringify = 1;
  33608. let Stringifier = /*@__PURE__*/ requireStringifier();
  33609. function stringify(node, builder) {
  33610. let str = new Stringifier(builder);
  33611. str.stringify(node);
  33612. }
  33613. stringify_1 = stringify;
  33614. stringify.default = stringify;
  33615. return stringify_1;
  33616. }
  33617. var symbols = {};
  33618. var hasRequiredSymbols;
  33619. function requireSymbols () {
  33620. if (hasRequiredSymbols) return symbols;
  33621. hasRequiredSymbols = 1;
  33622. symbols.isClean = Symbol('isClean');
  33623. symbols.my = Symbol('my');
  33624. return symbols;
  33625. }
  33626. var node$2;
  33627. var hasRequiredNode$2;
  33628. function requireNode$2 () {
  33629. if (hasRequiredNode$2) return node$2;
  33630. hasRequiredNode$2 = 1;
  33631. let CssSyntaxError = /*@__PURE__*/ requireCssSyntaxError();
  33632. let Stringifier = /*@__PURE__*/ requireStringifier();
  33633. let stringify = /*@__PURE__*/ requireStringify();
  33634. let { isClean, my } = /*@__PURE__*/ requireSymbols();
  33635. function cloneNode(obj, parent) {
  33636. let cloned = new obj.constructor();
  33637. // An explicit stack instead of recursive calls to survive deeply
  33638. // nested trees. Each entry is [source, its clone, clone's parent].
  33639. let stack = [[obj, cloned, parent]];
  33640. while (stack.length > 0) {
  33641. let [source, target, targetParent] = stack.pop();
  33642. for (let i in source) {
  33643. if (!Object.prototype.hasOwnProperty.call(source, i)) {
  33644. /* c8 ignore next 2 */
  33645. continue
  33646. }
  33647. if (i === 'proxyCache') continue
  33648. let value = source[i];
  33649. let type = typeof value;
  33650. if (i === 'parent' && type === 'object') {
  33651. if (targetParent) target[i] = targetParent;
  33652. } else if (i === 'source') {
  33653. target[i] = value;
  33654. } else if (Array.isArray(value)) {
  33655. let children = [];
  33656. target[i] = children;
  33657. for (let j of value) {
  33658. let childClone = new j.constructor();
  33659. children.push(childClone);
  33660. stack.push([j, childClone, target]);
  33661. }
  33662. } else {
  33663. if (type === 'object' && value !== null) {
  33664. let valueClone = new value.constructor();
  33665. stack.push([value, valueClone, undefined]);
  33666. value = valueClone;
  33667. }
  33668. target[i] = value;
  33669. }
  33670. }
  33671. }
  33672. return cloned
  33673. }
  33674. function sourceOffset(inputCSS, position) {
  33675. // Not all custom syntaxes support `offset` in `source.start` and `source.end`
  33676. if (position && typeof position.offset !== 'undefined') {
  33677. return position.offset
  33678. }
  33679. let column = 1;
  33680. let line = 1;
  33681. let offset = 0;
  33682. for (let i = 0; i < inputCSS.length; i++) {
  33683. if (line === position.line && column === position.column) {
  33684. offset = i;
  33685. break
  33686. }
  33687. if (inputCSS[i] === '\n') {
  33688. column = 1;
  33689. line += 1;
  33690. } else {
  33691. column += 1;
  33692. }
  33693. }
  33694. return offset
  33695. }
  33696. class Node {
  33697. get proxyOf() {
  33698. return this
  33699. }
  33700. constructor(defaults = {}) {
  33701. this.raws = {};
  33702. this[isClean] = false;
  33703. this[my] = true;
  33704. for (let name of Object.keys(defaults)) {
  33705. if (name === '__proto__') continue
  33706. if (name === 'nodes') {
  33707. this.nodes = [];
  33708. for (let node of defaults[name]) {
  33709. // Clone only nodes that already belong to another tree, so passing a
  33710. // freshly created (parent-less) node adopts that instance instead of
  33711. // a copy and keeps the caller's reference usable. See #1987.
  33712. if (typeof node.clone === 'function' && node.parent) {
  33713. this.append(node.clone());
  33714. } else {
  33715. this.append(node);
  33716. }
  33717. }
  33718. } else {
  33719. this[name] = defaults[name];
  33720. }
  33721. }
  33722. }
  33723. addToError(error) {
  33724. error.postcssNode = this;
  33725. if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
  33726. let s = this.source;
  33727. error.stack = error.stack.replace(
  33728. /\n\s{4}at /,
  33729. `$&${s.input.from}:${s.start.line}:${s.start.column}$&`
  33730. );
  33731. }
  33732. return error
  33733. }
  33734. after(add) {
  33735. this.parent.insertAfter(this, add);
  33736. return this
  33737. }
  33738. assign(overrides = {}) {
  33739. for (let name in overrides) {
  33740. this[name] = overrides[name];
  33741. }
  33742. return this
  33743. }
  33744. before(add) {
  33745. this.parent.insertBefore(this, add);
  33746. return this
  33747. }
  33748. cleanRaws(keepBetween) {
  33749. delete this.raws.before;
  33750. delete this.raws.after;
  33751. if (!keepBetween) delete this.raws.between;
  33752. }
  33753. clone(overrides = {}) {
  33754. let cloned = cloneNode(this);
  33755. for (let name in overrides) {
  33756. cloned[name] = overrides[name];
  33757. }
  33758. return cloned
  33759. }
  33760. cloneAfter(overrides = {}) {
  33761. let cloned = this.clone(overrides);
  33762. this.parent.insertAfter(this, cloned);
  33763. return cloned
  33764. }
  33765. cloneBefore(overrides = {}) {
  33766. let cloned = this.clone(overrides);
  33767. this.parent.insertBefore(this, cloned);
  33768. return cloned
  33769. }
  33770. error(message, opts = {}) {
  33771. if (this.source) {
  33772. let { end, start } = this.rangeBy(opts);
  33773. return this.source.input.error(
  33774. message,
  33775. { column: start.column, line: start.line },
  33776. { column: end.column, line: end.line },
  33777. opts
  33778. )
  33779. }
  33780. return new CssSyntaxError(message)
  33781. }
  33782. getProxyProcessor() {
  33783. return {
  33784. get(node, prop) {
  33785. if (prop === 'proxyOf') {
  33786. return node
  33787. } else if (prop === 'root') {
  33788. return () => node.root().toProxy()
  33789. } else {
  33790. return node[prop]
  33791. }
  33792. },
  33793. set(node, prop, value) {
  33794. if (node[prop] === value) return true
  33795. node[prop] = value;
  33796. if (
  33797. prop === 'prop' ||
  33798. prop === 'value' ||
  33799. prop === 'name' ||
  33800. prop === 'params' ||
  33801. prop === 'important' ||
  33802. /* c8 ignore next */
  33803. prop === 'text'
  33804. ) {
  33805. node.markDirty();
  33806. }
  33807. return true
  33808. }
  33809. }
  33810. }
  33811. /* c8 ignore next 3 */
  33812. markClean() {
  33813. this[isClean] = true;
  33814. }
  33815. markDirty() {
  33816. if (this[isClean]) {
  33817. this[isClean] = false;
  33818. let next = this;
  33819. while ((next = next.parent)) {
  33820. next[isClean] = false;
  33821. }
  33822. }
  33823. }
  33824. next() {
  33825. if (!this.parent) return undefined
  33826. let index = this.parent.index(this);
  33827. return this.parent.nodes[index + 1]
  33828. }
  33829. positionBy(opts = {}) {
  33830. let inputString =
  33831. 'document' in this.source.input
  33832. ? this.source.input.document
  33833. : this.source.input.css;
  33834. let pos = {
  33835. column: this.source.start.column,
  33836. line: this.source.start.line,
  33837. offset: sourceOffset(inputString, this.source.start)
  33838. };
  33839. if (opts.index) {
  33840. pos = this.positionInside(opts.index);
  33841. } else if (opts.word) {
  33842. let stringRepresentation = inputString.slice(
  33843. sourceOffset(inputString, this.source.start),
  33844. sourceOffset(inputString, this.source.end)
  33845. );
  33846. let index = stringRepresentation.indexOf(opts.word);
  33847. if (index !== -1) pos = this.positionInside(index);
  33848. }
  33849. return pos
  33850. }
  33851. positionInside(index) {
  33852. let column = this.source.start.column;
  33853. let line = this.source.start.line;
  33854. let inputString =
  33855. 'document' in this.source.input
  33856. ? this.source.input.document
  33857. : this.source.input.css;
  33858. let offset = sourceOffset(inputString, this.source.start);
  33859. let end = offset + index;
  33860. for (let i = offset; i < end; i++) {
  33861. if (inputString[i] === '\n') {
  33862. column = 1;
  33863. line += 1;
  33864. } else {
  33865. column += 1;
  33866. }
  33867. }
  33868. return { column, line, offset: end }
  33869. }
  33870. prev() {
  33871. if (!this.parent) return undefined
  33872. let index = this.parent.index(this);
  33873. return this.parent.nodes[index - 1]
  33874. }
  33875. rangeBy(opts = {}) {
  33876. let inputString =
  33877. 'document' in this.source.input
  33878. ? this.source.input.document
  33879. : this.source.input.css;
  33880. let start = {
  33881. column: this.source.start.column,
  33882. line: this.source.start.line,
  33883. offset: sourceOffset(inputString, this.source.start)
  33884. };
  33885. let end = this.source.end
  33886. ? {
  33887. column: this.source.end.column + 1,
  33888. line: this.source.end.line,
  33889. offset:
  33890. typeof this.source.end.offset === 'number'
  33891. ? // `source.end.offset` is exclusive, so we don't need to add 1
  33892. this.source.end.offset
  33893. : // Since line/column in this.source.end is inclusive,
  33894. // the `sourceOffset(... , this.source.end)` returns an inclusive offset.
  33895. // So, we add 1 to convert it to exclusive.
  33896. sourceOffset(inputString, this.source.end) + 1
  33897. }
  33898. : {
  33899. column: start.column + 1,
  33900. line: start.line,
  33901. offset: start.offset + 1
  33902. };
  33903. if (opts.word) {
  33904. let stringRepresentation = inputString.slice(
  33905. sourceOffset(inputString, this.source.start),
  33906. sourceOffset(inputString, this.source.end)
  33907. );
  33908. let index = stringRepresentation.indexOf(opts.word);
  33909. if (index !== -1) {
  33910. start = this.positionInside(index);
  33911. end = this.positionInside(index + opts.word.length);
  33912. }
  33913. } else {
  33914. if (opts.start) {
  33915. start = {
  33916. column: opts.start.column,
  33917. line: opts.start.line,
  33918. offset: sourceOffset(inputString, opts.start)
  33919. };
  33920. } else if (typeof opts.index === 'number') {
  33921. start = this.positionInside(opts.index);
  33922. }
  33923. if (opts.end) {
  33924. end = {
  33925. column: opts.end.column,
  33926. line: opts.end.line,
  33927. offset: sourceOffset(inputString, opts.end)
  33928. };
  33929. } else if (typeof opts.endIndex === 'number') {
  33930. end = this.positionInside(opts.endIndex);
  33931. } else if (typeof opts.index === 'number') {
  33932. end = this.positionInside(opts.index + 1);
  33933. }
  33934. }
  33935. if (
  33936. end.line < start.line ||
  33937. (end.line === start.line && end.column <= start.column)
  33938. ) {
  33939. end = {
  33940. column: start.column + 1,
  33941. line: start.line,
  33942. offset: start.offset + 1
  33943. };
  33944. }
  33945. return { end, start }
  33946. }
  33947. raw(prop, defaultType) {
  33948. let str = new Stringifier();
  33949. return str.raw(this, prop, defaultType)
  33950. }
  33951. remove() {
  33952. if (this.parent) {
  33953. this.parent.removeChild(this);
  33954. }
  33955. this.parent = undefined;
  33956. return this
  33957. }
  33958. replaceWith(...nodes) {
  33959. if (this.parent) {
  33960. let bookmark = this;
  33961. let foundSelf = false;
  33962. for (let node of nodes) {
  33963. if (node === this) {
  33964. foundSelf = true;
  33965. } else if (foundSelf) {
  33966. this.parent.insertAfter(bookmark, node);
  33967. bookmark = node;
  33968. } else {
  33969. this.parent.insertBefore(bookmark, node);
  33970. }
  33971. }
  33972. if (!foundSelf) {
  33973. this.remove();
  33974. }
  33975. }
  33976. return this
  33977. }
  33978. root() {
  33979. let result = this;
  33980. while (result.parent && result.parent.type !== 'document') {
  33981. result = result.parent;
  33982. }
  33983. return result
  33984. }
  33985. toJSON(_, inputs) {
  33986. let emitInputs = inputs == null;
  33987. inputs = inputs || new Map();
  33988. // A worklist instead of recursive `toJSON()` calls to survive deeply
  33989. // nested trees. Each entry converts one node and writes the result
  33990. // into the already converted parent by [holder, key].
  33991. let holderOfRoot = [];
  33992. let queue = [[this, holderOfRoot, 0]];
  33993. for (let step = 0; step < queue.length; step++) {
  33994. let [node, holder, key] = queue[step];
  33995. let fixed = {};
  33996. holder[key] = fixed;
  33997. for (let name in node) {
  33998. if (!Object.prototype.hasOwnProperty.call(node, name)) {
  33999. /* c8 ignore next 2 */
  34000. continue
  34001. }
  34002. if (name === 'parent' || name === 'proxyCache') continue
  34003. let value = node[name];
  34004. if (Array.isArray(value)) {
  34005. let fixedArray = [];
  34006. fixed[name] = fixedArray;
  34007. for (let i = 0; i < value.length; i++) {
  34008. let item = value[i];
  34009. if (typeof item === 'object' && item.toJSON) {
  34010. if (item.toJSON === Node.prototype.toJSON) {
  34011. queue.push([item, fixedArray, i]);
  34012. } else {
  34013. fixedArray[i] = item.toJSON(null, inputs);
  34014. }
  34015. } else {
  34016. fixedArray[i] = item;
  34017. }
  34018. }
  34019. } else if (typeof value === 'object' && value.toJSON) {
  34020. if (value.toJSON === Node.prototype.toJSON) {
  34021. queue.push([value, fixed, name]);
  34022. } else {
  34023. fixed[name] = value.toJSON(null, inputs);
  34024. }
  34025. } else if (name === 'source') {
  34026. if (value == null) continue
  34027. let inputId = inputs.get(value.input);
  34028. if (inputId == null) {
  34029. inputId = inputs.size;
  34030. inputs.set(value.input, inputId);
  34031. }
  34032. fixed[name] = {
  34033. end: value.end,
  34034. inputId,
  34035. start: value.start
  34036. };
  34037. } else {
  34038. fixed[name] = value;
  34039. }
  34040. }
  34041. }
  34042. let fixed = holderOfRoot[0];
  34043. if (emitInputs) {
  34044. fixed.inputs = [...inputs.keys()].map(input => input.toJSON());
  34045. }
  34046. return fixed
  34047. }
  34048. toProxy() {
  34049. if (!this.proxyCache) {
  34050. this.proxyCache = new Proxy(this, this.getProxyProcessor());
  34051. }
  34052. return this.proxyCache
  34053. }
  34054. toString(stringifier = stringify) {
  34055. if (stringifier.stringify) stringifier = stringifier.stringify;
  34056. let result = '';
  34057. stringifier(this, i => {
  34058. result += i;
  34059. });
  34060. return result
  34061. }
  34062. warn(result, text, opts = {}) {
  34063. let data = { node: this };
  34064. for (let i in opts) data[i] = opts[i];
  34065. return result.warn(text, data)
  34066. }
  34067. }
  34068. node$2 = Node;
  34069. Node.default = Node;
  34070. return node$2;
  34071. }
  34072. var comment$1;
  34073. var hasRequiredComment$1;
  34074. function requireComment$1 () {
  34075. if (hasRequiredComment$1) return comment$1;
  34076. hasRequiredComment$1 = 1;
  34077. let Node = /*@__PURE__*/ requireNode$2();
  34078. class Comment extends Node {
  34079. constructor(defaults) {
  34080. super(defaults);
  34081. this.type = 'comment';
  34082. }
  34083. }
  34084. comment$1 = Comment;
  34085. Comment.default = Comment;
  34086. return comment$1;
  34087. }
  34088. var declaration;
  34089. var hasRequiredDeclaration;
  34090. function requireDeclaration () {
  34091. if (hasRequiredDeclaration) return declaration;
  34092. hasRequiredDeclaration = 1;
  34093. let Node = /*@__PURE__*/ requireNode$2();
  34094. class Declaration extends Node {
  34095. get variable() {
  34096. return this.prop.startsWith('--') || this.prop[0] === '$'
  34097. }
  34098. constructor(defaults) {
  34099. if (
  34100. defaults &&
  34101. typeof defaults.value !== 'undefined' &&
  34102. typeof defaults.value !== 'string'
  34103. ) {
  34104. defaults = { ...defaults, value: String(defaults.value) };
  34105. }
  34106. super(defaults);
  34107. this.type = 'decl';
  34108. }
  34109. }
  34110. declaration = Declaration;
  34111. Declaration.default = Declaration;
  34112. return declaration;
  34113. }
  34114. var container$1;
  34115. var hasRequiredContainer$1;
  34116. function requireContainer$1 () {
  34117. if (hasRequiredContainer$1) return container$1;
  34118. hasRequiredContainer$1 = 1;
  34119. let Comment = /*@__PURE__*/ requireComment$1();
  34120. let Declaration = /*@__PURE__*/ requireDeclaration();
  34121. let Node = /*@__PURE__*/ requireNode$2();
  34122. let { isClean, my } = /*@__PURE__*/ requireSymbols();
  34123. let AtRule, parse, Root, Rule;
  34124. function cleanSource(nodes) {
  34125. let stack = nodes.slice();
  34126. while (stack.length > 0) {
  34127. let node = stack.pop();
  34128. delete node.source;
  34129. if (node.nodes) {
  34130. node.nodes = node.nodes.slice();
  34131. for (let i of node.nodes) stack.push(i);
  34132. }
  34133. }
  34134. return nodes.slice()
  34135. }
  34136. function markTreeDirty(node) {
  34137. let stack = [node];
  34138. while (stack.length > 0) {
  34139. let next = stack.pop();
  34140. next[isClean] = false;
  34141. if (next.proxyOf.nodes) {
  34142. for (let i of next.proxyOf.nodes) stack.push(i);
  34143. }
  34144. }
  34145. }
  34146. class Container extends Node {
  34147. get first() {
  34148. if (!this.proxyOf.nodes) return undefined
  34149. return this.proxyOf.nodes[0]
  34150. }
  34151. get last() {
  34152. if (!this.proxyOf.nodes) return undefined
  34153. return this.proxyOf.nodes[this.proxyOf.nodes.length - 1]
  34154. }
  34155. append(...children) {
  34156. for (let child of children) {
  34157. let nodes = this.normalize(child, this.last);
  34158. for (let node of nodes) this.proxyOf.nodes.push(node);
  34159. }
  34160. this.markDirty();
  34161. return this
  34162. }
  34163. cleanRaws(keepBetween) {
  34164. let stack = [this];
  34165. while (stack.length > 0) {
  34166. let node = stack.pop();
  34167. if (node !== this && node.cleanRaws !== Container.prototype.cleanRaws) {
  34168. // Subclass with own logic; let it handle its subtree
  34169. node.cleanRaws(keepBetween);
  34170. continue
  34171. }
  34172. Node.prototype.cleanRaws.call(node, keepBetween);
  34173. if (node.nodes) {
  34174. for (let child of node.nodes) stack.push(child);
  34175. }
  34176. }
  34177. }
  34178. each(callback) {
  34179. if (!this.proxyOf.nodes) return undefined
  34180. let iterator = this.getIterator();
  34181. let index, result;
  34182. while (this.indexes[iterator] < this.proxyOf.nodes.length) {
  34183. index = this.indexes[iterator];
  34184. result = callback(this.proxyOf.nodes[index], index);
  34185. if (result === false) break
  34186. this.indexes[iterator] += 1;
  34187. }
  34188. delete this.indexes[iterator];
  34189. return result
  34190. }
  34191. every(condition) {
  34192. return this.nodes.every(condition)
  34193. }
  34194. getIterator() {
  34195. if (!this.lastEach) this.lastEach = 0;
  34196. if (!this.indexes) this.indexes = {};
  34197. this.lastEach += 1;
  34198. let iterator = this.lastEach;
  34199. this.indexes[iterator] = 0;
  34200. return iterator
  34201. }
  34202. getProxyProcessor() {
  34203. return {
  34204. get(node, prop) {
  34205. if (prop === 'proxyOf') {
  34206. return node
  34207. } else if (!node[prop]) {
  34208. return node[prop]
  34209. } else if (
  34210. prop === 'each' ||
  34211. (typeof prop === 'string' && prop.startsWith('walk'))
  34212. ) {
  34213. return (...args) => {
  34214. return node[prop](
  34215. ...args.map(i => {
  34216. if (typeof i === 'function') {
  34217. return (child, index) => i(child.toProxy(), index)
  34218. } else {
  34219. return i
  34220. }
  34221. })
  34222. )
  34223. }
  34224. } else if (prop === 'every' || prop === 'some') {
  34225. return cb => {
  34226. return node[prop]((child, ...other) =>
  34227. cb(child.toProxy(), ...other)
  34228. )
  34229. }
  34230. } else if (prop === 'root') {
  34231. return () => node.root().toProxy()
  34232. } else if (prop === 'nodes') {
  34233. return node.nodes.map(i => i.toProxy())
  34234. } else if (prop === 'first' || prop === 'last') {
  34235. return node[prop].toProxy()
  34236. } else {
  34237. return node[prop]
  34238. }
  34239. },
  34240. set(node, prop, value) {
  34241. if (node[prop] === value) return true
  34242. node[prop] = value;
  34243. if (prop === 'name' || prop === 'params' || prop === 'selector') {
  34244. node.markDirty();
  34245. }
  34246. return true
  34247. }
  34248. }
  34249. }
  34250. index(child) {
  34251. if (typeof child === 'number') return child
  34252. if (child.proxyOf) child = child.proxyOf;
  34253. return this.proxyOf.nodes.indexOf(child)
  34254. }
  34255. insertAfter(exist, add) {
  34256. let existIndex = this.index(exist);
  34257. let nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse();
  34258. existIndex = this.index(exist);
  34259. for (let node of nodes) this.proxyOf.nodes.splice(existIndex + 1, 0, node);
  34260. let index;
  34261. for (let id in this.indexes) {
  34262. index = this.indexes[id];
  34263. if (existIndex < index) {
  34264. this.indexes[id] = index + nodes.length;
  34265. }
  34266. }
  34267. this.markDirty();
  34268. return this
  34269. }
  34270. insertBefore(exist, add) {
  34271. let existIndex = this.index(exist);
  34272. let type = existIndex === 0 ? 'prepend' : false;
  34273. let nodes = this.normalize(
  34274. add,
  34275. this.proxyOf.nodes[existIndex],
  34276. type
  34277. ).reverse();
  34278. existIndex = this.index(exist);
  34279. for (let node of nodes) this.proxyOf.nodes.splice(existIndex, 0, node);
  34280. let index;
  34281. for (let id in this.indexes) {
  34282. index = this.indexes[id];
  34283. if (existIndex <= index) {
  34284. this.indexes[id] = index + nodes.length;
  34285. }
  34286. }
  34287. this.markDirty();
  34288. return this
  34289. }
  34290. normalize(nodes, sample) {
  34291. if (typeof nodes === 'string') {
  34292. nodes = cleanSource(parse(nodes).nodes);
  34293. } else if (typeof nodes === 'undefined') {
  34294. nodes = [];
  34295. } else if (Array.isArray(nodes)) {
  34296. nodes = nodes.slice(0);
  34297. for (let i of nodes) {
  34298. if (i.parent) i.parent.removeChild(i, 'ignore');
  34299. }
  34300. } else if (nodes.type === 'root' && this.type !== 'document') {
  34301. nodes = nodes.nodes.slice(0);
  34302. for (let i of nodes) {
  34303. if (i.parent) i.parent.removeChild(i, 'ignore');
  34304. }
  34305. } else if (nodes.type) {
  34306. nodes = [nodes];
  34307. } else if (nodes.prop) {
  34308. if (typeof nodes.value === 'undefined') {
  34309. throw new Error('Value field is missed in node creation')
  34310. } else if (typeof nodes.value !== 'string') {
  34311. nodes.value = String(nodes.value);
  34312. }
  34313. nodes = [new Declaration(nodes)];
  34314. } else if (nodes.selector || nodes.selectors) {
  34315. nodes = [new Rule(nodes)];
  34316. } else if (nodes.name) {
  34317. nodes = [new AtRule(nodes)];
  34318. } else if (nodes.text) {
  34319. nodes = [new Comment(nodes)];
  34320. } else {
  34321. throw new Error('Unknown node type in node creation')
  34322. }
  34323. let processed = nodes.map(i => {
  34324. /* c8 ignore next */
  34325. if (!i[my]) Container.rebuild(i);
  34326. i = i.proxyOf;
  34327. if (i.parent) i.parent.removeChild(i);
  34328. if (i[isClean]) markTreeDirty(i);
  34329. if (!i.raws) i.raws = {};
  34330. if (typeof i.raws.before === 'undefined') {
  34331. if (sample && typeof sample.raws.before !== 'undefined') {
  34332. i.raws.before = sample.raws.before.replace(/\S/g, '');
  34333. }
  34334. }
  34335. i.parent = this.proxyOf;
  34336. return i
  34337. });
  34338. return processed
  34339. }
  34340. prepend(...children) {
  34341. children = children.reverse();
  34342. for (let child of children) {
  34343. let nodes = this.normalize(child, this.first, 'prepend').reverse();
  34344. for (let node of nodes) this.proxyOf.nodes.unshift(node);
  34345. for (let id in this.indexes) {
  34346. this.indexes[id] = this.indexes[id] + nodes.length;
  34347. }
  34348. }
  34349. this.markDirty();
  34350. return this
  34351. }
  34352. push(child) {
  34353. child.parent = this;
  34354. this.proxyOf.nodes.push(child);
  34355. return this
  34356. }
  34357. removeAll() {
  34358. for (let node of this.proxyOf.nodes) node.parent = undefined;
  34359. this.proxyOf.nodes = [];
  34360. this.markDirty();
  34361. return this
  34362. }
  34363. removeChild(child) {
  34364. child = this.index(child);
  34365. this.proxyOf.nodes[child].parent = undefined;
  34366. this.proxyOf.nodes.splice(child, 1);
  34367. let index;
  34368. for (let id in this.indexes) {
  34369. index = this.indexes[id];
  34370. if (index >= child) {
  34371. this.indexes[id] = index - 1;
  34372. }
  34373. }
  34374. this.markDirty();
  34375. return this
  34376. }
  34377. replaceValues(pattern, opts, callback) {
  34378. if (!callback) {
  34379. callback = opts;
  34380. opts = {};
  34381. }
  34382. this.walkDecls(decl => {
  34383. if (opts.props && !opts.props.includes(decl.prop)) return
  34384. if (opts.fast && !decl.value.includes(opts.fast)) return
  34385. decl.value = decl.value.replace(pattern, callback);
  34386. });
  34387. this.markDirty();
  34388. return this
  34389. }
  34390. some(condition) {
  34391. return this.nodes.some(condition)
  34392. }
  34393. walk(callback) {
  34394. if (!this.proxyOf.nodes) return undefined
  34395. // An explicit stack instead of recursive `each()` calls to survive
  34396. // deeply nested trees. Each frame keeps a live `indexes` slot, so
  34397. // insertion and removal during the walk behave like `each()`: the
  34398. // slot stays at the current child until its subtree is finished.
  34399. let stack = [{ iterator: this.getIterator(), node: this.proxyOf }];
  34400. while (stack.length > 0) {
  34401. let { iterator, node } = stack[stack.length - 1];
  34402. let index = node.indexes[iterator];
  34403. if (index >= node.proxyOf.nodes.length) {
  34404. delete node.indexes[iterator];
  34405. stack.pop();
  34406. let parent = stack[stack.length - 1];
  34407. // Finish the parent’s step for the child subtree we just left
  34408. if (parent) parent.node.indexes[parent.iterator] += 1;
  34409. continue
  34410. }
  34411. let child = node.proxyOf.nodes[index];
  34412. let result;
  34413. try {
  34414. result = callback(child, index);
  34415. } catch (e) {
  34416. throw child.addToError(e)
  34417. }
  34418. if (result === false) {
  34419. for (let opened of stack) {
  34420. delete opened.node.indexes[opened.iterator];
  34421. }
  34422. return false
  34423. }
  34424. if (child.walk && child.proxyOf.nodes) {
  34425. stack.push({ iterator: child.getIterator(), node: child });
  34426. } else {
  34427. node.indexes[iterator] += 1;
  34428. }
  34429. }
  34430. return undefined
  34431. }
  34432. walkAtRules(name, callback) {
  34433. if (!callback) {
  34434. callback = name;
  34435. return this.walk((child, i) => {
  34436. if (child.type === 'atrule') {
  34437. return callback(child, i)
  34438. }
  34439. })
  34440. }
  34441. if (name instanceof RegExp) {
  34442. return this.walk((child, i) => {
  34443. if (child.type === 'atrule' && name.test(child.name)) {
  34444. return callback(child, i)
  34445. }
  34446. })
  34447. }
  34448. return this.walk((child, i) => {
  34449. if (child.type === 'atrule' && child.name === name) {
  34450. return callback(child, i)
  34451. }
  34452. })
  34453. }
  34454. walkComments(callback) {
  34455. return this.walk((child, i) => {
  34456. if (child.type === 'comment') {
  34457. return callback(child, i)
  34458. }
  34459. })
  34460. }
  34461. walkDecls(prop, callback) {
  34462. if (!callback) {
  34463. callback = prop;
  34464. return this.walk((child, i) => {
  34465. if (child.type === 'decl') {
  34466. return callback(child, i)
  34467. }
  34468. })
  34469. }
  34470. if (prop instanceof RegExp) {
  34471. return this.walk((child, i) => {
  34472. if (child.type === 'decl' && prop.test(child.prop)) {
  34473. return callback(child, i)
  34474. }
  34475. })
  34476. }
  34477. return this.walk((child, i) => {
  34478. if (child.type === 'decl' && child.prop === prop) {
  34479. return callback(child, i)
  34480. }
  34481. })
  34482. }
  34483. walkRules(selector, callback) {
  34484. if (!callback) {
  34485. callback = selector;
  34486. return this.walk((child, i) => {
  34487. if (child.type === 'rule') {
  34488. return callback(child, i)
  34489. }
  34490. })
  34491. }
  34492. if (selector instanceof RegExp) {
  34493. return this.walk((child, i) => {
  34494. if (child.type === 'rule' && selector.test(child.selector)) {
  34495. return callback(child, i)
  34496. }
  34497. })
  34498. }
  34499. return this.walk((child, i) => {
  34500. if (child.type === 'rule' && child.selector === selector) {
  34501. return callback(child, i)
  34502. }
  34503. })
  34504. }
  34505. }
  34506. Container.registerParse = dependant => {
  34507. parse = dependant;
  34508. };
  34509. Container.registerRule = dependant => {
  34510. Rule = dependant;
  34511. };
  34512. Container.registerAtRule = dependant => {
  34513. AtRule = dependant;
  34514. };
  34515. Container.registerRoot = dependant => {
  34516. Root = dependant;
  34517. };
  34518. container$1 = Container;
  34519. Container.default = Container;
  34520. /* c8 ignore start */
  34521. Container.rebuild = node => {
  34522. let stack = [node];
  34523. while (stack.length > 0) {
  34524. let next = stack.pop();
  34525. if (next.type === 'atrule') {
  34526. Object.setPrototypeOf(next, AtRule.prototype);
  34527. } else if (next.type === 'rule') {
  34528. Object.setPrototypeOf(next, Rule.prototype);
  34529. } else if (next.type === 'decl') {
  34530. Object.setPrototypeOf(next, Declaration.prototype);
  34531. } else if (next.type === 'comment') {
  34532. Object.setPrototypeOf(next, Comment.prototype);
  34533. } else if (next.type === 'root') {
  34534. Object.setPrototypeOf(next, Root.prototype);
  34535. }
  34536. next[my] = true;
  34537. if (next.nodes) {
  34538. for (let child of next.nodes) stack.push(child);
  34539. }
  34540. }
  34541. };
  34542. /* c8 ignore stop */
  34543. return container$1;
  34544. }
  34545. var atRule;
  34546. var hasRequiredAtRule;
  34547. function requireAtRule () {
  34548. if (hasRequiredAtRule) return atRule;
  34549. hasRequiredAtRule = 1;
  34550. let Container = /*@__PURE__*/ requireContainer$1();
  34551. class AtRule extends Container {
  34552. constructor(defaults) {
  34553. super(defaults);
  34554. this.type = 'atrule';
  34555. }
  34556. append(...children) {
  34557. if (!this.proxyOf.nodes) this.nodes = [];
  34558. return super.append(...children)
  34559. }
  34560. prepend(...children) {
  34561. if (!this.proxyOf.nodes) this.nodes = [];
  34562. return super.prepend(...children)
  34563. }
  34564. }
  34565. atRule = AtRule;
  34566. AtRule.default = AtRule;
  34567. Container.registerAtRule(AtRule);
  34568. return atRule;
  34569. }
  34570. var document;
  34571. var hasRequiredDocument;
  34572. function requireDocument () {
  34573. if (hasRequiredDocument) return document;
  34574. hasRequiredDocument = 1;
  34575. let Container = /*@__PURE__*/ requireContainer$1();
  34576. let LazyResult, Processor;
  34577. class Document extends Container {
  34578. constructor(defaults) {
  34579. // type needs to be passed to super, otherwise child roots won't be normalized correctly
  34580. super({ type: 'document', ...defaults });
  34581. if (!this.nodes) {
  34582. this.nodes = [];
  34583. }
  34584. }
  34585. toResult(opts = {}) {
  34586. let lazy = new LazyResult(new Processor(), this, opts);
  34587. return lazy.stringify()
  34588. }
  34589. }
  34590. Document.registerLazyResult = dependant => {
  34591. LazyResult = dependant;
  34592. };
  34593. Document.registerProcessor = dependant => {
  34594. Processor = dependant;
  34595. };
  34596. document = Document;
  34597. Document.default = Document;
  34598. return document;
  34599. }
  34600. var nonSecure;
  34601. var hasRequiredNonSecure;
  34602. function requireNonSecure () {
  34603. if (hasRequiredNonSecure) return nonSecure;
  34604. hasRequiredNonSecure = 1;
  34605. let urlAlphabet =
  34606. 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
  34607. let customAlphabet = (alphabet, defaultSize = 21) => {
  34608. return (size = defaultSize) => {
  34609. let id = '';
  34610. let i = size | 0;
  34611. while (i-- > 0) {
  34612. id += alphabet[(Math.random() * alphabet.length) | 0];
  34613. }
  34614. return id
  34615. }
  34616. };
  34617. let nanoid = (size = 21) => {
  34618. let id = '';
  34619. let i = size | 0;
  34620. while (i-- > 0) {
  34621. id += urlAlphabet[(Math.random() * 64) | 0];
  34622. }
  34623. return id
  34624. };
  34625. nonSecure = { nanoid, customAlphabet };
  34626. return nonSecure;
  34627. }
  34628. var require$$2 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_url$1);
  34629. var previousMap;
  34630. var hasRequiredPreviousMap;
  34631. function requirePreviousMap () {
  34632. if (hasRequiredPreviousMap) return previousMap;
  34633. hasRequiredPreviousMap = 1;
  34634. let { existsSync, readFileSync } = require$$0$1;
  34635. let { dirname, isAbsolute, join, relative, sep } = require$$1;
  34636. let { SourceMapConsumer, SourceMapGenerator } = /*@__PURE__*/ requireSourceMap$1();
  34637. function fromBase64(str) {
  34638. if (Buffer$1) {
  34639. return Buffer$1.from(str, 'base64').toString()
  34640. } else {
  34641. /* c8 ignore next 2 */
  34642. return window.atob(str)
  34643. }
  34644. }
  34645. class PreviousMap {
  34646. constructor(css, opts) {
  34647. if (opts.map === false) return
  34648. if (opts.unsafeMap) this.unsafeMap = true;
  34649. this.loadAnnotation(css);
  34650. this.inline = this.startWith(this.annotation, 'data:');
  34651. let prev = opts.map ? opts.map.prev : undefined;
  34652. let text = this.loadMap(opts.from, prev);
  34653. if (!this.mapFile && opts.from) {
  34654. this.mapFile = opts.from;
  34655. }
  34656. if (this.mapFile) this.root = dirname(this.mapFile);
  34657. if (text) this.text = text;
  34658. }
  34659. consumer() {
  34660. if (!this.consumerCache) {
  34661. this.consumerCache = new SourceMapConsumer(this.json || this.text);
  34662. }
  34663. return this.consumerCache
  34664. }
  34665. decodeInline(text) {
  34666. let baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/;
  34667. let baseUri = /^data:application\/json;base64,/;
  34668. let charsetUri = /^data:application\/json;charset=utf-?8,/;
  34669. let uri = /^data:application\/json,/;
  34670. let uriMatch = text.match(charsetUri) || text.match(uri);
  34671. if (uriMatch) {
  34672. return decodeURIComponent(text.substr(uriMatch[0].length))
  34673. }
  34674. let baseUriMatch = text.match(baseCharsetUri) || text.match(baseUri);
  34675. if (baseUriMatch) {
  34676. return fromBase64(text.substr(baseUriMatch[0].length))
  34677. }
  34678. let encoding = text.slice('data:application/json;'.length);
  34679. encoding = encoding.slice(0, encoding.indexOf(','));
  34680. throw new Error('Unsupported source map encoding ' + encoding)
  34681. }
  34682. getAnnotationURL(sourceMapString) {
  34683. return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, '').trim()
  34684. }
  34685. isMap(map) {
  34686. if (typeof map !== 'object') return false
  34687. return (
  34688. typeof map.mappings === 'string' ||
  34689. typeof map._mappings === 'string' ||
  34690. Array.isArray(map.sections)
  34691. )
  34692. }
  34693. loadAnnotation(css) {
  34694. let comments = css.match(/\/\*\s*# sourceMappingURL=/g);
  34695. if (!comments) return
  34696. // sourceMappingURLs from comments, strings, etc.
  34697. let start = css.lastIndexOf(comments.pop());
  34698. let end = css.indexOf('*/', start);
  34699. if (start > -1 && end > -1) {
  34700. // Locate the last sourceMappingURL to avoid pickin
  34701. this.annotation = this.getAnnotationURL(css.substring(start, end));
  34702. }
  34703. }
  34704. loadFile(path, cssFile, trusted) {
  34705. if (!trusted && !this.unsafeMap) {
  34706. if (!/\.map$/i.test(path)) return undefined
  34707. if (!cssFile) return undefined
  34708. let rel = relative(dirname(cssFile), path);
  34709. if (rel === '..' || rel.startsWith('..' + sep) || isAbsolute(rel)) {
  34710. return undefined
  34711. }
  34712. }
  34713. this.root = dirname(path);
  34714. if (existsSync(path)) {
  34715. this.mapFile = path;
  34716. return readFileSync(path, 'utf-8').toString().trim()
  34717. }
  34718. }
  34719. loadMap(file, prev) {
  34720. if (prev === false) return false
  34721. if (prev) {
  34722. if (typeof prev === 'string') {
  34723. return prev
  34724. } else if (typeof prev === 'function') {
  34725. let prevPath = prev(file);
  34726. if (prevPath) {
  34727. let map = this.loadFile(prevPath, file, true);
  34728. if (!map) {
  34729. throw new Error(
  34730. 'Unable to load previous source map: ' + prevPath.toString()
  34731. )
  34732. }
  34733. return map
  34734. }
  34735. } else if (prev instanceof SourceMapConsumer) {
  34736. return SourceMapGenerator.fromSourceMap(prev).toString()
  34737. } else if (prev instanceof SourceMapGenerator) {
  34738. return prev.toString()
  34739. } else if (this.isMap(prev)) {
  34740. return JSON.stringify(prev)
  34741. } else {
  34742. throw new Error(
  34743. 'Unsupported previous source map format: ' + prev.toString()
  34744. )
  34745. }
  34746. } else if (this.inline) {
  34747. return this.decodeInline(this.annotation)
  34748. } else if (this.annotation) {
  34749. let map = this.annotation;
  34750. if (file) map = join(dirname(file), map);
  34751. let unknown = this.loadFile(map, file, false);
  34752. if (unknown) {
  34753. try {
  34754. /* c8 ignore next 4 */
  34755. this.json = JSON.parse(unknown.replace(/^\)]}'[^\n]*\n/, ''));
  34756. } catch {
  34757. return undefined
  34758. }
  34759. }
  34760. return unknown
  34761. }
  34762. }
  34763. startWith(string, start) {
  34764. if (!string) return false
  34765. return string.substr(0, start.length) === start
  34766. }
  34767. withContent() {
  34768. return !!(
  34769. this.consumer().sourcesContent &&
  34770. this.consumer().sourcesContent.length > 0
  34771. )
  34772. }
  34773. }
  34774. previousMap = PreviousMap;
  34775. PreviousMap.default = PreviousMap;
  34776. return previousMap;
  34777. }
  34778. var input;
  34779. var hasRequiredInput;
  34780. function requireInput () {
  34781. if (hasRequiredInput) return input;
  34782. hasRequiredInput = 1;
  34783. let { nanoid } = /*@__PURE__*/ requireNonSecure();
  34784. let { isAbsolute, resolve } = require$$1;
  34785. let { SourceMapConsumer, SourceMapGenerator } = /*@__PURE__*/ requireSourceMap$1();
  34786. let { fileURLToPath, pathToFileURL } = require$$2;
  34787. let CssSyntaxError = /*@__PURE__*/ requireCssSyntaxError();
  34788. let PreviousMap = /*@__PURE__*/ requirePreviousMap();
  34789. let terminalHighlight = /*@__PURE__*/ requireTerminalHighlight();
  34790. let lineToIndexCache = Symbol('lineToIndexCache');
  34791. let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator);
  34792. let pathAvailable = Boolean(resolve && isAbsolute);
  34793. function getLineToIndex(input) {
  34794. if (input[lineToIndexCache]) return input[lineToIndexCache]
  34795. let lines = input.css.split('\n');
  34796. let lineToIndex = new Array(lines.length);
  34797. let prevIndex = 0;
  34798. for (let i = 0, l = lines.length; i < l; i++) {
  34799. lineToIndex[i] = prevIndex;
  34800. prevIndex += lines[i].length + 1;
  34801. }
  34802. input[lineToIndexCache] = lineToIndex;
  34803. return lineToIndex
  34804. }
  34805. class Input {
  34806. get from() {
  34807. return this.file || this.id
  34808. }
  34809. constructor(css, opts = {}) {
  34810. if (
  34811. css === null ||
  34812. typeof css === 'undefined' ||
  34813. (typeof css === 'object' && !css.toString)
  34814. ) {
  34815. throw new Error(`PostCSS received ${css} instead of CSS string`)
  34816. }
  34817. this.css = css.toString();
  34818. if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') {
  34819. this.hasBOM = true;
  34820. this.css = this.css.slice(1);
  34821. } else {
  34822. this.hasBOM = false;
  34823. }
  34824. this.document = this.css;
  34825. if (opts.document) this.document = opts.document.toString();
  34826. if (opts.from) {
  34827. if (
  34828. !pathAvailable ||
  34829. /^\w+:\/\//.test(opts.from) ||
  34830. isAbsolute(opts.from)
  34831. ) {
  34832. this.file = opts.from;
  34833. } else {
  34834. this.file = resolve(opts.from);
  34835. }
  34836. }
  34837. if (pathAvailable && sourceMapAvailable) {
  34838. let map = new PreviousMap(this.css, opts);
  34839. if (map.text) {
  34840. this.map = map;
  34841. let file = map.consumer().file;
  34842. if (!this.file && file) this.file = this.mapResolve(file);
  34843. }
  34844. }
  34845. if (!this.file) {
  34846. this.id = '<input css ' + nanoid(6) + '>';
  34847. }
  34848. if (this.map) this.map.file = this.from;
  34849. }
  34850. error(message, line, column, opts = {}) {
  34851. let endColumn, endLine, endOffset, offset, result;
  34852. if (line && typeof line === 'object') {
  34853. let start = line;
  34854. let end = column;
  34855. if (typeof start.offset === 'number') {
  34856. offset = start.offset;
  34857. let pos = this.fromOffset(offset);
  34858. line = pos.line;
  34859. column = pos.col;
  34860. } else {
  34861. line = start.line;
  34862. column = start.column;
  34863. offset = this.fromLineAndColumn(line, column);
  34864. }
  34865. if (typeof end.offset === 'number') {
  34866. endOffset = end.offset;
  34867. let pos = this.fromOffset(endOffset);
  34868. endLine = pos.line;
  34869. endColumn = pos.col;
  34870. } else {
  34871. endLine = end.line;
  34872. endColumn = end.column;
  34873. endOffset = this.fromLineAndColumn(end.line, end.column);
  34874. }
  34875. } else if (!column) {
  34876. offset = line;
  34877. let pos = this.fromOffset(offset);
  34878. line = pos.line;
  34879. column = pos.col;
  34880. } else {
  34881. offset = this.fromLineAndColumn(line, column);
  34882. }
  34883. let origin = this.origin(line, column, endLine, endColumn);
  34884. if (origin) {
  34885. result = new CssSyntaxError(
  34886. message,
  34887. origin.endLine === undefined
  34888. ? origin.line
  34889. : { column: origin.column, line: origin.line },
  34890. origin.endLine === undefined
  34891. ? origin.column
  34892. : { column: origin.endColumn, line: origin.endLine },
  34893. origin.source,
  34894. origin.file,
  34895. opts.plugin
  34896. );
  34897. } else {
  34898. result = new CssSyntaxError(
  34899. message,
  34900. endLine === undefined ? line : { column, line },
  34901. endLine === undefined ? column : { column: endColumn, line: endLine },
  34902. this.css,
  34903. this.file,
  34904. opts.plugin
  34905. );
  34906. }
  34907. result.input = {
  34908. column,
  34909. endColumn,
  34910. endLine,
  34911. endOffset,
  34912. line,
  34913. offset,
  34914. source: this.css
  34915. };
  34916. if (this.file) {
  34917. if (pathToFileURL) {
  34918. result.input.url = pathToFileURL(this.file).toString();
  34919. }
  34920. result.input.file = this.file;
  34921. }
  34922. return result
  34923. }
  34924. fromLineAndColumn(line, column) {
  34925. let lineToIndex = getLineToIndex(this);
  34926. let index = lineToIndex[line - 1];
  34927. return index + column - 1
  34928. }
  34929. fromOffset(offset) {
  34930. let lineToIndex = getLineToIndex(this);
  34931. let lastLine = lineToIndex[lineToIndex.length - 1];
  34932. let min = 0;
  34933. if (offset >= lastLine) {
  34934. min = lineToIndex.length - 1;
  34935. } else {
  34936. let max = lineToIndex.length - 2;
  34937. let mid;
  34938. while (min < max) {
  34939. mid = min + ((max - min) >> 1);
  34940. if (offset < lineToIndex[mid]) {
  34941. max = mid - 1;
  34942. } else if (offset >= lineToIndex[mid + 1]) {
  34943. min = mid + 1;
  34944. } else {
  34945. min = mid;
  34946. break
  34947. }
  34948. }
  34949. }
  34950. return {
  34951. col: offset - lineToIndex[min] + 1,
  34952. line: min + 1
  34953. }
  34954. }
  34955. mapResolve(file) {
  34956. if (/^\w+:\/\//.test(file)) {
  34957. return file
  34958. }
  34959. return resolve(this.map.consumer().sourceRoot || this.map.root || '.', file)
  34960. }
  34961. origin(line, column, endLine, endColumn) {
  34962. if (!this.map) return false
  34963. let consumer = this.map.consumer();
  34964. let from = consumer.originalPositionFor({ column: column - 1, line });
  34965. if (!from.source) return false
  34966. let to;
  34967. if (typeof endLine === 'number') {
  34968. let toPosition = consumer.originalPositionFor({
  34969. column: endColumn - 1,
  34970. line: endLine
  34971. });
  34972. // The source map may not have a mapping that covers the end position
  34973. // (`originalPositionFor()` then returns `null` for `line`/`column`
  34974. // instead of omitting them). Treat that the same as not requesting
  34975. // an end position at all, so `endLine`/`endColumn` stay a consistent
  34976. // `undefined` pair instead of a mix of `null` and a bogus number.
  34977. if (toPosition.source) to = toPosition;
  34978. }
  34979. let fromUrl;
  34980. if (isAbsolute(from.source)) {
  34981. fromUrl = pathToFileURL(from.source);
  34982. } else {
  34983. fromUrl = new URL(
  34984. from.source,
  34985. this.map.consumer().sourceRoot || pathToFileURL(this.map.mapFile)
  34986. );
  34987. }
  34988. let result = {
  34989. column: from.column + 1,
  34990. endColumn: to && to.column + 1,
  34991. endLine: to && to.line,
  34992. line: from.line,
  34993. url: fromUrl.toString()
  34994. };
  34995. if (fromUrl.protocol === 'file:') {
  34996. if (fileURLToPath) {
  34997. result.file = fileURLToPath(fromUrl);
  34998. } else {
  34999. /* c8 ignore next 2 */
  35000. throw new Error(`file: protocol is not available in this PostCSS build`)
  35001. }
  35002. }
  35003. let source = consumer.sourceContentFor(from.source);
  35004. if (source) result.source = source;
  35005. return result
  35006. }
  35007. toJSON() {
  35008. let json = {};
  35009. for (let name of ['hasBOM', 'css', 'file', 'id']) {
  35010. if (this[name] != null) {
  35011. json[name] = this[name];
  35012. }
  35013. }
  35014. if (this.map) {
  35015. json.map = { ...this.map };
  35016. if (json.map.consumerCache) {
  35017. json.map.consumerCache = undefined;
  35018. }
  35019. }
  35020. return json
  35021. }
  35022. }
  35023. input = Input;
  35024. Input.default = Input;
  35025. if (terminalHighlight && terminalHighlight.registerInput) {
  35026. terminalHighlight.registerInput(Input);
  35027. }
  35028. return input;
  35029. }
  35030. var root$1;
  35031. var hasRequiredRoot$1;
  35032. function requireRoot$1 () {
  35033. if (hasRequiredRoot$1) return root$1;
  35034. hasRequiredRoot$1 = 1;
  35035. let Container = /*@__PURE__*/ requireContainer$1();
  35036. let LazyResult, Processor;
  35037. class Root extends Container {
  35038. constructor(defaults) {
  35039. super(defaults);
  35040. this.type = 'root';
  35041. if (!this.nodes) this.nodes = [];
  35042. }
  35043. normalize(child, sample, type) {
  35044. let keepBefore = new Set();
  35045. for (let node of Array.isArray(child) ? child : [child]) {
  35046. if (
  35047. node &&
  35048. typeof node === 'object' &&
  35049. !node.parent &&
  35050. node.raws &&
  35051. typeof node.raws.before !== 'undefined'
  35052. ) {
  35053. keepBefore.add(node.raws);
  35054. }
  35055. }
  35056. let nodes = super.normalize(child);
  35057. if (sample) {
  35058. if (type === 'prepend') {
  35059. if (this.nodes.length > 1) {
  35060. sample.raws.before = this.nodes[1].raws.before;
  35061. } else {
  35062. delete sample.raws.before;
  35063. }
  35064. } else if (this.first !== sample) {
  35065. for (let node of nodes) {
  35066. if (!keepBefore.has(node.raws)) {
  35067. node.raws.before = sample.raws.before;
  35068. }
  35069. }
  35070. }
  35071. }
  35072. return nodes
  35073. }
  35074. removeChild(child, ignore) {
  35075. let index = this.index(child);
  35076. if (!ignore && index === 0 && this.nodes.length > 1) {
  35077. this.nodes[1].raws.before = this.nodes[index].raws.before;
  35078. }
  35079. return super.removeChild(child)
  35080. }
  35081. toResult(opts = {}) {
  35082. let lazy = new LazyResult(new Processor(), this, opts);
  35083. return lazy.stringify()
  35084. }
  35085. }
  35086. Root.registerLazyResult = dependant => {
  35087. LazyResult = dependant;
  35088. };
  35089. Root.registerProcessor = dependant => {
  35090. Processor = dependant;
  35091. };
  35092. root$1 = Root;
  35093. Root.default = Root;
  35094. Container.registerRoot(Root);
  35095. return root$1;
  35096. }
  35097. var list_1;
  35098. var hasRequiredList;
  35099. function requireList () {
  35100. if (hasRequiredList) return list_1;
  35101. hasRequiredList = 1;
  35102. let list = {
  35103. comma(string) {
  35104. return list.split(string, [','], true)
  35105. },
  35106. space(string) {
  35107. let spaces = [' ', '\n', '\t'];
  35108. return list.split(string, spaces)
  35109. },
  35110. split(string, separators, last) {
  35111. let array = [];
  35112. let current = '';
  35113. let split = false;
  35114. let func = 0;
  35115. let inQuote = false;
  35116. let prevQuote = '';
  35117. let escape = false;
  35118. for (let letter of string) {
  35119. if (escape) {
  35120. escape = false;
  35121. } else if (letter === '\\') {
  35122. escape = true;
  35123. } else if (inQuote) {
  35124. if (letter === prevQuote) {
  35125. inQuote = false;
  35126. }
  35127. } else if (letter === '"' || letter === "'") {
  35128. inQuote = true;
  35129. prevQuote = letter;
  35130. } else if (letter === '(') {
  35131. func += 1;
  35132. } else if (letter === ')') {
  35133. if (func > 0) func -= 1;
  35134. } else if (func === 0) {
  35135. if (separators.includes(letter)) split = true;
  35136. }
  35137. if (split) {
  35138. if (current !== '') array.push(current.trim());
  35139. current = '';
  35140. split = false;
  35141. } else {
  35142. current += letter;
  35143. }
  35144. }
  35145. if (last || current !== '') array.push(current.trim());
  35146. return array
  35147. }
  35148. };
  35149. list_1 = list;
  35150. list.default = list;
  35151. return list_1;
  35152. }
  35153. var rule;
  35154. var hasRequiredRule;
  35155. function requireRule () {
  35156. if (hasRequiredRule) return rule;
  35157. hasRequiredRule = 1;
  35158. let Container = /*@__PURE__*/ requireContainer$1();
  35159. let list = /*@__PURE__*/ requireList();
  35160. class Rule extends Container {
  35161. get selectors() {
  35162. return list.comma(this.selector)
  35163. }
  35164. set selectors(values) {
  35165. let match = this.selector ? this.selector.match(/,\s*/) : null;
  35166. let sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen');
  35167. this.selector = values.join(sep);
  35168. }
  35169. constructor(defaults) {
  35170. super(defaults);
  35171. this.type = 'rule';
  35172. if (!this.nodes) this.nodes = [];
  35173. }
  35174. }
  35175. rule = Rule;
  35176. Rule.default = Rule;
  35177. Container.registerRule(Rule);
  35178. return rule;
  35179. }
  35180. var fromJSON_1;
  35181. var hasRequiredFromJSON;
  35182. function requireFromJSON () {
  35183. if (hasRequiredFromJSON) return fromJSON_1;
  35184. hasRequiredFromJSON = 1;
  35185. let AtRule = /*@__PURE__*/ requireAtRule();
  35186. let Comment = /*@__PURE__*/ requireComment$1();
  35187. let Declaration = /*@__PURE__*/ requireDeclaration();
  35188. let Input = /*@__PURE__*/ requireInput();
  35189. let PreviousMap = /*@__PURE__*/ requirePreviousMap();
  35190. let Root = /*@__PURE__*/ requireRoot$1();
  35191. let Rule = /*@__PURE__*/ requireRule();
  35192. function hydrateInputs(json, inputs) {
  35193. if (!json.inputs) return inputs
  35194. return json.inputs.map(input => {
  35195. let inputHydrated = { ...input, __proto__: Input.prototype };
  35196. if (inputHydrated.map) {
  35197. inputHydrated.map = {
  35198. ...inputHydrated.map,
  35199. __proto__: PreviousMap.prototype
  35200. };
  35201. }
  35202. return inputHydrated
  35203. })
  35204. }
  35205. function constructNode(json, inputs, children) {
  35206. let defaults = { ...json };
  35207. delete defaults.inputs;
  35208. delete defaults.nodes;
  35209. if (defaults.source) {
  35210. let { inputId, ...source } = defaults.source;
  35211. defaults.source = source;
  35212. if (inputId != null) {
  35213. defaults.source.input = inputs[inputId];
  35214. }
  35215. }
  35216. let node;
  35217. if (defaults.type === 'root') {
  35218. node = new Root(defaults);
  35219. } else if (defaults.type === 'decl') {
  35220. node = new Declaration(defaults);
  35221. } else if (defaults.type === 'rule') {
  35222. node = new Rule(defaults);
  35223. } else if (defaults.type === 'comment') {
  35224. node = new Comment(defaults);
  35225. } else if (defaults.type === 'atrule') {
  35226. node = new AtRule(defaults);
  35227. } else {
  35228. throw new Error('Unknown node type: ' + json.type)
  35229. }
  35230. // Rehydrated children are attached after construction. Passing them
  35231. // through the container constructor would re-run insertion spacing
  35232. // normalization and overwrite each child's own `raws.before`.
  35233. if (children) {
  35234. node.nodes = children;
  35235. for (let child of children) child.parent = node;
  35236. }
  35237. return node
  35238. }
  35239. function fromJSON(json, inputs) {
  35240. if (Array.isArray(json)) return json.map(n => fromJSON(n))
  35241. // An explicit stack instead of recursive calls to survive deeply
  35242. // nested trees. Children are rehydrated before their parent node
  35243. // is constructed.
  35244. let result;
  35245. let stack = [
  35246. { childIndex: 0, children: [], inputs: hydrateInputs(json, inputs), json }
  35247. ];
  35248. while (stack.length > 0) {
  35249. let frame = stack[stack.length - 1];
  35250. let jsonNodes = frame.json.nodes;
  35251. if (jsonNodes && frame.childIndex < jsonNodes.length) {
  35252. let childJson = jsonNodes[frame.childIndex];
  35253. frame.childIndex += 1;
  35254. stack.push({
  35255. childIndex: 0,
  35256. children: [],
  35257. inputs: hydrateInputs(childJson, frame.inputs),
  35258. json: childJson
  35259. });
  35260. continue
  35261. }
  35262. stack.pop();
  35263. let node = constructNode(
  35264. frame.json,
  35265. frame.inputs,
  35266. jsonNodes ? frame.children : undefined
  35267. );
  35268. if (stack.length > 0) {
  35269. stack[stack.length - 1].children.push(node);
  35270. } else {
  35271. result = node;
  35272. }
  35273. }
  35274. return result
  35275. }
  35276. fromJSON_1 = fromJSON;
  35277. fromJSON.default = fromJSON;
  35278. return fromJSON_1;
  35279. }
  35280. var mapGenerator;
  35281. var hasRequiredMapGenerator;
  35282. function requireMapGenerator () {
  35283. if (hasRequiredMapGenerator) return mapGenerator;
  35284. hasRequiredMapGenerator = 1;
  35285. let { dirname, relative, resolve, sep } = require$$1;
  35286. let { SourceMapConsumer, SourceMapGenerator } = /*@__PURE__*/ requireSourceMap$1();
  35287. let { pathToFileURL } = require$$2;
  35288. let Input = /*@__PURE__*/ requireInput();
  35289. let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator);
  35290. let pathAvailable = Boolean(dirname && resolve && relative && sep);
  35291. class MapGenerator {
  35292. constructor(stringify, root, opts, cssString) {
  35293. this.stringify = stringify;
  35294. this.mapOpts = opts.map || {};
  35295. this.root = root;
  35296. this.opts = opts;
  35297. this.css = cssString;
  35298. this.originalCSS = cssString;
  35299. this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute;
  35300. this.memoizedFileURLs = new Map();
  35301. this.memoizedPaths = new Map();
  35302. this.memoizedURLs = new Map();
  35303. }
  35304. addAnnotation() {
  35305. let content;
  35306. if (this.isInline()) {
  35307. content =
  35308. 'data:application/json;base64,' + this.toBase64(this.map.toString());
  35309. } else if (typeof this.mapOpts.annotation === 'string') {
  35310. content = this.mapOpts.annotation;
  35311. } else if (typeof this.mapOpts.annotation === 'function') {
  35312. content = this.mapOpts.annotation(this.opts.to, this.root);
  35313. } else {
  35314. content = this.outputFile() + '.map';
  35315. }
  35316. let eol = '\n';
  35317. if (this.css.includes('\r\n')) eol = '\r\n';
  35318. this.css += eol + '/*# sourceMappingURL=' + content + ' */';
  35319. }
  35320. applyPrevMaps() {
  35321. for (let prev of this.previous()) {
  35322. let from = this.toUrl(this.path(prev.file));
  35323. let root = prev.root || dirname(prev.file);
  35324. let map;
  35325. if (this.mapOpts.sourcesContent === false) {
  35326. map = new SourceMapConsumer(prev.text);
  35327. if (map.sourcesContent) {
  35328. map.sourcesContent = null;
  35329. }
  35330. } else {
  35331. map = prev.consumer();
  35332. }
  35333. this.map.applySourceMap(map, from, this.toUrl(this.path(root)));
  35334. }
  35335. }
  35336. clearAnnotation() {
  35337. if (this.mapOpts.annotation === false) return
  35338. if (this.root) {
  35339. let node;
  35340. for (let i = this.root.nodes.length - 1; i >= 0; i--) {
  35341. node = this.root.nodes[i];
  35342. if (node.type !== 'comment') continue
  35343. if (node.text.startsWith('# sourceMappingURL=')) {
  35344. this.root.removeChild(i);
  35345. }
  35346. }
  35347. } else if (this.css) {
  35348. let startIndex;
  35349. while ((startIndex = this.css.lastIndexOf('/*#')) !== -1) {
  35350. let endIndex = this.css.indexOf('*/', startIndex + 3);
  35351. if (endIndex === -1) break
  35352. while (startIndex > 0 && this.css[startIndex - 1] === '\n') {
  35353. startIndex--;
  35354. }
  35355. this.css = this.css.slice(0, startIndex) + this.css.slice(endIndex + 2);
  35356. }
  35357. }
  35358. }
  35359. generate() {
  35360. this.clearAnnotation();
  35361. if (pathAvailable && sourceMapAvailable && this.isMap()) {
  35362. return this.generateMap()
  35363. } else {
  35364. let result = '';
  35365. this.stringify(this.root, i => {
  35366. result += i;
  35367. });
  35368. return [result]
  35369. }
  35370. }
  35371. generateMap() {
  35372. if (this.root) {
  35373. this.generateString();
  35374. } else if (this.previous().length === 1) {
  35375. let prev = this.previous()[0].consumer();
  35376. prev.file = this.outputFile();
  35377. this.map = SourceMapGenerator.fromSourceMap(prev, {
  35378. ignoreInvalidMapping: true
  35379. });
  35380. } else {
  35381. this.map = new SourceMapGenerator({
  35382. file: this.outputFile(),
  35383. ignoreInvalidMapping: true
  35384. });
  35385. this.map.addMapping({
  35386. generated: { column: 0, line: 1 },
  35387. original: { column: 0, line: 1 },
  35388. source: this.opts.from
  35389. ? this.toUrl(this.path(this.opts.from))
  35390. : '<no source>'
  35391. });
  35392. }
  35393. if (this.isSourcesContent()) this.setSourcesContent();
  35394. if (this.root && this.previous().length > 0) this.applyPrevMaps();
  35395. if (this.isAnnotation()) this.addAnnotation();
  35396. if (this.isInline()) {
  35397. return [this.css]
  35398. } else {
  35399. return [this.css, this.map]
  35400. }
  35401. }
  35402. generateString() {
  35403. this.css = '';
  35404. this.map = new SourceMapGenerator({
  35405. file: this.outputFile(),
  35406. ignoreInvalidMapping: true
  35407. });
  35408. let line = 1;
  35409. let column = 1;
  35410. let noSource = '<no source>';
  35411. let mapping = {
  35412. generated: { column: 0, line: 0 },
  35413. original: { column: 0, line: 0 },
  35414. source: ''
  35415. };
  35416. let last, lines;
  35417. this.stringify(this.root, (str, node, type) => {
  35418. this.css += str;
  35419. if (node && type !== 'end') {
  35420. mapping.generated.line = line;
  35421. mapping.generated.column = column - 1;
  35422. if (node.source && node.source.start) {
  35423. mapping.source = this.sourcePath(node);
  35424. mapping.original.line = node.source.start.line;
  35425. mapping.original.column = node.source.start.column - 1;
  35426. this.map.addMapping(mapping);
  35427. } else {
  35428. mapping.source = noSource;
  35429. mapping.original.line = 1;
  35430. mapping.original.column = 0;
  35431. this.map.addMapping(mapping);
  35432. }
  35433. }
  35434. lines = str.match(/\n/g);
  35435. if (lines) {
  35436. line += lines.length;
  35437. last = str.lastIndexOf('\n');
  35438. column = str.length - last;
  35439. } else {
  35440. column += str.length;
  35441. }
  35442. if (node && type !== 'start') {
  35443. let p = node.parent || { raws: {} };
  35444. let childless =
  35445. node.type === 'decl' || (node.type === 'atrule' && !node.nodes);
  35446. if (!childless || node !== p.last || p.raws.semicolon) {
  35447. if (node.source && node.source.end) {
  35448. mapping.source = this.sourcePath(node);
  35449. mapping.original.line = node.source.end.line;
  35450. mapping.original.column = node.source.end.column - 1;
  35451. mapping.generated.line = line;
  35452. mapping.generated.column = column - 2;
  35453. this.map.addMapping(mapping);
  35454. } else {
  35455. mapping.source = noSource;
  35456. mapping.original.line = 1;
  35457. mapping.original.column = 0;
  35458. mapping.generated.line = line;
  35459. mapping.generated.column = column - 1;
  35460. this.map.addMapping(mapping);
  35461. }
  35462. }
  35463. }
  35464. });
  35465. }
  35466. isAnnotation() {
  35467. if (this.isInline()) {
  35468. return true
  35469. }
  35470. if (typeof this.mapOpts.annotation !== 'undefined') {
  35471. return this.mapOpts.annotation
  35472. }
  35473. if (this.previous().length) {
  35474. return this.previous().some(i => i.annotation)
  35475. }
  35476. return true
  35477. }
  35478. isInline() {
  35479. if (typeof this.mapOpts.inline !== 'undefined') {
  35480. return this.mapOpts.inline
  35481. }
  35482. let annotation = this.mapOpts.annotation;
  35483. if (typeof annotation !== 'undefined' && annotation !== true) {
  35484. return false
  35485. }
  35486. if (this.previous().length) {
  35487. return this.previous().some(i => i.inline)
  35488. }
  35489. return true
  35490. }
  35491. isMap() {
  35492. if (typeof this.opts.map !== 'undefined') {
  35493. return !!this.opts.map
  35494. }
  35495. return this.previous().length > 0
  35496. }
  35497. isSourcesContent() {
  35498. if (typeof this.mapOpts.sourcesContent !== 'undefined') {
  35499. return this.mapOpts.sourcesContent
  35500. }
  35501. if (this.previous().length) {
  35502. return this.previous().some(i => i.withContent())
  35503. }
  35504. return true
  35505. }
  35506. outputFile() {
  35507. if (this.opts.to) {
  35508. return this.path(this.opts.to)
  35509. } else if (this.opts.from) {
  35510. return this.path(this.opts.from)
  35511. } else {
  35512. return 'to.css'
  35513. }
  35514. }
  35515. path(file) {
  35516. if (this.mapOpts.absolute) return file
  35517. if (file.charCodeAt(0) === 60 /* `<` */) return file
  35518. if (/^\w+:\/\//.test(file)) return file
  35519. let cached = this.memoizedPaths.get(file);
  35520. if (cached) return cached
  35521. let from = this.opts.to ? dirname(this.opts.to) : '.';
  35522. if (typeof this.mapOpts.annotation === 'string') {
  35523. from = dirname(resolve(from, this.mapOpts.annotation));
  35524. }
  35525. let path = relative(from, file);
  35526. this.memoizedPaths.set(file, path);
  35527. return path
  35528. }
  35529. previous() {
  35530. if (!this.previousMaps) {
  35531. this.previousMaps = [];
  35532. if (this.root) {
  35533. this.root.walk(node => {
  35534. if (node.source && node.source.input.map) {
  35535. let map = node.source.input.map;
  35536. if (!this.previousMaps.includes(map)) {
  35537. this.previousMaps.push(map);
  35538. }
  35539. }
  35540. });
  35541. } else {
  35542. let input = new Input(this.originalCSS, this.opts);
  35543. if (input.map) this.previousMaps.push(input.map);
  35544. }
  35545. }
  35546. return this.previousMaps
  35547. }
  35548. setSourcesContent() {
  35549. let already = {};
  35550. if (this.root) {
  35551. this.root.walk(node => {
  35552. if (node.source) {
  35553. let from = node.source.input.from;
  35554. if (from && !already[from]) {
  35555. already[from] = true;
  35556. let fromUrl = this.usesFileUrls
  35557. ? this.toFileUrl(from)
  35558. : this.toUrl(this.path(from));
  35559. this.map.setSourceContent(fromUrl, node.source.input.css);
  35560. }
  35561. }
  35562. });
  35563. } else if (this.css) {
  35564. let from = this.opts.from
  35565. ? this.toUrl(this.path(this.opts.from))
  35566. : '<no source>';
  35567. this.map.setSourceContent(from, this.css);
  35568. }
  35569. }
  35570. sourcePath(node) {
  35571. if (this.mapOpts.from) {
  35572. return this.toUrl(this.mapOpts.from)
  35573. } else if (this.usesFileUrls) {
  35574. return this.toFileUrl(node.source.input.from)
  35575. } else {
  35576. return this.toUrl(this.path(node.source.input.from))
  35577. }
  35578. }
  35579. toBase64(str) {
  35580. if (Buffer$1) {
  35581. return Buffer$1.from(str).toString('base64')
  35582. } else {
  35583. return window.btoa(unescape(encodeURIComponent(str)))
  35584. }
  35585. }
  35586. toFileUrl(path) {
  35587. let cached = this.memoizedFileURLs.get(path);
  35588. if (cached) return cached
  35589. if (pathToFileURL) {
  35590. let fileURL = pathToFileURL(path).toString();
  35591. this.memoizedFileURLs.set(path, fileURL);
  35592. return fileURL
  35593. } else {
  35594. throw new Error(
  35595. '`map.absolute` option is not available in this PostCSS build'
  35596. )
  35597. }
  35598. }
  35599. toUrl(path) {
  35600. let cached = this.memoizedURLs.get(path);
  35601. if (cached) return cached
  35602. if (sep === '\\') {
  35603. path = path.replace(/\\/g, '/');
  35604. }
  35605. let url = encodeURI(path).replace(/[#?]/g, encodeURIComponent);
  35606. this.memoizedURLs.set(path, url);
  35607. return url
  35608. }
  35609. }
  35610. mapGenerator = MapGenerator;
  35611. return mapGenerator;
  35612. }
  35613. var parser$1;
  35614. var hasRequiredParser$1;
  35615. function requireParser$1 () {
  35616. if (hasRequiredParser$1) return parser$1;
  35617. hasRequiredParser$1 = 1;
  35618. let AtRule = /*@__PURE__*/ requireAtRule();
  35619. let Comment = /*@__PURE__*/ requireComment$1();
  35620. let Declaration = /*@__PURE__*/ requireDeclaration();
  35621. let Root = /*@__PURE__*/ requireRoot$1();
  35622. let Rule = /*@__PURE__*/ requireRule();
  35623. let tokenizer = /*@__PURE__*/ requireTokenize$1();
  35624. const SAFE_COMMENT_NEIGHBOR = {
  35625. empty: true,
  35626. space: true
  35627. };
  35628. function findLastWithPosition(tokens) {
  35629. for (let i = tokens.length - 1; i >= 0; i--) {
  35630. let token = tokens[i];
  35631. let pos = token[3] || token[2];
  35632. if (pos) return pos
  35633. }
  35634. }
  35635. function tokensToString(tokens, from, to) {
  35636. let result = '';
  35637. for (let i = from; i < to; i++) result += tokens[i][1];
  35638. return result
  35639. }
  35640. class Parser {
  35641. constructor(input) {
  35642. this.input = input;
  35643. this.root = new Root();
  35644. this.current = this.root;
  35645. this.spaces = '';
  35646. this.semicolon = false;
  35647. this.createTokenizer();
  35648. this.root.source = { input, start: { column: 1, line: 1, offset: 0 } };
  35649. }
  35650. atrule(token) {
  35651. let node = new AtRule();
  35652. node.name = token[1].slice(1);
  35653. if (node.name === '') {
  35654. this.unnamedAtrule(node, token);
  35655. }
  35656. this.init(node, token[2]);
  35657. let type;
  35658. let prev;
  35659. let shift;
  35660. let last = false;
  35661. let open = false;
  35662. let params = [];
  35663. let brackets = [];
  35664. while (!this.tokenizer.endOfFile()) {
  35665. token = this.tokenizer.nextToken();
  35666. type = token[0];
  35667. if (type === '(' || type === '[') {
  35668. brackets.push(type === '(' ? ')' : ']');
  35669. } else if (type === '{' && brackets.length > 0) {
  35670. brackets.push('}');
  35671. } else if (type === brackets[brackets.length - 1]) {
  35672. brackets.pop();
  35673. }
  35674. if (brackets.length === 0) {
  35675. if (type === ';') {
  35676. node.source.end = this.getPosition(token[2]);
  35677. node.source.end.offset++;
  35678. this.semicolon = true;
  35679. break
  35680. } else if (type === '{') {
  35681. open = true;
  35682. break
  35683. } else if (type === '}') {
  35684. if (params.length > 0) {
  35685. shift = params.length - 1;
  35686. prev = params[shift];
  35687. while (prev && prev[0] === 'space') {
  35688. prev = params[--shift];
  35689. }
  35690. if (prev) {
  35691. node.source.end = this.getPosition(prev[3] || prev[2]);
  35692. node.source.end.offset++;
  35693. }
  35694. }
  35695. this.end(token);
  35696. break
  35697. } else {
  35698. params.push(token);
  35699. }
  35700. } else {
  35701. params.push(token);
  35702. }
  35703. if (this.tokenizer.endOfFile()) {
  35704. last = true;
  35705. break
  35706. }
  35707. }
  35708. node.raws.between = this.spacesAndCommentsFromEnd(params);
  35709. if (params.length) {
  35710. node.raws.afterName = this.spacesAndCommentsFromStart(params);
  35711. this.raw(node, 'params', params);
  35712. if (last) {
  35713. token = params[params.length - 1];
  35714. node.source.end = this.getPosition(token[3] || token[2]);
  35715. node.source.end.offset++;
  35716. this.spaces = node.raws.between;
  35717. node.raws.between = '';
  35718. }
  35719. } else {
  35720. node.raws.afterName = '';
  35721. node.params = '';
  35722. }
  35723. if (open) {
  35724. node.nodes = [];
  35725. this.current = node;
  35726. }
  35727. }
  35728. checkMissedSemicolon(tokens) {
  35729. let colon = this.colon(tokens);
  35730. if (colon === false) return
  35731. let founded = 0;
  35732. let token;
  35733. for (let j = colon - 1; j >= 0; j--) {
  35734. token = tokens[j];
  35735. if (token[0] !== 'space') {
  35736. founded += 1;
  35737. if (founded === 2) break
  35738. }
  35739. }
  35740. // If the token is a word, e.g. `!important`, `red` or any other valid
  35741. // property's value. Then we need to return the colon after that word
  35742. // token. [3] is the "end" colon of that word. And because we need it
  35743. // after that one we do +1 to get the next one.
  35744. throw this.input.error(
  35745. 'Missed semicolon',
  35746. token[0] === 'word' ? token[3] + 1 : token[2]
  35747. )
  35748. }
  35749. colon(tokens) {
  35750. let brackets = 0;
  35751. let prev, token, type;
  35752. for (let [i, element] of tokens.entries()) {
  35753. token = element;
  35754. type = token[0];
  35755. if (type === '(') {
  35756. brackets += 1;
  35757. }
  35758. if (type === ')') {
  35759. brackets -= 1;
  35760. }
  35761. if (brackets === 0 && type === ':') {
  35762. if (!prev) {
  35763. this.doubleColon(token);
  35764. } else if (prev[0] === 'word' && prev[1] === 'progid') {
  35765. continue
  35766. } else {
  35767. return i
  35768. }
  35769. }
  35770. prev = token;
  35771. }
  35772. return false
  35773. }
  35774. comment(token) {
  35775. let node = new Comment();
  35776. this.init(node, token[2]);
  35777. node.source.end = this.getPosition(token[3] || token[2]);
  35778. node.source.end.offset++;
  35779. let text = token[1].slice(2, -2);
  35780. if (!text.trim()) {
  35781. node.text = '';
  35782. node.raws.left = text;
  35783. node.raws.right = '';
  35784. } else {
  35785. let match = text.match(/^(\s*)([^]*\S)(\s*)$/);
  35786. node.text = match[2];
  35787. node.raws.left = match[1];
  35788. node.raws.right = match[3];
  35789. }
  35790. }
  35791. createTokenizer() {
  35792. this.tokenizer = tokenizer(this.input);
  35793. }
  35794. decl(tokens, customProperty) {
  35795. let node = new Declaration();
  35796. this.init(node, tokens[0][2]);
  35797. let last = tokens[tokens.length - 1];
  35798. if (last[0] === ';') {
  35799. this.semicolon = true;
  35800. tokens.pop();
  35801. }
  35802. node.source.end = this.getPosition(
  35803. last[3] || last[2] || findLastWithPosition(tokens)
  35804. );
  35805. node.source.end.offset++;
  35806. let start = 0;
  35807. while (tokens[start][0] !== 'word') {
  35808. if (start === tokens.length - 1) this.unknownWord([tokens[start]]);
  35809. start++;
  35810. }
  35811. node.raws.before += tokensToString(tokens, 0, start);
  35812. node.source.start = this.getPosition(tokens[start][2]);
  35813. let propStart = start;
  35814. while (start < tokens.length) {
  35815. let type = tokens[start][0];
  35816. if (type === ':' || type === 'space' || type === 'comment') {
  35817. break
  35818. }
  35819. start++;
  35820. }
  35821. node.prop = tokensToString(tokens, propStart, start);
  35822. let betweenStart = start;
  35823. let token;
  35824. while (start < tokens.length) {
  35825. token = tokens[start];
  35826. start++;
  35827. if (token[0] === ':') break
  35828. if (token[0] === 'word' && /\w/.test(token[1])) {
  35829. this.unknownWord([token]);
  35830. }
  35831. }
  35832. node.raws.between = tokensToString(tokens, betweenStart, start);
  35833. if (node.prop[0] === '_' || node.prop[0] === '*') {
  35834. node.raws.before += node.prop[0];
  35835. node.prop = node.prop.slice(1);
  35836. }
  35837. let firstSpacesStart = start;
  35838. while (start < tokens.length) {
  35839. let next = tokens[start][0];
  35840. if (next !== 'space' && next !== 'comment') break
  35841. start++;
  35842. }
  35843. let firstSpaces = tokens.slice(firstSpacesStart, start);
  35844. tokens = tokens.slice(start);
  35845. this.precheckMissedSemicolon(tokens);
  35846. for (let i = tokens.length - 1; i >= 0; i--) {
  35847. token = tokens[i];
  35848. if (token[1].toLowerCase() === '!important') {
  35849. node.important = true;
  35850. let string = this.stringFrom(tokens, i);
  35851. string = this.spacesFromEnd(tokens) + string;
  35852. if (string !== ' !important') node.raws.important = string;
  35853. break
  35854. } else if (token[1].toLowerCase() === 'important') {
  35855. let cache = tokens.slice(0);
  35856. let str = '';
  35857. for (let j = i; j > 0; j--) {
  35858. let type = cache[j][0];
  35859. if (str.trim().startsWith('!') && type !== 'space') {
  35860. break
  35861. }
  35862. str = cache.pop()[1] + str;
  35863. }
  35864. if (str.trim().startsWith('!')) {
  35865. node.important = true;
  35866. node.raws.important = str;
  35867. tokens = cache;
  35868. }
  35869. }
  35870. if (token[0] !== 'space' && token[0] !== 'comment') {
  35871. break
  35872. }
  35873. }
  35874. let hasWord = tokens.some(i => i[0] !== 'space' && i[0] !== 'comment');
  35875. if (hasWord) {
  35876. node.raws.between += firstSpaces.map(i => i[1]).join('');
  35877. firstSpaces = [];
  35878. }
  35879. this.raw(node, 'value', firstSpaces.concat(tokens), customProperty);
  35880. if (node.value.includes(':') && !customProperty) {
  35881. this.checkMissedSemicolon(tokens);
  35882. }
  35883. }
  35884. doubleColon(token) {
  35885. throw this.input.error(
  35886. 'Double colon',
  35887. { offset: token[2] },
  35888. { offset: token[2] + token[1].length }
  35889. )
  35890. }
  35891. emptyRule(token) {
  35892. let node = new Rule();
  35893. this.init(node, token[2]);
  35894. node.selector = '';
  35895. node.raws.between = '';
  35896. this.current = node;
  35897. }
  35898. end(token) {
  35899. if (this.current.nodes && this.current.nodes.length) {
  35900. this.current.raws.semicolon = this.semicolon;
  35901. }
  35902. this.semicolon = false;
  35903. this.current.raws.after = (this.current.raws.after || '') + this.spaces;
  35904. this.spaces = '';
  35905. if (this.current.parent) {
  35906. this.current.source.end = this.getPosition(token[2]);
  35907. this.current.source.end.offset++;
  35908. this.current = this.current.parent;
  35909. } else {
  35910. this.unexpectedClose(token);
  35911. }
  35912. }
  35913. endFile() {
  35914. if (this.current.parent) this.unclosedBlock();
  35915. if (this.current.nodes && this.current.nodes.length) {
  35916. this.current.raws.semicolon = this.semicolon;
  35917. }
  35918. this.current.raws.after = (this.current.raws.after || '') + this.spaces;
  35919. this.root.source.end = this.getPosition(this.tokenizer.position());
  35920. }
  35921. freeSemicolon(token) {
  35922. this.spaces += token[1];
  35923. if (this.current.nodes) {
  35924. let prev = this.current.nodes[this.current.nodes.length - 1];
  35925. if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) {
  35926. prev.raws.ownSemicolon = this.spaces;
  35927. this.spaces = '';
  35928. prev.source.end = this.getPosition(token[2]);
  35929. prev.source.end.offset += prev.raws.ownSemicolon.length;
  35930. }
  35931. }
  35932. }
  35933. // Helpers
  35934. getPosition(offset) {
  35935. let pos = this.input.fromOffset(offset);
  35936. return {
  35937. column: pos.col,
  35938. line: pos.line,
  35939. offset
  35940. }
  35941. }
  35942. init(node, offset) {
  35943. this.current.push(node);
  35944. node.source = {
  35945. input: this.input,
  35946. start: this.getPosition(offset)
  35947. };
  35948. node.raws.before = this.spaces;
  35949. this.spaces = '';
  35950. if (node.type !== 'comment') this.semicolon = false;
  35951. }
  35952. other(start) {
  35953. let end = false;
  35954. let type = null;
  35955. let colon = false;
  35956. let bracket = null;
  35957. let brackets = [];
  35958. let customProperty = start[1].startsWith('--');
  35959. let tokens = [];
  35960. let token = start;
  35961. while (token) {
  35962. type = token[0];
  35963. tokens.push(token);
  35964. if (type === '(' || type === '[') {
  35965. if (!bracket) bracket = token;
  35966. brackets.push(type === '(' ? ')' : ']');
  35967. } else if (customProperty && colon && type === '{') {
  35968. if (!bracket) bracket = token;
  35969. brackets.push('}');
  35970. } else if (brackets.length === 0) {
  35971. if (type === ';') {
  35972. if (colon) {
  35973. this.decl(tokens, customProperty);
  35974. return
  35975. } else {
  35976. break
  35977. }
  35978. } else if (type === '{') {
  35979. this.rule(tokens);
  35980. return
  35981. } else if (type === '}') {
  35982. this.tokenizer.back(tokens.pop());
  35983. end = true;
  35984. break
  35985. } else if (type === ':') {
  35986. colon = true;
  35987. }
  35988. } else if (type === brackets[brackets.length - 1]) {
  35989. brackets.pop();
  35990. if (brackets.length === 0) bracket = null;
  35991. }
  35992. token = this.tokenizer.nextToken();
  35993. }
  35994. if (this.tokenizer.endOfFile()) end = true;
  35995. if (brackets.length > 0) this.unclosedBracket(bracket);
  35996. if (end && colon) {
  35997. if (!customProperty) {
  35998. while (tokens.length) {
  35999. token = tokens[tokens.length - 1][0];
  36000. if (token !== 'space' && token !== 'comment') break
  36001. this.tokenizer.back(tokens.pop());
  36002. }
  36003. }
  36004. this.decl(tokens, customProperty);
  36005. } else {
  36006. this.unknownWord(tokens);
  36007. }
  36008. }
  36009. parse() {
  36010. let token;
  36011. while (!this.tokenizer.endOfFile()) {
  36012. token = this.tokenizer.nextToken();
  36013. switch (token[0]) {
  36014. case 'space':
  36015. this.spaces += token[1];
  36016. break
  36017. case ';':
  36018. this.freeSemicolon(token);
  36019. break
  36020. case '}':
  36021. this.end(token);
  36022. break
  36023. case 'comment':
  36024. this.comment(token);
  36025. break
  36026. case 'at-word':
  36027. this.atrule(token);
  36028. break
  36029. case '{':
  36030. this.emptyRule(token);
  36031. break
  36032. default:
  36033. this.other(token);
  36034. break
  36035. }
  36036. }
  36037. this.endFile();
  36038. }
  36039. precheckMissedSemicolon(/* tokens */) {
  36040. // Hook for Safe Parser
  36041. }
  36042. raw(node, prop, tokens, customProperty) {
  36043. let token, type;
  36044. let length = tokens.length;
  36045. let value = '';
  36046. let clean = true;
  36047. let next, prev;
  36048. for (let i = 0; i < length; i += 1) {
  36049. token = tokens[i];
  36050. type = token[0];
  36051. if (type === 'space' && i === length - 1 && !customProperty) {
  36052. clean = false;
  36053. } else if (type === 'comment') {
  36054. prev = tokens[i - 1] ? tokens[i - 1][0] : 'empty';
  36055. next = tokens[i + 1] ? tokens[i + 1][0] : 'empty';
  36056. if (!SAFE_COMMENT_NEIGHBOR[prev] && !SAFE_COMMENT_NEIGHBOR[next]) {
  36057. if (value.slice(-1) === ',') {
  36058. clean = false;
  36059. } else {
  36060. value += token[1];
  36061. }
  36062. } else {
  36063. clean = false;
  36064. }
  36065. } else {
  36066. value += token[1];
  36067. }
  36068. }
  36069. if (!clean) {
  36070. let raw = tokens.reduce((all, i) => all + i[1], '');
  36071. node.raws[prop] = { raw, value };
  36072. }
  36073. node[prop] = value;
  36074. }
  36075. rule(tokens) {
  36076. tokens.pop();
  36077. let node = new Rule();
  36078. this.init(node, tokens[0][2]);
  36079. node.raws.between = this.spacesAndCommentsFromEnd(tokens);
  36080. this.raw(node, 'selector', tokens);
  36081. this.current = node;
  36082. }
  36083. spacesAndCommentsFromEnd(tokens) {
  36084. let lastTokenType;
  36085. let spaces = '';
  36086. while (tokens.length) {
  36087. lastTokenType = tokens[tokens.length - 1][0];
  36088. if (lastTokenType !== 'space' && lastTokenType !== 'comment') break
  36089. spaces = tokens.pop()[1] + spaces;
  36090. }
  36091. return spaces
  36092. }
  36093. // Errors
  36094. spacesAndCommentsFromStart(tokens) {
  36095. let next;
  36096. let spaces = '';
  36097. while (tokens.length) {
  36098. next = tokens[0][0];
  36099. if (next !== 'space' && next !== 'comment') break
  36100. spaces += tokens.shift()[1];
  36101. }
  36102. return spaces
  36103. }
  36104. spacesFromEnd(tokens) {
  36105. let lastTokenType;
  36106. let spaces = '';
  36107. while (tokens.length) {
  36108. lastTokenType = tokens[tokens.length - 1][0];
  36109. if (lastTokenType !== 'space') break
  36110. spaces = tokens.pop()[1] + spaces;
  36111. }
  36112. return spaces
  36113. }
  36114. stringFrom(tokens, from) {
  36115. let result = '';
  36116. for (let i = from; i < tokens.length; i++) {
  36117. result += tokens[i][1];
  36118. }
  36119. tokens.splice(from, tokens.length - from);
  36120. return result
  36121. }
  36122. unclosedBlock() {
  36123. let pos = this.current.source.start;
  36124. throw this.input.error('Unclosed block', pos.line, pos.column)
  36125. }
  36126. unclosedBracket(bracket) {
  36127. throw this.input.error(
  36128. 'Unclosed bracket',
  36129. { offset: bracket[2] },
  36130. { offset: bracket[2] + 1 }
  36131. )
  36132. }
  36133. unexpectedClose(token) {
  36134. throw this.input.error(
  36135. 'Unexpected }',
  36136. { offset: token[2] },
  36137. { offset: token[2] + 1 }
  36138. )
  36139. }
  36140. unknownWord(tokens) {
  36141. throw this.input.error(
  36142. 'Unknown word ' + tokens[0][1],
  36143. { offset: tokens[0][2] },
  36144. { offset: tokens[0][2] + tokens[0][1].length }
  36145. )
  36146. }
  36147. unnamedAtrule(node, token) {
  36148. throw this.input.error(
  36149. 'At-rule without name',
  36150. { offset: token[2] },
  36151. { offset: token[2] + token[1].length }
  36152. )
  36153. }
  36154. }
  36155. parser$1 = Parser;
  36156. return parser$1;
  36157. }
  36158. var parse_1;
  36159. var hasRequiredParse;
  36160. function requireParse () {
  36161. if (hasRequiredParse) return parse_1;
  36162. hasRequiredParse = 1;
  36163. let Container = /*@__PURE__*/ requireContainer$1();
  36164. let Input = /*@__PURE__*/ requireInput();
  36165. let Parser = /*@__PURE__*/ requireParser$1();
  36166. function parse(css, opts) {
  36167. let input = new Input(css, opts);
  36168. let parser = new Parser(input);
  36169. try {
  36170. parser.parse();
  36171. } catch (e) {
  36172. if (browser$1.env.NODE_ENV !== 'production') {
  36173. if (e.name === 'CssSyntaxError' && opts && opts.from) {
  36174. if (/\.scss$/i.test(opts.from)) {
  36175. e.message +=
  36176. '\nYou tried to parse SCSS with ' +
  36177. 'the standard CSS parser; ' +
  36178. 'try again with the postcss-scss parser';
  36179. } else if (/\.sass/i.test(opts.from)) {
  36180. e.message +=
  36181. '\nYou tried to parse Sass with ' +
  36182. 'the standard CSS parser; ' +
  36183. 'try again with the postcss-sass parser';
  36184. } else if (/\.less$/i.test(opts.from)) {
  36185. e.message +=
  36186. '\nYou tried to parse Less with ' +
  36187. 'the standard CSS parser; ' +
  36188. 'try again with the postcss-less parser';
  36189. }
  36190. }
  36191. }
  36192. throw e
  36193. }
  36194. return parser.root
  36195. }
  36196. parse_1 = parse;
  36197. parse.default = parse;
  36198. Container.registerParse(parse);
  36199. return parse_1;
  36200. }
  36201. var warning;
  36202. var hasRequiredWarning;
  36203. function requireWarning () {
  36204. if (hasRequiredWarning) return warning;
  36205. hasRequiredWarning = 1;
  36206. let Container = /*@__PURE__*/ requireContainer$1();
  36207. let { my } = /*@__PURE__*/ requireSymbols();
  36208. class Warning {
  36209. constructor(text, opts = {}) {
  36210. this.type = 'warning';
  36211. this.text = text;
  36212. if (opts.node && opts.node.source) {
  36213. if (!opts.node[my]) {
  36214. // The node comes from another PostCSS copy in node_modules, so it does
  36215. // not have this copy’s methods. Container#normalize() rebuilds such
  36216. // nodes on insert, but a node passed straight to Result#warn() never
  36217. // goes through it.
  36218. Container.rebuild(opts.node);
  36219. }
  36220. let range = opts.node.rangeBy(opts);
  36221. this.line = range.start.line;
  36222. this.column = range.start.column;
  36223. this.endLine = range.end.line;
  36224. this.endColumn = range.end.column;
  36225. }
  36226. for (let opt in opts) this[opt] = opts[opt];
  36227. }
  36228. toString() {
  36229. if (this.node) {
  36230. return this.node.error(this.text, {
  36231. index: this.index,
  36232. plugin: this.plugin,
  36233. word: this.word
  36234. }).message
  36235. }
  36236. if (this.plugin) {
  36237. return this.plugin + ': ' + this.text
  36238. }
  36239. return this.text
  36240. }
  36241. }
  36242. warning = Warning;
  36243. Warning.default = Warning;
  36244. return warning;
  36245. }
  36246. var result;
  36247. var hasRequiredResult;
  36248. function requireResult () {
  36249. if (hasRequiredResult) return result;
  36250. hasRequiredResult = 1;
  36251. let Warning = /*@__PURE__*/ requireWarning();
  36252. class Result {
  36253. get content() {
  36254. return this.css
  36255. }
  36256. constructor(processor, root, opts) {
  36257. this.processor = processor;
  36258. this.messages = [];
  36259. this.root = root;
  36260. this.opts = opts;
  36261. this.css = '';
  36262. this.map = undefined;
  36263. }
  36264. toString() {
  36265. return this.css
  36266. }
  36267. warn(text, opts = {}) {
  36268. if (!opts.plugin) {
  36269. if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
  36270. opts.plugin = this.lastPlugin.postcssPlugin;
  36271. }
  36272. }
  36273. let warning = new Warning(text, opts);
  36274. this.messages.push(warning);
  36275. return warning
  36276. }
  36277. warnings() {
  36278. return this.messages.filter(i => i.type === 'warning')
  36279. }
  36280. }
  36281. result = Result;
  36282. Result.default = Result;
  36283. return result;
  36284. }
  36285. /* eslint-disable no-console */
  36286. var warnOnce;
  36287. var hasRequiredWarnOnce;
  36288. function requireWarnOnce () {
  36289. if (hasRequiredWarnOnce) return warnOnce;
  36290. hasRequiredWarnOnce = 1;
  36291. let printed = {};
  36292. warnOnce = function warnOnce(message) {
  36293. if (printed[message]) return
  36294. printed[message] = true;
  36295. if (typeof console !== 'undefined' && console.warn) {
  36296. console.warn(message);
  36297. }
  36298. };
  36299. return warnOnce;
  36300. }
  36301. var lazyResult;
  36302. var hasRequiredLazyResult;
  36303. function requireLazyResult () {
  36304. if (hasRequiredLazyResult) return lazyResult;
  36305. hasRequiredLazyResult = 1;
  36306. let Container = /*@__PURE__*/ requireContainer$1();
  36307. let Document = /*@__PURE__*/ requireDocument();
  36308. let MapGenerator = /*@__PURE__*/ requireMapGenerator();
  36309. let parse = /*@__PURE__*/ requireParse();
  36310. let Result = /*@__PURE__*/ requireResult();
  36311. let Root = /*@__PURE__*/ requireRoot$1();
  36312. let stringify = /*@__PURE__*/ requireStringify();
  36313. let { isClean, my } = /*@__PURE__*/ requireSymbols();
  36314. let warnOnce = /*@__PURE__*/ requireWarnOnce();
  36315. const TYPE_TO_CLASS_NAME = {
  36316. atrule: 'AtRule',
  36317. comment: 'Comment',
  36318. decl: 'Declaration',
  36319. document: 'Document',
  36320. root: 'Root',
  36321. rule: 'Rule'
  36322. };
  36323. const PLUGIN_PROPS = {
  36324. AtRule: true,
  36325. AtRuleExit: true,
  36326. Comment: true,
  36327. CommentExit: true,
  36328. Declaration: true,
  36329. DeclarationExit: true,
  36330. Document: true,
  36331. DocumentExit: true,
  36332. Once: true,
  36333. OnceExit: true,
  36334. postcssPlugin: true,
  36335. prepare: true,
  36336. Root: true,
  36337. RootExit: true,
  36338. Rule: true,
  36339. RuleExit: true
  36340. };
  36341. const NOT_VISITORS = {
  36342. Once: true,
  36343. postcssPlugin: true,
  36344. prepare: true
  36345. };
  36346. const CHILDREN = 0;
  36347. function isPromise(obj) {
  36348. return typeof obj === 'object' && typeof obj.then === 'function'
  36349. }
  36350. function getEvents(node) {
  36351. let key = false;
  36352. let type = TYPE_TO_CLASS_NAME[node.type];
  36353. if (node.type === 'decl') {
  36354. key = node.prop.toLowerCase();
  36355. } else if (node.type === 'atrule') {
  36356. key = node.name.toLowerCase();
  36357. }
  36358. if (key && node.append) {
  36359. return [
  36360. type,
  36361. type + '-' + key,
  36362. CHILDREN,
  36363. type + 'Exit',
  36364. type + 'Exit-' + key
  36365. ]
  36366. } else if (key) {
  36367. return [type, type + '-' + key, type + 'Exit', type + 'Exit-' + key]
  36368. } else if (node.append) {
  36369. return [type, CHILDREN, type + 'Exit']
  36370. } else {
  36371. return [type, type + 'Exit']
  36372. }
  36373. }
  36374. function toStack(node) {
  36375. let events;
  36376. if (node.type === 'document') {
  36377. events = ['Document', CHILDREN, 'DocumentExit'];
  36378. } else if (node.type === 'root') {
  36379. events = ['Root', CHILDREN, 'RootExit'];
  36380. } else {
  36381. events = getEvents(node);
  36382. }
  36383. return {
  36384. eventIndex: 0,
  36385. events,
  36386. iterator: 0,
  36387. node,
  36388. visitorIndex: 0,
  36389. visitors: []
  36390. }
  36391. }
  36392. function cleanMarks(node) {
  36393. let stack = [node];
  36394. while (stack.length > 0) {
  36395. let next = stack.pop();
  36396. next[isClean] = false;
  36397. if (next.nodes) {
  36398. for (let i of next.nodes) stack.push(i);
  36399. }
  36400. }
  36401. return node
  36402. }
  36403. let postcss = {};
  36404. class LazyResult {
  36405. get content() {
  36406. return this.stringify().content
  36407. }
  36408. get css() {
  36409. return this.stringify().css
  36410. }
  36411. get map() {
  36412. return this.stringify().map
  36413. }
  36414. get messages() {
  36415. return this.sync().messages
  36416. }
  36417. get opts() {
  36418. return this.result.opts
  36419. }
  36420. get processor() {
  36421. return this.result.processor
  36422. }
  36423. get root() {
  36424. return this.sync().root
  36425. }
  36426. get [Symbol.toStringTag]() {
  36427. return 'LazyResult'
  36428. }
  36429. constructor(processor, css, opts) {
  36430. this.stringified = false;
  36431. this.processed = false;
  36432. let root;
  36433. if (
  36434. typeof css === 'object' &&
  36435. css !== null &&
  36436. (css.type === 'root' || css.type === 'document')
  36437. ) {
  36438. root = cleanMarks(css);
  36439. } else if (css instanceof LazyResult || css instanceof Result) {
  36440. root = cleanMarks(css.root);
  36441. if (css.map) {
  36442. if (typeof opts.map === 'undefined') opts.map = {};
  36443. if (!opts.map.inline) opts.map.inline = false;
  36444. opts.map.prev = css.map;
  36445. }
  36446. } else {
  36447. let parser = parse;
  36448. if (opts.syntax) parser = opts.syntax.parse;
  36449. if (opts.parser) parser = opts.parser;
  36450. if (parser.parse) parser = parser.parse;
  36451. try {
  36452. root = parser(css, opts);
  36453. } catch (error) {
  36454. this.processed = true;
  36455. this.error = error;
  36456. }
  36457. if (root && !root[my]) {
  36458. /* c8 ignore next 2 */
  36459. Container.rebuild(root);
  36460. }
  36461. }
  36462. this.result = new Result(processor, root, opts);
  36463. this.helpers = { ...postcss, postcss, result: this.result };
  36464. this.plugins = this.processor.plugins.map(plugin => {
  36465. if (typeof plugin === 'object' && plugin.prepare) {
  36466. return { ...plugin, ...plugin.prepare(this.result) }
  36467. } else {
  36468. return plugin
  36469. }
  36470. });
  36471. }
  36472. async() {
  36473. if (this.error) return Promise.reject(this.error)
  36474. if (this.processed) return Promise.resolve(this.result)
  36475. if (!this.processing) {
  36476. this.processing = this.runAsync();
  36477. }
  36478. return this.processing
  36479. }
  36480. catch(onRejected) {
  36481. return this.async().catch(onRejected)
  36482. }
  36483. finally(onFinally) {
  36484. return this.async().then(onFinally, onFinally)
  36485. }
  36486. getAsyncError() {
  36487. throw new Error('Use process(css).then(cb) to work with async plugins')
  36488. }
  36489. handleError(error, node) {
  36490. let plugin = this.result.lastPlugin;
  36491. try {
  36492. if (node) node.addToError(error);
  36493. this.error = error;
  36494. if (error.name === 'CssSyntaxError' && !error.plugin) {
  36495. error.plugin = plugin.postcssPlugin;
  36496. error.setMessage();
  36497. } else if (plugin.postcssVersion) {
  36498. if (browser$1.env.NODE_ENV !== 'production') {
  36499. let pluginName = plugin.postcssPlugin;
  36500. let pluginVer = plugin.postcssVersion;
  36501. let runtimeVer = this.result.processor.version;
  36502. let a = pluginVer.split('.');
  36503. let b = runtimeVer.split('.');
  36504. if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) {
  36505. // eslint-disable-next-line no-console
  36506. console.error(
  36507. 'Unknown error from PostCSS plugin. Your current PostCSS ' +
  36508. 'version is ' +
  36509. runtimeVer +
  36510. ', but ' +
  36511. pluginName +
  36512. ' uses ' +
  36513. pluginVer +
  36514. '. Perhaps this is the source of the error below.'
  36515. );
  36516. }
  36517. }
  36518. }
  36519. } catch (err) {
  36520. /* c8 ignore next 3 */
  36521. // eslint-disable-next-line no-console
  36522. if (console && console.error) console.error(err);
  36523. }
  36524. return error
  36525. }
  36526. prepareVisitors() {
  36527. this.listeners = {};
  36528. let add = (plugin, type, cb) => {
  36529. if (!this.listeners[type]) this.listeners[type] = [];
  36530. this.listeners[type].push([plugin, cb]);
  36531. };
  36532. for (let plugin of this.plugins) {
  36533. if (typeof plugin === 'object') {
  36534. for (let event in plugin) {
  36535. if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) {
  36536. throw new Error(
  36537. `Unknown event ${event} in ${plugin.postcssPlugin}. ` +
  36538. `Try to update PostCSS (${this.processor.version} now).`
  36539. )
  36540. }
  36541. if (!NOT_VISITORS[event]) {
  36542. if (typeof plugin[event] === 'object') {
  36543. for (let filter in plugin[event]) {
  36544. if (filter === '*') {
  36545. add(plugin, event, plugin[event][filter]);
  36546. } else {
  36547. add(
  36548. plugin,
  36549. event + '-' + filter.toLowerCase(),
  36550. plugin[event][filter]
  36551. );
  36552. }
  36553. }
  36554. } else if (typeof plugin[event] === 'function') {
  36555. add(plugin, event, plugin[event]);
  36556. }
  36557. }
  36558. }
  36559. }
  36560. }
  36561. this.hasListener = Object.keys(this.listeners).length > 0;
  36562. }
  36563. async runAsync() {
  36564. this.plugin = 0;
  36565. for (let i = 0; i < this.plugins.length; i++) {
  36566. let plugin = this.plugins[i];
  36567. let promise = this.runOnRoot(plugin);
  36568. if (isPromise(promise)) {
  36569. try {
  36570. await promise;
  36571. } catch (error) {
  36572. throw this.handleError(error)
  36573. }
  36574. }
  36575. }
  36576. this.prepareVisitors();
  36577. if (this.hasListener) {
  36578. let root = this.result.root;
  36579. while (!root[isClean]) {
  36580. root[isClean] = true;
  36581. let stack = [toStack(root)];
  36582. while (stack.length > 0) {
  36583. let promise = this.visitTick(stack);
  36584. if (isPromise(promise)) {
  36585. try {
  36586. await promise;
  36587. } catch (e) {
  36588. let node = stack[stack.length - 1].node;
  36589. throw this.handleError(e, node)
  36590. }
  36591. }
  36592. }
  36593. }
  36594. if (this.listeners.OnceExit) {
  36595. for (let [plugin, visitor] of this.listeners.OnceExit) {
  36596. this.result.lastPlugin = plugin;
  36597. try {
  36598. if (root.type === 'document') {
  36599. let roots = root.nodes.map(subRoot =>
  36600. visitor(subRoot, this.helpers)
  36601. );
  36602. await Promise.all(roots);
  36603. } else {
  36604. await visitor(root, this.helpers);
  36605. }
  36606. } catch (e) {
  36607. throw this.handleError(e)
  36608. }
  36609. }
  36610. }
  36611. }
  36612. this.processed = true;
  36613. return this.stringify()
  36614. }
  36615. runOnRoot(plugin) {
  36616. this.result.lastPlugin = plugin;
  36617. try {
  36618. if (typeof plugin === 'object' && plugin.Once) {
  36619. if (this.result.root.type === 'document') {
  36620. let roots = this.result.root.nodes.map(root =>
  36621. plugin.Once(root, this.helpers)
  36622. );
  36623. if (isPromise(roots[0])) {
  36624. return Promise.all(roots)
  36625. }
  36626. return roots
  36627. }
  36628. return plugin.Once(this.result.root, this.helpers)
  36629. } else if (typeof plugin === 'function') {
  36630. return plugin(this.result.root, this.result)
  36631. }
  36632. } catch (error) {
  36633. throw this.handleError(error)
  36634. }
  36635. }
  36636. stringify() {
  36637. if (this.error) throw this.error
  36638. if (this.stringified) return this.result
  36639. this.stringified = true;
  36640. this.sync();
  36641. let opts = this.result.opts;
  36642. let str = stringify;
  36643. if (opts.syntax) str = opts.syntax.stringify;
  36644. if (opts.stringifier) str = opts.stringifier;
  36645. if (str.stringify) str = str.stringify;
  36646. let rootSource = this.result.root.source;
  36647. if (
  36648. opts.map === undefined &&
  36649. !(rootSource && rootSource.input && rootSource.input.map)
  36650. ) {
  36651. let result = '';
  36652. str(this.result.root, i => {
  36653. result += i;
  36654. });
  36655. this.result.css = result;
  36656. return this.result
  36657. }
  36658. let map = new MapGenerator(str, this.result.root, this.result.opts);
  36659. let data = map.generate();
  36660. this.result.css = data[0];
  36661. this.result.map = data[1];
  36662. return this.result
  36663. }
  36664. sync() {
  36665. if (this.error) throw this.error
  36666. if (this.processed) return this.result
  36667. this.processed = true;
  36668. if (this.processing) {
  36669. throw this.getAsyncError()
  36670. }
  36671. for (let plugin of this.plugins) {
  36672. let promise = this.runOnRoot(plugin);
  36673. if (isPromise(promise)) {
  36674. throw this.getAsyncError()
  36675. }
  36676. }
  36677. this.prepareVisitors();
  36678. if (this.hasListener) {
  36679. let root = this.result.root;
  36680. while (!root[isClean]) {
  36681. root[isClean] = true;
  36682. this.walkSync(root);
  36683. }
  36684. if (this.listeners.OnceExit) {
  36685. if (root.type === 'document') {
  36686. for (let subRoot of root.nodes) {
  36687. this.visitSync(this.listeners.OnceExit, subRoot);
  36688. }
  36689. } else {
  36690. this.visitSync(this.listeners.OnceExit, root);
  36691. }
  36692. }
  36693. }
  36694. return this.result
  36695. }
  36696. then(onFulfilled, onRejected) {
  36697. if (browser$1.env.NODE_ENV !== 'production') {
  36698. if (!('from' in this.opts)) {
  36699. warnOnce(
  36700. 'Without `from` option PostCSS could generate wrong source map ' +
  36701. 'and will not find Browserslist config. Set it to CSS file path ' +
  36702. 'or to `undefined` to prevent this warning.'
  36703. );
  36704. }
  36705. }
  36706. return this.async().then(onFulfilled, onRejected)
  36707. }
  36708. toString() {
  36709. return this.css
  36710. }
  36711. visitSync(visitors, node) {
  36712. for (let [plugin, visitor] of visitors) {
  36713. this.result.lastPlugin = plugin;
  36714. let promise;
  36715. try {
  36716. promise = visitor(node, this.helpers);
  36717. } catch (e) {
  36718. throw this.handleError(e, node.proxyOf)
  36719. }
  36720. if (node.type !== 'root' && node.type !== 'document' && !node.parent) {
  36721. return true
  36722. }
  36723. if (isPromise(promise)) {
  36724. throw this.getAsyncError()
  36725. }
  36726. }
  36727. }
  36728. visitTick(stack) {
  36729. let visit = stack[stack.length - 1];
  36730. let { node, visitors } = visit;
  36731. if (node.type !== 'root' && node.type !== 'document' && !node.parent) {
  36732. stack.pop();
  36733. return
  36734. }
  36735. if (visitors.length > 0 && visit.visitorIndex < visitors.length) {
  36736. let [plugin, visitor] = visitors[visit.visitorIndex];
  36737. visit.visitorIndex += 1;
  36738. if (visit.visitorIndex === visitors.length) {
  36739. visit.visitors = [];
  36740. visit.visitorIndex = 0;
  36741. }
  36742. this.result.lastPlugin = plugin;
  36743. try {
  36744. return visitor(node.toProxy(), this.helpers)
  36745. } catch (e) {
  36746. throw this.handleError(e, node)
  36747. }
  36748. }
  36749. if (visit.iterator !== 0) {
  36750. let iterator = visit.iterator;
  36751. let child;
  36752. while ((child = node.nodes[node.indexes[iterator]])) {
  36753. node.indexes[iterator] += 1;
  36754. if (!child[isClean]) {
  36755. child[isClean] = true;
  36756. stack.push(toStack(child));
  36757. return
  36758. }
  36759. }
  36760. visit.iterator = 0;
  36761. delete node.indexes[iterator];
  36762. }
  36763. let events = visit.events;
  36764. while (visit.eventIndex < events.length) {
  36765. let event = events[visit.eventIndex];
  36766. visit.eventIndex += 1;
  36767. if (event === CHILDREN) {
  36768. if (node.nodes && node.nodes.length) {
  36769. node[isClean] = true;
  36770. visit.iterator = node.getIterator();
  36771. }
  36772. return
  36773. } else if (this.listeners[event]) {
  36774. visit.visitors = this.listeners[event];
  36775. return
  36776. }
  36777. }
  36778. stack.pop();
  36779. }
  36780. walkSync(node) {
  36781. // An explicit stack like in async `visitTick()` to survive deeply
  36782. // nested trees. Unlike `visitTick()`, nodes are marked clean only
  36783. // on entering, so a node dirtied by its own visitors is revisited
  36784. // on the next pass.
  36785. node[isClean] = true;
  36786. let stack = [{ eventIndex: 0, events: getEvents(node), iterator: 0, node }];
  36787. while (stack.length > 0) {
  36788. let visit = stack[stack.length - 1];
  36789. let visitNode = visit.node;
  36790. if (visit.iterator !== 0) {
  36791. let iterator = visit.iterator;
  36792. let child;
  36793. let descended = false;
  36794. while ((child = visitNode.nodes[visitNode.indexes[iterator]])) {
  36795. visitNode.indexes[iterator] += 1;
  36796. if (!child[isClean]) {
  36797. child[isClean] = true;
  36798. stack.push({
  36799. eventIndex: 0,
  36800. events: getEvents(child),
  36801. iterator: 0,
  36802. node: child
  36803. });
  36804. descended = true;
  36805. break
  36806. }
  36807. }
  36808. if (descended) continue
  36809. visit.iterator = 0;
  36810. delete visitNode.indexes[iterator];
  36811. }
  36812. if (visit.eventIndex < visit.events.length) {
  36813. let event = visit.events[visit.eventIndex];
  36814. visit.eventIndex += 1;
  36815. if (event === CHILDREN) {
  36816. if (visitNode.nodes && visitNode.nodes.length) {
  36817. visit.iterator = visitNode.getIterator();
  36818. }
  36819. } else {
  36820. let visitors = this.listeners[event];
  36821. if (visitors) {
  36822. if (this.visitSync(visitors, visitNode.toProxy())) stack.pop();
  36823. }
  36824. }
  36825. continue
  36826. }
  36827. stack.pop();
  36828. }
  36829. }
  36830. warnings() {
  36831. return this.sync().warnings()
  36832. }
  36833. }
  36834. LazyResult.registerPostcss = dependant => {
  36835. postcss = dependant;
  36836. };
  36837. lazyResult = LazyResult;
  36838. LazyResult.default = LazyResult;
  36839. Root.registerLazyResult(LazyResult);
  36840. Document.registerLazyResult(LazyResult);
  36841. return lazyResult;
  36842. }
  36843. var noWorkResult;
  36844. var hasRequiredNoWorkResult;
  36845. function requireNoWorkResult () {
  36846. if (hasRequiredNoWorkResult) return noWorkResult;
  36847. hasRequiredNoWorkResult = 1;
  36848. let MapGenerator = /*@__PURE__*/ requireMapGenerator();
  36849. let parse = /*@__PURE__*/ requireParse();
  36850. let Result = /*@__PURE__*/ requireResult();
  36851. let stringify = /*@__PURE__*/ requireStringify();
  36852. let warnOnce = /*@__PURE__*/ requireWarnOnce();
  36853. class NoWorkResult {
  36854. get content() {
  36855. return this.result.css
  36856. }
  36857. get css() {
  36858. return this.result.css
  36859. }
  36860. get map() {
  36861. return this.result.map
  36862. }
  36863. get messages() {
  36864. return []
  36865. }
  36866. get opts() {
  36867. return this.result.opts
  36868. }
  36869. get processor() {
  36870. return this.result.processor
  36871. }
  36872. get root() {
  36873. if (this._root) {
  36874. return this._root
  36875. }
  36876. let root;
  36877. let parser = parse;
  36878. try {
  36879. root = parser(this._css, this._opts);
  36880. } catch (error) {
  36881. this.error = error;
  36882. }
  36883. if (this.error) {
  36884. throw this.error
  36885. } else {
  36886. this._root = root;
  36887. return root
  36888. }
  36889. }
  36890. get [Symbol.toStringTag]() {
  36891. return 'NoWorkResult'
  36892. }
  36893. constructor(processor, css, opts) {
  36894. css = css.toString();
  36895. this.stringified = false;
  36896. this._processor = processor;
  36897. this._css = css;
  36898. this._opts = opts;
  36899. this._map = undefined;
  36900. let str = stringify;
  36901. this.result = new Result(this._processor, undefined, this._opts);
  36902. this.result.css = css;
  36903. let self = this;
  36904. Object.defineProperty(this.result, 'root', {
  36905. get() {
  36906. return self.root
  36907. }
  36908. });
  36909. let map = new MapGenerator(str, undefined, this._opts, css);
  36910. if (map.isMap()) {
  36911. let [generatedCSS, generatedMap] = map.generate();
  36912. if (generatedCSS) {
  36913. this.result.css = generatedCSS;
  36914. }
  36915. if (generatedMap) {
  36916. this.result.map = generatedMap;
  36917. }
  36918. } else {
  36919. map.clearAnnotation();
  36920. this.result.css = map.css;
  36921. }
  36922. }
  36923. async() {
  36924. if (this.error) return Promise.reject(this.error)
  36925. return Promise.resolve(this.result)
  36926. }
  36927. catch(onRejected) {
  36928. return this.async().catch(onRejected)
  36929. }
  36930. finally(onFinally) {
  36931. return this.async().then(onFinally, onFinally)
  36932. }
  36933. sync() {
  36934. if (this.error) throw this.error
  36935. return this.result
  36936. }
  36937. then(onFulfilled, onRejected) {
  36938. if (browser$1.env.NODE_ENV !== 'production') {
  36939. if (!('from' in this._opts)) {
  36940. warnOnce(
  36941. 'Without `from` option PostCSS could generate wrong source map ' +
  36942. 'and will not find Browserslist config. Set it to CSS file path ' +
  36943. 'or to `undefined` to prevent this warning.'
  36944. );
  36945. }
  36946. }
  36947. return this.async().then(onFulfilled, onRejected)
  36948. }
  36949. toString() {
  36950. return this._css
  36951. }
  36952. warnings() {
  36953. return []
  36954. }
  36955. }
  36956. noWorkResult = NoWorkResult;
  36957. NoWorkResult.default = NoWorkResult;
  36958. return noWorkResult;
  36959. }
  36960. var processor$1;
  36961. var hasRequiredProcessor$1;
  36962. function requireProcessor$1 () {
  36963. if (hasRequiredProcessor$1) return processor$1;
  36964. hasRequiredProcessor$1 = 1;
  36965. let Document = /*@__PURE__*/ requireDocument();
  36966. let LazyResult = /*@__PURE__*/ requireLazyResult();
  36967. let NoWorkResult = /*@__PURE__*/ requireNoWorkResult();
  36968. let Root = /*@__PURE__*/ requireRoot$1();
  36969. class Processor {
  36970. constructor(plugins = []) {
  36971. this.version = '8.5.23';
  36972. this.plugins = this.normalize(plugins);
  36973. }
  36974. normalize(plugins) {
  36975. let normalized = [];
  36976. for (let i of plugins) {
  36977. if (i.postcss === true) {
  36978. i = i();
  36979. } else if (i.postcss) {
  36980. i = i.postcss;
  36981. }
  36982. if (typeof i === 'object' && Array.isArray(i.plugins)) {
  36983. normalized = normalized.concat(i.plugins);
  36984. } else if (typeof i === 'object' && i.postcssPlugin) {
  36985. normalized.push(i);
  36986. } else if (typeof i === 'function') {
  36987. normalized.push(i);
  36988. } else if (typeof i === 'object' && (i.parse || i.stringify)) {
  36989. if (browser$1.env.NODE_ENV !== 'production') {
  36990. throw new Error(
  36991. 'PostCSS syntaxes cannot be used as plugins. Instead, please use ' +
  36992. 'one of the syntax/parser/stringifier options as outlined ' +
  36993. 'in your PostCSS runner documentation.'
  36994. )
  36995. }
  36996. } else {
  36997. throw new Error(i + ' is not a PostCSS plugin')
  36998. }
  36999. }
  37000. return normalized
  37001. }
  37002. process(css, opts = {}) {
  37003. if (
  37004. !this.plugins.length &&
  37005. !opts.parser &&
  37006. !opts.stringifier &&
  37007. !opts.syntax
  37008. ) {
  37009. return new NoWorkResult(this, css, opts)
  37010. } else {
  37011. return new LazyResult(this, css, opts)
  37012. }
  37013. }
  37014. use(plugin) {
  37015. this.plugins = this.plugins.concat(this.normalize([plugin]));
  37016. return this
  37017. }
  37018. }
  37019. processor$1 = Processor;
  37020. Processor.default = Processor;
  37021. Root.registerProcessor(Processor);
  37022. Document.registerProcessor(Processor);
  37023. return processor$1;
  37024. }
  37025. var postcss_1;
  37026. var hasRequiredPostcss;
  37027. function requirePostcss () {
  37028. if (hasRequiredPostcss) return postcss_1;
  37029. hasRequiredPostcss = 1;
  37030. let AtRule = /*@__PURE__*/ requireAtRule();
  37031. let Comment = /*@__PURE__*/ requireComment$1();
  37032. let Container = /*@__PURE__*/ requireContainer$1();
  37033. let CssSyntaxError = /*@__PURE__*/ requireCssSyntaxError();
  37034. let Declaration = /*@__PURE__*/ requireDeclaration();
  37035. let Document = /*@__PURE__*/ requireDocument();
  37036. let fromJSON = /*@__PURE__*/ requireFromJSON();
  37037. let Input = /*@__PURE__*/ requireInput();
  37038. let LazyResult = /*@__PURE__*/ requireLazyResult();
  37039. let list = /*@__PURE__*/ requireList();
  37040. let Node = /*@__PURE__*/ requireNode$2();
  37041. let parse = /*@__PURE__*/ requireParse();
  37042. let Processor = /*@__PURE__*/ requireProcessor$1();
  37043. let Result = /*@__PURE__*/ requireResult();
  37044. let Root = /*@__PURE__*/ requireRoot$1();
  37045. let Rule = /*@__PURE__*/ requireRule();
  37046. let stringify = /*@__PURE__*/ requireStringify();
  37047. let Warning = /*@__PURE__*/ requireWarning();
  37048. function postcss(...plugins) {
  37049. if (plugins.length === 1 && Array.isArray(plugins[0])) {
  37050. plugins = plugins[0];
  37051. }
  37052. return new Processor(plugins)
  37053. }
  37054. postcss.plugin = function plugin(name, initializer) {
  37055. let warningPrinted = false;
  37056. function creator(...args) {
  37057. // eslint-disable-next-line no-console
  37058. if (console && console.warn && !warningPrinted) {
  37059. warningPrinted = true;
  37060. // eslint-disable-next-line no-console
  37061. console.warn(
  37062. name +
  37063. ': postcss.plugin was deprecated. Migration guide:\n' +
  37064. 'https://evilmartians.com/chronicles/postcss-8-plugin-migration'
  37065. );
  37066. if (browser$1.env.LANG && browser$1.env.LANG.startsWith('cn')) {
  37067. /* c8 ignore next 7 */
  37068. // eslint-disable-next-line no-console
  37069. console.warn(
  37070. name +
  37071. ': 里面 postcss.plugin 被弃用. 迁移指南:\n' +
  37072. 'https://www.w3ctech.com/topic/2226'
  37073. );
  37074. }
  37075. }
  37076. let transformer = initializer(...args);
  37077. transformer.postcssPlugin = name;
  37078. transformer.postcssVersion = new Processor().version;
  37079. return transformer
  37080. }
  37081. let cache;
  37082. Object.defineProperty(creator, 'postcss', {
  37083. get() {
  37084. if (!cache) cache = creator();
  37085. return cache
  37086. }
  37087. });
  37088. creator.process = function (css, processOpts, pluginOpts) {
  37089. return postcss([creator(pluginOpts)]).process(css, processOpts)
  37090. };
  37091. return creator
  37092. };
  37093. postcss.stringify = stringify;
  37094. postcss.parse = parse;
  37095. postcss.fromJSON = fromJSON;
  37096. postcss.list = list;
  37097. postcss.comment = defaults => new Comment(defaults);
  37098. postcss.atRule = defaults => new AtRule(defaults);
  37099. postcss.decl = defaults => new Declaration(defaults);
  37100. postcss.rule = defaults => new Rule(defaults);
  37101. postcss.root = defaults => new Root(defaults);
  37102. postcss.document = defaults => new Document(defaults);
  37103. postcss.CssSyntaxError = CssSyntaxError;
  37104. postcss.Declaration = Declaration;
  37105. postcss.Container = Container;
  37106. postcss.Processor = Processor;
  37107. postcss.Document = Document;
  37108. postcss.Comment = Comment;
  37109. postcss.Warning = Warning;
  37110. postcss.AtRule = AtRule;
  37111. postcss.Result = Result;
  37112. postcss.Input = Input;
  37113. postcss.Rule = Rule;
  37114. postcss.Root = Root;
  37115. postcss.Node = Node;
  37116. LazyResult.registerPostcss(postcss);
  37117. postcss_1 = postcss;
  37118. postcss.default = postcss;
  37119. return postcss_1;
  37120. }
  37121. var postcssExports = /*@__PURE__*/ requirePostcss();
  37122. var postcss = /*@__PURE__*/getDefaultExportFromCjs(postcssExports);
  37123. postcss.stringify;
  37124. postcss.fromJSON;
  37125. postcss.plugin;
  37126. postcss.parse;
  37127. postcss.list;
  37128. postcss.document;
  37129. postcss.comment;
  37130. postcss.atRule;
  37131. postcss.rule;
  37132. postcss.decl;
  37133. postcss.root;
  37134. postcss.CssSyntaxError;
  37135. postcss.Declaration;
  37136. postcss.Container;
  37137. postcss.Processor;
  37138. postcss.Document;
  37139. postcss.Comment;
  37140. postcss.Warning;
  37141. postcss.AtRule;
  37142. postcss.Result;
  37143. postcss.Input;
  37144. const Rule = postcss.Rule;
  37145. postcss.Root;
  37146. postcss.Node;
  37147. const trimPlugin = () => {
  37148. return {
  37149. postcssPlugin: "vue-sfc-trim",
  37150. Once(root) {
  37151. root.walk(({ type, raws }) => {
  37152. if (type === "rule" || type === "atrule") {
  37153. if (raws.before) raws.before = "\n";
  37154. if ("after" in raws && raws.after) raws.after = "\n";
  37155. }
  37156. });
  37157. }
  37158. };
  37159. };
  37160. trimPlugin.postcss = true;
  37161. var processor = {};
  37162. var parser = {};
  37163. var root = {};
  37164. var container = {};
  37165. var util$1 = {};
  37166. var unesc = {};
  37167. var hasRequiredUnesc;
  37168. function requireUnesc () {
  37169. if (hasRequiredUnesc) return unesc;
  37170. hasRequiredUnesc = 1;
  37171. // Many thanks for this post which made this migration much easier.
  37172. // https://mathiasbynens.be/notes/css-escapes
  37173. Object.defineProperty(unesc, "__esModule", { value: true });
  37174. unesc.default = unesc$1;
  37175. /**
  37176. *
  37177. * @param {string} str
  37178. * @returns {[string, number]|undefined}
  37179. */
  37180. function gobbleHex(str) {
  37181. var lower = str.toLowerCase();
  37182. var hex = "";
  37183. var spaceTerminated = false;
  37184. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  37185. var code = lower.charCodeAt(i);
  37186. // check to see if we are dealing with a valid hex char [a-f|0-9]
  37187. var valid = (code >= 97 && code <= 102) || (code >= 48 && code <= 57);
  37188. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  37189. spaceTerminated = code === 32;
  37190. if (!valid) {
  37191. break;
  37192. }
  37193. hex += lower[i];
  37194. }
  37195. if (hex.length === 0) {
  37196. return undefined;
  37197. }
  37198. var codePoint = parseInt(hex, 16);
  37199. var isSurrogate = codePoint >= 0xd800 && codePoint <= 0xdfff;
  37200. // Add special case for
  37201. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  37202. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  37203. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10ffff) {
  37204. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  37205. }
  37206. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  37207. }
  37208. var CONTAINS_ESCAPE = /\\/;
  37209. function unesc$1(str) {
  37210. var needToProcess = CONTAINS_ESCAPE.test(str);
  37211. if (!needToProcess) {
  37212. return str;
  37213. }
  37214. var ret = "";
  37215. for (var i = 0; i < str.length; i++) {
  37216. if (str[i] === "\\") {
  37217. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  37218. if (gobbled !== undefined) {
  37219. ret += gobbled[0];
  37220. i += gobbled[1];
  37221. continue;
  37222. }
  37223. // Retain a pair of \\ if double escaped `\\\\`
  37224. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  37225. if (str[i + 1] === "\\") {
  37226. ret += "\\";
  37227. i++;
  37228. continue;
  37229. }
  37230. // if \\ is at the end of the string retain it
  37231. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  37232. if (str.length === i + 1) {
  37233. ret += str[i];
  37234. }
  37235. continue;
  37236. }
  37237. ret += str[i];
  37238. }
  37239. return ret;
  37240. }
  37241. return unesc;
  37242. }
  37243. var getProp = {};
  37244. var hasRequiredGetProp;
  37245. function requireGetProp () {
  37246. if (hasRequiredGetProp) return getProp;
  37247. hasRequiredGetProp = 1;
  37248. Object.defineProperty(getProp, "__esModule", { value: true });
  37249. getProp.default = getProp$1;
  37250. function getProp$1(obj) {
  37251. var props = [];
  37252. for (var _i = 1; _i < arguments.length; _i++) {
  37253. props[_i - 1] = arguments[_i];
  37254. }
  37255. while (props.length > 0) {
  37256. var prop = props.shift();
  37257. if (!obj[prop]) {
  37258. return undefined;
  37259. }
  37260. obj = obj[prop];
  37261. }
  37262. return obj;
  37263. }
  37264. return getProp;
  37265. }
  37266. var ensureObject = {};
  37267. var hasRequiredEnsureObject;
  37268. function requireEnsureObject () {
  37269. if (hasRequiredEnsureObject) return ensureObject;
  37270. hasRequiredEnsureObject = 1;
  37271. Object.defineProperty(ensureObject, "__esModule", { value: true });
  37272. ensureObject.default = ensureObject$1;
  37273. function ensureObject$1(obj) {
  37274. var props = [];
  37275. for (var _i = 1; _i < arguments.length; _i++) {
  37276. props[_i - 1] = arguments[_i];
  37277. }
  37278. while (props.length > 0) {
  37279. var prop = props.shift();
  37280. if (!obj[prop]) {
  37281. obj[prop] = {};
  37282. }
  37283. obj = obj[prop];
  37284. }
  37285. }
  37286. return ensureObject;
  37287. }
  37288. var stripComments = {};
  37289. var hasRequiredStripComments;
  37290. function requireStripComments () {
  37291. if (hasRequiredStripComments) return stripComments;
  37292. hasRequiredStripComments = 1;
  37293. Object.defineProperty(stripComments, "__esModule", { value: true });
  37294. stripComments.default = stripComments$1;
  37295. function stripComments$1(str) {
  37296. var s = "";
  37297. var commentStart = str.indexOf("/*");
  37298. var lastEnd = 0;
  37299. while (commentStart >= 0) {
  37300. s = s + str.slice(lastEnd, commentStart);
  37301. var commentEnd = str.indexOf("*/", commentStart + 2);
  37302. if (commentEnd < 0) {
  37303. return s;
  37304. }
  37305. lastEnd = commentEnd + 2;
  37306. commentStart = str.indexOf("/*", lastEnd);
  37307. }
  37308. s = s + str.slice(lastEnd);
  37309. return s;
  37310. }
  37311. return stripComments;
  37312. }
  37313. var maxNestingDepth = {};
  37314. var hasRequiredMaxNestingDepth;
  37315. function requireMaxNestingDepth () {
  37316. if (hasRequiredMaxNestingDepth) return maxNestingDepth;
  37317. hasRequiredMaxNestingDepth = 1;
  37318. (function (exports) {
  37319. Object.defineProperty(exports, "__esModule", { value: true });
  37320. exports.MAX_NESTING_DEPTH = void 0;
  37321. exports.default = resolveMaxNestingDepth;
  37322. /**
  37323. * The default maximum selector nesting depth allowed when parsing or
  37324. * serializing a selector. Going beyond this would otherwise recurse deeply
  37325. * enough to overflow the call stack (CVE-2026-9358 / CWE-674). Real-world
  37326. * selectors never get anywhere near this, so it acts purely as a safety net
  37327. * that turns an uncatchable stack overflow into a catchable error.
  37328. */
  37329. exports.MAX_NESTING_DEPTH = 256;
  37330. /**
  37331. * Coerce a user-supplied nesting-depth limit into a safe value. Anything that
  37332. * is not a non-negative safe integer (NaN, Infinity, negative numbers, or a
  37333. * non-number) would disable or break the guard, so it falls back to the
  37334. * default.
  37335. *
  37336. * @param {unknown} value the limit provided through the `maxNestingDepth` option
  37337. * @returns {number} a safe, non-negative integer limit
  37338. */
  37339. function resolveMaxNestingDepth(value) {
  37340. return Number.isSafeInteger(value) && value >= 0 ? value : exports.MAX_NESTING_DEPTH;
  37341. }
  37342. } (maxNestingDepth));
  37343. return maxNestingDepth;
  37344. }
  37345. var hasRequiredUtil$1;
  37346. function requireUtil$1 () {
  37347. if (hasRequiredUtil$1) return util$1;
  37348. hasRequiredUtil$1 = 1;
  37349. (function (exports) {
  37350. var __importDefault = (util$1 && util$1.__importDefault) || function (mod) {
  37351. return (mod && mod.__esModule) ? mod : { "default": mod };
  37352. };
  37353. Object.defineProperty(exports, "__esModule", { value: true });
  37354. exports.MAX_NESTING_DEPTH = exports.resolveMaxNestingDepth = exports.stripComments = exports.ensureObject = exports.getProp = exports.unesc = void 0;
  37355. var unesc_1 = /*@__PURE__*/ requireUnesc();
  37356. Object.defineProperty(exports, "unesc", { enumerable: true, get: function () { return __importDefault(unesc_1).default; } });
  37357. var getProp_1 = /*@__PURE__*/ requireGetProp();
  37358. Object.defineProperty(exports, "getProp", { enumerable: true, get: function () { return __importDefault(getProp_1).default; } });
  37359. var ensureObject_1 = /*@__PURE__*/ requireEnsureObject();
  37360. Object.defineProperty(exports, "ensureObject", { enumerable: true, get: function () { return __importDefault(ensureObject_1).default; } });
  37361. var stripComments_1 = /*@__PURE__*/ requireStripComments();
  37362. Object.defineProperty(exports, "stripComments", { enumerable: true, get: function () { return __importDefault(stripComments_1).default; } });
  37363. var maxNestingDepth_1 = /*@__PURE__*/ requireMaxNestingDepth();
  37364. Object.defineProperty(exports, "resolveMaxNestingDepth", { enumerable: true, get: function () { return __importDefault(maxNestingDepth_1).default; } });
  37365. Object.defineProperty(exports, "MAX_NESTING_DEPTH", { enumerable: true, get: function () { return maxNestingDepth_1.MAX_NESTING_DEPTH; } });
  37366. } (util$1));
  37367. return util$1;
  37368. }
  37369. var node$1 = {};
  37370. var hasRequiredNode$1;
  37371. function requireNode$1 () {
  37372. if (hasRequiredNode$1) return node$1;
  37373. hasRequiredNode$1 = 1;
  37374. Object.defineProperty(node$1, "__esModule", { value: true });
  37375. var util_1 = /*@__PURE__*/ requireUtil$1();
  37376. var cloneNode = function (obj, parent, depth) {
  37377. if (depth === void 0) { depth = 0; }
  37378. // Bound recursion so a pathologically deep node tree raises a catchable
  37379. // error instead of overflowing the call stack (CVE-2026-9358 / CWE-674).
  37380. if (depth > util_1.MAX_NESTING_DEPTH) {
  37381. throw new Error("Cannot clone selector: nesting depth exceeds the maximum of ".concat(util_1.MAX_NESTING_DEPTH, "."));
  37382. }
  37383. if (typeof obj !== "object" || obj === null) {
  37384. return obj;
  37385. }
  37386. var cloned = new obj.constructor();
  37387. for (var i in obj) {
  37388. if (!obj.hasOwnProperty(i)) {
  37389. continue;
  37390. }
  37391. var value = obj[i];
  37392. var type = typeof value;
  37393. if (i === "parent" && type === "object") {
  37394. if (parent) {
  37395. cloned[i] = parent;
  37396. }
  37397. }
  37398. else if (value instanceof Array) {
  37399. cloned[i] = value.map(function (j) { return cloneNode(j, cloned, depth + 1); });
  37400. }
  37401. else {
  37402. cloned[i] = cloneNode(value, cloned, depth + 1);
  37403. }
  37404. }
  37405. return cloned;
  37406. };
  37407. var Node = /** @class */ (function () {
  37408. function Node(opts) {
  37409. if (opts === void 0) { opts = {}; }
  37410. Object.assign(this, opts);
  37411. this.spaces = this.spaces || {};
  37412. this.spaces.before = this.spaces.before || "";
  37413. this.spaces.after = this.spaces.after || "";
  37414. }
  37415. Node.prototype.remove = function () {
  37416. if (this.parent) {
  37417. this.parent.removeChild(this);
  37418. }
  37419. this.parent = undefined;
  37420. return this;
  37421. };
  37422. Node.prototype.replaceWith = function () {
  37423. if (this.parent) {
  37424. for (var index in arguments) {
  37425. this.parent.insertBefore(this, arguments[index]);
  37426. }
  37427. this.remove();
  37428. }
  37429. return this;
  37430. };
  37431. Node.prototype.next = function () {
  37432. return this.parent.at(this.parent.index(this) + 1);
  37433. };
  37434. Node.prototype.prev = function () {
  37435. return this.parent.at(this.parent.index(this) - 1);
  37436. };
  37437. Node.prototype.clone = function (overrides) {
  37438. if (overrides === void 0) { overrides = {}; }
  37439. var cloned = cloneNode(this);
  37440. for (var name in overrides) {
  37441. cloned[name] = overrides[name];
  37442. }
  37443. return cloned;
  37444. };
  37445. /**
  37446. * Some non-standard syntax doesn't follow normal escaping rules for css.
  37447. * This allows non standard syntax to be appended to an existing property
  37448. * by specifying the escaped value. By specifying the escaped value,
  37449. * illegal characters are allowed to be directly inserted into css output.
  37450. * @param {string} name the property to set
  37451. * @param {any} value the unescaped value of the property
  37452. * @param {string} valueEscaped optional. the escaped value of the property.
  37453. */
  37454. Node.prototype.appendToPropertyAndEscape = function (name, value, valueEscaped) {
  37455. if (!this.raws) {
  37456. this.raws = {};
  37457. }
  37458. var originalValue = this[name];
  37459. var originalEscaped = this.raws[name];
  37460. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  37461. if (originalEscaped || valueEscaped !== value) {
  37462. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  37463. }
  37464. else {
  37465. delete this.raws[name]; // delete any escaped value that was created by the setter.
  37466. }
  37467. };
  37468. /**
  37469. * Some non-standard syntax doesn't follow normal escaping rules for css.
  37470. * This allows the escaped value to be specified directly, allowing illegal
  37471. * characters to be directly inserted into css output.
  37472. * @param {string} name the property to set
  37473. * @param {any} value the unescaped value of the property
  37474. * @param {string} valueEscaped the escaped value of the property.
  37475. */
  37476. Node.prototype.setPropertyAndEscape = function (name, value, valueEscaped) {
  37477. if (!this.raws) {
  37478. this.raws = {};
  37479. }
  37480. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  37481. this.raws[name] = valueEscaped;
  37482. };
  37483. /**
  37484. * When you want a value to passed through to CSS directly. This method
  37485. * deletes the corresponding raw value causing the stringifier to fallback
  37486. * to the unescaped value.
  37487. * @param {string} name the property to set.
  37488. * @param {any} value The value that is both escaped and unescaped.
  37489. */
  37490. Node.prototype.setPropertyWithoutEscape = function (name, value) {
  37491. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  37492. if (this.raws) {
  37493. delete this.raws[name];
  37494. }
  37495. };
  37496. /**
  37497. *
  37498. * @param {number} line The number (starting with 1)
  37499. * @param {number} column The column number (starting with 1)
  37500. */
  37501. Node.prototype.isAtPosition = function (line, column) {
  37502. if (this.source && this.source.start && this.source.end) {
  37503. if (this.source.start.line > line) {
  37504. return false;
  37505. }
  37506. if (this.source.end.line < line) {
  37507. return false;
  37508. }
  37509. if (this.source.start.line === line && this.source.start.column > column) {
  37510. return false;
  37511. }
  37512. if (this.source.end.line === line && this.source.end.column < column) {
  37513. return false;
  37514. }
  37515. return true;
  37516. }
  37517. return undefined;
  37518. };
  37519. Node.prototype.stringifyProperty = function (name) {
  37520. return (this.raws && this.raws[name]) || this[name];
  37521. };
  37522. Object.defineProperty(Node.prototype, "rawSpaceBefore", {
  37523. get: function () {
  37524. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  37525. if (rawSpace === undefined) {
  37526. rawSpace = this.spaces && this.spaces.before;
  37527. }
  37528. return rawSpace || "";
  37529. },
  37530. set: function (raw) {
  37531. (0, util_1.ensureObject)(this, "raws", "spaces");
  37532. this.raws.spaces.before = raw;
  37533. },
  37534. enumerable: false,
  37535. configurable: true
  37536. });
  37537. Object.defineProperty(Node.prototype, "rawSpaceAfter", {
  37538. get: function () {
  37539. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  37540. if (rawSpace === undefined) {
  37541. rawSpace = this.spaces.after;
  37542. }
  37543. return rawSpace || "";
  37544. },
  37545. set: function (raw) {
  37546. (0, util_1.ensureObject)(this, "raws", "spaces");
  37547. this.raws.spaces.after = raw;
  37548. },
  37549. enumerable: false,
  37550. configurable: true
  37551. });
  37552. Node.prototype.valueToString = function () {
  37553. return String(this.stringifyProperty("value"));
  37554. };
  37555. Node.prototype.toString = function () {
  37556. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join("");
  37557. };
  37558. // Internal recursion entry point used by Container serialization. Leaf
  37559. // nodes don't recurse, so they ignore the depth/limit and stringify
  37560. // themselves. Containers override this to thread the nesting depth.
  37561. Node.prototype._stringify = function () {
  37562. return this.toString();
  37563. };
  37564. return Node;
  37565. }());
  37566. node$1.default = Node;
  37567. return node$1;
  37568. }
  37569. var types = {};
  37570. var hasRequiredTypes;
  37571. function requireTypes () {
  37572. if (hasRequiredTypes) return types;
  37573. hasRequiredTypes = 1;
  37574. Object.defineProperty(types, "__esModule", { value: true });
  37575. types.UNIVERSAL = types.ATTRIBUTE = types.CLASS = types.COMBINATOR = types.COMMENT = types.ID = types.NESTING = types.PSEUDO = types.ROOT = types.SELECTOR = types.STRING = types.TAG = void 0;
  37576. types.TAG = "tag";
  37577. types.STRING = "string";
  37578. types.SELECTOR = "selector";
  37579. types.ROOT = "root";
  37580. types.PSEUDO = "pseudo";
  37581. types.NESTING = "nesting";
  37582. types.ID = "id";
  37583. types.COMMENT = "comment";
  37584. types.COMBINATOR = "combinator";
  37585. types.CLASS = "class";
  37586. types.ATTRIBUTE = "attribute";
  37587. types.UNIVERSAL = "universal";
  37588. return types;
  37589. }
  37590. var hasRequiredContainer;
  37591. function requireContainer () {
  37592. if (hasRequiredContainer) return container;
  37593. hasRequiredContainer = 1;
  37594. var __extends = (container && container.__extends) || (function () {
  37595. var extendStatics = function (d, b) {
  37596. extendStatics = Object.setPrototypeOf ||
  37597. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  37598. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  37599. return extendStatics(d, b);
  37600. };
  37601. return function (d, b) {
  37602. if (typeof b !== "function" && b !== null)
  37603. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  37604. extendStatics(d, b);
  37605. function __() { this.constructor = d; }
  37606. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  37607. };
  37608. })();
  37609. var __createBinding = (container && container.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  37610. if (k2 === undefined) k2 = k;
  37611. var desc = Object.getOwnPropertyDescriptor(m, k);
  37612. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  37613. desc = { enumerable: true, get: function() { return m[k]; } };
  37614. }
  37615. Object.defineProperty(o, k2, desc);
  37616. }) : (function(o, m, k, k2) {
  37617. if (k2 === undefined) k2 = k;
  37618. o[k2] = m[k];
  37619. }));
  37620. var __setModuleDefault = (container && container.__setModuleDefault) || (Object.create ? (function(o, v) {
  37621. Object.defineProperty(o, "default", { enumerable: true, value: v });
  37622. }) : function(o, v) {
  37623. o["default"] = v;
  37624. });
  37625. var __importStar = (container && container.__importStar) || (function () {
  37626. var ownKeys = function(o) {
  37627. ownKeys = Object.getOwnPropertyNames || function (o) {
  37628. var ar = [];
  37629. for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
  37630. return ar;
  37631. };
  37632. return ownKeys(o);
  37633. };
  37634. return function (mod) {
  37635. if (mod && mod.__esModule) return mod;
  37636. var result = {};
  37637. if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
  37638. __setModuleDefault(result, mod);
  37639. return result;
  37640. };
  37641. })();
  37642. var __values = (container && container.__values) || function(o) {
  37643. var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  37644. if (m) return m.call(o);
  37645. if (o && typeof o.length === "number") return {
  37646. next: function () {
  37647. if (o && i >= o.length) o = void 0;
  37648. return { value: o && o[i++], done: !o };
  37649. }
  37650. };
  37651. throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
  37652. };
  37653. var __read = (container && container.__read) || function (o, n) {
  37654. var m = typeof Symbol === "function" && o[Symbol.iterator];
  37655. if (!m) return o;
  37656. var i = m.call(o), r, ar = [], e;
  37657. try {
  37658. while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  37659. }
  37660. catch (error) { e = { error: error }; }
  37661. finally {
  37662. try {
  37663. if (r && !r.done && (m = i["return"])) m.call(i);
  37664. }
  37665. finally { if (e) throw e.error; }
  37666. }
  37667. return ar;
  37668. };
  37669. var __spreadArray = (container && container.__spreadArray) || function (to, from, pack) {
  37670. if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
  37671. if (ar || !(i in from)) {
  37672. if (!ar) ar = Array.prototype.slice.call(from, 0, i);
  37673. ar[i] = from[i];
  37674. }
  37675. }
  37676. return to.concat(ar || Array.prototype.slice.call(from));
  37677. };
  37678. var __importDefault = (container && container.__importDefault) || function (mod) {
  37679. return (mod && mod.__esModule) ? mod : { "default": mod };
  37680. };
  37681. Object.defineProperty(container, "__esModule", { value: true });
  37682. var util_1 = /*@__PURE__*/ requireUtil$1();
  37683. var node_1 = __importDefault(/*@__PURE__*/ requireNode$1());
  37684. var types = __importStar(/*@__PURE__*/ requireTypes());
  37685. var Container = /** @class */ (function (_super) {
  37686. __extends(Container, _super);
  37687. function Container(opts) {
  37688. var _this = _super.call(this, opts) || this;
  37689. if (!_this.nodes) {
  37690. _this.nodes = [];
  37691. }
  37692. return _this;
  37693. }
  37694. Container.prototype.append = function (selector) {
  37695. selector.parent = this;
  37696. this.nodes.push(selector);
  37697. return this;
  37698. };
  37699. Container.prototype.prepend = function (selector) {
  37700. selector.parent = this;
  37701. this.nodes.unshift(selector);
  37702. for (var id in this.indexes) {
  37703. this.indexes[id]++;
  37704. }
  37705. return this;
  37706. };
  37707. Container.prototype.at = function (index) {
  37708. return this.nodes[index];
  37709. };
  37710. Container.prototype.index = function (child) {
  37711. if (typeof child === "number") {
  37712. return child;
  37713. }
  37714. return this.nodes.indexOf(child);
  37715. };
  37716. Object.defineProperty(Container.prototype, "first", {
  37717. get: function () {
  37718. return this.at(0);
  37719. },
  37720. enumerable: false,
  37721. configurable: true
  37722. });
  37723. Object.defineProperty(Container.prototype, "last", {
  37724. get: function () {
  37725. return this.at(this.length - 1);
  37726. },
  37727. enumerable: false,
  37728. configurable: true
  37729. });
  37730. Object.defineProperty(Container.prototype, "length", {
  37731. get: function () {
  37732. return this.nodes.length;
  37733. },
  37734. enumerable: false,
  37735. configurable: true
  37736. });
  37737. Container.prototype.removeChild = function (child) {
  37738. child = this.index(child);
  37739. this.at(child).parent = undefined;
  37740. this.nodes.splice(child, 1);
  37741. var index;
  37742. for (var id in this.indexes) {
  37743. index = this.indexes[id];
  37744. if (index >= child) {
  37745. this.indexes[id] = index - 1;
  37746. }
  37747. }
  37748. return this;
  37749. };
  37750. Container.prototype.removeAll = function () {
  37751. var e_1, _a;
  37752. try {
  37753. for (var _b = __values(this.nodes), _c = _b.next(); !_c.done; _c = _b.next()) {
  37754. var node = _c.value;
  37755. node.parent = undefined;
  37756. }
  37757. }
  37758. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  37759. finally {
  37760. try {
  37761. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  37762. }
  37763. finally { if (e_1) throw e_1.error; }
  37764. }
  37765. this.nodes = [];
  37766. return this;
  37767. };
  37768. Container.prototype.empty = function () {
  37769. return this.removeAll();
  37770. };
  37771. Container.prototype.insertAfter = function (oldNode, newNode) {
  37772. var _a;
  37773. newNode.parent = this;
  37774. var oldIndex = this.index(oldNode);
  37775. var resetNode = [];
  37776. for (var i = 2; i < arguments.length; i++) {
  37777. resetNode.push(arguments[i]);
  37778. }
  37779. (_a = this.nodes).splice.apply(_a, __spreadArray([oldIndex + 1, 0, newNode], __read(resetNode), false));
  37780. newNode.parent = this;
  37781. var index;
  37782. for (var id in this.indexes) {
  37783. index = this.indexes[id];
  37784. if (oldIndex < index) {
  37785. this.indexes[id] = index + arguments.length - 1;
  37786. }
  37787. }
  37788. return this;
  37789. };
  37790. Container.prototype.insertBefore = function (oldNode, newNode) {
  37791. var _a;
  37792. newNode.parent = this;
  37793. var oldIndex = this.index(oldNode);
  37794. var resetNode = [];
  37795. for (var i = 2; i < arguments.length; i++) {
  37796. resetNode.push(arguments[i]);
  37797. }
  37798. (_a = this.nodes).splice.apply(_a, __spreadArray([oldIndex, 0, newNode], __read(resetNode), false));
  37799. newNode.parent = this;
  37800. var index;
  37801. for (var id in this.indexes) {
  37802. index = this.indexes[id];
  37803. if (index >= oldIndex) {
  37804. this.indexes[id] = index + arguments.length - 1;
  37805. }
  37806. }
  37807. return this;
  37808. };
  37809. Container.prototype._findChildAtPosition = function (line, col) {
  37810. var found = undefined;
  37811. this.each(function (node) {
  37812. if (node.atPosition) {
  37813. var foundChild = node.atPosition(line, col);
  37814. if (foundChild) {
  37815. found = foundChild;
  37816. return false;
  37817. }
  37818. }
  37819. else if (node.isAtPosition(line, col)) {
  37820. found = node;
  37821. return false;
  37822. }
  37823. });
  37824. return found;
  37825. };
  37826. /**
  37827. * Return the most specific node at the line and column number given.
  37828. * The source location is based on the original parsed location, locations aren't
  37829. * updated as selector nodes are mutated.
  37830. *
  37831. * Note that this location is relative to the location of the first character
  37832. * of the selector, and not the location of the selector in the overall document
  37833. * when used in conjunction with postcss.
  37834. *
  37835. * If not found, returns undefined.
  37836. * @param {number} line The line number of the node to find. (1-based index)
  37837. * @param {number} col The column number of the node to find. (1-based index)
  37838. */
  37839. Container.prototype.atPosition = function (line, col) {
  37840. if (this.isAtPosition(line, col)) {
  37841. return this._findChildAtPosition(line, col) || this;
  37842. }
  37843. else {
  37844. return undefined;
  37845. }
  37846. };
  37847. Container.prototype._inferEndPosition = function () {
  37848. if (this.last && this.last.source && this.last.source.end) {
  37849. this.source = this.source || {};
  37850. this.source.end = this.source.end || {};
  37851. Object.assign(this.source.end, this.last.source.end);
  37852. }
  37853. };
  37854. Container.prototype.each = function (callback) {
  37855. if (!this.lastEach) {
  37856. this.lastEach = 0;
  37857. }
  37858. if (!this.indexes) {
  37859. this.indexes = {};
  37860. }
  37861. this.lastEach++;
  37862. var id = this.lastEach;
  37863. this.indexes[id] = 0;
  37864. if (!this.length) {
  37865. return undefined;
  37866. }
  37867. var index, result;
  37868. while (this.indexes[id] < this.length) {
  37869. index = this.indexes[id];
  37870. result = callback(this.at(index), index);
  37871. if (result === false) {
  37872. break;
  37873. }
  37874. this.indexes[id] += 1;
  37875. }
  37876. delete this.indexes[id];
  37877. if (result === false) {
  37878. return false;
  37879. }
  37880. };
  37881. Container.prototype.walk = function (callback, depth) {
  37882. if (depth === void 0) { depth = 0; }
  37883. // Bound recursion so a pathologically deep node tree raises a catchable
  37884. // error instead of overflowing the call stack (CVE-2026-9358 / CWE-674).
  37885. if (depth > util_1.MAX_NESTING_DEPTH) {
  37886. throw new Error("Cannot walk selector: nesting depth exceeds the maximum of ".concat(util_1.MAX_NESTING_DEPTH, "."));
  37887. }
  37888. return this.each(function (node, i) {
  37889. var result = callback(node, i);
  37890. if (result !== false && node.length) {
  37891. result = node.walk(callback, depth + 1);
  37892. }
  37893. if (result === false) {
  37894. return false;
  37895. }
  37896. });
  37897. };
  37898. Container.prototype.walkAttributes = function (callback) {
  37899. var _this = this;
  37900. return this.walk(function (selector) {
  37901. if (selector.type === types.ATTRIBUTE) {
  37902. return callback.call(_this, selector);
  37903. }
  37904. });
  37905. };
  37906. Container.prototype.walkClasses = function (callback) {
  37907. var _this = this;
  37908. return this.walk(function (selector) {
  37909. if (selector.type === types.CLASS) {
  37910. return callback.call(_this, selector);
  37911. }
  37912. });
  37913. };
  37914. Container.prototype.walkCombinators = function (callback) {
  37915. var _this = this;
  37916. return this.walk(function (selector) {
  37917. if (selector.type === types.COMBINATOR) {
  37918. return callback.call(_this, selector);
  37919. }
  37920. });
  37921. };
  37922. Container.prototype.walkComments = function (callback) {
  37923. var _this = this;
  37924. return this.walk(function (selector) {
  37925. if (selector.type === types.COMMENT) {
  37926. return callback.call(_this, selector);
  37927. }
  37928. });
  37929. };
  37930. Container.prototype.walkIds = function (callback) {
  37931. var _this = this;
  37932. return this.walk(function (selector) {
  37933. if (selector.type === types.ID) {
  37934. return callback.call(_this, selector);
  37935. }
  37936. });
  37937. };
  37938. Container.prototype.walkNesting = function (callback) {
  37939. var _this = this;
  37940. return this.walk(function (selector) {
  37941. if (selector.type === types.NESTING) {
  37942. return callback.call(_this, selector);
  37943. }
  37944. });
  37945. };
  37946. Container.prototype.walkPseudos = function (callback) {
  37947. var _this = this;
  37948. return this.walk(function (selector) {
  37949. if (selector.type === types.PSEUDO) {
  37950. return callback.call(_this, selector);
  37951. }
  37952. });
  37953. };
  37954. Container.prototype.walkTags = function (callback) {
  37955. var _this = this;
  37956. return this.walk(function (selector) {
  37957. if (selector.type === types.TAG) {
  37958. return callback.call(_this, selector);
  37959. }
  37960. });
  37961. };
  37962. Container.prototype.walkUniversals = function (callback) {
  37963. var _this = this;
  37964. return this.walk(function (selector) {
  37965. if (selector.type === types.UNIVERSAL) {
  37966. return callback.call(_this, selector);
  37967. }
  37968. });
  37969. };
  37970. Container.prototype.split = function (callback) {
  37971. var _this = this;
  37972. var current = [];
  37973. return this.reduce(function (memo, node, index) {
  37974. var split = callback.call(_this, node);
  37975. current.push(node);
  37976. if (split) {
  37977. memo.push(current);
  37978. current = [];
  37979. }
  37980. else if (index === _this.length - 1) {
  37981. memo.push(current);
  37982. }
  37983. return memo;
  37984. }, []);
  37985. };
  37986. Container.prototype.map = function (callback) {
  37987. return this.nodes.map(callback);
  37988. };
  37989. Container.prototype.reduce = function (callback, memo) {
  37990. return this.nodes.reduce(callback, memo);
  37991. };
  37992. Container.prototype.every = function (callback) {
  37993. return this.nodes.every(callback);
  37994. };
  37995. Container.prototype.some = function (callback) {
  37996. return this.nodes.some(callback);
  37997. };
  37998. Container.prototype.filter = function (callback) {
  37999. return this.nodes.filter(callback);
  38000. };
  38001. Container.prototype.sort = function (callback) {
  38002. return this.nodes.sort(callback);
  38003. };
  38004. Container.prototype.toString = function (options) {
  38005. if (options === void 0) { options = {}; }
  38006. return this._stringify(options, 0, (0, util_1.resolveMaxNestingDepth)(options.maxNestingDepth));
  38007. };
  38008. Container.prototype._stringify = function (options, depth, max) {
  38009. var _this = this;
  38010. return this.map(function (child) { return _this._stringifyChild(child, options, depth, max); }).join("");
  38011. };
  38012. // Serialize a child node. Historically `toString` used `this.map(String)`,
  38013. // which leniently coerced anything — including raw arrays inserted via
  38014. // `replaceWith(array)` / `insertBefore` / `insertAfter` (e.g. Tailwind's
  38015. // `:merge()` expansion). Fall back to `String(child)` for values that are not
  38016. // parser nodes so that behaviour is preserved.
  38017. Container.prototype._stringifyChild = function (child, options, depth, max) {
  38018. return typeof child._stringify === "function"
  38019. ? child._stringify(options, depth, max)
  38020. : String(child);
  38021. };
  38022. return Container;
  38023. }(node_1.default));
  38024. container.default = Container;
  38025. return container;
  38026. }
  38027. var hasRequiredRoot;
  38028. function requireRoot () {
  38029. if (hasRequiredRoot) return root;
  38030. hasRequiredRoot = 1;
  38031. var __extends = (root && root.__extends) || (function () {
  38032. var extendStatics = function (d, b) {
  38033. extendStatics = Object.setPrototypeOf ||
  38034. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  38035. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  38036. return extendStatics(d, b);
  38037. };
  38038. return function (d, b) {
  38039. if (typeof b !== "function" && b !== null)
  38040. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  38041. extendStatics(d, b);
  38042. function __() { this.constructor = d; }
  38043. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  38044. };
  38045. })();
  38046. var __importDefault = (root && root.__importDefault) || function (mod) {
  38047. return (mod && mod.__esModule) ? mod : { "default": mod };
  38048. };
  38049. Object.defineProperty(root, "__esModule", { value: true });
  38050. var container_1 = __importDefault(/*@__PURE__*/ requireContainer());
  38051. var types_1 = /*@__PURE__*/ requireTypes();
  38052. var Root = /** @class */ (function (_super) {
  38053. __extends(Root, _super);
  38054. function Root(opts) {
  38055. var _this = _super.call(this, opts) || this;
  38056. _this.type = types_1.ROOT;
  38057. return _this;
  38058. }
  38059. Root.prototype._stringify = function (options, depth, max) {
  38060. var _this = this;
  38061. var str = this.reduce(function (memo, selector) {
  38062. memo.push(_this._stringifyChild(selector, options, depth, max));
  38063. return memo;
  38064. }, []).join(",");
  38065. return this.trailingComma ? str + "," : str;
  38066. };
  38067. Root.prototype.error = function (message, options) {
  38068. if (this._error) {
  38069. return this._error(message, options);
  38070. }
  38071. else {
  38072. return new Error(message);
  38073. }
  38074. };
  38075. Object.defineProperty(Root.prototype, "errorGenerator", {
  38076. set: function (handler) {
  38077. this._error = handler;
  38078. },
  38079. enumerable: false,
  38080. configurable: true
  38081. });
  38082. return Root;
  38083. }(container_1.default));
  38084. root.default = Root;
  38085. return root;
  38086. }
  38087. var selector = {};
  38088. var hasRequiredSelector;
  38089. function requireSelector () {
  38090. if (hasRequiredSelector) return selector;
  38091. hasRequiredSelector = 1;
  38092. var __extends = (selector && selector.__extends) || (function () {
  38093. var extendStatics = function (d, b) {
  38094. extendStatics = Object.setPrototypeOf ||
  38095. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  38096. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  38097. return extendStatics(d, b);
  38098. };
  38099. return function (d, b) {
  38100. if (typeof b !== "function" && b !== null)
  38101. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  38102. extendStatics(d, b);
  38103. function __() { this.constructor = d; }
  38104. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  38105. };
  38106. })();
  38107. var __importDefault = (selector && selector.__importDefault) || function (mod) {
  38108. return (mod && mod.__esModule) ? mod : { "default": mod };
  38109. };
  38110. Object.defineProperty(selector, "__esModule", { value: true });
  38111. var container_1 = __importDefault(/*@__PURE__*/ requireContainer());
  38112. var types_1 = /*@__PURE__*/ requireTypes();
  38113. var Selector = /** @class */ (function (_super) {
  38114. __extends(Selector, _super);
  38115. function Selector(opts) {
  38116. var _this = _super.call(this, opts) || this;
  38117. _this.type = types_1.SELECTOR;
  38118. return _this;
  38119. }
  38120. return Selector;
  38121. }(container_1.default));
  38122. selector.default = Selector;
  38123. return selector;
  38124. }
  38125. var className = {};
  38126. /*! https://mths.be/cssesc v3.0.0 by @mathias */
  38127. var cssesc_1;
  38128. var hasRequiredCssesc;
  38129. function requireCssesc () {
  38130. if (hasRequiredCssesc) return cssesc_1;
  38131. hasRequiredCssesc = 1;
  38132. var object = {};
  38133. var hasOwnProperty = object.hasOwnProperty;
  38134. var merge = function merge(options, defaults) {
  38135. if (!options) {
  38136. return defaults;
  38137. }
  38138. var result = {};
  38139. for (var key in defaults) {
  38140. // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
  38141. // only recognized option names are used.
  38142. result[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key];
  38143. }
  38144. return result;
  38145. };
  38146. var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
  38147. var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
  38148. var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  38149. // https://mathiasbynens.be/notes/css-escapes#css
  38150. var cssesc = function cssesc(string, options) {
  38151. options = merge(options, cssesc.options);
  38152. if (options.quotes != 'single' && options.quotes != 'double') {
  38153. options.quotes = 'single';
  38154. }
  38155. var quote = options.quotes == 'double' ? '"' : '\'';
  38156. var isIdentifier = options.isIdentifier;
  38157. var firstChar = string.charAt(0);
  38158. var output = '';
  38159. var counter = 0;
  38160. var length = string.length;
  38161. while (counter < length) {
  38162. var character = string.charAt(counter++);
  38163. var codePoint = character.charCodeAt();
  38164. var value = void 0;
  38165. // If it’s not a printable ASCII character…
  38166. if (codePoint < 0x20 || codePoint > 0x7E) {
  38167. if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
  38168. // It’s a high surrogate, and there is a next character.
  38169. var extra = string.charCodeAt(counter++);
  38170. if ((extra & 0xFC00) == 0xDC00) {
  38171. // next character is low surrogate
  38172. codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
  38173. } else {
  38174. // It’s an unmatched surrogate; only append this code unit, in case
  38175. // the next code unit is the high surrogate of a surrogate pair.
  38176. counter--;
  38177. }
  38178. }
  38179. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  38180. } else {
  38181. if (options.escapeEverything) {
  38182. if (regexAnySingleEscape.test(character)) {
  38183. value = '\\' + character;
  38184. } else {
  38185. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  38186. }
  38187. } else if (/[\t\n\f\r\x0B]/.test(character)) {
  38188. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  38189. } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
  38190. value = '\\' + character;
  38191. } else {
  38192. value = character;
  38193. }
  38194. }
  38195. output += value;
  38196. }
  38197. if (isIdentifier) {
  38198. if (/^-[-\d]/.test(output)) {
  38199. output = '\\-' + output.slice(1);
  38200. } else if (/\d/.test(firstChar)) {
  38201. output = '\\3' + firstChar + ' ' + output.slice(1);
  38202. }
  38203. }
  38204. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  38205. // since they’re redundant. Note that this is only possible if the escape
  38206. // sequence isn’t preceded by an odd number of backslashes.
  38207. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
  38208. if ($1 && $1.length % 2) {
  38209. // It’s not safe to remove the space, so don’t.
  38210. return $0;
  38211. }
  38212. // Strip the space.
  38213. return ($1 || '') + $2;
  38214. });
  38215. if (!isIdentifier && options.wrap) {
  38216. return quote + output + quote;
  38217. }
  38218. return output;
  38219. };
  38220. // Expose default options (so they can be overridden globally).
  38221. cssesc.options = {
  38222. 'escapeEverything': false,
  38223. 'isIdentifier': false,
  38224. 'quotes': 'single',
  38225. 'wrap': false
  38226. };
  38227. cssesc.version = '3.0.0';
  38228. cssesc_1 = cssesc;
  38229. return cssesc_1;
  38230. }
  38231. var hasRequiredClassName;
  38232. function requireClassName () {
  38233. if (hasRequiredClassName) return className;
  38234. hasRequiredClassName = 1;
  38235. var __extends = (className && className.__extends) || (function () {
  38236. var extendStatics = function (d, b) {
  38237. extendStatics = Object.setPrototypeOf ||
  38238. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  38239. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  38240. return extendStatics(d, b);
  38241. };
  38242. return function (d, b) {
  38243. if (typeof b !== "function" && b !== null)
  38244. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  38245. extendStatics(d, b);
  38246. function __() { this.constructor = d; }
  38247. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  38248. };
  38249. })();
  38250. var __importDefault = (className && className.__importDefault) || function (mod) {
  38251. return (mod && mod.__esModule) ? mod : { "default": mod };
  38252. };
  38253. Object.defineProperty(className, "__esModule", { value: true });
  38254. var cssesc_1 = __importDefault(/*@__PURE__*/ requireCssesc());
  38255. var util_1 = /*@__PURE__*/ requireUtil$1();
  38256. var node_1 = __importDefault(/*@__PURE__*/ requireNode$1());
  38257. var types_1 = /*@__PURE__*/ requireTypes();
  38258. var ClassName = /** @class */ (function (_super) {
  38259. __extends(ClassName, _super);
  38260. function ClassName(opts) {
  38261. var _this = _super.call(this, opts) || this;
  38262. _this.type = types_1.CLASS;
  38263. _this._constructed = true;
  38264. return _this;
  38265. }
  38266. Object.defineProperty(ClassName.prototype, "value", {
  38267. get: function () {
  38268. return this._value;
  38269. },
  38270. set: function (v) {
  38271. if (this._constructed) {
  38272. var escaped = (0, cssesc_1.default)(v, { isIdentifier: true });
  38273. if (escaped !== v) {
  38274. (0, util_1.ensureObject)(this, "raws");
  38275. this.raws.value = escaped;
  38276. }
  38277. else if (this.raws) {
  38278. delete this.raws.value;
  38279. }
  38280. }
  38281. this._value = v;
  38282. },
  38283. enumerable: false,
  38284. configurable: true
  38285. });
  38286. ClassName.prototype.valueToString = function () {
  38287. return "." + _super.prototype.valueToString.call(this);
  38288. };
  38289. return ClassName;
  38290. }(node_1.default));
  38291. className.default = ClassName;
  38292. return className;
  38293. }
  38294. var comment = {};
  38295. var hasRequiredComment;
  38296. function requireComment () {
  38297. if (hasRequiredComment) return comment;
  38298. hasRequiredComment = 1;
  38299. var __extends = (comment && comment.__extends) || (function () {
  38300. var extendStatics = function (d, b) {
  38301. extendStatics = Object.setPrototypeOf ||
  38302. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  38303. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  38304. return extendStatics(d, b);
  38305. };
  38306. return function (d, b) {
  38307. if (typeof b !== "function" && b !== null)
  38308. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  38309. extendStatics(d, b);
  38310. function __() { this.constructor = d; }
  38311. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  38312. };
  38313. })();
  38314. var __importDefault = (comment && comment.__importDefault) || function (mod) {
  38315. return (mod && mod.__esModule) ? mod : { "default": mod };
  38316. };
  38317. Object.defineProperty(comment, "__esModule", { value: true });
  38318. var node_1 = __importDefault(/*@__PURE__*/ requireNode$1());
  38319. var types_1 = /*@__PURE__*/ requireTypes();
  38320. var Comment = /** @class */ (function (_super) {
  38321. __extends(Comment, _super);
  38322. function Comment(opts) {
  38323. var _this = _super.call(this, opts) || this;
  38324. _this.type = types_1.COMMENT;
  38325. return _this;
  38326. }
  38327. return Comment;
  38328. }(node_1.default));
  38329. comment.default = Comment;
  38330. return comment;
  38331. }
  38332. var id = {};
  38333. var hasRequiredId;
  38334. function requireId () {
  38335. if (hasRequiredId) return id;
  38336. hasRequiredId = 1;
  38337. var __extends = (id && id.__extends) || (function () {
  38338. var extendStatics = function (d, b) {
  38339. extendStatics = Object.setPrototypeOf ||
  38340. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  38341. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  38342. return extendStatics(d, b);
  38343. };
  38344. return function (d, b) {
  38345. if (typeof b !== "function" && b !== null)
  38346. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  38347. extendStatics(d, b);
  38348. function __() { this.constructor = d; }
  38349. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  38350. };
  38351. })();
  38352. var __importDefault = (id && id.__importDefault) || function (mod) {
  38353. return (mod && mod.__esModule) ? mod : { "default": mod };
  38354. };
  38355. Object.defineProperty(id, "__esModule", { value: true });
  38356. var node_1 = __importDefault(/*@__PURE__*/ requireNode$1());
  38357. var types_1 = /*@__PURE__*/ requireTypes();
  38358. var ID = /** @class */ (function (_super) {
  38359. __extends(ID, _super);
  38360. function ID(opts) {
  38361. var _this = _super.call(this, opts) || this;
  38362. _this.type = types_1.ID;
  38363. return _this;
  38364. }
  38365. ID.prototype.valueToString = function () {
  38366. return "#" + _super.prototype.valueToString.call(this);
  38367. };
  38368. return ID;
  38369. }(node_1.default));
  38370. id.default = ID;
  38371. return id;
  38372. }
  38373. var tag = {};
  38374. var namespace = {};
  38375. var hasRequiredNamespace;
  38376. function requireNamespace () {
  38377. if (hasRequiredNamespace) return namespace;
  38378. hasRequiredNamespace = 1;
  38379. var __extends = (namespace && namespace.__extends) || (function () {
  38380. var extendStatics = function (d, b) {
  38381. extendStatics = Object.setPrototypeOf ||
  38382. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  38383. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  38384. return extendStatics(d, b);
  38385. };
  38386. return function (d, b) {
  38387. if (typeof b !== "function" && b !== null)
  38388. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  38389. extendStatics(d, b);
  38390. function __() { this.constructor = d; }
  38391. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  38392. };
  38393. })();
  38394. var __importDefault = (namespace && namespace.__importDefault) || function (mod) {
  38395. return (mod && mod.__esModule) ? mod : { "default": mod };
  38396. };
  38397. Object.defineProperty(namespace, "__esModule", { value: true });
  38398. var cssesc_1 = __importDefault(/*@__PURE__*/ requireCssesc());
  38399. var util_1 = /*@__PURE__*/ requireUtil$1();
  38400. var node_1 = __importDefault(/*@__PURE__*/ requireNode$1());
  38401. var Namespace = /** @class */ (function (_super) {
  38402. __extends(Namespace, _super);
  38403. function Namespace() {
  38404. return _super !== null && _super.apply(this, arguments) || this;
  38405. }
  38406. Object.defineProperty(Namespace.prototype, "namespace", {
  38407. get: function () {
  38408. return this._namespace;
  38409. },
  38410. set: function (namespace) {
  38411. if (namespace === true || namespace === "*" || namespace === "&") {
  38412. this._namespace = namespace;
  38413. if (this.raws) {
  38414. delete this.raws.namespace;
  38415. }
  38416. return;
  38417. }
  38418. var escaped = (0, cssesc_1.default)(namespace, { isIdentifier: true });
  38419. this._namespace = namespace;
  38420. if (escaped !== namespace) {
  38421. (0, util_1.ensureObject)(this, "raws");
  38422. this.raws.namespace = escaped;
  38423. }
  38424. else if (this.raws) {
  38425. delete this.raws.namespace;
  38426. }
  38427. },
  38428. enumerable: false,
  38429. configurable: true
  38430. });
  38431. Object.defineProperty(Namespace.prototype, "ns", {
  38432. get: function () {
  38433. return this._namespace;
  38434. },
  38435. set: function (namespace) {
  38436. this.namespace = namespace;
  38437. },
  38438. enumerable: false,
  38439. configurable: true
  38440. });
  38441. Object.defineProperty(Namespace.prototype, "namespaceString", {
  38442. get: function () {
  38443. if (this.namespace) {
  38444. var ns = this.stringifyProperty("namespace");
  38445. if (ns === true) {
  38446. return "";
  38447. }
  38448. else {
  38449. return ns;
  38450. }
  38451. }
  38452. else {
  38453. return "";
  38454. }
  38455. },
  38456. enumerable: false,
  38457. configurable: true
  38458. });
  38459. Namespace.prototype.qualifiedName = function (value) {
  38460. if (this.namespace) {
  38461. return "".concat(this.namespaceString, "|").concat(value);
  38462. }
  38463. else {
  38464. return value;
  38465. }
  38466. };
  38467. Namespace.prototype.valueToString = function () {
  38468. return this.qualifiedName(_super.prototype.valueToString.call(this));
  38469. };
  38470. return Namespace;
  38471. }(node_1.default));
  38472. namespace.default = Namespace;
  38473. return namespace;
  38474. }
  38475. var hasRequiredTag;
  38476. function requireTag () {
  38477. if (hasRequiredTag) return tag;
  38478. hasRequiredTag = 1;
  38479. var __extends = (tag && tag.__extends) || (function () {
  38480. var extendStatics = function (d, b) {
  38481. extendStatics = Object.setPrototypeOf ||
  38482. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  38483. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  38484. return extendStatics(d, b);
  38485. };
  38486. return function (d, b) {
  38487. if (typeof b !== "function" && b !== null)
  38488. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  38489. extendStatics(d, b);
  38490. function __() { this.constructor = d; }
  38491. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  38492. };
  38493. })();
  38494. var __importDefault = (tag && tag.__importDefault) || function (mod) {
  38495. return (mod && mod.__esModule) ? mod : { "default": mod };
  38496. };
  38497. Object.defineProperty(tag, "__esModule", { value: true });
  38498. var namespace_1 = __importDefault(/*@__PURE__*/ requireNamespace());
  38499. var types_1 = /*@__PURE__*/ requireTypes();
  38500. var Tag = /** @class */ (function (_super) {
  38501. __extends(Tag, _super);
  38502. function Tag(opts) {
  38503. var _this = _super.call(this, opts) || this;
  38504. _this.type = types_1.TAG;
  38505. return _this;
  38506. }
  38507. return Tag;
  38508. }(namespace_1.default));
  38509. tag.default = Tag;
  38510. return tag;
  38511. }
  38512. var string = {};
  38513. var hasRequiredString;
  38514. function requireString () {
  38515. if (hasRequiredString) return string;
  38516. hasRequiredString = 1;
  38517. var __extends = (string && string.__extends) || (function () {
  38518. var extendStatics = function (d, b) {
  38519. extendStatics = Object.setPrototypeOf ||
  38520. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  38521. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  38522. return extendStatics(d, b);
  38523. };
  38524. return function (d, b) {
  38525. if (typeof b !== "function" && b !== null)
  38526. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  38527. extendStatics(d, b);
  38528. function __() { this.constructor = d; }
  38529. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  38530. };
  38531. })();
  38532. var __importDefault = (string && string.__importDefault) || function (mod) {
  38533. return (mod && mod.__esModule) ? mod : { "default": mod };
  38534. };
  38535. Object.defineProperty(string, "__esModule", { value: true });
  38536. var node_1 = __importDefault(/*@__PURE__*/ requireNode$1());
  38537. var types_1 = /*@__PURE__*/ requireTypes();
  38538. var String = /** @class */ (function (_super) {
  38539. __extends(String, _super);
  38540. function String(opts) {
  38541. var _this = _super.call(this, opts) || this;
  38542. _this.type = types_1.STRING;
  38543. return _this;
  38544. }
  38545. return String;
  38546. }(node_1.default));
  38547. string.default = String;
  38548. return string;
  38549. }
  38550. var pseudo = {};
  38551. var hasRequiredPseudo;
  38552. function requirePseudo () {
  38553. if (hasRequiredPseudo) return pseudo;
  38554. hasRequiredPseudo = 1;
  38555. var __extends = (pseudo && pseudo.__extends) || (function () {
  38556. var extendStatics = function (d, b) {
  38557. extendStatics = Object.setPrototypeOf ||
  38558. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  38559. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  38560. return extendStatics(d, b);
  38561. };
  38562. return function (d, b) {
  38563. if (typeof b !== "function" && b !== null)
  38564. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  38565. extendStatics(d, b);
  38566. function __() { this.constructor = d; }
  38567. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  38568. };
  38569. })();
  38570. var __importDefault = (pseudo && pseudo.__importDefault) || function (mod) {
  38571. return (mod && mod.__esModule) ? mod : { "default": mod };
  38572. };
  38573. Object.defineProperty(pseudo, "__esModule", { value: true });
  38574. var container_1 = __importDefault(/*@__PURE__*/ requireContainer());
  38575. var types_1 = /*@__PURE__*/ requireTypes();
  38576. var Pseudo = /** @class */ (function (_super) {
  38577. __extends(Pseudo, _super);
  38578. function Pseudo(opts) {
  38579. var _this = _super.call(this, opts) || this;
  38580. _this.type = types_1.PSEUDO;
  38581. return _this;
  38582. }
  38583. Pseudo.prototype._stringify = function (options, depth, max) {
  38584. var _this = this;
  38585. if (depth >= max) {
  38586. throw new Error("Cannot serialize selector: nesting depth exceeds the maximum of ".concat(max, "."));
  38587. }
  38588. var params = this.length
  38589. ? "(" +
  38590. this.map(function (child) { return _this._stringifyChild(child, options, depth + 1, max); }).join(",") +
  38591. ")"
  38592. : "";
  38593. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join("");
  38594. };
  38595. return Pseudo;
  38596. }(container_1.default));
  38597. pseudo.default = Pseudo;
  38598. return pseudo;
  38599. }
  38600. var attribute = {};
  38601. var node;
  38602. var hasRequiredNode;
  38603. function requireNode () {
  38604. if (hasRequiredNode) return node;
  38605. hasRequiredNode = 1;
  38606. /**
  38607. * For Node.js, simply re-export the core `util.deprecate` function.
  38608. */
  38609. node = require$$0.deprecate;
  38610. return node;
  38611. }
  38612. var hasRequiredAttribute;
  38613. function requireAttribute () {
  38614. if (hasRequiredAttribute) return attribute;
  38615. hasRequiredAttribute = 1;
  38616. var __extends = (attribute && attribute.__extends) || (function () {
  38617. var extendStatics = function (d, b) {
  38618. extendStatics = Object.setPrototypeOf ||
  38619. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  38620. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  38621. return extendStatics(d, b);
  38622. };
  38623. return function (d, b) {
  38624. if (typeof b !== "function" && b !== null)
  38625. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  38626. extendStatics(d, b);
  38627. function __() { this.constructor = d; }
  38628. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  38629. };
  38630. })();
  38631. var __importDefault = (attribute && attribute.__importDefault) || function (mod) {
  38632. return (mod && mod.__esModule) ? mod : { "default": mod };
  38633. };
  38634. var _a;
  38635. Object.defineProperty(attribute, "__esModule", { value: true });
  38636. attribute.unescapeValue = unescapeValue;
  38637. var cssesc_1 = __importDefault(/*@__PURE__*/ requireCssesc());
  38638. var unesc_1 = __importDefault(/*@__PURE__*/ requireUnesc());
  38639. var namespace_1 = __importDefault(/*@__PURE__*/ requireNamespace());
  38640. var types_1 = /*@__PURE__*/ requireTypes();
  38641. var deprecate = /*@__PURE__*/ requireNode();
  38642. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  38643. var warnOfDeprecatedValueAssignment = deprecate(function () { }, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " +
  38644. "Call attribute.setValue() instead.");
  38645. var warnOfDeprecatedQuotedAssignment = deprecate(function () { }, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  38646. var warnOfDeprecatedConstructor = deprecate(function () { }, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  38647. function unescapeValue(value) {
  38648. var deprecatedUsage = false;
  38649. var quoteMark = null;
  38650. var unescaped = value;
  38651. var m = unescaped.match(WRAPPED_IN_QUOTES);
  38652. if (m) {
  38653. quoteMark = m[1];
  38654. unescaped = m[2];
  38655. }
  38656. unescaped = (0, unesc_1.default)(unescaped);
  38657. if (unescaped !== value) {
  38658. deprecatedUsage = true;
  38659. }
  38660. return {
  38661. deprecatedUsage: deprecatedUsage,
  38662. unescaped: unescaped,
  38663. quoteMark: quoteMark,
  38664. };
  38665. }
  38666. function handleDeprecatedContructorOpts(opts) {
  38667. if (opts.quoteMark !== undefined) {
  38668. return opts;
  38669. }
  38670. if (opts.value === undefined) {
  38671. return opts;
  38672. }
  38673. warnOfDeprecatedConstructor();
  38674. var _a = unescapeValue(opts.value), quoteMark = _a.quoteMark, unescaped = _a.unescaped;
  38675. if (!opts.raws) {
  38676. opts.raws = {};
  38677. }
  38678. if (opts.raws.value === undefined) {
  38679. opts.raws.value = opts.value;
  38680. }
  38681. opts.value = unescaped;
  38682. opts.quoteMark = quoteMark;
  38683. return opts;
  38684. }
  38685. var Attribute = /** @class */ (function (_super) {
  38686. __extends(Attribute, _super);
  38687. function Attribute(opts) {
  38688. if (opts === void 0) { opts = {}; }
  38689. var _this = _super.call(this, handleDeprecatedContructorOpts(opts)) || this;
  38690. _this.type = types_1.ATTRIBUTE;
  38691. _this.raws = _this.raws || {};
  38692. Object.defineProperty(_this.raws, "unquoted", {
  38693. get: deprecate(function () { return _this.value; }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  38694. set: deprecate(function () { return _this.value; }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now."),
  38695. });
  38696. _this._constructed = true;
  38697. return _this;
  38698. }
  38699. /**
  38700. * Returns the Attribute's value quoted such that it would be legal to use
  38701. * in the value of a css file. The original value's quotation setting
  38702. * used for stringification is left unchanged. See `setValue(value, options)`
  38703. * if you want to control the quote settings of a new value for the attribute.
  38704. *
  38705. * You can also change the quotation used for the current value by setting quoteMark.
  38706. *
  38707. * Options:
  38708. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  38709. * option is not set, the original value for quoteMark will be used. If
  38710. * indeterminate, a double quote is used. The legal values are:
  38711. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  38712. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  38713. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  38714. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  38715. * over the quoteMark option value.
  38716. * * smart {boolean} - if true, will select a quote mark based on the value
  38717. * and the other options specified here. See the `smartQuoteMark()`
  38718. * method.
  38719. **/
  38720. Attribute.prototype.getQuotedValue = function (options) {
  38721. if (options === void 0) { options = {}; }
  38722. var quoteMark = this._determineQuoteMark(options);
  38723. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  38724. var escaped = (0, cssesc_1.default)(this._value, cssescopts);
  38725. return escaped;
  38726. };
  38727. Attribute.prototype._determineQuoteMark = function (options) {
  38728. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  38729. };
  38730. /**
  38731. * Set the unescaped value with the specified quotation options. The value
  38732. * provided must not include any wrapping quote marks -- those quotes will
  38733. * be interpreted as part of the value and escaped accordingly.
  38734. */
  38735. Attribute.prototype.setValue = function (value, options) {
  38736. if (options === void 0) { options = {}; }
  38737. this._value = value;
  38738. this._quoteMark = this._determineQuoteMark(options);
  38739. this._syncRawValue();
  38740. };
  38741. /**
  38742. * Intelligently select a quoteMark value based on the value's contents. If
  38743. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  38744. * mark will be picked that minimizes the number of escapes.
  38745. *
  38746. * If there's no clear winner, the quote mark from these options is used,
  38747. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  38748. * true). If the quoteMark is unspecified, a double quote is used.
  38749. *
  38750. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  38751. * from the quoteValue method.
  38752. */
  38753. Attribute.prototype.smartQuoteMark = function (options) {
  38754. var v = this.value;
  38755. var numSingleQuotes = v.replace(/[^']/g, "").length;
  38756. var numDoubleQuotes = v.replace(/[^"]/g, "").length;
  38757. if (numSingleQuotes + numDoubleQuotes === 0) {
  38758. var escaped = (0, cssesc_1.default)(v, { isIdentifier: true });
  38759. if (escaped === v) {
  38760. return Attribute.NO_QUOTE;
  38761. }
  38762. else {
  38763. var pref = this.preferredQuoteMark(options);
  38764. if (pref === Attribute.NO_QUOTE) {
  38765. // pick a quote mark that isn't none and see if it's smaller
  38766. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  38767. var opts = CSSESC_QUOTE_OPTIONS[quote];
  38768. var quoteValue = (0, cssesc_1.default)(v, opts);
  38769. if (quoteValue.length < escaped.length) {
  38770. return quote;
  38771. }
  38772. }
  38773. return pref;
  38774. }
  38775. }
  38776. else if (numDoubleQuotes === numSingleQuotes) {
  38777. return this.preferredQuoteMark(options);
  38778. }
  38779. else if (numDoubleQuotes < numSingleQuotes) {
  38780. return Attribute.DOUBLE_QUOTE;
  38781. }
  38782. else {
  38783. return Attribute.SINGLE_QUOTE;
  38784. }
  38785. };
  38786. /**
  38787. * Selects the preferred quote mark based on the options and the current quote mark value.
  38788. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  38789. * instead.
  38790. */
  38791. Attribute.prototype.preferredQuoteMark = function (options) {
  38792. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  38793. if (quoteMark === undefined) {
  38794. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  38795. }
  38796. if (quoteMark === undefined) {
  38797. quoteMark = Attribute.DOUBLE_QUOTE;
  38798. }
  38799. return quoteMark;
  38800. };
  38801. Object.defineProperty(Attribute.prototype, "quoted", {
  38802. get: function () {
  38803. var qm = this.quoteMark;
  38804. return qm === "'" || qm === '"';
  38805. },
  38806. set: function (value) {
  38807. warnOfDeprecatedQuotedAssignment();
  38808. },
  38809. enumerable: false,
  38810. configurable: true
  38811. });
  38812. Object.defineProperty(Attribute.prototype, "quoteMark", {
  38813. /**
  38814. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  38815. * returns `null` if the value is not quoted.
  38816. * returns `undefined` if the quotation state is unknown (this can happen when
  38817. * the attribute is constructed without specifying a quote mark.)
  38818. */
  38819. get: function () {
  38820. return this._quoteMark;
  38821. },
  38822. /**
  38823. * Set the quote mark to be used by this attribute's value.
  38824. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  38825. * value is updated accordingly.
  38826. *
  38827. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  38828. */
  38829. set: function (quoteMark) {
  38830. if (!this._constructed) {
  38831. this._quoteMark = quoteMark;
  38832. return;
  38833. }
  38834. if (this._quoteMark !== quoteMark) {
  38835. this._quoteMark = quoteMark;
  38836. this._syncRawValue();
  38837. }
  38838. },
  38839. enumerable: false,
  38840. configurable: true
  38841. });
  38842. Attribute.prototype._syncRawValue = function () {
  38843. var rawValue = (0, cssesc_1.default)(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  38844. if (rawValue === this._value) {
  38845. if (this.raws) {
  38846. delete this.raws.value;
  38847. }
  38848. }
  38849. else {
  38850. this.raws.value = rawValue;
  38851. }
  38852. };
  38853. Object.defineProperty(Attribute.prototype, "qualifiedAttribute", {
  38854. get: function () {
  38855. return this.qualifiedName(this.raws.attribute || this.attribute);
  38856. },
  38857. enumerable: false,
  38858. configurable: true
  38859. });
  38860. Object.defineProperty(Attribute.prototype, "insensitiveFlag", {
  38861. get: function () {
  38862. return this.insensitive ? "i" : "";
  38863. },
  38864. enumerable: false,
  38865. configurable: true
  38866. });
  38867. Object.defineProperty(Attribute.prototype, "value", {
  38868. get: function () {
  38869. return this._value;
  38870. },
  38871. /**
  38872. * Before 3.0, the value had to be set to an escaped value including any wrapped
  38873. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  38874. * is unescaped during parsing and any quote marks are removed.
  38875. *
  38876. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  38877. * a deprecation warning is raised when the new value contains any characters that would
  38878. * require escaping (including if it contains wrapped quotes).
  38879. *
  38880. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  38881. * how the new value is quoted.
  38882. */
  38883. set: function (v) {
  38884. if (this._constructed) {
  38885. var _a = unescapeValue(v), deprecatedUsage = _a.deprecatedUsage, unescaped = _a.unescaped, quoteMark = _a.quoteMark;
  38886. if (deprecatedUsage) {
  38887. warnOfDeprecatedValueAssignment();
  38888. }
  38889. if (unescaped === this._value && quoteMark === this._quoteMark) {
  38890. return;
  38891. }
  38892. this._value = unescaped;
  38893. this._quoteMark = quoteMark;
  38894. this._syncRawValue();
  38895. }
  38896. else {
  38897. this._value = v;
  38898. }
  38899. },
  38900. enumerable: false,
  38901. configurable: true
  38902. });
  38903. Object.defineProperty(Attribute.prototype, "insensitive", {
  38904. get: function () {
  38905. return this._insensitive;
  38906. },
  38907. /**
  38908. * Set the case insensitive flag.
  38909. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  38910. * of the attribute is updated accordingly.
  38911. *
  38912. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  38913. */
  38914. set: function (insensitive) {
  38915. if (!insensitive) {
  38916. this._insensitive = false;
  38917. // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  38918. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  38919. if (this.raws && (this.raws.insensitiveFlag === "I" || this.raws.insensitiveFlag === "i")) {
  38920. this.raws.insensitiveFlag = undefined;
  38921. }
  38922. }
  38923. this._insensitive = insensitive;
  38924. },
  38925. enumerable: false,
  38926. configurable: true
  38927. });
  38928. Object.defineProperty(Attribute.prototype, "attribute", {
  38929. get: function () {
  38930. return this._attribute;
  38931. },
  38932. set: function (name) {
  38933. this._handleEscapes("attribute", name);
  38934. this._attribute = name;
  38935. },
  38936. enumerable: false,
  38937. configurable: true
  38938. });
  38939. Attribute.prototype._handleEscapes = function (prop, value) {
  38940. if (this._constructed) {
  38941. var escaped = (0, cssesc_1.default)(value, { isIdentifier: true });
  38942. if (escaped !== value) {
  38943. this.raws[prop] = escaped;
  38944. }
  38945. else {
  38946. delete this.raws[prop];
  38947. }
  38948. }
  38949. };
  38950. Attribute.prototype._spacesFor = function (name) {
  38951. var attrSpaces = { before: "", after: "" };
  38952. var spaces = this.spaces[name] || {};
  38953. var rawSpaces = (this.raws.spaces && this.raws.spaces[name]) || {};
  38954. return Object.assign(attrSpaces, spaces, rawSpaces);
  38955. };
  38956. Attribute.prototype._stringFor = function (name, spaceName, concat) {
  38957. if (spaceName === void 0) { spaceName = name; }
  38958. if (concat === void 0) { concat = defaultAttrConcat; }
  38959. var attrSpaces = this._spacesFor(spaceName);
  38960. return concat(this.stringifyProperty(name), attrSpaces);
  38961. };
  38962. /**
  38963. * returns the offset of the attribute part specified relative to the
  38964. * start of the node of the output string.
  38965. *
  38966. * * "ns" - alias for "namespace"
  38967. * * "namespace" - the namespace if it exists.
  38968. * * "attribute" - the attribute name
  38969. * * "attributeNS" - the start of the attribute or its namespace
  38970. * * "operator" - the match operator of the attribute
  38971. * * "value" - The value (string or identifier)
  38972. * * "insensitive" - the case insensitivity flag;
  38973. * @param part One of the possible values inside an attribute.
  38974. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  38975. */
  38976. Attribute.prototype.offsetOf = function (name) {
  38977. var count = 1;
  38978. var attributeSpaces = this._spacesFor("attribute");
  38979. count += attributeSpaces.before.length;
  38980. if (name === "namespace" || name === "ns") {
  38981. return this.namespace ? count : -1;
  38982. }
  38983. if (name === "attributeNS") {
  38984. return count;
  38985. }
  38986. count += this.namespaceString.length;
  38987. if (this.namespace) {
  38988. count += 1;
  38989. }
  38990. if (name === "attribute") {
  38991. return count;
  38992. }
  38993. count += this.stringifyProperty("attribute").length;
  38994. count += attributeSpaces.after.length;
  38995. var operatorSpaces = this._spacesFor("operator");
  38996. count += operatorSpaces.before.length;
  38997. var operator = this.stringifyProperty("operator");
  38998. if (name === "operator") {
  38999. return operator ? count : -1;
  39000. }
  39001. count += operator.length;
  39002. count += operatorSpaces.after.length;
  39003. var valueSpaces = this._spacesFor("value");
  39004. count += valueSpaces.before.length;
  39005. var value = this.stringifyProperty("value");
  39006. if (name === "value") {
  39007. return value ? count : -1;
  39008. }
  39009. count += value.length;
  39010. count += valueSpaces.after.length;
  39011. var insensitiveSpaces = this._spacesFor("insensitive");
  39012. count += insensitiveSpaces.before.length;
  39013. if (name === "insensitive") {
  39014. return this.insensitive ? count : -1;
  39015. }
  39016. return -1;
  39017. };
  39018. Attribute.prototype.toString = function () {
  39019. var _this = this;
  39020. var selector = [this.rawSpaceBefore, "["];
  39021. selector.push(this._stringFor("qualifiedAttribute", "attribute"));
  39022. if (this.operator && (this.value || this.value === "")) {
  39023. selector.push(this._stringFor("operator"));
  39024. selector.push(this._stringFor("value"));
  39025. selector.push(this._stringFor("insensitiveFlag", "insensitive", function (attrValue, attrSpaces) {
  39026. if (attrValue.length > 0 &&
  39027. !_this.quoted &&
  39028. attrSpaces.before.length === 0 &&
  39029. !(_this.spaces.value && _this.spaces.value.after)) {
  39030. attrSpaces.before = " ";
  39031. }
  39032. return defaultAttrConcat(attrValue, attrSpaces);
  39033. }));
  39034. }
  39035. selector.push("]");
  39036. selector.push(this.rawSpaceAfter);
  39037. return selector.join("");
  39038. };
  39039. Attribute.NO_QUOTE = null;
  39040. Attribute.SINGLE_QUOTE = "'";
  39041. Attribute.DOUBLE_QUOTE = '"';
  39042. return Attribute;
  39043. }(namespace_1.default));
  39044. attribute.default = Attribute;
  39045. var CSSESC_QUOTE_OPTIONS = (_a = {
  39046. "'": { quotes: "single", wrap: true },
  39047. '"': { quotes: "double", wrap: true }
  39048. },
  39049. _a[null] = { isIdentifier: true },
  39050. _a);
  39051. function defaultAttrConcat(attrValue, attrSpaces) {
  39052. return "".concat(attrSpaces.before).concat(attrValue).concat(attrSpaces.after);
  39053. }
  39054. return attribute;
  39055. }
  39056. var universal = {};
  39057. var hasRequiredUniversal;
  39058. function requireUniversal () {
  39059. if (hasRequiredUniversal) return universal;
  39060. hasRequiredUniversal = 1;
  39061. var __extends = (universal && universal.__extends) || (function () {
  39062. var extendStatics = function (d, b) {
  39063. extendStatics = Object.setPrototypeOf ||
  39064. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  39065. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  39066. return extendStatics(d, b);
  39067. };
  39068. return function (d, b) {
  39069. if (typeof b !== "function" && b !== null)
  39070. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  39071. extendStatics(d, b);
  39072. function __() { this.constructor = d; }
  39073. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  39074. };
  39075. })();
  39076. var __importDefault = (universal && universal.__importDefault) || function (mod) {
  39077. return (mod && mod.__esModule) ? mod : { "default": mod };
  39078. };
  39079. Object.defineProperty(universal, "__esModule", { value: true });
  39080. var namespace_1 = __importDefault(/*@__PURE__*/ requireNamespace());
  39081. var types_1 = /*@__PURE__*/ requireTypes();
  39082. var Universal = /** @class */ (function (_super) {
  39083. __extends(Universal, _super);
  39084. function Universal(opts) {
  39085. var _this = _super.call(this, opts) || this;
  39086. _this.type = types_1.UNIVERSAL;
  39087. _this.value = "*";
  39088. return _this;
  39089. }
  39090. return Universal;
  39091. }(namespace_1.default));
  39092. universal.default = Universal;
  39093. return universal;
  39094. }
  39095. var combinator = {};
  39096. var hasRequiredCombinator;
  39097. function requireCombinator () {
  39098. if (hasRequiredCombinator) return combinator;
  39099. hasRequiredCombinator = 1;
  39100. var __extends = (combinator && combinator.__extends) || (function () {
  39101. var extendStatics = function (d, b) {
  39102. extendStatics = Object.setPrototypeOf ||
  39103. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  39104. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  39105. return extendStatics(d, b);
  39106. };
  39107. return function (d, b) {
  39108. if (typeof b !== "function" && b !== null)
  39109. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  39110. extendStatics(d, b);
  39111. function __() { this.constructor = d; }
  39112. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  39113. };
  39114. })();
  39115. var __importDefault = (combinator && combinator.__importDefault) || function (mod) {
  39116. return (mod && mod.__esModule) ? mod : { "default": mod };
  39117. };
  39118. Object.defineProperty(combinator, "__esModule", { value: true });
  39119. var node_1 = __importDefault(/*@__PURE__*/ requireNode$1());
  39120. var types_1 = /*@__PURE__*/ requireTypes();
  39121. var Combinator = /** @class */ (function (_super) {
  39122. __extends(Combinator, _super);
  39123. function Combinator(opts) {
  39124. var _this = _super.call(this, opts) || this;
  39125. _this.type = types_1.COMBINATOR;
  39126. return _this;
  39127. }
  39128. return Combinator;
  39129. }(node_1.default));
  39130. combinator.default = Combinator;
  39131. return combinator;
  39132. }
  39133. var nesting = {};
  39134. var hasRequiredNesting;
  39135. function requireNesting () {
  39136. if (hasRequiredNesting) return nesting;
  39137. hasRequiredNesting = 1;
  39138. var __extends = (nesting && nesting.__extends) || (function () {
  39139. var extendStatics = function (d, b) {
  39140. extendStatics = Object.setPrototypeOf ||
  39141. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  39142. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  39143. return extendStatics(d, b);
  39144. };
  39145. return function (d, b) {
  39146. if (typeof b !== "function" && b !== null)
  39147. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  39148. extendStatics(d, b);
  39149. function __() { this.constructor = d; }
  39150. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  39151. };
  39152. })();
  39153. var __importDefault = (nesting && nesting.__importDefault) || function (mod) {
  39154. return (mod && mod.__esModule) ? mod : { "default": mod };
  39155. };
  39156. Object.defineProperty(nesting, "__esModule", { value: true });
  39157. var node_1 = __importDefault(/*@__PURE__*/ requireNode$1());
  39158. var types_1 = /*@__PURE__*/ requireTypes();
  39159. var Nesting = /** @class */ (function (_super) {
  39160. __extends(Nesting, _super);
  39161. function Nesting(opts) {
  39162. var _this = _super.call(this, opts) || this;
  39163. _this.type = types_1.NESTING;
  39164. _this.value = "&";
  39165. return _this;
  39166. }
  39167. return Nesting;
  39168. }(node_1.default));
  39169. nesting.default = Nesting;
  39170. return nesting;
  39171. }
  39172. var sortAscending = {};
  39173. var hasRequiredSortAscending;
  39174. function requireSortAscending () {
  39175. if (hasRequiredSortAscending) return sortAscending;
  39176. hasRequiredSortAscending = 1;
  39177. Object.defineProperty(sortAscending, "__esModule", { value: true });
  39178. sortAscending.default = sortAscending$1;
  39179. function sortAscending$1(list) {
  39180. return list.sort(function (a, b) { return a - b; });
  39181. }
  39182. return sortAscending;
  39183. }
  39184. var tokenize = {};
  39185. var tokenTypes = {};
  39186. var hasRequiredTokenTypes;
  39187. function requireTokenTypes () {
  39188. if (hasRequiredTokenTypes) return tokenTypes;
  39189. hasRequiredTokenTypes = 1;
  39190. (function (exports) {
  39191. Object.defineProperty(exports, "__esModule", { value: true });
  39192. exports.combinator = exports.word = exports.comment = exports.str = exports.tab = exports.newline = exports.feed = exports.cr = exports.backslash = exports.bang = exports.slash = exports.doubleQuote = exports.singleQuote = exports.space = exports.greaterThan = exports.pipe = exports.equals = exports.plus = exports.caret = exports.tilde = exports.dollar = exports.closeSquare = exports.openSquare = exports.closeParenthesis = exports.openParenthesis = exports.semicolon = exports.colon = exports.comma = exports.at = exports.asterisk = exports.ampersand = void 0;
  39193. exports.ampersand = 38; // `&`.charCodeAt(0);
  39194. exports.asterisk = 42; // `*`.charCodeAt(0);
  39195. exports.at = 64; // `@`.charCodeAt(0);
  39196. exports.comma = 44; // `,`.charCodeAt(0);
  39197. exports.colon = 58; // `:`.charCodeAt(0);
  39198. exports.semicolon = 59; // `;`.charCodeAt(0);
  39199. exports.openParenthesis = 40; // `(`.charCodeAt(0);
  39200. exports.closeParenthesis = 41; // `)`.charCodeAt(0);
  39201. exports.openSquare = 91; // `[`.charCodeAt(0);
  39202. exports.closeSquare = 93; // `]`.charCodeAt(0);
  39203. exports.dollar = 36; // `$`.charCodeAt(0);
  39204. exports.tilde = 126; // `~`.charCodeAt(0);
  39205. exports.caret = 94; // `^`.charCodeAt(0);
  39206. exports.plus = 43; // `+`.charCodeAt(0);
  39207. exports.equals = 61; // `=`.charCodeAt(0);
  39208. exports.pipe = 124; // `|`.charCodeAt(0);
  39209. exports.greaterThan = 62; // `>`.charCodeAt(0);
  39210. exports.space = 32; // ` `.charCodeAt(0);
  39211. exports.singleQuote = 39; // `'`.charCodeAt(0);
  39212. exports.doubleQuote = 34; // `"`.charCodeAt(0);
  39213. exports.slash = 47; // `/`.charCodeAt(0);
  39214. exports.bang = 33; // `!`.charCodeAt(0);
  39215. exports.backslash = 92; // '\\'.charCodeAt(0);
  39216. exports.cr = 13; // '\r'.charCodeAt(0);
  39217. exports.feed = 12; // '\f'.charCodeAt(0);
  39218. exports.newline = 10; // '\n'.charCodeAt(0);
  39219. exports.tab = 9; // '\t'.charCodeAt(0);
  39220. // Expose aliases primarily for readability.
  39221. exports.str = exports.singleQuote;
  39222. // No good single character representation!
  39223. exports.comment = -1;
  39224. exports.word = -2;
  39225. exports.combinator = -3;
  39226. } (tokenTypes));
  39227. return tokenTypes;
  39228. }
  39229. var hasRequiredTokenize;
  39230. function requireTokenize () {
  39231. if (hasRequiredTokenize) return tokenize;
  39232. hasRequiredTokenize = 1;
  39233. var __createBinding = (tokenize && tokenize.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  39234. if (k2 === undefined) k2 = k;
  39235. var desc = Object.getOwnPropertyDescriptor(m, k);
  39236. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  39237. desc = { enumerable: true, get: function() { return m[k]; } };
  39238. }
  39239. Object.defineProperty(o, k2, desc);
  39240. }) : (function(o, m, k, k2) {
  39241. if (k2 === undefined) k2 = k;
  39242. o[k2] = m[k];
  39243. }));
  39244. var __setModuleDefault = (tokenize && tokenize.__setModuleDefault) || (Object.create ? (function(o, v) {
  39245. Object.defineProperty(o, "default", { enumerable: true, value: v });
  39246. }) : function(o, v) {
  39247. o["default"] = v;
  39248. });
  39249. var __importStar = (tokenize && tokenize.__importStar) || (function () {
  39250. var ownKeys = function(o) {
  39251. ownKeys = Object.getOwnPropertyNames || function (o) {
  39252. var ar = [];
  39253. for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
  39254. return ar;
  39255. };
  39256. return ownKeys(o);
  39257. };
  39258. return function (mod) {
  39259. if (mod && mod.__esModule) return mod;
  39260. var result = {};
  39261. if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
  39262. __setModuleDefault(result, mod);
  39263. return result;
  39264. };
  39265. })();
  39266. var _a, _b;
  39267. Object.defineProperty(tokenize, "__esModule", { value: true });
  39268. tokenize.FIELDS = void 0;
  39269. tokenize.default = tokenize$1;
  39270. var t = __importStar(/*@__PURE__*/ requireTokenTypes());
  39271. var unescapable = (_a = {},
  39272. _a[t.tab] = true,
  39273. _a[t.newline] = true,
  39274. _a[t.cr] = true,
  39275. _a[t.feed] = true,
  39276. _a);
  39277. var wordDelimiters = (_b = {},
  39278. _b[t.space] = true,
  39279. _b[t.tab] = true,
  39280. _b[t.newline] = true,
  39281. _b[t.cr] = true,
  39282. _b[t.feed] = true,
  39283. _b[t.ampersand] = true,
  39284. _b[t.asterisk] = true,
  39285. _b[t.bang] = true,
  39286. _b[t.comma] = true,
  39287. _b[t.colon] = true,
  39288. _b[t.semicolon] = true,
  39289. _b[t.openParenthesis] = true,
  39290. _b[t.closeParenthesis] = true,
  39291. _b[t.openSquare] = true,
  39292. _b[t.closeSquare] = true,
  39293. _b[t.singleQuote] = true,
  39294. _b[t.doubleQuote] = true,
  39295. _b[t.plus] = true,
  39296. _b[t.pipe] = true,
  39297. _b[t.tilde] = true,
  39298. _b[t.greaterThan] = true,
  39299. _b[t.equals] = true,
  39300. _b[t.dollar] = true,
  39301. _b[t.caret] = true,
  39302. _b[t.slash] = true,
  39303. _b);
  39304. var hex = {};
  39305. var hexChars = "0123456789abcdefABCDEF";
  39306. for (var i = 0; i < hexChars.length; i++) {
  39307. hex[hexChars.charCodeAt(i)] = true;
  39308. }
  39309. /**
  39310. * Returns the last index of the bar css word
  39311. * @param {string} css The string in which the word begins
  39312. * @param {number} start The index into the string where word's first letter occurs
  39313. */
  39314. function consumeWord(css, start) {
  39315. var next = start;
  39316. var code;
  39317. do {
  39318. code = css.charCodeAt(next);
  39319. if (wordDelimiters[code]) {
  39320. return next - 1;
  39321. }
  39322. else if (code === t.backslash) {
  39323. next = consumeEscape(css, next) + 1;
  39324. }
  39325. else {
  39326. // All other characters are part of the word
  39327. next++;
  39328. }
  39329. } while (next < css.length);
  39330. return next - 1;
  39331. }
  39332. /**
  39333. * Returns the last index of the escape sequence
  39334. * @param {string} css The string in which the sequence begins
  39335. * @param {number} start The index into the string where escape character (`\`) occurs.
  39336. */
  39337. function consumeEscape(css, start) {
  39338. var next = start;
  39339. var code = css.charCodeAt(next + 1);
  39340. if (unescapable[code]) ;
  39341. else if (hex[code]) {
  39342. var hexDigits = 0;
  39343. // consume up to 6 hex chars
  39344. do {
  39345. next++;
  39346. hexDigits++;
  39347. code = css.charCodeAt(next + 1);
  39348. } while (hex[code] && hexDigits < 6);
  39349. // if fewer than 6 hex chars, a trailing space ends the escape
  39350. if (hexDigits < 6 && code === t.space) {
  39351. next++;
  39352. }
  39353. }
  39354. else {
  39355. // the next char is part of the current word
  39356. next++;
  39357. }
  39358. return next;
  39359. }
  39360. tokenize.FIELDS = {
  39361. TYPE: 0,
  39362. START_LINE: 1,
  39363. START_COL: 2,
  39364. END_LINE: 3,
  39365. END_COL: 4,
  39366. START_POS: 5,
  39367. END_POS: 6,
  39368. };
  39369. function tokenize$1(input) {
  39370. var tokens = [];
  39371. var css = input.css.valueOf();
  39372. var length = css.length;
  39373. var offset = -1;
  39374. var line = 1;
  39375. var start = 0;
  39376. var end = 0;
  39377. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  39378. function unclosed(what, fix) {
  39379. if (input.safe) {
  39380. // fyi: this is never set to true.
  39381. css += fix;
  39382. next = css.length - 1;
  39383. }
  39384. else {
  39385. throw input.error("Unclosed " + what, line, start - offset, start);
  39386. }
  39387. }
  39388. while (start < length) {
  39389. code = css.charCodeAt(start);
  39390. if (code === t.newline) {
  39391. offset = start;
  39392. line += 1;
  39393. }
  39394. switch (code) {
  39395. case t.space:
  39396. case t.tab:
  39397. case t.newline:
  39398. case t.cr:
  39399. case t.feed:
  39400. next = start;
  39401. do {
  39402. next += 1;
  39403. code = css.charCodeAt(next);
  39404. if (code === t.newline) {
  39405. offset = next;
  39406. line += 1;
  39407. }
  39408. } while (code === t.space ||
  39409. code === t.newline ||
  39410. code === t.tab ||
  39411. code === t.cr ||
  39412. code === t.feed);
  39413. tokenType = t.space;
  39414. endLine = line;
  39415. endColumn = next - offset - 1;
  39416. end = next;
  39417. break;
  39418. case t.plus:
  39419. case t.greaterThan:
  39420. case t.tilde:
  39421. case t.pipe:
  39422. next = start;
  39423. do {
  39424. next += 1;
  39425. code = css.charCodeAt(next);
  39426. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  39427. tokenType = t.combinator;
  39428. endLine = line;
  39429. endColumn = start - offset;
  39430. end = next;
  39431. break;
  39432. // Consume these characters as single tokens.
  39433. case t.asterisk:
  39434. case t.ampersand:
  39435. case t.bang:
  39436. case t.comma:
  39437. case t.equals:
  39438. case t.dollar:
  39439. case t.caret:
  39440. case t.openSquare:
  39441. case t.closeSquare:
  39442. case t.colon:
  39443. case t.semicolon:
  39444. case t.openParenthesis:
  39445. case t.closeParenthesis:
  39446. next = start;
  39447. tokenType = code;
  39448. endLine = line;
  39449. endColumn = start - offset;
  39450. end = next + 1;
  39451. break;
  39452. case t.singleQuote:
  39453. case t.doubleQuote:
  39454. quote = code === t.singleQuote ? "'" : '"';
  39455. next = start;
  39456. do {
  39457. escaped = false;
  39458. next = css.indexOf(quote, next + 1);
  39459. if (next === -1) {
  39460. unclosed("quote", quote);
  39461. }
  39462. escapePos = next;
  39463. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  39464. escapePos -= 1;
  39465. escaped = !escaped;
  39466. }
  39467. } while (escaped);
  39468. tokenType = t.str;
  39469. endLine = line;
  39470. endColumn = start - offset;
  39471. end = next + 1;
  39472. break;
  39473. default:
  39474. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  39475. next = css.indexOf("*/", start + 2) + 1;
  39476. if (next === 0) {
  39477. unclosed("comment", "*/");
  39478. }
  39479. content = css.slice(start, next + 1);
  39480. lines = content.split("\n");
  39481. last = lines.length - 1;
  39482. if (last > 0) {
  39483. nextLine = line + last;
  39484. nextOffset = next - lines[last].length;
  39485. }
  39486. else {
  39487. nextLine = line;
  39488. nextOffset = offset;
  39489. }
  39490. tokenType = t.comment;
  39491. line = nextLine;
  39492. endLine = nextLine;
  39493. endColumn = next - nextOffset;
  39494. }
  39495. else if (code === t.slash) {
  39496. next = start;
  39497. tokenType = code;
  39498. endLine = line;
  39499. endColumn = start - offset;
  39500. end = next + 1;
  39501. }
  39502. else {
  39503. next = consumeWord(css, start);
  39504. tokenType = t.word;
  39505. endLine = line;
  39506. endColumn = next - offset;
  39507. }
  39508. end = next + 1;
  39509. break;
  39510. }
  39511. // Ensure that the token structure remains consistent
  39512. tokens.push([
  39513. tokenType, // [0] Token type
  39514. line, // [1] Starting line
  39515. start - offset, // [2] Starting column
  39516. endLine, // [3] Ending line
  39517. endColumn, // [4] Ending column
  39518. start, // [5] Start position / Source index
  39519. end, // [6] End position
  39520. ]);
  39521. // Reset offset for the next token
  39522. if (nextOffset) {
  39523. offset = nextOffset;
  39524. nextOffset = null;
  39525. }
  39526. start = end;
  39527. }
  39528. return tokens;
  39529. }
  39530. return tokenize;
  39531. }
  39532. var hasRequiredParser;
  39533. function requireParser () {
  39534. if (hasRequiredParser) return parser;
  39535. hasRequiredParser = 1;
  39536. var __assign = (parser && parser.__assign) || function () {
  39537. __assign = Object.assign || function(t) {
  39538. for (var s, i = 1, n = arguments.length; i < n; i++) {
  39539. s = arguments[i];
  39540. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  39541. t[p] = s[p];
  39542. }
  39543. return t;
  39544. };
  39545. return __assign.apply(this, arguments);
  39546. };
  39547. var __createBinding = (parser && parser.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  39548. if (k2 === undefined) k2 = k;
  39549. var desc = Object.getOwnPropertyDescriptor(m, k);
  39550. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  39551. desc = { enumerable: true, get: function() { return m[k]; } };
  39552. }
  39553. Object.defineProperty(o, k2, desc);
  39554. }) : (function(o, m, k, k2) {
  39555. if (k2 === undefined) k2 = k;
  39556. o[k2] = m[k];
  39557. }));
  39558. var __setModuleDefault = (parser && parser.__setModuleDefault) || (Object.create ? (function(o, v) {
  39559. Object.defineProperty(o, "default", { enumerable: true, value: v });
  39560. }) : function(o, v) {
  39561. o["default"] = v;
  39562. });
  39563. var __importStar = (parser && parser.__importStar) || (function () {
  39564. var ownKeys = function(o) {
  39565. ownKeys = Object.getOwnPropertyNames || function (o) {
  39566. var ar = [];
  39567. for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
  39568. return ar;
  39569. };
  39570. return ownKeys(o);
  39571. };
  39572. return function (mod) {
  39573. if (mod && mod.__esModule) return mod;
  39574. var result = {};
  39575. if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
  39576. __setModuleDefault(result, mod);
  39577. return result;
  39578. };
  39579. })();
  39580. var __read = (parser && parser.__read) || function (o, n) {
  39581. var m = typeof Symbol === "function" && o[Symbol.iterator];
  39582. if (!m) return o;
  39583. var i = m.call(o), r, ar = [], e;
  39584. try {
  39585. while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  39586. }
  39587. catch (error) { e = { error: error }; }
  39588. finally {
  39589. try {
  39590. if (r && !r.done && (m = i["return"])) m.call(i);
  39591. }
  39592. finally { if (e) throw e.error; }
  39593. }
  39594. return ar;
  39595. };
  39596. var __spreadArray = (parser && parser.__spreadArray) || function (to, from, pack) {
  39597. if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
  39598. if (ar || !(i in from)) {
  39599. if (!ar) ar = Array.prototype.slice.call(from, 0, i);
  39600. ar[i] = from[i];
  39601. }
  39602. }
  39603. return to.concat(ar || Array.prototype.slice.call(from));
  39604. };
  39605. var __importDefault = (parser && parser.__importDefault) || function (mod) {
  39606. return (mod && mod.__esModule) ? mod : { "default": mod };
  39607. };
  39608. var _a, _b;
  39609. Object.defineProperty(parser, "__esModule", { value: true });
  39610. var root_1 = __importDefault(/*@__PURE__*/ requireRoot());
  39611. var selector_1 = __importDefault(/*@__PURE__*/ requireSelector());
  39612. var className_1 = __importDefault(/*@__PURE__*/ requireClassName());
  39613. var comment_1 = __importDefault(/*@__PURE__*/ requireComment());
  39614. var id_1 = __importDefault(/*@__PURE__*/ requireId());
  39615. var tag_1 = __importDefault(/*@__PURE__*/ requireTag());
  39616. var string_1 = __importDefault(/*@__PURE__*/ requireString());
  39617. var pseudo_1 = __importDefault(/*@__PURE__*/ requirePseudo());
  39618. var attribute_1 = __importStar(/*@__PURE__*/ requireAttribute());
  39619. var universal_1 = __importDefault(/*@__PURE__*/ requireUniversal());
  39620. var combinator_1 = __importDefault(/*@__PURE__*/ requireCombinator());
  39621. var nesting_1 = __importDefault(/*@__PURE__*/ requireNesting());
  39622. var sortAscending_1 = __importDefault(/*@__PURE__*/ requireSortAscending());
  39623. var tokenize_1 = __importStar(/*@__PURE__*/ requireTokenize());
  39624. var tokens = __importStar(/*@__PURE__*/ requireTokenTypes());
  39625. var types = __importStar(/*@__PURE__*/ requireTypes());
  39626. var util_1 = /*@__PURE__*/ requireUtil$1();
  39627. var WHITESPACE_TOKENS = (_a = {},
  39628. _a[tokens.space] = true,
  39629. _a[tokens.cr] = true,
  39630. _a[tokens.feed] = true,
  39631. _a[tokens.newline] = true,
  39632. _a[tokens.tab] = true,
  39633. _a);
  39634. var WHITESPACE_EQUIV_TOKENS = __assign(__assign({}, WHITESPACE_TOKENS), (_b = {}, _b[tokens.comment] = true, _b));
  39635. function tokenStart(token) {
  39636. return {
  39637. line: token[tokenize_1.FIELDS.START_LINE],
  39638. column: token[tokenize_1.FIELDS.START_COL],
  39639. };
  39640. }
  39641. function tokenEnd(token) {
  39642. return {
  39643. line: token[tokenize_1.FIELDS.END_LINE],
  39644. column: token[tokenize_1.FIELDS.END_COL],
  39645. };
  39646. }
  39647. function getSource(startLine, startColumn, endLine, endColumn) {
  39648. return {
  39649. start: {
  39650. line: startLine,
  39651. column: startColumn,
  39652. },
  39653. end: {
  39654. line: endLine,
  39655. column: endColumn,
  39656. },
  39657. };
  39658. }
  39659. function getTokenSource(token) {
  39660. return getSource(token[tokenize_1.FIELDS.START_LINE], token[tokenize_1.FIELDS.START_COL], token[tokenize_1.FIELDS.END_LINE], token[tokenize_1.FIELDS.END_COL]);
  39661. }
  39662. function getTokenSourceSpan(startToken, endToken) {
  39663. if (!startToken) {
  39664. return undefined;
  39665. }
  39666. return getSource(startToken[tokenize_1.FIELDS.START_LINE], startToken[tokenize_1.FIELDS.START_COL], endToken[tokenize_1.FIELDS.END_LINE], endToken[tokenize_1.FIELDS.END_COL]);
  39667. }
  39668. function unescapeProp(node, prop) {
  39669. var value = node[prop];
  39670. if (typeof value !== "string") {
  39671. return;
  39672. }
  39673. if (value.indexOf("\\") !== -1) {
  39674. (0, util_1.ensureObject)(node, "raws");
  39675. node[prop] = (0, util_1.unesc)(value);
  39676. if (node.raws[prop] === undefined) {
  39677. node.raws[prop] = value;
  39678. }
  39679. }
  39680. return node;
  39681. }
  39682. function indexesOf(array, item) {
  39683. var i = -1;
  39684. var indexes = [];
  39685. while ((i = array.indexOf(item, i + 1)) !== -1) {
  39686. indexes.push(i);
  39687. }
  39688. return indexes;
  39689. }
  39690. function uniqs() {
  39691. var list = Array.prototype.concat.apply([], arguments);
  39692. return list.filter(function (item, i) { return i === list.indexOf(item); });
  39693. }
  39694. var Parser = /** @class */ (function () {
  39695. function Parser(rule, options) {
  39696. if (options === void 0) { options = {}; }
  39697. this.rule = rule;
  39698. this.options = Object.assign({ lossy: false, safe: false }, options);
  39699. this.position = 0;
  39700. this.nestingDepth = 0;
  39701. this.maxNestingDepth = (0, util_1.resolveMaxNestingDepth)(this.options.maxNestingDepth);
  39702. this.css = typeof this.rule === "string" ? this.rule : this.rule.selector;
  39703. this.tokens = (0, tokenize_1.default)({
  39704. css: this.css,
  39705. error: this._errorGenerator(),
  39706. safe: this.options.safe,
  39707. });
  39708. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  39709. this.root = new root_1.default({ source: rootSource });
  39710. this.root.errorGenerator = this._errorGenerator();
  39711. var selector = new selector_1.default({
  39712. source: { start: { line: 1, column: 1 } },
  39713. sourceIndex: 0,
  39714. });
  39715. this.root.append(selector);
  39716. this.current = selector;
  39717. this.loop();
  39718. }
  39719. Parser.prototype._errorGenerator = function () {
  39720. var _this = this;
  39721. return function (message, errorOptions) {
  39722. if (typeof _this.rule === "string") {
  39723. return new Error(message);
  39724. }
  39725. return _this.rule.error(message, errorOptions);
  39726. };
  39727. };
  39728. Parser.prototype.attribute = function () {
  39729. var attr = [];
  39730. var startingToken = this.currToken;
  39731. this.position++;
  39732. while (this.position < this.tokens.length &&
  39733. this.currToken[tokenize_1.FIELDS.TYPE] !== tokens.closeSquare) {
  39734. attr.push(this.currToken);
  39735. this.position++;
  39736. }
  39737. if (this.currToken[tokenize_1.FIELDS.TYPE] !== tokens.closeSquare) {
  39738. return this.expected("closing square bracket", this.currToken[tokenize_1.FIELDS.START_POS]);
  39739. }
  39740. var len = attr.length;
  39741. var node = {
  39742. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  39743. sourceIndex: startingToken[tokenize_1.FIELDS.START_POS],
  39744. };
  39745. if (len === 1 && !~[tokens.word].indexOf(attr[0][tokenize_1.FIELDS.TYPE])) {
  39746. return this.expected("attribute", attr[0][tokenize_1.FIELDS.START_POS]);
  39747. }
  39748. var pos = 0;
  39749. var spaceBefore = "";
  39750. var commentBefore = "";
  39751. var lastAdded = null;
  39752. var spaceAfterMeaningfulToken = false;
  39753. while (pos < len) {
  39754. var token = attr[pos];
  39755. var content = this.content(token);
  39756. var next = attr[pos + 1];
  39757. switch (token[tokenize_1.FIELDS.TYPE]) {
  39758. case tokens.space:
  39759. // if (
  39760. // len === 1 ||
  39761. // pos === 0 && this.content(next) === '|'
  39762. // ) {
  39763. // return this.expected('attribute', token[TOKEN.START_POS], content);
  39764. // }
  39765. spaceAfterMeaningfulToken = true;
  39766. if (this.options.lossy) {
  39767. break;
  39768. }
  39769. if (lastAdded) {
  39770. (0, util_1.ensureObject)(node, "spaces", lastAdded);
  39771. var prevContent = node.spaces[lastAdded].after || "";
  39772. node.spaces[lastAdded].after = prevContent + content;
  39773. var existingComment = (0, util_1.getProp)(node, "raws", "spaces", lastAdded, "after") || null;
  39774. if (existingComment) {
  39775. node.raws.spaces[lastAdded].after = existingComment + content;
  39776. }
  39777. }
  39778. else {
  39779. spaceBefore = spaceBefore + content;
  39780. commentBefore = commentBefore + content;
  39781. }
  39782. break;
  39783. case tokens.asterisk:
  39784. if (next[tokenize_1.FIELDS.TYPE] === tokens.equals) {
  39785. node.operator = content;
  39786. lastAdded = "operator";
  39787. }
  39788. else if ((!node.namespace || (lastAdded === "namespace" && !spaceAfterMeaningfulToken)) &&
  39789. next) {
  39790. if (spaceBefore) {
  39791. (0, util_1.ensureObject)(node, "spaces", "attribute");
  39792. node.spaces.attribute.before = spaceBefore;
  39793. spaceBefore = "";
  39794. }
  39795. if (commentBefore) {
  39796. (0, util_1.ensureObject)(node, "raws", "spaces", "attribute");
  39797. node.raws.spaces.attribute.before = spaceBefore;
  39798. commentBefore = "";
  39799. }
  39800. node.namespace = (node.namespace || "") + content;
  39801. var rawValue = (0, util_1.getProp)(node, "raws", "namespace") || null;
  39802. if (rawValue) {
  39803. node.raws.namespace += content;
  39804. }
  39805. lastAdded = "namespace";
  39806. }
  39807. spaceAfterMeaningfulToken = false;
  39808. break;
  39809. case tokens.dollar:
  39810. if (lastAdded === "value") {
  39811. var oldRawValue = (0, util_1.getProp)(node, "raws", "value");
  39812. node.value += "$";
  39813. if (oldRawValue) {
  39814. node.raws.value = oldRawValue + "$";
  39815. }
  39816. break;
  39817. }
  39818. // Falls through
  39819. case tokens.caret:
  39820. if (next[tokenize_1.FIELDS.TYPE] === tokens.equals) {
  39821. node.operator = content;
  39822. lastAdded = "operator";
  39823. }
  39824. spaceAfterMeaningfulToken = false;
  39825. break;
  39826. case tokens.combinator:
  39827. if (content === "~" && next[tokenize_1.FIELDS.TYPE] === tokens.equals) {
  39828. node.operator = content;
  39829. lastAdded = "operator";
  39830. }
  39831. if (content !== "|") {
  39832. spaceAfterMeaningfulToken = false;
  39833. break;
  39834. }
  39835. if (next[tokenize_1.FIELDS.TYPE] === tokens.equals) {
  39836. node.operator = content;
  39837. lastAdded = "operator";
  39838. }
  39839. else if (!node.namespace && !node.attribute) {
  39840. node.namespace = true;
  39841. }
  39842. spaceAfterMeaningfulToken = false;
  39843. break;
  39844. case tokens.word:
  39845. if (next &&
  39846. this.content(next) === "|" &&
  39847. attr[pos + 2] &&
  39848. attr[pos + 2][tokenize_1.FIELDS.TYPE] !== tokens.equals && // this look-ahead probably fails with comment nodes involved.
  39849. !node.operator &&
  39850. !node.namespace) {
  39851. node.namespace = content;
  39852. lastAdded = "namespace";
  39853. }
  39854. else if (!node.attribute || (lastAdded === "attribute" && !spaceAfterMeaningfulToken)) {
  39855. if (spaceBefore) {
  39856. (0, util_1.ensureObject)(node, "spaces", "attribute");
  39857. node.spaces.attribute.before = spaceBefore;
  39858. spaceBefore = "";
  39859. }
  39860. if (commentBefore) {
  39861. (0, util_1.ensureObject)(node, "raws", "spaces", "attribute");
  39862. node.raws.spaces.attribute.before = commentBefore;
  39863. commentBefore = "";
  39864. }
  39865. node.attribute = (node.attribute || "") + content;
  39866. var rawValue = (0, util_1.getProp)(node, "raws", "attribute") || null;
  39867. if (rawValue) {
  39868. node.raws.attribute += content;
  39869. }
  39870. lastAdded = "attribute";
  39871. }
  39872. else if ((!node.value && node.value !== "") ||
  39873. (lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark))) {
  39874. var unescaped_1 = (0, util_1.unesc)(content);
  39875. var oldRawValue = (0, util_1.getProp)(node, "raws", "value") || "";
  39876. var oldValue = node.value || "";
  39877. node.value = oldValue + unescaped_1;
  39878. node.quoteMark = null;
  39879. if (unescaped_1 !== content || oldRawValue) {
  39880. (0, util_1.ensureObject)(node, "raws");
  39881. node.raws.value = (oldRawValue || oldValue) + content;
  39882. }
  39883. lastAdded = "value";
  39884. }
  39885. else {
  39886. var insensitive = content === "i" || content === "I";
  39887. if ((node.value || node.value === "") &&
  39888. (node.quoteMark || spaceAfterMeaningfulToken)) {
  39889. node.insensitive = insensitive;
  39890. if (!insensitive || content === "I") {
  39891. (0, util_1.ensureObject)(node, "raws");
  39892. node.raws.insensitiveFlag = content;
  39893. }
  39894. lastAdded = "insensitive";
  39895. if (spaceBefore) {
  39896. (0, util_1.ensureObject)(node, "spaces", "insensitive");
  39897. node.spaces.insensitive.before = spaceBefore;
  39898. spaceBefore = "";
  39899. }
  39900. if (commentBefore) {
  39901. (0, util_1.ensureObject)(node, "raws", "spaces", "insensitive");
  39902. node.raws.spaces.insensitive.before = commentBefore;
  39903. commentBefore = "";
  39904. }
  39905. }
  39906. else if (node.value || node.value === "") {
  39907. lastAdded = "value";
  39908. node.value += content;
  39909. if (node.raws.value) {
  39910. node.raws.value += content;
  39911. }
  39912. }
  39913. }
  39914. spaceAfterMeaningfulToken = false;
  39915. break;
  39916. case tokens.str:
  39917. if (!node.attribute || !node.operator) {
  39918. return this.error("Expected an attribute followed by an operator preceding the string.", {
  39919. index: token[tokenize_1.FIELDS.START_POS],
  39920. });
  39921. }
  39922. var _a = (0, attribute_1.unescapeValue)(content), unescaped = _a.unescaped, quoteMark = _a.quoteMark;
  39923. node.value = unescaped;
  39924. node.quoteMark = quoteMark;
  39925. lastAdded = "value";
  39926. (0, util_1.ensureObject)(node, "raws");
  39927. node.raws.value = content;
  39928. spaceAfterMeaningfulToken = false;
  39929. break;
  39930. case tokens.equals:
  39931. if (!node.attribute) {
  39932. return this.expected("attribute", token[tokenize_1.FIELDS.START_POS], content);
  39933. }
  39934. if (node.value) {
  39935. return this.error('Unexpected "=" found; an operator was already defined.', {
  39936. index: token[tokenize_1.FIELDS.START_POS],
  39937. });
  39938. }
  39939. node.operator = node.operator ? node.operator + content : content;
  39940. lastAdded = "operator";
  39941. spaceAfterMeaningfulToken = false;
  39942. break;
  39943. case tokens.comment:
  39944. if (lastAdded) {
  39945. if (spaceAfterMeaningfulToken ||
  39946. (next && next[tokenize_1.FIELDS.TYPE] === tokens.space) ||
  39947. lastAdded === "insensitive") {
  39948. var lastComment = (0, util_1.getProp)(node, "spaces", lastAdded, "after") || "";
  39949. var rawLastComment = (0, util_1.getProp)(node, "raws", "spaces", lastAdded, "after") || lastComment;
  39950. (0, util_1.ensureObject)(node, "raws", "spaces", lastAdded);
  39951. node.raws.spaces[lastAdded].after = rawLastComment + content;
  39952. }
  39953. else {
  39954. var lastValue = node[lastAdded] || "";
  39955. var rawLastValue = (0, util_1.getProp)(node, "raws", lastAdded) || lastValue;
  39956. (0, util_1.ensureObject)(node, "raws");
  39957. node.raws[lastAdded] = rawLastValue + content;
  39958. }
  39959. }
  39960. else {
  39961. commentBefore = commentBefore + content;
  39962. }
  39963. break;
  39964. default:
  39965. return this.error("Unexpected \"".concat(content, "\" found."), { index: token[tokenize_1.FIELDS.START_POS] });
  39966. }
  39967. pos++;
  39968. }
  39969. unescapeProp(node, "attribute");
  39970. unescapeProp(node, "namespace");
  39971. this.newNode(new attribute_1.default(node));
  39972. this.position++;
  39973. };
  39974. /**
  39975. * return a node containing meaningless garbage up to (but not including) the specified token position.
  39976. * if the token position is negative, all remaining tokens are consumed.
  39977. *
  39978. * This returns an array containing a single string node if all whitespace,
  39979. * otherwise an array of comment nodes with space before and after.
  39980. *
  39981. * These tokens are not added to the current selector, the caller can add them or use them to amend
  39982. * a previous node's space metadata.
  39983. *
  39984. * In lossy mode, this returns only comments.
  39985. */
  39986. Parser.prototype.parseWhitespaceEquivalentTokens = function (stopPosition) {
  39987. if (stopPosition < 0) {
  39988. stopPosition = this.tokens.length;
  39989. }
  39990. var startPosition = this.position;
  39991. var nodes = [];
  39992. var space = "";
  39993. var lastComment = undefined;
  39994. do {
  39995. if (WHITESPACE_TOKENS[this.currToken[tokenize_1.FIELDS.TYPE]]) {
  39996. if (!this.options.lossy) {
  39997. space += this.content();
  39998. }
  39999. }
  40000. else if (this.currToken[tokenize_1.FIELDS.TYPE] === tokens.comment) {
  40001. var spaces = {};
  40002. if (space) {
  40003. spaces.before = space;
  40004. space = "";
  40005. }
  40006. lastComment = new comment_1.default({
  40007. value: this.content(),
  40008. source: getTokenSource(this.currToken),
  40009. sourceIndex: this.currToken[tokenize_1.FIELDS.START_POS],
  40010. spaces: spaces,
  40011. });
  40012. nodes.push(lastComment);
  40013. }
  40014. } while (++this.position < stopPosition);
  40015. if (space) {
  40016. if (lastComment) {
  40017. lastComment.spaces.after = space;
  40018. }
  40019. else if (!this.options.lossy) {
  40020. var firstToken = this.tokens[startPosition];
  40021. var lastToken = this.tokens[this.position - 1];
  40022. nodes.push(new string_1.default({
  40023. value: "",
  40024. source: getSource(firstToken[tokenize_1.FIELDS.START_LINE], firstToken[tokenize_1.FIELDS.START_COL], lastToken[tokenize_1.FIELDS.END_LINE], lastToken[tokenize_1.FIELDS.END_COL]),
  40025. sourceIndex: firstToken[tokenize_1.FIELDS.START_POS],
  40026. spaces: { before: space, after: "" },
  40027. }));
  40028. }
  40029. }
  40030. return nodes;
  40031. };
  40032. /**
  40033. *
  40034. * @param {*} nodes
  40035. */
  40036. Parser.prototype.convertWhitespaceNodesToSpace = function (nodes, requiredSpace) {
  40037. var _this = this;
  40038. if (requiredSpace === void 0) { requiredSpace = false; }
  40039. var space = "";
  40040. var rawSpace = "";
  40041. nodes.forEach(function (n) {
  40042. var spaceBefore = _this.lossySpace(n.spaces.before, requiredSpace);
  40043. var rawSpaceBefore = _this.lossySpace(n.rawSpaceBefore, requiredSpace);
  40044. space +=
  40045. spaceBefore + _this.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  40046. rawSpace +=
  40047. spaceBefore +
  40048. n.value +
  40049. _this.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  40050. });
  40051. if (rawSpace === space) {
  40052. rawSpace = undefined;
  40053. }
  40054. var result = { space: space, rawSpace: rawSpace };
  40055. return result;
  40056. };
  40057. Parser.prototype.isNamedCombinator = function (position) {
  40058. if (position === void 0) { position = this.position; }
  40059. return (this.tokens[position + 0] &&
  40060. this.tokens[position + 0][tokenize_1.FIELDS.TYPE] === tokens.slash &&
  40061. this.tokens[position + 1] &&
  40062. this.tokens[position + 1][tokenize_1.FIELDS.TYPE] === tokens.word &&
  40063. this.tokens[position + 2] &&
  40064. this.tokens[position + 2][tokenize_1.FIELDS.TYPE] === tokens.slash);
  40065. };
  40066. Parser.prototype.namedCombinator = function () {
  40067. if (this.isNamedCombinator()) {
  40068. var nameRaw = this.content(this.tokens[this.position + 1]);
  40069. var name = (0, util_1.unesc)(nameRaw).toLowerCase();
  40070. var raws = {};
  40071. if (name !== nameRaw) {
  40072. raws.value = "/".concat(nameRaw, "/");
  40073. }
  40074. var node = new combinator_1.default({
  40075. value: "/".concat(name, "/"),
  40076. source: getSource(this.currToken[tokenize_1.FIELDS.START_LINE], this.currToken[tokenize_1.FIELDS.START_COL], this.tokens[this.position + 2][tokenize_1.FIELDS.END_LINE], this.tokens[this.position + 2][tokenize_1.FIELDS.END_COL]),
  40077. sourceIndex: this.currToken[tokenize_1.FIELDS.START_POS],
  40078. raws: raws,
  40079. });
  40080. this.position = this.position + 3;
  40081. return node;
  40082. }
  40083. else {
  40084. this.unexpected();
  40085. }
  40086. };
  40087. Parser.prototype.combinator = function () {
  40088. var _this = this;
  40089. if (this.content() === "|") {
  40090. return this.namespace();
  40091. }
  40092. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  40093. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  40094. if (nextSigTokenPos < 0 ||
  40095. this.tokens[nextSigTokenPos][tokenize_1.FIELDS.TYPE] === tokens.comma ||
  40096. this.tokens[nextSigTokenPos][tokenize_1.FIELDS.TYPE] === tokens.closeParenthesis) {
  40097. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  40098. if (nodes.length > 0) {
  40099. var last = this.current.last;
  40100. if (last) {
  40101. var _a = this.convertWhitespaceNodesToSpace(nodes), space = _a.space, rawSpace = _a.rawSpace;
  40102. if (rawSpace !== undefined) {
  40103. last.rawSpaceAfter += rawSpace;
  40104. }
  40105. last.spaces.after += space;
  40106. }
  40107. else {
  40108. nodes.forEach(function (n) { return _this.newNode(n); });
  40109. }
  40110. }
  40111. return;
  40112. }
  40113. var firstToken = this.currToken;
  40114. var spaceOrDescendantSelectorNodes = undefined;
  40115. if (nextSigTokenPos > this.position) {
  40116. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  40117. }
  40118. var node;
  40119. if (this.isNamedCombinator()) {
  40120. node = this.namedCombinator();
  40121. }
  40122. else if (this.currToken[tokenize_1.FIELDS.TYPE] === tokens.combinator) {
  40123. node = new combinator_1.default({
  40124. value: this.content(),
  40125. source: getTokenSource(this.currToken),
  40126. sourceIndex: this.currToken[tokenize_1.FIELDS.START_POS],
  40127. });
  40128. this.position++;
  40129. }
  40130. else if (WHITESPACE_TOKENS[this.currToken[tokenize_1.FIELDS.TYPE]]) ;
  40131. else if (!spaceOrDescendantSelectorNodes) {
  40132. this.unexpected();
  40133. }
  40134. if (node) {
  40135. if (spaceOrDescendantSelectorNodes) {
  40136. var _b = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes), space = _b.space, rawSpace = _b.rawSpace;
  40137. node.spaces.before = space;
  40138. node.rawSpaceBefore = rawSpace;
  40139. }
  40140. }
  40141. else {
  40142. // descendant combinator
  40143. var _c = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true), space = _c.space, rawSpace = _c.rawSpace;
  40144. if (!rawSpace) {
  40145. rawSpace = space;
  40146. }
  40147. var spaces = {};
  40148. var raws = { spaces: {} };
  40149. if (space.endsWith(" ") && rawSpace.endsWith(" ")) {
  40150. spaces.before = space.slice(0, space.length - 1);
  40151. raws.spaces.before = rawSpace.slice(0, rawSpace.length - 1);
  40152. }
  40153. else if (space[0] === " " && rawSpace[0] === " ") {
  40154. spaces.after = space.slice(1);
  40155. raws.spaces.after = rawSpace.slice(1);
  40156. }
  40157. else {
  40158. raws.value = rawSpace;
  40159. }
  40160. node = new combinator_1.default({
  40161. value: " ",
  40162. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  40163. sourceIndex: firstToken[tokenize_1.FIELDS.START_POS],
  40164. spaces: spaces,
  40165. raws: raws,
  40166. });
  40167. }
  40168. if (this.currToken && this.currToken[tokenize_1.FIELDS.TYPE] === tokens.space) {
  40169. node.spaces.after = this.optionalSpace(this.content());
  40170. this.position++;
  40171. }
  40172. return this.newNode(node);
  40173. };
  40174. Parser.prototype.comma = function () {
  40175. if (this.position === this.tokens.length - 1) {
  40176. this.root.trailingComma = true;
  40177. this.position++;
  40178. return;
  40179. }
  40180. this.current._inferEndPosition();
  40181. var selector = new selector_1.default({
  40182. source: {
  40183. start: tokenStart(this.tokens[this.position + 1]),
  40184. },
  40185. sourceIndex: this.tokens[this.position + 1][tokenize_1.FIELDS.START_POS],
  40186. });
  40187. this.current.parent.append(selector);
  40188. this.current = selector;
  40189. this.position++;
  40190. };
  40191. Parser.prototype.comment = function () {
  40192. var current = this.currToken;
  40193. this.newNode(new comment_1.default({
  40194. value: this.content(),
  40195. source: getTokenSource(current),
  40196. sourceIndex: current[tokenize_1.FIELDS.START_POS],
  40197. }));
  40198. this.position++;
  40199. };
  40200. Parser.prototype.error = function (message, opts) {
  40201. throw this.root.error(message, opts);
  40202. };
  40203. Parser.prototype.missingBackslash = function () {
  40204. return this.error("Expected a backslash preceding the semicolon.", {
  40205. index: this.currToken[tokenize_1.FIELDS.START_POS],
  40206. });
  40207. };
  40208. Parser.prototype.missingParenthesis = function () {
  40209. return this.expected("opening parenthesis", this.currToken[tokenize_1.FIELDS.START_POS]);
  40210. };
  40211. Parser.prototype.missingSquareBracket = function () {
  40212. return this.expected("opening square bracket", this.currToken[tokenize_1.FIELDS.START_POS]);
  40213. };
  40214. Parser.prototype.unexpected = function () {
  40215. return this.error("Unexpected '".concat(this.content(), "'. Escaping special characters with \\ may help."), this.currToken[tokenize_1.FIELDS.START_POS]);
  40216. };
  40217. Parser.prototype.unexpectedPipe = function () {
  40218. return this.error("Unexpected '|'.", this.currToken[tokenize_1.FIELDS.START_POS]);
  40219. };
  40220. Parser.prototype.namespace = function () {
  40221. var before = (this.prevToken && this.content(this.prevToken)) || true;
  40222. if (this.nextToken[tokenize_1.FIELDS.TYPE] === tokens.word) {
  40223. this.position++;
  40224. return this.word(before);
  40225. }
  40226. else if (this.nextToken[tokenize_1.FIELDS.TYPE] === tokens.asterisk) {
  40227. this.position++;
  40228. return this.universal(before);
  40229. }
  40230. this.unexpectedPipe();
  40231. };
  40232. Parser.prototype.nesting = function () {
  40233. if (this.nextToken) {
  40234. var nextContent = this.content(this.nextToken);
  40235. if (nextContent === "|") {
  40236. this.position++;
  40237. return;
  40238. }
  40239. }
  40240. var current = this.currToken;
  40241. this.newNode(new nesting_1.default({
  40242. value: this.content(),
  40243. source: getTokenSource(current),
  40244. sourceIndex: current[tokenize_1.FIELDS.START_POS],
  40245. }));
  40246. this.position++;
  40247. };
  40248. Parser.prototype.parentheses = function () {
  40249. var last = this.current.last;
  40250. var unbalanced = 1;
  40251. this.position++;
  40252. if (last && last.type === types.PSEUDO) {
  40253. var selector = new selector_1.default({
  40254. source: { start: tokenStart(this.tokens[this.position]) },
  40255. sourceIndex: this.tokens[this.position][tokenize_1.FIELDS.START_POS],
  40256. });
  40257. var cache = this.current;
  40258. last.append(selector);
  40259. this.current = selector;
  40260. // Track nesting depth so deeply nested pseudo selectors raise a
  40261. // catchable error instead of overflowing the call stack. The
  40262. // counter is restored in `finally` so the parser is never left in
  40263. // an inconsistent state, even on the error path.
  40264. this.nestingDepth++;
  40265. try {
  40266. if (this.nestingDepth > this.maxNestingDepth) {
  40267. this.error("Cannot parse selector: nesting depth exceeds the maximum of ".concat(this.maxNestingDepth, "."), { index: this.currToken[tokenize_1.FIELDS.START_POS] });
  40268. }
  40269. while (this.position < this.tokens.length && unbalanced) {
  40270. if (this.currToken[tokenize_1.FIELDS.TYPE] === tokens.openParenthesis) {
  40271. unbalanced++;
  40272. }
  40273. if (this.currToken[tokenize_1.FIELDS.TYPE] === tokens.closeParenthesis) {
  40274. unbalanced--;
  40275. }
  40276. if (unbalanced) {
  40277. this.parse();
  40278. }
  40279. else {
  40280. this.current.source.end = tokenEnd(this.currToken);
  40281. this.current.parent.source.end = tokenEnd(this.currToken);
  40282. this.position++;
  40283. }
  40284. }
  40285. }
  40286. finally {
  40287. this.nestingDepth--;
  40288. }
  40289. this.current = cache;
  40290. }
  40291. else {
  40292. // I think this case should be an error. It's used to implement a basic parse of media queries
  40293. // but I don't think it's a good idea.
  40294. var parenStart = this.currToken;
  40295. var parenValue = "(";
  40296. var parenEnd = void 0;
  40297. while (this.position < this.tokens.length && unbalanced) {
  40298. if (this.currToken[tokenize_1.FIELDS.TYPE] === tokens.openParenthesis) {
  40299. unbalanced++;
  40300. }
  40301. if (this.currToken[tokenize_1.FIELDS.TYPE] === tokens.closeParenthesis) {
  40302. unbalanced--;
  40303. }
  40304. parenEnd = this.currToken;
  40305. parenValue += this.parseParenthesisToken(this.currToken);
  40306. this.position++;
  40307. }
  40308. if (last) {
  40309. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  40310. }
  40311. else {
  40312. this.newNode(new string_1.default({
  40313. value: parenValue,
  40314. source: getSource(parenStart[tokenize_1.FIELDS.START_LINE], parenStart[tokenize_1.FIELDS.START_COL], parenEnd[tokenize_1.FIELDS.END_LINE], parenEnd[tokenize_1.FIELDS.END_COL]),
  40315. sourceIndex: parenStart[tokenize_1.FIELDS.START_POS],
  40316. }));
  40317. }
  40318. }
  40319. if (unbalanced) {
  40320. return this.expected("closing parenthesis", this.currToken[tokenize_1.FIELDS.START_POS]);
  40321. }
  40322. };
  40323. Parser.prototype.pseudo = function () {
  40324. var _this = this;
  40325. var pseudoStr = "";
  40326. var startingToken = this.currToken;
  40327. while (this.currToken && this.currToken[tokenize_1.FIELDS.TYPE] === tokens.colon) {
  40328. pseudoStr += this.content();
  40329. this.position++;
  40330. }
  40331. if (!this.currToken) {
  40332. return this.expected(["pseudo-class", "pseudo-element"], this.position - 1);
  40333. }
  40334. if (this.currToken[tokenize_1.FIELDS.TYPE] === tokens.word) {
  40335. this.splitWord(false, function (first, length) {
  40336. pseudoStr += first;
  40337. _this.newNode(new pseudo_1.default({
  40338. value: pseudoStr,
  40339. source: getTokenSourceSpan(startingToken, _this.currToken),
  40340. sourceIndex: startingToken[tokenize_1.FIELDS.START_POS],
  40341. }));
  40342. if (length > 1 && _this.nextToken && _this.nextToken[tokenize_1.FIELDS.TYPE] === tokens.openParenthesis) {
  40343. _this.error("Misplaced parenthesis.", {
  40344. index: _this.nextToken[tokenize_1.FIELDS.START_POS],
  40345. });
  40346. }
  40347. });
  40348. }
  40349. else {
  40350. return this.expected(["pseudo-class", "pseudo-element"], this.currToken[tokenize_1.FIELDS.START_POS]);
  40351. }
  40352. };
  40353. Parser.prototype.space = function () {
  40354. var content = this.content();
  40355. // Handle space before and after the selector
  40356. if (this.position === 0 ||
  40357. this.prevToken[tokenize_1.FIELDS.TYPE] === tokens.comma ||
  40358. this.prevToken[tokenize_1.FIELDS.TYPE] === tokens.openParenthesis ||
  40359. this.current.nodes.every(function (node) { return node.type === "comment"; })) {
  40360. this.spaces = this.optionalSpace(content);
  40361. this.position++;
  40362. }
  40363. else if (this.position === this.tokens.length - 1 ||
  40364. this.nextToken[tokenize_1.FIELDS.TYPE] === tokens.comma ||
  40365. this.nextToken[tokenize_1.FIELDS.TYPE] === tokens.closeParenthesis) {
  40366. this.current.last.spaces.after = this.optionalSpace(content);
  40367. this.position++;
  40368. }
  40369. else {
  40370. this.combinator();
  40371. }
  40372. };
  40373. Parser.prototype.string = function () {
  40374. var current = this.currToken;
  40375. this.newNode(new string_1.default({
  40376. value: this.content(),
  40377. source: getTokenSource(current),
  40378. sourceIndex: current[tokenize_1.FIELDS.START_POS],
  40379. }));
  40380. this.position++;
  40381. };
  40382. Parser.prototype.universal = function (namespace) {
  40383. var nextToken = this.nextToken;
  40384. if (nextToken && this.content(nextToken) === "|") {
  40385. this.position++;
  40386. return this.namespace();
  40387. }
  40388. var current = this.currToken;
  40389. this.newNode(new universal_1.default({
  40390. value: this.content(),
  40391. source: getTokenSource(current),
  40392. sourceIndex: current[tokenize_1.FIELDS.START_POS],
  40393. }), namespace);
  40394. this.position++;
  40395. };
  40396. Parser.prototype.splitWord = function (namespace, firstCallback) {
  40397. var _this = this;
  40398. var nextToken = this.nextToken;
  40399. var word = this.content();
  40400. while (nextToken &&
  40401. ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[tokenize_1.FIELDS.TYPE])) {
  40402. this.position++;
  40403. var current = this.content();
  40404. word += current;
  40405. if (current.lastIndexOf("\\") === current.length - 1) {
  40406. var next = this.nextToken;
  40407. if (next && next[tokenize_1.FIELDS.TYPE] === tokens.space) {
  40408. word += this.requiredSpace(this.content(next));
  40409. this.position++;
  40410. }
  40411. }
  40412. nextToken = this.nextToken;
  40413. }
  40414. var hasClass = indexesOf(word, ".").filter(function (i) {
  40415. // Allow escaped dot within class name
  40416. var escapedDot = word[i - 1] === "\\";
  40417. // Allow decimal numbers percent in @keyframes
  40418. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  40419. return !escapedDot && !isKeyframesPercent;
  40420. });
  40421. var hasId = indexesOf(word, "#").filter(function (i) { return word[i - 1] !== "\\"; });
  40422. // Eliminate Sass interpolations from the list of id indexes
  40423. var interpolations = indexesOf(word, "#{");
  40424. if (interpolations.length) {
  40425. hasId = hasId.filter(function (hashIndex) { return !~interpolations.indexOf(hashIndex); });
  40426. }
  40427. var indices = (0, sortAscending_1.default)(uniqs(__spreadArray(__spreadArray([0], __read(hasClass), false), __read(hasId), false)));
  40428. indices.forEach(function (ind, i) {
  40429. var index = indices[i + 1] || word.length;
  40430. var value = word.slice(ind, index);
  40431. if (i === 0 && firstCallback) {
  40432. return firstCallback.call(_this, value, indices.length);
  40433. }
  40434. var node;
  40435. var current = _this.currToken;
  40436. var sourceIndex = current[tokenize_1.FIELDS.START_POS] + indices[i];
  40437. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  40438. if (~hasClass.indexOf(ind)) {
  40439. var classNameOpts = {
  40440. value: value.slice(1),
  40441. source: source,
  40442. sourceIndex: sourceIndex,
  40443. };
  40444. node = new className_1.default(unescapeProp(classNameOpts, "value"));
  40445. }
  40446. else if (~hasId.indexOf(ind)) {
  40447. var idOpts = {
  40448. value: value.slice(1),
  40449. source: source,
  40450. sourceIndex: sourceIndex,
  40451. };
  40452. node = new id_1.default(unescapeProp(idOpts, "value"));
  40453. }
  40454. else {
  40455. var tagOpts = {
  40456. value: value,
  40457. source: source,
  40458. sourceIndex: sourceIndex,
  40459. };
  40460. unescapeProp(tagOpts, "value");
  40461. node = new tag_1.default(tagOpts);
  40462. }
  40463. _this.newNode(node, namespace);
  40464. // Ensure that the namespace is used only once
  40465. namespace = null;
  40466. });
  40467. this.position++;
  40468. };
  40469. Parser.prototype.word = function (namespace) {
  40470. var nextToken = this.nextToken;
  40471. if (nextToken && this.content(nextToken) === "|") {
  40472. this.position++;
  40473. return this.namespace();
  40474. }
  40475. return this.splitWord(namespace);
  40476. };
  40477. Parser.prototype.loop = function () {
  40478. while (this.position < this.tokens.length) {
  40479. this.parse(true);
  40480. }
  40481. this.current._inferEndPosition();
  40482. return this.root;
  40483. };
  40484. Parser.prototype.parse = function (throwOnParenthesis) {
  40485. switch (this.currToken[tokenize_1.FIELDS.TYPE]) {
  40486. case tokens.space:
  40487. this.space();
  40488. break;
  40489. case tokens.comment:
  40490. this.comment();
  40491. break;
  40492. case tokens.openParenthesis:
  40493. this.parentheses();
  40494. break;
  40495. case tokens.closeParenthesis:
  40496. if (throwOnParenthesis) {
  40497. this.missingParenthesis();
  40498. }
  40499. break;
  40500. case tokens.openSquare:
  40501. this.attribute();
  40502. break;
  40503. case tokens.dollar:
  40504. case tokens.caret:
  40505. case tokens.equals:
  40506. case tokens.word:
  40507. this.word();
  40508. break;
  40509. case tokens.colon:
  40510. this.pseudo();
  40511. break;
  40512. case tokens.comma:
  40513. this.comma();
  40514. break;
  40515. case tokens.asterisk:
  40516. this.universal();
  40517. break;
  40518. case tokens.ampersand:
  40519. this.nesting();
  40520. break;
  40521. case tokens.slash:
  40522. case tokens.combinator:
  40523. this.combinator();
  40524. break;
  40525. case tokens.str:
  40526. this.string();
  40527. break;
  40528. // These cases throw; no break needed.
  40529. case tokens.closeSquare:
  40530. this.missingSquareBracket();
  40531. case tokens.semicolon:
  40532. this.missingBackslash();
  40533. default:
  40534. this.unexpected();
  40535. }
  40536. };
  40537. /**
  40538. * Helpers
  40539. */
  40540. Parser.prototype.expected = function (description, index, found) {
  40541. if (Array.isArray(description)) {
  40542. var last = description.pop();
  40543. description = "".concat(description.join(", "), " or ").concat(last);
  40544. }
  40545. var an = /^[aeiou]/.test(description[0]) ? "an" : "a";
  40546. if (!found) {
  40547. return this.error("Expected ".concat(an, " ").concat(description, "."), { index: index });
  40548. }
  40549. return this.error("Expected ".concat(an, " ").concat(description, ", found \"").concat(found, "\" instead."), { index: index });
  40550. };
  40551. Parser.prototype.requiredSpace = function (space) {
  40552. return this.options.lossy ? " " : space;
  40553. };
  40554. Parser.prototype.optionalSpace = function (space) {
  40555. return this.options.lossy ? "" : space;
  40556. };
  40557. Parser.prototype.lossySpace = function (space, required) {
  40558. if (this.options.lossy) {
  40559. return required ? " " : "";
  40560. }
  40561. else {
  40562. return space;
  40563. }
  40564. };
  40565. Parser.prototype.parseParenthesisToken = function (token) {
  40566. var content = this.content(token);
  40567. if (token[tokenize_1.FIELDS.TYPE] === tokens.space) {
  40568. return this.requiredSpace(content);
  40569. }
  40570. else {
  40571. return content;
  40572. }
  40573. };
  40574. Parser.prototype.newNode = function (node, namespace) {
  40575. if (namespace) {
  40576. if (/^ +$/.test(namespace)) {
  40577. if (!this.options.lossy) {
  40578. this.spaces = (this.spaces || "") + namespace;
  40579. }
  40580. namespace = true;
  40581. }
  40582. node.namespace = namespace;
  40583. unescapeProp(node, "namespace");
  40584. }
  40585. if (this.spaces) {
  40586. node.spaces.before = this.spaces;
  40587. this.spaces = "";
  40588. }
  40589. return this.current.append(node);
  40590. };
  40591. Parser.prototype.content = function (token) {
  40592. if (token === void 0) { token = this.currToken; }
  40593. return this.css.slice(token[tokenize_1.FIELDS.START_POS], token[tokenize_1.FIELDS.END_POS]);
  40594. };
  40595. Object.defineProperty(Parser.prototype, "currToken", {
  40596. get: function () {
  40597. return this.tokens[this.position];
  40598. },
  40599. enumerable: false,
  40600. configurable: true
  40601. });
  40602. Object.defineProperty(Parser.prototype, "nextToken", {
  40603. get: function () {
  40604. return this.tokens[this.position + 1];
  40605. },
  40606. enumerable: false,
  40607. configurable: true
  40608. });
  40609. Object.defineProperty(Parser.prototype, "prevToken", {
  40610. get: function () {
  40611. return this.tokens[this.position - 1];
  40612. },
  40613. enumerable: false,
  40614. configurable: true
  40615. });
  40616. /**
  40617. * returns the index of the next non-whitespace, non-comment token.
  40618. * returns -1 if no meaningful token is found.
  40619. */
  40620. Parser.prototype.locateNextMeaningfulToken = function (startPosition) {
  40621. if (startPosition === void 0) { startPosition = this.position + 1; }
  40622. var searchPosition = startPosition;
  40623. while (searchPosition < this.tokens.length) {
  40624. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][tokenize_1.FIELDS.TYPE]]) {
  40625. searchPosition++;
  40626. continue;
  40627. }
  40628. else {
  40629. return searchPosition;
  40630. }
  40631. }
  40632. return -1;
  40633. };
  40634. return Parser;
  40635. }());
  40636. parser.default = Parser;
  40637. return parser;
  40638. }
  40639. var hasRequiredProcessor;
  40640. function requireProcessor () {
  40641. if (hasRequiredProcessor) return processor;
  40642. hasRequiredProcessor = 1;
  40643. var __importDefault = (processor && processor.__importDefault) || function (mod) {
  40644. return (mod && mod.__esModule) ? mod : { "default": mod };
  40645. };
  40646. Object.defineProperty(processor, "__esModule", { value: true });
  40647. var parser_1 = __importDefault(/*@__PURE__*/ requireParser());
  40648. var Processor = /** @class */ (function () {
  40649. function Processor(func, options) {
  40650. this.func = func || function noop() { };
  40651. this.funcRes = null;
  40652. this.options = options;
  40653. }
  40654. Processor.prototype._shouldUpdateSelector = function (rule, options) {
  40655. if (options === void 0) { options = {}; }
  40656. var merged = Object.assign({}, this.options, options);
  40657. if (merged.updateSelector === false) {
  40658. return false;
  40659. }
  40660. else {
  40661. return typeof rule !== "string";
  40662. }
  40663. };
  40664. Processor.prototype._isLossy = function (options) {
  40665. if (options === void 0) { options = {}; }
  40666. var merged = Object.assign({}, this.options, options);
  40667. if (merged.lossless === false) {
  40668. return true;
  40669. }
  40670. else {
  40671. return false;
  40672. }
  40673. };
  40674. Processor.prototype._root = function (rule, options) {
  40675. if (options === void 0) { options = {}; }
  40676. var parser = new parser_1.default(rule, this._parseOptions(options));
  40677. return parser.root;
  40678. };
  40679. Processor.prototype._parseOptions = function (options) {
  40680. var merged = Object.assign({}, this.options, options);
  40681. return {
  40682. lossy: this._isLossy(merged),
  40683. maxNestingDepth: merged.maxNestingDepth,
  40684. };
  40685. };
  40686. Processor.prototype._stringifyOptions = function (options) {
  40687. var merged = Object.assign({}, this.options, options);
  40688. return {
  40689. maxNestingDepth: merged.maxNestingDepth,
  40690. };
  40691. };
  40692. Processor.prototype._run = function (rule, options) {
  40693. var _this = this;
  40694. if (options === void 0) { options = {}; }
  40695. return new Promise(function (resolve, reject) {
  40696. try {
  40697. var root_1 = _this._root(rule, options);
  40698. Promise.resolve(_this.func(root_1))
  40699. .then(function (transform) {
  40700. var string = undefined;
  40701. if (_this._shouldUpdateSelector(rule, options)) {
  40702. string = root_1.toString(_this._stringifyOptions(options));
  40703. rule.selector = string;
  40704. }
  40705. return { transform: transform, root: root_1, string: string };
  40706. })
  40707. .then(resolve, reject);
  40708. }
  40709. catch (e) {
  40710. reject(e);
  40711. return;
  40712. }
  40713. });
  40714. };
  40715. Processor.prototype._runSync = function (rule, options) {
  40716. if (options === void 0) { options = {}; }
  40717. var root = this._root(rule, options);
  40718. var transform = this.func(root);
  40719. if (transform && typeof transform.then === "function") {
  40720. throw new Error("Selector processor returned a promise to a synchronous call.");
  40721. }
  40722. var string = undefined;
  40723. if (options.updateSelector && typeof rule !== "string") {
  40724. string = root.toString(this._stringifyOptions(options));
  40725. rule.selector = string;
  40726. }
  40727. return { transform: transform, root: root, string: string };
  40728. };
  40729. /**
  40730. * Process rule into a selector AST.
  40731. *
  40732. * @param rule {postcss.Rule | string} The css selector to be processed
  40733. * @param options The options for processing
  40734. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  40735. */
  40736. Processor.prototype.ast = function (rule, options) {
  40737. return this._run(rule, options).then(function (result) { return result.root; });
  40738. };
  40739. /**
  40740. * Process rule into a selector AST synchronously.
  40741. *
  40742. * @param rule {postcss.Rule | string} The css selector to be processed
  40743. * @param options The options for processing
  40744. * @returns {parser.Root} The AST of the selector after processing it.
  40745. */
  40746. Processor.prototype.astSync = function (rule, options) {
  40747. return this._runSync(rule, options).root;
  40748. };
  40749. /**
  40750. * Process a selector into a transformed value asynchronously
  40751. *
  40752. * @param rule {postcss.Rule | string} The css selector to be processed
  40753. * @param options The options for processing
  40754. * @returns {Promise<any>} The value returned by the processor.
  40755. */
  40756. Processor.prototype.transform = function (rule, options) {
  40757. return this._run(rule, options).then(function (result) { return result.transform; });
  40758. };
  40759. /**
  40760. * Process a selector into a transformed value synchronously.
  40761. *
  40762. * @param rule {postcss.Rule | string} The css selector to be processed
  40763. * @param options The options for processing
  40764. * @returns {any} The value returned by the processor.
  40765. */
  40766. Processor.prototype.transformSync = function (rule, options) {
  40767. return this._runSync(rule, options).transform;
  40768. };
  40769. /**
  40770. * Process a selector into a new selector string asynchronously.
  40771. *
  40772. * @param rule {postcss.Rule | string} The css selector to be processed
  40773. * @param options The options for processing
  40774. * @returns {string} the selector after processing.
  40775. */
  40776. Processor.prototype.process = function (rule, options) {
  40777. var _this = this;
  40778. return this._run(rule, options).then(function (result) { return result.string || result.root.toString(_this._stringifyOptions(options)); });
  40779. };
  40780. /**
  40781. * Process a selector into a new selector string synchronously.
  40782. *
  40783. * @param rule {postcss.Rule | string} The css selector to be processed
  40784. * @param options The options for processing
  40785. * @returns {string} the selector after processing.
  40786. */
  40787. Processor.prototype.processSync = function (rule, options) {
  40788. var result = this._runSync(rule, options);
  40789. return result.string || result.root.toString(this._stringifyOptions(options));
  40790. };
  40791. return Processor;
  40792. }());
  40793. processor.default = Processor;
  40794. return processor;
  40795. }
  40796. var selectors = {};
  40797. var constructors = {};
  40798. var hasRequiredConstructors;
  40799. function requireConstructors () {
  40800. if (hasRequiredConstructors) return constructors;
  40801. hasRequiredConstructors = 1;
  40802. var __importDefault = (constructors && constructors.__importDefault) || function (mod) {
  40803. return (mod && mod.__esModule) ? mod : { "default": mod };
  40804. };
  40805. Object.defineProperty(constructors, "__esModule", { value: true });
  40806. 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;
  40807. var attribute_1 = __importDefault(/*@__PURE__*/ requireAttribute());
  40808. var className_1 = __importDefault(/*@__PURE__*/ requireClassName());
  40809. var combinator_1 = __importDefault(/*@__PURE__*/ requireCombinator());
  40810. var comment_1 = __importDefault(/*@__PURE__*/ requireComment());
  40811. var id_1 = __importDefault(/*@__PURE__*/ requireId());
  40812. var nesting_1 = __importDefault(/*@__PURE__*/ requireNesting());
  40813. var pseudo_1 = __importDefault(/*@__PURE__*/ requirePseudo());
  40814. var root_1 = __importDefault(/*@__PURE__*/ requireRoot());
  40815. var selector_1 = __importDefault(/*@__PURE__*/ requireSelector());
  40816. var string_1 = __importDefault(/*@__PURE__*/ requireString());
  40817. var tag_1 = __importDefault(/*@__PURE__*/ requireTag());
  40818. var universal_1 = __importDefault(/*@__PURE__*/ requireUniversal());
  40819. var attribute = function (opts) { return new attribute_1.default(opts); };
  40820. constructors.attribute = attribute;
  40821. var className = function (opts) { return new className_1.default(opts); };
  40822. constructors.className = className;
  40823. var combinator = function (opts) { return new combinator_1.default(opts); };
  40824. constructors.combinator = combinator;
  40825. var comment = function (opts) { return new comment_1.default(opts); };
  40826. constructors.comment = comment;
  40827. var id = function (opts) { return new id_1.default(opts); };
  40828. constructors.id = id;
  40829. var nesting = function (opts) { return new nesting_1.default(opts); };
  40830. constructors.nesting = nesting;
  40831. var pseudo = function (opts) { return new pseudo_1.default(opts); };
  40832. constructors.pseudo = pseudo;
  40833. var root = function (opts) { return new root_1.default(opts); };
  40834. constructors.root = root;
  40835. var selector = function (opts) { return new selector_1.default(opts); };
  40836. constructors.selector = selector;
  40837. var string = function (opts) { return new string_1.default(opts); };
  40838. constructors.string = string;
  40839. var tag = function (opts) { return new tag_1.default(opts); };
  40840. constructors.tag = tag;
  40841. var universal = function (opts) { return new universal_1.default(opts); };
  40842. constructors.universal = universal;
  40843. return constructors;
  40844. }
  40845. var guards = {};
  40846. var hasRequiredGuards;
  40847. function requireGuards () {
  40848. if (hasRequiredGuards) return guards;
  40849. hasRequiredGuards = 1;
  40850. (function (exports) {
  40851. var _a;
  40852. Object.defineProperty(exports, "__esModule", { value: true });
  40853. exports.isUniversal = exports.isTag = exports.isString = exports.isSelector = exports.isRoot = exports.isPseudo = exports.isNesting = exports.isIdentifier = exports.isComment = exports.isCombinator = exports.isClassName = exports.isAttribute = void 0;
  40854. exports.isNode = isNode;
  40855. exports.isPseudoElement = isPseudoElement;
  40856. exports.isPseudoClass = isPseudoClass;
  40857. exports.isContainer = isContainer;
  40858. exports.isNamespace = isNamespace;
  40859. var types_1 = /*@__PURE__*/ requireTypes();
  40860. var IS_TYPE = (_a = {},
  40861. _a[types_1.ATTRIBUTE] = true,
  40862. _a[types_1.CLASS] = true,
  40863. _a[types_1.COMBINATOR] = true,
  40864. _a[types_1.COMMENT] = true,
  40865. _a[types_1.ID] = true,
  40866. _a[types_1.NESTING] = true,
  40867. _a[types_1.PSEUDO] = true,
  40868. _a[types_1.ROOT] = true,
  40869. _a[types_1.SELECTOR] = true,
  40870. _a[types_1.STRING] = true,
  40871. _a[types_1.TAG] = true,
  40872. _a[types_1.UNIVERSAL] = true,
  40873. _a);
  40874. function isNode(node) {
  40875. return typeof node === "object" && IS_TYPE[node.type];
  40876. }
  40877. function isNodeType(type, node) {
  40878. return isNode(node) && node.type === type;
  40879. }
  40880. exports.isAttribute = isNodeType.bind(null, types_1.ATTRIBUTE);
  40881. exports.isClassName = isNodeType.bind(null, types_1.CLASS);
  40882. exports.isCombinator = isNodeType.bind(null, types_1.COMBINATOR);
  40883. exports.isComment = isNodeType.bind(null, types_1.COMMENT);
  40884. exports.isIdentifier = isNodeType.bind(null, types_1.ID);
  40885. exports.isNesting = isNodeType.bind(null, types_1.NESTING);
  40886. exports.isPseudo = isNodeType.bind(null, types_1.PSEUDO);
  40887. exports.isRoot = isNodeType.bind(null, types_1.ROOT);
  40888. exports.isSelector = isNodeType.bind(null, types_1.SELECTOR);
  40889. exports.isString = isNodeType.bind(null, types_1.STRING);
  40890. exports.isTag = isNodeType.bind(null, types_1.TAG);
  40891. exports.isUniversal = isNodeType.bind(null, types_1.UNIVERSAL);
  40892. function isPseudoElement(node) {
  40893. return ((0, exports.isPseudo)(node) &&
  40894. node.value &&
  40895. (node.value.startsWith("::") ||
  40896. node.value.toLowerCase() === ":before" ||
  40897. node.value.toLowerCase() === ":after" ||
  40898. node.value.toLowerCase() === ":first-letter" ||
  40899. node.value.toLowerCase() === ":first-line"));
  40900. }
  40901. function isPseudoClass(node) {
  40902. return (0, exports.isPseudo)(node) && !isPseudoElement(node);
  40903. }
  40904. function isContainer(node) {
  40905. return !!(isNode(node) && node.walk);
  40906. }
  40907. function isNamespace(node) {
  40908. return (0, exports.isAttribute)(node) || (0, exports.isTag)(node);
  40909. }
  40910. } (guards));
  40911. return guards;
  40912. }
  40913. var hasRequiredSelectors;
  40914. function requireSelectors () {
  40915. if (hasRequiredSelectors) return selectors;
  40916. hasRequiredSelectors = 1;
  40917. (function (exports) {
  40918. var __createBinding = (selectors && selectors.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  40919. if (k2 === undefined) k2 = k;
  40920. var desc = Object.getOwnPropertyDescriptor(m, k);
  40921. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  40922. desc = { enumerable: true, get: function() { return m[k]; } };
  40923. }
  40924. Object.defineProperty(o, k2, desc);
  40925. }) : (function(o, m, k, k2) {
  40926. if (k2 === undefined) k2 = k;
  40927. o[k2] = m[k];
  40928. }));
  40929. var __exportStar = (selectors && selectors.__exportStar) || function(m, exports) {
  40930. for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
  40931. };
  40932. Object.defineProperty(exports, "__esModule", { value: true });
  40933. __exportStar(/*@__PURE__*/ requireTypes(), exports);
  40934. __exportStar(/*@__PURE__*/ requireConstructors(), exports);
  40935. __exportStar(/*@__PURE__*/ requireGuards(), exports);
  40936. } (selectors));
  40937. return selectors;
  40938. }
  40939. var dist;
  40940. var hasRequiredDist;
  40941. function requireDist () {
  40942. if (hasRequiredDist) return dist;
  40943. hasRequiredDist = 1;
  40944. var __createBinding = (dist && dist.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  40945. if (k2 === undefined) k2 = k;
  40946. var desc = Object.getOwnPropertyDescriptor(m, k);
  40947. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  40948. desc = { enumerable: true, get: function() { return m[k]; } };
  40949. }
  40950. Object.defineProperty(o, k2, desc);
  40951. }) : (function(o, m, k, k2) {
  40952. if (k2 === undefined) k2 = k;
  40953. o[k2] = m[k];
  40954. }));
  40955. var __setModuleDefault = (dist && dist.__setModuleDefault) || (Object.create ? (function(o, v) {
  40956. Object.defineProperty(o, "default", { enumerable: true, value: v });
  40957. }) : function(o, v) {
  40958. o["default"] = v;
  40959. });
  40960. var __importStar = (dist && dist.__importStar) || (function () {
  40961. var ownKeys = function(o) {
  40962. ownKeys = Object.getOwnPropertyNames || function (o) {
  40963. var ar = [];
  40964. for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
  40965. return ar;
  40966. };
  40967. return ownKeys(o);
  40968. };
  40969. return function (mod) {
  40970. if (mod && mod.__esModule) return mod;
  40971. var result = {};
  40972. if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
  40973. __setModuleDefault(result, mod);
  40974. return result;
  40975. };
  40976. })();
  40977. var __importDefault = (dist && dist.__importDefault) || function (mod) {
  40978. return (mod && mod.__esModule) ? mod : { "default": mod };
  40979. };
  40980. var processor_1 = __importDefault(/*@__PURE__*/ requireProcessor());
  40981. var selectors = __importStar(/*@__PURE__*/ requireSelectors());
  40982. var parser = function (processor) { return new processor_1.default(processor); };
  40983. Object.assign(parser, selectors);
  40984. delete parser.__esModule;
  40985. dist = parser;
  40986. return dist;
  40987. }
  40988. var distExports = /*@__PURE__*/ requireDist();
  40989. var selectorParser = /*@__PURE__*/getDefaultExportFromCjs(distExports);
  40990. const animationNameRE = /^(?:-\w+-)?animation-name$/;
  40991. const animationRE = /^(?:-\w+-)?animation$/;
  40992. const keyframesRE = /^(?:-\w+-)?keyframes$/;
  40993. const scopedPlugin = (id = "") => {
  40994. const keyframes = /* @__PURE__ */ Object.create(null);
  40995. const shortId = id.replace(/^data-v-/, "");
  40996. return {
  40997. postcssPlugin: "vue-sfc-scoped",
  40998. Rule(rule) {
  40999. processRule(id, rule);
  41000. },
  41001. AtRule(node) {
  41002. if (keyframesRE.test(node.name) && !node.params.endsWith(`-${shortId}`)) {
  41003. keyframes[node.params] = node.params = node.params + "-" + shortId;
  41004. }
  41005. },
  41006. OnceExit(root) {
  41007. if (Object.keys(keyframes).length) {
  41008. root.walkDecls((decl) => {
  41009. if (animationNameRE.test(decl.prop)) {
  41010. decl.value = decl.value.split(",").map((v) => keyframes[v.trim()] || v.trim()).join(",");
  41011. }
  41012. if (animationRE.test(decl.prop)) {
  41013. decl.value = decl.value.split(",").map((v) => {
  41014. const vals = v.trim().split(/\s+/);
  41015. const i = vals.findIndex((val) => keyframes[val]);
  41016. if (i !== -1) {
  41017. vals.splice(i, 1, keyframes[vals[i]]);
  41018. return vals.join(" ");
  41019. } else {
  41020. return v;
  41021. }
  41022. }).join(",");
  41023. }
  41024. });
  41025. }
  41026. }
  41027. };
  41028. };
  41029. const processedRules = /* @__PURE__ */ new WeakSet();
  41030. function processRule(id, rule) {
  41031. if (processedRules.has(rule) || rule.parent && rule.parent.type === "atrule" && keyframesRE.test(rule.parent.name)) {
  41032. return;
  41033. }
  41034. processedRules.add(rule);
  41035. let deep = false;
  41036. let parent = rule.parent;
  41037. while (parent && parent.type !== "root") {
  41038. if (parent.__deep) {
  41039. deep = true;
  41040. break;
  41041. }
  41042. parent = parent.parent;
  41043. }
  41044. rule.selector = selectorParser((selectorRoot) => {
  41045. selectorRoot.each((selector) => {
  41046. rewriteSelector(id, rule, selector, selectorRoot, deep);
  41047. });
  41048. }).processSync(rule.selector);
  41049. }
  41050. function rewriteSelector(id, rule, selector, selectorRoot, deep, slotted = false) {
  41051. let node = null;
  41052. let shouldInject = !deep;
  41053. let hasNestedDeep = false;
  41054. let splitForNestedDeep = false;
  41055. selector.each((n) => {
  41056. if (n.type === "combinator" && (n.value === ">>>" || n.value === "/deep/")) {
  41057. n.value = " ";
  41058. n.spaces.before = n.spaces.after = "";
  41059. warn(
  41060. `the >>> and /deep/ combinators have been deprecated. Use :deep() instead.`
  41061. );
  41062. return false;
  41063. }
  41064. if (n.type === "pseudo") {
  41065. const { value } = n;
  41066. if (isDeepContainerPseudo(n)) {
  41067. const hasDeepSelectors = n.nodes.some(
  41068. (selector2) => selector2.some(isDeepSelector)
  41069. );
  41070. if (hasDeepSelectors) {
  41071. const hasScopeAnchor = !!node;
  41072. const hasMixedSelectors = n.nodes.some(
  41073. (selector2) => !selector2.some(isDeepSelector)
  41074. );
  41075. const hasTrailingNodes = selector.index(n) < selector.length - 1;
  41076. if (canSplitDeepContainerPseudo(n) && !deep && !hasScopeAnchor && hasMixedSelectors && hasTrailingNodes) {
  41077. splitSelectorForNestedDeep(
  41078. id,
  41079. rule,
  41080. selector,
  41081. selectorRoot,
  41082. n,
  41083. deep,
  41084. slotted
  41085. );
  41086. splitForNestedDeep = true;
  41087. return false;
  41088. }
  41089. if (value === ":not" && !deep && !hasScopeAnchor && hasMixedSelectors && hasTrailingNodes) {
  41090. return;
  41091. }
  41092. n.nodes.forEach(
  41093. (selector2) => rewriteSelector(
  41094. id,
  41095. rule,
  41096. selector2,
  41097. selectorRoot,
  41098. deep || hasScopeAnchor,
  41099. slotted
  41100. )
  41101. );
  41102. if (!hasScopeAnchor) {
  41103. node = n;
  41104. shouldInject = false;
  41105. }
  41106. hasNestedDeep = true;
  41107. }
  41108. }
  41109. if (value === ":deep" || value === "::v-deep") {
  41110. rule.__deep = true;
  41111. if (n.nodes.length) {
  41112. let last = n;
  41113. n.nodes[0].each((ss) => {
  41114. selector.insertAfter(last, ss);
  41115. last = ss;
  41116. });
  41117. const prev = selector.at(selector.index(n) - 1);
  41118. if (!prev || !isSpaceCombinator(prev)) {
  41119. selector.insertAfter(
  41120. n,
  41121. selectorParser.combinator({
  41122. value: " "
  41123. })
  41124. );
  41125. }
  41126. selector.removeChild(n);
  41127. } else {
  41128. warn(
  41129. `${value} usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead of ${value} <inner-selector>.`
  41130. );
  41131. const prev = selector.at(selector.index(n) - 1);
  41132. if (prev && isSpaceCombinator(prev)) {
  41133. selector.removeChild(prev);
  41134. }
  41135. selector.removeChild(n);
  41136. }
  41137. return false;
  41138. }
  41139. if (value === ":slotted" || value === "::v-slotted") {
  41140. rewriteSelector(
  41141. id,
  41142. rule,
  41143. n.nodes[0],
  41144. selectorRoot,
  41145. deep,
  41146. true
  41147. );
  41148. let last = n;
  41149. n.nodes[0].each((ss) => {
  41150. selector.insertAfter(last, ss);
  41151. last = ss;
  41152. });
  41153. selector.removeChild(n);
  41154. shouldInject = false;
  41155. return false;
  41156. }
  41157. if (value === ":global" || value === "::v-global") {
  41158. selector.replaceWith(n.nodes[0]);
  41159. return false;
  41160. }
  41161. }
  41162. if (n.type === "universal") {
  41163. const prev = selector.at(selector.index(n) - 1);
  41164. const next = selector.at(selector.index(n) + 1);
  41165. if (!prev) {
  41166. if (next) {
  41167. if (next.type === "combinator" && next.value === " ") {
  41168. selector.removeChild(next);
  41169. }
  41170. selector.removeChild(n);
  41171. return;
  41172. } else {
  41173. node = selectorParser.combinator({
  41174. value: ""
  41175. });
  41176. selector.insertBefore(n, node);
  41177. selector.removeChild(n);
  41178. return false;
  41179. }
  41180. }
  41181. if (node) return;
  41182. }
  41183. if (!hasNestedDeep && (n.type !== "pseudo" && n.type !== "combinator" || n.type === "pseudo" && (n.value === ":is" || n.value === ":where") && !node)) {
  41184. node = n;
  41185. }
  41186. });
  41187. if (splitForNestedDeep) {
  41188. return;
  41189. }
  41190. if (rule.nodes.some((node2) => node2.type === "rule")) {
  41191. const deep2 = rule.__deep;
  41192. if (!deep2) {
  41193. extractAndWrapNodes(rule);
  41194. const atruleNodes = rule.nodes.filter((node2) => node2.type === "atrule");
  41195. for (const atnode of atruleNodes) {
  41196. extractAndWrapNodes(atnode);
  41197. }
  41198. }
  41199. shouldInject = deep2;
  41200. }
  41201. if (node && !hasNestedDeep) {
  41202. const { type, value } = node;
  41203. if (type === "pseudo" && (value === ":is" || value === ":where")) {
  41204. node.nodes.forEach(
  41205. (value2) => rewriteSelector(id, rule, value2, selectorRoot, deep, slotted)
  41206. );
  41207. shouldInject = false;
  41208. }
  41209. }
  41210. if (node) {
  41211. node.spaces.after = "";
  41212. } else {
  41213. selector.first.spaces.before = "";
  41214. }
  41215. if (shouldInject) {
  41216. const idToAdd = slotted ? id + "-s" : id;
  41217. selector.insertAfter(
  41218. // If node is null it means we need to inject [id] at the start
  41219. // insertAfter can handle `null` here
  41220. node,
  41221. selectorParser.attribute({
  41222. attribute: idToAdd,
  41223. value: idToAdd,
  41224. raws: {},
  41225. quoteMark: `"`
  41226. })
  41227. );
  41228. }
  41229. }
  41230. function isSpaceCombinator(node) {
  41231. return node.type === "combinator" && /^\s+$/.test(node.value);
  41232. }
  41233. function isDeepSelector(node) {
  41234. var _a;
  41235. if (node.type === "pseudo" && (node.value === ":deep" || node.value === "::v-deep")) {
  41236. return true;
  41237. }
  41238. return !!((_a = node.nodes) == null ? void 0 : _a.some((child) => isDeepSelector(child)));
  41239. }
  41240. function isDeepContainerPseudo(node) {
  41241. return node.type === "pseudo" && (node.value === ":is" || node.value === ":where" || node.value === ":has" || node.value === ":not");
  41242. }
  41243. function canSplitDeepContainerPseudo(node) {
  41244. return node.value === ":is" || node.value === ":where" || node.value === ":has";
  41245. }
  41246. function splitSelectorForNestedDeep(id, rule, selector, selectorRoot, pseudo, deep, slotted) {
  41247. const pseudoIndex = selector.index(pseudo);
  41248. const selectors = pseudo.nodes.map((branch, index) => {
  41249. const branchSelector = selector.clone();
  41250. if (branchSelector.first) {
  41251. branchSelector.first.spaces.before = index === 0 ? selector.first.spaces.before : " ";
  41252. }
  41253. const branchPseudo = branchSelector.at(pseudoIndex);
  41254. const branchClone = branch.clone();
  41255. if (branchClone.first) {
  41256. branchClone.first.spaces.before = "";
  41257. }
  41258. branchPseudo.removeAll();
  41259. branchPseudo.append(branchClone);
  41260. rewriteSelector(id, rule, branchSelector, selectorRoot, deep, slotted);
  41261. return branchSelector;
  41262. });
  41263. selector.replaceWith(...selectors);
  41264. }
  41265. function extractAndWrapNodes(parentNode) {
  41266. if (!parentNode.nodes) return;
  41267. const nodes = parentNode.nodes.filter(
  41268. (node) => node.type === "decl" || node.type === "comment"
  41269. );
  41270. if (nodes.length) {
  41271. for (const node of nodes) {
  41272. parentNode.removeChild(node);
  41273. }
  41274. const wrappedRule = new Rule({
  41275. nodes,
  41276. selector: "&"
  41277. });
  41278. parentNode.prepend(wrappedRule);
  41279. }
  41280. }
  41281. scopedPlugin.postcss = true;
  41282. var sourceMap = {};
  41283. var sourceMapGenerator = {};
  41284. var base64Vlq = {};
  41285. var base64 = {};
  41286. /* -*- Mode: js; js-indent-level: 2; -*- */
  41287. var hasRequiredBase64;
  41288. function requireBase64 () {
  41289. if (hasRequiredBase64) return base64;
  41290. hasRequiredBase64 = 1;
  41291. /*
  41292. * Copyright 2011 Mozilla Foundation and contributors
  41293. * Licensed under the New BSD license. See LICENSE or:
  41294. * http://opensource.org/licenses/BSD-3-Clause
  41295. */
  41296. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  41297. /**
  41298. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  41299. */
  41300. base64.encode = function (number) {
  41301. if (0 <= number && number < intToCharMap.length) {
  41302. return intToCharMap[number];
  41303. }
  41304. throw new TypeError("Must be between 0 and 63: " + number);
  41305. };
  41306. /**
  41307. * Decode a single base 64 character code digit to an integer. Returns -1 on
  41308. * failure.
  41309. */
  41310. base64.decode = function (charCode) {
  41311. var bigA = 65; // 'A'
  41312. var bigZ = 90; // 'Z'
  41313. var littleA = 97; // 'a'
  41314. var littleZ = 122; // 'z'
  41315. var zero = 48; // '0'
  41316. var nine = 57; // '9'
  41317. var plus = 43; // '+'
  41318. var slash = 47; // '/'
  41319. var littleOffset = 26;
  41320. var numberOffset = 52;
  41321. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  41322. if (bigA <= charCode && charCode <= bigZ) {
  41323. return (charCode - bigA);
  41324. }
  41325. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  41326. if (littleA <= charCode && charCode <= littleZ) {
  41327. return (charCode - littleA + littleOffset);
  41328. }
  41329. // 52 - 61: 0123456789
  41330. if (zero <= charCode && charCode <= nine) {
  41331. return (charCode - zero + numberOffset);
  41332. }
  41333. // 62: +
  41334. if (charCode == plus) {
  41335. return 62;
  41336. }
  41337. // 63: /
  41338. if (charCode == slash) {
  41339. return 63;
  41340. }
  41341. // Invalid base64 digit.
  41342. return -1;
  41343. };
  41344. return base64;
  41345. }
  41346. /* -*- Mode: js; js-indent-level: 2; -*- */
  41347. var hasRequiredBase64Vlq;
  41348. function requireBase64Vlq () {
  41349. if (hasRequiredBase64Vlq) return base64Vlq;
  41350. hasRequiredBase64Vlq = 1;
  41351. /*
  41352. * Copyright 2011 Mozilla Foundation and contributors
  41353. * Licensed under the New BSD license. See LICENSE or:
  41354. * http://opensource.org/licenses/BSD-3-Clause
  41355. *
  41356. * Based on the Base 64 VLQ implementation in Closure Compiler:
  41357. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  41358. *
  41359. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  41360. * Redistribution and use in source and binary forms, with or without
  41361. * modification, are permitted provided that the following conditions are
  41362. * met:
  41363. *
  41364. * * Redistributions of source code must retain the above copyright
  41365. * notice, this list of conditions and the following disclaimer.
  41366. * * Redistributions in binary form must reproduce the above
  41367. * copyright notice, this list of conditions and the following
  41368. * disclaimer in the documentation and/or other materials provided
  41369. * with the distribution.
  41370. * * Neither the name of Google Inc. nor the names of its
  41371. * contributors may be used to endorse or promote products derived
  41372. * from this software without specific prior written permission.
  41373. *
  41374. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  41375. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  41376. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  41377. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  41378. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  41379. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  41380. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  41381. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  41382. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  41383. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  41384. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  41385. */
  41386. var base64 = /*@__PURE__*/ requireBase64();
  41387. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  41388. // length quantities we use in the source map spec, the first bit is the sign,
  41389. // the next four bits are the actual value, and the 6th bit is the
  41390. // continuation bit. The continuation bit tells us whether there are more
  41391. // digits in this value following this digit.
  41392. //
  41393. // Continuation
  41394. // | Sign
  41395. // | |
  41396. // V V
  41397. // 101011
  41398. var VLQ_BASE_SHIFT = 5;
  41399. // binary: 100000
  41400. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  41401. // binary: 011111
  41402. var VLQ_BASE_MASK = VLQ_BASE - 1;
  41403. // binary: 100000
  41404. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  41405. /**
  41406. * Converts from a two-complement value to a value where the sign bit is
  41407. * placed in the least significant bit. For example, as decimals:
  41408. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  41409. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  41410. */
  41411. function toVLQSigned(aValue) {
  41412. return aValue < 0
  41413. ? ((-aValue) << 1) + 1
  41414. : (aValue << 1) + 0;
  41415. }
  41416. /**
  41417. * Converts to a two-complement value from a value where the sign bit is
  41418. * placed in the least significant bit. For example, as decimals:
  41419. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  41420. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  41421. */
  41422. function fromVLQSigned(aValue) {
  41423. var isNegative = (aValue & 1) === 1;
  41424. var shifted = aValue >> 1;
  41425. return isNegative
  41426. ? -shifted
  41427. : shifted;
  41428. }
  41429. /**
  41430. * Returns the base 64 VLQ encoded value.
  41431. */
  41432. base64Vlq.encode = function base64VLQ_encode(aValue) {
  41433. var encoded = "";
  41434. var digit;
  41435. var vlq = toVLQSigned(aValue);
  41436. do {
  41437. digit = vlq & VLQ_BASE_MASK;
  41438. vlq >>>= VLQ_BASE_SHIFT;
  41439. if (vlq > 0) {
  41440. // There are still more digits in this value, so we must make sure the
  41441. // continuation bit is marked.
  41442. digit |= VLQ_CONTINUATION_BIT;
  41443. }
  41444. encoded += base64.encode(digit);
  41445. } while (vlq > 0);
  41446. return encoded;
  41447. };
  41448. /**
  41449. * Decodes the next base 64 VLQ value from the given string and returns the
  41450. * value and the rest of the string via the out parameter.
  41451. */
  41452. base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  41453. var strLen = aStr.length;
  41454. var result = 0;
  41455. var shift = 0;
  41456. var continuation, digit;
  41457. do {
  41458. if (aIndex >= strLen) {
  41459. throw new Error("Expected more digits in base 64 VLQ value.");
  41460. }
  41461. digit = base64.decode(aStr.charCodeAt(aIndex++));
  41462. if (digit === -1) {
  41463. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  41464. }
  41465. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  41466. digit &= VLQ_BASE_MASK;
  41467. result = result + (digit << shift);
  41468. shift += VLQ_BASE_SHIFT;
  41469. } while (continuation);
  41470. aOutParam.value = fromVLQSigned(result);
  41471. aOutParam.rest = aIndex;
  41472. };
  41473. return base64Vlq;
  41474. }
  41475. var util = {};
  41476. /* -*- Mode: js; js-indent-level: 2; -*- */
  41477. var hasRequiredUtil;
  41478. function requireUtil () {
  41479. if (hasRequiredUtil) return util;
  41480. hasRequiredUtil = 1;
  41481. (function (exports) {
  41482. /*
  41483. * Copyright 2011 Mozilla Foundation and contributors
  41484. * Licensed under the New BSD license. See LICENSE or:
  41485. * http://opensource.org/licenses/BSD-3-Clause
  41486. */
  41487. /**
  41488. * This is a helper function for getting values from parameter/options
  41489. * objects.
  41490. *
  41491. * @param args The object we are extracting values from
  41492. * @param name The name of the property we are getting.
  41493. * @param defaultValue An optional value to return if the property is missing
  41494. * from the object. If this is not specified and the property is missing, an
  41495. * error will be thrown.
  41496. */
  41497. function getArg(aArgs, aName, aDefaultValue) {
  41498. if (aName in aArgs) {
  41499. return aArgs[aName];
  41500. } else if (arguments.length === 3) {
  41501. return aDefaultValue;
  41502. } else {
  41503. throw new Error('"' + aName + '" is a required argument.');
  41504. }
  41505. }
  41506. exports.getArg = getArg;
  41507. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  41508. var dataUrlRegexp = /^data:.+\,.+$/;
  41509. function urlParse(aUrl) {
  41510. var match = aUrl.match(urlRegexp);
  41511. if (!match) {
  41512. return null;
  41513. }
  41514. return {
  41515. scheme: match[1],
  41516. auth: match[2],
  41517. host: match[3],
  41518. port: match[4],
  41519. path: match[5]
  41520. };
  41521. }
  41522. exports.urlParse = urlParse;
  41523. function urlGenerate(aParsedUrl) {
  41524. var url = '';
  41525. if (aParsedUrl.scheme) {
  41526. url += aParsedUrl.scheme + ':';
  41527. }
  41528. url += '//';
  41529. if (aParsedUrl.auth) {
  41530. url += aParsedUrl.auth + '@';
  41531. }
  41532. if (aParsedUrl.host) {
  41533. url += aParsedUrl.host;
  41534. }
  41535. if (aParsedUrl.port) {
  41536. url += ":" + aParsedUrl.port;
  41537. }
  41538. if (aParsedUrl.path) {
  41539. url += aParsedUrl.path;
  41540. }
  41541. return url;
  41542. }
  41543. exports.urlGenerate = urlGenerate;
  41544. /**
  41545. * Normalizes a path, or the path portion of a URL:
  41546. *
  41547. * - Replaces consecutive slashes with one slash.
  41548. * - Removes unnecessary '.' parts.
  41549. * - Removes unnecessary '<dir>/..' parts.
  41550. *
  41551. * Based on code in the Node.js 'path' core module.
  41552. *
  41553. * @param aPath The path or url to normalize.
  41554. */
  41555. function normalize(aPath) {
  41556. var path = aPath;
  41557. var url = urlParse(aPath);
  41558. if (url) {
  41559. if (!url.path) {
  41560. return aPath;
  41561. }
  41562. path = url.path;
  41563. }
  41564. var isAbsolute = exports.isAbsolute(path);
  41565. var parts = path.split(/\/+/);
  41566. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  41567. part = parts[i];
  41568. if (part === '.') {
  41569. parts.splice(i, 1);
  41570. } else if (part === '..') {
  41571. up++;
  41572. } else if (up > 0) {
  41573. if (part === '') {
  41574. // The first part is blank if the path is absolute. Trying to go
  41575. // above the root is a no-op. Therefore we can remove all '..' parts
  41576. // directly after the root.
  41577. parts.splice(i + 1, up);
  41578. up = 0;
  41579. } else {
  41580. parts.splice(i, 2);
  41581. up--;
  41582. }
  41583. }
  41584. }
  41585. path = parts.join('/');
  41586. if (path === '') {
  41587. path = isAbsolute ? '/' : '.';
  41588. }
  41589. if (url) {
  41590. url.path = path;
  41591. return urlGenerate(url);
  41592. }
  41593. return path;
  41594. }
  41595. exports.normalize = normalize;
  41596. /**
  41597. * Joins two paths/URLs.
  41598. *
  41599. * @param aRoot The root path or URL.
  41600. * @param aPath The path or URL to be joined with the root.
  41601. *
  41602. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  41603. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  41604. * first.
  41605. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  41606. * is updated with the result and aRoot is returned. Otherwise the result
  41607. * is returned.
  41608. * - If aPath is absolute, the result is aPath.
  41609. * - Otherwise the two paths are joined with a slash.
  41610. * - Joining for example 'http://' and 'www.example.com' is also supported.
  41611. */
  41612. function join(aRoot, aPath) {
  41613. if (aRoot === "") {
  41614. aRoot = ".";
  41615. }
  41616. if (aPath === "") {
  41617. aPath = ".";
  41618. }
  41619. var aPathUrl = urlParse(aPath);
  41620. var aRootUrl = urlParse(aRoot);
  41621. if (aRootUrl) {
  41622. aRoot = aRootUrl.path || '/';
  41623. }
  41624. // `join(foo, '//www.example.org')`
  41625. if (aPathUrl && !aPathUrl.scheme) {
  41626. if (aRootUrl) {
  41627. aPathUrl.scheme = aRootUrl.scheme;
  41628. }
  41629. return urlGenerate(aPathUrl);
  41630. }
  41631. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  41632. return aPath;
  41633. }
  41634. // `join('http://', 'www.example.com')`
  41635. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  41636. aRootUrl.host = aPath;
  41637. return urlGenerate(aRootUrl);
  41638. }
  41639. var joined = aPath.charAt(0) === '/'
  41640. ? aPath
  41641. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  41642. if (aRootUrl) {
  41643. aRootUrl.path = joined;
  41644. return urlGenerate(aRootUrl);
  41645. }
  41646. return joined;
  41647. }
  41648. exports.join = join;
  41649. exports.isAbsolute = function (aPath) {
  41650. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  41651. };
  41652. /**
  41653. * Make a path relative to a URL or another path.
  41654. *
  41655. * @param aRoot The root path or URL.
  41656. * @param aPath The path or URL to be made relative to aRoot.
  41657. */
  41658. function relative(aRoot, aPath) {
  41659. if (aRoot === "") {
  41660. aRoot = ".";
  41661. }
  41662. aRoot = aRoot.replace(/\/$/, '');
  41663. // It is possible for the path to be above the root. In this case, simply
  41664. // checking whether the root is a prefix of the path won't work. Instead, we
  41665. // need to remove components from the root one by one, until either we find
  41666. // a prefix that fits, or we run out of components to remove.
  41667. var level = 0;
  41668. while (aPath.indexOf(aRoot + '/') !== 0) {
  41669. var index = aRoot.lastIndexOf("/");
  41670. if (index < 0) {
  41671. return aPath;
  41672. }
  41673. // If the only part of the root that is left is the scheme (i.e. http://,
  41674. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  41675. // have exhausted all components, so the path is not relative to the root.
  41676. aRoot = aRoot.slice(0, index);
  41677. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  41678. return aPath;
  41679. }
  41680. ++level;
  41681. }
  41682. // Make sure we add a "../" for each component we removed from the root.
  41683. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  41684. }
  41685. exports.relative = relative;
  41686. var supportsNullProto = (function () {
  41687. var obj = Object.create(null);
  41688. return !('__proto__' in obj);
  41689. }());
  41690. function identity (s) {
  41691. return s;
  41692. }
  41693. /**
  41694. * Because behavior goes wacky when you set `__proto__` on objects, we
  41695. * have to prefix all the strings in our set with an arbitrary character.
  41696. *
  41697. * See https://github.com/mozilla/source-map/pull/31 and
  41698. * https://github.com/mozilla/source-map/issues/30
  41699. *
  41700. * @param String aStr
  41701. */
  41702. function toSetString(aStr) {
  41703. if (isProtoString(aStr)) {
  41704. return '$' + aStr;
  41705. }
  41706. return aStr;
  41707. }
  41708. exports.toSetString = supportsNullProto ? identity : toSetString;
  41709. function fromSetString(aStr) {
  41710. if (isProtoString(aStr)) {
  41711. return aStr.slice(1);
  41712. }
  41713. return aStr;
  41714. }
  41715. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  41716. function isProtoString(s) {
  41717. if (!s) {
  41718. return false;
  41719. }
  41720. var length = s.length;
  41721. if (length < 9 /* "__proto__".length */) {
  41722. return false;
  41723. }
  41724. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  41725. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  41726. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  41727. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  41728. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  41729. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  41730. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  41731. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  41732. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  41733. return false;
  41734. }
  41735. for (var i = length - 10; i >= 0; i--) {
  41736. if (s.charCodeAt(i) !== 36 /* '$' */) {
  41737. return false;
  41738. }
  41739. }
  41740. return true;
  41741. }
  41742. /**
  41743. * Comparator between two mappings where the original positions are compared.
  41744. *
  41745. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  41746. * mappings with the same original source/line/column, but different generated
  41747. * line and column the same. Useful when searching for a mapping with a
  41748. * stubbed out mapping.
  41749. */
  41750. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  41751. var cmp = strcmp(mappingA.source, mappingB.source);
  41752. if (cmp !== 0) {
  41753. return cmp;
  41754. }
  41755. cmp = mappingA.originalLine - mappingB.originalLine;
  41756. if (cmp !== 0) {
  41757. return cmp;
  41758. }
  41759. cmp = mappingA.originalColumn - mappingB.originalColumn;
  41760. if (cmp !== 0 || onlyCompareOriginal) {
  41761. return cmp;
  41762. }
  41763. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  41764. if (cmp !== 0) {
  41765. return cmp;
  41766. }
  41767. cmp = mappingA.generatedLine - mappingB.generatedLine;
  41768. if (cmp !== 0) {
  41769. return cmp;
  41770. }
  41771. return strcmp(mappingA.name, mappingB.name);
  41772. }
  41773. exports.compareByOriginalPositions = compareByOriginalPositions;
  41774. /**
  41775. * Comparator between two mappings with deflated source and name indices where
  41776. * the generated positions are compared.
  41777. *
  41778. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  41779. * mappings with the same generated line and column, but different
  41780. * source/name/original line and column the same. Useful when searching for a
  41781. * mapping with a stubbed out mapping.
  41782. */
  41783. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  41784. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  41785. if (cmp !== 0) {
  41786. return cmp;
  41787. }
  41788. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  41789. if (cmp !== 0 || onlyCompareGenerated) {
  41790. return cmp;
  41791. }
  41792. cmp = strcmp(mappingA.source, mappingB.source);
  41793. if (cmp !== 0) {
  41794. return cmp;
  41795. }
  41796. cmp = mappingA.originalLine - mappingB.originalLine;
  41797. if (cmp !== 0) {
  41798. return cmp;
  41799. }
  41800. cmp = mappingA.originalColumn - mappingB.originalColumn;
  41801. if (cmp !== 0) {
  41802. return cmp;
  41803. }
  41804. return strcmp(mappingA.name, mappingB.name);
  41805. }
  41806. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  41807. function strcmp(aStr1, aStr2) {
  41808. if (aStr1 === aStr2) {
  41809. return 0;
  41810. }
  41811. if (aStr1 === null) {
  41812. return 1; // aStr2 !== null
  41813. }
  41814. if (aStr2 === null) {
  41815. return -1; // aStr1 !== null
  41816. }
  41817. if (aStr1 > aStr2) {
  41818. return 1;
  41819. }
  41820. return -1;
  41821. }
  41822. /**
  41823. * Comparator between two mappings with inflated source and name strings where
  41824. * the generated positions are compared.
  41825. */
  41826. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  41827. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  41828. if (cmp !== 0) {
  41829. return cmp;
  41830. }
  41831. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  41832. if (cmp !== 0) {
  41833. return cmp;
  41834. }
  41835. cmp = strcmp(mappingA.source, mappingB.source);
  41836. if (cmp !== 0) {
  41837. return cmp;
  41838. }
  41839. cmp = mappingA.originalLine - mappingB.originalLine;
  41840. if (cmp !== 0) {
  41841. return cmp;
  41842. }
  41843. cmp = mappingA.originalColumn - mappingB.originalColumn;
  41844. if (cmp !== 0) {
  41845. return cmp;
  41846. }
  41847. return strcmp(mappingA.name, mappingB.name);
  41848. }
  41849. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  41850. /**
  41851. * Strip any JSON XSSI avoidance prefix from the string (as documented
  41852. * in the source maps specification), and then parse the string as
  41853. * JSON.
  41854. */
  41855. function parseSourceMapInput(str) {
  41856. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  41857. }
  41858. exports.parseSourceMapInput = parseSourceMapInput;
  41859. /**
  41860. * Compute the URL of a source given the the source root, the source's
  41861. * URL, and the source map's URL.
  41862. */
  41863. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  41864. sourceURL = sourceURL || '';
  41865. if (sourceRoot) {
  41866. // This follows what Chrome does.
  41867. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  41868. sourceRoot += '/';
  41869. }
  41870. // The spec says:
  41871. // Line 4: An optional source root, useful for relocating source
  41872. // files on a server or removing repeated values in the
  41873. // “sources” entry. This value is prepended to the individual
  41874. // entries in the “source” field.
  41875. sourceURL = sourceRoot + sourceURL;
  41876. }
  41877. // Historically, SourceMapConsumer did not take the sourceMapURL as
  41878. // a parameter. This mode is still somewhat supported, which is why
  41879. // this code block is conditional. However, it's preferable to pass
  41880. // the source map URL to SourceMapConsumer, so that this function
  41881. // can implement the source URL resolution algorithm as outlined in
  41882. // the spec. This block is basically the equivalent of:
  41883. // new URL(sourceURL, sourceMapURL).toString()
  41884. // ... except it avoids using URL, which wasn't available in the
  41885. // older releases of node still supported by this library.
  41886. //
  41887. // The spec says:
  41888. // If the sources are not absolute URLs after prepending of the
  41889. // “sourceRoot”, the sources are resolved relative to the
  41890. // SourceMap (like resolving script src in a html document).
  41891. if (sourceMapURL) {
  41892. var parsed = urlParse(sourceMapURL);
  41893. if (!parsed) {
  41894. throw new Error("sourceMapURL could not be parsed");
  41895. }
  41896. if (parsed.path) {
  41897. // Strip the last path component, but keep the "/".
  41898. var index = parsed.path.lastIndexOf('/');
  41899. if (index >= 0) {
  41900. parsed.path = parsed.path.substring(0, index + 1);
  41901. }
  41902. }
  41903. sourceURL = join(urlGenerate(parsed), sourceURL);
  41904. }
  41905. return normalize(sourceURL);
  41906. }
  41907. exports.computeSourceURL = computeSourceURL;
  41908. } (util));
  41909. return util;
  41910. }
  41911. var arraySet = {};
  41912. /* -*- Mode: js; js-indent-level: 2; -*- */
  41913. var hasRequiredArraySet;
  41914. function requireArraySet () {
  41915. if (hasRequiredArraySet) return arraySet;
  41916. hasRequiredArraySet = 1;
  41917. /*
  41918. * Copyright 2011 Mozilla Foundation and contributors
  41919. * Licensed under the New BSD license. See LICENSE or:
  41920. * http://opensource.org/licenses/BSD-3-Clause
  41921. */
  41922. var util = /*@__PURE__*/ requireUtil();
  41923. var has = Object.prototype.hasOwnProperty;
  41924. var hasNativeMap = typeof Map !== "undefined";
  41925. /**
  41926. * A data structure which is a combination of an array and a set. Adding a new
  41927. * member is O(1), testing for membership is O(1), and finding the index of an
  41928. * element is O(1). Removing elements from the set is not supported. Only
  41929. * strings are supported for membership.
  41930. */
  41931. function ArraySet() {
  41932. this._array = [];
  41933. this._set = hasNativeMap ? new Map() : Object.create(null);
  41934. }
  41935. /**
  41936. * Static method for creating ArraySet instances from an existing array.
  41937. */
  41938. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  41939. var set = new ArraySet();
  41940. for (var i = 0, len = aArray.length; i < len; i++) {
  41941. set.add(aArray[i], aAllowDuplicates);
  41942. }
  41943. return set;
  41944. };
  41945. /**
  41946. * Return how many unique items are in this ArraySet. If duplicates have been
  41947. * added, than those do not count towards the size.
  41948. *
  41949. * @returns Number
  41950. */
  41951. ArraySet.prototype.size = function ArraySet_size() {
  41952. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  41953. };
  41954. /**
  41955. * Add the given string to this set.
  41956. *
  41957. * @param String aStr
  41958. */
  41959. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  41960. var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
  41961. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  41962. var idx = this._array.length;
  41963. if (!isDuplicate || aAllowDuplicates) {
  41964. this._array.push(aStr);
  41965. }
  41966. if (!isDuplicate) {
  41967. if (hasNativeMap) {
  41968. this._set.set(aStr, idx);
  41969. } else {
  41970. this._set[sStr] = idx;
  41971. }
  41972. }
  41973. };
  41974. /**
  41975. * Is the given string a member of this set?
  41976. *
  41977. * @param String aStr
  41978. */
  41979. ArraySet.prototype.has = function ArraySet_has(aStr) {
  41980. if (hasNativeMap) {
  41981. return this._set.has(aStr);
  41982. } else {
  41983. var sStr = util.toSetString(aStr);
  41984. return has.call(this._set, sStr);
  41985. }
  41986. };
  41987. /**
  41988. * What is the index of the given string in the array?
  41989. *
  41990. * @param String aStr
  41991. */
  41992. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  41993. if (hasNativeMap) {
  41994. var idx = this._set.get(aStr);
  41995. if (idx >= 0) {
  41996. return idx;
  41997. }
  41998. } else {
  41999. var sStr = util.toSetString(aStr);
  42000. if (has.call(this._set, sStr)) {
  42001. return this._set[sStr];
  42002. }
  42003. }
  42004. throw new Error('"' + aStr + '" is not in the set.');
  42005. };
  42006. /**
  42007. * What is the element at the given index?
  42008. *
  42009. * @param Number aIdx
  42010. */
  42011. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  42012. if (aIdx >= 0 && aIdx < this._array.length) {
  42013. return this._array[aIdx];
  42014. }
  42015. throw new Error('No element indexed by ' + aIdx);
  42016. };
  42017. /**
  42018. * Returns the array representation of this set (which has the proper indices
  42019. * indicated by indexOf). Note that this is a copy of the internal array used
  42020. * for storing the members so that no one can mess with internal state.
  42021. */
  42022. ArraySet.prototype.toArray = function ArraySet_toArray() {
  42023. return this._array.slice();
  42024. };
  42025. arraySet.ArraySet = ArraySet;
  42026. return arraySet;
  42027. }
  42028. var mappingList = {};
  42029. /* -*- Mode: js; js-indent-level: 2; -*- */
  42030. var hasRequiredMappingList;
  42031. function requireMappingList () {
  42032. if (hasRequiredMappingList) return mappingList;
  42033. hasRequiredMappingList = 1;
  42034. /*
  42035. * Copyright 2014 Mozilla Foundation and contributors
  42036. * Licensed under the New BSD license. See LICENSE or:
  42037. * http://opensource.org/licenses/BSD-3-Clause
  42038. */
  42039. var util = /*@__PURE__*/ requireUtil();
  42040. /**
  42041. * Determine whether mappingB is after mappingA with respect to generated
  42042. * position.
  42043. */
  42044. function generatedPositionAfter(mappingA, mappingB) {
  42045. // Optimized for most common case
  42046. var lineA = mappingA.generatedLine;
  42047. var lineB = mappingB.generatedLine;
  42048. var columnA = mappingA.generatedColumn;
  42049. var columnB = mappingB.generatedColumn;
  42050. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  42051. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  42052. }
  42053. /**
  42054. * A data structure to provide a sorted view of accumulated mappings in a
  42055. * performance conscious manner. It trades a neglibable overhead in general
  42056. * case for a large speedup in case of mappings being added in order.
  42057. */
  42058. function MappingList() {
  42059. this._array = [];
  42060. this._sorted = true;
  42061. // Serves as infimum
  42062. this._last = {generatedLine: -1, generatedColumn: 0};
  42063. }
  42064. /**
  42065. * Iterate through internal items. This method takes the same arguments that
  42066. * `Array.prototype.forEach` takes.
  42067. *
  42068. * NOTE: The order of the mappings is NOT guaranteed.
  42069. */
  42070. MappingList.prototype.unsortedForEach =
  42071. function MappingList_forEach(aCallback, aThisArg) {
  42072. this._array.forEach(aCallback, aThisArg);
  42073. };
  42074. /**
  42075. * Add the given source mapping.
  42076. *
  42077. * @param Object aMapping
  42078. */
  42079. MappingList.prototype.add = function MappingList_add(aMapping) {
  42080. if (generatedPositionAfter(this._last, aMapping)) {
  42081. this._last = aMapping;
  42082. this._array.push(aMapping);
  42083. } else {
  42084. this._sorted = false;
  42085. this._array.push(aMapping);
  42086. }
  42087. };
  42088. /**
  42089. * Returns the flat, sorted array of mappings. The mappings are sorted by
  42090. * generated position.
  42091. *
  42092. * WARNING: This method returns internal data without copying, for
  42093. * performance. The return value must NOT be mutated, and should be treated as
  42094. * an immutable borrow. If you want to take ownership, you must make your own
  42095. * copy.
  42096. */
  42097. MappingList.prototype.toArray = function MappingList_toArray() {
  42098. if (!this._sorted) {
  42099. this._array.sort(util.compareByGeneratedPositionsInflated);
  42100. this._sorted = true;
  42101. }
  42102. return this._array;
  42103. };
  42104. mappingList.MappingList = MappingList;
  42105. return mappingList;
  42106. }
  42107. /* -*- Mode: js; js-indent-level: 2; -*- */
  42108. var hasRequiredSourceMapGenerator;
  42109. function requireSourceMapGenerator () {
  42110. if (hasRequiredSourceMapGenerator) return sourceMapGenerator;
  42111. hasRequiredSourceMapGenerator = 1;
  42112. /*
  42113. * Copyright 2011 Mozilla Foundation and contributors
  42114. * Licensed under the New BSD license. See LICENSE or:
  42115. * http://opensource.org/licenses/BSD-3-Clause
  42116. */
  42117. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  42118. var util = /*@__PURE__*/ requireUtil();
  42119. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  42120. var MappingList = /*@__PURE__*/ requireMappingList().MappingList;
  42121. /**
  42122. * An instance of the SourceMapGenerator represents a source map which is
  42123. * being built incrementally. You may pass an object with the following
  42124. * properties:
  42125. *
  42126. * - file: The filename of the generated source.
  42127. * - sourceRoot: A root for all relative URLs in this source map.
  42128. */
  42129. function SourceMapGenerator(aArgs) {
  42130. if (!aArgs) {
  42131. aArgs = {};
  42132. }
  42133. this._file = util.getArg(aArgs, 'file', null);
  42134. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  42135. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  42136. this._sources = new ArraySet();
  42137. this._names = new ArraySet();
  42138. this._mappings = new MappingList();
  42139. this._sourcesContents = null;
  42140. }
  42141. SourceMapGenerator.prototype._version = 3;
  42142. /**
  42143. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  42144. *
  42145. * @param aSourceMapConsumer The SourceMap.
  42146. */
  42147. SourceMapGenerator.fromSourceMap =
  42148. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  42149. var sourceRoot = aSourceMapConsumer.sourceRoot;
  42150. var generator = new SourceMapGenerator({
  42151. file: aSourceMapConsumer.file,
  42152. sourceRoot: sourceRoot
  42153. });
  42154. aSourceMapConsumer.eachMapping(function (mapping) {
  42155. var newMapping = {
  42156. generated: {
  42157. line: mapping.generatedLine,
  42158. column: mapping.generatedColumn
  42159. }
  42160. };
  42161. if (mapping.source != null) {
  42162. newMapping.source = mapping.source;
  42163. if (sourceRoot != null) {
  42164. newMapping.source = util.relative(sourceRoot, newMapping.source);
  42165. }
  42166. newMapping.original = {
  42167. line: mapping.originalLine,
  42168. column: mapping.originalColumn
  42169. };
  42170. if (mapping.name != null) {
  42171. newMapping.name = mapping.name;
  42172. }
  42173. }
  42174. generator.addMapping(newMapping);
  42175. });
  42176. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  42177. var sourceRelative = sourceFile;
  42178. if (sourceRoot !== null) {
  42179. sourceRelative = util.relative(sourceRoot, sourceFile);
  42180. }
  42181. if (!generator._sources.has(sourceRelative)) {
  42182. generator._sources.add(sourceRelative);
  42183. }
  42184. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  42185. if (content != null) {
  42186. generator.setSourceContent(sourceFile, content);
  42187. }
  42188. });
  42189. return generator;
  42190. };
  42191. /**
  42192. * Add a single mapping from original source line and column to the generated
  42193. * source's line and column for this source map being created. The mapping
  42194. * object should have the following properties:
  42195. *
  42196. * - generated: An object with the generated line and column positions.
  42197. * - original: An object with the original line and column positions.
  42198. * - source: The original source file (relative to the sourceRoot).
  42199. * - name: An optional original token name for this mapping.
  42200. */
  42201. SourceMapGenerator.prototype.addMapping =
  42202. function SourceMapGenerator_addMapping(aArgs) {
  42203. var generated = util.getArg(aArgs, 'generated');
  42204. var original = util.getArg(aArgs, 'original', null);
  42205. var source = util.getArg(aArgs, 'source', null);
  42206. var name = util.getArg(aArgs, 'name', null);
  42207. if (!this._skipValidation) {
  42208. this._validateMapping(generated, original, source, name);
  42209. }
  42210. if (source != null) {
  42211. source = String(source);
  42212. if (!this._sources.has(source)) {
  42213. this._sources.add(source);
  42214. }
  42215. }
  42216. if (name != null) {
  42217. name = String(name);
  42218. if (!this._names.has(name)) {
  42219. this._names.add(name);
  42220. }
  42221. }
  42222. this._mappings.add({
  42223. generatedLine: generated.line,
  42224. generatedColumn: generated.column,
  42225. originalLine: original != null && original.line,
  42226. originalColumn: original != null && original.column,
  42227. source: source,
  42228. name: name
  42229. });
  42230. };
  42231. /**
  42232. * Set the source content for a source file.
  42233. */
  42234. SourceMapGenerator.prototype.setSourceContent =
  42235. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  42236. var source = aSourceFile;
  42237. if (this._sourceRoot != null) {
  42238. source = util.relative(this._sourceRoot, source);
  42239. }
  42240. if (aSourceContent != null) {
  42241. // Add the source content to the _sourcesContents map.
  42242. // Create a new _sourcesContents map if the property is null.
  42243. if (!this._sourcesContents) {
  42244. this._sourcesContents = Object.create(null);
  42245. }
  42246. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  42247. } else if (this._sourcesContents) {
  42248. // Remove the source file from the _sourcesContents map.
  42249. // If the _sourcesContents map is empty, set the property to null.
  42250. delete this._sourcesContents[util.toSetString(source)];
  42251. if (Object.keys(this._sourcesContents).length === 0) {
  42252. this._sourcesContents = null;
  42253. }
  42254. }
  42255. };
  42256. /**
  42257. * Applies the mappings of a sub-source-map for a specific source file to the
  42258. * source map being generated. Each mapping to the supplied source file is
  42259. * rewritten using the supplied source map. Note: The resolution for the
  42260. * resulting mappings is the minimium of this map and the supplied map.
  42261. *
  42262. * @param aSourceMapConsumer The source map to be applied.
  42263. * @param aSourceFile Optional. The filename of the source file.
  42264. * If omitted, SourceMapConsumer's file property will be used.
  42265. * @param aSourceMapPath Optional. The dirname of the path to the source map
  42266. * to be applied. If relative, it is relative to the SourceMapConsumer.
  42267. * This parameter is needed when the two source maps aren't in the same
  42268. * directory, and the source map to be applied contains relative source
  42269. * paths. If so, those relative source paths need to be rewritten
  42270. * relative to the SourceMapGenerator.
  42271. */
  42272. SourceMapGenerator.prototype.applySourceMap =
  42273. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  42274. var sourceFile = aSourceFile;
  42275. // If aSourceFile is omitted, we will use the file property of the SourceMap
  42276. if (aSourceFile == null) {
  42277. if (aSourceMapConsumer.file == null) {
  42278. throw new Error(
  42279. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  42280. 'or the source map\'s "file" property. Both were omitted.'
  42281. );
  42282. }
  42283. sourceFile = aSourceMapConsumer.file;
  42284. }
  42285. var sourceRoot = this._sourceRoot;
  42286. // Make "sourceFile" relative if an absolute Url is passed.
  42287. if (sourceRoot != null) {
  42288. sourceFile = util.relative(sourceRoot, sourceFile);
  42289. }
  42290. // Applying the SourceMap can add and remove items from the sources and
  42291. // the names array.
  42292. var newSources = new ArraySet();
  42293. var newNames = new ArraySet();
  42294. // Find mappings for the "sourceFile"
  42295. this._mappings.unsortedForEach(function (mapping) {
  42296. if (mapping.source === sourceFile && mapping.originalLine != null) {
  42297. // Check if it can be mapped by the source map, then update the mapping.
  42298. var original = aSourceMapConsumer.originalPositionFor({
  42299. line: mapping.originalLine,
  42300. column: mapping.originalColumn
  42301. });
  42302. if (original.source != null) {
  42303. // Copy mapping
  42304. mapping.source = original.source;
  42305. if (aSourceMapPath != null) {
  42306. mapping.source = util.join(aSourceMapPath, mapping.source);
  42307. }
  42308. if (sourceRoot != null) {
  42309. mapping.source = util.relative(sourceRoot, mapping.source);
  42310. }
  42311. mapping.originalLine = original.line;
  42312. mapping.originalColumn = original.column;
  42313. if (original.name != null) {
  42314. mapping.name = original.name;
  42315. }
  42316. }
  42317. }
  42318. var source = mapping.source;
  42319. if (source != null && !newSources.has(source)) {
  42320. newSources.add(source);
  42321. }
  42322. var name = mapping.name;
  42323. if (name != null && !newNames.has(name)) {
  42324. newNames.add(name);
  42325. }
  42326. }, this);
  42327. this._sources = newSources;
  42328. this._names = newNames;
  42329. // Copy sourcesContents of applied map.
  42330. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  42331. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  42332. if (content != null) {
  42333. if (aSourceMapPath != null) {
  42334. sourceFile = util.join(aSourceMapPath, sourceFile);
  42335. }
  42336. if (sourceRoot != null) {
  42337. sourceFile = util.relative(sourceRoot, sourceFile);
  42338. }
  42339. this.setSourceContent(sourceFile, content);
  42340. }
  42341. }, this);
  42342. };
  42343. /**
  42344. * A mapping can have one of the three levels of data:
  42345. *
  42346. * 1. Just the generated position.
  42347. * 2. The Generated position, original position, and original source.
  42348. * 3. Generated and original position, original source, as well as a name
  42349. * token.
  42350. *
  42351. * To maintain consistency, we validate that any new mapping being added falls
  42352. * in to one of these categories.
  42353. */
  42354. SourceMapGenerator.prototype._validateMapping =
  42355. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  42356. aName) {
  42357. // When aOriginal is truthy but has empty values for .line and .column,
  42358. // it is most likely a programmer error. In this case we throw a very
  42359. // specific error message to try to guide them the right way.
  42360. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  42361. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  42362. throw new Error(
  42363. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  42364. 'the original mapping entirely and only map the generated position. If so, pass ' +
  42365. 'null for the original mapping instead of an object with empty or null values.'
  42366. );
  42367. }
  42368. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  42369. && aGenerated.line > 0 && aGenerated.column >= 0
  42370. && !aOriginal && !aSource && !aName) {
  42371. // Case 1.
  42372. return;
  42373. }
  42374. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  42375. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  42376. && aGenerated.line > 0 && aGenerated.column >= 0
  42377. && aOriginal.line > 0 && aOriginal.column >= 0
  42378. && aSource) {
  42379. // Cases 2 and 3.
  42380. return;
  42381. }
  42382. else {
  42383. throw new Error('Invalid mapping: ' + JSON.stringify({
  42384. generated: aGenerated,
  42385. source: aSource,
  42386. original: aOriginal,
  42387. name: aName
  42388. }));
  42389. }
  42390. };
  42391. /**
  42392. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  42393. * specified by the source map format.
  42394. */
  42395. SourceMapGenerator.prototype._serializeMappings =
  42396. function SourceMapGenerator_serializeMappings() {
  42397. var previousGeneratedColumn = 0;
  42398. var previousGeneratedLine = 1;
  42399. var previousOriginalColumn = 0;
  42400. var previousOriginalLine = 0;
  42401. var previousName = 0;
  42402. var previousSource = 0;
  42403. var result = '';
  42404. var next;
  42405. var mapping;
  42406. var nameIdx;
  42407. var sourceIdx;
  42408. var mappings = this._mappings.toArray();
  42409. for (var i = 0, len = mappings.length; i < len; i++) {
  42410. mapping = mappings[i];
  42411. next = '';
  42412. if (mapping.generatedLine !== previousGeneratedLine) {
  42413. previousGeneratedColumn = 0;
  42414. while (mapping.generatedLine !== previousGeneratedLine) {
  42415. next += ';';
  42416. previousGeneratedLine++;
  42417. }
  42418. }
  42419. else {
  42420. if (i > 0) {
  42421. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  42422. continue;
  42423. }
  42424. next += ',';
  42425. }
  42426. }
  42427. next += base64VLQ.encode(mapping.generatedColumn
  42428. - previousGeneratedColumn);
  42429. previousGeneratedColumn = mapping.generatedColumn;
  42430. if (mapping.source != null) {
  42431. sourceIdx = this._sources.indexOf(mapping.source);
  42432. next += base64VLQ.encode(sourceIdx - previousSource);
  42433. previousSource = sourceIdx;
  42434. // lines are stored 0-based in SourceMap spec version 3
  42435. next += base64VLQ.encode(mapping.originalLine - 1
  42436. - previousOriginalLine);
  42437. previousOriginalLine = mapping.originalLine - 1;
  42438. next += base64VLQ.encode(mapping.originalColumn
  42439. - previousOriginalColumn);
  42440. previousOriginalColumn = mapping.originalColumn;
  42441. if (mapping.name != null) {
  42442. nameIdx = this._names.indexOf(mapping.name);
  42443. next += base64VLQ.encode(nameIdx - previousName);
  42444. previousName = nameIdx;
  42445. }
  42446. }
  42447. result += next;
  42448. }
  42449. return result;
  42450. };
  42451. SourceMapGenerator.prototype._generateSourcesContent =
  42452. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  42453. return aSources.map(function (source) {
  42454. if (!this._sourcesContents) {
  42455. return null;
  42456. }
  42457. if (aSourceRoot != null) {
  42458. source = util.relative(aSourceRoot, source);
  42459. }
  42460. var key = util.toSetString(source);
  42461. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  42462. ? this._sourcesContents[key]
  42463. : null;
  42464. }, this);
  42465. };
  42466. /**
  42467. * Externalize the source map.
  42468. */
  42469. SourceMapGenerator.prototype.toJSON =
  42470. function SourceMapGenerator_toJSON() {
  42471. var map = {
  42472. version: this._version,
  42473. sources: this._sources.toArray(),
  42474. names: this._names.toArray(),
  42475. mappings: this._serializeMappings()
  42476. };
  42477. if (this._file != null) {
  42478. map.file = this._file;
  42479. }
  42480. if (this._sourceRoot != null) {
  42481. map.sourceRoot = this._sourceRoot;
  42482. }
  42483. if (this._sourcesContents) {
  42484. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  42485. }
  42486. return map;
  42487. };
  42488. /**
  42489. * Render the source map being generated to a string.
  42490. */
  42491. SourceMapGenerator.prototype.toString =
  42492. function SourceMapGenerator_toString() {
  42493. return JSON.stringify(this.toJSON());
  42494. };
  42495. sourceMapGenerator.SourceMapGenerator = SourceMapGenerator;
  42496. return sourceMapGenerator;
  42497. }
  42498. var sourceMapConsumer = {};
  42499. var binarySearch = {};
  42500. /* -*- Mode: js; js-indent-level: 2; -*- */
  42501. var hasRequiredBinarySearch;
  42502. function requireBinarySearch () {
  42503. if (hasRequiredBinarySearch) return binarySearch;
  42504. hasRequiredBinarySearch = 1;
  42505. (function (exports) {
  42506. /*
  42507. * Copyright 2011 Mozilla Foundation and contributors
  42508. * Licensed under the New BSD license. See LICENSE or:
  42509. * http://opensource.org/licenses/BSD-3-Clause
  42510. */
  42511. exports.GREATEST_LOWER_BOUND = 1;
  42512. exports.LEAST_UPPER_BOUND = 2;
  42513. /**
  42514. * Recursive implementation of binary search.
  42515. *
  42516. * @param aLow Indices here and lower do not contain the needle.
  42517. * @param aHigh Indices here and higher do not contain the needle.
  42518. * @param aNeedle The element being searched for.
  42519. * @param aHaystack The non-empty array being searched.
  42520. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  42521. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  42522. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  42523. * closest element that is smaller than or greater than the one we are
  42524. * searching for, respectively, if the exact element cannot be found.
  42525. */
  42526. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  42527. // This function terminates when one of the following is true:
  42528. //
  42529. // 1. We find the exact element we are looking for.
  42530. //
  42531. // 2. We did not find the exact element, but we can return the index of
  42532. // the next-closest element.
  42533. //
  42534. // 3. We did not find the exact element, and there is no next-closest
  42535. // element than the one we are searching for, so we return -1.
  42536. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  42537. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  42538. if (cmp === 0) {
  42539. // Found the element we are looking for.
  42540. return mid;
  42541. }
  42542. else if (cmp > 0) {
  42543. // Our needle is greater than aHaystack[mid].
  42544. if (aHigh - mid > 1) {
  42545. // The element is in the upper half.
  42546. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  42547. }
  42548. // The exact needle element was not found in this haystack. Determine if
  42549. // we are in termination case (3) or (2) and return the appropriate thing.
  42550. if (aBias == exports.LEAST_UPPER_BOUND) {
  42551. return aHigh < aHaystack.length ? aHigh : -1;
  42552. } else {
  42553. return mid;
  42554. }
  42555. }
  42556. else {
  42557. // Our needle is less than aHaystack[mid].
  42558. if (mid - aLow > 1) {
  42559. // The element is in the lower half.
  42560. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  42561. }
  42562. // we are in termination case (3) or (2) and return the appropriate thing.
  42563. if (aBias == exports.LEAST_UPPER_BOUND) {
  42564. return mid;
  42565. } else {
  42566. return aLow < 0 ? -1 : aLow;
  42567. }
  42568. }
  42569. }
  42570. /**
  42571. * This is an implementation of binary search which will always try and return
  42572. * the index of the closest element if there is no exact hit. This is because
  42573. * mappings between original and generated line/col pairs are single points,
  42574. * and there is an implicit region between each of them, so a miss just means
  42575. * that you aren't on the very start of a region.
  42576. *
  42577. * @param aNeedle The element you are looking for.
  42578. * @param aHaystack The array that is being searched.
  42579. * @param aCompare A function which takes the needle and an element in the
  42580. * array and returns -1, 0, or 1 depending on whether the needle is less
  42581. * than, equal to, or greater than the element, respectively.
  42582. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  42583. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  42584. * closest element that is smaller than or greater than the one we are
  42585. * searching for, respectively, if the exact element cannot be found.
  42586. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  42587. */
  42588. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  42589. if (aHaystack.length === 0) {
  42590. return -1;
  42591. }
  42592. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  42593. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  42594. if (index < 0) {
  42595. return -1;
  42596. }
  42597. // We have found either the exact element, or the next-closest element than
  42598. // the one we are searching for. However, there may be more than one such
  42599. // element. Make sure we always return the smallest of these.
  42600. while (index - 1 >= 0) {
  42601. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  42602. break;
  42603. }
  42604. --index;
  42605. }
  42606. return index;
  42607. };
  42608. } (binarySearch));
  42609. return binarySearch;
  42610. }
  42611. var quickSort = {};
  42612. /* -*- Mode: js; js-indent-level: 2; -*- */
  42613. var hasRequiredQuickSort;
  42614. function requireQuickSort () {
  42615. if (hasRequiredQuickSort) return quickSort;
  42616. hasRequiredQuickSort = 1;
  42617. /*
  42618. * Copyright 2011 Mozilla Foundation and contributors
  42619. * Licensed under the New BSD license. See LICENSE or:
  42620. * http://opensource.org/licenses/BSD-3-Clause
  42621. */
  42622. // It turns out that some (most?) JavaScript engines don't self-host
  42623. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  42624. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  42625. // custom comparator function, calling back and forth between the VM's C++ and
  42626. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  42627. // worse generated code for the comparator function than would be optimal. In
  42628. // fact, when sorting with a comparator, these costs outweigh the benefits of
  42629. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  42630. // a ~3500ms mean speed-up in `bench/bench.html`.
  42631. /**
  42632. * Swap the elements indexed by `x` and `y` in the array `ary`.
  42633. *
  42634. * @param {Array} ary
  42635. * The array.
  42636. * @param {Number} x
  42637. * The index of the first item.
  42638. * @param {Number} y
  42639. * The index of the second item.
  42640. */
  42641. function swap(ary, x, y) {
  42642. var temp = ary[x];
  42643. ary[x] = ary[y];
  42644. ary[y] = temp;
  42645. }
  42646. /**
  42647. * Returns a random integer within the range `low .. high` inclusive.
  42648. *
  42649. * @param {Number} low
  42650. * The lower bound on the range.
  42651. * @param {Number} high
  42652. * The upper bound on the range.
  42653. */
  42654. function randomIntInRange(low, high) {
  42655. return Math.round(low + (Math.random() * (high - low)));
  42656. }
  42657. /**
  42658. * The Quick Sort algorithm.
  42659. *
  42660. * @param {Array} ary
  42661. * An array to sort.
  42662. * @param {function} comparator
  42663. * Function to use to compare two items.
  42664. * @param {Number} p
  42665. * Start index of the array
  42666. * @param {Number} r
  42667. * End index of the array
  42668. */
  42669. function doQuickSort(ary, comparator, p, r) {
  42670. // If our lower bound is less than our upper bound, we (1) partition the
  42671. // array into two pieces and (2) recurse on each half. If it is not, this is
  42672. // the empty array and our base case.
  42673. if (p < r) {
  42674. // (1) Partitioning.
  42675. //
  42676. // The partitioning chooses a pivot between `p` and `r` and moves all
  42677. // elements that are less than or equal to the pivot to the before it, and
  42678. // all the elements that are greater than it after it. The effect is that
  42679. // once partition is done, the pivot is in the exact place it will be when
  42680. // the array is put in sorted order, and it will not need to be moved
  42681. // again. This runs in O(n) time.
  42682. // Always choose a random pivot so that an input array which is reverse
  42683. // sorted does not cause O(n^2) running time.
  42684. var pivotIndex = randomIntInRange(p, r);
  42685. var i = p - 1;
  42686. swap(ary, pivotIndex, r);
  42687. var pivot = ary[r];
  42688. // Immediately after `j` is incremented in this loop, the following hold
  42689. // true:
  42690. //
  42691. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  42692. //
  42693. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  42694. for (var j = p; j < r; j++) {
  42695. if (comparator(ary[j], pivot) <= 0) {
  42696. i += 1;
  42697. swap(ary, i, j);
  42698. }
  42699. }
  42700. swap(ary, i + 1, j);
  42701. var q = i + 1;
  42702. // (2) Recurse on each half.
  42703. doQuickSort(ary, comparator, p, q - 1);
  42704. doQuickSort(ary, comparator, q + 1, r);
  42705. }
  42706. }
  42707. /**
  42708. * Sort the given array in-place with the given comparator function.
  42709. *
  42710. * @param {Array} ary
  42711. * An array to sort.
  42712. * @param {function} comparator
  42713. * Function to use to compare two items.
  42714. */
  42715. quickSort.quickSort = function (ary, comparator) {
  42716. doQuickSort(ary, comparator, 0, ary.length - 1);
  42717. };
  42718. return quickSort;
  42719. }
  42720. /* -*- Mode: js; js-indent-level: 2; -*- */
  42721. var hasRequiredSourceMapConsumer;
  42722. function requireSourceMapConsumer () {
  42723. if (hasRequiredSourceMapConsumer) return sourceMapConsumer;
  42724. hasRequiredSourceMapConsumer = 1;
  42725. /*
  42726. * Copyright 2011 Mozilla Foundation and contributors
  42727. * Licensed under the New BSD license. See LICENSE or:
  42728. * http://opensource.org/licenses/BSD-3-Clause
  42729. */
  42730. var util = /*@__PURE__*/ requireUtil();
  42731. var binarySearch = /*@__PURE__*/ requireBinarySearch();
  42732. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  42733. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  42734. var quickSort = /*@__PURE__*/ requireQuickSort().quickSort;
  42735. function SourceMapConsumer(aSourceMap, aSourceMapURL) {
  42736. var sourceMap = aSourceMap;
  42737. if (typeof aSourceMap === 'string') {
  42738. sourceMap = util.parseSourceMapInput(aSourceMap);
  42739. }
  42740. return sourceMap.sections != null
  42741. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  42742. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  42743. }
  42744. SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  42745. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  42746. };
  42747. /**
  42748. * The version of the source mapping spec that we are consuming.
  42749. */
  42750. SourceMapConsumer.prototype._version = 3;
  42751. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  42752. // parsed mapping coordinates from the source map's "mappings" attribute. They
  42753. // are lazily instantiated, accessed via the `_generatedMappings` and
  42754. // `_originalMappings` getters respectively, and we only parse the mappings
  42755. // and create these arrays once queried for a source location. We jump through
  42756. // these hoops because there can be many thousands of mappings, and parsing
  42757. // them is expensive, so we only want to do it if we must.
  42758. //
  42759. // Each object in the arrays is of the form:
  42760. //
  42761. // {
  42762. // generatedLine: The line number in the generated code,
  42763. // generatedColumn: The column number in the generated code,
  42764. // source: The path to the original source file that generated this
  42765. // chunk of code,
  42766. // originalLine: The line number in the original source that
  42767. // corresponds to this chunk of generated code,
  42768. // originalColumn: The column number in the original source that
  42769. // corresponds to this chunk of generated code,
  42770. // name: The name of the original symbol which generated this chunk of
  42771. // code.
  42772. // }
  42773. //
  42774. // All properties except for `generatedLine` and `generatedColumn` can be
  42775. // `null`.
  42776. //
  42777. // `_generatedMappings` is ordered by the generated positions.
  42778. //
  42779. // `_originalMappings` is ordered by the original positions.
  42780. SourceMapConsumer.prototype.__generatedMappings = null;
  42781. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  42782. configurable: true,
  42783. enumerable: true,
  42784. get: function () {
  42785. if (!this.__generatedMappings) {
  42786. this._parseMappings(this._mappings, this.sourceRoot);
  42787. }
  42788. return this.__generatedMappings;
  42789. }
  42790. });
  42791. SourceMapConsumer.prototype.__originalMappings = null;
  42792. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  42793. configurable: true,
  42794. enumerable: true,
  42795. get: function () {
  42796. if (!this.__originalMappings) {
  42797. this._parseMappings(this._mappings, this.sourceRoot);
  42798. }
  42799. return this.__originalMappings;
  42800. }
  42801. });
  42802. SourceMapConsumer.prototype._charIsMappingSeparator =
  42803. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  42804. var c = aStr.charAt(index);
  42805. return c === ";" || c === ",";
  42806. };
  42807. /**
  42808. * Parse the mappings in a string in to a data structure which we can easily
  42809. * query (the ordered arrays in the `this.__generatedMappings` and
  42810. * `this.__originalMappings` properties).
  42811. */
  42812. SourceMapConsumer.prototype._parseMappings =
  42813. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  42814. throw new Error("Subclasses must implement _parseMappings");
  42815. };
  42816. SourceMapConsumer.GENERATED_ORDER = 1;
  42817. SourceMapConsumer.ORIGINAL_ORDER = 2;
  42818. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  42819. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  42820. /**
  42821. * Iterate over each mapping between an original source/line/column and a
  42822. * generated line/column in this source map.
  42823. *
  42824. * @param Function aCallback
  42825. * The function that is called with each mapping.
  42826. * @param Object aContext
  42827. * Optional. If specified, this object will be the value of `this` every
  42828. * time that `aCallback` is called.
  42829. * @param aOrder
  42830. * Either `SourceMapConsumer.GENERATED_ORDER` or
  42831. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  42832. * iterate over the mappings sorted by the generated file's line/column
  42833. * order or the original's source/line/column order, respectively. Defaults to
  42834. * `SourceMapConsumer.GENERATED_ORDER`.
  42835. */
  42836. SourceMapConsumer.prototype.eachMapping =
  42837. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  42838. var context = aContext || null;
  42839. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  42840. var mappings;
  42841. switch (order) {
  42842. case SourceMapConsumer.GENERATED_ORDER:
  42843. mappings = this._generatedMappings;
  42844. break;
  42845. case SourceMapConsumer.ORIGINAL_ORDER:
  42846. mappings = this._originalMappings;
  42847. break;
  42848. default:
  42849. throw new Error("Unknown order of iteration.");
  42850. }
  42851. var sourceRoot = this.sourceRoot;
  42852. mappings.map(function (mapping) {
  42853. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  42854. source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  42855. return {
  42856. source: source,
  42857. generatedLine: mapping.generatedLine,
  42858. generatedColumn: mapping.generatedColumn,
  42859. originalLine: mapping.originalLine,
  42860. originalColumn: mapping.originalColumn,
  42861. name: mapping.name === null ? null : this._names.at(mapping.name)
  42862. };
  42863. }, this).forEach(aCallback, context);
  42864. };
  42865. /**
  42866. * Returns all generated line and column information for the original source,
  42867. * line, and column provided. If no column is provided, returns all mappings
  42868. * corresponding to a either the line we are searching for or the next
  42869. * closest line that has any mappings. Otherwise, returns all mappings
  42870. * corresponding to the given line and either the column we are searching for
  42871. * or the next closest column that has any offsets.
  42872. *
  42873. * The only argument is an object with the following properties:
  42874. *
  42875. * - source: The filename of the original source.
  42876. * - line: The line number in the original source. The line number is 1-based.
  42877. * - column: Optional. the column number in the original source.
  42878. * The column number is 0-based.
  42879. *
  42880. * and an array of objects is returned, each with the following properties:
  42881. *
  42882. * - line: The line number in the generated source, or null. The
  42883. * line number is 1-based.
  42884. * - column: The column number in the generated source, or null.
  42885. * The column number is 0-based.
  42886. */
  42887. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  42888. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  42889. var line = util.getArg(aArgs, 'line');
  42890. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  42891. // returns the index of the closest mapping less than the needle. By
  42892. // setting needle.originalColumn to 0, we thus find the last mapping for
  42893. // the given line, provided such a mapping exists.
  42894. var needle = {
  42895. source: util.getArg(aArgs, 'source'),
  42896. originalLine: line,
  42897. originalColumn: util.getArg(aArgs, 'column', 0)
  42898. };
  42899. needle.source = this._findSourceIndex(needle.source);
  42900. if (needle.source < 0) {
  42901. return [];
  42902. }
  42903. var mappings = [];
  42904. var index = this._findMapping(needle,
  42905. this._originalMappings,
  42906. "originalLine",
  42907. "originalColumn",
  42908. util.compareByOriginalPositions,
  42909. binarySearch.LEAST_UPPER_BOUND);
  42910. if (index >= 0) {
  42911. var mapping = this._originalMappings[index];
  42912. if (aArgs.column === undefined) {
  42913. var originalLine = mapping.originalLine;
  42914. // Iterate until either we run out of mappings, or we run into
  42915. // a mapping for a different line than the one we found. Since
  42916. // mappings are sorted, this is guaranteed to find all mappings for
  42917. // the line we found.
  42918. while (mapping && mapping.originalLine === originalLine) {
  42919. mappings.push({
  42920. line: util.getArg(mapping, 'generatedLine', null),
  42921. column: util.getArg(mapping, 'generatedColumn', null),
  42922. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  42923. });
  42924. mapping = this._originalMappings[++index];
  42925. }
  42926. } else {
  42927. var originalColumn = mapping.originalColumn;
  42928. // Iterate until either we run out of mappings, or we run into
  42929. // a mapping for a different line than the one we were searching for.
  42930. // Since mappings are sorted, this is guaranteed to find all mappings for
  42931. // the line we are searching for.
  42932. while (mapping &&
  42933. mapping.originalLine === line &&
  42934. mapping.originalColumn == originalColumn) {
  42935. mappings.push({
  42936. line: util.getArg(mapping, 'generatedLine', null),
  42937. column: util.getArg(mapping, 'generatedColumn', null),
  42938. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  42939. });
  42940. mapping = this._originalMappings[++index];
  42941. }
  42942. }
  42943. }
  42944. return mappings;
  42945. };
  42946. sourceMapConsumer.SourceMapConsumer = SourceMapConsumer;
  42947. /**
  42948. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  42949. * query for information about the original file positions by giving it a file
  42950. * position in the generated source.
  42951. *
  42952. * The first parameter is the raw source map (either as a JSON string, or
  42953. * already parsed to an object). According to the spec, source maps have the
  42954. * following attributes:
  42955. *
  42956. * - version: Which version of the source map spec this map is following.
  42957. * - sources: An array of URLs to the original source files.
  42958. * - names: An array of identifiers which can be referrenced by individual mappings.
  42959. * - sourceRoot: Optional. The URL root from which all sources are relative.
  42960. * - sourcesContent: Optional. An array of contents of the original source files.
  42961. * - mappings: A string of base64 VLQs which contain the actual mappings.
  42962. * - file: Optional. The generated file this source map is associated with.
  42963. *
  42964. * Here is an example source map, taken from the source map spec[0]:
  42965. *
  42966. * {
  42967. * version : 3,
  42968. * file: "out.js",
  42969. * sourceRoot : "",
  42970. * sources: ["foo.js", "bar.js"],
  42971. * names: ["src", "maps", "are", "fun"],
  42972. * mappings: "AA,AB;;ABCDE;"
  42973. * }
  42974. *
  42975. * The second parameter, if given, is a string whose value is the URL
  42976. * at which the source map was found. This URL is used to compute the
  42977. * sources array.
  42978. *
  42979. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  42980. */
  42981. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  42982. var sourceMap = aSourceMap;
  42983. if (typeof aSourceMap === 'string') {
  42984. sourceMap = util.parseSourceMapInput(aSourceMap);
  42985. }
  42986. var version = util.getArg(sourceMap, 'version');
  42987. var sources = util.getArg(sourceMap, 'sources');
  42988. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  42989. // requires the array) to play nice here.
  42990. var names = util.getArg(sourceMap, 'names', []);
  42991. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  42992. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  42993. var mappings = util.getArg(sourceMap, 'mappings');
  42994. var file = util.getArg(sourceMap, 'file', null);
  42995. // Once again, Sass deviates from the spec and supplies the version as a
  42996. // string rather than a number, so we use loose equality checking here.
  42997. if (version != this._version) {
  42998. throw new Error('Unsupported version: ' + version);
  42999. }
  43000. if (sourceRoot) {
  43001. sourceRoot = util.normalize(sourceRoot);
  43002. }
  43003. sources = sources
  43004. .map(String)
  43005. // Some source maps produce relative source paths like "./foo.js" instead of
  43006. // "foo.js". Normalize these first so that future comparisons will succeed.
  43007. // See bugzil.la/1090768.
  43008. .map(util.normalize)
  43009. // Always ensure that absolute sources are internally stored relative to
  43010. // the source root, if the source root is absolute. Not doing this would
  43011. // be particularly problematic when the source root is a prefix of the
  43012. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  43013. .map(function (source) {
  43014. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  43015. ? util.relative(sourceRoot, source)
  43016. : source;
  43017. });
  43018. // Pass `true` below to allow duplicate names and sources. While source maps
  43019. // are intended to be compressed and deduplicated, the TypeScript compiler
  43020. // sometimes generates source maps with duplicates in them. See Github issue
  43021. // #72 and bugzil.la/889492.
  43022. this._names = ArraySet.fromArray(names.map(String), true);
  43023. this._sources = ArraySet.fromArray(sources, true);
  43024. this._absoluteSources = this._sources.toArray().map(function (s) {
  43025. return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
  43026. });
  43027. this.sourceRoot = sourceRoot;
  43028. this.sourcesContent = sourcesContent;
  43029. this._mappings = mappings;
  43030. this._sourceMapURL = aSourceMapURL;
  43031. this.file = file;
  43032. }
  43033. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  43034. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  43035. /**
  43036. * Utility function to find the index of a source. Returns -1 if not
  43037. * found.
  43038. */
  43039. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  43040. var relativeSource = aSource;
  43041. if (this.sourceRoot != null) {
  43042. relativeSource = util.relative(this.sourceRoot, relativeSource);
  43043. }
  43044. if (this._sources.has(relativeSource)) {
  43045. return this._sources.indexOf(relativeSource);
  43046. }
  43047. // Maybe aSource is an absolute URL as returned by |sources|. In
  43048. // this case we can't simply undo the transform.
  43049. var i;
  43050. for (i = 0; i < this._absoluteSources.length; ++i) {
  43051. if (this._absoluteSources[i] == aSource) {
  43052. return i;
  43053. }
  43054. }
  43055. return -1;
  43056. };
  43057. /**
  43058. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  43059. *
  43060. * @param SourceMapGenerator aSourceMap
  43061. * The source map that will be consumed.
  43062. * @param String aSourceMapURL
  43063. * The URL at which the source map can be found (optional)
  43064. * @returns BasicSourceMapConsumer
  43065. */
  43066. BasicSourceMapConsumer.fromSourceMap =
  43067. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  43068. var smc = Object.create(BasicSourceMapConsumer.prototype);
  43069. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  43070. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  43071. smc.sourceRoot = aSourceMap._sourceRoot;
  43072. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  43073. smc.sourceRoot);
  43074. smc.file = aSourceMap._file;
  43075. smc._sourceMapURL = aSourceMapURL;
  43076. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  43077. return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  43078. });
  43079. // Because we are modifying the entries (by converting string sources and
  43080. // names to indices into the sources and names ArraySets), we have to make
  43081. // a copy of the entry or else bad things happen. Shared mutable state
  43082. // strikes again! See github issue #191.
  43083. var generatedMappings = aSourceMap._mappings.toArray().slice();
  43084. var destGeneratedMappings = smc.__generatedMappings = [];
  43085. var destOriginalMappings = smc.__originalMappings = [];
  43086. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  43087. var srcMapping = generatedMappings[i];
  43088. var destMapping = new Mapping;
  43089. destMapping.generatedLine = srcMapping.generatedLine;
  43090. destMapping.generatedColumn = srcMapping.generatedColumn;
  43091. if (srcMapping.source) {
  43092. destMapping.source = sources.indexOf(srcMapping.source);
  43093. destMapping.originalLine = srcMapping.originalLine;
  43094. destMapping.originalColumn = srcMapping.originalColumn;
  43095. if (srcMapping.name) {
  43096. destMapping.name = names.indexOf(srcMapping.name);
  43097. }
  43098. destOriginalMappings.push(destMapping);
  43099. }
  43100. destGeneratedMappings.push(destMapping);
  43101. }
  43102. quickSort(smc.__originalMappings, util.compareByOriginalPositions);
  43103. return smc;
  43104. };
  43105. /**
  43106. * The version of the source mapping spec that we are consuming.
  43107. */
  43108. BasicSourceMapConsumer.prototype._version = 3;
  43109. /**
  43110. * The list of original sources.
  43111. */
  43112. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  43113. get: function () {
  43114. return this._absoluteSources.slice();
  43115. }
  43116. });
  43117. /**
  43118. * Provide the JIT with a nice shape / hidden class.
  43119. */
  43120. function Mapping() {
  43121. this.generatedLine = 0;
  43122. this.generatedColumn = 0;
  43123. this.source = null;
  43124. this.originalLine = null;
  43125. this.originalColumn = null;
  43126. this.name = null;
  43127. }
  43128. /**
  43129. * Parse the mappings in a string in to a data structure which we can easily
  43130. * query (the ordered arrays in the `this.__generatedMappings` and
  43131. * `this.__originalMappings` properties).
  43132. */
  43133. BasicSourceMapConsumer.prototype._parseMappings =
  43134. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  43135. var generatedLine = 1;
  43136. var previousGeneratedColumn = 0;
  43137. var previousOriginalLine = 0;
  43138. var previousOriginalColumn = 0;
  43139. var previousSource = 0;
  43140. var previousName = 0;
  43141. var length = aStr.length;
  43142. var index = 0;
  43143. var cachedSegments = {};
  43144. var temp = {};
  43145. var originalMappings = [];
  43146. var generatedMappings = [];
  43147. var mapping, str, segment, end, value;
  43148. while (index < length) {
  43149. if (aStr.charAt(index) === ';') {
  43150. generatedLine++;
  43151. index++;
  43152. previousGeneratedColumn = 0;
  43153. }
  43154. else if (aStr.charAt(index) === ',') {
  43155. index++;
  43156. }
  43157. else {
  43158. mapping = new Mapping();
  43159. mapping.generatedLine = generatedLine;
  43160. // Because each offset is encoded relative to the previous one,
  43161. // many segments often have the same encoding. We can exploit this
  43162. // fact by caching the parsed variable length fields of each segment,
  43163. // allowing us to avoid a second parse if we encounter the same
  43164. // segment again.
  43165. for (end = index; end < length; end++) {
  43166. if (this._charIsMappingSeparator(aStr, end)) {
  43167. break;
  43168. }
  43169. }
  43170. str = aStr.slice(index, end);
  43171. segment = cachedSegments[str];
  43172. if (segment) {
  43173. index += str.length;
  43174. } else {
  43175. segment = [];
  43176. while (index < end) {
  43177. base64VLQ.decode(aStr, index, temp);
  43178. value = temp.value;
  43179. index = temp.rest;
  43180. segment.push(value);
  43181. }
  43182. if (segment.length === 2) {
  43183. throw new Error('Found a source, but no line and column');
  43184. }
  43185. if (segment.length === 3) {
  43186. throw new Error('Found a source and line, but no column');
  43187. }
  43188. cachedSegments[str] = segment;
  43189. }
  43190. // Generated column.
  43191. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  43192. previousGeneratedColumn = mapping.generatedColumn;
  43193. if (segment.length > 1) {
  43194. // Original source.
  43195. mapping.source = previousSource + segment[1];
  43196. previousSource += segment[1];
  43197. // Original line.
  43198. mapping.originalLine = previousOriginalLine + segment[2];
  43199. previousOriginalLine = mapping.originalLine;
  43200. // Lines are stored 0-based
  43201. mapping.originalLine += 1;
  43202. // Original column.
  43203. mapping.originalColumn = previousOriginalColumn + segment[3];
  43204. previousOriginalColumn = mapping.originalColumn;
  43205. if (segment.length > 4) {
  43206. // Original name.
  43207. mapping.name = previousName + segment[4];
  43208. previousName += segment[4];
  43209. }
  43210. }
  43211. generatedMappings.push(mapping);
  43212. if (typeof mapping.originalLine === 'number') {
  43213. originalMappings.push(mapping);
  43214. }
  43215. }
  43216. }
  43217. quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
  43218. this.__generatedMappings = generatedMappings;
  43219. quickSort(originalMappings, util.compareByOriginalPositions);
  43220. this.__originalMappings = originalMappings;
  43221. };
  43222. /**
  43223. * Find the mapping that best matches the hypothetical "needle" mapping that
  43224. * we are searching for in the given "haystack" of mappings.
  43225. */
  43226. BasicSourceMapConsumer.prototype._findMapping =
  43227. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  43228. aColumnName, aComparator, aBias) {
  43229. // To return the position we are searching for, we must first find the
  43230. // mapping for the given position and then return the opposite position it
  43231. // points to. Because the mappings are sorted, we can use binary search to
  43232. // find the best mapping.
  43233. if (aNeedle[aLineName] <= 0) {
  43234. throw new TypeError('Line must be greater than or equal to 1, got '
  43235. + aNeedle[aLineName]);
  43236. }
  43237. if (aNeedle[aColumnName] < 0) {
  43238. throw new TypeError('Column must be greater than or equal to 0, got '
  43239. + aNeedle[aColumnName]);
  43240. }
  43241. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  43242. };
  43243. /**
  43244. * Compute the last column for each generated mapping. The last column is
  43245. * inclusive.
  43246. */
  43247. BasicSourceMapConsumer.prototype.computeColumnSpans =
  43248. function SourceMapConsumer_computeColumnSpans() {
  43249. for (var index = 0; index < this._generatedMappings.length; ++index) {
  43250. var mapping = this._generatedMappings[index];
  43251. // Mappings do not contain a field for the last generated columnt. We
  43252. // can come up with an optimistic estimate, however, by assuming that
  43253. // mappings are contiguous (i.e. given two consecutive mappings, the
  43254. // first mapping ends where the second one starts).
  43255. if (index + 1 < this._generatedMappings.length) {
  43256. var nextMapping = this._generatedMappings[index + 1];
  43257. if (mapping.generatedLine === nextMapping.generatedLine) {
  43258. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  43259. continue;
  43260. }
  43261. }
  43262. // The last mapping for each line spans the entire line.
  43263. mapping.lastGeneratedColumn = Infinity;
  43264. }
  43265. };
  43266. /**
  43267. * Returns the original source, line, and column information for the generated
  43268. * source's line and column positions provided. The only argument is an object
  43269. * with the following properties:
  43270. *
  43271. * - line: The line number in the generated source. The line number
  43272. * is 1-based.
  43273. * - column: The column number in the generated source. The column
  43274. * number is 0-based.
  43275. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  43276. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  43277. * closest element that is smaller than or greater than the one we are
  43278. * searching for, respectively, if the exact element cannot be found.
  43279. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  43280. *
  43281. * and an object is returned with the following properties:
  43282. *
  43283. * - source: The original source file, or null.
  43284. * - line: The line number in the original source, or null. The
  43285. * line number is 1-based.
  43286. * - column: The column number in the original source, or null. The
  43287. * column number is 0-based.
  43288. * - name: The original identifier, or null.
  43289. */
  43290. BasicSourceMapConsumer.prototype.originalPositionFor =
  43291. function SourceMapConsumer_originalPositionFor(aArgs) {
  43292. var needle = {
  43293. generatedLine: util.getArg(aArgs, 'line'),
  43294. generatedColumn: util.getArg(aArgs, 'column')
  43295. };
  43296. var index = this._findMapping(
  43297. needle,
  43298. this._generatedMappings,
  43299. "generatedLine",
  43300. "generatedColumn",
  43301. util.compareByGeneratedPositionsDeflated,
  43302. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  43303. );
  43304. if (index >= 0) {
  43305. var mapping = this._generatedMappings[index];
  43306. if (mapping.generatedLine === needle.generatedLine) {
  43307. var source = util.getArg(mapping, 'source', null);
  43308. if (source !== null) {
  43309. source = this._sources.at(source);
  43310. source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  43311. }
  43312. var name = util.getArg(mapping, 'name', null);
  43313. if (name !== null) {
  43314. name = this._names.at(name);
  43315. }
  43316. return {
  43317. source: source,
  43318. line: util.getArg(mapping, 'originalLine', null),
  43319. column: util.getArg(mapping, 'originalColumn', null),
  43320. name: name
  43321. };
  43322. }
  43323. }
  43324. return {
  43325. source: null,
  43326. line: null,
  43327. column: null,
  43328. name: null
  43329. };
  43330. };
  43331. /**
  43332. * Return true if we have the source content for every source in the source
  43333. * map, false otherwise.
  43334. */
  43335. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  43336. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  43337. if (!this.sourcesContent) {
  43338. return false;
  43339. }
  43340. return this.sourcesContent.length >= this._sources.size() &&
  43341. !this.sourcesContent.some(function (sc) { return sc == null; });
  43342. };
  43343. /**
  43344. * Returns the original source content. The only argument is the url of the
  43345. * original source file. Returns null if no original source content is
  43346. * available.
  43347. */
  43348. BasicSourceMapConsumer.prototype.sourceContentFor =
  43349. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  43350. if (!this.sourcesContent) {
  43351. return null;
  43352. }
  43353. var index = this._findSourceIndex(aSource);
  43354. if (index >= 0) {
  43355. return this.sourcesContent[index];
  43356. }
  43357. var relativeSource = aSource;
  43358. if (this.sourceRoot != null) {
  43359. relativeSource = util.relative(this.sourceRoot, relativeSource);
  43360. }
  43361. var url;
  43362. if (this.sourceRoot != null
  43363. && (url = util.urlParse(this.sourceRoot))) {
  43364. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  43365. // many users. We can help them out when they expect file:// URIs to
  43366. // behave like it would if they were running a local HTTP server. See
  43367. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  43368. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  43369. if (url.scheme == "file"
  43370. && this._sources.has(fileUriAbsPath)) {
  43371. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  43372. }
  43373. if ((!url.path || url.path == "/")
  43374. && this._sources.has("/" + relativeSource)) {
  43375. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  43376. }
  43377. }
  43378. // This function is used recursively from
  43379. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  43380. // don't want to throw if we can't find the source - we just want to
  43381. // return null, so we provide a flag to exit gracefully.
  43382. if (nullOnMissing) {
  43383. return null;
  43384. }
  43385. else {
  43386. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  43387. }
  43388. };
  43389. /**
  43390. * Returns the generated line and column information for the original source,
  43391. * line, and column positions provided. The only argument is an object with
  43392. * the following properties:
  43393. *
  43394. * - source: The filename of the original source.
  43395. * - line: The line number in the original source. The line number
  43396. * is 1-based.
  43397. * - column: The column number in the original source. The column
  43398. * number is 0-based.
  43399. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  43400. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  43401. * closest element that is smaller than or greater than the one we are
  43402. * searching for, respectively, if the exact element cannot be found.
  43403. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  43404. *
  43405. * and an object is returned with the following properties:
  43406. *
  43407. * - line: The line number in the generated source, or null. The
  43408. * line number is 1-based.
  43409. * - column: The column number in the generated source, or null.
  43410. * The column number is 0-based.
  43411. */
  43412. BasicSourceMapConsumer.prototype.generatedPositionFor =
  43413. function SourceMapConsumer_generatedPositionFor(aArgs) {
  43414. var source = util.getArg(aArgs, 'source');
  43415. source = this._findSourceIndex(source);
  43416. if (source < 0) {
  43417. return {
  43418. line: null,
  43419. column: null,
  43420. lastColumn: null
  43421. };
  43422. }
  43423. var needle = {
  43424. source: source,
  43425. originalLine: util.getArg(aArgs, 'line'),
  43426. originalColumn: util.getArg(aArgs, 'column')
  43427. };
  43428. var index = this._findMapping(
  43429. needle,
  43430. this._originalMappings,
  43431. "originalLine",
  43432. "originalColumn",
  43433. util.compareByOriginalPositions,
  43434. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  43435. );
  43436. if (index >= 0) {
  43437. var mapping = this._originalMappings[index];
  43438. if (mapping.source === needle.source) {
  43439. return {
  43440. line: util.getArg(mapping, 'generatedLine', null),
  43441. column: util.getArg(mapping, 'generatedColumn', null),
  43442. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  43443. };
  43444. }
  43445. }
  43446. return {
  43447. line: null,
  43448. column: null,
  43449. lastColumn: null
  43450. };
  43451. };
  43452. sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer;
  43453. /**
  43454. * An IndexedSourceMapConsumer instance represents a parsed source map which
  43455. * we can query for information. It differs from BasicSourceMapConsumer in
  43456. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  43457. * input.
  43458. *
  43459. * The first parameter is a raw source map (either as a JSON string, or already
  43460. * parsed to an object). According to the spec for indexed source maps, they
  43461. * have the following attributes:
  43462. *
  43463. * - version: Which version of the source map spec this map is following.
  43464. * - file: Optional. The generated file this source map is associated with.
  43465. * - sections: A list of section definitions.
  43466. *
  43467. * Each value under the "sections" field has two fields:
  43468. * - offset: The offset into the original specified at which this section
  43469. * begins to apply, defined as an object with a "line" and "column"
  43470. * field.
  43471. * - map: A source map definition. This source map could also be indexed,
  43472. * but doesn't have to be.
  43473. *
  43474. * Instead of the "map" field, it's also possible to have a "url" field
  43475. * specifying a URL to retrieve a source map from, but that's currently
  43476. * unsupported.
  43477. *
  43478. * Here's an example source map, taken from the source map spec[0], but
  43479. * modified to omit a section which uses the "url" field.
  43480. *
  43481. * {
  43482. * version : 3,
  43483. * file: "app.js",
  43484. * sections: [{
  43485. * offset: {line:100, column:10},
  43486. * map: {
  43487. * version : 3,
  43488. * file: "section.js",
  43489. * sources: ["foo.js", "bar.js"],
  43490. * names: ["src", "maps", "are", "fun"],
  43491. * mappings: "AAAA,E;;ABCDE;"
  43492. * }
  43493. * }],
  43494. * }
  43495. *
  43496. * The second parameter, if given, is a string whose value is the URL
  43497. * at which the source map was found. This URL is used to compute the
  43498. * sources array.
  43499. *
  43500. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  43501. */
  43502. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  43503. var sourceMap = aSourceMap;
  43504. if (typeof aSourceMap === 'string') {
  43505. sourceMap = util.parseSourceMapInput(aSourceMap);
  43506. }
  43507. var version = util.getArg(sourceMap, 'version');
  43508. var sections = util.getArg(sourceMap, 'sections');
  43509. if (version != this._version) {
  43510. throw new Error('Unsupported version: ' + version);
  43511. }
  43512. this._sources = new ArraySet();
  43513. this._names = new ArraySet();
  43514. var lastOffset = {
  43515. line: -1,
  43516. column: 0
  43517. };
  43518. this._sections = sections.map(function (s) {
  43519. if (s.url) {
  43520. // The url field will require support for asynchronicity.
  43521. // See https://github.com/mozilla/source-map/issues/16
  43522. throw new Error('Support for url field in sections not implemented.');
  43523. }
  43524. var offset = util.getArg(s, 'offset');
  43525. var offsetLine = util.getArg(offset, 'line');
  43526. var offsetColumn = util.getArg(offset, 'column');
  43527. if (offsetLine < lastOffset.line ||
  43528. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  43529. throw new Error('Section offsets must be ordered and non-overlapping.');
  43530. }
  43531. lastOffset = offset;
  43532. return {
  43533. generatedOffset: {
  43534. // The offset fields are 0-based, but we use 1-based indices when
  43535. // encoding/decoding from VLQ.
  43536. generatedLine: offsetLine + 1,
  43537. generatedColumn: offsetColumn + 1
  43538. },
  43539. consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
  43540. }
  43541. });
  43542. }
  43543. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  43544. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  43545. /**
  43546. * The version of the source mapping spec that we are consuming.
  43547. */
  43548. IndexedSourceMapConsumer.prototype._version = 3;
  43549. /**
  43550. * The list of original sources.
  43551. */
  43552. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  43553. get: function () {
  43554. var sources = [];
  43555. for (var i = 0; i < this._sections.length; i++) {
  43556. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  43557. sources.push(this._sections[i].consumer.sources[j]);
  43558. }
  43559. }
  43560. return sources;
  43561. }
  43562. });
  43563. /**
  43564. * Returns the original source, line, and column information for the generated
  43565. * source's line and column positions provided. The only argument is an object
  43566. * with the following properties:
  43567. *
  43568. * - line: The line number in the generated source. The line number
  43569. * is 1-based.
  43570. * - column: The column number in the generated source. The column
  43571. * number is 0-based.
  43572. *
  43573. * and an object is returned with the following properties:
  43574. *
  43575. * - source: The original source file, or null.
  43576. * - line: The line number in the original source, or null. The
  43577. * line number is 1-based.
  43578. * - column: The column number in the original source, or null. The
  43579. * column number is 0-based.
  43580. * - name: The original identifier, or null.
  43581. */
  43582. IndexedSourceMapConsumer.prototype.originalPositionFor =
  43583. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  43584. var needle = {
  43585. generatedLine: util.getArg(aArgs, 'line'),
  43586. generatedColumn: util.getArg(aArgs, 'column')
  43587. };
  43588. // Find the section containing the generated position we're trying to map
  43589. // to an original position.
  43590. var sectionIndex = binarySearch.search(needle, this._sections,
  43591. function(needle, section) {
  43592. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  43593. if (cmp) {
  43594. return cmp;
  43595. }
  43596. return (needle.generatedColumn -
  43597. section.generatedOffset.generatedColumn);
  43598. });
  43599. var section = this._sections[sectionIndex];
  43600. if (!section) {
  43601. return {
  43602. source: null,
  43603. line: null,
  43604. column: null,
  43605. name: null
  43606. };
  43607. }
  43608. return section.consumer.originalPositionFor({
  43609. line: needle.generatedLine -
  43610. (section.generatedOffset.generatedLine - 1),
  43611. column: needle.generatedColumn -
  43612. (section.generatedOffset.generatedLine === needle.generatedLine
  43613. ? section.generatedOffset.generatedColumn - 1
  43614. : 0),
  43615. bias: aArgs.bias
  43616. });
  43617. };
  43618. /**
  43619. * Return true if we have the source content for every source in the source
  43620. * map, false otherwise.
  43621. */
  43622. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  43623. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  43624. return this._sections.every(function (s) {
  43625. return s.consumer.hasContentsOfAllSources();
  43626. });
  43627. };
  43628. /**
  43629. * Returns the original source content. The only argument is the url of the
  43630. * original source file. Returns null if no original source content is
  43631. * available.
  43632. */
  43633. IndexedSourceMapConsumer.prototype.sourceContentFor =
  43634. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  43635. for (var i = 0; i < this._sections.length; i++) {
  43636. var section = this._sections[i];
  43637. var content = section.consumer.sourceContentFor(aSource, true);
  43638. if (content) {
  43639. return content;
  43640. }
  43641. }
  43642. if (nullOnMissing) {
  43643. return null;
  43644. }
  43645. else {
  43646. throw new Error('"' + aSource + '" is not in the SourceMap.');
  43647. }
  43648. };
  43649. /**
  43650. * Returns the generated line and column information for the original source,
  43651. * line, and column positions provided. The only argument is an object with
  43652. * the following properties:
  43653. *
  43654. * - source: The filename of the original source.
  43655. * - line: The line number in the original source. The line number
  43656. * is 1-based.
  43657. * - column: The column number in the original source. The column
  43658. * number is 0-based.
  43659. *
  43660. * and an object is returned with the following properties:
  43661. *
  43662. * - line: The line number in the generated source, or null. The
  43663. * line number is 1-based.
  43664. * - column: The column number in the generated source, or null.
  43665. * The column number is 0-based.
  43666. */
  43667. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  43668. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  43669. for (var i = 0; i < this._sections.length; i++) {
  43670. var section = this._sections[i];
  43671. // Only consider this section if the requested source is in the list of
  43672. // sources of the consumer.
  43673. if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
  43674. continue;
  43675. }
  43676. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  43677. if (generatedPosition) {
  43678. var ret = {
  43679. line: generatedPosition.line +
  43680. (section.generatedOffset.generatedLine - 1),
  43681. column: generatedPosition.column +
  43682. (section.generatedOffset.generatedLine === generatedPosition.line
  43683. ? section.generatedOffset.generatedColumn - 1
  43684. : 0)
  43685. };
  43686. return ret;
  43687. }
  43688. }
  43689. return {
  43690. line: null,
  43691. column: null
  43692. };
  43693. };
  43694. /**
  43695. * Parse the mappings in a string in to a data structure which we can easily
  43696. * query (the ordered arrays in the `this.__generatedMappings` and
  43697. * `this.__originalMappings` properties).
  43698. */
  43699. IndexedSourceMapConsumer.prototype._parseMappings =
  43700. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  43701. this.__generatedMappings = [];
  43702. this.__originalMappings = [];
  43703. for (var i = 0; i < this._sections.length; i++) {
  43704. var section = this._sections[i];
  43705. var sectionMappings = section.consumer._generatedMappings;
  43706. for (var j = 0; j < sectionMappings.length; j++) {
  43707. var mapping = sectionMappings[j];
  43708. var source = section.consumer._sources.at(mapping.source);
  43709. source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  43710. this._sources.add(source);
  43711. source = this._sources.indexOf(source);
  43712. var name = null;
  43713. if (mapping.name) {
  43714. name = section.consumer._names.at(mapping.name);
  43715. this._names.add(name);
  43716. name = this._names.indexOf(name);
  43717. }
  43718. // The mappings coming from the consumer for the section have
  43719. // generated positions relative to the start of the section, so we
  43720. // need to offset them to be relative to the start of the concatenated
  43721. // generated file.
  43722. var adjustedMapping = {
  43723. source: source,
  43724. generatedLine: mapping.generatedLine +
  43725. (section.generatedOffset.generatedLine - 1),
  43726. generatedColumn: mapping.generatedColumn +
  43727. (section.generatedOffset.generatedLine === mapping.generatedLine
  43728. ? section.generatedOffset.generatedColumn - 1
  43729. : 0),
  43730. originalLine: mapping.originalLine,
  43731. originalColumn: mapping.originalColumn,
  43732. name: name
  43733. };
  43734. this.__generatedMappings.push(adjustedMapping);
  43735. if (typeof adjustedMapping.originalLine === 'number') {
  43736. this.__originalMappings.push(adjustedMapping);
  43737. }
  43738. }
  43739. }
  43740. quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  43741. quickSort(this.__originalMappings, util.compareByOriginalPositions);
  43742. };
  43743. sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  43744. return sourceMapConsumer;
  43745. }
  43746. var sourceNode = {};
  43747. /* -*- Mode: js; js-indent-level: 2; -*- */
  43748. var hasRequiredSourceNode;
  43749. function requireSourceNode () {
  43750. if (hasRequiredSourceNode) return sourceNode;
  43751. hasRequiredSourceNode = 1;
  43752. /*
  43753. * Copyright 2011 Mozilla Foundation and contributors
  43754. * Licensed under the New BSD license. See LICENSE or:
  43755. * http://opensource.org/licenses/BSD-3-Clause
  43756. */
  43757. var SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  43758. var util = /*@__PURE__*/ requireUtil();
  43759. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  43760. // operating systems these days (capturing the result).
  43761. var REGEX_NEWLINE = /(\r?\n)/;
  43762. // Newline character code for charCodeAt() comparisons
  43763. var NEWLINE_CODE = 10;
  43764. // Private symbol for identifying `SourceNode`s when multiple versions of
  43765. // the source-map library are loaded. This MUST NOT CHANGE across
  43766. // versions!
  43767. var isSourceNode = "$$$isSourceNode$$$";
  43768. /**
  43769. * SourceNodes provide a way to abstract over interpolating/concatenating
  43770. * snippets of generated JavaScript source code while maintaining the line and
  43771. * column information associated with the original source code.
  43772. *
  43773. * @param aLine The original line number.
  43774. * @param aColumn The original column number.
  43775. * @param aSource The original source's filename.
  43776. * @param aChunks Optional. An array of strings which are snippets of
  43777. * generated JS, or other SourceNodes.
  43778. * @param aName The original identifier.
  43779. */
  43780. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  43781. this.children = [];
  43782. this.sourceContents = {};
  43783. this.line = aLine == null ? null : aLine;
  43784. this.column = aColumn == null ? null : aColumn;
  43785. this.source = aSource == null ? null : aSource;
  43786. this.name = aName == null ? null : aName;
  43787. this[isSourceNode] = true;
  43788. if (aChunks != null) this.add(aChunks);
  43789. }
  43790. /**
  43791. * Creates a SourceNode from generated code and a SourceMapConsumer.
  43792. *
  43793. * @param aGeneratedCode The generated code
  43794. * @param aSourceMapConsumer The SourceMap for the generated code
  43795. * @param aRelativePath Optional. The path that relative sources in the
  43796. * SourceMapConsumer should be relative to.
  43797. */
  43798. SourceNode.fromStringWithSourceMap =
  43799. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  43800. // The SourceNode we want to fill with the generated code
  43801. // and the SourceMap
  43802. var node = new SourceNode();
  43803. // All even indices of this array are one line of the generated code,
  43804. // while all odd indices are the newlines between two adjacent lines
  43805. // (since `REGEX_NEWLINE` captures its match).
  43806. // Processed fragments are accessed by calling `shiftNextLine`.
  43807. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  43808. var remainingLinesIndex = 0;
  43809. var shiftNextLine = function() {
  43810. var lineContents = getNextLine();
  43811. // The last line of a file might not have a newline.
  43812. var newLine = getNextLine() || "";
  43813. return lineContents + newLine;
  43814. function getNextLine() {
  43815. return remainingLinesIndex < remainingLines.length ?
  43816. remainingLines[remainingLinesIndex++] : undefined;
  43817. }
  43818. };
  43819. // We need to remember the position of "remainingLines"
  43820. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  43821. // The generate SourceNodes we need a code range.
  43822. // To extract it current and last mapping is used.
  43823. // Here we store the last mapping.
  43824. var lastMapping = null;
  43825. aSourceMapConsumer.eachMapping(function (mapping) {
  43826. if (lastMapping !== null) {
  43827. // We add the code from "lastMapping" to "mapping":
  43828. // First check if there is a new line in between.
  43829. if (lastGeneratedLine < mapping.generatedLine) {
  43830. // Associate first line with "lastMapping"
  43831. addMappingWithCode(lastMapping, shiftNextLine());
  43832. lastGeneratedLine++;
  43833. lastGeneratedColumn = 0;
  43834. // The remaining code is added without mapping
  43835. } else {
  43836. // There is no new line in between.
  43837. // Associate the code between "lastGeneratedColumn" and
  43838. // "mapping.generatedColumn" with "lastMapping"
  43839. var nextLine = remainingLines[remainingLinesIndex] || '';
  43840. var code = nextLine.substr(0, mapping.generatedColumn -
  43841. lastGeneratedColumn);
  43842. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  43843. lastGeneratedColumn);
  43844. lastGeneratedColumn = mapping.generatedColumn;
  43845. addMappingWithCode(lastMapping, code);
  43846. // No more remaining code, continue
  43847. lastMapping = mapping;
  43848. return;
  43849. }
  43850. }
  43851. // We add the generated code until the first mapping
  43852. // to the SourceNode without any mapping.
  43853. // Each line is added as separate string.
  43854. while (lastGeneratedLine < mapping.generatedLine) {
  43855. node.add(shiftNextLine());
  43856. lastGeneratedLine++;
  43857. }
  43858. if (lastGeneratedColumn < mapping.generatedColumn) {
  43859. var nextLine = remainingLines[remainingLinesIndex] || '';
  43860. node.add(nextLine.substr(0, mapping.generatedColumn));
  43861. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  43862. lastGeneratedColumn = mapping.generatedColumn;
  43863. }
  43864. lastMapping = mapping;
  43865. }, this);
  43866. // We have processed all mappings.
  43867. if (remainingLinesIndex < remainingLines.length) {
  43868. if (lastMapping) {
  43869. // Associate the remaining code in the current line with "lastMapping"
  43870. addMappingWithCode(lastMapping, shiftNextLine());
  43871. }
  43872. // and add the remaining lines without any mapping
  43873. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  43874. }
  43875. // Copy sourcesContent into SourceNode
  43876. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  43877. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  43878. if (content != null) {
  43879. if (aRelativePath != null) {
  43880. sourceFile = util.join(aRelativePath, sourceFile);
  43881. }
  43882. node.setSourceContent(sourceFile, content);
  43883. }
  43884. });
  43885. return node;
  43886. function addMappingWithCode(mapping, code) {
  43887. if (mapping === null || mapping.source === undefined) {
  43888. node.add(code);
  43889. } else {
  43890. var source = aRelativePath
  43891. ? util.join(aRelativePath, mapping.source)
  43892. : mapping.source;
  43893. node.add(new SourceNode(mapping.originalLine,
  43894. mapping.originalColumn,
  43895. source,
  43896. code,
  43897. mapping.name));
  43898. }
  43899. }
  43900. };
  43901. /**
  43902. * Add a chunk of generated JS to this source node.
  43903. *
  43904. * @param aChunk A string snippet of generated JS code, another instance of
  43905. * SourceNode, or an array where each member is one of those things.
  43906. */
  43907. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  43908. if (Array.isArray(aChunk)) {
  43909. aChunk.forEach(function (chunk) {
  43910. this.add(chunk);
  43911. }, this);
  43912. }
  43913. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  43914. if (aChunk) {
  43915. this.children.push(aChunk);
  43916. }
  43917. }
  43918. else {
  43919. throw new TypeError(
  43920. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  43921. );
  43922. }
  43923. return this;
  43924. };
  43925. /**
  43926. * Add a chunk of generated JS to the beginning of this source node.
  43927. *
  43928. * @param aChunk A string snippet of generated JS code, another instance of
  43929. * SourceNode, or an array where each member is one of those things.
  43930. */
  43931. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  43932. if (Array.isArray(aChunk)) {
  43933. for (var i = aChunk.length-1; i >= 0; i--) {
  43934. this.prepend(aChunk[i]);
  43935. }
  43936. }
  43937. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  43938. this.children.unshift(aChunk);
  43939. }
  43940. else {
  43941. throw new TypeError(
  43942. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  43943. );
  43944. }
  43945. return this;
  43946. };
  43947. /**
  43948. * Walk over the tree of JS snippets in this node and its children. The
  43949. * walking function is called once for each snippet of JS and is passed that
  43950. * snippet and the its original associated source's line/column location.
  43951. *
  43952. * @param aFn The traversal function.
  43953. */
  43954. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  43955. var chunk;
  43956. for (var i = 0, len = this.children.length; i < len; i++) {
  43957. chunk = this.children[i];
  43958. if (chunk[isSourceNode]) {
  43959. chunk.walk(aFn);
  43960. }
  43961. else {
  43962. if (chunk !== '') {
  43963. aFn(chunk, { source: this.source,
  43964. line: this.line,
  43965. column: this.column,
  43966. name: this.name });
  43967. }
  43968. }
  43969. }
  43970. };
  43971. /**
  43972. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  43973. * each of `this.children`.
  43974. *
  43975. * @param aSep The separator.
  43976. */
  43977. SourceNode.prototype.join = function SourceNode_join(aSep) {
  43978. var newChildren;
  43979. var i;
  43980. var len = this.children.length;
  43981. if (len > 0) {
  43982. newChildren = [];
  43983. for (i = 0; i < len-1; i++) {
  43984. newChildren.push(this.children[i]);
  43985. newChildren.push(aSep);
  43986. }
  43987. newChildren.push(this.children[i]);
  43988. this.children = newChildren;
  43989. }
  43990. return this;
  43991. };
  43992. /**
  43993. * Call String.prototype.replace on the very right-most source snippet. Useful
  43994. * for trimming whitespace from the end of a source node, etc.
  43995. *
  43996. * @param aPattern The pattern to replace.
  43997. * @param aReplacement The thing to replace the pattern with.
  43998. */
  43999. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  44000. var lastChild = this.children[this.children.length - 1];
  44001. if (lastChild[isSourceNode]) {
  44002. lastChild.replaceRight(aPattern, aReplacement);
  44003. }
  44004. else if (typeof lastChild === 'string') {
  44005. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  44006. }
  44007. else {
  44008. this.children.push(''.replace(aPattern, aReplacement));
  44009. }
  44010. return this;
  44011. };
  44012. /**
  44013. * Set the source content for a source file. This will be added to the SourceMapGenerator
  44014. * in the sourcesContent field.
  44015. *
  44016. * @param aSourceFile The filename of the source file
  44017. * @param aSourceContent The content of the source file
  44018. */
  44019. SourceNode.prototype.setSourceContent =
  44020. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  44021. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  44022. };
  44023. /**
  44024. * Walk over the tree of SourceNodes. The walking function is called for each
  44025. * source file content and is passed the filename and source content.
  44026. *
  44027. * @param aFn The traversal function.
  44028. */
  44029. SourceNode.prototype.walkSourceContents =
  44030. function SourceNode_walkSourceContents(aFn) {
  44031. for (var i = 0, len = this.children.length; i < len; i++) {
  44032. if (this.children[i][isSourceNode]) {
  44033. this.children[i].walkSourceContents(aFn);
  44034. }
  44035. }
  44036. var sources = Object.keys(this.sourceContents);
  44037. for (var i = 0, len = sources.length; i < len; i++) {
  44038. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  44039. }
  44040. };
  44041. /**
  44042. * Return the string representation of this source node. Walks over the tree
  44043. * and concatenates all the various snippets together to one string.
  44044. */
  44045. SourceNode.prototype.toString = function SourceNode_toString() {
  44046. var str = "";
  44047. this.walk(function (chunk) {
  44048. str += chunk;
  44049. });
  44050. return str;
  44051. };
  44052. /**
  44053. * Returns the string representation of this source node along with a source
  44054. * map.
  44055. */
  44056. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  44057. var generated = {
  44058. code: "",
  44059. line: 1,
  44060. column: 0
  44061. };
  44062. var map = new SourceMapGenerator(aArgs);
  44063. var sourceMappingActive = false;
  44064. var lastOriginalSource = null;
  44065. var lastOriginalLine = null;
  44066. var lastOriginalColumn = null;
  44067. var lastOriginalName = null;
  44068. this.walk(function (chunk, original) {
  44069. generated.code += chunk;
  44070. if (original.source !== null
  44071. && original.line !== null
  44072. && original.column !== null) {
  44073. if(lastOriginalSource !== original.source
  44074. || lastOriginalLine !== original.line
  44075. || lastOriginalColumn !== original.column
  44076. || lastOriginalName !== original.name) {
  44077. map.addMapping({
  44078. source: original.source,
  44079. original: {
  44080. line: original.line,
  44081. column: original.column
  44082. },
  44083. generated: {
  44084. line: generated.line,
  44085. column: generated.column
  44086. },
  44087. name: original.name
  44088. });
  44089. }
  44090. lastOriginalSource = original.source;
  44091. lastOriginalLine = original.line;
  44092. lastOriginalColumn = original.column;
  44093. lastOriginalName = original.name;
  44094. sourceMappingActive = true;
  44095. } else if (sourceMappingActive) {
  44096. map.addMapping({
  44097. generated: {
  44098. line: generated.line,
  44099. column: generated.column
  44100. }
  44101. });
  44102. lastOriginalSource = null;
  44103. sourceMappingActive = false;
  44104. }
  44105. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  44106. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  44107. generated.line++;
  44108. generated.column = 0;
  44109. // Mappings end at eol
  44110. if (idx + 1 === length) {
  44111. lastOriginalSource = null;
  44112. sourceMappingActive = false;
  44113. } else if (sourceMappingActive) {
  44114. map.addMapping({
  44115. source: original.source,
  44116. original: {
  44117. line: original.line,
  44118. column: original.column
  44119. },
  44120. generated: {
  44121. line: generated.line,
  44122. column: generated.column
  44123. },
  44124. name: original.name
  44125. });
  44126. }
  44127. } else {
  44128. generated.column++;
  44129. }
  44130. }
  44131. });
  44132. this.walkSourceContents(function (sourceFile, sourceContent) {
  44133. map.setSourceContent(sourceFile, sourceContent);
  44134. });
  44135. return { code: generated.code, map: map };
  44136. };
  44137. sourceNode.SourceNode = SourceNode;
  44138. return sourceNode;
  44139. }
  44140. /*
  44141. * Copyright 2009-2011 Mozilla Foundation and contributors
  44142. * Licensed under the New BSD license. See LICENSE.txt or:
  44143. * http://opensource.org/licenses/BSD-3-Clause
  44144. */
  44145. var hasRequiredSourceMap;
  44146. function requireSourceMap () {
  44147. if (hasRequiredSourceMap) return sourceMap;
  44148. hasRequiredSourceMap = 1;
  44149. sourceMap.SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  44150. sourceMap.SourceMapConsumer = /*@__PURE__*/ requireSourceMapConsumer().SourceMapConsumer;
  44151. sourceMap.SourceNode = /*@__PURE__*/ requireSourceNode().SourceNode;
  44152. return sourceMap;
  44153. }
  44154. var mergeSourceMap;
  44155. var hasRequiredMergeSourceMap;
  44156. function requireMergeSourceMap () {
  44157. if (hasRequiredMergeSourceMap) return mergeSourceMap;
  44158. hasRequiredMergeSourceMap = 1;
  44159. var sourceMap = /*@__PURE__*/ requireSourceMap();
  44160. var SourceMapConsumer = sourceMap.SourceMapConsumer;
  44161. var SourceMapGenerator = sourceMap.SourceMapGenerator;
  44162. mergeSourceMap = merge;
  44163. /**
  44164. * Merge old source map and new source map and return merged.
  44165. * If old or new source map value is falsy, return another one as it is.
  44166. *
  44167. * @param {object|string} [oldMap] old source map object
  44168. * @param {object|string} [newmap] new source map object
  44169. * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
  44170. */
  44171. function merge(oldMap, newMap) {
  44172. if (!oldMap) return newMap
  44173. if (!newMap) return oldMap
  44174. var oldMapConsumer = new SourceMapConsumer(oldMap);
  44175. var newMapConsumer = new SourceMapConsumer(newMap);
  44176. var mergedMapGenerator = new SourceMapGenerator();
  44177. // iterate on new map and overwrite original position of new map with one of old map
  44178. newMapConsumer.eachMapping(function(m) {
  44179. // pass when `originalLine` is null.
  44180. // It occurs in case that the node does not have origin in original code.
  44181. if (m.originalLine == null) return
  44182. var origPosInOldMap = oldMapConsumer.originalPositionFor({
  44183. line: m.originalLine,
  44184. column: m.originalColumn
  44185. });
  44186. if (origPosInOldMap.source == null) return
  44187. mergedMapGenerator.addMapping({
  44188. original: {
  44189. line: origPosInOldMap.line,
  44190. column: origPosInOldMap.column
  44191. },
  44192. generated: {
  44193. line: m.generatedLine,
  44194. column: m.generatedColumn
  44195. },
  44196. source: origPosInOldMap.source,
  44197. name: origPosInOldMap.name
  44198. });
  44199. });
  44200. var consumers = [oldMapConsumer, newMapConsumer];
  44201. consumers.forEach(function(consumer) {
  44202. consumer.sources.forEach(function(sourceFile) {
  44203. mergedMapGenerator._sources.add(sourceFile);
  44204. var sourceContent = consumer.sourceContentFor(sourceFile);
  44205. if (sourceContent != null) {
  44206. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  44207. }
  44208. });
  44209. });
  44210. mergedMapGenerator._sourceRoot = oldMap.sourceRoot;
  44211. mergedMapGenerator._file = oldMap.file;
  44212. return JSON.parse(mergedMapGenerator.toString())
  44213. }
  44214. return mergeSourceMap;
  44215. }
  44216. var mergeSourceMapExports = /*@__PURE__*/ requireMergeSourceMap();
  44217. var merge = /*@__PURE__*/getDefaultExportFromCjs(mergeSourceMapExports);
  44218. var __defProp$5 = Object.defineProperty;
  44219. var __defProps$4 = Object.defineProperties;
  44220. var __getOwnPropDescs$4 = Object.getOwnPropertyDescriptors;
  44221. var __getOwnPropSymbols$5 = Object.getOwnPropertySymbols;
  44222. var __hasOwnProp$5 = Object.prototype.hasOwnProperty;
  44223. var __propIsEnum$5 = Object.prototype.propertyIsEnumerable;
  44224. var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  44225. var __spreadValues$5 = (a, b) => {
  44226. for (var prop in b || (b = {}))
  44227. if (__hasOwnProp$5.call(b, prop))
  44228. __defNormalProp$5(a, prop, b[prop]);
  44229. if (__getOwnPropSymbols$5)
  44230. for (var prop of __getOwnPropSymbols$5(b)) {
  44231. if (__propIsEnum$5.call(b, prop))
  44232. __defNormalProp$5(a, prop, b[prop]);
  44233. }
  44234. return a;
  44235. };
  44236. var __spreadProps$4 = (a, b) => __defProps$4(a, __getOwnPropDescs$4(b));
  44237. const scss = (source, map, options, load = require) => {
  44238. const nodeSass = load("sass");
  44239. const { compileString, renderSync } = nodeSass;
  44240. const data = getSource(source, options.filename, options.additionalData);
  44241. let css;
  44242. let dependencies;
  44243. let sourceMap;
  44244. try {
  44245. if (compileString) {
  44246. const { pathToFileURL, fileURLToPath } = load("url");
  44247. const result = compileString(data, __spreadProps$4(__spreadValues$5({}, options), {
  44248. url: pathToFileURL(options.filename),
  44249. sourceMap: !!map
  44250. }));
  44251. css = result.css;
  44252. dependencies = result.loadedUrls.map((url) => fileURLToPath(url));
  44253. sourceMap = map ? result.sourceMap : void 0;
  44254. } else {
  44255. const result = renderSync(__spreadProps$4(__spreadValues$5({}, options), {
  44256. data,
  44257. file: options.filename,
  44258. outFile: options.filename,
  44259. sourceMap: !!map
  44260. }));
  44261. css = result.css.toString();
  44262. dependencies = result.stats.includedFiles;
  44263. sourceMap = map ? JSON.parse(result.map.toString()) : void 0;
  44264. }
  44265. if (map) {
  44266. return {
  44267. code: css,
  44268. errors: [],
  44269. dependencies,
  44270. map: merge(map, sourceMap)
  44271. };
  44272. }
  44273. return { code: css, errors: [], dependencies };
  44274. } catch (e) {
  44275. return { code: "", errors: [e], dependencies: [] };
  44276. }
  44277. };
  44278. const sass = (source, map, options, load) => scss(
  44279. source,
  44280. map,
  44281. __spreadProps$4(__spreadValues$5({}, options), {
  44282. indentedSyntax: true
  44283. }),
  44284. load
  44285. );
  44286. const less = (source, map, options, load = require) => {
  44287. const nodeLess = load("less");
  44288. let result;
  44289. let error = null;
  44290. nodeLess.render(
  44291. getSource(source, options.filename, options.additionalData),
  44292. __spreadProps$4(__spreadValues$5({}, options), { syncImport: true }),
  44293. (err, output) => {
  44294. error = err;
  44295. result = output;
  44296. }
  44297. );
  44298. if (error) return { code: "", errors: [error], dependencies: [] };
  44299. const dependencies = result.imports;
  44300. if (map) {
  44301. return {
  44302. code: result.css.toString(),
  44303. map: merge(map, result.map),
  44304. errors: [],
  44305. dependencies
  44306. };
  44307. }
  44308. return {
  44309. code: result.css.toString(),
  44310. errors: [],
  44311. dependencies
  44312. };
  44313. };
  44314. const styl = (source, map, options, load = require) => {
  44315. const nodeStylus = load("stylus");
  44316. try {
  44317. const ref = nodeStylus(source, options);
  44318. if (map) ref.set("sourcemap", { inline: false, comment: false });
  44319. const result = ref.render();
  44320. const dependencies = ref.deps();
  44321. if (map) {
  44322. return {
  44323. code: result,
  44324. map: merge(map, ref.sourcemap),
  44325. errors: [],
  44326. dependencies
  44327. };
  44328. }
  44329. return { code: result, errors: [], dependencies };
  44330. } catch (e) {
  44331. return { code: "", errors: [e], dependencies: [] };
  44332. }
  44333. };
  44334. function getSource(source, filename, additionalData) {
  44335. if (!additionalData) return source;
  44336. if (isFunction$1(additionalData)) {
  44337. return additionalData(source, filename);
  44338. }
  44339. return additionalData + source;
  44340. }
  44341. const processors = {
  44342. less,
  44343. sass,
  44344. scss,
  44345. styl,
  44346. stylus: styl
  44347. };
  44348. var __defProp$4 = Object.defineProperty;
  44349. var __defProps$3 = Object.defineProperties;
  44350. var __getOwnPropDescs$3 = Object.getOwnPropertyDescriptors;
  44351. var __getOwnPropSymbols$4 = Object.getOwnPropertySymbols;
  44352. var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
  44353. var __propIsEnum$4 = Object.prototype.propertyIsEnumerable;
  44354. var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  44355. var __spreadValues$4 = (a, b) => {
  44356. for (var prop in b || (b = {}))
  44357. if (__hasOwnProp$4.call(b, prop))
  44358. __defNormalProp$4(a, prop, b[prop]);
  44359. if (__getOwnPropSymbols$4)
  44360. for (var prop of __getOwnPropSymbols$4(b)) {
  44361. if (__propIsEnum$4.call(b, prop))
  44362. __defNormalProp$4(a, prop, b[prop]);
  44363. }
  44364. return a;
  44365. };
  44366. var __spreadProps$3 = (a, b) => __defProps$3(a, __getOwnPropDescs$3(b));
  44367. function compileStyle(options) {
  44368. return doCompileStyle(__spreadProps$3(__spreadValues$4({}, options), {
  44369. isAsync: false
  44370. }));
  44371. }
  44372. function compileStyleAsync(options) {
  44373. return doCompileStyle(__spreadProps$3(__spreadValues$4({}, options), {
  44374. isAsync: true
  44375. }));
  44376. }
  44377. function doCompileStyle(options) {
  44378. const {
  44379. filename,
  44380. id,
  44381. scoped = false,
  44382. trim = true,
  44383. isProd = false,
  44384. modules = false,
  44385. modulesOptions = {},
  44386. preprocessLang,
  44387. postcssOptions,
  44388. postcssPlugins
  44389. } = options;
  44390. const preprocessor = preprocessLang && processors[preprocessLang];
  44391. const preProcessedSource = preprocessor && preprocess(options, preprocessor);
  44392. const map = preProcessedSource ? preProcessedSource.map : options.inMap || options.map;
  44393. const source = preProcessedSource ? preProcessedSource.code : options.source;
  44394. const shortId = id.replace(/^data-v-/, "");
  44395. const longId = `data-v-${shortId}`;
  44396. const plugins = (postcssPlugins || []).slice();
  44397. plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
  44398. if (trim) {
  44399. plugins.push(trimPlugin());
  44400. }
  44401. if (scoped) {
  44402. plugins.push(scopedPlugin(longId));
  44403. }
  44404. let cssModules;
  44405. if (modules) {
  44406. {
  44407. throw new Error(
  44408. "[@vue/compiler-sfc] `modules` option is not supported in the browser build."
  44409. );
  44410. }
  44411. }
  44412. const postCSSOptions = __spreadProps$3(__spreadValues$4({}, postcssOptions), {
  44413. to: filename,
  44414. from: filename
  44415. });
  44416. if (map) {
  44417. postCSSOptions.map = {
  44418. inline: false,
  44419. annotation: false,
  44420. prev: map
  44421. };
  44422. }
  44423. let result;
  44424. let code;
  44425. let outMap;
  44426. const dependencies = new Set(
  44427. preProcessedSource ? preProcessedSource.dependencies : []
  44428. );
  44429. dependencies.delete(filename);
  44430. const errors = [];
  44431. if (preProcessedSource && preProcessedSource.errors.length) {
  44432. errors.push(...preProcessedSource.errors);
  44433. }
  44434. const recordPlainCssDependencies = (messages) => {
  44435. messages.forEach((msg) => {
  44436. if (msg.type === "dependency") {
  44437. dependencies.add(msg.file);
  44438. }
  44439. });
  44440. return dependencies;
  44441. };
  44442. try {
  44443. result = postcss(plugins).process(source, postCSSOptions);
  44444. if (options.isAsync) {
  44445. return result.then((result2) => ({
  44446. code: result2.css || "",
  44447. map: result2.map && result2.map.toJSON(),
  44448. errors,
  44449. modules: cssModules,
  44450. rawResult: result2,
  44451. dependencies: recordPlainCssDependencies(result2.messages)
  44452. })).catch((error) => ({
  44453. code: "",
  44454. map: void 0,
  44455. errors: [...errors, error],
  44456. rawResult: void 0,
  44457. dependencies
  44458. }));
  44459. }
  44460. recordPlainCssDependencies(result.messages);
  44461. code = result.css;
  44462. outMap = result.map;
  44463. } catch (e) {
  44464. errors.push(e);
  44465. }
  44466. return {
  44467. code: code || ``,
  44468. map: outMap && outMap.toJSON(),
  44469. errors,
  44470. rawResult: result,
  44471. dependencies
  44472. };
  44473. }
  44474. function preprocess(options, preprocessor) {
  44475. if (!options.preprocessCustomRequire) {
  44476. throw new Error(
  44477. `[@vue/compiler-sfc] Style preprocessing in the browser build must provide the \`preprocessCustomRequire\` option to return the in-browser version of the preprocessor.`
  44478. );
  44479. }
  44480. return preprocessor(
  44481. options.source,
  44482. options.inMap || options.map,
  44483. __spreadValues$4({
  44484. filename: options.filename
  44485. }, options.preprocessOptions),
  44486. options.preprocessCustomRequire
  44487. );
  44488. }
  44489. const UNKNOWN_TYPE = "Unknown";
  44490. function resolveObjectKey(node, computed) {
  44491. switch (node.type) {
  44492. case "StringLiteral":
  44493. case "NumericLiteral":
  44494. return String(node.value);
  44495. case "Identifier":
  44496. if (!computed) return node.name;
  44497. }
  44498. return void 0;
  44499. }
  44500. function concatStrings(strs) {
  44501. return strs.filter((s) => !!s).join(", ");
  44502. }
  44503. function isLiteralNode(node) {
  44504. return node.type.endsWith("Literal");
  44505. }
  44506. function isCallOf(node, test) {
  44507. return !!(node && test && node.type === "CallExpression" && node.callee.type === "Identifier" && (typeof test === "string" ? node.callee.name === test : test(node.callee.name)));
  44508. }
  44509. function toRuntimeTypeString(types) {
  44510. return types.length > 1 ? `[${types.join(", ")}]` : types[0];
  44511. }
  44512. function getImportedName(specifier) {
  44513. if (specifier.type === "ImportSpecifier")
  44514. return specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
  44515. else if (specifier.type === "ImportNamespaceSpecifier") return "*";
  44516. return "default";
  44517. }
  44518. function getId(node) {
  44519. return node.type === "Identifier" ? node.name : node.type === "StringLiteral" ? node.value : null;
  44520. }
  44521. function getStringLiteralKey(node) {
  44522. 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;
  44523. }
  44524. const normalize = (path.posix || path).normalize;
  44525. const windowsSlashRE = /\\/g;
  44526. function normalizePath(p) {
  44527. return normalize(p.replace(windowsSlashRE, "/"));
  44528. }
  44529. const joinPaths = (path.posix || path).join;
  44530. const propNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~\-]/;
  44531. function getEscapedPropName(key) {
  44532. return propNameEscapeSymbolsRE.test(key) ? JSON.stringify(key) : key;
  44533. }
  44534. const isJS = (...langs) => langs.some((lang) => lang === "js" || lang === "jsx");
  44535. const isTS = (...langs) => langs.some((lang) => lang === "ts" || lang === "tsx");
  44536. function analyzeScriptBindings(ast) {
  44537. for (const node of ast) {
  44538. if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "ObjectExpression") {
  44539. return analyzeBindingsFromOptions(node.declaration);
  44540. }
  44541. }
  44542. return {};
  44543. }
  44544. function analyzeBindingsFromOptions(node) {
  44545. const bindings = {};
  44546. Object.defineProperty(bindings, "__isScriptSetup", {
  44547. enumerable: false,
  44548. value: false
  44549. });
  44550. for (const property of node.properties) {
  44551. if (property.type === "ObjectProperty" && !property.computed && property.key.type === "Identifier") {
  44552. if (property.key.name === "props") {
  44553. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  44554. bindings[key] = "props";
  44555. }
  44556. } else if (property.key.name === "inject") {
  44557. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  44558. bindings[key] = "options";
  44559. }
  44560. } else if (property.value.type === "ObjectExpression" && (property.key.name === "computed" || property.key.name === "methods")) {
  44561. for (const key of getObjectExpressionKeys(property.value)) {
  44562. bindings[key] = "options";
  44563. }
  44564. }
  44565. } else if (property.type === "ObjectMethod" && property.key.type === "Identifier" && (property.key.name === "setup" || property.key.name === "data")) {
  44566. for (const bodyItem of property.body.body) {
  44567. if (bodyItem.type === "ReturnStatement" && bodyItem.argument && bodyItem.argument.type === "ObjectExpression") {
  44568. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  44569. bindings[key] = property.key.name === "setup" ? "setup-maybe-ref" : "data";
  44570. }
  44571. }
  44572. }
  44573. }
  44574. }
  44575. return bindings;
  44576. }
  44577. function getObjectExpressionKeys(node) {
  44578. const keys = [];
  44579. for (const prop of node.properties) {
  44580. if (prop.type === "SpreadElement") continue;
  44581. const key = resolveObjectKey(prop.key, prop.computed);
  44582. if (key) keys.push(String(key));
  44583. }
  44584. return keys;
  44585. }
  44586. function getArrayExpressionKeys(node) {
  44587. const keys = [];
  44588. for (const element of node.elements) {
  44589. if (element && element.type === "StringLiteral") {
  44590. keys.push(element.value);
  44591. }
  44592. }
  44593. return keys;
  44594. }
  44595. function getObjectOrArrayExpressionKeys(value) {
  44596. if (value.type === "ArrayExpression") {
  44597. return getArrayExpressionKeys(value);
  44598. }
  44599. if (value.type === "ObjectExpression") {
  44600. return getObjectExpressionKeys(value);
  44601. }
  44602. return [];
  44603. }
  44604. // src/vlq.ts
  44605. var comma = ",".charCodeAt(0);
  44606. var semicolon = ";".charCodeAt(0);
  44607. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  44608. var intToChar = new Uint8Array(64);
  44609. var charToInt = new Uint8Array(128);
  44610. for (let i = 0; i < chars.length; i++) {
  44611. const c = chars.charCodeAt(i);
  44612. intToChar[i] = c;
  44613. charToInt[c] = i;
  44614. }
  44615. function encodeInteger(builder, num, relative) {
  44616. let delta = num - relative;
  44617. delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
  44618. do {
  44619. let clamped = delta & 31;
  44620. delta >>>= 5;
  44621. if (delta > 0) clamped |= 32;
  44622. builder.write(intToChar[clamped]);
  44623. } while (delta > 0);
  44624. return num;
  44625. }
  44626. // src/strings.ts
  44627. var bufLength = 1024 * 16;
  44628. var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
  44629. decode(buf) {
  44630. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  44631. return out.toString();
  44632. }
  44633. } : {
  44634. decode(buf) {
  44635. let out = "";
  44636. for (let i = 0; i < buf.length; i++) {
  44637. out += String.fromCharCode(buf[i]);
  44638. }
  44639. return out;
  44640. }
  44641. };
  44642. var StringWriter = class {
  44643. constructor() {
  44644. this.pos = 0;
  44645. this.out = "";
  44646. this.buffer = new Uint8Array(bufLength);
  44647. }
  44648. write(v) {
  44649. const { buffer } = this;
  44650. buffer[this.pos++] = v;
  44651. if (this.pos === bufLength) {
  44652. this.out += td.decode(buffer);
  44653. this.pos = 0;
  44654. }
  44655. }
  44656. flush() {
  44657. const { buffer, out, pos } = this;
  44658. return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
  44659. }
  44660. };
  44661. function encode(decoded) {
  44662. const writer = new StringWriter();
  44663. let sourcesIndex = 0;
  44664. let sourceLine = 0;
  44665. let sourceColumn = 0;
  44666. let namesIndex = 0;
  44667. for (let i = 0; i < decoded.length; i++) {
  44668. const line = decoded[i];
  44669. if (i > 0) writer.write(semicolon);
  44670. if (line.length === 0) continue;
  44671. let genColumn = 0;
  44672. for (let j = 0; j < line.length; j++) {
  44673. const segment = line[j];
  44674. if (j > 0) writer.write(comma);
  44675. genColumn = encodeInteger(writer, segment[0], genColumn);
  44676. if (segment.length === 1) continue;
  44677. sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
  44678. sourceLine = encodeInteger(writer, segment[2], sourceLine);
  44679. sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
  44680. if (segment.length === 4) continue;
  44681. namesIndex = encodeInteger(writer, segment[4], namesIndex);
  44682. }
  44683. }
  44684. return writer.flush();
  44685. }
  44686. class BitSet {
  44687. constructor(arg) {
  44688. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  44689. }
  44690. add(n) {
  44691. this.bits[n >> 5] |= 1 << (n & 31);
  44692. }
  44693. has(n) {
  44694. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  44695. }
  44696. }
  44697. class Chunk {
  44698. constructor(start, end, content) {
  44699. this.start = start;
  44700. this.end = end;
  44701. this.original = content;
  44702. this.intro = '';
  44703. this.outro = '';
  44704. this.content = content;
  44705. this.storeName = false;
  44706. this.edited = false;
  44707. {
  44708. this.previous = null;
  44709. this.next = null;
  44710. }
  44711. }
  44712. appendLeft(content) {
  44713. this.outro += content;
  44714. }
  44715. appendRight(content) {
  44716. this.intro = this.intro + content;
  44717. }
  44718. clone() {
  44719. const chunk = new Chunk(this.start, this.end, this.original);
  44720. chunk.intro = this.intro;
  44721. chunk.outro = this.outro;
  44722. chunk.content = this.content;
  44723. chunk.storeName = this.storeName;
  44724. chunk.edited = this.edited;
  44725. return chunk;
  44726. }
  44727. contains(index) {
  44728. return this.start < index && index < this.end;
  44729. }
  44730. eachNext(fn) {
  44731. let chunk = this;
  44732. while (chunk) {
  44733. fn(chunk);
  44734. chunk = chunk.next;
  44735. }
  44736. }
  44737. eachPrevious(fn) {
  44738. let chunk = this;
  44739. while (chunk) {
  44740. fn(chunk);
  44741. chunk = chunk.previous;
  44742. }
  44743. }
  44744. edit(content, storeName, contentOnly) {
  44745. this.content = content;
  44746. if (!contentOnly) {
  44747. this.intro = '';
  44748. this.outro = '';
  44749. }
  44750. this.storeName = storeName;
  44751. this.edited = true;
  44752. return this;
  44753. }
  44754. prependLeft(content) {
  44755. this.outro = content + this.outro;
  44756. }
  44757. prependRight(content) {
  44758. this.intro = content + this.intro;
  44759. }
  44760. reset() {
  44761. this.intro = '';
  44762. this.outro = '';
  44763. if (this.edited) {
  44764. this.content = this.original;
  44765. this.storeName = false;
  44766. this.edited = false;
  44767. }
  44768. }
  44769. split(index) {
  44770. const sliceIndex = index - this.start;
  44771. const originalBefore = this.original.slice(0, sliceIndex);
  44772. const originalAfter = this.original.slice(sliceIndex);
  44773. this.original = originalBefore;
  44774. const newChunk = new Chunk(index, this.end, originalAfter);
  44775. newChunk.outro = this.outro;
  44776. this.outro = '';
  44777. this.end = index;
  44778. if (this.edited) {
  44779. // after split we should save the edit content record into the correct chunk
  44780. // to make sure sourcemap correct
  44781. // For example:
  44782. // ' test'.trim()
  44783. // split -> ' ' + 'test'
  44784. // ✔️ edit -> '' + 'test'
  44785. // ✖️ edit -> 'test' + ''
  44786. // TODO is this block necessary?...
  44787. newChunk.edit('', false);
  44788. this.content = '';
  44789. } else {
  44790. this.content = originalBefore;
  44791. }
  44792. newChunk.next = this.next;
  44793. if (newChunk.next) newChunk.next.previous = newChunk;
  44794. newChunk.previous = this;
  44795. this.next = newChunk;
  44796. return newChunk;
  44797. }
  44798. toString() {
  44799. return this.intro + this.content + this.outro;
  44800. }
  44801. trimEnd(rx) {
  44802. this.outro = this.outro.replace(rx, '');
  44803. if (this.outro.length) return true;
  44804. const trimmed = this.content.replace(rx, '');
  44805. if (trimmed.length) {
  44806. if (trimmed !== this.content) {
  44807. this.split(this.start + trimmed.length).edit('', undefined, true);
  44808. if (this.edited) {
  44809. // save the change, if it has been edited
  44810. this.edit(trimmed, this.storeName, true);
  44811. }
  44812. }
  44813. return true;
  44814. } else {
  44815. this.edit('', undefined, true);
  44816. this.intro = this.intro.replace(rx, '');
  44817. if (this.intro.length) return true;
  44818. }
  44819. }
  44820. trimStart(rx) {
  44821. this.intro = this.intro.replace(rx, '');
  44822. if (this.intro.length) return true;
  44823. const trimmed = this.content.replace(rx, '');
  44824. if (trimmed.length) {
  44825. if (trimmed !== this.content) {
  44826. const newChunk = this.split(this.end - trimmed.length);
  44827. if (this.edited) {
  44828. // save the change, if it has been edited
  44829. newChunk.edit(trimmed, this.storeName, true);
  44830. }
  44831. this.edit('', undefined, true);
  44832. }
  44833. return true;
  44834. } else {
  44835. this.edit('', undefined, true);
  44836. this.outro = this.outro.replace(rx, '');
  44837. if (this.outro.length) return true;
  44838. }
  44839. }
  44840. }
  44841. function getBtoa() {
  44842. if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {
  44843. return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
  44844. } else if (typeof Buffer === 'function') {
  44845. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  44846. } else {
  44847. return () => {
  44848. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  44849. };
  44850. }
  44851. }
  44852. const btoa = /*#__PURE__*/ getBtoa();
  44853. class SourceMap {
  44854. constructor(properties) {
  44855. this.version = 3;
  44856. this.file = properties.file;
  44857. this.sources = properties.sources;
  44858. this.sourcesContent = properties.sourcesContent;
  44859. this.names = properties.names;
  44860. this.mappings = encode(properties.mappings);
  44861. if (typeof properties.x_google_ignoreList !== 'undefined') {
  44862. this.x_google_ignoreList = properties.x_google_ignoreList;
  44863. }
  44864. if (typeof properties.debugId !== 'undefined') {
  44865. this.debugId = properties.debugId;
  44866. }
  44867. }
  44868. toString() {
  44869. return JSON.stringify(this);
  44870. }
  44871. toUrl() {
  44872. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  44873. }
  44874. }
  44875. function guessIndent(code) {
  44876. const lines = code.split('\n');
  44877. const tabbed = lines.filter((line) => /^\t+/.test(line));
  44878. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  44879. if (tabbed.length === 0 && spaced.length === 0) {
  44880. return null;
  44881. }
  44882. // More lines tabbed than spaced? Assume tabs, and
  44883. // default to tabs in the case of a tie (or nothing
  44884. // to go on)
  44885. if (tabbed.length >= spaced.length) {
  44886. return '\t';
  44887. }
  44888. // Otherwise, we need to guess the multiple
  44889. const min = spaced.reduce((previous, current) => {
  44890. const numSpaces = /^ +/.exec(current)[0].length;
  44891. return Math.min(numSpaces, previous);
  44892. }, Infinity);
  44893. return new Array(min + 1).join(' ');
  44894. }
  44895. function getRelativePath(from, to) {
  44896. const fromParts = from.split(/[/\\]/);
  44897. const toParts = to.split(/[/\\]/);
  44898. fromParts.pop(); // get dirname
  44899. while (fromParts[0] === toParts[0]) {
  44900. fromParts.shift();
  44901. toParts.shift();
  44902. }
  44903. if (fromParts.length) {
  44904. let i = fromParts.length;
  44905. while (i--) fromParts[i] = '..';
  44906. }
  44907. return fromParts.concat(toParts).join('/');
  44908. }
  44909. const toString = Object.prototype.toString;
  44910. function isObject(thing) {
  44911. return toString.call(thing) === '[object Object]';
  44912. }
  44913. function getLocator(source) {
  44914. const originalLines = source.split('\n');
  44915. const lineOffsets = [];
  44916. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  44917. lineOffsets.push(pos);
  44918. pos += originalLines[i].length + 1;
  44919. }
  44920. return function locate(index) {
  44921. let i = 0;
  44922. let j = lineOffsets.length;
  44923. while (i < j) {
  44924. const m = (i + j) >> 1;
  44925. if (index < lineOffsets[m]) {
  44926. j = m;
  44927. } else {
  44928. i = m + 1;
  44929. }
  44930. }
  44931. const line = i - 1;
  44932. const column = index - lineOffsets[line];
  44933. return { line, column };
  44934. };
  44935. }
  44936. const wordRegex = /\w/;
  44937. class Mappings {
  44938. constructor(hires) {
  44939. this.hires = hires;
  44940. this.generatedCodeLine = 0;
  44941. this.generatedCodeColumn = 0;
  44942. this.raw = [];
  44943. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  44944. this.pending = null;
  44945. }
  44946. addEdit(sourceIndex, content, loc, nameIndex) {
  44947. if (content.length) {
  44948. const contentLengthMinusOne = content.length - 1;
  44949. let contentLineEnd = content.indexOf('\n', 0);
  44950. let previousContentLineEnd = -1;
  44951. // Loop through each line in the content and add a segment, but stop if the last line is empty,
  44952. // else code afterwards would fill one line too many
  44953. while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
  44954. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  44955. if (nameIndex >= 0) {
  44956. segment.push(nameIndex);
  44957. }
  44958. this.rawSegments.push(segment);
  44959. this.generatedCodeLine += 1;
  44960. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  44961. this.generatedCodeColumn = 0;
  44962. previousContentLineEnd = contentLineEnd;
  44963. contentLineEnd = content.indexOf('\n', contentLineEnd + 1);
  44964. }
  44965. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  44966. if (nameIndex >= 0) {
  44967. segment.push(nameIndex);
  44968. }
  44969. this.rawSegments.push(segment);
  44970. this.advance(content.slice(previousContentLineEnd + 1));
  44971. } else if (this.pending) {
  44972. this.rawSegments.push(this.pending);
  44973. this.advance(content);
  44974. }
  44975. this.pending = null;
  44976. }
  44977. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  44978. let originalCharIndex = chunk.start;
  44979. let first = true;
  44980. // when iterating each char, check if it's in a word boundary
  44981. let charInHiresBoundary = false;
  44982. while (originalCharIndex < chunk.end) {
  44983. if (original[originalCharIndex] === '\n') {
  44984. loc.line += 1;
  44985. loc.column = 0;
  44986. this.generatedCodeLine += 1;
  44987. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  44988. this.generatedCodeColumn = 0;
  44989. first = true;
  44990. charInHiresBoundary = false;
  44991. } else {
  44992. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  44993. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  44994. if (this.hires === 'boundary') {
  44995. // in hires "boundary", group segments per word boundary than per char
  44996. if (wordRegex.test(original[originalCharIndex])) {
  44997. // for first char in the boundary found, start the boundary by pushing a segment
  44998. if (!charInHiresBoundary) {
  44999. this.rawSegments.push(segment);
  45000. charInHiresBoundary = true;
  45001. }
  45002. } else {
  45003. // for non-word char, end the boundary by pushing a segment
  45004. this.rawSegments.push(segment);
  45005. charInHiresBoundary = false;
  45006. }
  45007. } else {
  45008. this.rawSegments.push(segment);
  45009. }
  45010. }
  45011. loc.column += 1;
  45012. this.generatedCodeColumn += 1;
  45013. first = false;
  45014. }
  45015. originalCharIndex += 1;
  45016. }
  45017. this.pending = null;
  45018. }
  45019. advance(str) {
  45020. if (!str) return;
  45021. const lines = str.split('\n');
  45022. if (lines.length > 1) {
  45023. for (let i = 0; i < lines.length - 1; i++) {
  45024. this.generatedCodeLine++;
  45025. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  45026. }
  45027. this.generatedCodeColumn = 0;
  45028. }
  45029. this.generatedCodeColumn += lines[lines.length - 1].length;
  45030. }
  45031. }
  45032. const n = '\n';
  45033. const warned = {
  45034. insertLeft: false,
  45035. insertRight: false,
  45036. storeName: false,
  45037. };
  45038. class MagicString {
  45039. constructor(string, options = {}) {
  45040. const chunk = new Chunk(0, string.length, string);
  45041. Object.defineProperties(this, {
  45042. original: { writable: true, value: string },
  45043. outro: { writable: true, value: '' },
  45044. intro: { writable: true, value: '' },
  45045. firstChunk: { writable: true, value: chunk },
  45046. lastChunk: { writable: true, value: chunk },
  45047. lastSearchedChunk: { writable: true, value: chunk },
  45048. byStart: { writable: true, value: {} },
  45049. byEnd: { writable: true, value: {} },
  45050. filename: { writable: true, value: options.filename },
  45051. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  45052. sourcemapLocations: { writable: true, value: new BitSet() },
  45053. storedNames: { writable: true, value: {} },
  45054. indentStr: { writable: true, value: undefined },
  45055. ignoreList: { writable: true, value: options.ignoreList },
  45056. offset: { writable: true, value: options.offset || 0 },
  45057. });
  45058. this.byStart[0] = chunk;
  45059. this.byEnd[string.length] = chunk;
  45060. }
  45061. addSourcemapLocation(char) {
  45062. this.sourcemapLocations.add(char);
  45063. }
  45064. append(content) {
  45065. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  45066. this.outro += content;
  45067. return this;
  45068. }
  45069. appendLeft(index, content) {
  45070. index = index + this.offset;
  45071. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  45072. this._split(index);
  45073. const chunk = this.byEnd[index];
  45074. if (chunk) {
  45075. chunk.appendLeft(content);
  45076. } else {
  45077. this.intro += content;
  45078. }
  45079. return this;
  45080. }
  45081. appendRight(index, content) {
  45082. index = index + this.offset;
  45083. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  45084. this._split(index);
  45085. const chunk = this.byStart[index];
  45086. if (chunk) {
  45087. chunk.appendRight(content);
  45088. } else {
  45089. this.outro += content;
  45090. }
  45091. return this;
  45092. }
  45093. clone() {
  45094. const cloned = new MagicString(this.original, { filename: this.filename, offset: this.offset });
  45095. let originalChunk = this.firstChunk;
  45096. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  45097. while (originalChunk) {
  45098. cloned.byStart[clonedChunk.start] = clonedChunk;
  45099. cloned.byEnd[clonedChunk.end] = clonedChunk;
  45100. const nextOriginalChunk = originalChunk.next;
  45101. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  45102. if (nextClonedChunk) {
  45103. clonedChunk.next = nextClonedChunk;
  45104. nextClonedChunk.previous = clonedChunk;
  45105. clonedChunk = nextClonedChunk;
  45106. }
  45107. originalChunk = nextOriginalChunk;
  45108. }
  45109. cloned.lastChunk = clonedChunk;
  45110. if (this.indentExclusionRanges) {
  45111. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  45112. }
  45113. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  45114. cloned.intro = this.intro;
  45115. cloned.outro = this.outro;
  45116. return cloned;
  45117. }
  45118. generateDecodedMap(options) {
  45119. options = options || {};
  45120. const sourceIndex = 0;
  45121. const names = Object.keys(this.storedNames);
  45122. const mappings = new Mappings(options.hires);
  45123. const locate = getLocator(this.original);
  45124. if (this.intro) {
  45125. mappings.advance(this.intro);
  45126. }
  45127. this.firstChunk.eachNext((chunk) => {
  45128. const loc = locate(chunk.start);
  45129. if (chunk.intro.length) mappings.advance(chunk.intro);
  45130. if (chunk.edited) {
  45131. mappings.addEdit(
  45132. sourceIndex,
  45133. chunk.content,
  45134. loc,
  45135. chunk.storeName ? names.indexOf(chunk.original) : -1,
  45136. );
  45137. } else {
  45138. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  45139. }
  45140. if (chunk.outro.length) mappings.advance(chunk.outro);
  45141. });
  45142. if (this.outro) {
  45143. mappings.advance(this.outro);
  45144. }
  45145. return {
  45146. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  45147. sources: [
  45148. options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
  45149. ],
  45150. sourcesContent: options.includeContent ? [this.original] : undefined,
  45151. names,
  45152. mappings: mappings.raw,
  45153. x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
  45154. };
  45155. }
  45156. generateMap(options) {
  45157. return new SourceMap(this.generateDecodedMap(options));
  45158. }
  45159. _ensureindentStr() {
  45160. if (this.indentStr === undefined) {
  45161. this.indentStr = guessIndent(this.original);
  45162. }
  45163. }
  45164. _getRawIndentString() {
  45165. this._ensureindentStr();
  45166. return this.indentStr;
  45167. }
  45168. getIndentString() {
  45169. this._ensureindentStr();
  45170. return this.indentStr === null ? '\t' : this.indentStr;
  45171. }
  45172. indent(indentStr, options) {
  45173. const pattern = /^[^\r\n]/gm;
  45174. if (isObject(indentStr)) {
  45175. options = indentStr;
  45176. indentStr = undefined;
  45177. }
  45178. if (indentStr === undefined) {
  45179. this._ensureindentStr();
  45180. indentStr = this.indentStr || '\t';
  45181. }
  45182. if (indentStr === '') return this; // noop
  45183. options = options || {};
  45184. // Process exclusion ranges
  45185. const isExcluded = {};
  45186. if (options.exclude) {
  45187. const exclusions =
  45188. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  45189. exclusions.forEach((exclusion) => {
  45190. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  45191. isExcluded[i] = true;
  45192. }
  45193. });
  45194. }
  45195. let shouldIndentNextCharacter = options.indentStart !== false;
  45196. const replacer = (match) => {
  45197. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  45198. shouldIndentNextCharacter = true;
  45199. return match;
  45200. };
  45201. this.intro = this.intro.replace(pattern, replacer);
  45202. let charIndex = 0;
  45203. let chunk = this.firstChunk;
  45204. while (chunk) {
  45205. const end = chunk.end;
  45206. if (chunk.edited) {
  45207. if (!isExcluded[charIndex]) {
  45208. chunk.content = chunk.content.replace(pattern, replacer);
  45209. if (chunk.content.length) {
  45210. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  45211. }
  45212. }
  45213. } else {
  45214. charIndex = chunk.start;
  45215. while (charIndex < end) {
  45216. if (!isExcluded[charIndex]) {
  45217. const char = this.original[charIndex];
  45218. if (char === '\n') {
  45219. shouldIndentNextCharacter = true;
  45220. } else if (char !== '\r' && shouldIndentNextCharacter) {
  45221. shouldIndentNextCharacter = false;
  45222. if (charIndex === chunk.start) {
  45223. chunk.prependRight(indentStr);
  45224. } else {
  45225. this._splitChunk(chunk, charIndex);
  45226. chunk = chunk.next;
  45227. chunk.prependRight(indentStr);
  45228. }
  45229. }
  45230. }
  45231. charIndex += 1;
  45232. }
  45233. }
  45234. charIndex = chunk.end;
  45235. chunk = chunk.next;
  45236. }
  45237. this.outro = this.outro.replace(pattern, replacer);
  45238. return this;
  45239. }
  45240. insert() {
  45241. throw new Error(
  45242. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
  45243. );
  45244. }
  45245. insertLeft(index, content) {
  45246. if (!warned.insertLeft) {
  45247. console.warn(
  45248. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
  45249. );
  45250. warned.insertLeft = true;
  45251. }
  45252. return this.appendLeft(index, content);
  45253. }
  45254. insertRight(index, content) {
  45255. if (!warned.insertRight) {
  45256. console.warn(
  45257. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
  45258. );
  45259. warned.insertRight = true;
  45260. }
  45261. return this.prependRight(index, content);
  45262. }
  45263. move(start, end, index) {
  45264. start = start + this.offset;
  45265. end = end + this.offset;
  45266. index = index + this.offset;
  45267. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  45268. this._split(start);
  45269. this._split(end);
  45270. this._split(index);
  45271. const first = this.byStart[start];
  45272. const last = this.byEnd[end];
  45273. const oldLeft = first.previous;
  45274. const oldRight = last.next;
  45275. const newRight = this.byStart[index];
  45276. if (!newRight && last === this.lastChunk) return this;
  45277. const newLeft = newRight ? newRight.previous : this.lastChunk;
  45278. if (oldLeft) oldLeft.next = oldRight;
  45279. if (oldRight) oldRight.previous = oldLeft;
  45280. if (newLeft) newLeft.next = first;
  45281. if (newRight) newRight.previous = last;
  45282. if (!first.previous) this.firstChunk = last.next;
  45283. if (!last.next) {
  45284. this.lastChunk = first.previous;
  45285. this.lastChunk.next = null;
  45286. }
  45287. first.previous = newLeft;
  45288. last.next = newRight || null;
  45289. if (!newLeft) this.firstChunk = first;
  45290. if (!newRight) this.lastChunk = last;
  45291. return this;
  45292. }
  45293. overwrite(start, end, content, options) {
  45294. options = options || {};
  45295. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  45296. }
  45297. update(start, end, content, options) {
  45298. start = start + this.offset;
  45299. end = end + this.offset;
  45300. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  45301. if (this.original.length !== 0) {
  45302. while (start < 0) start += this.original.length;
  45303. while (end < 0) end += this.original.length;
  45304. }
  45305. if (end > this.original.length) throw new Error('end is out of bounds');
  45306. if (start === end)
  45307. throw new Error(
  45308. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
  45309. );
  45310. this._split(start);
  45311. this._split(end);
  45312. if (options === true) {
  45313. if (!warned.storeName) {
  45314. console.warn(
  45315. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
  45316. );
  45317. warned.storeName = true;
  45318. }
  45319. options = { storeName: true };
  45320. }
  45321. const storeName = options !== undefined ? options.storeName : false;
  45322. const overwrite = options !== undefined ? options.overwrite : false;
  45323. if (storeName) {
  45324. const original = this.original.slice(start, end);
  45325. Object.defineProperty(this.storedNames, original, {
  45326. writable: true,
  45327. value: true,
  45328. enumerable: true,
  45329. });
  45330. }
  45331. const first = this.byStart[start];
  45332. const last = this.byEnd[end];
  45333. if (first) {
  45334. let chunk = first;
  45335. while (chunk !== last) {
  45336. if (chunk.next !== this.byStart[chunk.end]) {
  45337. throw new Error('Cannot overwrite across a split point');
  45338. }
  45339. chunk = chunk.next;
  45340. chunk.edit('', false);
  45341. }
  45342. first.edit(content, storeName, !overwrite);
  45343. } else {
  45344. // must be inserting at the end
  45345. const newChunk = new Chunk(start, end, '').edit(content, storeName);
  45346. // TODO last chunk in the array may not be the last chunk, if it's moved...
  45347. last.next = newChunk;
  45348. newChunk.previous = last;
  45349. }
  45350. return this;
  45351. }
  45352. prepend(content) {
  45353. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  45354. this.intro = content + this.intro;
  45355. return this;
  45356. }
  45357. prependLeft(index, content) {
  45358. index = index + this.offset;
  45359. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  45360. this._split(index);
  45361. const chunk = this.byEnd[index];
  45362. if (chunk) {
  45363. chunk.prependLeft(content);
  45364. } else {
  45365. this.intro = content + this.intro;
  45366. }
  45367. return this;
  45368. }
  45369. prependRight(index, content) {
  45370. index = index + this.offset;
  45371. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  45372. this._split(index);
  45373. const chunk = this.byStart[index];
  45374. if (chunk) {
  45375. chunk.prependRight(content);
  45376. } else {
  45377. this.outro = content + this.outro;
  45378. }
  45379. return this;
  45380. }
  45381. remove(start, end) {
  45382. start = start + this.offset;
  45383. end = end + this.offset;
  45384. if (this.original.length !== 0) {
  45385. while (start < 0) start += this.original.length;
  45386. while (end < 0) end += this.original.length;
  45387. }
  45388. if (start === end) return this;
  45389. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  45390. if (start > end) throw new Error('end must be greater than start');
  45391. this._split(start);
  45392. this._split(end);
  45393. let chunk = this.byStart[start];
  45394. while (chunk) {
  45395. chunk.intro = '';
  45396. chunk.outro = '';
  45397. chunk.edit('');
  45398. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  45399. }
  45400. return this;
  45401. }
  45402. reset(start, end) {
  45403. start = start + this.offset;
  45404. end = end + this.offset;
  45405. if (this.original.length !== 0) {
  45406. while (start < 0) start += this.original.length;
  45407. while (end < 0) end += this.original.length;
  45408. }
  45409. if (start === end) return this;
  45410. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  45411. if (start > end) throw new Error('end must be greater than start');
  45412. this._split(start);
  45413. this._split(end);
  45414. let chunk = this.byStart[start];
  45415. while (chunk) {
  45416. chunk.reset();
  45417. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  45418. }
  45419. return this;
  45420. }
  45421. lastChar() {
  45422. if (this.outro.length) return this.outro[this.outro.length - 1];
  45423. let chunk = this.lastChunk;
  45424. do {
  45425. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  45426. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  45427. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  45428. } while ((chunk = chunk.previous));
  45429. if (this.intro.length) return this.intro[this.intro.length - 1];
  45430. return '';
  45431. }
  45432. lastLine() {
  45433. let lineIndex = this.outro.lastIndexOf(n);
  45434. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  45435. let lineStr = this.outro;
  45436. let chunk = this.lastChunk;
  45437. do {
  45438. if (chunk.outro.length > 0) {
  45439. lineIndex = chunk.outro.lastIndexOf(n);
  45440. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  45441. lineStr = chunk.outro + lineStr;
  45442. }
  45443. if (chunk.content.length > 0) {
  45444. lineIndex = chunk.content.lastIndexOf(n);
  45445. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  45446. lineStr = chunk.content + lineStr;
  45447. }
  45448. if (chunk.intro.length > 0) {
  45449. lineIndex = chunk.intro.lastIndexOf(n);
  45450. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  45451. lineStr = chunk.intro + lineStr;
  45452. }
  45453. } while ((chunk = chunk.previous));
  45454. lineIndex = this.intro.lastIndexOf(n);
  45455. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  45456. return this.intro + lineStr;
  45457. }
  45458. slice(start = 0, end = this.original.length - this.offset) {
  45459. start = start + this.offset;
  45460. end = end + this.offset;
  45461. if (this.original.length !== 0) {
  45462. while (start < 0) start += this.original.length;
  45463. while (end < 0) end += this.original.length;
  45464. }
  45465. let result = '';
  45466. // find start chunk
  45467. let chunk = this.firstChunk;
  45468. while (chunk && (chunk.start > start || chunk.end <= start)) {
  45469. // found end chunk before start
  45470. if (chunk.start < end && chunk.end >= end) {
  45471. return result;
  45472. }
  45473. chunk = chunk.next;
  45474. }
  45475. if (chunk && chunk.edited && chunk.start !== start)
  45476. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  45477. const startChunk = chunk;
  45478. while (chunk) {
  45479. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  45480. result += chunk.intro;
  45481. }
  45482. const containsEnd = chunk.start < end && chunk.end >= end;
  45483. if (containsEnd && chunk.edited && chunk.end !== end)
  45484. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  45485. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  45486. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  45487. result += chunk.content.slice(sliceStart, sliceEnd);
  45488. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  45489. result += chunk.outro;
  45490. }
  45491. if (containsEnd) {
  45492. break;
  45493. }
  45494. chunk = chunk.next;
  45495. }
  45496. return result;
  45497. }
  45498. // TODO deprecate this? not really very useful
  45499. snip(start, end) {
  45500. const clone = this.clone();
  45501. clone.remove(0, start);
  45502. clone.remove(end, clone.original.length);
  45503. return clone;
  45504. }
  45505. _split(index) {
  45506. if (this.byStart[index] || this.byEnd[index]) return;
  45507. let chunk = this.lastSearchedChunk;
  45508. let previousChunk = chunk;
  45509. const searchForward = index > chunk.end;
  45510. while (chunk) {
  45511. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  45512. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  45513. // Prevent infinite loop (e.g. via empty chunks, where start === end)
  45514. if (chunk === previousChunk) return;
  45515. previousChunk = chunk;
  45516. }
  45517. }
  45518. _splitChunk(chunk, index) {
  45519. if (chunk.edited && chunk.content.length) {
  45520. // zero-length edited chunks are a special case (overlapping replacements)
  45521. const loc = getLocator(this.original)(index);
  45522. throw new Error(
  45523. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
  45524. );
  45525. }
  45526. const newChunk = chunk.split(index);
  45527. this.byEnd[index] = chunk;
  45528. this.byStart[index] = newChunk;
  45529. this.byEnd[newChunk.end] = newChunk;
  45530. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  45531. this.lastSearchedChunk = chunk;
  45532. return true;
  45533. }
  45534. toString() {
  45535. let str = this.intro;
  45536. let chunk = this.firstChunk;
  45537. while (chunk) {
  45538. str += chunk.toString();
  45539. chunk = chunk.next;
  45540. }
  45541. return str + this.outro;
  45542. }
  45543. isEmpty() {
  45544. let chunk = this.firstChunk;
  45545. do {
  45546. if (
  45547. (chunk.intro.length && chunk.intro.trim()) ||
  45548. (chunk.content.length && chunk.content.trim()) ||
  45549. (chunk.outro.length && chunk.outro.trim())
  45550. )
  45551. return false;
  45552. } while ((chunk = chunk.next));
  45553. return true;
  45554. }
  45555. length() {
  45556. let chunk = this.firstChunk;
  45557. let length = 0;
  45558. do {
  45559. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  45560. } while ((chunk = chunk.next));
  45561. return length;
  45562. }
  45563. trimLines() {
  45564. return this.trim('[\\r\\n]');
  45565. }
  45566. trim(charType) {
  45567. return this.trimStart(charType).trimEnd(charType);
  45568. }
  45569. trimEndAborted(charType) {
  45570. const rx = new RegExp((charType || '\\s') + '+$');
  45571. this.outro = this.outro.replace(rx, '');
  45572. if (this.outro.length) return true;
  45573. let chunk = this.lastChunk;
  45574. do {
  45575. const end = chunk.end;
  45576. const aborted = chunk.trimEnd(rx);
  45577. // if chunk was trimmed, we have a new lastChunk
  45578. if (chunk.end !== end) {
  45579. if (this.lastChunk === chunk) {
  45580. this.lastChunk = chunk.next;
  45581. }
  45582. this.byEnd[chunk.end] = chunk;
  45583. this.byStart[chunk.next.start] = chunk.next;
  45584. this.byEnd[chunk.next.end] = chunk.next;
  45585. }
  45586. if (aborted) return true;
  45587. chunk = chunk.previous;
  45588. } while (chunk);
  45589. return false;
  45590. }
  45591. trimEnd(charType) {
  45592. this.trimEndAborted(charType);
  45593. return this;
  45594. }
  45595. trimStartAborted(charType) {
  45596. const rx = new RegExp('^' + (charType || '\\s') + '+');
  45597. this.intro = this.intro.replace(rx, '');
  45598. if (this.intro.length) return true;
  45599. let chunk = this.firstChunk;
  45600. do {
  45601. const end = chunk.end;
  45602. const aborted = chunk.trimStart(rx);
  45603. if (chunk.end !== end) {
  45604. // special case...
  45605. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  45606. this.byEnd[chunk.end] = chunk;
  45607. this.byStart[chunk.next.start] = chunk.next;
  45608. this.byEnd[chunk.next.end] = chunk.next;
  45609. }
  45610. if (aborted) return true;
  45611. chunk = chunk.next;
  45612. } while (chunk);
  45613. return false;
  45614. }
  45615. trimStart(charType) {
  45616. this.trimStartAborted(charType);
  45617. return this;
  45618. }
  45619. hasChanged() {
  45620. return this.original !== this.toString();
  45621. }
  45622. _replaceRegexp(searchValue, replacement) {
  45623. function getReplacement(match, str) {
  45624. if (typeof replacement === 'string') {
  45625. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  45626. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  45627. if (i === '$') return '$';
  45628. if (i === '&') return match[0];
  45629. const num = +i;
  45630. if (num < match.length) return match[+i];
  45631. return `$${i}`;
  45632. });
  45633. } else {
  45634. return replacement(...match, match.index, str, match.groups);
  45635. }
  45636. }
  45637. function matchAll(re, str) {
  45638. let match;
  45639. const matches = [];
  45640. while ((match = re.exec(str))) {
  45641. matches.push(match);
  45642. }
  45643. return matches;
  45644. }
  45645. if (searchValue.global) {
  45646. const matches = matchAll(searchValue, this.original);
  45647. matches.forEach((match) => {
  45648. if (match.index != null) {
  45649. const replacement = getReplacement(match, this.original);
  45650. if (replacement !== match[0]) {
  45651. this.overwrite(match.index, match.index + match[0].length, replacement);
  45652. }
  45653. }
  45654. });
  45655. } else {
  45656. const match = this.original.match(searchValue);
  45657. if (match && match.index != null) {
  45658. const replacement = getReplacement(match, this.original);
  45659. if (replacement !== match[0]) {
  45660. this.overwrite(match.index, match.index + match[0].length, replacement);
  45661. }
  45662. }
  45663. }
  45664. return this;
  45665. }
  45666. _replaceString(string, replacement) {
  45667. const { original } = this;
  45668. const index = original.indexOf(string);
  45669. if (index !== -1) {
  45670. if (typeof replacement === 'function') {
  45671. replacement = replacement(string, index, original);
  45672. }
  45673. if (string !== replacement) {
  45674. this.overwrite(index, index + string.length, replacement);
  45675. }
  45676. }
  45677. return this;
  45678. }
  45679. replace(searchValue, replacement) {
  45680. if (typeof searchValue === 'string') {
  45681. return this._replaceString(searchValue, replacement);
  45682. }
  45683. return this._replaceRegexp(searchValue, replacement);
  45684. }
  45685. _replaceAllString(string, replacement) {
  45686. const { original } = this;
  45687. const stringLength = string.length;
  45688. for (
  45689. let index = original.indexOf(string);
  45690. index !== -1;
  45691. index = original.indexOf(string, index + stringLength)
  45692. ) {
  45693. const previous = original.slice(index, index + stringLength);
  45694. let _replacement = replacement;
  45695. if (typeof replacement === 'function') {
  45696. _replacement = replacement(previous, index, original);
  45697. }
  45698. if (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement);
  45699. }
  45700. return this;
  45701. }
  45702. replaceAll(searchValue, replacement) {
  45703. if (typeof searchValue === 'string') {
  45704. return this._replaceAllString(searchValue, replacement);
  45705. }
  45706. if (!searchValue.global) {
  45707. throw new TypeError(
  45708. 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
  45709. );
  45710. }
  45711. return this._replaceRegexp(searchValue, replacement);
  45712. }
  45713. }
  45714. var _a, _b;
  45715. class ScriptCompileContext {
  45716. constructor(descriptor, options) {
  45717. this.descriptor = descriptor;
  45718. this.options = options;
  45719. this.isCE = false;
  45720. this.source = this.descriptor.source;
  45721. this.filename = this.descriptor.filename;
  45722. this.s = new MagicString(this.source);
  45723. this.startOffset = (_a = this.descriptor.scriptSetup) == null ? void 0 : _a.loc.start.offset;
  45724. this.endOffset = (_b = this.descriptor.scriptSetup) == null ? void 0 : _b.loc.end.offset;
  45725. this.userImports = /* @__PURE__ */ Object.create(null);
  45726. // macros presence check
  45727. this.hasDefinePropsCall = false;
  45728. this.hasDefineEmitCall = false;
  45729. this.hasDefineExposeCall = false;
  45730. this.hasDefaultExportName = false;
  45731. this.hasDefaultExportRender = false;
  45732. this.hasDefineOptionsCall = false;
  45733. this.hasDefineSlotsCall = false;
  45734. this.hasDefineModelCall = false;
  45735. this.propsDestructuredBindings = /* @__PURE__ */ Object.create(null);
  45736. // defineModel
  45737. this.modelDecls = /* @__PURE__ */ Object.create(null);
  45738. // codegen
  45739. this.bindingMetadata = {};
  45740. this.helperImports = /* @__PURE__ */ new Set();
  45741. const { script, scriptSetup } = descriptor;
  45742. const scriptLang = script && script.lang;
  45743. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  45744. this.isJS = isJS(scriptLang, scriptSetupLang);
  45745. this.isTS = isTS(scriptLang, scriptSetupLang);
  45746. const customElement = options.customElement;
  45747. const filename = this.descriptor.filename;
  45748. if (customElement) {
  45749. this.isCE = typeof customElement === "boolean" ? customElement : customElement(filename);
  45750. }
  45751. const plugins = resolveParserPlugins(
  45752. scriptLang || scriptSetupLang,
  45753. options.babelParserPlugins
  45754. );
  45755. function parse(input, offset) {
  45756. try {
  45757. return libExports.parse(input, {
  45758. plugins,
  45759. sourceType: "module"
  45760. }).program;
  45761. } catch (e) {
  45762. e.message = `[vue/compiler-sfc] ${e.message}
  45763. ${descriptor.filename}
  45764. ${generateCodeFrame(
  45765. descriptor.source,
  45766. e.pos + offset,
  45767. e.pos + offset + 1
  45768. )}`;
  45769. throw e;
  45770. }
  45771. }
  45772. this.scriptAst = descriptor.script && parse(descriptor.script.content, descriptor.script.loc.start.offset);
  45773. this.scriptSetupAst = descriptor.scriptSetup && parse(descriptor.scriptSetup.content, this.startOffset);
  45774. }
  45775. helper(key) {
  45776. this.helperImports.add(key);
  45777. return `_${key}`;
  45778. }
  45779. getString(node, scriptSetup = true) {
  45780. const block = scriptSetup ? this.descriptor.scriptSetup : this.descriptor.script;
  45781. return block.content.slice(node.start, node.end);
  45782. }
  45783. warn(msg, node, scope) {
  45784. warn(generateError(msg, node, this, scope));
  45785. }
  45786. error(msg, node, scope) {
  45787. throw new Error(
  45788. `[@vue/compiler-sfc] ${generateError(msg, node, this, scope)}`
  45789. );
  45790. }
  45791. }
  45792. function generateError(msg, node, ctx, scope) {
  45793. const offset = scope ? scope.offset : ctx.startOffset;
  45794. return `${msg}
  45795. ${(scope || ctx.descriptor).filename}
  45796. ${generateCodeFrame(
  45797. (scope || ctx.descriptor).source,
  45798. node.start + offset,
  45799. node.end + offset
  45800. )}`;
  45801. }
  45802. function resolveParserPlugins(lang, userPlugins, dts = false) {
  45803. const plugins = [];
  45804. if (!userPlugins || !userPlugins.some(
  45805. (p) => p === "importAssertions" || p === "importAttributes" || isArray$3(p) && p[0] === "importAttributes"
  45806. )) {
  45807. plugins.push("importAttributes");
  45808. }
  45809. if (lang === "jsx" || lang === "tsx" || lang === "mtsx") {
  45810. plugins.push("jsx");
  45811. } else if (userPlugins) {
  45812. userPlugins = userPlugins.filter((p) => p !== "jsx");
  45813. }
  45814. if (lang === "ts" || lang === "mts" || lang === "tsx" || lang === "cts" || lang === "mtsx") {
  45815. plugins.push(["typescript", { dts }], "explicitResourceManagement");
  45816. if (!userPlugins || !userPlugins.includes("decorators")) {
  45817. plugins.push("decorators-legacy");
  45818. }
  45819. }
  45820. if (userPlugins) {
  45821. plugins.push(...userPlugins);
  45822. }
  45823. return plugins;
  45824. }
  45825. function rewriteDefault(input, as, parserPlugins) {
  45826. const ast = libExports.parse(input, {
  45827. sourceType: "module",
  45828. plugins: resolveParserPlugins("js", parserPlugins)
  45829. }).program.body;
  45830. const s = new MagicString(input);
  45831. rewriteDefaultAST(ast, s, as);
  45832. return s.toString();
  45833. }
  45834. function rewriteDefaultAST(ast, s, as) {
  45835. if (!hasDefaultExport(ast)) {
  45836. s.append(`
  45837. const ${as} = {}`);
  45838. return;
  45839. }
  45840. ast.forEach((node) => {
  45841. if (node.type === "ExportDefaultDeclaration") {
  45842. if (node.declaration.type === "ClassDeclaration" && node.declaration.id) {
  45843. const start = node.declaration.decorators && node.declaration.decorators.length > 0 ? node.declaration.decorators[node.declaration.decorators.length - 1].end : node.start;
  45844. s.overwrite(start, node.declaration.id.start, ` class `);
  45845. s.append(`
  45846. const ${as} = ${node.declaration.id.name}`);
  45847. } else {
  45848. s.overwrite(node.start, node.declaration.start, `const ${as} = `);
  45849. }
  45850. } else if (node.type === "ExportNamedDeclaration") {
  45851. for (const specifier of node.specifiers) {
  45852. if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier" && specifier.exported.name === "default") {
  45853. if (node.source) {
  45854. if (specifier.local.name === "default") {
  45855. s.prepend(
  45856. `import { default as __VUE_DEFAULT__ } from '${node.source.value}'
  45857. `
  45858. );
  45859. const end2 = specifierEnd(s, specifier.local.end, node.end);
  45860. s.remove(specifier.start, end2);
  45861. s.append(`
  45862. const ${as} = __VUE_DEFAULT__`);
  45863. continue;
  45864. } else {
  45865. s.prepend(
  45866. `import { ${s.slice(
  45867. specifier.local.start,
  45868. specifier.local.end
  45869. )} as __VUE_DEFAULT__ } from '${node.source.value}'
  45870. `
  45871. );
  45872. const end2 = specifierEnd(s, specifier.exported.end, node.end);
  45873. s.remove(specifier.start, end2);
  45874. s.append(`
  45875. const ${as} = __VUE_DEFAULT__`);
  45876. continue;
  45877. }
  45878. }
  45879. const end = specifierEnd(s, specifier.end, node.end);
  45880. s.remove(specifier.start, end);
  45881. s.append(`
  45882. const ${as} = ${specifier.local.name}`);
  45883. }
  45884. }
  45885. }
  45886. });
  45887. }
  45888. function hasDefaultExport(ast) {
  45889. for (const stmt of ast) {
  45890. if (stmt.type === "ExportDefaultDeclaration") {
  45891. return true;
  45892. } else if (stmt.type === "ExportNamedDeclaration" && stmt.specifiers.some(
  45893. (spec) => spec.exported.name === "default"
  45894. )) {
  45895. return true;
  45896. }
  45897. }
  45898. return false;
  45899. }
  45900. function specifierEnd(s, end, nodeEnd) {
  45901. let hasCommas = false;
  45902. let oldEnd = end;
  45903. while (end < nodeEnd) {
  45904. if (/\s/.test(s.slice(end, end + 1))) {
  45905. end++;
  45906. } else if (s.slice(end, end + 1) === ",") {
  45907. end++;
  45908. hasCommas = true;
  45909. break;
  45910. } else if (s.slice(end, end + 1) === "}") {
  45911. break;
  45912. }
  45913. }
  45914. return hasCommas ? end : oldEnd;
  45915. }
  45916. var __defProp$3 = Object.defineProperty;
  45917. var __defProps$2 = Object.defineProperties;
  45918. var __getOwnPropDescs$2 = Object.getOwnPropertyDescriptors;
  45919. var __getOwnPropSymbols$3 = Object.getOwnPropertySymbols;
  45920. var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
  45921. var __propIsEnum$3 = Object.prototype.propertyIsEnumerable;
  45922. var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  45923. var __spreadValues$3 = (a, b) => {
  45924. for (var prop in b || (b = {}))
  45925. if (__hasOwnProp$3.call(b, prop))
  45926. __defNormalProp$3(a, prop, b[prop]);
  45927. if (__getOwnPropSymbols$3)
  45928. for (var prop of __getOwnPropSymbols$3(b)) {
  45929. if (__propIsEnum$3.call(b, prop))
  45930. __defNormalProp$3(a, prop, b[prop]);
  45931. }
  45932. return a;
  45933. };
  45934. var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
  45935. const normalScriptDefaultVar = `__default__`;
  45936. function processNormalScript(ctx, scopeId) {
  45937. var _a;
  45938. const script = ctx.descriptor.script;
  45939. try {
  45940. let content = script.content;
  45941. let map = script.map;
  45942. const scriptAst = ctx.scriptAst;
  45943. const bindings = analyzeScriptBindings(scriptAst.body);
  45944. const { cssVars } = ctx.descriptor;
  45945. const { genDefaultAs, isProd } = ctx.options;
  45946. if (cssVars.length || genDefaultAs) {
  45947. const defaultVar = genDefaultAs || normalScriptDefaultVar;
  45948. const s = new MagicString(content);
  45949. rewriteDefaultAST(scriptAst.body, s, defaultVar);
  45950. content = s.toString();
  45951. if (cssVars.length && !((_a = ctx.options.templateOptions) == null ? void 0 : _a.ssr)) {
  45952. content += genNormalScriptCssVarsCode(
  45953. cssVars,
  45954. bindings,
  45955. scopeId,
  45956. !!isProd,
  45957. defaultVar
  45958. );
  45959. }
  45960. if (!genDefaultAs) {
  45961. content += `
  45962. export default ${defaultVar}`;
  45963. }
  45964. }
  45965. return __spreadProps$2(__spreadValues$3({}, script), {
  45966. content,
  45967. map,
  45968. bindings,
  45969. scriptAst: scriptAst.body
  45970. });
  45971. } catch (e) {
  45972. return script;
  45973. }
  45974. }
  45975. var __defProp$2 = Object.defineProperty;
  45976. var __defProps$1 = Object.defineProperties;
  45977. var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
  45978. var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols;
  45979. var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
  45980. var __propIsEnum$2 = Object.prototype.propertyIsEnumerable;
  45981. var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  45982. var __spreadValues$2 = (a, b) => {
  45983. for (var prop in b || (b = {}))
  45984. if (__hasOwnProp$2.call(b, prop))
  45985. __defNormalProp$2(a, prop, b[prop]);
  45986. if (__getOwnPropSymbols$2)
  45987. for (var prop of __getOwnPropSymbols$2(b)) {
  45988. if (__propIsEnum$2.call(b, prop))
  45989. __defNormalProp$2(a, prop, b[prop]);
  45990. }
  45991. return a;
  45992. };
  45993. var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
  45994. class TypeScope {
  45995. constructor(filename, source, offset = 0, imports = /* @__PURE__ */ Object.create(null), types = /* @__PURE__ */ Object.create(null), declares = /* @__PURE__ */ Object.create(null)) {
  45996. this.filename = filename;
  45997. this.source = source;
  45998. this.offset = offset;
  45999. this.imports = imports;
  46000. this.types = types;
  46001. this.declares = declares;
  46002. this.isGenericScope = false;
  46003. this.resolvedImportSources = /* @__PURE__ */ Object.create(null);
  46004. this.exportedTypes = /* @__PURE__ */ Object.create(null);
  46005. this.exportedDeclares = /* @__PURE__ */ Object.create(null);
  46006. }
  46007. }
  46008. function recordScopeDep(ctx, scope) {
  46009. if (scope && scope.filename !== ctx.filename) {
  46010. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(scope.filename);
  46011. }
  46012. }
  46013. function recordResolvedElementDeps(ctx, { props }) {
  46014. for (const key in props) {
  46015. recordScopeDep(ctx, props[key]._ownerScope);
  46016. }
  46017. }
  46018. function resolveTypeElements(ctx, node, scope, typeParameters) {
  46019. const canCache = !typeParameters;
  46020. if (canCache && node._resolvedElements) {
  46021. recordResolvedElementDeps(ctx, node._resolvedElements);
  46022. return node._resolvedElements;
  46023. }
  46024. const resolved = innerResolveTypeElements(
  46025. ctx,
  46026. node,
  46027. node._ownerScope || scope || ctxToScope(ctx),
  46028. typeParameters
  46029. );
  46030. return canCache ? node._resolvedElements = resolved : resolved;
  46031. }
  46032. function innerResolveTypeElements(ctx, node, scope, typeParameters) {
  46033. var _a, _b;
  46034. if (hasVueIgnore(node)) {
  46035. if ((node.type === "TSIntersectionType" || node.type === "TSUnionType") && node.types.length > 1) {
  46036. return mergeElements(
  46037. [
  46038. { props: {} },
  46039. ...node.types.slice(1).map((t) => resolveTypeElements(ctx, t, scope, typeParameters))
  46040. ],
  46041. node.type
  46042. );
  46043. }
  46044. return { props: {} };
  46045. }
  46046. switch (node.type) {
  46047. case "TSTypeLiteral":
  46048. return typeElementsToMap(ctx, node.members, scope, typeParameters);
  46049. case "TSInterfaceDeclaration":
  46050. return resolveInterfaceMembers(ctx, node, scope, typeParameters);
  46051. case "TSTypeAliasDeclaration":
  46052. case "TSTypeAnnotation":
  46053. case "TSParenthesizedType":
  46054. return resolveTypeElements(
  46055. ctx,
  46056. node.typeAnnotation,
  46057. scope,
  46058. typeParameters
  46059. );
  46060. case "TSFunctionType": {
  46061. return { props: {}, calls: [node] };
  46062. }
  46063. case "TSUnionType":
  46064. case "TSIntersectionType":
  46065. return mergeElements(
  46066. node.types.map((t) => resolveTypeElements(ctx, t, scope, typeParameters)),
  46067. node.type
  46068. );
  46069. case "TSMappedType":
  46070. return resolveMappedType(ctx, node, scope, typeParameters);
  46071. case "TSIndexedAccessType": {
  46072. const types = resolveIndexType(ctx, node, scope);
  46073. return mergeElements(
  46074. types.map((t) => resolveTypeElements(ctx, t, t._ownerScope)),
  46075. "TSUnionType"
  46076. );
  46077. }
  46078. case "TSExpressionWithTypeArguments":
  46079. // referenced by interface extends
  46080. case "TSTypeReference": {
  46081. const typeName = getReferenceName(node);
  46082. if ((typeName === "ExtractPropTypes" || typeName === "ExtractPublicPropTypes") && node.typeParameters && ((_a = scope.imports[typeName]) == null ? void 0 : _a.source) === "vue") {
  46083. return resolveExtractPropTypes(
  46084. resolveTypeElements(
  46085. ctx,
  46086. node.typeParameters.params[0],
  46087. scope,
  46088. typeParameters
  46089. ),
  46090. scope
  46091. );
  46092. }
  46093. const resolved = resolveTypeReference(ctx, node, scope);
  46094. if (resolved) {
  46095. let typeParams;
  46096. if ((resolved.type === "TSTypeAliasDeclaration" || resolved.type === "TSInterfaceDeclaration") && resolved.typeParameters && node.typeParameters) {
  46097. typeParams = /* @__PURE__ */ Object.create(null);
  46098. resolved.typeParameters.params.forEach((p, i) => {
  46099. let param = typeParameters && typeParameters[p.name];
  46100. if (!param) param = node.typeParameters.params[i];
  46101. typeParams[p.name] = param;
  46102. });
  46103. }
  46104. return resolveTypeElements(
  46105. ctx,
  46106. resolved,
  46107. resolved._ownerScope,
  46108. typeParams
  46109. );
  46110. } else {
  46111. if (typeof typeName === "string") {
  46112. if (typeParameters && typeParameters[typeName]) {
  46113. return resolveTypeElements(
  46114. ctx,
  46115. typeParameters[typeName],
  46116. scope,
  46117. typeParameters
  46118. );
  46119. }
  46120. if (
  46121. // @ts-expect-error
  46122. SupportedBuiltinsSet.has(typeName)
  46123. ) {
  46124. return resolveBuiltin(
  46125. ctx,
  46126. node,
  46127. typeName,
  46128. scope,
  46129. typeParameters
  46130. );
  46131. } else if (typeName === "ReturnType" && node.typeParameters) {
  46132. const ret = resolveReturnType(
  46133. ctx,
  46134. node.typeParameters.params[0],
  46135. scope
  46136. );
  46137. if (ret) {
  46138. return resolveTypeElements(ctx, ret, scope);
  46139. }
  46140. }
  46141. }
  46142. return ctx.error(
  46143. `Unresolvable type reference or unsupported built-in utility type`,
  46144. node,
  46145. scope
  46146. );
  46147. }
  46148. }
  46149. case "TSImportType": {
  46150. if (getId(node.argument) === "vue" && ((_b = node.qualifier) == null ? void 0 : _b.type) === "Identifier" && node.qualifier.name === "ExtractPropTypes" && node.typeParameters) {
  46151. return resolveExtractPropTypes(
  46152. resolveTypeElements(ctx, node.typeParameters.params[0], scope),
  46153. scope
  46154. );
  46155. }
  46156. const sourceScope = importSourceToScope(
  46157. ctx,
  46158. node.argument,
  46159. scope,
  46160. node.argument.value
  46161. );
  46162. const resolved = resolveTypeReference(ctx, node, sourceScope);
  46163. if (resolved) {
  46164. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  46165. }
  46166. break;
  46167. }
  46168. case "TSTypeQuery":
  46169. {
  46170. const resolved = resolveTypeReference(ctx, node, scope);
  46171. if (resolved) {
  46172. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  46173. }
  46174. }
  46175. break;
  46176. }
  46177. return ctx.error(`Unresolvable type: ${node.type}`, node, scope);
  46178. }
  46179. function typeElementsToMap(ctx, elements, scope = ctxToScope(ctx), typeParameters) {
  46180. const res = { props: {} };
  46181. for (const e of elements) {
  46182. if (e.type === "TSPropertySignature" || e.type === "TSMethodSignature") {
  46183. if (typeParameters) {
  46184. scope = createChildScope(scope);
  46185. scope.isGenericScope = true;
  46186. Object.assign(scope.types, typeParameters);
  46187. }
  46188. e._ownerScope = scope;
  46189. const name = getStringLiteralKey(e);
  46190. if (name !== null) {
  46191. res.props[name] = e;
  46192. } else {
  46193. ctx.error(
  46194. `Unsupported computed key in type referenced by a macro`,
  46195. e.key,
  46196. scope
  46197. );
  46198. }
  46199. } else if (e.type === "TSCallSignatureDeclaration") {
  46200. (res.calls || (res.calls = [])).push(e);
  46201. }
  46202. }
  46203. return res;
  46204. }
  46205. function hasVueIgnore(node) {
  46206. return !!(node.leadingComments && node.leadingComments.some((c) => c.value.includes("@vue-ignore")));
  46207. }
  46208. function mergeElements(maps, type) {
  46209. if (maps.length === 1) return maps[0];
  46210. const res = { props: {} };
  46211. const { props: baseProps } = res;
  46212. for (const { props, calls } of maps) {
  46213. for (const key in props) {
  46214. if (!hasOwn(baseProps, key)) {
  46215. baseProps[key] = props[key];
  46216. } else {
  46217. baseProps[key] = createProperty(
  46218. baseProps[key].key,
  46219. {
  46220. type,
  46221. // @ts-expect-error
  46222. types: [baseProps[key], props[key]]
  46223. },
  46224. baseProps[key]._ownerScope,
  46225. baseProps[key].optional || props[key].optional
  46226. );
  46227. }
  46228. }
  46229. if (calls) {
  46230. (res.calls || (res.calls = [])).push(...calls);
  46231. }
  46232. }
  46233. return res;
  46234. }
  46235. function createProperty(key, typeAnnotation, scope, optional) {
  46236. return {
  46237. type: "TSPropertySignature",
  46238. key,
  46239. kind: "get",
  46240. optional,
  46241. typeAnnotation: {
  46242. type: "TSTypeAnnotation",
  46243. typeAnnotation
  46244. },
  46245. _ownerScope: scope
  46246. };
  46247. }
  46248. function resolveInterfaceMembers(ctx, node, scope, typeParameters) {
  46249. const base = typeElementsToMap(
  46250. ctx,
  46251. node.body.body,
  46252. node._ownerScope,
  46253. typeParameters
  46254. );
  46255. if (node.extends) {
  46256. for (const ext of node.extends) {
  46257. try {
  46258. const { props, calls } = resolveTypeElements(ctx, ext, scope);
  46259. for (const key in props) {
  46260. if (!hasOwn(base.props, key)) {
  46261. base.props[key] = props[key];
  46262. }
  46263. }
  46264. if (calls) {
  46265. ;
  46266. (base.calls || (base.calls = [])).push(...calls);
  46267. }
  46268. } catch (e) {
  46269. if (!ctx.silentOnExtendsFailure) {
  46270. ctx.error(
  46271. `Failed to resolve extends base type.
  46272. If this previously worked in 3.2, you can instruct the compiler to ignore this extend by adding /* @vue-ignore */ before it, for example:
  46273. interface Props extends /* @vue-ignore */ Base {}
  46274. Note: both in 3.2 or with the ignore, the properties in the base type are treated as fallthrough attrs at runtime.`,
  46275. ext,
  46276. scope
  46277. );
  46278. }
  46279. }
  46280. }
  46281. }
  46282. return base;
  46283. }
  46284. function resolveMappedType(ctx, node, scope, typeParameters) {
  46285. const res = { props: {} };
  46286. let keys;
  46287. if (node.nameType) {
  46288. const { name, constraint } = node.typeParameter;
  46289. scope = createChildScope(scope);
  46290. Object.assign(scope.types, __spreadProps$1(__spreadValues$2({}, typeParameters), { [name]: constraint }));
  46291. keys = resolveStringType(ctx, node.nameType, scope);
  46292. } else {
  46293. keys = resolveStringType(ctx, node.typeParameter.constraint, scope);
  46294. }
  46295. for (const key of keys) {
  46296. res.props[key] = createProperty(
  46297. {
  46298. type: "Identifier",
  46299. name: key
  46300. },
  46301. node.typeAnnotation,
  46302. scope,
  46303. !!node.optional
  46304. );
  46305. }
  46306. return res;
  46307. }
  46308. function resolveIndexType(ctx, node, scope) {
  46309. var _a, _b;
  46310. if (node.indexType.type === "TSNumberKeyword") {
  46311. return resolveArrayElementType(ctx, node.objectType, scope);
  46312. }
  46313. const { indexType, objectType } = node;
  46314. const types = [];
  46315. let keys;
  46316. let resolved;
  46317. if (indexType.type === "TSStringKeyword") {
  46318. resolved = resolveTypeElements(ctx, objectType, scope);
  46319. keys = Object.keys(resolved.props);
  46320. } else {
  46321. keys = resolveStringType(ctx, indexType, scope);
  46322. resolved = resolveTypeElements(ctx, objectType, scope);
  46323. }
  46324. for (const key of keys) {
  46325. const targetType = (_b = (_a = resolved.props[key]) == null ? void 0 : _a.typeAnnotation) == null ? void 0 : _b.typeAnnotation;
  46326. if (targetType) {
  46327. targetType._ownerScope = resolved.props[key]._ownerScope;
  46328. types.push(targetType);
  46329. }
  46330. }
  46331. return types;
  46332. }
  46333. function resolveArrayElementType(ctx, node, scope) {
  46334. if (node.type === "TSArrayType") {
  46335. return [node.elementType];
  46336. }
  46337. if (node.type === "TSTupleType") {
  46338. return node.elementTypes.map(
  46339. (t) => t.type === "TSNamedTupleMember" ? t.elementType : t
  46340. );
  46341. }
  46342. if (node.type === "TSTypeReference") {
  46343. if (getReferenceName(node) === "Array" && node.typeParameters) {
  46344. return node.typeParameters.params;
  46345. } else {
  46346. const resolved = resolveTypeReference(ctx, node, scope);
  46347. if (resolved) {
  46348. return resolveArrayElementType(ctx, resolved, scope);
  46349. }
  46350. }
  46351. }
  46352. return ctx.error(
  46353. "Failed to resolve element type from target type",
  46354. node,
  46355. scope
  46356. );
  46357. }
  46358. function resolveStringType(ctx, node, scope, typeParameters) {
  46359. switch (node.type) {
  46360. case "StringLiteral":
  46361. return [node.value];
  46362. case "TSLiteralType":
  46363. return resolveStringType(ctx, node.literal, scope, typeParameters);
  46364. case "TSUnionType":
  46365. return node.types.map((t) => resolveStringType(ctx, t, scope, typeParameters)).flat();
  46366. case "TemplateLiteral": {
  46367. return resolveTemplateKeys(ctx, node, scope);
  46368. }
  46369. case "TSTypeReference": {
  46370. const resolved = resolveTypeReference(ctx, node, scope);
  46371. if (resolved) {
  46372. return resolveStringType(ctx, resolved, scope, typeParameters);
  46373. }
  46374. if (node.typeName.type === "Identifier") {
  46375. const name = node.typeName.name;
  46376. if (typeParameters && typeParameters[name]) {
  46377. return resolveStringType(
  46378. ctx,
  46379. typeParameters[name],
  46380. scope,
  46381. typeParameters
  46382. );
  46383. }
  46384. const getParam = (index = 0) => resolveStringType(
  46385. ctx,
  46386. node.typeParameters.params[index],
  46387. scope,
  46388. typeParameters
  46389. );
  46390. switch (name) {
  46391. case "Extract":
  46392. return getParam(1);
  46393. case "Exclude": {
  46394. const excluded = getParam(1);
  46395. return getParam().filter((s) => !excluded.includes(s));
  46396. }
  46397. case "Uppercase":
  46398. return getParam().map((s) => s.toUpperCase());
  46399. case "Lowercase":
  46400. return getParam().map((s) => s.toLowerCase());
  46401. case "Capitalize":
  46402. return getParam().map(capitalize);
  46403. case "Uncapitalize":
  46404. return getParam().map((s) => s[0].toLowerCase() + s.slice(1));
  46405. default:
  46406. ctx.error(
  46407. "Unsupported type when resolving index type",
  46408. node.typeName,
  46409. scope
  46410. );
  46411. }
  46412. }
  46413. }
  46414. }
  46415. return ctx.error("Failed to resolve index type into finite keys", node, scope);
  46416. }
  46417. function resolveTemplateKeys(ctx, node, scope) {
  46418. if (!node.expressions.length) {
  46419. return [node.quasis[0].value.raw];
  46420. }
  46421. const res = [];
  46422. const e = node.expressions[0];
  46423. const q = node.quasis[0];
  46424. const leading = q ? q.value.raw : ``;
  46425. const resolved = resolveStringType(ctx, e, scope);
  46426. const restResolved = resolveTemplateKeys(
  46427. ctx,
  46428. __spreadProps$1(__spreadValues$2({}, node), {
  46429. expressions: node.expressions.slice(1),
  46430. quasis: q ? node.quasis.slice(1) : node.quasis
  46431. }),
  46432. scope
  46433. );
  46434. for (const r of resolved) {
  46435. for (const rr of restResolved) {
  46436. res.push(leading + r + rr);
  46437. }
  46438. }
  46439. return res;
  46440. }
  46441. const SupportedBuiltinsSet = /* @__PURE__ */ new Set([
  46442. "Partial",
  46443. "Required",
  46444. "Readonly",
  46445. "Pick",
  46446. "Omit"
  46447. ]);
  46448. function resolveBuiltin(ctx, node, name, scope, typeParameters) {
  46449. const t = resolveTypeElements(
  46450. ctx,
  46451. node.typeParameters.params[0],
  46452. scope,
  46453. typeParameters
  46454. );
  46455. switch (name) {
  46456. case "Partial": {
  46457. const res2 = { props: {}, calls: t.calls };
  46458. Object.keys(t.props).forEach((key) => {
  46459. res2.props[key] = __spreadProps$1(__spreadValues$2({}, t.props[key]), { optional: true });
  46460. });
  46461. return res2;
  46462. }
  46463. case "Required": {
  46464. const res2 = { props: {}, calls: t.calls };
  46465. Object.keys(t.props).forEach((key) => {
  46466. res2.props[key] = __spreadProps$1(__spreadValues$2({}, t.props[key]), { optional: false });
  46467. });
  46468. return res2;
  46469. }
  46470. case "Readonly":
  46471. return t;
  46472. case "Pick": {
  46473. const picked = resolveStringType(
  46474. ctx,
  46475. node.typeParameters.params[1],
  46476. scope,
  46477. typeParameters
  46478. );
  46479. const res2 = { props: {}, calls: t.calls };
  46480. for (const key of picked) {
  46481. res2.props[key] = t.props[key];
  46482. }
  46483. return res2;
  46484. }
  46485. case "Omit":
  46486. const omitted = resolveStringType(
  46487. ctx,
  46488. node.typeParameters.params[1],
  46489. scope,
  46490. typeParameters
  46491. );
  46492. const res = { props: {}, calls: t.calls };
  46493. for (const key in t.props) {
  46494. if (!omitted.includes(key)) {
  46495. res.props[key] = t.props[key];
  46496. }
  46497. }
  46498. return res;
  46499. }
  46500. }
  46501. function resolveTypeReference(ctx, node, scope, name, onlyExported = false) {
  46502. const canCache = !(scope == null ? void 0 : scope.isGenericScope);
  46503. if (canCache && node._resolvedReference) {
  46504. recordScopeDep(ctx, node._resolvedReference._ownerScope);
  46505. return node._resolvedReference;
  46506. }
  46507. const resolved = innerResolveTypeReference(
  46508. ctx,
  46509. scope || ctxToScope(ctx),
  46510. name || getReferenceName(node),
  46511. node,
  46512. onlyExported
  46513. );
  46514. return canCache ? node._resolvedReference = resolved : resolved;
  46515. }
  46516. function innerResolveTypeReference(ctx, scope, name, node, onlyExported) {
  46517. if (typeof name === "string") {
  46518. if (scope.imports[name]) {
  46519. return resolveTypeFromImport(ctx, node, name, scope);
  46520. } else {
  46521. const lookupSource = node.type === "TSTypeQuery" ? onlyExported ? scope.exportedDeclares : scope.declares : onlyExported ? scope.exportedTypes : scope.types;
  46522. if (lookupSource[name]) {
  46523. return lookupSource[name];
  46524. } else {
  46525. const globalScopes = resolveGlobalScope(ctx);
  46526. if (globalScopes) {
  46527. for (const s of globalScopes) {
  46528. const src = node.type === "TSTypeQuery" ? s.declares : s.types;
  46529. if (src[name]) {
  46530. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(s.filename);
  46531. const resolved = src[name];
  46532. if (resolved._ownerScope && resolved._ownerScope !== s) {
  46533. ctx.deps.add(resolved._ownerScope.filename);
  46534. }
  46535. return resolved;
  46536. }
  46537. }
  46538. }
  46539. }
  46540. }
  46541. } else {
  46542. let ns = innerResolveTypeReference(ctx, scope, name[0], node, onlyExported);
  46543. if (ns) {
  46544. if (ns.type !== "TSModuleDeclaration") {
  46545. ns = ns._ns;
  46546. }
  46547. if (ns) {
  46548. const childScope = moduleDeclToScope(ctx, ns, ns._ownerScope || scope);
  46549. return innerResolveTypeReference(
  46550. ctx,
  46551. childScope,
  46552. name.length > 2 ? name.slice(1) : name[name.length - 1],
  46553. node,
  46554. !ns.declare
  46555. );
  46556. }
  46557. }
  46558. }
  46559. }
  46560. function getReferenceName(node) {
  46561. const ref = node.type === "TSTypeReference" ? node.typeName : node.type === "TSExpressionWithTypeArguments" ? node.expression : node.type === "TSImportType" ? node.qualifier : node.exprName;
  46562. if ((ref == null ? void 0 : ref.type) === "Identifier") {
  46563. return ref.name;
  46564. } else if ((ref == null ? void 0 : ref.type) === "TSQualifiedName") {
  46565. return qualifiedNameToPath(ref);
  46566. } else {
  46567. return "default";
  46568. }
  46569. }
  46570. function qualifiedNameToPath(node) {
  46571. if (node.type === "Identifier") {
  46572. return [node.name];
  46573. } else {
  46574. return [...qualifiedNameToPath(node.left), node.right.name];
  46575. }
  46576. }
  46577. function resolveGlobalScope(ctx) {
  46578. if (ctx.options.globalTypeFiles) {
  46579. const fs = resolveFS(ctx);
  46580. if (!fs) {
  46581. throw new Error("[vue/compiler-sfc] globalTypeFiles requires fs access.");
  46582. }
  46583. return ctx.options.globalTypeFiles.map(
  46584. (file) => fileToScope(ctx, normalizePath(file), true)
  46585. );
  46586. }
  46587. }
  46588. let ts;
  46589. let loadTS;
  46590. function registerTS(_loadTS) {
  46591. loadTS = () => {
  46592. try {
  46593. return _loadTS();
  46594. } catch (err) {
  46595. if (typeof err.message === "string" && err.message.includes("Cannot find module")) {
  46596. throw new Error(
  46597. 'Failed to load TypeScript, which is required for resolving imported types. Please make sure "TypeScript" is installed as a project dependency.'
  46598. );
  46599. } else {
  46600. throw new Error(
  46601. "Failed to load TypeScript for resolving imported types."
  46602. );
  46603. }
  46604. }
  46605. };
  46606. }
  46607. function resolveFS(ctx) {
  46608. if (ctx.fs) {
  46609. return ctx.fs;
  46610. }
  46611. if (!ts && loadTS) {
  46612. ts = loadTS();
  46613. }
  46614. const fs = ctx.options.fs || (ts == null ? void 0 : ts.sys);
  46615. if (!fs) {
  46616. return;
  46617. }
  46618. return ctx.fs = {
  46619. fileExists(file) {
  46620. if (file.endsWith(".vue.ts") && !file.endsWith(".d.vue.ts")) {
  46621. file = file.replace(/\.ts$/, "");
  46622. }
  46623. return fs.fileExists(file);
  46624. },
  46625. readFile(file) {
  46626. if (file.endsWith(".vue.ts") && !file.endsWith(".d.vue.ts")) {
  46627. file = file.replace(/\.ts$/, "");
  46628. }
  46629. return fs.readFile(file);
  46630. },
  46631. realpath: fs.realpath
  46632. };
  46633. }
  46634. function resolveTypeFromImport(ctx, node, name, scope) {
  46635. const { source, imported } = scope.imports[name];
  46636. const sourceScope = importSourceToScope(ctx, node, scope, source);
  46637. return resolveTypeReference(ctx, node, sourceScope, imported, true);
  46638. }
  46639. function importSourceToScope(ctx, node, scope, source, trackDep = true) {
  46640. let fs;
  46641. try {
  46642. fs = resolveFS(ctx);
  46643. } catch (err) {
  46644. return ctx.error(err.message, node, scope);
  46645. }
  46646. if (!fs) {
  46647. return ctx.error(
  46648. `No fs option provided to \`compileScript\` in non-Node environment. File system access is required for resolving imported types.`,
  46649. node,
  46650. scope
  46651. );
  46652. }
  46653. let resolved = scope.resolvedImportSources[source];
  46654. if (!resolved) {
  46655. if (source.startsWith("..")) {
  46656. const osSpecificJoinFn = joinPaths;
  46657. const filename = osSpecificJoinFn(dirname(scope.filename), source);
  46658. resolved = resolveExt(filename, fs);
  46659. } else if (source[0] === ".") {
  46660. const filename = joinPaths(dirname(scope.filename), source);
  46661. resolved = resolveExt(filename, fs);
  46662. } else {
  46663. {
  46664. return ctx.error(
  46665. `Type import from non-relative sources is not supported in the browser build.`,
  46666. node,
  46667. scope
  46668. );
  46669. }
  46670. }
  46671. if (!resolved && source[0] === "." && false) {
  46672. if (!ts) {
  46673. if (loadTS) ts = loadTS();
  46674. }
  46675. if (ts) {
  46676. resolved = resolveWithTS(scope.filename);
  46677. }
  46678. }
  46679. if (resolved) {
  46680. resolved = scope.resolvedImportSources[source] = normalizePath(resolved);
  46681. }
  46682. }
  46683. if (resolved) {
  46684. if (trackDep) {
  46685. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(resolved);
  46686. }
  46687. return fileToScope(ctx, resolved);
  46688. } else {
  46689. return ctx.error(
  46690. `Failed to resolve import source ${JSON.stringify(source)}.`,
  46691. node,
  46692. scope
  46693. );
  46694. }
  46695. }
  46696. function resolveExt(filename, fs) {
  46697. let moduleType = "u";
  46698. if (filename.endsWith(".mjs")) {
  46699. moduleType = "m";
  46700. } else if (filename.endsWith(".cjs")) {
  46701. moduleType = "c";
  46702. }
  46703. filename = filename.replace(/\.[cm]?jsx?$/, "");
  46704. const tryResolve = (filename2) => {
  46705. if (fs.fileExists(filename2)) return filename2;
  46706. };
  46707. const resolveTs = () => tryResolve(filename + `.ts`) || tryResolve(filename + `.tsx`) || tryResolve(filename + `.d.ts`);
  46708. const resolveMts = () => tryResolve(filename + `.mts`) || tryResolve(filename + `.d.mts`);
  46709. const resolveCts = () => tryResolve(filename + `.cts`) || tryResolve(filename + `.d.cts`);
  46710. return tryResolve(filename) || // For explicit .mjs/.cjs imports, prefer .mts/.cts declarations first.
  46711. (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`));
  46712. }
  46713. const tsConfigCache = createCache();
  46714. const tsConfigRefMap = /* @__PURE__ */ new Map();
  46715. function resolveWithTS(containingFile, source, ts2, fs) {
  46716. return;
  46717. }
  46718. const fileToScopeCache = createCache();
  46719. const fileToGlobalScopeCache = createCache();
  46720. function invalidateTypeCache(filename) {
  46721. filename = normalizePath(filename);
  46722. fileToScopeCache.delete(filename);
  46723. fileToGlobalScopeCache.delete(filename);
  46724. tsConfigCache.delete(filename);
  46725. const affectedConfig = tsConfigRefMap.get(filename);
  46726. if (affectedConfig) tsConfigCache.delete(affectedConfig);
  46727. }
  46728. function fileToScope(ctx, filename, asGlobal = false) {
  46729. const cache = asGlobal ? fileToGlobalScopeCache : fileToScopeCache;
  46730. const cached = cache.get(filename);
  46731. if (cached) {
  46732. return cached;
  46733. }
  46734. const fs = resolveFS(ctx);
  46735. const source = fs.readFile(filename) || "";
  46736. const body = parseFile(filename, source, fs, ctx.options.babelParserPlugins);
  46737. const scope = new TypeScope(filename, source, 0, recordImports(body));
  46738. recordTypes(ctx, body, scope, asGlobal);
  46739. cache.set(filename, scope);
  46740. return scope;
  46741. }
  46742. function parseFile(filename, content, fs, parserPlugins) {
  46743. const ext = extname(filename);
  46744. if (ext === ".ts" || ext === ".mts" || ext === ".tsx" || ext === ".cts" || ext === ".mtsx") {
  46745. return libExports.parse(content, {
  46746. plugins: resolveParserPlugins(
  46747. ext.slice(1),
  46748. parserPlugins,
  46749. /\.d\.[cm]?ts$/.test(filename)
  46750. ),
  46751. sourceType: "module"
  46752. }).program.body;
  46753. }
  46754. const isUnknownTypeSource = !/\.[cm]?[tj]sx?$/.test(filename);
  46755. const arbitraryTypeSource = `${filename.slice(0, -ext.length)}.d${ext}.ts`;
  46756. const hasArbitraryTypeDeclaration = isUnknownTypeSource && fs.fileExists(arbitraryTypeSource);
  46757. if (hasArbitraryTypeDeclaration) {
  46758. return libExports.parse(fs.readFile(arbitraryTypeSource), {
  46759. plugins: resolveParserPlugins("ts", parserPlugins, true),
  46760. sourceType: "module"
  46761. }).program.body;
  46762. }
  46763. if (ext === ".vue") {
  46764. const {
  46765. descriptor: { script, scriptSetup }
  46766. } = parse$2(content);
  46767. if (!script && !scriptSetup) {
  46768. return [];
  46769. }
  46770. const scriptOffset = script ? script.loc.start.offset : Infinity;
  46771. const scriptSetupOffset = scriptSetup ? scriptSetup.loc.start.offset : Infinity;
  46772. const firstBlock = scriptOffset < scriptSetupOffset ? script : scriptSetup;
  46773. const secondBlock = scriptOffset < scriptSetupOffset ? scriptSetup : script;
  46774. let scriptContent = " ".repeat(Math.min(scriptOffset, scriptSetupOffset)) + firstBlock.content;
  46775. if (secondBlock) {
  46776. scriptContent += " ".repeat(secondBlock.loc.start.offset - script.loc.end.offset) + secondBlock.content;
  46777. }
  46778. const lang = (script == null ? void 0 : script.lang) || (scriptSetup == null ? void 0 : scriptSetup.lang);
  46779. return libExports.parse(scriptContent, {
  46780. plugins: resolveParserPlugins(lang, parserPlugins),
  46781. sourceType: "module"
  46782. }).program.body;
  46783. }
  46784. return [];
  46785. }
  46786. function ctxToScope(ctx) {
  46787. if (ctx.scope) {
  46788. return ctx.scope;
  46789. }
  46790. const body = "ast" in ctx ? ctx.ast : ctx.scriptAst ? [...ctx.scriptAst.body, ...ctx.scriptSetupAst.body] : ctx.scriptSetupAst.body;
  46791. const scope = new TypeScope(
  46792. ctx.filename,
  46793. ctx.source,
  46794. "startOffset" in ctx ? ctx.startOffset : 0,
  46795. "userImports" in ctx ? Object.create(ctx.userImports) : recordImports(body)
  46796. );
  46797. recordTypes(ctx, body, scope);
  46798. return ctx.scope = scope;
  46799. }
  46800. function moduleDeclToScope(ctx, node, parentScope) {
  46801. if (node._resolvedChildScope) {
  46802. return node._resolvedChildScope;
  46803. }
  46804. const scope = createChildScope(parentScope);
  46805. if (node.body.type === "TSModuleDeclaration") {
  46806. const decl = node.body;
  46807. decl._ownerScope = scope;
  46808. const id = getId(decl.id);
  46809. scope.types[id] = scope.exportedTypes[id] = decl;
  46810. } else {
  46811. recordTypes(ctx, node.body.body, scope);
  46812. }
  46813. return node._resolvedChildScope = scope;
  46814. }
  46815. function createChildScope(parentScope) {
  46816. return new TypeScope(
  46817. parentScope.filename,
  46818. parentScope.source,
  46819. parentScope.offset,
  46820. Object.create(parentScope.imports),
  46821. Object.create(parentScope.types),
  46822. Object.create(parentScope.declares)
  46823. );
  46824. }
  46825. const importExportRE = /^Import|^Export/;
  46826. function recordTypes(ctx, body, scope, asGlobal = false) {
  46827. const { types, declares, exportedTypes, exportedDeclares, imports } = scope;
  46828. const isAmbient = asGlobal ? !body.some((s) => importExportRE.test(s.type)) : false;
  46829. for (const stmt of body) {
  46830. if (asGlobal) {
  46831. if (isAmbient) {
  46832. if (stmt.declare) {
  46833. recordType(stmt, types, declares);
  46834. }
  46835. } else if (stmt.type === "TSModuleDeclaration" && stmt.global) {
  46836. for (const s of stmt.body.body) {
  46837. if (s.type === "ExportNamedDeclaration") {
  46838. if (s.declaration) {
  46839. recordType(s.declaration, types, declares);
  46840. } else if (s.source) {
  46841. const sourceScope = importSourceToScope(
  46842. ctx,
  46843. s.source,
  46844. scope,
  46845. s.source.value,
  46846. false
  46847. );
  46848. for (const spec of s.specifiers) {
  46849. if (spec.type === "ExportSpecifier") {
  46850. const exported = getId(spec.exported);
  46851. const local = spec.local.name;
  46852. if (sourceScope.exportedTypes[local]) {
  46853. types[exported] = sourceScope.exportedTypes[local];
  46854. }
  46855. if (sourceScope.exportedDeclares[local]) {
  46856. declares[exported] = sourceScope.exportedDeclares[local];
  46857. }
  46858. }
  46859. }
  46860. }
  46861. } else if (s.type === "ExportAllDeclaration" && s.source) {
  46862. const sourceScope = importSourceToScope(
  46863. ctx,
  46864. s.source,
  46865. scope,
  46866. s.source.value,
  46867. false
  46868. );
  46869. Object.assign(types, sourceScope.exportedTypes);
  46870. Object.assign(declares, sourceScope.exportedDeclares);
  46871. } else {
  46872. recordType(s, types, declares);
  46873. }
  46874. }
  46875. }
  46876. } else {
  46877. recordType(stmt, types, declares);
  46878. }
  46879. }
  46880. if (!asGlobal) {
  46881. for (const stmt of body) {
  46882. if (stmt.type === "ExportNamedDeclaration") {
  46883. if (stmt.declaration) {
  46884. recordType(stmt.declaration, types, declares);
  46885. recordType(stmt.declaration, exportedTypes, exportedDeclares);
  46886. } else {
  46887. for (const spec of stmt.specifiers) {
  46888. if (spec.type === "ExportSpecifier") {
  46889. const local = spec.local.name;
  46890. const exported = getId(spec.exported);
  46891. if (stmt.source) {
  46892. imports[exported] = {
  46893. source: stmt.source.value,
  46894. imported: local
  46895. };
  46896. exportedTypes[exported] = {
  46897. type: "TSTypeReference",
  46898. typeName: {
  46899. type: "Identifier",
  46900. name: local
  46901. },
  46902. _ownerScope: scope
  46903. };
  46904. } else if (types[local]) {
  46905. exportedTypes[exported] = types[local];
  46906. }
  46907. }
  46908. }
  46909. }
  46910. } else if (stmt.type === "ExportAllDeclaration") {
  46911. const sourceScope = importSourceToScope(
  46912. ctx,
  46913. stmt.source,
  46914. scope,
  46915. stmt.source.value
  46916. );
  46917. Object.assign(scope.exportedTypes, sourceScope.exportedTypes);
  46918. } else if (stmt.type === "ExportDefaultDeclaration" && stmt.declaration) {
  46919. if (stmt.declaration.type !== "Identifier") {
  46920. recordType(stmt.declaration, types, declares, "default");
  46921. recordType(
  46922. stmt.declaration,
  46923. exportedTypes,
  46924. exportedDeclares,
  46925. "default"
  46926. );
  46927. } else if (types[stmt.declaration.name]) {
  46928. exportedTypes["default"] = types[stmt.declaration.name];
  46929. }
  46930. }
  46931. }
  46932. }
  46933. for (const key of Object.keys(types)) {
  46934. const node = types[key];
  46935. if (!node._ownerScope) node._ownerScope = scope;
  46936. if (node._ns && !node._ns._ownerScope) node._ns._ownerScope = scope;
  46937. }
  46938. for (const key of Object.keys(declares)) {
  46939. if (!declares[key]._ownerScope) declares[key]._ownerScope = scope;
  46940. }
  46941. }
  46942. function recordType(node, types, declares, overwriteId) {
  46943. switch (node.type) {
  46944. case "TSInterfaceDeclaration":
  46945. case "TSEnumDeclaration":
  46946. case "TSModuleDeclaration": {
  46947. if (node.type === "TSModuleDeclaration" && node.global) {
  46948. const body = node.body;
  46949. for (const s of body.body) {
  46950. if (s.type === "ExportNamedDeclaration" && s.declaration) {
  46951. recordType(s.declaration, types, declares);
  46952. } else {
  46953. recordType(s, types, declares);
  46954. }
  46955. }
  46956. break;
  46957. }
  46958. const id = overwriteId || getId(node.id);
  46959. let existing = types[id];
  46960. if (existing) {
  46961. if (node.type === "TSModuleDeclaration") {
  46962. if (existing.type === "TSModuleDeclaration") {
  46963. mergeNamespaces(existing, node);
  46964. } else {
  46965. attachNamespace(existing, node);
  46966. }
  46967. break;
  46968. }
  46969. if (existing.type === "TSModuleDeclaration") {
  46970. types[id] = node;
  46971. attachNamespace(node, existing);
  46972. break;
  46973. }
  46974. if (existing.type !== node.type) {
  46975. break;
  46976. }
  46977. if (node.type === "TSInterfaceDeclaration") {
  46978. existing.body.body.push(...node.body.body);
  46979. } else {
  46980. existing.members.push(...node.members);
  46981. }
  46982. } else {
  46983. types[id] = node;
  46984. }
  46985. break;
  46986. }
  46987. case "ClassDeclaration":
  46988. if (overwriteId || node.id) types[overwriteId || getId(node.id)] = node;
  46989. break;
  46990. case "TSTypeAliasDeclaration":
  46991. types[node.id.name] = node.typeParameters ? node : node.typeAnnotation;
  46992. break;
  46993. case "TSDeclareFunction":
  46994. if (node.id) declares[node.id.name] = node;
  46995. break;
  46996. case "VariableDeclaration": {
  46997. if (node.declare) {
  46998. for (const decl of node.declarations) {
  46999. if (decl.id.type === "Identifier" && decl.id.typeAnnotation) {
  47000. declares[decl.id.name] = decl.id.typeAnnotation.typeAnnotation;
  47001. }
  47002. }
  47003. }
  47004. break;
  47005. }
  47006. }
  47007. }
  47008. function mergeNamespaces(to, from) {
  47009. const toBody = to.body;
  47010. const fromBody = from.body;
  47011. if (toBody.type === "TSModuleDeclaration") {
  47012. if (fromBody.type === "TSModuleDeclaration") {
  47013. mergeNamespaces(toBody, fromBody);
  47014. } else {
  47015. fromBody.body.push({
  47016. type: "ExportNamedDeclaration",
  47017. declaration: toBody,
  47018. exportKind: "type",
  47019. specifiers: []
  47020. });
  47021. }
  47022. } else if (fromBody.type === "TSModuleDeclaration") {
  47023. toBody.body.push({
  47024. type: "ExportNamedDeclaration",
  47025. declaration: fromBody,
  47026. exportKind: "type",
  47027. specifiers: []
  47028. });
  47029. } else {
  47030. toBody.body.push(...fromBody.body);
  47031. }
  47032. }
  47033. function attachNamespace(to, ns) {
  47034. if (!to._ns) {
  47035. to._ns = ns;
  47036. } else {
  47037. mergeNamespaces(to._ns, ns);
  47038. }
  47039. }
  47040. function recordImports(body) {
  47041. const imports = /* @__PURE__ */ Object.create(null);
  47042. for (const s of body) {
  47043. recordImport(s, imports);
  47044. }
  47045. return imports;
  47046. }
  47047. function recordImport(node, imports) {
  47048. if (node.type !== "ImportDeclaration") {
  47049. return;
  47050. }
  47051. for (const s of node.specifiers) {
  47052. imports[s.local.name] = {
  47053. imported: getImportedName(s),
  47054. source: node.source.value
  47055. };
  47056. }
  47057. }
  47058. function inferRuntimeType(ctx, node, scope = node._ownerScope || ctxToScope(ctx), isKeyOf = false, typeParameters) {
  47059. if (node.leadingComments && node.leadingComments.some((c) => c.value.includes("@vue-ignore"))) {
  47060. return [UNKNOWN_TYPE];
  47061. }
  47062. const prevSilent = ctx.silentOnExtendsFailure;
  47063. ctx.silentOnExtendsFailure = true;
  47064. try {
  47065. switch (node.type) {
  47066. case "TSStringKeyword":
  47067. return ["String"];
  47068. case "TSNumberKeyword":
  47069. return ["Number"];
  47070. case "TSBooleanKeyword":
  47071. return ["Boolean"];
  47072. case "TSObjectKeyword":
  47073. return ["Object"];
  47074. case "TSNullKeyword":
  47075. return ["null"];
  47076. case "TSTypeLiteral":
  47077. case "TSInterfaceDeclaration": {
  47078. const types = /* @__PURE__ */ new Set();
  47079. const members = node.type === "TSTypeLiteral" ? node.members : node.body.body;
  47080. for (const m of members) {
  47081. if (isKeyOf) {
  47082. if (m.type === "TSPropertySignature" && m.key.type === "NumericLiteral") {
  47083. types.add("Number");
  47084. } else if (m.type === "TSIndexSignature") {
  47085. const annotation = m.parameters[0].typeAnnotation;
  47086. if (annotation && annotation.type !== "Noop") {
  47087. const type = inferRuntimeType(
  47088. ctx,
  47089. annotation.typeAnnotation,
  47090. scope
  47091. )[0];
  47092. if (type === UNKNOWN_TYPE) return [UNKNOWN_TYPE];
  47093. types.add(type);
  47094. }
  47095. } else {
  47096. types.add("String");
  47097. }
  47098. } else if (m.type === "TSCallSignatureDeclaration" || m.type === "TSConstructSignatureDeclaration") {
  47099. types.add("Function");
  47100. } else {
  47101. types.add("Object");
  47102. }
  47103. }
  47104. return types.size ? Array.from(types) : [isKeyOf ? UNKNOWN_TYPE : "Object"];
  47105. }
  47106. case "TSPropertySignature":
  47107. if (node.typeAnnotation) {
  47108. return inferRuntimeType(
  47109. ctx,
  47110. node.typeAnnotation.typeAnnotation,
  47111. scope
  47112. );
  47113. }
  47114. break;
  47115. case "TSMethodSignature":
  47116. case "TSFunctionType":
  47117. return ["Function"];
  47118. case "TSArrayType":
  47119. case "TSTupleType":
  47120. return ["Array"];
  47121. case "TSLiteralType":
  47122. switch (node.literal.type) {
  47123. case "StringLiteral":
  47124. return ["String"];
  47125. case "BooleanLiteral":
  47126. return ["Boolean"];
  47127. case "NumericLiteral":
  47128. case "BigIntLiteral":
  47129. return ["Number"];
  47130. default:
  47131. return [UNKNOWN_TYPE];
  47132. }
  47133. case "TSTypeReference": {
  47134. let resolved;
  47135. try {
  47136. resolved = resolveTypeReference(ctx, node, scope);
  47137. } catch (e) {
  47138. }
  47139. if (resolved) {
  47140. if (resolved.type === "TSTypeAliasDeclaration") {
  47141. if (resolved.typeAnnotation.type === "TSFunctionType") {
  47142. return ["Function"];
  47143. }
  47144. if (node.typeParameters) {
  47145. const typeParams = /* @__PURE__ */ Object.create(null);
  47146. if (resolved.typeParameters) {
  47147. resolved.typeParameters.params.forEach((p, i) => {
  47148. typeParams[p.name] = node.typeParameters.params[i];
  47149. });
  47150. }
  47151. return inferRuntimeType(
  47152. ctx,
  47153. resolved.typeAnnotation,
  47154. resolved._ownerScope,
  47155. isKeyOf,
  47156. typeParams
  47157. );
  47158. }
  47159. }
  47160. return inferRuntimeType(ctx, resolved, resolved._ownerScope, isKeyOf);
  47161. }
  47162. if (node.typeName.type === "Identifier") {
  47163. if (typeParameters && typeParameters[node.typeName.name]) {
  47164. return inferRuntimeType(
  47165. ctx,
  47166. typeParameters[node.typeName.name],
  47167. scope,
  47168. isKeyOf,
  47169. typeParameters
  47170. );
  47171. }
  47172. if (isKeyOf) {
  47173. switch (node.typeName.name) {
  47174. case "String":
  47175. case "Array":
  47176. case "ArrayLike":
  47177. case "Parameters":
  47178. case "ConstructorParameters":
  47179. case "ReadonlyArray":
  47180. return ["String", "Number"];
  47181. // TS built-in utility types
  47182. case "Record":
  47183. case "Partial":
  47184. case "Required":
  47185. case "Readonly":
  47186. if (node.typeParameters && node.typeParameters.params[0]) {
  47187. return inferRuntimeType(
  47188. ctx,
  47189. node.typeParameters.params[0],
  47190. scope,
  47191. true
  47192. );
  47193. }
  47194. break;
  47195. case "Pick":
  47196. case "Extract":
  47197. if (node.typeParameters && node.typeParameters.params[1]) {
  47198. return inferRuntimeType(
  47199. ctx,
  47200. node.typeParameters.params[1],
  47201. scope
  47202. );
  47203. }
  47204. break;
  47205. case "Function":
  47206. case "Object":
  47207. case "Set":
  47208. case "Map":
  47209. case "WeakSet":
  47210. case "WeakMap":
  47211. case "Date":
  47212. case "Promise":
  47213. case "Error":
  47214. case "Uppercase":
  47215. case "Lowercase":
  47216. case "Capitalize":
  47217. case "Uncapitalize":
  47218. case "ReadonlyMap":
  47219. case "ReadonlySet":
  47220. return ["String"];
  47221. }
  47222. } else {
  47223. switch (node.typeName.name) {
  47224. case "Array":
  47225. case "Function":
  47226. case "Object":
  47227. case "Set":
  47228. case "Map":
  47229. case "WeakSet":
  47230. case "WeakMap":
  47231. case "Date":
  47232. case "Promise":
  47233. case "Error":
  47234. return [node.typeName.name];
  47235. // TS built-in utility types
  47236. // https://www.typescriptlang.org/docs/handbook/utility-types.html
  47237. case "Partial":
  47238. case "Required":
  47239. case "Readonly":
  47240. case "Record":
  47241. case "Pick":
  47242. case "Omit":
  47243. case "InstanceType":
  47244. return ["Object"];
  47245. case "Uppercase":
  47246. case "Lowercase":
  47247. case "Capitalize":
  47248. case "Uncapitalize":
  47249. return ["String"];
  47250. case "Parameters":
  47251. case "ConstructorParameters":
  47252. case "ReadonlyArray":
  47253. return ["Array"];
  47254. case "ReadonlyMap":
  47255. return ["Map"];
  47256. case "ReadonlySet":
  47257. return ["Set"];
  47258. // Vue ref wrapper types — handled here so that runtime type
  47259. // inference still works when `vue` types cannot be resolved
  47260. // (e.g. consumed as built artifacts in another package). #14729
  47261. case "Ref":
  47262. case "ShallowRef":
  47263. case "ComputedRef":
  47264. case "WritableComputedRef":
  47265. return ["Object"];
  47266. case "MaybeRef":
  47267. case "MaybeRefOrGetter": {
  47268. const types = /* @__PURE__ */ new Set(["Object"]);
  47269. if (node.typeName.name === "MaybeRefOrGetter") {
  47270. types.add("Function");
  47271. }
  47272. if (node.typeParameters && node.typeParameters.params[0]) {
  47273. for (const t of inferRuntimeType(
  47274. ctx,
  47275. node.typeParameters.params[0],
  47276. scope,
  47277. false,
  47278. typeParameters
  47279. )) {
  47280. types.add(t);
  47281. }
  47282. }
  47283. return Array.from(types);
  47284. }
  47285. case "NonNullable":
  47286. if (node.typeParameters && node.typeParameters.params[0]) {
  47287. return inferRuntimeType(
  47288. ctx,
  47289. node.typeParameters.params[0],
  47290. scope
  47291. ).filter((t) => t !== "null");
  47292. }
  47293. break;
  47294. case "Extract":
  47295. if (node.typeParameters && node.typeParameters.params[1]) {
  47296. return inferRuntimeType(
  47297. ctx,
  47298. node.typeParameters.params[1],
  47299. scope
  47300. );
  47301. }
  47302. break;
  47303. case "Exclude":
  47304. case "OmitThisParameter":
  47305. if (node.typeParameters && node.typeParameters.params[0]) {
  47306. return inferRuntimeType(
  47307. ctx,
  47308. node.typeParameters.params[0],
  47309. scope
  47310. );
  47311. }
  47312. break;
  47313. }
  47314. }
  47315. }
  47316. break;
  47317. }
  47318. case "TSParenthesizedType":
  47319. return inferRuntimeType(ctx, node.typeAnnotation, scope);
  47320. case "TSUnionType":
  47321. return flattenTypes(ctx, node.types, scope, isKeyOf, typeParameters);
  47322. case "TSIntersectionType": {
  47323. return flattenTypes(
  47324. ctx,
  47325. node.types,
  47326. scope,
  47327. isKeyOf,
  47328. typeParameters
  47329. ).filter((t) => t !== UNKNOWN_TYPE);
  47330. }
  47331. case "TSMappedType": {
  47332. const { typeAnnotation, typeParameter } = node;
  47333. if (typeAnnotation && typeAnnotation.type === "TSIndexedAccessType" && typeParameter && typeParameter.constraint && typeParameters) {
  47334. const constraint = typeParameter.constraint;
  47335. if (constraint.type === "TSTypeOperator" && constraint.operator === "keyof" && constraint.typeAnnotation && constraint.typeAnnotation.type === "TSTypeReference" && constraint.typeAnnotation.typeName.type === "Identifier") {
  47336. const typeName = constraint.typeAnnotation.typeName.name;
  47337. const index = typeAnnotation.indexType;
  47338. const obj = typeAnnotation.objectType;
  47339. 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) {
  47340. const targetType = typeParameters[typeName];
  47341. if (targetType) {
  47342. return inferRuntimeType(ctx, targetType, scope);
  47343. }
  47344. }
  47345. }
  47346. }
  47347. return [UNKNOWN_TYPE];
  47348. }
  47349. case "TSEnumDeclaration":
  47350. return inferEnumType(node);
  47351. case "TSSymbolKeyword":
  47352. return ["Symbol"];
  47353. case "TSIndexedAccessType": {
  47354. const types = resolveIndexType(ctx, node, scope);
  47355. return flattenTypes(ctx, types, scope, isKeyOf);
  47356. }
  47357. case "ClassDeclaration":
  47358. return ["Object"];
  47359. case "TSImportType": {
  47360. const sourceScope = importSourceToScope(
  47361. ctx,
  47362. node.argument,
  47363. scope,
  47364. node.argument.value
  47365. );
  47366. const resolved = resolveTypeReference(ctx, node, sourceScope);
  47367. if (resolved) {
  47368. return inferRuntimeType(ctx, resolved, resolved._ownerScope);
  47369. }
  47370. break;
  47371. }
  47372. case "TSTypeQuery": {
  47373. const id = node.exprName;
  47374. if (id.type === "Identifier") {
  47375. const matched = scope.declares[id.name];
  47376. if (matched) {
  47377. return inferRuntimeType(ctx, matched, matched._ownerScope, isKeyOf);
  47378. }
  47379. }
  47380. break;
  47381. }
  47382. // e.g. readonly
  47383. case "TSTypeOperator": {
  47384. return inferRuntimeType(
  47385. ctx,
  47386. node.typeAnnotation,
  47387. scope,
  47388. node.operator === "keyof"
  47389. );
  47390. }
  47391. case "TSAnyKeyword": {
  47392. if (isKeyOf) {
  47393. return ["String", "Number", "Symbol"];
  47394. }
  47395. break;
  47396. }
  47397. }
  47398. } catch (e) {
  47399. } finally {
  47400. ctx.silentOnExtendsFailure = prevSilent;
  47401. }
  47402. return [UNKNOWN_TYPE];
  47403. }
  47404. function flattenTypes(ctx, types, scope, isKeyOf = false, typeParameters = void 0) {
  47405. if (types.length === 1) {
  47406. return inferRuntimeType(
  47407. ctx,
  47408. types[0],
  47409. types[0]._ownerScope || scope,
  47410. isKeyOf,
  47411. typeParameters
  47412. );
  47413. }
  47414. return [
  47415. ...new Set(
  47416. [].concat(
  47417. ...types.map(
  47418. (t) => inferRuntimeType(
  47419. ctx,
  47420. t,
  47421. t._ownerScope || scope,
  47422. isKeyOf,
  47423. typeParameters
  47424. )
  47425. )
  47426. )
  47427. )
  47428. ];
  47429. }
  47430. function inferEnumType(node) {
  47431. const types = /* @__PURE__ */ new Set();
  47432. for (const m of node.members) {
  47433. if (m.initializer) {
  47434. switch (m.initializer.type) {
  47435. case "StringLiteral":
  47436. types.add("String");
  47437. break;
  47438. case "NumericLiteral":
  47439. types.add("Number");
  47440. break;
  47441. }
  47442. }
  47443. }
  47444. return types.size ? [...types] : ["Number"];
  47445. }
  47446. function resolveExtractPropTypes({ props }, scope) {
  47447. const res = { props: {} };
  47448. for (const key in props) {
  47449. const raw = props[key];
  47450. res.props[key] = reverseInferType(
  47451. raw.key,
  47452. raw.typeAnnotation.typeAnnotation,
  47453. scope
  47454. );
  47455. }
  47456. return res;
  47457. }
  47458. function reverseInferType(key, node, scope, optional = true, checkObjectSyntax = true) {
  47459. if (checkObjectSyntax && node.type === "TSTypeLiteral") {
  47460. const typeType = findStaticPropertyType(node, "type");
  47461. if (typeType) {
  47462. const requiredType = findStaticPropertyType(node, "required");
  47463. const optional2 = requiredType && requiredType.type === "TSLiteralType" && requiredType.literal.type === "BooleanLiteral" ? !requiredType.literal.value : true;
  47464. return reverseInferType(key, typeType, scope, optional2, false);
  47465. }
  47466. } else if (node.type === "TSTypeReference" && node.typeName.type === "Identifier") {
  47467. if (node.typeName.name.endsWith("Constructor")) {
  47468. return createProperty(
  47469. key,
  47470. ctorToType(node.typeName.name),
  47471. scope,
  47472. optional
  47473. );
  47474. } else if (node.typeName.name === "PropType" && node.typeParameters) {
  47475. return createProperty(key, node.typeParameters.params[0], scope, optional);
  47476. }
  47477. }
  47478. if ((node.type === "TSTypeReference" || node.type === "TSImportType") && node.typeParameters) {
  47479. for (const t of node.typeParameters.params) {
  47480. const inferred = reverseInferType(key, t, scope, optional);
  47481. if (inferred) return inferred;
  47482. }
  47483. }
  47484. return createProperty(key, { type: `TSNullKeyword` }, scope, optional);
  47485. }
  47486. function ctorToType(ctorType) {
  47487. const ctor = ctorType.slice(0, -11);
  47488. switch (ctor) {
  47489. case "String":
  47490. case "Number":
  47491. case "Boolean":
  47492. return { type: `TS${ctor}Keyword` };
  47493. case "Array":
  47494. case "Function":
  47495. case "Object":
  47496. case "Set":
  47497. case "Map":
  47498. case "WeakSet":
  47499. case "WeakMap":
  47500. case "Date":
  47501. case "Promise":
  47502. return {
  47503. type: "TSTypeReference",
  47504. typeName: { type: "Identifier", name: ctor }
  47505. };
  47506. }
  47507. return { type: `TSNullKeyword` };
  47508. }
  47509. function findStaticPropertyType(node, key) {
  47510. const prop = node.members.find(
  47511. (m) => m.type === "TSPropertySignature" && getStringLiteralKey(m) === key && m.typeAnnotation
  47512. );
  47513. return prop && prop.typeAnnotation.typeAnnotation;
  47514. }
  47515. function resolveReturnType(ctx, arg, scope) {
  47516. var _a;
  47517. let resolved = arg;
  47518. if (arg.type === "TSTypeReference" || arg.type === "TSTypeQuery" || arg.type === "TSImportType") {
  47519. resolved = resolveTypeReference(ctx, arg, scope);
  47520. }
  47521. if (!resolved) return;
  47522. if (resolved.type === "TSFunctionType") {
  47523. return (_a = resolved.typeAnnotation) == null ? void 0 : _a.typeAnnotation;
  47524. }
  47525. if (resolved.type === "TSDeclareFunction") {
  47526. return resolved.returnType;
  47527. }
  47528. }
  47529. function resolveUnionType(ctx, node, scope) {
  47530. if (node.type === "TSTypeReference") {
  47531. const resolved = resolveTypeReference(ctx, node, scope);
  47532. if (resolved) node = resolved;
  47533. }
  47534. let types;
  47535. if (node.type === "TSUnionType") {
  47536. types = node.types.flatMap((node2) => resolveUnionType(ctx, node2, scope));
  47537. } else {
  47538. types = [node];
  47539. }
  47540. return types;
  47541. }
  47542. const DEFINE_MODEL = "defineModel";
  47543. function processDefineModel(ctx, node, declId) {
  47544. if (!isCallOf(node, DEFINE_MODEL)) {
  47545. return false;
  47546. }
  47547. ctx.hasDefineModelCall = true;
  47548. const type = node.typeParameters && node.typeParameters.params[0] || void 0;
  47549. let modelName;
  47550. let options;
  47551. const arg0 = node.arguments[0] && unwrapTSNode(node.arguments[0]);
  47552. const hasName = arg0 && (arg0.type === "StringLiteral" || arg0.type === "TemplateLiteral" && arg0.expressions.length === 0);
  47553. if (hasName) {
  47554. modelName = arg0.type === "StringLiteral" ? arg0.value : arg0.quasis[0].value.cooked;
  47555. options = node.arguments[1];
  47556. } else {
  47557. modelName = "modelValue";
  47558. options = arg0;
  47559. }
  47560. if (ctx.modelDecls[modelName]) {
  47561. ctx.error(`duplicate model name ${JSON.stringify(modelName)}`, node);
  47562. }
  47563. let optionsString = options && ctx.getString(options);
  47564. let optionsRemoved = !options;
  47565. const runtimeOptionNodes = [];
  47566. if (options && options.type === "ObjectExpression" && !options.properties.some((p) => p.type === "SpreadElement" || p.computed)) {
  47567. let removed = 0;
  47568. for (let i = options.properties.length - 1; i >= 0; i--) {
  47569. const p = options.properties[i];
  47570. const next = options.properties[i + 1];
  47571. const start = p.start;
  47572. const end = next ? next.start : options.end - 1;
  47573. 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"))) {
  47574. optionsString = optionsString.slice(0, start - options.start) + optionsString.slice(end - options.start);
  47575. } else {
  47576. removed++;
  47577. ctx.s.remove(ctx.startOffset + start, ctx.startOffset + end);
  47578. runtimeOptionNodes.push(p);
  47579. }
  47580. }
  47581. if (removed === options.properties.length) {
  47582. optionsRemoved = true;
  47583. ctx.s.remove(
  47584. ctx.startOffset + (hasName ? arg0.end : options.start),
  47585. ctx.startOffset + options.end
  47586. );
  47587. }
  47588. }
  47589. ctx.modelDecls[modelName] = {
  47590. type,
  47591. options: optionsString,
  47592. runtimeOptionNodes,
  47593. identifier: declId && declId.type === "Identifier" ? declId.name : void 0
  47594. };
  47595. ctx.bindingMetadata[modelName] = "props";
  47596. ctx.s.overwrite(
  47597. ctx.startOffset + node.callee.start,
  47598. ctx.startOffset + node.callee.end,
  47599. ctx.helper("useModel")
  47600. );
  47601. ctx.s.appendLeft(
  47602. ctx.startOffset + (node.arguments.length ? node.arguments[0].start : node.end - 1),
  47603. `__props, ` + (hasName ? `` : `${JSON.stringify(modelName)}${optionsRemoved ? `` : `, `}`)
  47604. );
  47605. return true;
  47606. }
  47607. function genModelProps(ctx) {
  47608. if (!ctx.hasDefineModelCall) return;
  47609. const isProd = !!ctx.options.isProd;
  47610. let modelPropsDecl = "";
  47611. for (const [name, { type, options: runtimeOptions }] of Object.entries(
  47612. ctx.modelDecls
  47613. )) {
  47614. let skipCheck = false;
  47615. let codegenOptions = ``;
  47616. let runtimeTypes = type && inferRuntimeType(ctx, type);
  47617. if (runtimeTypes) {
  47618. const hasBoolean = runtimeTypes.includes("Boolean");
  47619. const hasFunction = runtimeTypes.includes("Function");
  47620. const hasUnknownType = runtimeTypes.includes(UNKNOWN_TYPE);
  47621. if (hasUnknownType) {
  47622. if (hasBoolean || hasFunction) {
  47623. runtimeTypes = runtimeTypes.filter((t) => t !== UNKNOWN_TYPE);
  47624. skipCheck = true;
  47625. } else {
  47626. runtimeTypes = ["null"];
  47627. }
  47628. }
  47629. if (!isProd) {
  47630. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}` + (skipCheck ? ", skipCheck: true" : "");
  47631. } else if (hasBoolean || runtimeOptions && hasFunction) {
  47632. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}`;
  47633. } else ;
  47634. }
  47635. let decl;
  47636. if (codegenOptions && runtimeOptions) {
  47637. decl = ctx.isTS ? `{ ${codegenOptions}, ...${runtimeOptions} }` : `Object.assign({ ${codegenOptions} }, ${runtimeOptions})`;
  47638. } else if (codegenOptions) {
  47639. decl = `{ ${codegenOptions} }`;
  47640. } else if (runtimeOptions) {
  47641. decl = runtimeOptions;
  47642. } else {
  47643. decl = `{}`;
  47644. }
  47645. modelPropsDecl += `
  47646. ${JSON.stringify(name)}: ${decl},`;
  47647. const modifierPropName = JSON.stringify(
  47648. name === "modelValue" ? `modelModifiers` : `${name}Modifiers`
  47649. );
  47650. modelPropsDecl += `
  47651. ${modifierPropName}: {},`;
  47652. }
  47653. return `{${modelPropsDecl}
  47654. }`;
  47655. }
  47656. const DEFINE_PROPS = "defineProps";
  47657. const WITH_DEFAULTS = "withDefaults";
  47658. function processDefineProps(ctx, node, declId, isWithDefaults = false) {
  47659. if (!isCallOf(node, DEFINE_PROPS)) {
  47660. return processWithDefaults(ctx, node, declId);
  47661. }
  47662. if (ctx.hasDefinePropsCall) {
  47663. ctx.error(`duplicate ${DEFINE_PROPS}() call`, node);
  47664. }
  47665. ctx.hasDefinePropsCall = true;
  47666. ctx.propsRuntimeDecl = node.arguments[0];
  47667. if (ctx.propsRuntimeDecl) {
  47668. for (const key of getObjectOrArrayExpressionKeys(ctx.propsRuntimeDecl)) {
  47669. if (!(key in ctx.bindingMetadata)) {
  47670. ctx.bindingMetadata[key] = "props";
  47671. }
  47672. }
  47673. }
  47674. if (node.typeParameters) {
  47675. if (ctx.propsRuntimeDecl) {
  47676. ctx.error(
  47677. `${DEFINE_PROPS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  47678. node
  47679. );
  47680. }
  47681. ctx.propsTypeDecl = node.typeParameters.params[0];
  47682. }
  47683. if (!isWithDefaults && declId && declId.type === "ObjectPattern") {
  47684. processPropsDestructure(ctx, declId);
  47685. }
  47686. ctx.propsCall = node;
  47687. ctx.propsDecl = declId;
  47688. return true;
  47689. }
  47690. function processWithDefaults(ctx, node, declId) {
  47691. if (!isCallOf(node, WITH_DEFAULTS)) {
  47692. return false;
  47693. }
  47694. if (!processDefineProps(
  47695. ctx,
  47696. node.arguments[0],
  47697. declId,
  47698. true
  47699. )) {
  47700. ctx.error(
  47701. `${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`,
  47702. node.arguments[0] || node
  47703. );
  47704. }
  47705. if (ctx.propsRuntimeDecl) {
  47706. ctx.error(
  47707. `${WITH_DEFAULTS} can only be used with type-based ${DEFINE_PROPS} declaration.`,
  47708. node
  47709. );
  47710. }
  47711. if (declId && declId.type === "ObjectPattern") {
  47712. ctx.warn(
  47713. `${WITH_DEFAULTS}() is unnecessary when using destructure with ${DEFINE_PROPS}().
  47714. Reactive destructure will be disabled when using withDefaults().
  47715. Prefer using destructure default values, e.g. const { foo = 1 } = defineProps(...). `,
  47716. node.callee
  47717. );
  47718. }
  47719. ctx.propsRuntimeDefaults = node.arguments[1];
  47720. if (!ctx.propsRuntimeDefaults) {
  47721. ctx.error(`The 2nd argument of ${WITH_DEFAULTS} is required.`, node);
  47722. }
  47723. ctx.propsCall = node;
  47724. return true;
  47725. }
  47726. function genRuntimeProps(ctx) {
  47727. let propsDecls;
  47728. if (ctx.propsRuntimeDecl) {
  47729. propsDecls = ctx.getString(ctx.propsRuntimeDecl).trim();
  47730. if (ctx.propsDestructureDecl) {
  47731. const defaults = [];
  47732. for (const key in ctx.propsDestructuredBindings) {
  47733. const d = genDestructuredDefaultValue(ctx, key);
  47734. const finalKey = getEscapedPropName(key);
  47735. if (d)
  47736. defaults.push(
  47737. `${finalKey}: ${d.valueString}${d.needSkipFactory ? `, __skip_${finalKey}: true` : ``}`
  47738. );
  47739. }
  47740. if (defaults.length) {
  47741. propsDecls = `/*@__PURE__*/${ctx.helper(
  47742. `mergeDefaults`
  47743. )}(${propsDecls}, {
  47744. ${defaults.join(",\n ")}
  47745. })`;
  47746. }
  47747. }
  47748. } else if (ctx.propsTypeDecl) {
  47749. propsDecls = extractRuntimeProps(ctx);
  47750. }
  47751. const modelsDecls = genModelProps(ctx);
  47752. if (propsDecls && modelsDecls) {
  47753. return `/*@__PURE__*/${ctx.helper(
  47754. "mergeModels"
  47755. )}(${propsDecls}, ${modelsDecls})`;
  47756. } else {
  47757. return modelsDecls || propsDecls;
  47758. }
  47759. }
  47760. function extractRuntimeProps(ctx) {
  47761. const props = resolveRuntimePropsFromType(ctx, ctx.propsTypeDecl);
  47762. if (!props.length) {
  47763. return;
  47764. }
  47765. const propStrings = [];
  47766. const hasStaticDefaults = hasStaticWithDefaults(ctx);
  47767. for (const prop of props) {
  47768. propStrings.push(genRuntimePropFromType(ctx, prop, hasStaticDefaults));
  47769. if ("bindingMetadata" in ctx && !(prop.key in ctx.bindingMetadata)) {
  47770. ctx.bindingMetadata[prop.key] = "props";
  47771. }
  47772. }
  47773. let propsDecls = `{
  47774. ${propStrings.join(",\n ")}
  47775. }`;
  47776. if (ctx.propsRuntimeDefaults && !hasStaticDefaults) {
  47777. propsDecls = `/*@__PURE__*/${ctx.helper(
  47778. "mergeDefaults"
  47779. )}(${propsDecls}, ${ctx.getString(ctx.propsRuntimeDefaults)})`;
  47780. }
  47781. return propsDecls;
  47782. }
  47783. function resolveRuntimePropsFromType(ctx, node) {
  47784. const props = [];
  47785. const elements = resolveTypeElements(ctx, node);
  47786. for (const key in elements.props) {
  47787. const e = elements.props[key];
  47788. let type = inferRuntimeType(ctx, e);
  47789. let skipCheck = false;
  47790. if (type.includes(UNKNOWN_TYPE)) {
  47791. if (type.includes("Boolean") || type.includes("Function")) {
  47792. type = type.filter((t) => t !== UNKNOWN_TYPE);
  47793. skipCheck = true;
  47794. } else {
  47795. type = ["null"];
  47796. }
  47797. }
  47798. props.push({
  47799. key,
  47800. required: !e.optional,
  47801. type: type || [`null`],
  47802. skipCheck
  47803. });
  47804. }
  47805. return props;
  47806. }
  47807. function genRuntimePropFromType(ctx, { key, required, type, skipCheck }, hasStaticDefaults) {
  47808. let defaultString;
  47809. const destructured = genDestructuredDefaultValue(ctx, key, type);
  47810. if (destructured) {
  47811. defaultString = `default: ${destructured.valueString}${destructured.needSkipFactory ? `, skipFactory: true` : ``}`;
  47812. } else if (hasStaticDefaults) {
  47813. const prop = ctx.propsRuntimeDefaults.properties.find(
  47814. (node) => {
  47815. if (node.type === "SpreadElement") return false;
  47816. return resolveObjectKey(node.key, node.computed) === key;
  47817. }
  47818. );
  47819. if (prop) {
  47820. if (prop.type === "ObjectProperty") {
  47821. defaultString = `default: ${ctx.getString(prop.value)}`;
  47822. } else {
  47823. let paramsString = "";
  47824. if (prop.params.length) {
  47825. const start = prop.params[0].start;
  47826. const end = prop.params[prop.params.length - 1].end;
  47827. paramsString = ctx.getString({ start, end });
  47828. }
  47829. defaultString = `${prop.async ? "async " : ""}${prop.kind !== "method" ? `${prop.kind} ` : ""}default(${paramsString}) ${ctx.getString(prop.body)}`;
  47830. }
  47831. }
  47832. }
  47833. const finalKey = getEscapedPropName(key);
  47834. if (!ctx.options.isProd) {
  47835. return `${finalKey}: { ${concatStrings([
  47836. `type: ${toRuntimeTypeString(type)}`,
  47837. `required: ${required}`,
  47838. skipCheck && "skipCheck: true",
  47839. defaultString
  47840. ])} }`;
  47841. } else if (type.some(
  47842. (el) => el === "Boolean" || (!hasStaticDefaults || defaultString) && el === "Function"
  47843. )) {
  47844. return `${finalKey}: { ${concatStrings([
  47845. `type: ${toRuntimeTypeString(type)}`,
  47846. defaultString
  47847. ])} }`;
  47848. } else {
  47849. if (ctx.isCE) {
  47850. if (defaultString) {
  47851. return `${finalKey}: ${`{ ${defaultString}, type: ${toRuntimeTypeString(
  47852. type
  47853. )} }`}`;
  47854. } else {
  47855. return `${finalKey}: {type: ${toRuntimeTypeString(type)}}`;
  47856. }
  47857. }
  47858. return `${finalKey}: ${defaultString ? `{ ${defaultString} }` : `{}`}`;
  47859. }
  47860. }
  47861. function hasStaticWithDefaults(ctx) {
  47862. return !!(ctx.propsRuntimeDefaults && ctx.propsRuntimeDefaults.type === "ObjectExpression" && ctx.propsRuntimeDefaults.properties.every(
  47863. (node) => node.type !== "SpreadElement" && (!node.computed || node.key.type.endsWith("Literal"))
  47864. ));
  47865. }
  47866. function genDestructuredDefaultValue(ctx, key, inferredType) {
  47867. const destructured = ctx.propsDestructuredBindings[key];
  47868. const defaultVal = destructured && destructured.default;
  47869. if (defaultVal) {
  47870. const value = ctx.getString(defaultVal);
  47871. const unwrapped = unwrapTSNode(defaultVal);
  47872. if (inferredType && inferredType.length && !inferredType.includes("null")) {
  47873. const valueType = inferValueType(unwrapped);
  47874. if (valueType && !inferredType.includes(valueType)) {
  47875. ctx.error(
  47876. `Default value of prop "${key}" does not match declared type.`,
  47877. unwrapped
  47878. );
  47879. }
  47880. }
  47881. const needSkipFactory = !inferredType && (isFunctionType(unwrapped) || unwrapped.type === "Identifier");
  47882. const needFactoryWrap = !needSkipFactory && !isLiteralNode(unwrapped) && !(inferredType == null ? void 0 : inferredType.includes("Function"));
  47883. return {
  47884. valueString: needFactoryWrap ? `() => (${value})` : value,
  47885. needSkipFactory
  47886. };
  47887. }
  47888. }
  47889. function inferValueType(node) {
  47890. switch (node.type) {
  47891. case "StringLiteral":
  47892. return "String";
  47893. case "NumericLiteral":
  47894. return "Number";
  47895. case "BooleanLiteral":
  47896. return "Boolean";
  47897. case "ObjectExpression":
  47898. return "Object";
  47899. case "ArrayExpression":
  47900. return "Array";
  47901. case "FunctionExpression":
  47902. case "ArrowFunctionExpression":
  47903. return "Function";
  47904. }
  47905. }
  47906. function processPropsDestructure(ctx, declId) {
  47907. if (ctx.options.propsDestructure === "error") {
  47908. ctx.error(`Props destructure is explicitly prohibited via config.`, declId);
  47909. } else if (ctx.options.propsDestructure === false) {
  47910. return;
  47911. }
  47912. ctx.propsDestructureDecl = declId;
  47913. const registerBinding = (key, local, defaultValue) => {
  47914. ctx.propsDestructuredBindings[key] = { local, default: defaultValue };
  47915. if (local !== key) {
  47916. ctx.bindingMetadata[local] = "props-aliased";
  47917. (ctx.bindingMetadata.__propsAliases || (ctx.bindingMetadata.__propsAliases = {}))[local] = key;
  47918. }
  47919. };
  47920. for (const prop of declId.properties) {
  47921. if (prop.type === "ObjectProperty") {
  47922. const propKey = resolveObjectKey(prop.key, prop.computed);
  47923. if (!propKey) {
  47924. ctx.error(
  47925. `${DEFINE_PROPS}() destructure cannot use computed key.`,
  47926. prop.key
  47927. );
  47928. }
  47929. if (prop.value.type === "AssignmentPattern") {
  47930. const { left, right } = prop.value;
  47931. if (left.type !== "Identifier") {
  47932. ctx.error(
  47933. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  47934. left
  47935. );
  47936. }
  47937. registerBinding(propKey, left.name, right);
  47938. } else if (prop.value.type === "Identifier") {
  47939. registerBinding(propKey, prop.value.name);
  47940. } else {
  47941. ctx.error(
  47942. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  47943. prop.value
  47944. );
  47945. }
  47946. } else {
  47947. ctx.propsDestructureRestId = prop.argument.name;
  47948. ctx.bindingMetadata[ctx.propsDestructureRestId] = "setup-reactive-const";
  47949. }
  47950. }
  47951. }
  47952. function transformDestructuredProps(ctx, vueImportAliases) {
  47953. if (ctx.options.propsDestructure === false) {
  47954. return;
  47955. }
  47956. const rootScope = /* @__PURE__ */ Object.create(null);
  47957. const scopeStack = [rootScope];
  47958. const functionScopeStack = [rootScope];
  47959. let currentScope = rootScope;
  47960. const excludedIds = /* @__PURE__ */ new WeakSet();
  47961. const parentStack = [];
  47962. const propsLocalToPublicMap = /* @__PURE__ */ Object.create(null);
  47963. for (const key in ctx.propsDestructuredBindings) {
  47964. const { local } = ctx.propsDestructuredBindings[key];
  47965. rootScope[local] = true;
  47966. propsLocalToPublicMap[local] = key;
  47967. }
  47968. function pushScope(isFunctionScope = false) {
  47969. const scope = currentScope = Object.create(currentScope);
  47970. scopeStack.push(scope);
  47971. if (isFunctionScope) {
  47972. functionScopeStack.push(scope);
  47973. }
  47974. }
  47975. function popScope(isFunctionScope = false) {
  47976. scopeStack.pop();
  47977. if (isFunctionScope) {
  47978. functionScopeStack.pop();
  47979. }
  47980. currentScope = scopeStack[scopeStack.length - 1] || null;
  47981. }
  47982. function registerLocalBinding(id, scope = currentScope) {
  47983. excludedIds.add(id);
  47984. if (scope) {
  47985. scope[id.name] = false;
  47986. } else {
  47987. ctx.error(
  47988. "registerBinding called without active scope, something is wrong.",
  47989. id
  47990. );
  47991. }
  47992. }
  47993. function walkScope(node, isRoot = false) {
  47994. for (const stmt of node.body) {
  47995. if (stmt.type === "VariableDeclaration") {
  47996. walkVariableDeclaration(stmt, isRoot);
  47997. } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
  47998. if (stmt.declare || !stmt.id) continue;
  47999. registerLocalBinding(stmt.id);
  48000. } else if (stmt.type === "ExportNamedDeclaration" && stmt.declaration && stmt.declaration.type === "VariableDeclaration") {
  48001. walkVariableDeclaration(stmt.declaration, isRoot);
  48002. } else if (stmt.type === "LabeledStatement" && stmt.body.type === "VariableDeclaration") {
  48003. walkVariableDeclaration(stmt.body, isRoot);
  48004. }
  48005. }
  48006. }
  48007. function walkVariableDeclaration(stmt, isRoot = false, scope = stmt.kind === "var" ? functionScopeStack[functionScopeStack.length - 1] : currentScope) {
  48008. if (stmt.declare) {
  48009. return;
  48010. }
  48011. for (const decl of stmt.declarations) {
  48012. const isDefineProps = isRoot && decl.init && isCallOf(unwrapTSNode(decl.init), "defineProps");
  48013. for (const id of extractIdentifiers$1(decl.id)) {
  48014. if (isDefineProps) {
  48015. excludedIds.add(id);
  48016. } else {
  48017. registerLocalBinding(id, scope);
  48018. }
  48019. }
  48020. }
  48021. }
  48022. function walkFunctionScopeVarDeclarations(scopeNode, isRoot = false) {
  48023. const scope = functionScopeStack[functionScopeStack.length - 1];
  48024. walk$2(scopeNode, {
  48025. enter(node, parent) {
  48026. if (parent && parent.type.startsWith("TS") && !TS_NODE_TYPES.includes(parent.type)) {
  48027. return this.skip();
  48028. }
  48029. if (isFunctionType(node) || node.type === "ClassDeclaration" || node.type === "ClassExpression") {
  48030. return this.skip();
  48031. }
  48032. if (node.type === "VariableDeclaration" && node.kind === "var") {
  48033. walkVariableDeclaration(node, isRoot && parent === scopeNode, scope);
  48034. }
  48035. }
  48036. });
  48037. }
  48038. function rewriteId(id, parent, parentStack2) {
  48039. if (parent.type === "AssignmentExpression" && id === parent.left || parent.type === "UpdateExpression") {
  48040. ctx.error(`Cannot assign to destructured props as they are readonly.`, id);
  48041. }
  48042. if (isStaticProperty(parent) && parent.shorthand) {
  48043. if (!parent.inPattern || isInDestructureAssignment(parent, parentStack2)) {
  48044. ctx.s.appendLeft(
  48045. id.end + ctx.startOffset,
  48046. `: ${genPropsAccessExp(propsLocalToPublicMap[id.name])}`
  48047. );
  48048. }
  48049. } else {
  48050. ctx.s.overwrite(
  48051. id.start + ctx.startOffset,
  48052. id.end + ctx.startOffset,
  48053. genPropsAccessExp(propsLocalToPublicMap[id.name])
  48054. );
  48055. }
  48056. }
  48057. function checkUsage(node, method, alias = method) {
  48058. if (isCallOf(node, alias)) {
  48059. const arg = unwrapTSNode(node.arguments[0]);
  48060. if (arg.type === "Identifier" && currentScope[arg.name]) {
  48061. ctx.error(
  48062. `"${arg.name}" is a destructured prop and should not be passed directly to ${method}(). Pass a getter () => ${arg.name} instead.`,
  48063. arg
  48064. );
  48065. }
  48066. }
  48067. }
  48068. const ast = ctx.scriptSetupAst;
  48069. walkFunctionScopeVarDeclarations(ast, true);
  48070. walkScope(ast, true);
  48071. walk$2(ast, {
  48072. enter(node, parent) {
  48073. parent && parentStack.push(parent);
  48074. if (parent && parent.type.startsWith("TS") && !TS_NODE_TYPES.includes(parent.type)) {
  48075. return this.skip();
  48076. }
  48077. checkUsage(node, "watch", vueImportAliases.watch);
  48078. checkUsage(node, "toRef", vueImportAliases.toRef);
  48079. if (isFunctionType(node)) {
  48080. pushScope(true);
  48081. walkFunctionParams(node, registerLocalBinding);
  48082. if (node.body.type === "BlockStatement") {
  48083. walkFunctionScopeVarDeclarations(node.body);
  48084. walkScope(node.body);
  48085. }
  48086. return;
  48087. }
  48088. if (node.type === "CatchClause") {
  48089. pushScope();
  48090. if (node.param && node.param.type === "Identifier") {
  48091. registerLocalBinding(node.param);
  48092. }
  48093. walkScope(node.body);
  48094. return;
  48095. }
  48096. if (node.type === "ForOfStatement" || node.type === "ForInStatement" || node.type === "ForStatement") {
  48097. pushScope();
  48098. const varDecl = node.type === "ForStatement" ? node.init : node.left;
  48099. if (varDecl && varDecl.type === "VariableDeclaration") {
  48100. walkVariableDeclaration(varDecl);
  48101. }
  48102. if (node.body.type === "BlockStatement") {
  48103. walkScope(node.body);
  48104. }
  48105. return;
  48106. }
  48107. if (node.type === "BlockStatement" && !isFunctionType(parent)) {
  48108. pushScope();
  48109. walkScope(node);
  48110. return;
  48111. }
  48112. if (node.type === "Identifier") {
  48113. if (isReferencedIdentifier(node, parent, parentStack) && !excludedIds.has(node)) {
  48114. if (currentScope[node.name]) {
  48115. rewriteId(node, parent, parentStack);
  48116. }
  48117. }
  48118. }
  48119. },
  48120. leave(node, parent) {
  48121. parent && parentStack.pop();
  48122. if (isFunctionType(node)) {
  48123. popScope(true);
  48124. } else if (node.type === "BlockStatement" && !isFunctionType(parent)) {
  48125. popScope();
  48126. } else if (node.type === "CatchClause" || node.type === "ForOfStatement" || node.type === "ForInStatement" || node.type === "ForStatement") {
  48127. popScope();
  48128. }
  48129. }
  48130. });
  48131. }
  48132. const DEFINE_EMITS = "defineEmits";
  48133. function processDefineEmits(ctx, node, declId) {
  48134. if (!isCallOf(node, DEFINE_EMITS)) {
  48135. return false;
  48136. }
  48137. if (ctx.hasDefineEmitCall) {
  48138. ctx.error(`duplicate ${DEFINE_EMITS}() call`, node);
  48139. }
  48140. ctx.hasDefineEmitCall = true;
  48141. ctx.emitsRuntimeDecl = node.arguments[0];
  48142. if (node.typeParameters) {
  48143. if (ctx.emitsRuntimeDecl) {
  48144. ctx.error(
  48145. `${DEFINE_EMITS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  48146. node
  48147. );
  48148. }
  48149. ctx.emitsTypeDecl = node.typeParameters.params[0];
  48150. }
  48151. ctx.emitDecl = declId;
  48152. return true;
  48153. }
  48154. function genRuntimeEmits(ctx) {
  48155. let emitsDecl = "";
  48156. if (ctx.emitsRuntimeDecl) {
  48157. emitsDecl = ctx.getString(ctx.emitsRuntimeDecl).trim();
  48158. } else if (ctx.emitsTypeDecl) {
  48159. const typeDeclaredEmits = extractRuntimeEmits(ctx);
  48160. emitsDecl = typeDeclaredEmits.size ? `[${Array.from(typeDeclaredEmits).map((k) => JSON.stringify(k)).join(", ")}]` : ``;
  48161. }
  48162. if (ctx.hasDefineModelCall) {
  48163. let modelEmitsDecl = `[${Object.keys(ctx.modelDecls).map((n) => JSON.stringify(`update:${n}`)).join(", ")}]`;
  48164. emitsDecl = emitsDecl ? `/*@__PURE__*/${ctx.helper(
  48165. "mergeModels"
  48166. )}(${emitsDecl}, ${modelEmitsDecl})` : modelEmitsDecl;
  48167. }
  48168. return emitsDecl;
  48169. }
  48170. function extractRuntimeEmits(ctx) {
  48171. const emits = /* @__PURE__ */ new Set();
  48172. const node = ctx.emitsTypeDecl;
  48173. if (node.type === "TSFunctionType") {
  48174. extractEventNames(ctx, node.parameters[0], emits);
  48175. return emits;
  48176. }
  48177. const { props, calls } = resolveTypeElements(ctx, node);
  48178. let hasProperty = false;
  48179. for (const key in props) {
  48180. emits.add(key);
  48181. hasProperty = true;
  48182. }
  48183. if (calls) {
  48184. if (hasProperty) {
  48185. ctx.error(
  48186. `defineEmits() type cannot mixed call signature and property syntax.`,
  48187. node
  48188. );
  48189. }
  48190. for (const call of calls) {
  48191. extractEventNames(ctx, call.parameters[0], emits);
  48192. }
  48193. }
  48194. return emits;
  48195. }
  48196. function extractEventNames(ctx, eventName, emits) {
  48197. if (eventName.type === "Identifier" && eventName.typeAnnotation && eventName.typeAnnotation.type === "TSTypeAnnotation") {
  48198. const types = resolveUnionType(ctx, eventName.typeAnnotation.typeAnnotation);
  48199. for (const type of types) {
  48200. if (type.type === "TSLiteralType") {
  48201. if (type.literal.type !== "UnaryExpression" && type.literal.type !== "TemplateLiteral") {
  48202. emits.add(String(type.literal.value));
  48203. }
  48204. }
  48205. }
  48206. }
  48207. }
  48208. const DEFINE_EXPOSE = "defineExpose";
  48209. function processDefineExpose(ctx, node) {
  48210. if (isCallOf(node, DEFINE_EXPOSE)) {
  48211. if (ctx.hasDefineExposeCall) {
  48212. ctx.error(`duplicate ${DEFINE_EXPOSE}() call`, node);
  48213. }
  48214. ctx.hasDefineExposeCall = true;
  48215. return true;
  48216. }
  48217. return false;
  48218. }
  48219. const DEFINE_SLOTS = "defineSlots";
  48220. function processDefineSlots(ctx, node, declId) {
  48221. if (!isCallOf(node, DEFINE_SLOTS)) {
  48222. return false;
  48223. }
  48224. if (ctx.hasDefineSlotsCall) {
  48225. ctx.error(`duplicate ${DEFINE_SLOTS}() call`, node);
  48226. }
  48227. ctx.hasDefineSlotsCall = true;
  48228. if (node.arguments.length > 0) {
  48229. ctx.error(`${DEFINE_SLOTS}() cannot accept arguments`, node);
  48230. }
  48231. if (declId) {
  48232. ctx.s.overwrite(
  48233. ctx.startOffset + node.start,
  48234. ctx.startOffset + node.end,
  48235. `${ctx.helper("useSlots")}()`
  48236. );
  48237. }
  48238. return true;
  48239. }
  48240. const DEFINE_OPTIONS = "defineOptions";
  48241. function processDefineOptions(ctx, node) {
  48242. if (!isCallOf(node, DEFINE_OPTIONS)) {
  48243. return false;
  48244. }
  48245. if (ctx.hasDefineOptionsCall) {
  48246. ctx.error(`duplicate ${DEFINE_OPTIONS}() call`, node);
  48247. }
  48248. if (node.typeParameters) {
  48249. ctx.error(`${DEFINE_OPTIONS}() cannot accept type arguments`, node);
  48250. }
  48251. if (!node.arguments[0]) return true;
  48252. ctx.hasDefineOptionsCall = true;
  48253. ctx.optionsRuntimeDecl = unwrapTSNode(node.arguments[0]);
  48254. let propsOption = void 0;
  48255. let emitsOption = void 0;
  48256. let exposeOption = void 0;
  48257. let slotsOption = void 0;
  48258. if (ctx.optionsRuntimeDecl.type === "ObjectExpression") {
  48259. for (const prop of ctx.optionsRuntimeDecl.properties) {
  48260. if ((prop.type === "ObjectProperty" || prop.type === "ObjectMethod") && prop.key.type === "Identifier") {
  48261. switch (prop.key.name) {
  48262. case "props":
  48263. propsOption = prop;
  48264. break;
  48265. case "emits":
  48266. emitsOption = prop;
  48267. break;
  48268. case "expose":
  48269. exposeOption = prop;
  48270. break;
  48271. case "slots":
  48272. slotsOption = prop;
  48273. break;
  48274. }
  48275. }
  48276. }
  48277. }
  48278. if (propsOption) {
  48279. ctx.error(
  48280. `${DEFINE_OPTIONS}() cannot be used to declare props. Use ${DEFINE_PROPS}() instead.`,
  48281. propsOption
  48282. );
  48283. }
  48284. if (emitsOption) {
  48285. ctx.error(
  48286. `${DEFINE_OPTIONS}() cannot be used to declare emits. Use ${DEFINE_EMITS}() instead.`,
  48287. emitsOption
  48288. );
  48289. }
  48290. if (exposeOption) {
  48291. ctx.error(
  48292. `${DEFINE_OPTIONS}() cannot be used to declare expose. Use ${DEFINE_EXPOSE}() instead.`,
  48293. exposeOption
  48294. );
  48295. }
  48296. if (slotsOption) {
  48297. ctx.error(
  48298. `${DEFINE_OPTIONS}() cannot be used to declare slots. Use ${DEFINE_SLOTS}() instead.`,
  48299. slotsOption
  48300. );
  48301. }
  48302. return true;
  48303. }
  48304. function processAwait(ctx, node, needSemi, isStatement) {
  48305. const argumentStart = node.argument.extra && node.argument.extra.parenthesized ? node.argument.extra.parenStart : node.argument.start;
  48306. const startOffset = ctx.startOffset;
  48307. const argumentStr = ctx.descriptor.source.slice(
  48308. argumentStart + startOffset,
  48309. node.argument.end + startOffset
  48310. );
  48311. const containsNestedAwait = /\bawait\b/.test(argumentStr);
  48312. ctx.s.overwrite(
  48313. node.start + startOffset,
  48314. argumentStart + startOffset,
  48315. `${needSemi ? `;` : ``}(
  48316. ([__temp,__restore] = ${ctx.helper(
  48317. `withAsyncContext`
  48318. )}(${containsNestedAwait ? `async ` : ``}() => `
  48319. );
  48320. ctx.s.appendLeft(
  48321. node.end + startOffset,
  48322. `)),
  48323. ${isStatement ? `` : `__temp = `}await __temp,
  48324. __restore()${isStatement ? `` : `,
  48325. __temp`}
  48326. )`
  48327. );
  48328. }
  48329. var __defProp$1 = Object.defineProperty;
  48330. var __defProps = Object.defineProperties;
  48331. var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
  48332. var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
  48333. var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
  48334. var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
  48335. var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  48336. var __spreadValues$1 = (a, b) => {
  48337. for (var prop in b || (b = {}))
  48338. if (__hasOwnProp$1.call(b, prop))
  48339. __defNormalProp$1(a, prop, b[prop]);
  48340. if (__getOwnPropSymbols$1)
  48341. for (var prop of __getOwnPropSymbols$1(b)) {
  48342. if (__propIsEnum$1.call(b, prop))
  48343. __defNormalProp$1(a, prop, b[prop]);
  48344. }
  48345. return a;
  48346. };
  48347. var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
  48348. const MACROS = [
  48349. DEFINE_PROPS,
  48350. DEFINE_EMITS,
  48351. DEFINE_EXPOSE,
  48352. DEFINE_OPTIONS,
  48353. DEFINE_SLOTS,
  48354. DEFINE_MODEL,
  48355. WITH_DEFAULTS
  48356. ];
  48357. function compileScript(sfc, options) {
  48358. var _a, _b, _c;
  48359. if (!options.id) {
  48360. warnOnce$1(
  48361. `compileScript now requires passing the \`id\` option.
  48362. Upgrade your vite or vue-loader version for compatibility with the latest experimental proposals.`
  48363. );
  48364. }
  48365. const { script, scriptSetup, source, filename } = sfc;
  48366. const hoistStatic = options.hoistStatic !== false && !script;
  48367. const scopeId = options.id ? options.id.replace(/^data-v-/, "") : "";
  48368. const scriptLang = script && script.lang;
  48369. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  48370. const isJSOrTS = isJS(scriptLang, scriptSetupLang) || isTS(scriptLang, scriptSetupLang);
  48371. if (script && scriptSetup && scriptLang !== scriptSetupLang) {
  48372. throw new Error(
  48373. `[@vue/compiler-sfc] <script> and <script setup> must have the same language type.`
  48374. );
  48375. }
  48376. if (!scriptSetup) {
  48377. if (!script) {
  48378. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
  48379. }
  48380. if (script.lang && !isJSOrTS) {
  48381. return script;
  48382. }
  48383. const ctx2 = new ScriptCompileContext(sfc, options);
  48384. return processNormalScript(ctx2, scopeId);
  48385. }
  48386. if (scriptSetupLang && !isJSOrTS) {
  48387. return scriptSetup;
  48388. }
  48389. const ctx = new ScriptCompileContext(sfc, options);
  48390. const scriptBindings = /* @__PURE__ */ Object.create(null);
  48391. const setupBindings = /* @__PURE__ */ Object.create(null);
  48392. let defaultExport;
  48393. let hasAwait = false;
  48394. let hasInlinedSsrRenderFn = false;
  48395. const startOffset = ctx.startOffset;
  48396. const endOffset = ctx.endOffset;
  48397. const scriptStartOffset = script && script.loc.start.offset;
  48398. const scriptEndOffset = script && script.loc.end.offset;
  48399. function hoistNode(node) {
  48400. const start = node.start + startOffset;
  48401. let end = node.end + startOffset;
  48402. if (node.trailingComments && node.trailingComments.length > 0) {
  48403. const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
  48404. end = lastCommentNode.end + startOffset;
  48405. }
  48406. while (end <= source.length) {
  48407. if (!/\s/.test(source.charAt(end))) {
  48408. break;
  48409. }
  48410. end++;
  48411. }
  48412. ctx.s.move(start, end, 0);
  48413. }
  48414. function registerUserImport(source2, local, imported, isType, isFromSetup, needTemplateUsageCheck) {
  48415. let isUsedInTemplate = needTemplateUsageCheck;
  48416. if (needTemplateUsageCheck && ctx.isTS && sfc.template && !sfc.template.src && !sfc.template.lang) {
  48417. isUsedInTemplate = isImportUsed(local, sfc, options.templateOptions);
  48418. }
  48419. ctx.userImports[local] = {
  48420. isType,
  48421. imported,
  48422. local,
  48423. source: source2,
  48424. isFromSetup,
  48425. isUsedInTemplate
  48426. };
  48427. }
  48428. function checkInvalidScopeReference(node, method) {
  48429. if (!node) return;
  48430. walkIdentifiers(node, (id) => {
  48431. const binding = setupBindings[id.name];
  48432. if (binding && binding !== "literal-const") {
  48433. ctx.error(
  48434. `\`${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.`,
  48435. id
  48436. );
  48437. }
  48438. });
  48439. }
  48440. const scriptAst = ctx.scriptAst;
  48441. const scriptSetupAst = ctx.scriptSetupAst;
  48442. if (scriptAst) {
  48443. for (const node of scriptAst.body) {
  48444. if (node.type === "ImportDeclaration") {
  48445. for (const specifier of node.specifiers) {
  48446. const imported = getImportedName(specifier);
  48447. registerUserImport(
  48448. node.source.value,
  48449. specifier.local.name,
  48450. imported,
  48451. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  48452. false,
  48453. !options.inlineTemplate
  48454. );
  48455. }
  48456. }
  48457. }
  48458. }
  48459. for (const node of scriptSetupAst.body) {
  48460. if (node.type === "ImportDeclaration") {
  48461. hoistNode(node);
  48462. let removed = 0;
  48463. const removeSpecifier = (i) => {
  48464. const removeLeft = i > removed;
  48465. removed++;
  48466. const current = node.specifiers[i];
  48467. const next = node.specifiers[i + 1];
  48468. ctx.s.remove(
  48469. removeLeft ? node.specifiers[i - 1].end + startOffset : current.start + startOffset,
  48470. next && !removeLeft ? next.start + startOffset : current.end + startOffset
  48471. );
  48472. };
  48473. for (let i = 0; i < node.specifiers.length; i++) {
  48474. const specifier = node.specifiers[i];
  48475. const local = specifier.local.name;
  48476. const imported = getImportedName(specifier);
  48477. const source2 = node.source.value;
  48478. const existing = ctx.userImports[local];
  48479. if (source2 === "vue" && MACROS.includes(imported)) {
  48480. if (local === imported) {
  48481. warnOnce$1(
  48482. `\`${imported}\` is a compiler macro and no longer needs to be imported.`
  48483. );
  48484. } else {
  48485. ctx.error(
  48486. `\`${imported}\` is a compiler macro and cannot be aliased to a different name.`,
  48487. specifier
  48488. );
  48489. }
  48490. removeSpecifier(i);
  48491. } else if (existing) {
  48492. if (existing.source === source2 && existing.imported === imported) {
  48493. removeSpecifier(i);
  48494. } else {
  48495. ctx.error(
  48496. `different imports aliased to same local name.`,
  48497. specifier
  48498. );
  48499. }
  48500. } else {
  48501. registerUserImport(
  48502. source2,
  48503. local,
  48504. imported,
  48505. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  48506. true,
  48507. !options.inlineTemplate
  48508. );
  48509. }
  48510. }
  48511. if (node.specifiers.length && removed === node.specifiers.length) {
  48512. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  48513. }
  48514. }
  48515. }
  48516. const vueImportAliases = {};
  48517. for (const key in ctx.userImports) {
  48518. const { source: source2, imported, local } = ctx.userImports[key];
  48519. if (source2 === "vue") vueImportAliases[imported] = local;
  48520. }
  48521. if (script && scriptAst) {
  48522. for (const node of scriptAst.body) {
  48523. if (node.type === "ExportDefaultDeclaration") {
  48524. defaultExport = node;
  48525. let optionProperties;
  48526. if (defaultExport.declaration.type === "ObjectExpression") {
  48527. optionProperties = defaultExport.declaration.properties;
  48528. } else if (defaultExport.declaration.type === "CallExpression" && defaultExport.declaration.arguments[0] && defaultExport.declaration.arguments[0].type === "ObjectExpression") {
  48529. optionProperties = defaultExport.declaration.arguments[0].properties;
  48530. }
  48531. if (optionProperties) {
  48532. for (const p of optionProperties) {
  48533. if (p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name") {
  48534. ctx.hasDefaultExportName = true;
  48535. }
  48536. if ((p.type === "ObjectMethod" || p.type === "ObjectProperty") && p.key.type === "Identifier" && p.key.name === "render") {
  48537. ctx.hasDefaultExportRender = true;
  48538. }
  48539. }
  48540. }
  48541. const start = node.start + scriptStartOffset;
  48542. const end = node.declaration.start + scriptStartOffset;
  48543. ctx.s.overwrite(start, end, `const ${normalScriptDefaultVar} = `);
  48544. } else if (node.type === "ExportNamedDeclaration") {
  48545. const defaultSpecifier = node.specifiers.find(
  48546. (s) => s.exported.type === "Identifier" && s.exported.name === "default"
  48547. );
  48548. if (defaultSpecifier) {
  48549. defaultExport = node;
  48550. if (node.specifiers.length > 1) {
  48551. ctx.s.remove(
  48552. defaultSpecifier.start + scriptStartOffset,
  48553. defaultSpecifier.end + scriptStartOffset
  48554. );
  48555. } else {
  48556. ctx.s.remove(
  48557. node.start + scriptStartOffset,
  48558. node.end + scriptStartOffset
  48559. );
  48560. }
  48561. if (node.source) {
  48562. ctx.s.prepend(
  48563. `import { ${defaultSpecifier.local.name} as ${normalScriptDefaultVar} } from '${node.source.value}'
  48564. `
  48565. );
  48566. } else {
  48567. ctx.s.appendLeft(
  48568. scriptEndOffset,
  48569. `
  48570. const ${normalScriptDefaultVar} = ${defaultSpecifier.local.name}
  48571. `
  48572. );
  48573. }
  48574. }
  48575. if (node.declaration) {
  48576. walkDeclaration(
  48577. "script",
  48578. node.declaration,
  48579. scriptBindings,
  48580. vueImportAliases,
  48581. hoistStatic
  48582. );
  48583. }
  48584. } else if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  48585. walkDeclaration(
  48586. "script",
  48587. node,
  48588. scriptBindings,
  48589. vueImportAliases,
  48590. hoistStatic
  48591. );
  48592. }
  48593. }
  48594. if (scriptStartOffset > startOffset) {
  48595. if (!/\n$/.test(script.content.trim())) {
  48596. ctx.s.appendLeft(scriptEndOffset, `
  48597. `);
  48598. }
  48599. ctx.s.move(scriptStartOffset, scriptEndOffset, 0);
  48600. }
  48601. }
  48602. for (const node of scriptSetupAst.body) {
  48603. if (node.type === "ExpressionStatement") {
  48604. const expr = unwrapTSNode(node.expression);
  48605. if (processDefineProps(ctx, expr) || processDefineEmits(ctx, expr) || processDefineOptions(ctx, expr) || processDefineSlots(ctx, expr)) {
  48606. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  48607. } else if (processDefineExpose(ctx, expr)) {
  48608. const callee = expr.callee;
  48609. ctx.s.overwrite(
  48610. callee.start + startOffset,
  48611. callee.end + startOffset,
  48612. "__expose"
  48613. );
  48614. } else {
  48615. processDefineModel(ctx, expr);
  48616. }
  48617. }
  48618. if (node.type === "VariableDeclaration" && !node.declare) {
  48619. const total = node.declarations.length;
  48620. let left = total;
  48621. let lastNonRemoved;
  48622. for (let i = 0; i < total; i++) {
  48623. const decl = node.declarations[i];
  48624. const init = decl.init && unwrapTSNode(decl.init);
  48625. if (init) {
  48626. if (processDefineOptions(ctx, init)) {
  48627. ctx.error(
  48628. `${DEFINE_OPTIONS}() has no returning value, it cannot be assigned.`,
  48629. node
  48630. );
  48631. }
  48632. const isDefineProps = processDefineProps(ctx, init, decl.id);
  48633. if (ctx.propsDestructureRestId) {
  48634. setupBindings[ctx.propsDestructureRestId] = "setup-reactive-const";
  48635. }
  48636. const isDefineEmits = !isDefineProps && processDefineEmits(ctx, init, decl.id);
  48637. !isDefineEmits && (processDefineSlots(ctx, init, decl.id) || processDefineModel(ctx, init, decl.id));
  48638. if (isDefineProps && !ctx.propsDestructureRestId && ctx.propsDestructureDecl) {
  48639. if (left === 1) {
  48640. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  48641. } else {
  48642. let start = decl.start + startOffset;
  48643. let end = decl.end + startOffset;
  48644. if (i === total - 1) {
  48645. start = node.declarations[lastNonRemoved].end + startOffset;
  48646. } else {
  48647. end = node.declarations[i + 1].start + startOffset;
  48648. }
  48649. ctx.s.remove(start, end);
  48650. left--;
  48651. }
  48652. } else if (isDefineEmits) {
  48653. ctx.s.overwrite(
  48654. startOffset + init.start,
  48655. startOffset + init.end,
  48656. "__emit"
  48657. );
  48658. } else {
  48659. lastNonRemoved = i;
  48660. }
  48661. }
  48662. }
  48663. }
  48664. let isAllLiteral = false;
  48665. if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  48666. isAllLiteral = walkDeclaration(
  48667. "scriptSetup",
  48668. node,
  48669. setupBindings,
  48670. vueImportAliases,
  48671. hoistStatic,
  48672. !!ctx.propsDestructureDecl
  48673. );
  48674. }
  48675. if (hoistStatic && isAllLiteral) {
  48676. hoistNode(node);
  48677. }
  48678. if (node.type === "VariableDeclaration" && !node.declare || node.type.endsWith("Statement")) {
  48679. const scope = [scriptSetupAst.body];
  48680. walk$2(node, {
  48681. enter(child, parent) {
  48682. if (isFunctionType(child)) {
  48683. this.skip();
  48684. }
  48685. if (child.type === "BlockStatement") {
  48686. scope.push(child.body);
  48687. }
  48688. if (child.type === "AwaitExpression") {
  48689. hasAwait = true;
  48690. const currentScope = scope[scope.length - 1];
  48691. const needsSemi = currentScope.some((n, i) => {
  48692. return (scope.length === 1 || i > 0) && n.type === "ExpressionStatement" && n.start === child.start;
  48693. });
  48694. processAwait(
  48695. ctx,
  48696. child,
  48697. needsSemi,
  48698. parent.type === "ExpressionStatement"
  48699. );
  48700. }
  48701. },
  48702. exit(node2) {
  48703. if (node2.type === "BlockStatement") scope.pop();
  48704. }
  48705. });
  48706. }
  48707. if (node.type === "ExportNamedDeclaration" && node.exportKind !== "type" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration") {
  48708. ctx.error(
  48709. `<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.`,
  48710. node
  48711. );
  48712. }
  48713. if (ctx.isTS) {
  48714. if (node.type.startsWith("TS") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "VariableDeclaration" && node.declare) {
  48715. if (node.type !== "TSEnumDeclaration") {
  48716. hoistNode(node);
  48717. }
  48718. }
  48719. }
  48720. }
  48721. if (ctx.propsDestructureDecl) {
  48722. transformDestructuredProps(ctx, vueImportAliases);
  48723. }
  48724. checkInvalidScopeReference(ctx.propsRuntimeDecl, DEFINE_PROPS);
  48725. checkInvalidScopeReference(ctx.propsRuntimeDefaults, DEFINE_PROPS);
  48726. checkInvalidScopeReference(ctx.propsDestructureDecl, DEFINE_PROPS);
  48727. checkInvalidScopeReference(ctx.emitsRuntimeDecl, DEFINE_EMITS);
  48728. checkInvalidScopeReference(ctx.optionsRuntimeDecl, DEFINE_OPTIONS);
  48729. for (const { runtimeOptionNodes } of Object.values(ctx.modelDecls)) {
  48730. for (const node of runtimeOptionNodes) {
  48731. checkInvalidScopeReference(node, DEFINE_MODEL);
  48732. }
  48733. }
  48734. if (script) {
  48735. if (startOffset < scriptStartOffset) {
  48736. ctx.s.remove(0, startOffset);
  48737. ctx.s.remove(endOffset, scriptStartOffset);
  48738. ctx.s.remove(scriptEndOffset, source.length);
  48739. } else {
  48740. ctx.s.remove(0, scriptStartOffset);
  48741. ctx.s.remove(scriptEndOffset, startOffset);
  48742. ctx.s.remove(endOffset, source.length);
  48743. }
  48744. } else {
  48745. ctx.s.remove(0, startOffset);
  48746. ctx.s.remove(endOffset, source.length);
  48747. }
  48748. if (scriptAst) {
  48749. Object.assign(ctx.bindingMetadata, analyzeScriptBindings(scriptAst.body));
  48750. }
  48751. for (const [key, { isType, imported, source: source2 }] of Object.entries(
  48752. ctx.userImports
  48753. )) {
  48754. if (isType) continue;
  48755. ctx.bindingMetadata[key] = imported === "*" || imported === "default" && source2.endsWith(".vue") || source2 === "vue" ? "setup-const" : "setup-maybe-ref";
  48756. }
  48757. for (const key in scriptBindings) {
  48758. ctx.bindingMetadata[key] = scriptBindings[key];
  48759. }
  48760. for (const key in setupBindings) {
  48761. ctx.bindingMetadata[key] = setupBindings[key];
  48762. }
  48763. if (sfc.template && !sfc.template.src && sfc.template.ast) {
  48764. const vModelIds = resolveTemplateVModelIdentifiers(
  48765. sfc,
  48766. options.templateOptions
  48767. );
  48768. if (vModelIds.size) {
  48769. const toDemote = /* @__PURE__ */ new Set();
  48770. for (const id of vModelIds) {
  48771. if (setupBindings[id] === "setup-reactive-const") {
  48772. toDemote.add(id);
  48773. }
  48774. }
  48775. if (toDemote.size) {
  48776. for (const node of scriptSetupAst.body) {
  48777. if (node.type === "VariableDeclaration" && node.kind === "const" && !node.declare) {
  48778. const demotedInDecl = [];
  48779. for (const decl of node.declarations) {
  48780. if (decl.id.type === "Identifier" && toDemote.has(decl.id.name)) {
  48781. demotedInDecl.push(decl.id.name);
  48782. }
  48783. }
  48784. if (demotedInDecl.length) {
  48785. ctx.s.overwrite(
  48786. node.start + startOffset,
  48787. node.start + startOffset + "const".length,
  48788. "let"
  48789. );
  48790. for (const id of demotedInDecl) {
  48791. setupBindings[id] = "setup-let";
  48792. ctx.bindingMetadata[id] = "setup-let";
  48793. warnOnce$1(
  48794. `\`v-model\` cannot update a \`const\` reactive binding \`${id}\`. The compiler has transformed it to \`let\` to make the update work.`
  48795. );
  48796. }
  48797. }
  48798. }
  48799. }
  48800. }
  48801. }
  48802. }
  48803. if (sfc.cssVars.length && // no need to do this when targeting SSR
  48804. !((_a = options.templateOptions) == null ? void 0 : _a.ssr)) {
  48805. ctx.helperImports.add(CSS_VARS_HELPER);
  48806. ctx.helperImports.add("unref");
  48807. ctx.s.prependLeft(
  48808. startOffset,
  48809. `
  48810. ${genCssVarsCode(
  48811. sfc.cssVars,
  48812. ctx.bindingMetadata,
  48813. scopeId,
  48814. !!options.isProd
  48815. )}
  48816. `
  48817. );
  48818. }
  48819. let args = `__props`;
  48820. if (ctx.propsTypeDecl) {
  48821. args += `: any`;
  48822. }
  48823. if (ctx.propsDecl) {
  48824. if (ctx.propsDestructureRestId) {
  48825. ctx.s.overwrite(
  48826. startOffset + ctx.propsCall.start,
  48827. startOffset + ctx.propsCall.end,
  48828. `${ctx.helper(`createPropsRestProxy`)}(__props, ${JSON.stringify(
  48829. Object.keys(ctx.propsDestructuredBindings)
  48830. )})`
  48831. );
  48832. ctx.s.overwrite(
  48833. startOffset + ctx.propsDestructureDecl.start,
  48834. startOffset + ctx.propsDestructureDecl.end,
  48835. ctx.propsDestructureRestId
  48836. );
  48837. } else if (!ctx.propsDestructureDecl) {
  48838. ctx.s.overwrite(
  48839. startOffset + ctx.propsCall.start,
  48840. startOffset + ctx.propsCall.end,
  48841. "__props"
  48842. );
  48843. }
  48844. }
  48845. if (hasAwait) {
  48846. const any = ctx.isTS ? `: any` : ``;
  48847. ctx.s.prependLeft(startOffset, `
  48848. let __temp${any}, __restore${any}
  48849. `);
  48850. }
  48851. const destructureElements = ctx.hasDefineExposeCall || !options.inlineTemplate ? [`expose: __expose`] : [];
  48852. if (ctx.emitDecl) {
  48853. destructureElements.push(`emit: __emit`);
  48854. }
  48855. if (destructureElements.length) {
  48856. args += `, { ${destructureElements.join(", ")} }`;
  48857. }
  48858. let templateMap;
  48859. let returned;
  48860. const propsDecl = genRuntimeProps(ctx);
  48861. if (!options.inlineTemplate || !sfc.template && ctx.hasDefaultExportRender) {
  48862. const allBindings = __spreadValues$1(__spreadValues$1({}, scriptBindings), setupBindings);
  48863. for (const key in ctx.userImports) {
  48864. if (!ctx.userImports[key].isType && ctx.userImports[key].isUsedInTemplate) {
  48865. allBindings[key] = true;
  48866. }
  48867. }
  48868. returned = `{ `;
  48869. for (const key in allBindings) {
  48870. if (allBindings[key] === true && ctx.userImports[key].source !== "vue" && !ctx.userImports[key].source.endsWith(".vue")) {
  48871. returned += `get ${key}() { return ${key} }, `;
  48872. } else if (ctx.bindingMetadata[key] === "setup-let") {
  48873. const setArg = key === "v" ? `_v` : `v`;
  48874. returned += `get ${key}() { return ${key} }, set ${key}(${setArg}) { ${key} = ${setArg} }, `;
  48875. } else {
  48876. returned += `${key}, `;
  48877. }
  48878. }
  48879. returned = returned.replace(/, $/, "") + ` }`;
  48880. } else {
  48881. if (sfc.template && !sfc.template.src) {
  48882. if (options.templateOptions && options.templateOptions.ssr) {
  48883. hasInlinedSsrRenderFn = true;
  48884. }
  48885. const { code, ast, preamble, tips, errors, map: map2 } = compileTemplate(__spreadProps(__spreadValues$1({
  48886. filename,
  48887. ast: sfc.template.ast,
  48888. source: sfc.template.content,
  48889. inMap: sfc.template.map
  48890. }, options.templateOptions), {
  48891. id: scopeId,
  48892. scoped: sfc.styles.some((s) => s.scoped),
  48893. isProd: options.isProd,
  48894. ssrCssVars: sfc.cssVars,
  48895. compilerOptions: __spreadProps(__spreadValues$1({}, options.templateOptions && options.templateOptions.compilerOptions), {
  48896. inline: true,
  48897. isTS: ctx.isTS,
  48898. bindingMetadata: ctx.bindingMetadata
  48899. })
  48900. }));
  48901. templateMap = map2;
  48902. if (tips.length) {
  48903. tips.forEach(warnOnce$1);
  48904. }
  48905. const err = errors[0];
  48906. if (typeof err === "string") {
  48907. throw new Error(err);
  48908. } else if (err) {
  48909. if (err.loc) {
  48910. err.message += `
  48911. ` + sfc.filename + "\n" + generateCodeFrame(
  48912. source,
  48913. err.loc.start.offset,
  48914. err.loc.end.offset
  48915. ) + `
  48916. `;
  48917. }
  48918. throw err;
  48919. }
  48920. if (preamble) {
  48921. ctx.s.prepend(preamble);
  48922. }
  48923. if (ast && ast.helpers.has(UNREF)) {
  48924. ctx.helperImports.delete("unref");
  48925. }
  48926. returned = code;
  48927. } else {
  48928. returned = `() => {}`;
  48929. }
  48930. }
  48931. if (!options.inlineTemplate && true) {
  48932. ctx.s.appendRight(
  48933. endOffset,
  48934. `
  48935. const __returned__ = ${returned}
  48936. Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })
  48937. return __returned__
  48938. }
  48939. `
  48940. );
  48941. } else {
  48942. ctx.s.appendRight(endOffset, `
  48943. return ${returned}
  48944. }
  48945. `);
  48946. }
  48947. const genDefaultAs = options.genDefaultAs ? `const ${options.genDefaultAs} =` : `export default`;
  48948. let runtimeOptions = ``;
  48949. if (!ctx.hasDefaultExportName && filename && filename !== DEFAULT_FILENAME) {
  48950. const match = filename.match(/([^/\\]+)\.\w+$/);
  48951. if (match) {
  48952. runtimeOptions += `
  48953. __name: '${match[1]}',`;
  48954. }
  48955. }
  48956. if (hasInlinedSsrRenderFn) {
  48957. runtimeOptions += `
  48958. __ssrInlineRender: true,`;
  48959. }
  48960. if (propsDecl) runtimeOptions += `
  48961. props: ${propsDecl},`;
  48962. const emitsDecl = genRuntimeEmits(ctx);
  48963. if (emitsDecl) runtimeOptions += `
  48964. emits: ${emitsDecl},`;
  48965. let definedOptions = "";
  48966. if (ctx.optionsRuntimeDecl) {
  48967. definedOptions = scriptSetup.content.slice(ctx.optionsRuntimeDecl.start, ctx.optionsRuntimeDecl.end).trim();
  48968. }
  48969. const exposeCall = ctx.hasDefineExposeCall || options.inlineTemplate ? `` : ` __expose();
  48970. `;
  48971. if (ctx.isTS) {
  48972. const def = (defaultExport ? `
  48973. ...${normalScriptDefaultVar},` : ``) + (definedOptions ? `
  48974. ...${definedOptions},` : "");
  48975. ctx.s.prependLeft(
  48976. startOffset,
  48977. `
  48978. ${genDefaultAs} /*@__PURE__*/${ctx.helper(
  48979. `defineComponent`
  48980. )}({${def}${runtimeOptions}
  48981. ${hasAwait ? `async ` : ``}setup(${args}) {
  48982. ${exposeCall}`
  48983. );
  48984. ctx.s.appendRight(endOffset, `})`);
  48985. } else {
  48986. if (defaultExport || definedOptions) {
  48987. ctx.s.prependLeft(
  48988. startOffset,
  48989. `
  48990. ${genDefaultAs} /*@__PURE__*/Object.assign(${defaultExport ? `${normalScriptDefaultVar}, ` : ""}${definedOptions ? `${definedOptions}, ` : ""}{${runtimeOptions}
  48991. ${hasAwait ? `async ` : ``}setup(${args}) {
  48992. ${exposeCall}`
  48993. );
  48994. ctx.s.appendRight(endOffset, `})`);
  48995. } else {
  48996. ctx.s.prependLeft(
  48997. startOffset,
  48998. `
  48999. ${genDefaultAs} {${runtimeOptions}
  49000. ${hasAwait ? `async ` : ``}setup(${args}) {
  49001. ${exposeCall}`
  49002. );
  49003. ctx.s.appendRight(endOffset, `}`);
  49004. }
  49005. }
  49006. if (ctx.helperImports.size > 0) {
  49007. const runtimeModuleName = (_c = (_b = options.templateOptions) == null ? void 0 : _b.compilerOptions) == null ? void 0 : _c.runtimeModuleName;
  49008. const importSrc = runtimeModuleName ? JSON.stringify(runtimeModuleName) : `'vue'`;
  49009. ctx.s.prepend(
  49010. `import { ${[...ctx.helperImports].map((h) => `${h} as _${h}`).join(", ")} } from ${importSrc}
  49011. `
  49012. );
  49013. }
  49014. const content = ctx.s.toString();
  49015. let map = options.sourceMap !== false ? ctx.s.generateMap({
  49016. source: filename,
  49017. hires: true,
  49018. includeContent: true
  49019. }) : void 0;
  49020. if (templateMap && map) {
  49021. const offset = content.indexOf(returned);
  49022. const templateLineOffset = content.slice(0, offset).split(/\r?\n/).length - 1;
  49023. map = mergeSourceMaps(map, templateMap, templateLineOffset);
  49024. }
  49025. return __spreadProps(__spreadValues$1({}, scriptSetup), {
  49026. bindings: ctx.bindingMetadata,
  49027. imports: ctx.userImports,
  49028. content,
  49029. map,
  49030. scriptAst: scriptAst == null ? void 0 : scriptAst.body,
  49031. scriptSetupAst: scriptSetupAst == null ? void 0 : scriptSetupAst.body,
  49032. deps: ctx.deps ? [...ctx.deps] : void 0
  49033. });
  49034. }
  49035. function registerBinding(bindings, node, type) {
  49036. bindings[node.name] = type;
  49037. }
  49038. function walkDeclaration(from, node, bindings, userImportAliases, hoistStatic, isPropsDestructureEnabled = false) {
  49039. let isAllLiteral = false;
  49040. if (node.type === "VariableDeclaration") {
  49041. const isConst = node.kind === "const";
  49042. isAllLiteral = isConst && node.declarations.every(
  49043. (decl) => decl.id.type === "Identifier" && isStaticNode(decl.init)
  49044. );
  49045. for (const { id, init: _init } of node.declarations) {
  49046. const init = _init && unwrapTSNode(_init);
  49047. const isConstMacroCall = isConst && isCallOf(
  49048. init,
  49049. (c) => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS || c === DEFINE_SLOTS
  49050. );
  49051. if (id.type === "Identifier") {
  49052. let bindingType;
  49053. const userReactiveBinding = userImportAliases["reactive"];
  49054. if ((hoistStatic || from === "script") && (isAllLiteral || isConst && isStaticNode(init))) {
  49055. bindingType = "literal-const";
  49056. } else if (isCallOf(init, userReactiveBinding)) {
  49057. bindingType = isConst ? "setup-reactive-const" : "setup-let";
  49058. } else if (
  49059. // if a declaration is a const literal, we can mark it so that
  49060. // the generated render fn code doesn't need to unref() it
  49061. isConstMacroCall || isConst && canNeverBeRef(init, userReactiveBinding)
  49062. ) {
  49063. bindingType = isCallOf(init, DEFINE_PROPS) ? "setup-reactive-const" : "setup-const";
  49064. } else if (isConst) {
  49065. if (isCallOf(
  49066. init,
  49067. (m) => m === userImportAliases["ref"] || m === userImportAliases["computed"] || m === userImportAliases["shallowRef"] || m === userImportAliases["customRef"] || m === userImportAliases["toRef"] || m === userImportAliases["useTemplateRef"] || m === DEFINE_MODEL
  49068. )) {
  49069. bindingType = "setup-ref";
  49070. } else {
  49071. bindingType = "setup-maybe-ref";
  49072. }
  49073. } else {
  49074. bindingType = "setup-let";
  49075. }
  49076. registerBinding(bindings, id, bindingType);
  49077. } else {
  49078. if (isCallOf(init, DEFINE_PROPS) && isPropsDestructureEnabled) {
  49079. continue;
  49080. }
  49081. if (id.type === "ObjectPattern") {
  49082. walkObjectPattern(id, bindings, isConst, isConstMacroCall);
  49083. } else if (id.type === "ArrayPattern") {
  49084. walkArrayPattern(id, bindings, isConst, isConstMacroCall);
  49085. }
  49086. }
  49087. }
  49088. } else if (node.type === "TSEnumDeclaration") {
  49089. isAllLiteral = node.members.every(
  49090. (member) => !member.initializer || isStaticNode(member.initializer)
  49091. );
  49092. bindings[node.id.name] = isAllLiteral ? "literal-const" : "setup-const";
  49093. } else if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
  49094. bindings[node.id.name] = "setup-const";
  49095. }
  49096. return isAllLiteral;
  49097. }
  49098. function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
  49099. for (const p of node.properties) {
  49100. if (p.type === "ObjectProperty") {
  49101. if (p.key.type === "Identifier" && p.key === p.value) {
  49102. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  49103. registerBinding(bindings, p.key, type);
  49104. } else {
  49105. walkPattern(p.value, bindings, isConst, isDefineCall);
  49106. }
  49107. } else {
  49108. const type = isConst ? "setup-const" : "setup-let";
  49109. registerBinding(bindings, p.argument, type);
  49110. }
  49111. }
  49112. }
  49113. function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
  49114. for (const e of node.elements) {
  49115. e && walkPattern(e, bindings, isConst, isDefineCall);
  49116. }
  49117. }
  49118. function walkPattern(node, bindings, isConst, isDefineCall = false) {
  49119. if (node.type === "Identifier") {
  49120. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  49121. registerBinding(bindings, node, type);
  49122. } else if (node.type === "RestElement") {
  49123. const type = isConst ? "setup-const" : "setup-let";
  49124. registerBinding(bindings, node.argument, type);
  49125. } else if (node.type === "ObjectPattern") {
  49126. walkObjectPattern(node, bindings, isConst);
  49127. } else if (node.type === "ArrayPattern") {
  49128. walkArrayPattern(node, bindings, isConst);
  49129. } else if (node.type === "AssignmentPattern") {
  49130. if (node.left.type === "Identifier") {
  49131. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  49132. registerBinding(bindings, node.left, type);
  49133. } else {
  49134. walkPattern(node.left, bindings, isConst);
  49135. }
  49136. }
  49137. }
  49138. function canNeverBeRef(node, userReactiveImport) {
  49139. if (isCallOf(node, userReactiveImport)) {
  49140. return true;
  49141. }
  49142. switch (node.type) {
  49143. case "UnaryExpression":
  49144. case "BinaryExpression":
  49145. case "ArrayExpression":
  49146. case "ObjectExpression":
  49147. case "FunctionExpression":
  49148. case "ArrowFunctionExpression":
  49149. case "UpdateExpression":
  49150. case "ClassExpression":
  49151. case "TaggedTemplateExpression":
  49152. return true;
  49153. case "SequenceExpression":
  49154. return canNeverBeRef(
  49155. node.expressions[node.expressions.length - 1],
  49156. userReactiveImport
  49157. );
  49158. default:
  49159. if (isLiteralNode(node)) {
  49160. return true;
  49161. }
  49162. return false;
  49163. }
  49164. }
  49165. function isStaticNode(node) {
  49166. node = unwrapTSNode(node);
  49167. switch (node.type) {
  49168. case "UnaryExpression":
  49169. return isStaticNode(node.argument);
  49170. case "LogicalExpression":
  49171. // 1 > 2
  49172. case "BinaryExpression":
  49173. return isStaticNode(node.left) && isStaticNode(node.right);
  49174. case "ConditionalExpression": {
  49175. return isStaticNode(node.test) && isStaticNode(node.consequent) && isStaticNode(node.alternate);
  49176. }
  49177. case "SequenceExpression":
  49178. // (1, 2)
  49179. case "TemplateLiteral":
  49180. return node.expressions.every((expr) => isStaticNode(expr));
  49181. case "ParenthesizedExpression":
  49182. return isStaticNode(node.expression);
  49183. case "StringLiteral":
  49184. case "NumericLiteral":
  49185. case "BooleanLiteral":
  49186. case "NullLiteral":
  49187. case "BigIntLiteral":
  49188. return true;
  49189. }
  49190. return false;
  49191. }
  49192. function mergeSourceMaps(scriptMap, templateMap, templateLineOffset) {
  49193. const generator = new sourceMapExports.SourceMapGenerator();
  49194. const addMapping = (map, lineOffset = 0) => {
  49195. const consumer = new sourceMapExports.SourceMapConsumer(map);
  49196. consumer.sources.forEach((sourceFile) => {
  49197. generator._sources.add(sourceFile);
  49198. const sourceContent = consumer.sourceContentFor(sourceFile);
  49199. if (sourceContent != null) {
  49200. generator.setSourceContent(sourceFile, sourceContent);
  49201. }
  49202. });
  49203. consumer.eachMapping((m) => {
  49204. if (m.originalLine == null) return;
  49205. generator.addMapping({
  49206. generated: {
  49207. line: m.generatedLine + lineOffset,
  49208. column: m.generatedColumn
  49209. },
  49210. original: {
  49211. line: m.originalLine,
  49212. column: m.originalColumn
  49213. },
  49214. source: m.source,
  49215. name: m.name
  49216. });
  49217. });
  49218. };
  49219. addMapping(scriptMap);
  49220. addMapping(templateMap, templateLineOffset);
  49221. generator._sourceRoot = scriptMap.sourceRoot;
  49222. generator._file = scriptMap.file;
  49223. return generator.toJSON();
  49224. }
  49225. var __defProp = Object.defineProperty;
  49226. var __getOwnPropSymbols = Object.getOwnPropertySymbols;
  49227. var __hasOwnProp = Object.prototype.hasOwnProperty;
  49228. var __propIsEnum = Object.prototype.propertyIsEnumerable;
  49229. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  49230. var __spreadValues = (a, b) => {
  49231. for (var prop in b || (b = {}))
  49232. if (__hasOwnProp.call(b, prop))
  49233. __defNormalProp(a, prop, b[prop]);
  49234. if (__getOwnPropSymbols)
  49235. for (var prop of __getOwnPropSymbols(b)) {
  49236. if (__propIsEnum.call(b, prop))
  49237. __defNormalProp(a, prop, b[prop]);
  49238. }
  49239. return a;
  49240. };
  49241. const version = "3.5.42";
  49242. const parseCache = parseCache$1;
  49243. const errorMessages = __spreadValues(__spreadValues({}, errorMessages$1), DOMErrorMessages);
  49244. const walk = walk$2;
  49245. const shouldTransformRef = () => false;
  49246. var parse$4 = libExports.parse;
  49247. 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 };