compiler-sfc.cjs.js 871 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297
  1. /**
  2. * @vue/compiler-sfc v3.5.42
  3. * (c) 2018-present Yuxi (Evan) You and Vue contributors
  4. * @license MIT
  5. **/
  6. 'use strict';
  7. Object.defineProperty(exports, '__esModule', { value: true });
  8. var compilerCore = require('@vue/compiler-core');
  9. var CompilerDOM = require('@vue/compiler-dom');
  10. var sourceMapJs = require('source-map-js');
  11. var shared = require('@vue/shared');
  12. var path$1 = require('path');
  13. var url = require('url');
  14. var CompilerSSR = require('@vue/compiler-ssr');
  15. var require$$2 = require('util');
  16. var require$$0 = require('fs');
  17. var require$$0$1 = require('postcss');
  18. var estreeWalker = require('estree-walker');
  19. var MagicString = require('magic-string');
  20. var parser$2 = require('@babel/parser');
  21. var process$1 = require('process');
  22. function _interopNamespaceDefault(e) {
  23. var n = Object.create(null);
  24. if (e) {
  25. for (var k in e) {
  26. n[k] = e[k];
  27. }
  28. }
  29. n.default = e;
  30. return Object.freeze(n);
  31. }
  32. var CompilerDOM__namespace = /*#__PURE__*/_interopNamespaceDefault(CompilerDOM);
  33. var CompilerSSR__namespace = /*#__PURE__*/_interopNamespaceDefault(CompilerSSR);
  34. var process__namespace = /*#__PURE__*/_interopNamespaceDefault(process$1);
  35. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  36. function getDefaultExportFromCjs (x) {
  37. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  38. }
  39. var hashSum;
  40. var hasRequiredHashSum;
  41. function requireHashSum () {
  42. if (hasRequiredHashSum) return hashSum;
  43. hasRequiredHashSum = 1;
  44. function pad (hash, len) {
  45. while (hash.length < len) {
  46. hash = '0' + hash;
  47. }
  48. return hash;
  49. }
  50. function fold (hash, text) {
  51. var i;
  52. var chr;
  53. var len;
  54. if (text.length === 0) {
  55. return hash;
  56. }
  57. for (i = 0, len = text.length; i < len; i++) {
  58. chr = text.charCodeAt(i);
  59. hash = ((hash << 5) - hash) + chr;
  60. hash |= 0;
  61. }
  62. return hash < 0 ? hash * -2 : hash;
  63. }
  64. function foldObject (hash, o, seen) {
  65. return Object.keys(o).sort().reduce(foldKey, hash);
  66. function foldKey (hash, key) {
  67. return foldValue(hash, o[key], key, seen);
  68. }
  69. }
  70. function foldValue (input, value, key, seen) {
  71. var hash = fold(fold(fold(input, key), toString(value)), typeof value);
  72. if (value === null) {
  73. return fold(hash, 'null');
  74. }
  75. if (value === undefined) {
  76. return fold(hash, 'undefined');
  77. }
  78. if (typeof value === 'object' || typeof value === 'function') {
  79. if (seen.indexOf(value) !== -1) {
  80. return fold(hash, '[Circular]' + key);
  81. }
  82. seen.push(value);
  83. var objHash = foldObject(hash, value, seen);
  84. if (!('valueOf' in value) || typeof value.valueOf !== 'function') {
  85. return objHash;
  86. }
  87. try {
  88. return fold(objHash, String(value.valueOf()))
  89. } catch (err) {
  90. return fold(objHash, '[valueOf exception]' + (err.stack || err.message))
  91. }
  92. }
  93. return fold(hash, value.toString());
  94. }
  95. function toString (o) {
  96. return Object.prototype.toString.call(o);
  97. }
  98. function sum (o) {
  99. return pad(foldValue(0, o, '', []).toString(16), 8);
  100. }
  101. hashSum = sum;
  102. return hashSum;
  103. }
  104. var hashSumExports = /*@__PURE__*/ requireHashSum();
  105. var hash = /*@__PURE__*/getDefaultExportFromCjs(hashSumExports);
  106. const CSS_VARS_HELPER = `useCssVars`;
  107. function genCssVarsFromList(vars, id, isProd, isSSR = false) {
  108. return `{
  109. ${vars.map(
  110. (key) => (
  111. // The `:` prefix here is used in `ssrRenderStyle` to distinguish whether
  112. // a custom property comes from `ssrCssVars`. If it does, we need to reset
  113. // its value to `initial` on the component instance to avoid unintentionally
  114. // inheriting the same property value from a different instance of the same
  115. // component in the outer scope.
  116. `"${isSSR ? `:--` : ``}${genVarName(id, key, isProd, isSSR)}": (${key})`
  117. )
  118. ).join(",\n ")}
  119. }`;
  120. }
  121. function genVarName(id, raw, isProd, isSSR = false) {
  122. if (isProd) {
  123. return hash(id + raw).replace(/^\d/, (r) => `v${r}`);
  124. } else {
  125. return `${id}-${shared.getEscapedCssVarName(raw, isSSR)}`;
  126. }
  127. }
  128. function normalizeExpression(exp) {
  129. exp = exp.trim();
  130. if (exp[0] === `'` && exp[exp.length - 1] === `'` || exp[0] === `"` && exp[exp.length - 1] === `"`) {
  131. return exp.slice(1, -1);
  132. }
  133. return exp;
  134. }
  135. const vBindRE = /v-bind\s*\(/g;
  136. function parseCssVars(sfc) {
  137. const vars = [];
  138. sfc.styles.forEach((style) => {
  139. let match;
  140. const content = style.content.replace(/\/\*([\s\S]*?)\*\/|\/\/.*/g, "");
  141. while (match = vBindRE.exec(content)) {
  142. const start = match.index + match[0].length;
  143. const end = lexBinding(content, start);
  144. if (end !== null) {
  145. const variable = normalizeExpression(content.slice(start, end));
  146. if (!vars.includes(variable)) {
  147. vars.push(variable);
  148. }
  149. }
  150. }
  151. });
  152. return vars;
  153. }
  154. function lexBinding(content, start) {
  155. let state = 0 /* inParens */;
  156. let parenDepth = 0;
  157. for (let i = start; i < content.length; i++) {
  158. const char = content.charAt(i);
  159. switch (state) {
  160. case 0 /* inParens */:
  161. if (char === `'`) {
  162. state = 1 /* inSingleQuoteString */;
  163. } else if (char === `"`) {
  164. state = 2 /* inDoubleQuoteString */;
  165. } else if (char === `(`) {
  166. parenDepth++;
  167. } else if (char === `)`) {
  168. if (parenDepth > 0) {
  169. parenDepth--;
  170. } else {
  171. return i;
  172. }
  173. }
  174. break;
  175. case 1 /* inSingleQuoteString */:
  176. if (char === `'`) {
  177. state = 0 /* inParens */;
  178. }
  179. break;
  180. case 2 /* inDoubleQuoteString */:
  181. if (char === `"`) {
  182. state = 0 /* inParens */;
  183. }
  184. break;
  185. }
  186. }
  187. return null;
  188. }
  189. const cssVarsPlugin = (opts) => {
  190. const { id, isProd } = opts;
  191. return {
  192. postcssPlugin: "vue-sfc-vars",
  193. Declaration(decl) {
  194. const value = decl.value;
  195. if (vBindRE.test(value)) {
  196. vBindRE.lastIndex = 0;
  197. let transformed = "";
  198. let lastIndex = 0;
  199. let match;
  200. while (match = vBindRE.exec(value)) {
  201. const start = match.index + match[0].length;
  202. const end = lexBinding(value, start);
  203. if (end !== null) {
  204. const variable = normalizeExpression(value.slice(start, end));
  205. transformed += value.slice(lastIndex, match.index) + `var(--${genVarName(id, variable, isProd)})`;
  206. lastIndex = end + 1;
  207. }
  208. }
  209. decl.value = transformed + value.slice(lastIndex);
  210. }
  211. }
  212. };
  213. };
  214. cssVarsPlugin.postcss = true;
  215. function genCssVarsCode(vars, bindings, id, isProd) {
  216. const varsExp = genCssVarsFromList(vars, id, isProd);
  217. const exp = CompilerDOM.createSimpleExpression(varsExp, false);
  218. const context = CompilerDOM.createTransformContext(CompilerDOM.createRoot([]), {
  219. prefixIdentifiers: true,
  220. inline: true,
  221. bindingMetadata: bindings.__isScriptSetup === false ? void 0 : bindings
  222. });
  223. const transformed = CompilerDOM.processExpression(exp, context);
  224. const transformedString = transformed.type === 4 ? transformed.content : transformed.children.map((c) => {
  225. return typeof c === "string" ? c : c.content;
  226. }).join("");
  227. return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`;
  228. }
  229. function genNormalScriptCssVarsCode(cssVars, bindings, id, isProd, defaultVar) {
  230. return `
  231. import { ${CSS_VARS_HELPER} as _${CSS_VARS_HELPER} } from 'vue'
  232. const __injectCSSVars__ = () => {
  233. ${genCssVarsCode(
  234. cssVars,
  235. bindings,
  236. id,
  237. isProd
  238. )}}
  239. const __setup__ = ${defaultVar}.setup
  240. ${defaultVar}.setup = __setup__
  241. ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }
  242. : __injectCSSVars__
  243. `;
  244. }
  245. /**
  246. * @module LRUCache
  247. */
  248. const perf = typeof performance === 'object' &&
  249. performance &&
  250. typeof performance.now === 'function'
  251. ? performance
  252. : Date;
  253. const warned = new Set();
  254. /* c8 ignore start */
  255. const PROCESS = (typeof process === 'object' && !!process ? process : {});
  256. /* c8 ignore start */
  257. const emitWarning = (msg, type, code, fn) => {
  258. typeof PROCESS.emitWarning === 'function'
  259. ? PROCESS.emitWarning(msg, type, code, fn)
  260. : console.error(`[${code}] ${type}: ${msg}`);
  261. };
  262. let AC = globalThis.AbortController;
  263. let AS = globalThis.AbortSignal;
  264. /* c8 ignore start */
  265. if (typeof AC === 'undefined') {
  266. //@ts-ignore
  267. AS = class AbortSignal {
  268. onabort;
  269. _onabort = [];
  270. reason;
  271. aborted = false;
  272. addEventListener(_, fn) {
  273. this._onabort.push(fn);
  274. }
  275. };
  276. //@ts-ignore
  277. AC = class AbortController {
  278. constructor() {
  279. warnACPolyfill();
  280. }
  281. signal = new AS();
  282. abort(reason) {
  283. if (this.signal.aborted)
  284. return;
  285. //@ts-ignore
  286. this.signal.reason = reason;
  287. //@ts-ignore
  288. this.signal.aborted = true;
  289. //@ts-ignore
  290. for (const fn of this.signal._onabort) {
  291. fn(reason);
  292. }
  293. this.signal.onabort?.(reason);
  294. }
  295. };
  296. let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1';
  297. const warnACPolyfill = () => {
  298. if (!printACPolyfillWarning)
  299. return;
  300. printACPolyfillWarning = false;
  301. emitWarning('AbortController is not defined. If using lru-cache in ' +
  302. 'node 14, load an AbortController polyfill from the ' +
  303. '`node-abort-controller` package. A minimal polyfill is ' +
  304. 'provided for use by LRUCache.fetch(), but it should not be ' +
  305. 'relied upon in other contexts (eg, passing it to other APIs that ' +
  306. 'use AbortController/AbortSignal might have undesirable effects). ' +
  307. 'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.', 'NO_ABORT_CONTROLLER', 'ENOTSUP', warnACPolyfill);
  308. };
  309. }
  310. /* c8 ignore stop */
  311. const shouldWarn = (code) => !warned.has(code);
  312. const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);
  313. /* c8 ignore start */
  314. // This is a little bit ridiculous, tbh.
  315. // The maximum array length is 2^32-1 or thereabouts on most JS impls.
  316. // And well before that point, you're caching the entire world, I mean,
  317. // that's ~32GB of just integers for the next/prev links, plus whatever
  318. // else to hold that many keys and values. Just filling the memory with
  319. // zeroes at init time is brutal when you get that big.
  320. // But why not be complete?
  321. // Maybe in the future, these limits will have expanded.
  322. const getUintArray = (max) => !isPosInt(max)
  323. ? null
  324. : max <= Math.pow(2, 8)
  325. ? Uint8Array
  326. : max <= Math.pow(2, 16)
  327. ? Uint16Array
  328. : max <= Math.pow(2, 32)
  329. ? Uint32Array
  330. : max <= Number.MAX_SAFE_INTEGER
  331. ? ZeroArray
  332. : null;
  333. /* c8 ignore stop */
  334. class ZeroArray extends Array {
  335. constructor(size) {
  336. super(size);
  337. this.fill(0);
  338. }
  339. }
  340. class Stack {
  341. heap;
  342. length;
  343. // private constructor
  344. static #constructing = false;
  345. static create(max) {
  346. const HeapCls = getUintArray(max);
  347. if (!HeapCls)
  348. return [];
  349. Stack.#constructing = true;
  350. const s = new Stack(max, HeapCls);
  351. Stack.#constructing = false;
  352. return s;
  353. }
  354. constructor(max, HeapCls) {
  355. /* c8 ignore start */
  356. if (!Stack.#constructing) {
  357. throw new TypeError('instantiate Stack using Stack.create(n)');
  358. }
  359. /* c8 ignore stop */
  360. this.heap = new HeapCls(max);
  361. this.length = 0;
  362. }
  363. push(n) {
  364. this.heap[this.length++] = n;
  365. }
  366. pop() {
  367. return this.heap[--this.length];
  368. }
  369. }
  370. /**
  371. * Default export, the thing you're using this module to get.
  372. *
  373. * All properties from the options object (with the exception of
  374. * {@link OptionsBase.max} and {@link OptionsBase.maxSize}) are added as
  375. * normal public members. (`max` and `maxBase` are read-only getters.)
  376. * Changing any of these will alter the defaults for subsequent method calls,
  377. * but is otherwise safe.
  378. */
  379. class LRUCache {
  380. // properties coming in from the options of these, only max and maxSize
  381. // really *need* to be protected. The rest can be modified, as they just
  382. // set defaults for various methods.
  383. #max;
  384. #maxSize;
  385. #dispose;
  386. #disposeAfter;
  387. #fetchMethod;
  388. /**
  389. * {@link LRUCache.OptionsBase.ttl}
  390. */
  391. ttl;
  392. /**
  393. * {@link LRUCache.OptionsBase.ttlResolution}
  394. */
  395. ttlResolution;
  396. /**
  397. * {@link LRUCache.OptionsBase.ttlAutopurge}
  398. */
  399. ttlAutopurge;
  400. /**
  401. * {@link LRUCache.OptionsBase.updateAgeOnGet}
  402. */
  403. updateAgeOnGet;
  404. /**
  405. * {@link LRUCache.OptionsBase.updateAgeOnHas}
  406. */
  407. updateAgeOnHas;
  408. /**
  409. * {@link LRUCache.OptionsBase.allowStale}
  410. */
  411. allowStale;
  412. /**
  413. * {@link LRUCache.OptionsBase.noDisposeOnSet}
  414. */
  415. noDisposeOnSet;
  416. /**
  417. * {@link LRUCache.OptionsBase.noUpdateTTL}
  418. */
  419. noUpdateTTL;
  420. /**
  421. * {@link LRUCache.OptionsBase.maxEntrySize}
  422. */
  423. maxEntrySize;
  424. /**
  425. * {@link LRUCache.OptionsBase.sizeCalculation}
  426. */
  427. sizeCalculation;
  428. /**
  429. * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
  430. */
  431. noDeleteOnFetchRejection;
  432. /**
  433. * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
  434. */
  435. noDeleteOnStaleGet;
  436. /**
  437. * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
  438. */
  439. allowStaleOnFetchAbort;
  440. /**
  441. * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
  442. */
  443. allowStaleOnFetchRejection;
  444. /**
  445. * {@link LRUCache.OptionsBase.ignoreFetchAbort}
  446. */
  447. ignoreFetchAbort;
  448. // computed properties
  449. #size;
  450. #calculatedSize;
  451. #keyMap;
  452. #keyList;
  453. #valList;
  454. #next;
  455. #prev;
  456. #head;
  457. #tail;
  458. #free;
  459. #disposed;
  460. #sizes;
  461. #starts;
  462. #ttls;
  463. #hasDispose;
  464. #hasFetchMethod;
  465. #hasDisposeAfter;
  466. /**
  467. * Do not call this method unless you need to inspect the
  468. * inner workings of the cache. If anything returned by this
  469. * object is modified in any way, strange breakage may occur.
  470. *
  471. * These fields are private for a reason!
  472. *
  473. * @internal
  474. */
  475. static unsafeExposeInternals(c) {
  476. return {
  477. // properties
  478. starts: c.#starts,
  479. ttls: c.#ttls,
  480. sizes: c.#sizes,
  481. keyMap: c.#keyMap,
  482. keyList: c.#keyList,
  483. valList: c.#valList,
  484. next: c.#next,
  485. prev: c.#prev,
  486. get head() {
  487. return c.#head;
  488. },
  489. get tail() {
  490. return c.#tail;
  491. },
  492. free: c.#free,
  493. // methods
  494. isBackgroundFetch: (p) => c.#isBackgroundFetch(p),
  495. backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context),
  496. moveToTail: (index) => c.#moveToTail(index),
  497. indexes: (options) => c.#indexes(options),
  498. rindexes: (options) => c.#rindexes(options),
  499. isStale: (index) => c.#isStale(index),
  500. };
  501. }
  502. // Protected read-only members
  503. /**
  504. * {@link LRUCache.OptionsBase.max} (read-only)
  505. */
  506. get max() {
  507. return this.#max;
  508. }
  509. /**
  510. * {@link LRUCache.OptionsBase.maxSize} (read-only)
  511. */
  512. get maxSize() {
  513. return this.#maxSize;
  514. }
  515. /**
  516. * The total computed size of items in the cache (read-only)
  517. */
  518. get calculatedSize() {
  519. return this.#calculatedSize;
  520. }
  521. /**
  522. * The number of items stored in the cache (read-only)
  523. */
  524. get size() {
  525. return this.#size;
  526. }
  527. /**
  528. * {@link LRUCache.OptionsBase.fetchMethod} (read-only)
  529. */
  530. get fetchMethod() {
  531. return this.#fetchMethod;
  532. }
  533. /**
  534. * {@link LRUCache.OptionsBase.dispose} (read-only)
  535. */
  536. get dispose() {
  537. return this.#dispose;
  538. }
  539. /**
  540. * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
  541. */
  542. get disposeAfter() {
  543. return this.#disposeAfter;
  544. }
  545. constructor(options) {
  546. const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, } = options;
  547. if (max !== 0 && !isPosInt(max)) {
  548. throw new TypeError('max option must be a nonnegative integer');
  549. }
  550. const UintArray = max ? getUintArray(max) : Array;
  551. if (!UintArray) {
  552. throw new Error('invalid max value: ' + max);
  553. }
  554. this.#max = max;
  555. this.#maxSize = maxSize;
  556. this.maxEntrySize = maxEntrySize || this.#maxSize;
  557. this.sizeCalculation = sizeCalculation;
  558. if (this.sizeCalculation) {
  559. if (!this.#maxSize && !this.maxEntrySize) {
  560. throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize');
  561. }
  562. if (typeof this.sizeCalculation !== 'function') {
  563. throw new TypeError('sizeCalculation set to non-function');
  564. }
  565. }
  566. if (fetchMethod !== undefined &&
  567. typeof fetchMethod !== 'function') {
  568. throw new TypeError('fetchMethod must be a function if specified');
  569. }
  570. this.#fetchMethod = fetchMethod;
  571. this.#hasFetchMethod = !!fetchMethod;
  572. this.#keyMap = new Map();
  573. this.#keyList = new Array(max).fill(undefined);
  574. this.#valList = new Array(max).fill(undefined);
  575. this.#next = new UintArray(max);
  576. this.#prev = new UintArray(max);
  577. this.#head = 0;
  578. this.#tail = 0;
  579. this.#free = Stack.create(max);
  580. this.#size = 0;
  581. this.#calculatedSize = 0;
  582. if (typeof dispose === 'function') {
  583. this.#dispose = dispose;
  584. }
  585. if (typeof disposeAfter === 'function') {
  586. this.#disposeAfter = disposeAfter;
  587. this.#disposed = [];
  588. }
  589. else {
  590. this.#disposeAfter = undefined;
  591. this.#disposed = undefined;
  592. }
  593. this.#hasDispose = !!this.#dispose;
  594. this.#hasDisposeAfter = !!this.#disposeAfter;
  595. this.noDisposeOnSet = !!noDisposeOnSet;
  596. this.noUpdateTTL = !!noUpdateTTL;
  597. this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
  598. this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
  599. this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
  600. this.ignoreFetchAbort = !!ignoreFetchAbort;
  601. // NB: maxEntrySize is set to maxSize if it's set
  602. if (this.maxEntrySize !== 0) {
  603. if (this.#maxSize !== 0) {
  604. if (!isPosInt(this.#maxSize)) {
  605. throw new TypeError('maxSize must be a positive integer if specified');
  606. }
  607. }
  608. if (!isPosInt(this.maxEntrySize)) {
  609. throw new TypeError('maxEntrySize must be a positive integer if specified');
  610. }
  611. this.#initializeSizeTracking();
  612. }
  613. this.allowStale = !!allowStale;
  614. this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
  615. this.updateAgeOnGet = !!updateAgeOnGet;
  616. this.updateAgeOnHas = !!updateAgeOnHas;
  617. this.ttlResolution =
  618. isPosInt(ttlResolution) || ttlResolution === 0
  619. ? ttlResolution
  620. : 1;
  621. this.ttlAutopurge = !!ttlAutopurge;
  622. this.ttl = ttl || 0;
  623. if (this.ttl) {
  624. if (!isPosInt(this.ttl)) {
  625. throw new TypeError('ttl must be a positive integer if specified');
  626. }
  627. this.#initializeTTLTracking();
  628. }
  629. // do not allow completely unbounded caches
  630. if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
  631. throw new TypeError('At least one of max, maxSize, or ttl is required');
  632. }
  633. if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
  634. const code = 'LRU_CACHE_UNBOUNDED';
  635. if (shouldWarn(code)) {
  636. warned.add(code);
  637. const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' +
  638. 'result in unbounded memory consumption.';
  639. emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache);
  640. }
  641. }
  642. }
  643. /**
  644. * Return the remaining TTL time for a given entry key
  645. */
  646. getRemainingTTL(key) {
  647. return this.#keyMap.has(key) ? Infinity : 0;
  648. }
  649. #initializeTTLTracking() {
  650. const ttls = new ZeroArray(this.#max);
  651. const starts = new ZeroArray(this.#max);
  652. this.#ttls = ttls;
  653. this.#starts = starts;
  654. this.#setItemTTL = (index, ttl, start = perf.now()) => {
  655. starts[index] = ttl !== 0 ? start : 0;
  656. ttls[index] = ttl;
  657. if (ttl !== 0 && this.ttlAutopurge) {
  658. const t = setTimeout(() => {
  659. if (this.#isStale(index)) {
  660. this.delete(this.#keyList[index]);
  661. }
  662. }, ttl + 1);
  663. // unref() not supported on all platforms
  664. /* c8 ignore start */
  665. if (t.unref) {
  666. t.unref();
  667. }
  668. /* c8 ignore stop */
  669. }
  670. };
  671. this.#updateItemAge = index => {
  672. starts[index] = ttls[index] !== 0 ? perf.now() : 0;
  673. };
  674. this.#statusTTL = (status, index) => {
  675. if (ttls[index]) {
  676. const ttl = ttls[index];
  677. const start = starts[index];
  678. /* c8 ignore next */
  679. if (!ttl || !start)
  680. return;
  681. status.ttl = ttl;
  682. status.start = start;
  683. status.now = cachedNow || getNow();
  684. const age = status.now - start;
  685. status.remainingTTL = ttl - age;
  686. }
  687. };
  688. // debounce calls to perf.now() to 1s so we're not hitting
  689. // that costly call repeatedly.
  690. let cachedNow = 0;
  691. const getNow = () => {
  692. const n = perf.now();
  693. if (this.ttlResolution > 0) {
  694. cachedNow = n;
  695. const t = setTimeout(() => (cachedNow = 0), this.ttlResolution);
  696. // not available on all platforms
  697. /* c8 ignore start */
  698. if (t.unref) {
  699. t.unref();
  700. }
  701. /* c8 ignore stop */
  702. }
  703. return n;
  704. };
  705. this.getRemainingTTL = key => {
  706. const index = this.#keyMap.get(key);
  707. if (index === undefined) {
  708. return 0;
  709. }
  710. const ttl = ttls[index];
  711. const start = starts[index];
  712. if (!ttl || !start) {
  713. return Infinity;
  714. }
  715. const age = (cachedNow || getNow()) - start;
  716. return ttl - age;
  717. };
  718. this.#isStale = index => {
  719. const s = starts[index];
  720. const t = ttls[index];
  721. return !!t && !!s && (cachedNow || getNow()) - s > t;
  722. };
  723. }
  724. // conditionally set private methods related to TTL
  725. #updateItemAge = () => { };
  726. #statusTTL = () => { };
  727. #setItemTTL = () => { };
  728. /* c8 ignore stop */
  729. #isStale = () => false;
  730. #initializeSizeTracking() {
  731. const sizes = new ZeroArray(this.#max);
  732. this.#calculatedSize = 0;
  733. this.#sizes = sizes;
  734. this.#removeItemSize = index => {
  735. this.#calculatedSize -= sizes[index];
  736. sizes[index] = 0;
  737. };
  738. this.#requireSize = (k, v, size, sizeCalculation) => {
  739. // provisionally accept background fetches.
  740. // actual value size will be checked when they return.
  741. if (this.#isBackgroundFetch(v)) {
  742. return 0;
  743. }
  744. if (!isPosInt(size)) {
  745. if (sizeCalculation) {
  746. if (typeof sizeCalculation !== 'function') {
  747. throw new TypeError('sizeCalculation must be a function');
  748. }
  749. size = sizeCalculation(v, k);
  750. if (!isPosInt(size)) {
  751. throw new TypeError('sizeCalculation return invalid (expect positive integer)');
  752. }
  753. }
  754. else {
  755. throw new TypeError('invalid size value (must be positive integer). ' +
  756. 'When maxSize or maxEntrySize is used, sizeCalculation ' +
  757. 'or size must be set.');
  758. }
  759. }
  760. return size;
  761. };
  762. this.#addItemSize = (index, size, status) => {
  763. sizes[index] = size;
  764. if (this.#maxSize) {
  765. const maxSize = this.#maxSize - sizes[index];
  766. while (this.#calculatedSize > maxSize) {
  767. this.#evict(true);
  768. }
  769. }
  770. this.#calculatedSize += sizes[index];
  771. if (status) {
  772. status.entrySize = size;
  773. status.totalCalculatedSize = this.#calculatedSize;
  774. }
  775. };
  776. }
  777. #removeItemSize = _i => { };
  778. #addItemSize = (_i, _s, _st) => { };
  779. #requireSize = (_k, _v, size, sizeCalculation) => {
  780. if (size || sizeCalculation) {
  781. throw new TypeError('cannot set size without setting maxSize or maxEntrySize on cache');
  782. }
  783. return 0;
  784. };
  785. *#indexes({ allowStale = this.allowStale } = {}) {
  786. if (this.#size) {
  787. for (let i = this.#tail; true;) {
  788. if (!this.#isValidIndex(i)) {
  789. break;
  790. }
  791. if (allowStale || !this.#isStale(i)) {
  792. yield i;
  793. }
  794. if (i === this.#head) {
  795. break;
  796. }
  797. else {
  798. i = this.#prev[i];
  799. }
  800. }
  801. }
  802. }
  803. *#rindexes({ allowStale = this.allowStale } = {}) {
  804. if (this.#size) {
  805. for (let i = this.#head; true;) {
  806. if (!this.#isValidIndex(i)) {
  807. break;
  808. }
  809. if (allowStale || !this.#isStale(i)) {
  810. yield i;
  811. }
  812. if (i === this.#tail) {
  813. break;
  814. }
  815. else {
  816. i = this.#next[i];
  817. }
  818. }
  819. }
  820. }
  821. #isValidIndex(index) {
  822. return (index !== undefined &&
  823. this.#keyMap.get(this.#keyList[index]) === index);
  824. }
  825. /**
  826. * Return a generator yielding `[key, value]` pairs,
  827. * in order from most recently used to least recently used.
  828. */
  829. *entries() {
  830. for (const i of this.#indexes()) {
  831. if (this.#valList[i] !== undefined &&
  832. this.#keyList[i] !== undefined &&
  833. !this.#isBackgroundFetch(this.#valList[i])) {
  834. yield [this.#keyList[i], this.#valList[i]];
  835. }
  836. }
  837. }
  838. /**
  839. * Inverse order version of {@link LRUCache.entries}
  840. *
  841. * Return a generator yielding `[key, value]` pairs,
  842. * in order from least recently used to most recently used.
  843. */
  844. *rentries() {
  845. for (const i of this.#rindexes()) {
  846. if (this.#valList[i] !== undefined &&
  847. this.#keyList[i] !== undefined &&
  848. !this.#isBackgroundFetch(this.#valList[i])) {
  849. yield [this.#keyList[i], this.#valList[i]];
  850. }
  851. }
  852. }
  853. /**
  854. * Return a generator yielding the keys in the cache,
  855. * in order from most recently used to least recently used.
  856. */
  857. *keys() {
  858. for (const i of this.#indexes()) {
  859. const k = this.#keyList[i];
  860. if (k !== undefined &&
  861. !this.#isBackgroundFetch(this.#valList[i])) {
  862. yield k;
  863. }
  864. }
  865. }
  866. /**
  867. * Inverse order version of {@link LRUCache.keys}
  868. *
  869. * Return a generator yielding the keys in the cache,
  870. * in order from least recently used to most recently used.
  871. */
  872. *rkeys() {
  873. for (const i of this.#rindexes()) {
  874. const k = this.#keyList[i];
  875. if (k !== undefined &&
  876. !this.#isBackgroundFetch(this.#valList[i])) {
  877. yield k;
  878. }
  879. }
  880. }
  881. /**
  882. * Return a generator yielding the values in the cache,
  883. * in order from most recently used to least recently used.
  884. */
  885. *values() {
  886. for (const i of this.#indexes()) {
  887. const v = this.#valList[i];
  888. if (v !== undefined &&
  889. !this.#isBackgroundFetch(this.#valList[i])) {
  890. yield this.#valList[i];
  891. }
  892. }
  893. }
  894. /**
  895. * Inverse order version of {@link LRUCache.values}
  896. *
  897. * Return a generator yielding the values in the cache,
  898. * in order from least recently used to most recently used.
  899. */
  900. *rvalues() {
  901. for (const i of this.#rindexes()) {
  902. const v = this.#valList[i];
  903. if (v !== undefined &&
  904. !this.#isBackgroundFetch(this.#valList[i])) {
  905. yield this.#valList[i];
  906. }
  907. }
  908. }
  909. /**
  910. * Iterating over the cache itself yields the same results as
  911. * {@link LRUCache.entries}
  912. */
  913. [Symbol.iterator]() {
  914. return this.entries();
  915. }
  916. /**
  917. * Find a value for which the supplied fn method returns a truthy value,
  918. * similar to Array.find(). fn is called as fn(value, key, cache).
  919. */
  920. find(fn, getOptions = {}) {
  921. for (const i of this.#indexes()) {
  922. const v = this.#valList[i];
  923. const value = this.#isBackgroundFetch(v)
  924. ? v.__staleWhileFetching
  925. : v;
  926. if (value === undefined)
  927. continue;
  928. if (fn(value, this.#keyList[i], this)) {
  929. return this.get(this.#keyList[i], getOptions);
  930. }
  931. }
  932. }
  933. /**
  934. * Call the supplied function on each item in the cache, in order from
  935. * most recently used to least recently used. fn is called as
  936. * fn(value, key, cache). Does not update age or recenty of use.
  937. * Does not iterate over stale values.
  938. */
  939. forEach(fn, thisp = this) {
  940. for (const i of this.#indexes()) {
  941. const v = this.#valList[i];
  942. const value = this.#isBackgroundFetch(v)
  943. ? v.__staleWhileFetching
  944. : v;
  945. if (value === undefined)
  946. continue;
  947. fn.call(thisp, value, this.#keyList[i], this);
  948. }
  949. }
  950. /**
  951. * The same as {@link LRUCache.forEach} but items are iterated over in
  952. * reverse order. (ie, less recently used items are iterated over first.)
  953. */
  954. rforEach(fn, thisp = this) {
  955. for (const i of this.#rindexes()) {
  956. const v = this.#valList[i];
  957. const value = this.#isBackgroundFetch(v)
  958. ? v.__staleWhileFetching
  959. : v;
  960. if (value === undefined)
  961. continue;
  962. fn.call(thisp, value, this.#keyList[i], this);
  963. }
  964. }
  965. /**
  966. * Delete any stale entries. Returns true if anything was removed,
  967. * false otherwise.
  968. */
  969. purgeStale() {
  970. let deleted = false;
  971. for (const i of this.#rindexes({ allowStale: true })) {
  972. if (this.#isStale(i)) {
  973. this.delete(this.#keyList[i]);
  974. deleted = true;
  975. }
  976. }
  977. return deleted;
  978. }
  979. /**
  980. * Get the extended info about a given entry, to get its value, size, and
  981. * TTL info simultaneously. Like {@link LRUCache#dump}, but just for a
  982. * single key. Always returns stale values, if their info is found in the
  983. * cache, so be sure to check for expired TTLs if relevant.
  984. */
  985. info(key) {
  986. const i = this.#keyMap.get(key);
  987. if (i === undefined)
  988. return undefined;
  989. const v = this.#valList[i];
  990. const value = this.#isBackgroundFetch(v)
  991. ? v.__staleWhileFetching
  992. : v;
  993. if (value === undefined)
  994. return undefined;
  995. const entry = { value };
  996. if (this.#ttls && this.#starts) {
  997. const ttl = this.#ttls[i];
  998. const start = this.#starts[i];
  999. if (ttl && start) {
  1000. const remain = ttl - (perf.now() - start);
  1001. entry.ttl = remain;
  1002. entry.start = Date.now();
  1003. }
  1004. }
  1005. if (this.#sizes) {
  1006. entry.size = this.#sizes[i];
  1007. }
  1008. return entry;
  1009. }
  1010. /**
  1011. * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
  1012. * passed to cache.load()
  1013. */
  1014. dump() {
  1015. const arr = [];
  1016. for (const i of this.#indexes({ allowStale: true })) {
  1017. const key = this.#keyList[i];
  1018. const v = this.#valList[i];
  1019. const value = this.#isBackgroundFetch(v)
  1020. ? v.__staleWhileFetching
  1021. : v;
  1022. if (value === undefined || key === undefined)
  1023. continue;
  1024. const entry = { value };
  1025. if (this.#ttls && this.#starts) {
  1026. entry.ttl = this.#ttls[i];
  1027. // always dump the start relative to a portable timestamp
  1028. // it's ok for this to be a bit slow, it's a rare operation.
  1029. const age = perf.now() - this.#starts[i];
  1030. entry.start = Math.floor(Date.now() - age);
  1031. }
  1032. if (this.#sizes) {
  1033. entry.size = this.#sizes[i];
  1034. }
  1035. arr.unshift([key, entry]);
  1036. }
  1037. return arr;
  1038. }
  1039. /**
  1040. * Reset the cache and load in the items in entries in the order listed.
  1041. * Note that the shape of the resulting cache may be different if the
  1042. * same options are not used in both caches.
  1043. */
  1044. load(arr) {
  1045. this.clear();
  1046. for (const [key, entry] of arr) {
  1047. if (entry.start) {
  1048. // entry.start is a portable timestamp, but we may be using
  1049. // node's performance.now(), so calculate the offset, so that
  1050. // we get the intended remaining TTL, no matter how long it's
  1051. // been on ice.
  1052. //
  1053. // it's ok for this to be a bit slow, it's a rare operation.
  1054. const age = Date.now() - entry.start;
  1055. entry.start = perf.now() - age;
  1056. }
  1057. this.set(key, entry.value, entry);
  1058. }
  1059. }
  1060. /**
  1061. * Add a value to the cache.
  1062. *
  1063. * Note: if `undefined` is specified as a value, this is an alias for
  1064. * {@link LRUCache#delete}
  1065. */
  1066. set(k, v, setOptions = {}) {
  1067. if (v === undefined) {
  1068. this.delete(k);
  1069. return this;
  1070. }
  1071. const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions;
  1072. let { noUpdateTTL = this.noUpdateTTL } = setOptions;
  1073. const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
  1074. // if the item doesn't fit, don't do anything
  1075. // NB: maxEntrySize set to maxSize by default
  1076. if (this.maxEntrySize && size > this.maxEntrySize) {
  1077. if (status) {
  1078. status.set = 'miss';
  1079. status.maxEntrySizeExceeded = true;
  1080. }
  1081. // have to delete, in case something is there already.
  1082. this.delete(k);
  1083. return this;
  1084. }
  1085. let index = this.#size === 0 ? undefined : this.#keyMap.get(k);
  1086. if (index === undefined) {
  1087. // addition
  1088. index = (this.#size === 0
  1089. ? this.#tail
  1090. : this.#free.length !== 0
  1091. ? this.#free.pop()
  1092. : this.#size === this.#max
  1093. ? this.#evict(false)
  1094. : this.#size);
  1095. this.#keyList[index] = k;
  1096. this.#valList[index] = v;
  1097. this.#keyMap.set(k, index);
  1098. this.#next[this.#tail] = index;
  1099. this.#prev[index] = this.#tail;
  1100. this.#tail = index;
  1101. this.#size++;
  1102. this.#addItemSize(index, size, status);
  1103. if (status)
  1104. status.set = 'add';
  1105. noUpdateTTL = false;
  1106. }
  1107. else {
  1108. // update
  1109. this.#moveToTail(index);
  1110. const oldVal = this.#valList[index];
  1111. if (v !== oldVal) {
  1112. if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
  1113. oldVal.__abortController.abort(new Error('replaced'));
  1114. const { __staleWhileFetching: s } = oldVal;
  1115. if (s !== undefined && !noDisposeOnSet) {
  1116. if (this.#hasDispose) {
  1117. this.#dispose?.(s, k, 'set');
  1118. }
  1119. if (this.#hasDisposeAfter) {
  1120. this.#disposed?.push([s, k, 'set']);
  1121. }
  1122. }
  1123. }
  1124. else if (!noDisposeOnSet) {
  1125. if (this.#hasDispose) {
  1126. this.#dispose?.(oldVal, k, 'set');
  1127. }
  1128. if (this.#hasDisposeAfter) {
  1129. this.#disposed?.push([oldVal, k, 'set']);
  1130. }
  1131. }
  1132. this.#removeItemSize(index);
  1133. this.#addItemSize(index, size, status);
  1134. this.#valList[index] = v;
  1135. if (status) {
  1136. status.set = 'replace';
  1137. const oldValue = oldVal && this.#isBackgroundFetch(oldVal)
  1138. ? oldVal.__staleWhileFetching
  1139. : oldVal;
  1140. if (oldValue !== undefined)
  1141. status.oldValue = oldValue;
  1142. }
  1143. }
  1144. else if (status) {
  1145. status.set = 'update';
  1146. }
  1147. }
  1148. if (ttl !== 0 && !this.#ttls) {
  1149. this.#initializeTTLTracking();
  1150. }
  1151. if (this.#ttls) {
  1152. if (!noUpdateTTL) {
  1153. this.#setItemTTL(index, ttl, start);
  1154. }
  1155. if (status)
  1156. this.#statusTTL(status, index);
  1157. }
  1158. if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
  1159. const dt = this.#disposed;
  1160. let task;
  1161. while ((task = dt?.shift())) {
  1162. this.#disposeAfter?.(...task);
  1163. }
  1164. }
  1165. return this;
  1166. }
  1167. /**
  1168. * Evict the least recently used item, returning its value or
  1169. * `undefined` if cache is empty.
  1170. */
  1171. pop() {
  1172. try {
  1173. while (this.#size) {
  1174. const val = this.#valList[this.#head];
  1175. this.#evict(true);
  1176. if (this.#isBackgroundFetch(val)) {
  1177. if (val.__staleWhileFetching) {
  1178. return val.__staleWhileFetching;
  1179. }
  1180. }
  1181. else if (val !== undefined) {
  1182. return val;
  1183. }
  1184. }
  1185. }
  1186. finally {
  1187. if (this.#hasDisposeAfter && this.#disposed) {
  1188. const dt = this.#disposed;
  1189. let task;
  1190. while ((task = dt?.shift())) {
  1191. this.#disposeAfter?.(...task);
  1192. }
  1193. }
  1194. }
  1195. }
  1196. #evict(free) {
  1197. const head = this.#head;
  1198. const k = this.#keyList[head];
  1199. const v = this.#valList[head];
  1200. if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
  1201. v.__abortController.abort(new Error('evicted'));
  1202. }
  1203. else if (this.#hasDispose || this.#hasDisposeAfter) {
  1204. if (this.#hasDispose) {
  1205. this.#dispose?.(v, k, 'evict');
  1206. }
  1207. if (this.#hasDisposeAfter) {
  1208. this.#disposed?.push([v, k, 'evict']);
  1209. }
  1210. }
  1211. this.#removeItemSize(head);
  1212. // if we aren't about to use the index, then null these out
  1213. if (free) {
  1214. this.#keyList[head] = undefined;
  1215. this.#valList[head] = undefined;
  1216. this.#free.push(head);
  1217. }
  1218. if (this.#size === 1) {
  1219. this.#head = this.#tail = 0;
  1220. this.#free.length = 0;
  1221. }
  1222. else {
  1223. this.#head = this.#next[head];
  1224. }
  1225. this.#keyMap.delete(k);
  1226. this.#size--;
  1227. return head;
  1228. }
  1229. /**
  1230. * Check if a key is in the cache, without updating the recency of use.
  1231. * Will return false if the item is stale, even though it is technically
  1232. * in the cache.
  1233. *
  1234. * Will not update item age unless
  1235. * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
  1236. */
  1237. has(k, hasOptions = {}) {
  1238. const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
  1239. const index = this.#keyMap.get(k);
  1240. if (index !== undefined) {
  1241. const v = this.#valList[index];
  1242. if (this.#isBackgroundFetch(v) &&
  1243. v.__staleWhileFetching === undefined) {
  1244. return false;
  1245. }
  1246. if (!this.#isStale(index)) {
  1247. if (updateAgeOnHas) {
  1248. this.#updateItemAge(index);
  1249. }
  1250. if (status) {
  1251. status.has = 'hit';
  1252. this.#statusTTL(status, index);
  1253. }
  1254. return true;
  1255. }
  1256. else if (status) {
  1257. status.has = 'stale';
  1258. this.#statusTTL(status, index);
  1259. }
  1260. }
  1261. else if (status) {
  1262. status.has = 'miss';
  1263. }
  1264. return false;
  1265. }
  1266. /**
  1267. * Like {@link LRUCache#get} but doesn't update recency or delete stale
  1268. * items.
  1269. *
  1270. * Returns `undefined` if the item is stale, unless
  1271. * {@link LRUCache.OptionsBase.allowStale} is set.
  1272. */
  1273. peek(k, peekOptions = {}) {
  1274. const { allowStale = this.allowStale } = peekOptions;
  1275. const index = this.#keyMap.get(k);
  1276. if (index === undefined ||
  1277. (!allowStale && this.#isStale(index))) {
  1278. return;
  1279. }
  1280. const v = this.#valList[index];
  1281. // either stale and allowed, or forcing a refresh of non-stale value
  1282. return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
  1283. }
  1284. #backgroundFetch(k, index, options, context) {
  1285. const v = index === undefined ? undefined : this.#valList[index];
  1286. if (this.#isBackgroundFetch(v)) {
  1287. return v;
  1288. }
  1289. const ac = new AC();
  1290. const { signal } = options;
  1291. // when/if our AC signals, then stop listening to theirs.
  1292. signal?.addEventListener('abort', () => ac.abort(signal.reason), {
  1293. signal: ac.signal,
  1294. });
  1295. const fetchOpts = {
  1296. signal: ac.signal,
  1297. options,
  1298. context,
  1299. };
  1300. const cb = (v, updateCache = false) => {
  1301. const { aborted } = ac.signal;
  1302. const ignoreAbort = options.ignoreFetchAbort && v !== undefined;
  1303. if (options.status) {
  1304. if (aborted && !updateCache) {
  1305. options.status.fetchAborted = true;
  1306. options.status.fetchError = ac.signal.reason;
  1307. if (ignoreAbort)
  1308. options.status.fetchAbortIgnored = true;
  1309. }
  1310. else {
  1311. options.status.fetchResolved = true;
  1312. }
  1313. }
  1314. if (aborted && !ignoreAbort && !updateCache) {
  1315. return fetchFail(ac.signal.reason);
  1316. }
  1317. // either we didn't abort, and are still here, or we did, and ignored
  1318. const bf = p;
  1319. if (this.#valList[index] === p) {
  1320. if (v === undefined) {
  1321. if (bf.__staleWhileFetching) {
  1322. this.#valList[index] = bf.__staleWhileFetching;
  1323. }
  1324. else {
  1325. this.delete(k);
  1326. }
  1327. }
  1328. else {
  1329. if (options.status)
  1330. options.status.fetchUpdated = true;
  1331. this.set(k, v, fetchOpts.options);
  1332. }
  1333. }
  1334. return v;
  1335. };
  1336. const eb = (er) => {
  1337. if (options.status) {
  1338. options.status.fetchRejected = true;
  1339. options.status.fetchError = er;
  1340. }
  1341. return fetchFail(er);
  1342. };
  1343. const fetchFail = (er) => {
  1344. const { aborted } = ac.signal;
  1345. const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
  1346. const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
  1347. const noDelete = allowStale || options.noDeleteOnFetchRejection;
  1348. const bf = p;
  1349. if (this.#valList[index] === p) {
  1350. // if we allow stale on fetch rejections, then we need to ensure that
  1351. // the stale value is not removed from the cache when the fetch fails.
  1352. const del = !noDelete || bf.__staleWhileFetching === undefined;
  1353. if (del) {
  1354. this.delete(k);
  1355. }
  1356. else if (!allowStaleAborted) {
  1357. // still replace the *promise* with the stale value,
  1358. // since we are done with the promise at this point.
  1359. // leave it untouched if we're still waiting for an
  1360. // aborted background fetch that hasn't yet returned.
  1361. this.#valList[index] = bf.__staleWhileFetching;
  1362. }
  1363. }
  1364. if (allowStale) {
  1365. if (options.status && bf.__staleWhileFetching !== undefined) {
  1366. options.status.returnedStale = true;
  1367. }
  1368. return bf.__staleWhileFetching;
  1369. }
  1370. else if (bf.__returned === bf) {
  1371. throw er;
  1372. }
  1373. };
  1374. const pcall = (res, rej) => {
  1375. const fmp = this.#fetchMethod?.(k, v, fetchOpts);
  1376. if (fmp && fmp instanceof Promise) {
  1377. fmp.then(v => res(v === undefined ? undefined : v), rej);
  1378. }
  1379. // ignored, we go until we finish, regardless.
  1380. // defer check until we are actually aborting,
  1381. // so fetchMethod can override.
  1382. ac.signal.addEventListener('abort', () => {
  1383. if (!options.ignoreFetchAbort ||
  1384. options.allowStaleOnFetchAbort) {
  1385. res(undefined);
  1386. // when it eventually resolves, update the cache.
  1387. if (options.allowStaleOnFetchAbort) {
  1388. res = v => cb(v, true);
  1389. }
  1390. }
  1391. });
  1392. };
  1393. if (options.status)
  1394. options.status.fetchDispatched = true;
  1395. const p = new Promise(pcall).then(cb, eb);
  1396. const bf = Object.assign(p, {
  1397. __abortController: ac,
  1398. __staleWhileFetching: v,
  1399. __returned: undefined,
  1400. });
  1401. if (index === undefined) {
  1402. // internal, don't expose status.
  1403. this.set(k, bf, { ...fetchOpts.options, status: undefined });
  1404. index = this.#keyMap.get(k);
  1405. }
  1406. else {
  1407. this.#valList[index] = bf;
  1408. }
  1409. return bf;
  1410. }
  1411. #isBackgroundFetch(p) {
  1412. if (!this.#hasFetchMethod)
  1413. return false;
  1414. const b = p;
  1415. return (!!b &&
  1416. b instanceof Promise &&
  1417. b.hasOwnProperty('__staleWhileFetching') &&
  1418. b.__abortController instanceof AC);
  1419. }
  1420. async fetch(k, fetchOptions = {}) {
  1421. const {
  1422. // get options
  1423. allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet,
  1424. // set options
  1425. ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL,
  1426. // fetch exclusive options
  1427. noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = false, status, signal, } = fetchOptions;
  1428. if (!this.#hasFetchMethod) {
  1429. if (status)
  1430. status.fetch = 'get';
  1431. return this.get(k, {
  1432. allowStale,
  1433. updateAgeOnGet,
  1434. noDeleteOnStaleGet,
  1435. status,
  1436. });
  1437. }
  1438. const options = {
  1439. allowStale,
  1440. updateAgeOnGet,
  1441. noDeleteOnStaleGet,
  1442. ttl,
  1443. noDisposeOnSet,
  1444. size,
  1445. sizeCalculation,
  1446. noUpdateTTL,
  1447. noDeleteOnFetchRejection,
  1448. allowStaleOnFetchRejection,
  1449. allowStaleOnFetchAbort,
  1450. ignoreFetchAbort,
  1451. status,
  1452. signal,
  1453. };
  1454. let index = this.#keyMap.get(k);
  1455. if (index === undefined) {
  1456. if (status)
  1457. status.fetch = 'miss';
  1458. const p = this.#backgroundFetch(k, index, options, context);
  1459. return (p.__returned = p);
  1460. }
  1461. else {
  1462. // in cache, maybe already fetching
  1463. const v = this.#valList[index];
  1464. if (this.#isBackgroundFetch(v)) {
  1465. const stale = allowStale && v.__staleWhileFetching !== undefined;
  1466. if (status) {
  1467. status.fetch = 'inflight';
  1468. if (stale)
  1469. status.returnedStale = true;
  1470. }
  1471. return stale ? v.__staleWhileFetching : (v.__returned = v);
  1472. }
  1473. // if we force a refresh, that means do NOT serve the cached value,
  1474. // unless we are already in the process of refreshing the cache.
  1475. const isStale = this.#isStale(index);
  1476. if (!forceRefresh && !isStale) {
  1477. if (status)
  1478. status.fetch = 'hit';
  1479. this.#moveToTail(index);
  1480. if (updateAgeOnGet) {
  1481. this.#updateItemAge(index);
  1482. }
  1483. if (status)
  1484. this.#statusTTL(status, index);
  1485. return v;
  1486. }
  1487. // ok, it is stale or a forced refresh, and not already fetching.
  1488. // refresh the cache.
  1489. const p = this.#backgroundFetch(k, index, options, context);
  1490. const hasStale = p.__staleWhileFetching !== undefined;
  1491. const staleVal = hasStale && allowStale;
  1492. if (status) {
  1493. status.fetch = isStale ? 'stale' : 'refresh';
  1494. if (staleVal && isStale)
  1495. status.returnedStale = true;
  1496. }
  1497. return staleVal ? p.__staleWhileFetching : (p.__returned = p);
  1498. }
  1499. }
  1500. /**
  1501. * Return a value from the cache. Will update the recency of the cache
  1502. * entry found.
  1503. *
  1504. * If the key is not found, get() will return `undefined`.
  1505. */
  1506. get(k, getOptions = {}) {
  1507. const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions;
  1508. const index = this.#keyMap.get(k);
  1509. if (index !== undefined) {
  1510. const value = this.#valList[index];
  1511. const fetching = this.#isBackgroundFetch(value);
  1512. if (status)
  1513. this.#statusTTL(status, index);
  1514. if (this.#isStale(index)) {
  1515. if (status)
  1516. status.get = 'stale';
  1517. // delete only if not an in-flight background fetch
  1518. if (!fetching) {
  1519. if (!noDeleteOnStaleGet) {
  1520. this.delete(k);
  1521. }
  1522. if (status && allowStale)
  1523. status.returnedStale = true;
  1524. return allowStale ? value : undefined;
  1525. }
  1526. else {
  1527. if (status &&
  1528. allowStale &&
  1529. value.__staleWhileFetching !== undefined) {
  1530. status.returnedStale = true;
  1531. }
  1532. return allowStale ? value.__staleWhileFetching : undefined;
  1533. }
  1534. }
  1535. else {
  1536. if (status)
  1537. status.get = 'hit';
  1538. // if we're currently fetching it, we don't actually have it yet
  1539. // it's not stale, which means this isn't a staleWhileRefetching.
  1540. // If it's not stale, and fetching, AND has a __staleWhileFetching
  1541. // value, then that means the user fetched with {forceRefresh:true},
  1542. // so it's safe to return that value.
  1543. if (fetching) {
  1544. return value.__staleWhileFetching;
  1545. }
  1546. this.#moveToTail(index);
  1547. if (updateAgeOnGet) {
  1548. this.#updateItemAge(index);
  1549. }
  1550. return value;
  1551. }
  1552. }
  1553. else if (status) {
  1554. status.get = 'miss';
  1555. }
  1556. }
  1557. #connect(p, n) {
  1558. this.#prev[n] = p;
  1559. this.#next[p] = n;
  1560. }
  1561. #moveToTail(index) {
  1562. // if tail already, nothing to do
  1563. // if head, move head to next[index]
  1564. // else
  1565. // move next[prev[index]] to next[index] (head has no prev)
  1566. // move prev[next[index]] to prev[index]
  1567. // prev[index] = tail
  1568. // next[tail] = index
  1569. // tail = index
  1570. if (index !== this.#tail) {
  1571. if (index === this.#head) {
  1572. this.#head = this.#next[index];
  1573. }
  1574. else {
  1575. this.#connect(this.#prev[index], this.#next[index]);
  1576. }
  1577. this.#connect(this.#tail, index);
  1578. this.#tail = index;
  1579. }
  1580. }
  1581. /**
  1582. * Deletes a key out of the cache.
  1583. * Returns true if the key was deleted, false otherwise.
  1584. */
  1585. delete(k) {
  1586. let deleted = false;
  1587. if (this.#size !== 0) {
  1588. const index = this.#keyMap.get(k);
  1589. if (index !== undefined) {
  1590. deleted = true;
  1591. if (this.#size === 1) {
  1592. this.clear();
  1593. }
  1594. else {
  1595. this.#removeItemSize(index);
  1596. const v = this.#valList[index];
  1597. if (this.#isBackgroundFetch(v)) {
  1598. v.__abortController.abort(new Error('deleted'));
  1599. }
  1600. else if (this.#hasDispose || this.#hasDisposeAfter) {
  1601. if (this.#hasDispose) {
  1602. this.#dispose?.(v, k, 'delete');
  1603. }
  1604. if (this.#hasDisposeAfter) {
  1605. this.#disposed?.push([v, k, 'delete']);
  1606. }
  1607. }
  1608. this.#keyMap.delete(k);
  1609. this.#keyList[index] = undefined;
  1610. this.#valList[index] = undefined;
  1611. if (index === this.#tail) {
  1612. this.#tail = this.#prev[index];
  1613. }
  1614. else if (index === this.#head) {
  1615. this.#head = this.#next[index];
  1616. }
  1617. else {
  1618. const pi = this.#prev[index];
  1619. this.#next[pi] = this.#next[index];
  1620. const ni = this.#next[index];
  1621. this.#prev[ni] = this.#prev[index];
  1622. }
  1623. this.#size--;
  1624. this.#free.push(index);
  1625. }
  1626. }
  1627. }
  1628. if (this.#hasDisposeAfter && this.#disposed?.length) {
  1629. const dt = this.#disposed;
  1630. let task;
  1631. while ((task = dt?.shift())) {
  1632. this.#disposeAfter?.(...task);
  1633. }
  1634. }
  1635. return deleted;
  1636. }
  1637. /**
  1638. * Clear the cache entirely, throwing away all values.
  1639. */
  1640. clear() {
  1641. for (const index of this.#rindexes({ allowStale: true })) {
  1642. const v = this.#valList[index];
  1643. if (this.#isBackgroundFetch(v)) {
  1644. v.__abortController.abort(new Error('deleted'));
  1645. }
  1646. else {
  1647. const k = this.#keyList[index];
  1648. if (this.#hasDispose) {
  1649. this.#dispose?.(v, k, 'delete');
  1650. }
  1651. if (this.#hasDisposeAfter) {
  1652. this.#disposed?.push([v, k, 'delete']);
  1653. }
  1654. }
  1655. }
  1656. this.#keyMap.clear();
  1657. this.#valList.fill(undefined);
  1658. this.#keyList.fill(undefined);
  1659. if (this.#ttls && this.#starts) {
  1660. this.#ttls.fill(0);
  1661. this.#starts.fill(0);
  1662. }
  1663. if (this.#sizes) {
  1664. this.#sizes.fill(0);
  1665. }
  1666. this.#head = 0;
  1667. this.#tail = 0;
  1668. this.#free.length = 0;
  1669. this.#calculatedSize = 0;
  1670. this.#size = 0;
  1671. if (this.#hasDisposeAfter && this.#disposed) {
  1672. const dt = this.#disposed;
  1673. let task;
  1674. while ((task = dt?.shift())) {
  1675. this.#disposeAfter?.(...task);
  1676. }
  1677. }
  1678. }
  1679. }
  1680. function createCache(max = 500) {
  1681. return new LRUCache({ max });
  1682. }
  1683. function resolveTemplateAST(inAST, options) {
  1684. if (!(inAST == null ? void 0 : inAST.transformed)) {
  1685. return inAST;
  1686. }
  1687. const { compiler = CompilerDOM__namespace, compilerOptions, ssr, onError } = options;
  1688. const newAST = (ssr ? CompilerDOM__namespace : compiler).parse(inAST.source, {
  1689. prefixIdentifiers: true,
  1690. ...compilerOptions,
  1691. parseMode: "sfc",
  1692. onError
  1693. });
  1694. const template = newAST.children.find(
  1695. (node) => node.type === 1 && node.tag === "template"
  1696. );
  1697. return compilerCore.createRoot(template.children, inAST.source);
  1698. }
  1699. function isImportUsed(local, sfc, options) {
  1700. return resolveTemplateUsedIdentifiers(sfc, options).has(local);
  1701. }
  1702. const templateAnalysisCache = createCache();
  1703. function resolveTemplateVModelIdentifiers(sfc, options) {
  1704. return resolveTemplateAnalysisResult(sfc, false, options).vModelIds;
  1705. }
  1706. function resolveTemplateUsedIdentifiers(sfc, options) {
  1707. return resolveTemplateAnalysisResult(sfc, true, options).usedIds;
  1708. }
  1709. function resolveTemplateAnalysisResult(sfc, collectUsedIds = true, options) {
  1710. const { content, ast } = sfc.template;
  1711. const cached = templateAnalysisCache.get(content);
  1712. if (cached && (!collectUsedIds || cached.usedIds)) {
  1713. return cached;
  1714. }
  1715. const ids = collectUsedIds ? /* @__PURE__ */ new Set() : void 0;
  1716. const vModelIds = /* @__PURE__ */ new Set();
  1717. const root = resolveTemplateAST(ast, {
  1718. compiler: options == null ? void 0 : options.compiler,
  1719. compilerOptions: options == null ? void 0 : options.compilerOptions,
  1720. ssr: options == null ? void 0 : options.ssr,
  1721. // ignore errors since they were already reported by the SFC parser
  1722. onError: () => {
  1723. }
  1724. });
  1725. root.children.forEach(walk);
  1726. function walk(node) {
  1727. var _a;
  1728. switch (node.type) {
  1729. case 1:
  1730. let tag = node.tag;
  1731. if (tag.includes(".")) tag = tag.split(".")[0].trim();
  1732. if (!CompilerDOM.parserOptions.isNativeTag(tag) && !CompilerDOM.parserOptions.isBuiltInComponent(tag)) {
  1733. if (ids) {
  1734. ids.add(shared.camelize(tag));
  1735. ids.add(shared.capitalize(shared.camelize(tag)));
  1736. }
  1737. }
  1738. for (let i = 0; i < node.props.length; i++) {
  1739. const prop = node.props[i];
  1740. if (prop.type === 7) {
  1741. if (ids) {
  1742. if (!shared.isBuiltInDirective(prop.name)) {
  1743. ids.add(`v${shared.capitalize(shared.camelize(prop.name))}`);
  1744. }
  1745. }
  1746. if (prop.name === "model") {
  1747. const exp = prop.exp;
  1748. if (exp && exp.type === 4) {
  1749. const expString = exp.content.trim();
  1750. if (CompilerDOM.isSimpleIdentifier(expString) && expString !== "undefined") {
  1751. vModelIds.add(expString);
  1752. }
  1753. }
  1754. }
  1755. if (ids && prop.arg && !prop.arg.isStatic) {
  1756. extractIdentifiers(ids, prop.arg);
  1757. }
  1758. if (ids) {
  1759. if (prop.name === "for") {
  1760. extractIdentifiers(ids, prop.forParseResult.source);
  1761. } else if (prop.exp) {
  1762. extractIdentifiers(ids, prop.exp);
  1763. } else if (prop.name === "bind" && !prop.exp) {
  1764. ids.add(shared.camelize(prop.arg.content));
  1765. }
  1766. }
  1767. }
  1768. if (ids && prop.type === 6 && prop.name === "ref" && ((_a = prop.value) == null ? void 0 : _a.content)) {
  1769. ids.add(prop.value.content);
  1770. }
  1771. }
  1772. node.children.forEach(walk);
  1773. break;
  1774. case 5:
  1775. if (ids) extractIdentifiers(ids, node.content);
  1776. break;
  1777. }
  1778. }
  1779. const result = { usedIds: ids, vModelIds };
  1780. templateAnalysisCache.set(content, result);
  1781. return result;
  1782. }
  1783. function extractIdentifiers(ids, node) {
  1784. if (node.ast) {
  1785. CompilerDOM.walkIdentifiers(node.ast, (n) => ids.add(n.name));
  1786. } else if (node.ast === null) {
  1787. ids.add(node.content);
  1788. }
  1789. }
  1790. const DEFAULT_FILENAME = "anonymous.vue";
  1791. const parseCache$1 = createCache();
  1792. function parse$1(source, options = {}) {
  1793. var _a;
  1794. const sourceKey = shared.genCacheKey(source, {
  1795. ...options,
  1796. compiler: { parse: (_a = options.compiler) == null ? void 0 : _a.parse }
  1797. });
  1798. const cache = parseCache$1.get(sourceKey);
  1799. if (cache) {
  1800. return cache;
  1801. }
  1802. const {
  1803. sourceMap = true,
  1804. filename = DEFAULT_FILENAME,
  1805. sourceRoot = "",
  1806. pad = false,
  1807. ignoreEmpty = true,
  1808. compiler = CompilerDOM__namespace,
  1809. templateParseOptions = {}
  1810. } = options;
  1811. const descriptor = {
  1812. filename,
  1813. source,
  1814. template: null,
  1815. script: null,
  1816. scriptSetup: null,
  1817. styles: [],
  1818. customBlocks: [],
  1819. cssVars: [],
  1820. slotted: false,
  1821. shouldForceReload: (prevImports) => hmrShouldReload(prevImports, descriptor)
  1822. };
  1823. const errors = [];
  1824. const ast = compiler.parse(source, {
  1825. parseMode: "sfc",
  1826. prefixIdentifiers: true,
  1827. ...templateParseOptions,
  1828. onError: (e) => {
  1829. errors.push(e);
  1830. }
  1831. });
  1832. ast.children.forEach((node) => {
  1833. if (node.type !== 1) {
  1834. return;
  1835. }
  1836. if (ignoreEmpty && node.tag !== "template" && isEmpty(node) && !hasSrc(node)) {
  1837. return;
  1838. }
  1839. switch (node.tag) {
  1840. case "template":
  1841. if (!descriptor.template) {
  1842. const templateBlock = descriptor.template = createBlock(
  1843. node,
  1844. source,
  1845. false
  1846. );
  1847. if (!templateBlock.attrs.src) {
  1848. templateBlock.ast = compilerCore.createRoot(node.children, source);
  1849. }
  1850. if (templateBlock.attrs.functional) {
  1851. const err = new SyntaxError(
  1852. `<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.`
  1853. );
  1854. err.loc = node.props.find(
  1855. (p) => p.type === 6 && p.name === "functional"
  1856. ).loc;
  1857. errors.push(err);
  1858. }
  1859. } else {
  1860. errors.push(createDuplicateBlockError(node));
  1861. }
  1862. break;
  1863. case "script":
  1864. const scriptBlock = createBlock(node, source, pad);
  1865. const isSetup = !!scriptBlock.attrs.setup;
  1866. if (isSetup && !descriptor.scriptSetup) {
  1867. descriptor.scriptSetup = scriptBlock;
  1868. break;
  1869. }
  1870. if (!isSetup && !descriptor.script) {
  1871. descriptor.script = scriptBlock;
  1872. break;
  1873. }
  1874. errors.push(createDuplicateBlockError(node, isSetup));
  1875. break;
  1876. case "style":
  1877. const styleBlock = createBlock(node, source, pad);
  1878. if (styleBlock.attrs.vars) {
  1879. errors.push(
  1880. new SyntaxError(
  1881. `<style vars> has been replaced by a new proposal: https://github.com/vuejs/rfcs/pull/231`
  1882. )
  1883. );
  1884. }
  1885. descriptor.styles.push(styleBlock);
  1886. break;
  1887. default:
  1888. descriptor.customBlocks.push(createBlock(node, source, pad));
  1889. break;
  1890. }
  1891. });
  1892. if (!descriptor.template && !descriptor.script && !descriptor.scriptSetup) {
  1893. errors.push(
  1894. new SyntaxError(
  1895. `At least one <template> or <script> is required in a single file component. ${descriptor.filename}`
  1896. )
  1897. );
  1898. }
  1899. if (descriptor.scriptSetup) {
  1900. if (descriptor.scriptSetup.src) {
  1901. errors.push(
  1902. new SyntaxError(
  1903. `<script setup> cannot use the "src" attribute because its syntax will be ambiguous outside of the component.`
  1904. )
  1905. );
  1906. descriptor.scriptSetup = null;
  1907. }
  1908. if (descriptor.script && descriptor.script.src) {
  1909. errors.push(
  1910. new SyntaxError(
  1911. `<script> cannot use the "src" attribute when <script setup> is also present because they must be processed together.`
  1912. )
  1913. );
  1914. descriptor.script = null;
  1915. }
  1916. }
  1917. let templateColumnOffset = 0;
  1918. if (descriptor.template && (descriptor.template.lang === "pug" || descriptor.template.lang === "jade")) {
  1919. [descriptor.template.content, templateColumnOffset] = dedent(
  1920. descriptor.template.content
  1921. );
  1922. }
  1923. if (sourceMap) {
  1924. const genMap = (block, columnOffset = 0) => {
  1925. if (block && !block.src) {
  1926. block.map = generateSourceMap(
  1927. filename,
  1928. source,
  1929. block.content,
  1930. sourceRoot,
  1931. !pad || block.type === "template" ? block.loc.start.line - 1 : 0,
  1932. columnOffset
  1933. );
  1934. }
  1935. };
  1936. genMap(descriptor.template, templateColumnOffset);
  1937. genMap(descriptor.script);
  1938. descriptor.styles.forEach((s) => genMap(s));
  1939. descriptor.customBlocks.forEach((s) => genMap(s));
  1940. }
  1941. descriptor.cssVars = parseCssVars(descriptor);
  1942. const slottedRE = /(?:::v-|:)slotted\(/;
  1943. descriptor.slotted = descriptor.styles.some(
  1944. (s) => s.scoped && slottedRE.test(s.content)
  1945. );
  1946. const result = {
  1947. descriptor,
  1948. errors
  1949. };
  1950. parseCache$1.set(sourceKey, result);
  1951. return result;
  1952. }
  1953. function createDuplicateBlockError(node, isScriptSetup = false) {
  1954. const err = new SyntaxError(
  1955. `Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element`
  1956. );
  1957. err.loc = node.loc;
  1958. return err;
  1959. }
  1960. function createBlock(node, source, pad) {
  1961. const type = node.tag;
  1962. const loc = node.innerLoc;
  1963. const attrs = {};
  1964. const block = {
  1965. type,
  1966. content: source.slice(loc.start.offset, loc.end.offset),
  1967. loc,
  1968. attrs
  1969. };
  1970. if (pad) {
  1971. block.content = padContent(source, block, pad) + block.content;
  1972. }
  1973. node.props.forEach((p) => {
  1974. if (p.type === 6) {
  1975. const name = p.name;
  1976. attrs[name] = p.value ? p.value.content || true : true;
  1977. if (name === "lang") {
  1978. block.lang = p.value && p.value.content;
  1979. } else if (name === "src") {
  1980. block.src = p.value && p.value.content;
  1981. } else if (type === "style") {
  1982. if (name === "scoped") {
  1983. block.scoped = true;
  1984. } else if (name === "module") {
  1985. block.module = attrs[name];
  1986. }
  1987. } else if (type === "script" && name === "setup") {
  1988. block.setup = attrs.setup;
  1989. }
  1990. }
  1991. });
  1992. return block;
  1993. }
  1994. const splitRE = /\r?\n/g;
  1995. const emptyRE = /^(?:\/\/)?\s*$/;
  1996. const replaceRE = /./g;
  1997. function generateSourceMap(filename, source, generated, sourceRoot, lineOffset, columnOffset) {
  1998. const map = new sourceMapJs.SourceMapGenerator({
  1999. file: filename.replace(/\\/g, "/"),
  2000. sourceRoot: sourceRoot.replace(/\\/g, "/")
  2001. });
  2002. map.setSourceContent(filename, source);
  2003. map._sources.add(filename);
  2004. generated.split(splitRE).forEach((line, index) => {
  2005. if (!emptyRE.test(line)) {
  2006. const originalLine = index + 1 + lineOffset;
  2007. const generatedLine = index + 1;
  2008. for (let i = 0; i < line.length; i++) {
  2009. if (!/\s/.test(line[i])) {
  2010. map._mappings.add({
  2011. originalLine,
  2012. originalColumn: i + columnOffset,
  2013. generatedLine,
  2014. generatedColumn: i,
  2015. source: filename,
  2016. name: null
  2017. });
  2018. }
  2019. }
  2020. }
  2021. });
  2022. return map.toJSON();
  2023. }
  2024. function padContent(content, block, pad) {
  2025. content = content.slice(0, block.loc.start.offset);
  2026. if (pad === "space") {
  2027. return content.replace(replaceRE, " ");
  2028. } else {
  2029. const offset = content.split(splitRE).length;
  2030. const padChar = block.type === "script" && !block.lang ? "//\n" : "\n";
  2031. return Array(offset).join(padChar);
  2032. }
  2033. }
  2034. function hasSrc(node) {
  2035. return node.props.some((p) => {
  2036. if (p.type !== 6) {
  2037. return false;
  2038. }
  2039. return p.name === "src";
  2040. });
  2041. }
  2042. function isEmpty(node) {
  2043. for (let i = 0; i < node.children.length; i++) {
  2044. const child = node.children[i];
  2045. if (child.type !== 2 || child.content.trim() !== "") {
  2046. return false;
  2047. }
  2048. }
  2049. return true;
  2050. }
  2051. function hmrShouldReload(prevImports, next) {
  2052. if (!next.scriptSetup || next.scriptSetup.lang !== "ts" && next.scriptSetup.lang !== "tsx") {
  2053. return false;
  2054. }
  2055. for (const key in prevImports) {
  2056. if (!prevImports[key].isUsedInTemplate && isImportUsed(key, next)) {
  2057. return true;
  2058. }
  2059. }
  2060. return false;
  2061. }
  2062. function dedent(s) {
  2063. const lines = s.split("\n");
  2064. const minIndent = lines.reduce(function(minIndent2, line) {
  2065. var _a, _b;
  2066. if (line.trim() === "") {
  2067. return minIndent2;
  2068. }
  2069. const indent = ((_b = (_a = line.match(/^\s*/)) == null ? void 0 : _a[0]) == null ? void 0 : _b.length) || 0;
  2070. return Math.min(indent, minIndent2);
  2071. }, Infinity);
  2072. if (minIndent === 0) {
  2073. return [s, minIndent];
  2074. }
  2075. return [
  2076. lines.map(function(line) {
  2077. return line.slice(minIndent);
  2078. }).join("\n"),
  2079. minIndent
  2080. ];
  2081. }
  2082. function isRelativeUrl(url) {
  2083. const firstChar = url.charAt(0);
  2084. return firstChar === "." || firstChar === "~" || firstChar === "@" || firstChar === "#";
  2085. }
  2086. const externalRE = /^(?:https?:)?\/\//;
  2087. function isExternalUrl(url) {
  2088. return externalRE.test(url);
  2089. }
  2090. const dataUrlRE = /^\s*data:/i;
  2091. function isDataUrl(url) {
  2092. return dataUrlRE.test(url);
  2093. }
  2094. function normalizeDecodedImportPath(source) {
  2095. try {
  2096. return decodeURIComponent(source);
  2097. } catch {
  2098. return source;
  2099. }
  2100. }
  2101. function parseUrl(url) {
  2102. const firstChar = url.charAt(0);
  2103. if (firstChar === "~") {
  2104. const secondChar = url.charAt(1);
  2105. url = url.slice(secondChar === "/" ? 2 : 1);
  2106. }
  2107. return parseUriParts(url);
  2108. }
  2109. function parseUriParts(urlString) {
  2110. return url.parse(shared.isString(urlString) ? urlString : "", false, true);
  2111. }
  2112. const resourceUrlTagConfig = {
  2113. video: ["src", "poster"],
  2114. source: ["src"],
  2115. img: ["src"]
  2116. };
  2117. const defaultAssetUrlOptions = {
  2118. base: null,
  2119. includeAbsolute: false,
  2120. tags: {
  2121. ...resourceUrlTagConfig,
  2122. image: ["xlink:href", "href"],
  2123. use: ["xlink:href", "href"]
  2124. }
  2125. };
  2126. const normalizeOptions = (options) => {
  2127. if (Object.keys(options).some((key) => shared.isArray(options[key]))) {
  2128. return {
  2129. ...defaultAssetUrlOptions,
  2130. tags: options
  2131. };
  2132. }
  2133. return {
  2134. ...defaultAssetUrlOptions,
  2135. ...options
  2136. };
  2137. };
  2138. const createAssetUrlTransformWithOptions = (options) => {
  2139. return (node, context) => transformAssetUrl(node, context, options);
  2140. };
  2141. function canTransformHashImport(tag, attrName) {
  2142. var _a;
  2143. return !!((_a = resourceUrlTagConfig[tag]) == null ? void 0 : _a.includes(attrName));
  2144. }
  2145. const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
  2146. if (node.type === 1) {
  2147. if (!node.props.length) {
  2148. return;
  2149. }
  2150. const tags = options.tags || defaultAssetUrlOptions.tags;
  2151. const attrs = tags[node.tag];
  2152. const wildCardAttrs = tags["*"];
  2153. if (!attrs && !wildCardAttrs) {
  2154. return;
  2155. }
  2156. const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
  2157. node.props.forEach((attr, index) => {
  2158. if (attr.type !== 6 || !assetAttrs.includes(attr.name) || !attr.value) {
  2159. return;
  2160. }
  2161. const urlValue = attr.value.content;
  2162. const isHashOnlyValue = urlValue[0] === "#";
  2163. if (isExternalUrl(urlValue) || isDataUrl(urlValue) || // a bare `#` is never a valid import specifier
  2164. urlValue === "#" || isHashOnlyValue && !canTransformHashImport(node.tag, attr.name) || !options.includeAbsolute && !isRelativeUrl(urlValue)) {
  2165. return;
  2166. }
  2167. const url = parseUrl(urlValue);
  2168. if (options.base && urlValue[0] === ".") {
  2169. const base = parseUrl(options.base);
  2170. const protocol = base.protocol || "";
  2171. const host = base.host ? protocol + "//" + base.host : "";
  2172. const basePath = base.path || "/";
  2173. attr.value.content = host + (path$1.posix || path$1).join(basePath, url.path + (url.hash || ""));
  2174. return;
  2175. }
  2176. const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
  2177. node.props[index] = {
  2178. type: 7,
  2179. name: "bind",
  2180. arg: compilerCore.createSimpleExpression(attr.name, true, attr.loc),
  2181. exp,
  2182. modifiers: [],
  2183. loc: attr.loc
  2184. };
  2185. });
  2186. }
  2187. };
  2188. function resolveOrRegisterImport(source, loc, context) {
  2189. const normalizedSource = normalizeDecodedImportPath(source);
  2190. const existingIndex = context.imports.findIndex(
  2191. (i) => i.path === normalizedSource
  2192. );
  2193. if (existingIndex > -1) {
  2194. return {
  2195. name: `_imports_${existingIndex}`,
  2196. exp: context.imports[existingIndex].exp
  2197. };
  2198. }
  2199. const name = `_imports_${context.imports.length}`;
  2200. const exp = compilerCore.createSimpleExpression(
  2201. name,
  2202. false,
  2203. loc,
  2204. 3
  2205. );
  2206. context.imports.push({
  2207. exp,
  2208. path: normalizedSource
  2209. });
  2210. return { name, exp };
  2211. }
  2212. function getImportsExpressionExp(path2, hash, loc, context) {
  2213. if (!path2 && !hash) {
  2214. return compilerCore.createSimpleExpression(`''`, false, loc, 3);
  2215. }
  2216. if (!path2 && hash) {
  2217. const { exp } = resolveOrRegisterImport(hash, loc, context);
  2218. return exp;
  2219. }
  2220. if (path2 && !hash) {
  2221. const { exp } = resolveOrRegisterImport(path2, loc, context);
  2222. return exp;
  2223. }
  2224. const { name } = resolveOrRegisterImport(path2, loc, context);
  2225. const hashExp = `${name} + '${hash}'`;
  2226. const finalExp = compilerCore.createSimpleExpression(
  2227. hashExp,
  2228. false,
  2229. loc,
  2230. 3
  2231. );
  2232. if (!context.hoistStatic) {
  2233. return finalExp;
  2234. }
  2235. const existingHoistIndex = context.hoists.findIndex((h) => {
  2236. return h && h.type === 4 && !h.isStatic && h.content === hashExp;
  2237. });
  2238. if (existingHoistIndex > -1) {
  2239. return compilerCore.createSimpleExpression(
  2240. `_hoisted_${existingHoistIndex + 1}`,
  2241. false,
  2242. loc,
  2243. 3
  2244. );
  2245. }
  2246. return context.hoist(finalExp);
  2247. }
  2248. const srcsetTags = ["img", "source"];
  2249. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  2250. const createSrcsetTransformWithOptions = (options) => {
  2251. return (node, context) => transformSrcset(node, context, options);
  2252. };
  2253. const transformSrcset = (node, context, options = defaultAssetUrlOptions) => {
  2254. if (node.type === 1) {
  2255. if (srcsetTags.includes(node.tag) && node.props.length) {
  2256. node.props.forEach((attr, index) => {
  2257. if (attr.name === "srcset" && attr.type === 6) {
  2258. if (!attr.value) return;
  2259. const value = attr.value.content;
  2260. if (!value) return;
  2261. const imageCandidates = value.split(",").map((s) => {
  2262. const [url, descriptor] = s.replace(escapedSpaceCharacters, " ").trim().split(" ", 2);
  2263. return { url, descriptor };
  2264. });
  2265. for (let i = 0; i < imageCandidates.length; i++) {
  2266. const { url } = imageCandidates[i];
  2267. if (isDataUrl(url)) {
  2268. imageCandidates[i + 1].url = url + "," + imageCandidates[i + 1].url;
  2269. imageCandidates.splice(i, 1);
  2270. }
  2271. }
  2272. const shouldProcessUrl = (url) => {
  2273. return url && !isExternalUrl(url) && !isDataUrl(url) && (options.includeAbsolute || isRelativeUrl(url));
  2274. };
  2275. if (!imageCandidates.some(({ url }) => shouldProcessUrl(url))) {
  2276. return;
  2277. }
  2278. if (options.base) {
  2279. const base = options.base;
  2280. const set = [];
  2281. let needImportTransform = false;
  2282. imageCandidates.forEach((candidate) => {
  2283. let { url, descriptor } = candidate;
  2284. descriptor = descriptor ? ` ${descriptor}` : ``;
  2285. if (url[0] === ".") {
  2286. candidate.url = (path$1.posix || path$1).join(base, url);
  2287. set.push(candidate.url + descriptor);
  2288. } else if (shouldProcessUrl(url)) {
  2289. needImportTransform = true;
  2290. } else {
  2291. set.push(url + descriptor);
  2292. }
  2293. });
  2294. if (!needImportTransform) {
  2295. attr.value.content = set.join(", ");
  2296. return;
  2297. }
  2298. }
  2299. const compoundExpression = compilerCore.createCompoundExpression([], attr.loc);
  2300. imageCandidates.forEach(({ url, descriptor }, index2) => {
  2301. if (shouldProcessUrl(url)) {
  2302. const { path: path2, hash } = parseUrl(url);
  2303. const source = path2 ? path2 : hash;
  2304. if (source) {
  2305. const normalizedSource = normalizeDecodedImportPath(source);
  2306. const existingImportsIndex = context.imports.findIndex(
  2307. (i) => i.path === normalizedSource
  2308. );
  2309. let exp2;
  2310. if (existingImportsIndex > -1) {
  2311. exp2 = compilerCore.createSimpleExpression(
  2312. `_imports_${existingImportsIndex}`,
  2313. false,
  2314. attr.loc,
  2315. 3
  2316. );
  2317. } else {
  2318. exp2 = compilerCore.createSimpleExpression(
  2319. `_imports_${context.imports.length}`,
  2320. false,
  2321. attr.loc,
  2322. 3
  2323. );
  2324. context.imports.push({ exp: exp2, path: normalizedSource });
  2325. }
  2326. if (path2 && hash) {
  2327. exp2 = compilerCore.createSimpleExpression(
  2328. `${exp2.content} + '${hash}'`,
  2329. false,
  2330. attr.loc,
  2331. 3
  2332. );
  2333. }
  2334. compoundExpression.children.push(exp2);
  2335. }
  2336. } else {
  2337. const exp2 = compilerCore.createSimpleExpression(
  2338. `"${url}"`,
  2339. false,
  2340. attr.loc,
  2341. 3
  2342. );
  2343. compoundExpression.children.push(exp2);
  2344. }
  2345. const isNotLast = imageCandidates.length - 1 > index2;
  2346. if (descriptor && isNotLast) {
  2347. compoundExpression.children.push(` + ' ${descriptor}, ' + `);
  2348. } else if (descriptor) {
  2349. compoundExpression.children.push(` + ' ${descriptor}'`);
  2350. } else if (isNotLast) {
  2351. compoundExpression.children.push(` + ', ' + `);
  2352. }
  2353. });
  2354. let exp = compoundExpression;
  2355. if (context.hoistStatic) {
  2356. exp = context.hoist(compoundExpression);
  2357. exp.constType = 3;
  2358. }
  2359. node.props[index] = {
  2360. type: 7,
  2361. name: "bind",
  2362. arg: compilerCore.createSimpleExpression("srcset", true, attr.loc),
  2363. exp,
  2364. modifiers: [],
  2365. loc: attr.loc
  2366. };
  2367. }
  2368. });
  2369. }
  2370. }
  2371. };
  2372. function commonjsRequire(path) {
  2373. throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
  2374. }
  2375. var consolidate$2 = {exports: {}};
  2376. var hasRequiredConsolidate$1;
  2377. function requireConsolidate$1 () {
  2378. if (hasRequiredConsolidate$1) return consolidate$2.exports;
  2379. hasRequiredConsolidate$1 = 1;
  2380. (function (module, exports) {
  2381. /*
  2382. * Engines which do not support caching of their file contents
  2383. * should use the `read()` function defined in consolidate.js
  2384. * On top of this, when an engine compiles to a `Function`,
  2385. * these functions should either be cached within consolidate.js
  2386. * or the engine itself via `options.cache`. This will allow
  2387. * users and frameworks to pass `options.cache = true` for
  2388. * `NODE_ENV=production`, however edit the file(s) without
  2389. * re-loading the application in development.
  2390. */
  2391. /**
  2392. * Module dependencies.
  2393. */
  2394. var fs = require$$0;
  2395. var path = path$1;
  2396. var util = require$$2;
  2397. var join = path.join;
  2398. var resolve = path.resolve;
  2399. var extname = path.extname;
  2400. var dirname = path.dirname;
  2401. var isAbsolute = path.isAbsolute;
  2402. var readCache = {};
  2403. /**
  2404. * Require cache.
  2405. */
  2406. var cacheStore = {};
  2407. /**
  2408. * Require cache.
  2409. */
  2410. var requires = {};
  2411. /**
  2412. * Clear the cache.
  2413. *
  2414. * @api public
  2415. */
  2416. exports.clearCache = function() {
  2417. readCache = {};
  2418. cacheStore = {};
  2419. };
  2420. /**
  2421. * Conditionally cache `compiled` template based
  2422. * on the `options` filename and `.cache` boolean.
  2423. *
  2424. * @param {Object} options
  2425. * @param {Function} compiled
  2426. * @return {Function}
  2427. * @api private
  2428. */
  2429. function cache(options, compiled) {
  2430. // cachable
  2431. if (compiled && options.filename && options.cache) {
  2432. delete readCache[options.filename];
  2433. cacheStore[options.filename] = compiled;
  2434. return compiled;
  2435. }
  2436. // check cache
  2437. if (options.filename && options.cache) {
  2438. return cacheStore[options.filename];
  2439. }
  2440. return compiled;
  2441. }
  2442. /**
  2443. * Read `path` with `options` with
  2444. * callback `(err, str)`. When `options.cache`
  2445. * is true the template string will be cached.
  2446. *
  2447. * @param {String} options
  2448. * @param {Function} cb
  2449. * @api private
  2450. */
  2451. function read(path, options, cb) {
  2452. var str = readCache[path];
  2453. var cached = options.cache && str && typeof str === 'string';
  2454. // cached (only if cached is a string and not a compiled template function)
  2455. if (cached) return cb(null, str);
  2456. // read
  2457. fs.readFile(path, 'utf8', function(err, str) {
  2458. if (err) return cb(err);
  2459. // remove extraneous utf8 BOM marker
  2460. str = str.replace(/^\uFEFF/, '');
  2461. if (options.cache) readCache[path] = str;
  2462. cb(null, str);
  2463. });
  2464. }
  2465. /**
  2466. * Read `path` with `options` with
  2467. * callback `(err, str)`. When `options.cache`
  2468. * is true the partial string will be cached.
  2469. *
  2470. * @param {String} options
  2471. * @param {Function} fn
  2472. * @api private
  2473. */
  2474. function readPartials(path, options, cb) {
  2475. if (!options.partials) return cb();
  2476. var keys = Object.keys(options.partials);
  2477. var partials = {};
  2478. function next(index) {
  2479. if (index === keys.length) return cb(null, partials);
  2480. var key = keys[index];
  2481. var partialPath = options.partials[key];
  2482. if (partialPath === undefined || partialPath === null || partialPath === false) {
  2483. return next(++index);
  2484. }
  2485. var file;
  2486. if (isAbsolute(partialPath)) {
  2487. if (extname(partialPath) !== '') {
  2488. file = partialPath;
  2489. } else {
  2490. file = join(partialPath + extname(path));
  2491. }
  2492. } else {
  2493. file = join(dirname(path), partialPath + extname(path));
  2494. }
  2495. read(file, options, function(err, str) {
  2496. if (err) return cb(err);
  2497. partials[key] = str;
  2498. next(++index);
  2499. });
  2500. }
  2501. next(0);
  2502. }
  2503. /**
  2504. * promisify
  2505. */
  2506. function promisify(cb, fn) {
  2507. return new Promise(function(resolve, reject) {
  2508. cb = cb || function(err, html) {
  2509. if (err) {
  2510. return reject(err);
  2511. }
  2512. resolve(html);
  2513. };
  2514. fn(cb);
  2515. });
  2516. }
  2517. /**
  2518. * fromStringRenderer
  2519. */
  2520. function fromStringRenderer(name) {
  2521. return function(path, options, cb) {
  2522. options.filename = path;
  2523. return promisify(cb, function(cb) {
  2524. readPartials(path, options, function(err, partials) {
  2525. var extend = (requires.extend || (requires.extend = require$$2._extend));
  2526. var opts = extend({}, options);
  2527. opts.partials = partials;
  2528. if (err) return cb(err);
  2529. if (cache(opts)) {
  2530. exports[name].render('', opts, cb);
  2531. } else {
  2532. read(path, opts, function(err, str) {
  2533. if (err) return cb(err);
  2534. exports[name].render(str, opts, cb);
  2535. });
  2536. }
  2537. });
  2538. });
  2539. };
  2540. }
  2541. /**
  2542. * velocity support.
  2543. */
  2544. exports.velocityjs = fromStringRenderer('velocityjs');
  2545. /**
  2546. * velocity string support.
  2547. */
  2548. exports.velocityjs.render = function(str, options, cb) {
  2549. return promisify(cb, function(cb) {
  2550. var engine = requires.velocityjs || (requires.velocityjs = require('velocityjs'));
  2551. try {
  2552. options.locals = options;
  2553. cb(null, engine.render(str, options).trimLeft());
  2554. } catch (err) {
  2555. cb(err);
  2556. }
  2557. });
  2558. };
  2559. /**
  2560. * Liquid support.
  2561. */
  2562. exports.liquid = fromStringRenderer('liquid');
  2563. /**
  2564. * Liquid string support.
  2565. */
  2566. /**
  2567. * Note that in order to get filters and custom tags we've had to push
  2568. * all user-defined locals down into @locals. However, just to make things
  2569. * backwards-compatible, any property of `options` that is left after
  2570. * processing and removing `locals`, `meta`, `filters`, `customTags` and
  2571. * `includeDir` will also become a local.
  2572. */
  2573. function _renderTinyliquid(engine, str, options, cb) {
  2574. var context = engine.newContext();
  2575. var k;
  2576. /**
  2577. * Note that there's a bug in the library that doesn't allow us to pass
  2578. * the locals to newContext(), hence looping through the keys:
  2579. */
  2580. if (options.locals) {
  2581. for (k in options.locals) {
  2582. context.setLocals(k, options.locals[k]);
  2583. }
  2584. delete options.locals;
  2585. }
  2586. if (options.meta) {
  2587. context.setLocals('page', options.meta);
  2588. delete options.meta;
  2589. }
  2590. /**
  2591. * Add any defined filters:
  2592. */
  2593. if (options.filters) {
  2594. for (k in options.filters) {
  2595. context.setFilter(k, options.filters[k]);
  2596. }
  2597. delete options.filters;
  2598. }
  2599. /**
  2600. * Set up a callback for the include directory:
  2601. */
  2602. var includeDir = options.includeDir || process.cwd();
  2603. context.onInclude(function(name, callback) {
  2604. var extname = path.extname(name) ? '' : '.liquid';
  2605. var filename = path.resolve(includeDir, name + extname);
  2606. fs.readFile(filename, {encoding: 'utf8'}, function(err, data) {
  2607. if (err) return callback(err);
  2608. callback(null, engine.parse(data));
  2609. });
  2610. });
  2611. delete options.includeDir;
  2612. /**
  2613. * The custom tag functions need to have their results pushed back
  2614. * through the parser, so set up a shim before calling the provided
  2615. * callback:
  2616. */
  2617. var compileOptions = {
  2618. customTags: {}
  2619. };
  2620. if (options.customTags) {
  2621. var tagFunctions = options.customTags;
  2622. for (k in options.customTags) {
  2623. /*Tell jshint there's no problem with having this function in the loop */
  2624. /*jshint -W083 */
  2625. compileOptions.customTags[k] = function(context, name, body) {
  2626. var tpl = tagFunctions[name](body.trim());
  2627. context.astStack.push(engine.parse(tpl));
  2628. };
  2629. /*jshint +W083 */
  2630. }
  2631. delete options.customTags;
  2632. }
  2633. /**
  2634. * Now anything left in `options` becomes a local:
  2635. */
  2636. for (k in options) {
  2637. context.setLocals(k, options[k]);
  2638. }
  2639. /**
  2640. * Finally, execute the template:
  2641. */
  2642. var tmpl = cache(context) || cache(context, engine.compile(str, compileOptions));
  2643. tmpl(context, cb);
  2644. }
  2645. exports.liquid.render = function(str, options, cb) {
  2646. return promisify(cb, function(cb) {
  2647. var engine = requires.liquid;
  2648. var Liquid;
  2649. try {
  2650. // set up tinyliquid engine
  2651. engine = requires.liquid = require('tinyliquid');
  2652. // use tinyliquid engine
  2653. _renderTinyliquid(engine, str, options, cb);
  2654. return;
  2655. } catch (err) {
  2656. // set up liquid-node engine
  2657. try {
  2658. Liquid = requires.liquid = require('liquid-node');
  2659. engine = new Liquid.Engine();
  2660. } catch (err) {
  2661. throw err;
  2662. }
  2663. }
  2664. // use liquid-node engine
  2665. try {
  2666. var locals = options.locals || {};
  2667. if (options.meta) {
  2668. locals.pages = options.meta;
  2669. delete options.meta;
  2670. }
  2671. /**
  2672. * Add any defined filters:
  2673. */
  2674. if (options.filters) {
  2675. engine.registerFilters(options.filters);
  2676. delete options.filters;
  2677. }
  2678. /**
  2679. * Set up a callback for the include directory:
  2680. */
  2681. var includeDir = options.includeDir || process.cwd();
  2682. engine.fileSystem = new Liquid.LocalFileSystem(includeDir, 'liquid');
  2683. delete options.includeDir;
  2684. /**
  2685. * The custom tag functions need to have their results pushed back
  2686. * through the parser, so set up a shim before calling the provided
  2687. * callback:
  2688. */
  2689. if (options.customTags) {
  2690. var tagFunctions = options.customTags;
  2691. for (k in options.customTags) {
  2692. engine.registerTag(k, tagFunctions[k]);
  2693. }
  2694. delete options.customTags;
  2695. }
  2696. /**
  2697. * Now anything left in `options` becomes a local:
  2698. */
  2699. for (var k in options) {
  2700. locals[k] = options[k];
  2701. }
  2702. /**
  2703. * Finally, execute the template:
  2704. */
  2705. return engine
  2706. .parseAndRender(str, locals)
  2707. .nodeify(function(err, result) {
  2708. if (err) {
  2709. throw new Error(err);
  2710. } else {
  2711. return cb(null, result);
  2712. }
  2713. });
  2714. } catch (err) {
  2715. cb(err);
  2716. }
  2717. });
  2718. };
  2719. /**
  2720. * Jade support.
  2721. */
  2722. exports.jade = function(path, options, cb) {
  2723. return promisify(cb, function(cb) {
  2724. var engine = requires.jade;
  2725. if (!engine) {
  2726. try {
  2727. engine = requires.jade = require('jade');
  2728. } catch (err) {
  2729. try {
  2730. engine = requires.jade = require('then-jade');
  2731. } catch (otherError) {
  2732. throw err;
  2733. }
  2734. }
  2735. }
  2736. try {
  2737. var tmpl = cache(options) || cache(options, engine.compileFile(path, options));
  2738. cb(null, tmpl(options));
  2739. } catch (err) {
  2740. cb(err);
  2741. }
  2742. });
  2743. };
  2744. /**
  2745. * Jade string support.
  2746. */
  2747. exports.jade.render = function(str, options, cb) {
  2748. return promisify(cb, function(cb) {
  2749. var engine = requires.jade;
  2750. if (!engine) {
  2751. try {
  2752. engine = requires.jade = require('jade');
  2753. } catch (err) {
  2754. try {
  2755. engine = requires.jade = require('then-jade');
  2756. } catch (otherError) {
  2757. throw err;
  2758. }
  2759. }
  2760. }
  2761. try {
  2762. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2763. cb(null, tmpl(options));
  2764. } catch (err) {
  2765. cb(err);
  2766. }
  2767. });
  2768. };
  2769. /**
  2770. * Dust support.
  2771. */
  2772. exports.dust = fromStringRenderer('dust');
  2773. /**
  2774. * Dust string support.
  2775. */
  2776. exports.dust.render = function(str, options, cb) {
  2777. return promisify(cb, function(cb) {
  2778. var engine = requires.dust;
  2779. if (!engine) {
  2780. try {
  2781. engine = requires.dust = require('dust');
  2782. } catch (err) {
  2783. try {
  2784. engine = requires.dust = require('dustjs-helpers');
  2785. } catch (err) {
  2786. engine = requires.dust = require('dustjs-linkedin');
  2787. }
  2788. }
  2789. }
  2790. var ext = 'dust';
  2791. var views = '.';
  2792. if (options) {
  2793. if (options.ext) ext = options.ext;
  2794. if (options.views) views = options.views;
  2795. if (options.settings && options.settings.views) views = options.settings.views;
  2796. }
  2797. if (!options || (options && !options.cache)) engine.cache = {};
  2798. engine.onLoad = function(path, callback) {
  2799. if (extname(path) === '') path += '.' + ext;
  2800. if (path[0] !== '/') path = views + '/' + path;
  2801. read(path, options, callback);
  2802. };
  2803. try {
  2804. var templateName;
  2805. if (options.filename) {
  2806. templateName = options.filename.replace(new RegExp('^' + views + '/'), '').replace(new RegExp('\\.' + ext), '');
  2807. }
  2808. var tmpl = cache(options) || cache(options, engine.compileFn(str, templateName));
  2809. tmpl(options, cb);
  2810. } catch (err) {
  2811. cb(err);
  2812. }
  2813. });
  2814. };
  2815. /**
  2816. * Swig support.
  2817. */
  2818. exports.swig = fromStringRenderer('swig');
  2819. /**
  2820. * Swig string support.
  2821. */
  2822. exports.swig.render = function(str, options, cb) {
  2823. return promisify(cb, function(cb) {
  2824. var engine = requires.swig;
  2825. if (!engine) {
  2826. try {
  2827. engine = requires.swig = require('swig');
  2828. } catch (err) {
  2829. try {
  2830. engine = requires.swig = require('swig-templates');
  2831. } catch (otherError) {
  2832. throw err;
  2833. }
  2834. }
  2835. }
  2836. try {
  2837. if (options.cache === true) options.cache = 'memory';
  2838. engine.setDefaults({ cache: options.cache });
  2839. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2840. cb(null, tmpl(options));
  2841. } catch (err) {
  2842. cb(err);
  2843. }
  2844. });
  2845. };
  2846. /**
  2847. * Razor support.
  2848. */
  2849. exports.razor = function(path, options, cb) {
  2850. return promisify(cb, function(cb) {
  2851. var engine = requires.razor;
  2852. if (!engine) {
  2853. try {
  2854. engine = requires.razor = require('razor-tmpl');
  2855. } catch (err) {
  2856. throw err;
  2857. }
  2858. }
  2859. try {
  2860. var tmpl = cache(options) || cache(options, (locals) => {
  2861. console.log('Rendering razor file', path);
  2862. return engine.renderFileSync(path, locals);
  2863. });
  2864. cb(null, tmpl(options));
  2865. } catch (err) {
  2866. cb(err);
  2867. }
  2868. });
  2869. };
  2870. /**
  2871. * razor string support.
  2872. */
  2873. exports.razor.render = function(str, options, cb) {
  2874. return promisify(cb, function(cb) {
  2875. try {
  2876. var engine = requires.razor = require('razor-tmpl');
  2877. } catch (err) {
  2878. throw err;
  2879. }
  2880. try {
  2881. var tf = engine.compile(str);
  2882. var tmpl = cache(options) || cache(options, tf);
  2883. cb(null, tmpl(options));
  2884. } catch (err) {
  2885. cb(err);
  2886. }
  2887. });
  2888. };
  2889. /**
  2890. * Atpl support.
  2891. */
  2892. exports.atpl = fromStringRenderer('atpl');
  2893. /**
  2894. * Atpl string support.
  2895. */
  2896. exports.atpl.render = function(str, options, cb) {
  2897. return promisify(cb, function(cb) {
  2898. var engine = requires.atpl || (requires.atpl = require('atpl'));
  2899. try {
  2900. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2901. cb(null, tmpl(options));
  2902. } catch (err) {
  2903. cb(err);
  2904. }
  2905. });
  2906. };
  2907. /**
  2908. * Liquor support,
  2909. */
  2910. exports.liquor = fromStringRenderer('liquor');
  2911. /**
  2912. * Liquor string support.
  2913. */
  2914. exports.liquor.render = function(str, options, cb) {
  2915. return promisify(cb, function(cb) {
  2916. var engine = requires.liquor || (requires.liquor = require('liquor'));
  2917. try {
  2918. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2919. cb(null, tmpl(options));
  2920. } catch (err) {
  2921. cb(err);
  2922. }
  2923. });
  2924. };
  2925. /**
  2926. * Twig support.
  2927. */
  2928. exports.twig = fromStringRenderer('twig');
  2929. /**
  2930. * Twig string support.
  2931. */
  2932. exports.twig.render = function(str, options, cb) {
  2933. return promisify(cb, function(cb) {
  2934. var engine = requires.twig || (requires.twig = require('twig').twig);
  2935. var templateData = {
  2936. data: str,
  2937. allowInlineIncludes: options.allowInlineIncludes,
  2938. namespaces: options.namespaces,
  2939. path: options.path
  2940. };
  2941. try {
  2942. var tmpl = cache(templateData) || cache(templateData, engine(templateData));
  2943. cb(null, tmpl.render(options));
  2944. } catch (err) {
  2945. cb(err);
  2946. }
  2947. });
  2948. };
  2949. /**
  2950. * EJS support.
  2951. */
  2952. exports.ejs = fromStringRenderer('ejs');
  2953. /**
  2954. * EJS string support.
  2955. */
  2956. exports.ejs.render = function(str, options, cb) {
  2957. return promisify(cb, function(cb) {
  2958. var engine = requires.ejs || (requires.ejs = require('ejs'));
  2959. try {
  2960. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2961. cb(null, tmpl(options));
  2962. } catch (err) {
  2963. cb(err);
  2964. }
  2965. });
  2966. };
  2967. /**
  2968. * Eco support.
  2969. */
  2970. exports.eco = fromStringRenderer('eco');
  2971. /**
  2972. * Eco string support.
  2973. */
  2974. exports.eco.render = function(str, options, cb) {
  2975. return promisify(cb, function(cb) {
  2976. var engine = requires.eco || (requires.eco = require('eco'));
  2977. try {
  2978. cb(null, engine.render(str, options));
  2979. } catch (err) {
  2980. cb(err);
  2981. }
  2982. });
  2983. };
  2984. /**
  2985. * Jazz support.
  2986. */
  2987. exports.jazz = fromStringRenderer('jazz');
  2988. /**
  2989. * Jazz string support.
  2990. */
  2991. exports.jazz.render = function(str, options, cb) {
  2992. return promisify(cb, function(cb) {
  2993. var engine = requires.jazz || (requires.jazz = require('jazz'));
  2994. try {
  2995. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2996. tmpl.eval(options, function(str) {
  2997. cb(null, str);
  2998. });
  2999. } catch (err) {
  3000. cb(err);
  3001. }
  3002. });
  3003. };
  3004. /**
  3005. * JQTPL support.
  3006. */
  3007. exports.jqtpl = fromStringRenderer('jqtpl');
  3008. /**
  3009. * JQTPL string support.
  3010. */
  3011. exports.jqtpl.render = function(str, options, cb) {
  3012. return promisify(cb, function(cb) {
  3013. var engine = requires.jqtpl || (requires.jqtpl = require('jqtpl'));
  3014. try {
  3015. engine.template(str, str);
  3016. cb(null, engine.tmpl(str, options));
  3017. } catch (err) {
  3018. cb(err);
  3019. }
  3020. });
  3021. };
  3022. /**
  3023. * Haml support.
  3024. */
  3025. exports.haml = fromStringRenderer('haml');
  3026. /**
  3027. * Haml string support.
  3028. */
  3029. exports.haml.render = function(str, options, cb) {
  3030. return promisify(cb, function(cb) {
  3031. var engine = requires.haml || (requires.haml = require('hamljs'));
  3032. try {
  3033. options.locals = options;
  3034. cb(null, engine.render(str, options).trimLeft());
  3035. } catch (err) {
  3036. cb(err);
  3037. }
  3038. });
  3039. };
  3040. /**
  3041. * Hamlet support.
  3042. */
  3043. exports.hamlet = fromStringRenderer('hamlet');
  3044. /**
  3045. * Hamlet string support.
  3046. */
  3047. exports.hamlet.render = function(str, options, cb) {
  3048. return promisify(cb, function(cb) {
  3049. var engine = requires.hamlet || (requires.hamlet = require('hamlet'));
  3050. try {
  3051. options.locals = options;
  3052. cb(null, engine.render(str, options).trimLeft());
  3053. } catch (err) {
  3054. cb(err);
  3055. }
  3056. });
  3057. };
  3058. /**
  3059. * Whiskers support.
  3060. */
  3061. exports.whiskers = function(path, options, cb) {
  3062. return promisify(cb, function(cb) {
  3063. var engine = requires.whiskers || (requires.whiskers = require('whiskers'));
  3064. engine.__express(path, options, cb);
  3065. });
  3066. };
  3067. /**
  3068. * Whiskers string support.
  3069. */
  3070. exports.whiskers.render = function(str, options, cb) {
  3071. return promisify(cb, function(cb) {
  3072. var engine = requires.whiskers || (requires.whiskers = require('whiskers'));
  3073. try {
  3074. cb(null, engine.render(str, options));
  3075. } catch (err) {
  3076. cb(err);
  3077. }
  3078. });
  3079. };
  3080. /**
  3081. * Coffee-HAML support.
  3082. */
  3083. exports['haml-coffee'] = fromStringRenderer('haml-coffee');
  3084. /**
  3085. * Coffee-HAML string support.
  3086. */
  3087. exports['haml-coffee'].render = function(str, options, cb) {
  3088. return promisify(cb, function(cb) {
  3089. var engine = requires['haml-coffee'] || (requires['haml-coffee'] = require('haml-coffee'));
  3090. try {
  3091. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3092. cb(null, tmpl(options));
  3093. } catch (err) {
  3094. cb(err);
  3095. }
  3096. });
  3097. };
  3098. /**
  3099. * Hogan support.
  3100. */
  3101. exports.hogan = fromStringRenderer('hogan');
  3102. /**
  3103. * Hogan string support.
  3104. */
  3105. exports.hogan.render = function(str, options, cb) {
  3106. return promisify(cb, function(cb) {
  3107. var engine = requires.hogan || (requires.hogan = require('hogan.js'));
  3108. try {
  3109. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3110. cb(null, tmpl.render(options, options.partials));
  3111. } catch (err) {
  3112. cb(err);
  3113. }
  3114. });
  3115. };
  3116. /**
  3117. * templayed.js support.
  3118. */
  3119. exports.templayed = fromStringRenderer('templayed');
  3120. /**
  3121. * templayed.js string support.
  3122. */
  3123. exports.templayed.render = function(str, options, cb) {
  3124. return promisify(cb, function(cb) {
  3125. var engine = requires.templayed || (requires.templayed = require('templayed'));
  3126. try {
  3127. var tmpl = cache(options) || cache(options, engine(str));
  3128. cb(null, tmpl(options));
  3129. } catch (err) {
  3130. cb(err);
  3131. }
  3132. });
  3133. };
  3134. /**
  3135. * Handlebars support.
  3136. */
  3137. exports.handlebars = fromStringRenderer('handlebars');
  3138. /**
  3139. * Handlebars string support.
  3140. */
  3141. exports.handlebars.render = function(str, options, cb) {
  3142. return promisify(cb, function(cb) {
  3143. var engine = requires.handlebars || (requires.handlebars = require('handlebars'));
  3144. try {
  3145. for (var partial in options.partials) {
  3146. engine.registerPartial(partial, options.partials[partial]);
  3147. }
  3148. for (var helper in options.helpers) {
  3149. engine.registerHelper(helper, options.helpers[helper]);
  3150. }
  3151. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3152. cb(null, tmpl(options));
  3153. } catch (err) {
  3154. cb(err);
  3155. }
  3156. });
  3157. };
  3158. /**
  3159. * Underscore support.
  3160. */
  3161. exports.underscore = fromStringRenderer('underscore');
  3162. /**
  3163. * Underscore string support.
  3164. */
  3165. exports.underscore.render = function(str, options, cb) {
  3166. return promisify(cb, function(cb) {
  3167. var engine = requires.underscore || (requires.underscore = require('underscore'));
  3168. try {
  3169. const partials = {};
  3170. for (var partial in options.partials) {
  3171. partials[partial] = engine.template(options.partials[partial]);
  3172. }
  3173. options.partials = partials;
  3174. var tmpl = cache(options) || cache(options, engine.template(str, null, options));
  3175. cb(null, tmpl(options).replace(/\n$/, ''));
  3176. } catch (err) {
  3177. cb(err);
  3178. }
  3179. });
  3180. };
  3181. /**
  3182. * Lodash support.
  3183. */
  3184. exports.lodash = fromStringRenderer('lodash');
  3185. /**
  3186. * Lodash string support.
  3187. */
  3188. exports.lodash.render = function(str, options, cb) {
  3189. return promisify(cb, function(cb) {
  3190. var engine = requires.lodash || (requires.lodash = require('lodash'));
  3191. try {
  3192. var tmpl = cache(options) || cache(options, engine.template(str, options));
  3193. cb(null, tmpl(options).replace(/\n$/, ''));
  3194. } catch (err) {
  3195. cb(err);
  3196. }
  3197. });
  3198. };
  3199. /**
  3200. * Pug support. (formerly Jade)
  3201. */
  3202. exports.pug = function(path, options, cb) {
  3203. return promisify(cb, function(cb) {
  3204. var engine = requires.pug;
  3205. if (!engine) {
  3206. try {
  3207. engine = requires.pug = require('pug');
  3208. } catch (err) {
  3209. try {
  3210. engine = requires.pug = require('then-pug');
  3211. } catch (otherError) {
  3212. throw err;
  3213. }
  3214. }
  3215. }
  3216. try {
  3217. var tmpl = cache(options) || cache(options, engine.compileFile(path, options));
  3218. cb(null, tmpl(options));
  3219. } catch (err) {
  3220. cb(err);
  3221. }
  3222. });
  3223. };
  3224. /**
  3225. * Pug string support.
  3226. */
  3227. exports.pug.render = function(str, options, cb) {
  3228. return promisify(cb, function(cb) {
  3229. var engine = requires.pug;
  3230. if (!engine) {
  3231. try {
  3232. engine = requires.pug = require('pug');
  3233. } catch (err) {
  3234. try {
  3235. engine = requires.pug = require('then-pug');
  3236. } catch (otherError) {
  3237. throw err;
  3238. }
  3239. }
  3240. }
  3241. try {
  3242. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3243. cb(null, tmpl(options));
  3244. } catch (err) {
  3245. cb(err);
  3246. }
  3247. });
  3248. };
  3249. /**
  3250. * QEJS support.
  3251. */
  3252. exports.qejs = fromStringRenderer('qejs');
  3253. /**
  3254. * QEJS string support.
  3255. */
  3256. exports.qejs.render = function(str, options, cb) {
  3257. return promisify(cb, function(cb) {
  3258. try {
  3259. var engine = requires.qejs || (requires.qejs = require('qejs'));
  3260. engine.render(str, options).then(function(result) {
  3261. cb(null, result);
  3262. }, function(err) {
  3263. cb(err);
  3264. }).done();
  3265. } catch (err) {
  3266. cb(err);
  3267. }
  3268. });
  3269. };
  3270. /**
  3271. * Walrus support.
  3272. */
  3273. exports.walrus = fromStringRenderer('walrus');
  3274. /**
  3275. * Walrus string support.
  3276. */
  3277. exports.walrus.render = function(str, options, cb) {
  3278. return promisify(cb, function(cb) {
  3279. var engine = requires.walrus || (requires.walrus = require('walrus'));
  3280. try {
  3281. var tmpl = cache(options) || cache(options, engine.parse(str));
  3282. cb(null, tmpl.compile(options));
  3283. } catch (err) {
  3284. cb(err);
  3285. }
  3286. });
  3287. };
  3288. /**
  3289. * Mustache support.
  3290. */
  3291. exports.mustache = fromStringRenderer('mustache');
  3292. /**
  3293. * Mustache string support.
  3294. */
  3295. exports.mustache.render = function(str, options, cb) {
  3296. return promisify(cb, function(cb) {
  3297. var engine = requires.mustache || (requires.mustache = require('mustache'));
  3298. try {
  3299. cb(null, engine.render(str, options, options.partials));
  3300. } catch (err) {
  3301. cb(err);
  3302. }
  3303. });
  3304. };
  3305. /**
  3306. * Just support.
  3307. */
  3308. exports.just = function(path, options, cb) {
  3309. return promisify(cb, function(cb) {
  3310. var engine = requires.just;
  3311. if (!engine) {
  3312. var JUST = require('just');
  3313. engine = requires.just = new JUST();
  3314. }
  3315. engine.configure({ useCache: options.cache });
  3316. engine.render(path, options, cb);
  3317. });
  3318. };
  3319. /**
  3320. * Just string support.
  3321. */
  3322. exports.just.render = function(str, options, cb) {
  3323. return promisify(cb, function(cb) {
  3324. var JUST = require('just');
  3325. var engine = new JUST({ root: { page: str }});
  3326. engine.render('page', options, cb);
  3327. });
  3328. };
  3329. /**
  3330. * ECT support.
  3331. */
  3332. exports.ect = function(path, options, cb) {
  3333. return promisify(cb, function(cb) {
  3334. var engine = requires.ect;
  3335. if (!engine) {
  3336. var ECT = require('ect');
  3337. engine = requires.ect = new ECT(options);
  3338. }
  3339. engine.configure({ cache: options.cache });
  3340. engine.render(path, options, cb);
  3341. });
  3342. };
  3343. /**
  3344. * ECT string support.
  3345. */
  3346. exports.ect.render = function(str, options, cb) {
  3347. return promisify(cb, function(cb) {
  3348. var ECT = require('ect');
  3349. var engine = new ECT({ root: { page: str }});
  3350. engine.render('page', options, cb);
  3351. });
  3352. };
  3353. /**
  3354. * mote support.
  3355. */
  3356. exports.mote = fromStringRenderer('mote');
  3357. /**
  3358. * mote string support.
  3359. */
  3360. exports.mote.render = function(str, options, cb) {
  3361. return promisify(cb, function(cb) {
  3362. var engine = requires.mote || (requires.mote = require('mote'));
  3363. try {
  3364. var tmpl = cache(options) || cache(options, engine.compile(str));
  3365. cb(null, tmpl(options));
  3366. } catch (err) {
  3367. cb(err);
  3368. }
  3369. });
  3370. };
  3371. /**
  3372. * Toffee support.
  3373. */
  3374. exports.toffee = function(path, options, cb) {
  3375. return promisify(cb, function(cb) {
  3376. var toffee = requires.toffee || (requires.toffee = require('toffee'));
  3377. toffee.__consolidate_engine_render(path, options, cb);
  3378. });
  3379. };
  3380. /**
  3381. * Toffee string support.
  3382. */
  3383. exports.toffee.render = function(str, options, cb) {
  3384. return promisify(cb, function(cb) {
  3385. var engine = requires.toffee || (requires.toffee = require('toffee'));
  3386. try {
  3387. engine.str_render(str, options, cb);
  3388. } catch (err) {
  3389. cb(err);
  3390. }
  3391. });
  3392. };
  3393. /**
  3394. * doT support.
  3395. */
  3396. exports.dot = fromStringRenderer('dot');
  3397. /**
  3398. * doT string support.
  3399. */
  3400. exports.dot.render = function(str, options, cb) {
  3401. return promisify(cb, function(cb) {
  3402. var engine = requires.dot || (requires.dot = require('dot'));
  3403. var extend = (requires.extend || (requires.extend = require$$2._extend));
  3404. try {
  3405. var settings = {};
  3406. settings = extend(settings, engine.templateSettings);
  3407. settings = extend(settings, options ? options.dot : {});
  3408. var tmpl = cache(options) || cache(options, engine.template(str, settings, options));
  3409. cb(null, tmpl(options));
  3410. } catch (err) {
  3411. cb(err);
  3412. }
  3413. });
  3414. };
  3415. /**
  3416. * bracket support.
  3417. */
  3418. exports.bracket = fromStringRenderer('bracket');
  3419. /**
  3420. * bracket string support.
  3421. */
  3422. exports.bracket.render = function(str, options, cb) {
  3423. return promisify(cb, function(cb) {
  3424. var engine = requires.bracket || (requires.bracket = require('bracket-template'));
  3425. try {
  3426. var tmpl = cache(options) || cache(options, engine.default.compile(str, options));
  3427. cb(null, tmpl(options));
  3428. } catch (err) {
  3429. cb(err);
  3430. }
  3431. });
  3432. };
  3433. /**
  3434. * Ractive support.
  3435. */
  3436. exports.ractive = fromStringRenderer('ractive');
  3437. /**
  3438. * Ractive string support.
  3439. */
  3440. exports.ractive.render = function(str, options, cb) {
  3441. return promisify(cb, function(cb) {
  3442. var Engine = requires.ractive || (requires.ractive = require('ractive'));
  3443. var template = cache(options) || cache(options, Engine.parse(str));
  3444. options.template = template;
  3445. if (options.data === null || options.data === undefined) {
  3446. var extend = (requires.extend || (requires.extend = require$$2._extend));
  3447. // Shallow clone the options object
  3448. options.data = extend({}, options);
  3449. // Remove consolidate-specific properties from the clone
  3450. var i;
  3451. var length;
  3452. var properties = ['template', 'filename', 'cache', 'partials'];
  3453. for (i = 0, length = properties.length; i < length; i++) {
  3454. var property = properties[i];
  3455. delete options.data[property];
  3456. }
  3457. }
  3458. try {
  3459. cb(null, new Engine(options).toHTML());
  3460. } catch (err) {
  3461. cb(err);
  3462. }
  3463. });
  3464. };
  3465. /**
  3466. * Nunjucks support.
  3467. */
  3468. exports.nunjucks = fromStringRenderer('nunjucks');
  3469. /**
  3470. * Nunjucks string support.
  3471. */
  3472. exports.nunjucks.render = function(str, options, cb) {
  3473. return promisify(cb, function(cb) {
  3474. try {
  3475. var engine = options.nunjucksEnv || requires.nunjucks || (requires.nunjucks = require('nunjucks'));
  3476. var env = engine;
  3477. // deprecated fallback support for express
  3478. // <https://github.com/tj/consolidate.js/pull/152>
  3479. // <https://github.com/tj/consolidate.js/pull/224>
  3480. if (options.settings && options.settings.views) {
  3481. env = engine.configure(options.settings.views);
  3482. } else if (options.nunjucks && options.nunjucks.configure) {
  3483. env = engine.configure.apply(engine, options.nunjucks.configure);
  3484. }
  3485. //
  3486. // because `renderString` does not initiate loaders
  3487. // we must manually create a loader for it based off
  3488. // either `options.settings.views` or `options.nunjucks` or `options.nunjucks.root`
  3489. //
  3490. // <https://github.com/mozilla/nunjucks/issues/730>
  3491. // <https://github.com/crocodilejs/node-email-templates/issues/182>
  3492. //
  3493. // so instead we simply check if we passed a custom loader
  3494. // otherwise we create a simple file based loader
  3495. if (options.loader) {
  3496. env = new engine.Environment(options.loader);
  3497. } else if (options.settings && options.settings.views) {
  3498. env = new engine.Environment(
  3499. new engine.FileSystemLoader(options.settings.views)
  3500. );
  3501. } else if (options.nunjucks && options.nunjucks.loader) {
  3502. if (typeof options.nunjucks.loader === 'string') {
  3503. env = new engine.Environment(new engine.FileSystemLoader(options.nunjucks.loader));
  3504. } else {
  3505. env = new engine.Environment(
  3506. new engine.FileSystemLoader(
  3507. options.nunjucks.loader[0],
  3508. options.nunjucks.loader[1]
  3509. )
  3510. );
  3511. }
  3512. }
  3513. env.renderString(str, options, cb);
  3514. } catch (err) {
  3515. throw cb(err);
  3516. }
  3517. });
  3518. };
  3519. /**
  3520. * HTMLing support.
  3521. */
  3522. exports.htmling = fromStringRenderer('htmling');
  3523. /**
  3524. * HTMLing string support.
  3525. */
  3526. exports.htmling.render = function(str, options, cb) {
  3527. return promisify(cb, function(cb) {
  3528. var engine = requires.htmling || (requires.htmling = require('htmling'));
  3529. try {
  3530. var tmpl = cache(options) || cache(options, engine.string(str));
  3531. cb(null, tmpl.render(options));
  3532. } catch (err) {
  3533. cb(err);
  3534. }
  3535. });
  3536. };
  3537. /**
  3538. * Rendering function
  3539. */
  3540. function requireReact(module, filename) {
  3541. var babel = requires.babel || (requires.babel = require('babel-core'));
  3542. var compiled = babel.transformFileSync(filename, { presets: [ 'react' ] }).code;
  3543. return module._compile(compiled, filename);
  3544. }
  3545. exports.requireReact = requireReact;
  3546. /**
  3547. * Converting a string into a node module.
  3548. */
  3549. function requireReactString(src, filename) {
  3550. var babel = requires.babel || (requires.babel = require('babel-core'));
  3551. if (!filename) filename = '';
  3552. var m = new module.constructor();
  3553. filename = filename || '';
  3554. // Compile Using React
  3555. var compiled = babel.transform(src, { presets: [ 'react' ] }).code;
  3556. // Compile as a module
  3557. m.paths = module.paths;
  3558. m._compile(compiled, filename);
  3559. return m.exports;
  3560. }
  3561. /**
  3562. * A naive helper to replace {{tags}} with options.tags content
  3563. */
  3564. function reactBaseTmpl(data, options) {
  3565. var exp;
  3566. var regex;
  3567. // Iterates through the keys in file object
  3568. // and interpolate / replace {{key}} with it's value
  3569. for (var k in options) {
  3570. if (options.hasOwnProperty(k)) {
  3571. exp = '{{' + k + '}}';
  3572. regex = new RegExp(exp, 'g');
  3573. if (data.match(regex)) {
  3574. data = data.replace(regex, options[k]);
  3575. }
  3576. }
  3577. }
  3578. return data;
  3579. }
  3580. /**
  3581. * Plates Support.
  3582. */
  3583. exports.plates = fromStringRenderer('plates');
  3584. /**
  3585. * Plates string support.
  3586. */
  3587. exports.plates.render = function(str, options, cb) {
  3588. return promisify(cb, function(cb) {
  3589. var engine = requires.plates || (requires.plates = require('plates'));
  3590. var map = options.map || undefined;
  3591. try {
  3592. var tmpl = engine.bind(str, options, map);
  3593. cb(null, tmpl);
  3594. } catch (err) {
  3595. cb(err);
  3596. }
  3597. });
  3598. };
  3599. /**
  3600. * The main render parser for React bsaed templates
  3601. */
  3602. function reactRenderer(type) {
  3603. if (commonjsRequire.extensions) {
  3604. // Ensure JSX is transformed on require
  3605. if (!commonjsRequire.extensions['.jsx']) {
  3606. commonjsRequire.extensions['.jsx'] = requireReact;
  3607. }
  3608. // Supporting .react extension as well as test cases
  3609. // Using .react extension is not recommended.
  3610. if (!commonjsRequire.extensions['.react']) {
  3611. commonjsRequire.extensions['.react'] = requireReact;
  3612. }
  3613. }
  3614. // Return rendering fx
  3615. return function(str, options, cb) {
  3616. return promisify(cb, function(cb) {
  3617. // React Import
  3618. var ReactDOM = requires.ReactDOM || (requires.ReactDOM = require('react-dom/server'));
  3619. var react = requires.react || (requires.react = require('react'));
  3620. // Assign HTML Base
  3621. var base = options.base;
  3622. delete options.base;
  3623. var enableCache = options.cache;
  3624. delete options.cache;
  3625. var isNonStatic = options.isNonStatic;
  3626. delete options.isNonStatic;
  3627. // Start Conversion
  3628. try {
  3629. var Code;
  3630. var Factory;
  3631. var baseStr;
  3632. var content;
  3633. var parsed;
  3634. if (!cache(options)) {
  3635. // Parsing
  3636. if (type === 'path') {
  3637. var path = resolve(str);
  3638. delete require.cache[path];
  3639. Code = commonjsRequire(path);
  3640. } else {
  3641. Code = requireReactString(str);
  3642. }
  3643. Factory = cache(options, react.createFactory(Code));
  3644. } else {
  3645. Factory = cache(options);
  3646. }
  3647. parsed = new Factory(options);
  3648. content = (isNonStatic) ? ReactDOM.renderToString(parsed) : ReactDOM.renderToStaticMarkup(parsed);
  3649. if (base) {
  3650. baseStr = readCache[str] || fs.readFileSync(resolve(base), 'utf8');
  3651. if (enableCache) {
  3652. readCache[str] = baseStr;
  3653. }
  3654. options.content = content;
  3655. content = reactBaseTmpl(baseStr, options);
  3656. }
  3657. cb(null, content);
  3658. } catch (err) {
  3659. cb(err);
  3660. }
  3661. });
  3662. };
  3663. }
  3664. /**
  3665. * React JS Support
  3666. */
  3667. exports.react = reactRenderer('path');
  3668. /**
  3669. * React JS string support.
  3670. */
  3671. exports.react.render = reactRenderer('string');
  3672. /**
  3673. * ARC-templates support.
  3674. */
  3675. exports['arc-templates'] = fromStringRenderer('arc-templates');
  3676. /**
  3677. * ARC-templates string support.
  3678. */
  3679. exports['arc-templates'].render = function(str, options, cb) {
  3680. var readFileWithOptions = util.promisify(read);
  3681. var consolidateFileSystem = {};
  3682. consolidateFileSystem.readFile = function(path) {
  3683. return readFileWithOptions(path, options);
  3684. };
  3685. return promisify(cb, function(cb) {
  3686. try {
  3687. var engine = requires['arc-templates'];
  3688. if (!engine) {
  3689. var Engine = require('arc-templates/dist/es5');
  3690. engine = requires['arc-templates'] = new Engine({ filesystem: consolidateFileSystem });
  3691. }
  3692. var compiler = cache(options) || cache(options, engine.compileString(str, options.filename));
  3693. compiler.then(function(func) { return func(options); })
  3694. .then(function(result) { cb(null, result.content); })
  3695. .catch(cb);
  3696. } catch (err) {
  3697. cb(err);
  3698. }
  3699. });
  3700. };
  3701. /**
  3702. * Vash support
  3703. */
  3704. exports.vash = fromStringRenderer('vash');
  3705. /**
  3706. * Vash string support
  3707. */
  3708. exports.vash.render = function(str, options, cb) {
  3709. return promisify(cb, function(cb) {
  3710. var engine = requires.vash || (requires.vash = require('vash'));
  3711. try {
  3712. // helper system : https://github.com/kirbysayshi/vash#helper-system
  3713. if (options.helpers) {
  3714. for (var key in options.helpers) {
  3715. if (!options.helpers.hasOwnProperty(key) || typeof options.helpers[key] !== 'function') {
  3716. continue;
  3717. }
  3718. engine.helpers[key] = options.helpers[key];
  3719. }
  3720. }
  3721. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3722. tmpl(options, function sealLayout(err, ctx) {
  3723. if (err) cb(err);
  3724. ctx.finishLayout();
  3725. cb(null, ctx.toString().replace(/\n$/, ''));
  3726. });
  3727. } catch (err) {
  3728. cb(err);
  3729. }
  3730. });
  3731. };
  3732. /**
  3733. * Slm support.
  3734. */
  3735. exports.slm = fromStringRenderer('slm');
  3736. /**
  3737. * Slm string support.
  3738. */
  3739. exports.slm.render = function(str, options, cb) {
  3740. return promisify(cb, function(cb) {
  3741. var engine = requires.slm || (requires.slm = require('slm'));
  3742. try {
  3743. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3744. cb(null, tmpl(options));
  3745. } catch (err) {
  3746. cb(err);
  3747. }
  3748. });
  3749. };
  3750. /**
  3751. * Marko support.
  3752. */
  3753. exports.marko = function(path, options, cb) {
  3754. return promisify(cb, function(cb) {
  3755. var engine = requires.marko || (requires.marko = require('marko'));
  3756. options.writeToDisk = !!options.cache;
  3757. try {
  3758. var tmpl = cache(options) || cache(options, engine.load(path, options));
  3759. tmpl.renderToString(options, cb);
  3760. } catch (err) {
  3761. cb(err);
  3762. }
  3763. });
  3764. };
  3765. /**
  3766. * Marko string support.
  3767. */
  3768. exports.marko.render = function(str, options, cb) {
  3769. return promisify(cb, function(cb) {
  3770. var engine = requires.marko || (requires.marko = require('marko'));
  3771. options.writeToDisk = !!options.cache;
  3772. options.filename = options.filename || 'string.marko';
  3773. try {
  3774. var tmpl = cache(options) || cache(options, engine.load(options.filename, str, options));
  3775. tmpl.renderToString(options, cb);
  3776. } catch (err) {
  3777. cb(err);
  3778. }
  3779. });
  3780. };
  3781. /**
  3782. * Teacup support.
  3783. */
  3784. exports.teacup = function(path, options, cb) {
  3785. return promisify(cb, function(cb) {
  3786. var engine = requires.teacup || (requires.teacup = require('teacup/lib/express'));
  3787. commonjsRequire.extensions['.teacup'] = commonjsRequire.extensions['.coffee'];
  3788. if (path[0] !== '/') {
  3789. path = join(process.cwd(), path);
  3790. }
  3791. if (!options.cache) {
  3792. var callback = cb;
  3793. cb = function() {
  3794. delete require.cache[path];
  3795. callback.apply(this, arguments);
  3796. };
  3797. }
  3798. engine.renderFile(path, options, cb);
  3799. });
  3800. };
  3801. /**
  3802. * Teacup string support.
  3803. */
  3804. exports.teacup.render = function(str, options, cb) {
  3805. var coffee = require('coffee-script');
  3806. var vm = require('vm');
  3807. var sandbox = {
  3808. module: {exports: {}},
  3809. require: commonjsRequire
  3810. };
  3811. return promisify(cb, function(cb) {
  3812. vm.runInNewContext(coffee.compile(str), sandbox);
  3813. var tmpl = sandbox.module.exports;
  3814. cb(null, tmpl(options));
  3815. });
  3816. };
  3817. /**
  3818. * Squirrelly support.
  3819. */
  3820. exports.squirrelly = fromStringRenderer('squirrelly');
  3821. /**
  3822. * Squirrelly string support.
  3823. */
  3824. exports.squirrelly.render = function(str, options, cb) {
  3825. return promisify(cb, function(cb) {
  3826. var engine = requires.squirrelly || (requires.squirrelly = require('squirrelly'));
  3827. try {
  3828. for (var partial in options.partials) {
  3829. engine.definePartial(partial, options.partials[partial]);
  3830. }
  3831. for (var helper in options.helpers) {
  3832. engine.defineHelper(helper, options.helpers[helper]);
  3833. }
  3834. var tmpl = cache(options) || cache(options, engine.Compile(str, options));
  3835. cb(null, tmpl(options, engine));
  3836. } catch (err) {
  3837. cb(err);
  3838. }
  3839. });
  3840. };
  3841. /**
  3842. * Twing support.
  3843. */
  3844. exports.twing = fromStringRenderer('twing');
  3845. /**
  3846. * Twing string support.
  3847. */
  3848. exports.twing.render = function(str, options, cb) {
  3849. return promisify(cb, function(cb) {
  3850. var engine = requires.twing || (requires.twing = require('twing'));
  3851. try {
  3852. new engine.TwingEnvironment(new engine.TwingLoaderNull()).createTemplate(str).then((twingTemplate) => {
  3853. twingTemplate.render(options).then((rendTmpl) => {
  3854. var tmpl = cache(options) || cache(options, rendTmpl);
  3855. cb(null, tmpl);
  3856. });
  3857. });
  3858. } catch (err) {
  3859. cb(err);
  3860. }
  3861. });
  3862. };
  3863. /**
  3864. * expose the instance of the engine
  3865. */
  3866. exports.requires = requires;
  3867. } (consolidate$2, consolidate$2.exports));
  3868. return consolidate$2.exports;
  3869. }
  3870. var consolidate$1;
  3871. var hasRequiredConsolidate;
  3872. function requireConsolidate () {
  3873. if (hasRequiredConsolidate) return consolidate$1;
  3874. hasRequiredConsolidate = 1;
  3875. consolidate$1 = /*@__PURE__*/ requireConsolidate$1();
  3876. return consolidate$1;
  3877. }
  3878. var consolidateExports = /*@__PURE__*/ requireConsolidate();
  3879. var consolidate = /*@__PURE__*/getDefaultExportFromCjs(consolidateExports);
  3880. const hasWarned = {};
  3881. function warnOnce(msg) {
  3882. const isNodeProd = typeof process !== "undefined" && process.env.NODE_ENV === "production";
  3883. if (!isNodeProd && true && !hasWarned[msg]) {
  3884. hasWarned[msg] = true;
  3885. warn(msg);
  3886. }
  3887. }
  3888. function warn(msg) {
  3889. console.warn(
  3890. `\x1B[1m\x1B[33m[@vue/compiler-sfc]\x1B[0m\x1B[33m ${msg}\x1B[0m
  3891. `
  3892. );
  3893. }
  3894. function preprocess$1({ source, filename, preprocessOptions }, preprocessor) {
  3895. let res = "";
  3896. let err = null;
  3897. preprocessor.render(
  3898. source,
  3899. { filename, ...preprocessOptions },
  3900. (_err, _res) => {
  3901. if (_err) err = _err;
  3902. res = _res;
  3903. }
  3904. );
  3905. if (err) throw err;
  3906. return res;
  3907. }
  3908. function compileTemplate(options) {
  3909. const { preprocessLang, preprocessCustomRequire } = options;
  3910. const preprocessor = preprocessLang ? preprocessCustomRequire ? preprocessCustomRequire(preprocessLang) : consolidate[preprocessLang] : false;
  3911. if (preprocessor) {
  3912. try {
  3913. return doCompileTemplate({
  3914. ...options,
  3915. source: preprocess$1(options, preprocessor),
  3916. ast: void 0
  3917. // invalidate AST if template goes through preprocessor
  3918. });
  3919. } catch (e) {
  3920. return {
  3921. code: `export default function render() {}`,
  3922. source: options.source,
  3923. tips: [],
  3924. errors: [e]
  3925. };
  3926. }
  3927. } else if (preprocessLang) {
  3928. return {
  3929. code: `export default function render() {}`,
  3930. source: options.source,
  3931. tips: [
  3932. `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
  3933. ],
  3934. errors: [
  3935. `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
  3936. ]
  3937. };
  3938. } else {
  3939. return doCompileTemplate(options);
  3940. }
  3941. }
  3942. function doCompileTemplate({
  3943. filename,
  3944. id,
  3945. scoped,
  3946. slotted,
  3947. inMap,
  3948. source,
  3949. ast: inAST,
  3950. ssr = false,
  3951. ssrCssVars,
  3952. isProd = false,
  3953. compiler,
  3954. compilerOptions = {},
  3955. transformAssetUrls
  3956. }) {
  3957. const errors = [];
  3958. const warnings = [];
  3959. let nodeTransforms = [];
  3960. if (shared.isObject(transformAssetUrls)) {
  3961. const assetOptions = normalizeOptions(transformAssetUrls);
  3962. nodeTransforms = [
  3963. createAssetUrlTransformWithOptions(assetOptions),
  3964. createSrcsetTransformWithOptions(assetOptions)
  3965. ];
  3966. } else if (transformAssetUrls !== false) {
  3967. nodeTransforms = [transformAssetUrl, transformSrcset];
  3968. }
  3969. if (ssr && !ssrCssVars) {
  3970. warnOnce(
  3971. `compileTemplate is called with \`ssr: true\` but no corresponding \`cssVars\` option.`
  3972. );
  3973. }
  3974. if (!id) {
  3975. warnOnce(`compileTemplate now requires the \`id\` option.`);
  3976. id = "";
  3977. }
  3978. const shortId = id.replace(/^data-v-/, "");
  3979. const longId = `data-v-${shortId}`;
  3980. const defaultCompiler = ssr ? CompilerSSR__namespace : CompilerDOM__namespace;
  3981. compiler = compiler || defaultCompiler;
  3982. if (compiler !== defaultCompiler) {
  3983. inAST = void 0;
  3984. }
  3985. inAST = resolveTemplateAST(inAST, {
  3986. compiler,
  3987. compilerOptions,
  3988. ssr,
  3989. onError: (e) => errors.push(e)
  3990. });
  3991. let { code, ast, preamble, map } = compiler.compile(inAST || source, {
  3992. mode: "module",
  3993. prefixIdentifiers: true,
  3994. hoistStatic: true,
  3995. cacheHandlers: true,
  3996. ssrCssVars: ssr && ssrCssVars && ssrCssVars.length ? genCssVarsFromList(ssrCssVars, shortId, isProd, true) : "",
  3997. scopeId: scoped ? longId : void 0,
  3998. slotted,
  3999. sourceMap: true,
  4000. ...compilerOptions,
  4001. hmr: !isProd,
  4002. nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []),
  4003. filename,
  4004. onError: (e) => errors.push(e),
  4005. onWarn: (w) => warnings.push(w)
  4006. });
  4007. if (inMap && !inAST) {
  4008. if (map) {
  4009. map = mapLines(inMap, map);
  4010. }
  4011. if (errors.length) {
  4012. patchErrors(errors, source, inMap);
  4013. }
  4014. }
  4015. const tips = warnings.map((w) => {
  4016. let msg = w.message;
  4017. if (w.loc) {
  4018. msg += `
  4019. ${shared.generateCodeFrame(
  4020. (inAST == null ? void 0 : inAST.source) || source,
  4021. w.loc.start.offset,
  4022. w.loc.end.offset
  4023. )}`;
  4024. }
  4025. return msg;
  4026. });
  4027. return { code, ast, preamble, source, errors, tips, map };
  4028. }
  4029. function mapLines(oldMap, newMap) {
  4030. if (!oldMap) return newMap;
  4031. if (!newMap) return oldMap;
  4032. const oldMapConsumer = new sourceMapJs.SourceMapConsumer(oldMap);
  4033. const newMapConsumer = new sourceMapJs.SourceMapConsumer(newMap);
  4034. const mergedMapGenerator = new sourceMapJs.SourceMapGenerator();
  4035. newMapConsumer.eachMapping((m) => {
  4036. if (m.originalLine == null) {
  4037. return;
  4038. }
  4039. const origPosInOldMap = oldMapConsumer.originalPositionFor({
  4040. line: m.originalLine,
  4041. column: m.originalColumn
  4042. });
  4043. if (origPosInOldMap.source == null) {
  4044. return;
  4045. }
  4046. mergedMapGenerator.addMapping({
  4047. generated: {
  4048. line: m.generatedLine,
  4049. column: m.generatedColumn
  4050. },
  4051. original: {
  4052. line: origPosInOldMap.line,
  4053. // map line
  4054. // use current column, since the oldMap produced by @vue/compiler-sfc
  4055. // does not
  4056. column: m.originalColumn
  4057. },
  4058. source: origPosInOldMap.source,
  4059. name: origPosInOldMap.name
  4060. });
  4061. });
  4062. const generator = mergedMapGenerator;
  4063. oldMapConsumer.sources.forEach((sourceFile) => {
  4064. generator._sources.add(sourceFile);
  4065. const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
  4066. if (sourceContent != null) {
  4067. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  4068. }
  4069. });
  4070. generator._sourceRoot = oldMap.sourceRoot;
  4071. generator._file = oldMap.file;
  4072. return generator.toJSON();
  4073. }
  4074. function patchErrors(errors, source, inMap) {
  4075. const originalSource = inMap.sourcesContent[0];
  4076. const offset = originalSource.indexOf(source);
  4077. const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
  4078. errors.forEach((err) => {
  4079. if (err.loc) {
  4080. err.loc.start.line += lineOffset;
  4081. err.loc.start.offset += offset;
  4082. if (err.loc.end !== err.loc.start) {
  4083. err.loc.end.line += lineOffset;
  4084. err.loc.end.offset += offset;
  4085. }
  4086. }
  4087. });
  4088. }
  4089. const trimPlugin = () => {
  4090. return {
  4091. postcssPlugin: "vue-sfc-trim",
  4092. Once(root) {
  4093. root.walk(({ type, raws }) => {
  4094. if (type === "rule" || type === "atrule") {
  4095. if (raws.before) raws.before = "\n";
  4096. if ("after" in raws && raws.after) raws.after = "\n";
  4097. }
  4098. });
  4099. }
  4100. };
  4101. };
  4102. trimPlugin.postcss = true;
  4103. var processor$1 = {};
  4104. var parser$1 = {};
  4105. var root$1 = {};
  4106. var container$1 = {};
  4107. var util$2 = {};
  4108. var unesc$1 = {};
  4109. var hasRequiredUnesc$1;
  4110. function requireUnesc$1 () {
  4111. if (hasRequiredUnesc$1) return unesc$1;
  4112. hasRequiredUnesc$1 = 1;
  4113. // Many thanks for this post which made this migration much easier.
  4114. // https://mathiasbynens.be/notes/css-escapes
  4115. Object.defineProperty(unesc$1, "__esModule", { value: true });
  4116. unesc$1.default = unesc;
  4117. /**
  4118. *
  4119. * @param {string} str
  4120. * @returns {[string, number]|undefined}
  4121. */
  4122. function gobbleHex(str) {
  4123. var lower = str.toLowerCase();
  4124. var hex = "";
  4125. var spaceTerminated = false;
  4126. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  4127. var code = lower.charCodeAt(i);
  4128. // check to see if we are dealing with a valid hex char [a-f|0-9]
  4129. var valid = (code >= 97 && code <= 102) || (code >= 48 && code <= 57);
  4130. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  4131. spaceTerminated = code === 32;
  4132. if (!valid) {
  4133. break;
  4134. }
  4135. hex += lower[i];
  4136. }
  4137. if (hex.length === 0) {
  4138. return undefined;
  4139. }
  4140. var codePoint = parseInt(hex, 16);
  4141. var isSurrogate = codePoint >= 0xd800 && codePoint <= 0xdfff;
  4142. // Add special case for
  4143. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  4144. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  4145. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10ffff) {
  4146. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  4147. }
  4148. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  4149. }
  4150. var CONTAINS_ESCAPE = /\\/;
  4151. function unesc(str) {
  4152. var needToProcess = CONTAINS_ESCAPE.test(str);
  4153. if (!needToProcess) {
  4154. return str;
  4155. }
  4156. var ret = "";
  4157. for (var i = 0; i < str.length; i++) {
  4158. if (str[i] === "\\") {
  4159. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  4160. if (gobbled !== undefined) {
  4161. ret += gobbled[0];
  4162. i += gobbled[1];
  4163. continue;
  4164. }
  4165. // Retain a pair of \\ if double escaped `\\\\`
  4166. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  4167. if (str[i + 1] === "\\") {
  4168. ret += "\\";
  4169. i++;
  4170. continue;
  4171. }
  4172. // if \\ is at the end of the string retain it
  4173. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  4174. if (str.length === i + 1) {
  4175. ret += str[i];
  4176. }
  4177. continue;
  4178. }
  4179. ret += str[i];
  4180. }
  4181. return ret;
  4182. }
  4183. return unesc$1;
  4184. }
  4185. var getProp$1 = {};
  4186. var hasRequiredGetProp$1;
  4187. function requireGetProp$1 () {
  4188. if (hasRequiredGetProp$1) return getProp$1;
  4189. hasRequiredGetProp$1 = 1;
  4190. Object.defineProperty(getProp$1, "__esModule", { value: true });
  4191. getProp$1.default = getProp;
  4192. function getProp(obj) {
  4193. var props = [];
  4194. for (var _i = 1; _i < arguments.length; _i++) {
  4195. props[_i - 1] = arguments[_i];
  4196. }
  4197. while (props.length > 0) {
  4198. var prop = props.shift();
  4199. if (!obj[prop]) {
  4200. return undefined;
  4201. }
  4202. obj = obj[prop];
  4203. }
  4204. return obj;
  4205. }
  4206. return getProp$1;
  4207. }
  4208. var ensureObject$1 = {};
  4209. var hasRequiredEnsureObject$1;
  4210. function requireEnsureObject$1 () {
  4211. if (hasRequiredEnsureObject$1) return ensureObject$1;
  4212. hasRequiredEnsureObject$1 = 1;
  4213. Object.defineProperty(ensureObject$1, "__esModule", { value: true });
  4214. ensureObject$1.default = ensureObject;
  4215. function ensureObject(obj) {
  4216. var props = [];
  4217. for (var _i = 1; _i < arguments.length; _i++) {
  4218. props[_i - 1] = arguments[_i];
  4219. }
  4220. while (props.length > 0) {
  4221. var prop = props.shift();
  4222. if (!obj[prop]) {
  4223. obj[prop] = {};
  4224. }
  4225. obj = obj[prop];
  4226. }
  4227. }
  4228. return ensureObject$1;
  4229. }
  4230. var stripComments$1 = {};
  4231. var hasRequiredStripComments$1;
  4232. function requireStripComments$1 () {
  4233. if (hasRequiredStripComments$1) return stripComments$1;
  4234. hasRequiredStripComments$1 = 1;
  4235. Object.defineProperty(stripComments$1, "__esModule", { value: true });
  4236. stripComments$1.default = stripComments;
  4237. function stripComments(str) {
  4238. var s = "";
  4239. var commentStart = str.indexOf("/*");
  4240. var lastEnd = 0;
  4241. while (commentStart >= 0) {
  4242. s = s + str.slice(lastEnd, commentStart);
  4243. var commentEnd = str.indexOf("*/", commentStart + 2);
  4244. if (commentEnd < 0) {
  4245. return s;
  4246. }
  4247. lastEnd = commentEnd + 2;
  4248. commentStart = str.indexOf("/*", lastEnd);
  4249. }
  4250. s = s + str.slice(lastEnd);
  4251. return s;
  4252. }
  4253. return stripComments$1;
  4254. }
  4255. var maxNestingDepth = {};
  4256. var hasRequiredMaxNestingDepth;
  4257. function requireMaxNestingDepth () {
  4258. if (hasRequiredMaxNestingDepth) return maxNestingDepth;
  4259. hasRequiredMaxNestingDepth = 1;
  4260. (function (exports) {
  4261. Object.defineProperty(exports, "__esModule", { value: true });
  4262. exports.MAX_NESTING_DEPTH = void 0;
  4263. exports.default = resolveMaxNestingDepth;
  4264. /**
  4265. * The default maximum selector nesting depth allowed when parsing or
  4266. * serializing a selector. Going beyond this would otherwise recurse deeply
  4267. * enough to overflow the call stack (CVE-2026-9358 / CWE-674). Real-world
  4268. * selectors never get anywhere near this, so it acts purely as a safety net
  4269. * that turns an uncatchable stack overflow into a catchable error.
  4270. */
  4271. exports.MAX_NESTING_DEPTH = 256;
  4272. /**
  4273. * Coerce a user-supplied nesting-depth limit into a safe value. Anything that
  4274. * is not a non-negative safe integer (NaN, Infinity, negative numbers, or a
  4275. * non-number) would disable or break the guard, so it falls back to the
  4276. * default.
  4277. *
  4278. * @param {unknown} value the limit provided through the `maxNestingDepth` option
  4279. * @returns {number} a safe, non-negative integer limit
  4280. */
  4281. function resolveMaxNestingDepth(value) {
  4282. return Number.isSafeInteger(value) && value >= 0 ? value : exports.MAX_NESTING_DEPTH;
  4283. }
  4284. } (maxNestingDepth));
  4285. return maxNestingDepth;
  4286. }
  4287. var hasRequiredUtil$2;
  4288. function requireUtil$2 () {
  4289. if (hasRequiredUtil$2) return util$2;
  4290. hasRequiredUtil$2 = 1;
  4291. (function (exports) {
  4292. var __importDefault = (util$2 && util$2.__importDefault) || function (mod) {
  4293. return (mod && mod.__esModule) ? mod : { "default": mod };
  4294. };
  4295. Object.defineProperty(exports, "__esModule", { value: true });
  4296. exports.MAX_NESTING_DEPTH = exports.resolveMaxNestingDepth = exports.stripComments = exports.ensureObject = exports.getProp = exports.unesc = void 0;
  4297. var unesc_1 = /*@__PURE__*/ requireUnesc$1();
  4298. Object.defineProperty(exports, "unesc", { enumerable: true, get: function () { return __importDefault(unesc_1).default; } });
  4299. var getProp_1 = /*@__PURE__*/ requireGetProp$1();
  4300. Object.defineProperty(exports, "getProp", { enumerable: true, get: function () { return __importDefault(getProp_1).default; } });
  4301. var ensureObject_1 = /*@__PURE__*/ requireEnsureObject$1();
  4302. Object.defineProperty(exports, "ensureObject", { enumerable: true, get: function () { return __importDefault(ensureObject_1).default; } });
  4303. var stripComments_1 = /*@__PURE__*/ requireStripComments$1();
  4304. Object.defineProperty(exports, "stripComments", { enumerable: true, get: function () { return __importDefault(stripComments_1).default; } });
  4305. var maxNestingDepth_1 = /*@__PURE__*/ requireMaxNestingDepth();
  4306. Object.defineProperty(exports, "resolveMaxNestingDepth", { enumerable: true, get: function () { return __importDefault(maxNestingDepth_1).default; } });
  4307. Object.defineProperty(exports, "MAX_NESTING_DEPTH", { enumerable: true, get: function () { return maxNestingDepth_1.MAX_NESTING_DEPTH; } });
  4308. } (util$2));
  4309. return util$2;
  4310. }
  4311. var node$2 = {};
  4312. var hasRequiredNode$2;
  4313. function requireNode$2 () {
  4314. if (hasRequiredNode$2) return node$2;
  4315. hasRequiredNode$2 = 1;
  4316. Object.defineProperty(node$2, "__esModule", { value: true });
  4317. var util_1 = /*@__PURE__*/ requireUtil$2();
  4318. var cloneNode = function (obj, parent, depth) {
  4319. if (depth === void 0) { depth = 0; }
  4320. // Bound recursion so a pathologically deep node tree raises a catchable
  4321. // error instead of overflowing the call stack (CVE-2026-9358 / CWE-674).
  4322. if (depth > util_1.MAX_NESTING_DEPTH) {
  4323. throw new Error("Cannot clone selector: nesting depth exceeds the maximum of ".concat(util_1.MAX_NESTING_DEPTH, "."));
  4324. }
  4325. if (typeof obj !== "object" || obj === null) {
  4326. return obj;
  4327. }
  4328. var cloned = new obj.constructor();
  4329. for (var i in obj) {
  4330. if (!obj.hasOwnProperty(i)) {
  4331. continue;
  4332. }
  4333. var value = obj[i];
  4334. var type = typeof value;
  4335. if (i === "parent" && type === "object") {
  4336. if (parent) {
  4337. cloned[i] = parent;
  4338. }
  4339. }
  4340. else if (value instanceof Array) {
  4341. cloned[i] = value.map(function (j) { return cloneNode(j, cloned, depth + 1); });
  4342. }
  4343. else {
  4344. cloned[i] = cloneNode(value, cloned, depth + 1);
  4345. }
  4346. }
  4347. return cloned;
  4348. };
  4349. var Node = /** @class */ (function () {
  4350. function Node(opts) {
  4351. if (opts === void 0) { opts = {}; }
  4352. Object.assign(this, opts);
  4353. this.spaces = this.spaces || {};
  4354. this.spaces.before = this.spaces.before || "";
  4355. this.spaces.after = this.spaces.after || "";
  4356. }
  4357. Node.prototype.remove = function () {
  4358. if (this.parent) {
  4359. this.parent.removeChild(this);
  4360. }
  4361. this.parent = undefined;
  4362. return this;
  4363. };
  4364. Node.prototype.replaceWith = function () {
  4365. if (this.parent) {
  4366. for (var index in arguments) {
  4367. this.parent.insertBefore(this, arguments[index]);
  4368. }
  4369. this.remove();
  4370. }
  4371. return this;
  4372. };
  4373. Node.prototype.next = function () {
  4374. return this.parent.at(this.parent.index(this) + 1);
  4375. };
  4376. Node.prototype.prev = function () {
  4377. return this.parent.at(this.parent.index(this) - 1);
  4378. };
  4379. Node.prototype.clone = function (overrides) {
  4380. if (overrides === void 0) { overrides = {}; }
  4381. var cloned = cloneNode(this);
  4382. for (var name in overrides) {
  4383. cloned[name] = overrides[name];
  4384. }
  4385. return cloned;
  4386. };
  4387. /**
  4388. * Some non-standard syntax doesn't follow normal escaping rules for css.
  4389. * This allows non standard syntax to be appended to an existing property
  4390. * by specifying the escaped value. By specifying the escaped value,
  4391. * illegal characters are allowed to be directly inserted into css output.
  4392. * @param {string} name the property to set
  4393. * @param {any} value the unescaped value of the property
  4394. * @param {string} valueEscaped optional. the escaped value of the property.
  4395. */
  4396. Node.prototype.appendToPropertyAndEscape = function (name, value, valueEscaped) {
  4397. if (!this.raws) {
  4398. this.raws = {};
  4399. }
  4400. var originalValue = this[name];
  4401. var originalEscaped = this.raws[name];
  4402. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  4403. if (originalEscaped || valueEscaped !== value) {
  4404. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  4405. }
  4406. else {
  4407. delete this.raws[name]; // delete any escaped value that was created by the setter.
  4408. }
  4409. };
  4410. /**
  4411. * Some non-standard syntax doesn't follow normal escaping rules for css.
  4412. * This allows the escaped value to be specified directly, allowing illegal
  4413. * characters to be directly inserted into css output.
  4414. * @param {string} name the property to set
  4415. * @param {any} value the unescaped value of the property
  4416. * @param {string} valueEscaped the escaped value of the property.
  4417. */
  4418. Node.prototype.setPropertyAndEscape = function (name, value, valueEscaped) {
  4419. if (!this.raws) {
  4420. this.raws = {};
  4421. }
  4422. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  4423. this.raws[name] = valueEscaped;
  4424. };
  4425. /**
  4426. * When you want a value to passed through to CSS directly. This method
  4427. * deletes the corresponding raw value causing the stringifier to fallback
  4428. * to the unescaped value.
  4429. * @param {string} name the property to set.
  4430. * @param {any} value The value that is both escaped and unescaped.
  4431. */
  4432. Node.prototype.setPropertyWithoutEscape = function (name, value) {
  4433. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  4434. if (this.raws) {
  4435. delete this.raws[name];
  4436. }
  4437. };
  4438. /**
  4439. *
  4440. * @param {number} line The number (starting with 1)
  4441. * @param {number} column The column number (starting with 1)
  4442. */
  4443. Node.prototype.isAtPosition = function (line, column) {
  4444. if (this.source && this.source.start && this.source.end) {
  4445. if (this.source.start.line > line) {
  4446. return false;
  4447. }
  4448. if (this.source.end.line < line) {
  4449. return false;
  4450. }
  4451. if (this.source.start.line === line && this.source.start.column > column) {
  4452. return false;
  4453. }
  4454. if (this.source.end.line === line && this.source.end.column < column) {
  4455. return false;
  4456. }
  4457. return true;
  4458. }
  4459. return undefined;
  4460. };
  4461. Node.prototype.stringifyProperty = function (name) {
  4462. return (this.raws && this.raws[name]) || this[name];
  4463. };
  4464. Object.defineProperty(Node.prototype, "rawSpaceBefore", {
  4465. get: function () {
  4466. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  4467. if (rawSpace === undefined) {
  4468. rawSpace = this.spaces && this.spaces.before;
  4469. }
  4470. return rawSpace || "";
  4471. },
  4472. set: function (raw) {
  4473. (0, util_1.ensureObject)(this, "raws", "spaces");
  4474. this.raws.spaces.before = raw;
  4475. },
  4476. enumerable: false,
  4477. configurable: true
  4478. });
  4479. Object.defineProperty(Node.prototype, "rawSpaceAfter", {
  4480. get: function () {
  4481. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  4482. if (rawSpace === undefined) {
  4483. rawSpace = this.spaces.after;
  4484. }
  4485. return rawSpace || "";
  4486. },
  4487. set: function (raw) {
  4488. (0, util_1.ensureObject)(this, "raws", "spaces");
  4489. this.raws.spaces.after = raw;
  4490. },
  4491. enumerable: false,
  4492. configurable: true
  4493. });
  4494. Node.prototype.valueToString = function () {
  4495. return String(this.stringifyProperty("value"));
  4496. };
  4497. Node.prototype.toString = function () {
  4498. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join("");
  4499. };
  4500. // Internal recursion entry point used by Container serialization. Leaf
  4501. // nodes don't recurse, so they ignore the depth/limit and stringify
  4502. // themselves. Containers override this to thread the nesting depth.
  4503. Node.prototype._stringify = function () {
  4504. return this.toString();
  4505. };
  4506. return Node;
  4507. }());
  4508. node$2.default = Node;
  4509. return node$2;
  4510. }
  4511. var types$2 = {};
  4512. var hasRequiredTypes$1;
  4513. function requireTypes$1 () {
  4514. if (hasRequiredTypes$1) return types$2;
  4515. hasRequiredTypes$1 = 1;
  4516. Object.defineProperty(types$2, "__esModule", { value: true });
  4517. types$2.UNIVERSAL = types$2.ATTRIBUTE = types$2.CLASS = types$2.COMBINATOR = types$2.COMMENT = types$2.ID = types$2.NESTING = types$2.PSEUDO = types$2.ROOT = types$2.SELECTOR = types$2.STRING = types$2.TAG = void 0;
  4518. types$2.TAG = "tag";
  4519. types$2.STRING = "string";
  4520. types$2.SELECTOR = "selector";
  4521. types$2.ROOT = "root";
  4522. types$2.PSEUDO = "pseudo";
  4523. types$2.NESTING = "nesting";
  4524. types$2.ID = "id";
  4525. types$2.COMMENT = "comment";
  4526. types$2.COMBINATOR = "combinator";
  4527. types$2.CLASS = "class";
  4528. types$2.ATTRIBUTE = "attribute";
  4529. types$2.UNIVERSAL = "universal";
  4530. return types$2;
  4531. }
  4532. var hasRequiredContainer$1;
  4533. function requireContainer$1 () {
  4534. if (hasRequiredContainer$1) return container$1;
  4535. hasRequiredContainer$1 = 1;
  4536. var __extends = (container$1 && container$1.__extends) || (function () {
  4537. var extendStatics = function (d, b) {
  4538. extendStatics = Object.setPrototypeOf ||
  4539. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4540. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  4541. return extendStatics(d, b);
  4542. };
  4543. return function (d, b) {
  4544. if (typeof b !== "function" && b !== null)
  4545. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  4546. extendStatics(d, b);
  4547. function __() { this.constructor = d; }
  4548. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4549. };
  4550. })();
  4551. var __createBinding = (container$1 && container$1.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  4552. if (k2 === undefined) k2 = k;
  4553. var desc = Object.getOwnPropertyDescriptor(m, k);
  4554. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  4555. desc = { enumerable: true, get: function() { return m[k]; } };
  4556. }
  4557. Object.defineProperty(o, k2, desc);
  4558. }) : (function(o, m, k, k2) {
  4559. if (k2 === undefined) k2 = k;
  4560. o[k2] = m[k];
  4561. }));
  4562. var __setModuleDefault = (container$1 && container$1.__setModuleDefault) || (Object.create ? (function(o, v) {
  4563. Object.defineProperty(o, "default", { enumerable: true, value: v });
  4564. }) : function(o, v) {
  4565. o["default"] = v;
  4566. });
  4567. var __importStar = (container$1 && container$1.__importStar) || (function () {
  4568. var ownKeys = function(o) {
  4569. ownKeys = Object.getOwnPropertyNames || function (o) {
  4570. var ar = [];
  4571. for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
  4572. return ar;
  4573. };
  4574. return ownKeys(o);
  4575. };
  4576. return function (mod) {
  4577. if (mod && mod.__esModule) return mod;
  4578. var result = {};
  4579. if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
  4580. __setModuleDefault(result, mod);
  4581. return result;
  4582. };
  4583. })();
  4584. var __values = (container$1 && container$1.__values) || function(o) {
  4585. var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  4586. if (m) return m.call(o);
  4587. if (o && typeof o.length === "number") return {
  4588. next: function () {
  4589. if (o && i >= o.length) o = void 0;
  4590. return { value: o && o[i++], done: !o };
  4591. }
  4592. };
  4593. throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
  4594. };
  4595. var __read = (container$1 && container$1.__read) || function (o, n) {
  4596. var m = typeof Symbol === "function" && o[Symbol.iterator];
  4597. if (!m) return o;
  4598. var i = m.call(o), r, ar = [], e;
  4599. try {
  4600. while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  4601. }
  4602. catch (error) { e = { error: error }; }
  4603. finally {
  4604. try {
  4605. if (r && !r.done && (m = i["return"])) m.call(i);
  4606. }
  4607. finally { if (e) throw e.error; }
  4608. }
  4609. return ar;
  4610. };
  4611. var __spreadArray = (container$1 && container$1.__spreadArray) || function (to, from, pack) {
  4612. if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
  4613. if (ar || !(i in from)) {
  4614. if (!ar) ar = Array.prototype.slice.call(from, 0, i);
  4615. ar[i] = from[i];
  4616. }
  4617. }
  4618. return to.concat(ar || Array.prototype.slice.call(from));
  4619. };
  4620. var __importDefault = (container$1 && container$1.__importDefault) || function (mod) {
  4621. return (mod && mod.__esModule) ? mod : { "default": mod };
  4622. };
  4623. Object.defineProperty(container$1, "__esModule", { value: true });
  4624. var util_1 = /*@__PURE__*/ requireUtil$2();
  4625. var node_1 = __importDefault(/*@__PURE__*/ requireNode$2());
  4626. var types = __importStar(/*@__PURE__*/ requireTypes$1());
  4627. var Container = /** @class */ (function (_super) {
  4628. __extends(Container, _super);
  4629. function Container(opts) {
  4630. var _this = _super.call(this, opts) || this;
  4631. if (!_this.nodes) {
  4632. _this.nodes = [];
  4633. }
  4634. return _this;
  4635. }
  4636. Container.prototype.append = function (selector) {
  4637. selector.parent = this;
  4638. this.nodes.push(selector);
  4639. return this;
  4640. };
  4641. Container.prototype.prepend = function (selector) {
  4642. selector.parent = this;
  4643. this.nodes.unshift(selector);
  4644. for (var id in this.indexes) {
  4645. this.indexes[id]++;
  4646. }
  4647. return this;
  4648. };
  4649. Container.prototype.at = function (index) {
  4650. return this.nodes[index];
  4651. };
  4652. Container.prototype.index = function (child) {
  4653. if (typeof child === "number") {
  4654. return child;
  4655. }
  4656. return this.nodes.indexOf(child);
  4657. };
  4658. Object.defineProperty(Container.prototype, "first", {
  4659. get: function () {
  4660. return this.at(0);
  4661. },
  4662. enumerable: false,
  4663. configurable: true
  4664. });
  4665. Object.defineProperty(Container.prototype, "last", {
  4666. get: function () {
  4667. return this.at(this.length - 1);
  4668. },
  4669. enumerable: false,
  4670. configurable: true
  4671. });
  4672. Object.defineProperty(Container.prototype, "length", {
  4673. get: function () {
  4674. return this.nodes.length;
  4675. },
  4676. enumerable: false,
  4677. configurable: true
  4678. });
  4679. Container.prototype.removeChild = function (child) {
  4680. child = this.index(child);
  4681. this.at(child).parent = undefined;
  4682. this.nodes.splice(child, 1);
  4683. var index;
  4684. for (var id in this.indexes) {
  4685. index = this.indexes[id];
  4686. if (index >= child) {
  4687. this.indexes[id] = index - 1;
  4688. }
  4689. }
  4690. return this;
  4691. };
  4692. Container.prototype.removeAll = function () {
  4693. var e_1, _a;
  4694. try {
  4695. for (var _b = __values(this.nodes), _c = _b.next(); !_c.done; _c = _b.next()) {
  4696. var node = _c.value;
  4697. node.parent = undefined;
  4698. }
  4699. }
  4700. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  4701. finally {
  4702. try {
  4703. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  4704. }
  4705. finally { if (e_1) throw e_1.error; }
  4706. }
  4707. this.nodes = [];
  4708. return this;
  4709. };
  4710. Container.prototype.empty = function () {
  4711. return this.removeAll();
  4712. };
  4713. Container.prototype.insertAfter = function (oldNode, newNode) {
  4714. var _a;
  4715. newNode.parent = this;
  4716. var oldIndex = this.index(oldNode);
  4717. var resetNode = [];
  4718. for (var i = 2; i < arguments.length; i++) {
  4719. resetNode.push(arguments[i]);
  4720. }
  4721. (_a = this.nodes).splice.apply(_a, __spreadArray([oldIndex + 1, 0, newNode], __read(resetNode), false));
  4722. newNode.parent = this;
  4723. var index;
  4724. for (var id in this.indexes) {
  4725. index = this.indexes[id];
  4726. if (oldIndex < index) {
  4727. this.indexes[id] = index + arguments.length - 1;
  4728. }
  4729. }
  4730. return this;
  4731. };
  4732. Container.prototype.insertBefore = function (oldNode, newNode) {
  4733. var _a;
  4734. newNode.parent = this;
  4735. var oldIndex = this.index(oldNode);
  4736. var resetNode = [];
  4737. for (var i = 2; i < arguments.length; i++) {
  4738. resetNode.push(arguments[i]);
  4739. }
  4740. (_a = this.nodes).splice.apply(_a, __spreadArray([oldIndex, 0, newNode], __read(resetNode), false));
  4741. newNode.parent = this;
  4742. var index;
  4743. for (var id in this.indexes) {
  4744. index = this.indexes[id];
  4745. if (index >= oldIndex) {
  4746. this.indexes[id] = index + arguments.length - 1;
  4747. }
  4748. }
  4749. return this;
  4750. };
  4751. Container.prototype._findChildAtPosition = function (line, col) {
  4752. var found = undefined;
  4753. this.each(function (node) {
  4754. if (node.atPosition) {
  4755. var foundChild = node.atPosition(line, col);
  4756. if (foundChild) {
  4757. found = foundChild;
  4758. return false;
  4759. }
  4760. }
  4761. else if (node.isAtPosition(line, col)) {
  4762. found = node;
  4763. return false;
  4764. }
  4765. });
  4766. return found;
  4767. };
  4768. /**
  4769. * Return the most specific node at the line and column number given.
  4770. * The source location is based on the original parsed location, locations aren't
  4771. * updated as selector nodes are mutated.
  4772. *
  4773. * Note that this location is relative to the location of the first character
  4774. * of the selector, and not the location of the selector in the overall document
  4775. * when used in conjunction with postcss.
  4776. *
  4777. * If not found, returns undefined.
  4778. * @param {number} line The line number of the node to find. (1-based index)
  4779. * @param {number} col The column number of the node to find. (1-based index)
  4780. */
  4781. Container.prototype.atPosition = function (line, col) {
  4782. if (this.isAtPosition(line, col)) {
  4783. return this._findChildAtPosition(line, col) || this;
  4784. }
  4785. else {
  4786. return undefined;
  4787. }
  4788. };
  4789. Container.prototype._inferEndPosition = function () {
  4790. if (this.last && this.last.source && this.last.source.end) {
  4791. this.source = this.source || {};
  4792. this.source.end = this.source.end || {};
  4793. Object.assign(this.source.end, this.last.source.end);
  4794. }
  4795. };
  4796. Container.prototype.each = function (callback) {
  4797. if (!this.lastEach) {
  4798. this.lastEach = 0;
  4799. }
  4800. if (!this.indexes) {
  4801. this.indexes = {};
  4802. }
  4803. this.lastEach++;
  4804. var id = this.lastEach;
  4805. this.indexes[id] = 0;
  4806. if (!this.length) {
  4807. return undefined;
  4808. }
  4809. var index, result;
  4810. while (this.indexes[id] < this.length) {
  4811. index = this.indexes[id];
  4812. result = callback(this.at(index), index);
  4813. if (result === false) {
  4814. break;
  4815. }
  4816. this.indexes[id] += 1;
  4817. }
  4818. delete this.indexes[id];
  4819. if (result === false) {
  4820. return false;
  4821. }
  4822. };
  4823. Container.prototype.walk = function (callback, depth) {
  4824. if (depth === void 0) { depth = 0; }
  4825. // Bound recursion so a pathologically deep node tree raises a catchable
  4826. // error instead of overflowing the call stack (CVE-2026-9358 / CWE-674).
  4827. if (depth > util_1.MAX_NESTING_DEPTH) {
  4828. throw new Error("Cannot walk selector: nesting depth exceeds the maximum of ".concat(util_1.MAX_NESTING_DEPTH, "."));
  4829. }
  4830. return this.each(function (node, i) {
  4831. var result = callback(node, i);
  4832. if (result !== false && node.length) {
  4833. result = node.walk(callback, depth + 1);
  4834. }
  4835. if (result === false) {
  4836. return false;
  4837. }
  4838. });
  4839. };
  4840. Container.prototype.walkAttributes = function (callback) {
  4841. var _this = this;
  4842. return this.walk(function (selector) {
  4843. if (selector.type === types.ATTRIBUTE) {
  4844. return callback.call(_this, selector);
  4845. }
  4846. });
  4847. };
  4848. Container.prototype.walkClasses = function (callback) {
  4849. var _this = this;
  4850. return this.walk(function (selector) {
  4851. if (selector.type === types.CLASS) {
  4852. return callback.call(_this, selector);
  4853. }
  4854. });
  4855. };
  4856. Container.prototype.walkCombinators = function (callback) {
  4857. var _this = this;
  4858. return this.walk(function (selector) {
  4859. if (selector.type === types.COMBINATOR) {
  4860. return callback.call(_this, selector);
  4861. }
  4862. });
  4863. };
  4864. Container.prototype.walkComments = function (callback) {
  4865. var _this = this;
  4866. return this.walk(function (selector) {
  4867. if (selector.type === types.COMMENT) {
  4868. return callback.call(_this, selector);
  4869. }
  4870. });
  4871. };
  4872. Container.prototype.walkIds = function (callback) {
  4873. var _this = this;
  4874. return this.walk(function (selector) {
  4875. if (selector.type === types.ID) {
  4876. return callback.call(_this, selector);
  4877. }
  4878. });
  4879. };
  4880. Container.prototype.walkNesting = function (callback) {
  4881. var _this = this;
  4882. return this.walk(function (selector) {
  4883. if (selector.type === types.NESTING) {
  4884. return callback.call(_this, selector);
  4885. }
  4886. });
  4887. };
  4888. Container.prototype.walkPseudos = function (callback) {
  4889. var _this = this;
  4890. return this.walk(function (selector) {
  4891. if (selector.type === types.PSEUDO) {
  4892. return callback.call(_this, selector);
  4893. }
  4894. });
  4895. };
  4896. Container.prototype.walkTags = function (callback) {
  4897. var _this = this;
  4898. return this.walk(function (selector) {
  4899. if (selector.type === types.TAG) {
  4900. return callback.call(_this, selector);
  4901. }
  4902. });
  4903. };
  4904. Container.prototype.walkUniversals = function (callback) {
  4905. var _this = this;
  4906. return this.walk(function (selector) {
  4907. if (selector.type === types.UNIVERSAL) {
  4908. return callback.call(_this, selector);
  4909. }
  4910. });
  4911. };
  4912. Container.prototype.split = function (callback) {
  4913. var _this = this;
  4914. var current = [];
  4915. return this.reduce(function (memo, node, index) {
  4916. var split = callback.call(_this, node);
  4917. current.push(node);
  4918. if (split) {
  4919. memo.push(current);
  4920. current = [];
  4921. }
  4922. else if (index === _this.length - 1) {
  4923. memo.push(current);
  4924. }
  4925. return memo;
  4926. }, []);
  4927. };
  4928. Container.prototype.map = function (callback) {
  4929. return this.nodes.map(callback);
  4930. };
  4931. Container.prototype.reduce = function (callback, memo) {
  4932. return this.nodes.reduce(callback, memo);
  4933. };
  4934. Container.prototype.every = function (callback) {
  4935. return this.nodes.every(callback);
  4936. };
  4937. Container.prototype.some = function (callback) {
  4938. return this.nodes.some(callback);
  4939. };
  4940. Container.prototype.filter = function (callback) {
  4941. return this.nodes.filter(callback);
  4942. };
  4943. Container.prototype.sort = function (callback) {
  4944. return this.nodes.sort(callback);
  4945. };
  4946. Container.prototype.toString = function (options) {
  4947. if (options === void 0) { options = {}; }
  4948. return this._stringify(options, 0, (0, util_1.resolveMaxNestingDepth)(options.maxNestingDepth));
  4949. };
  4950. Container.prototype._stringify = function (options, depth, max) {
  4951. var _this = this;
  4952. return this.map(function (child) { return _this._stringifyChild(child, options, depth, max); }).join("");
  4953. };
  4954. // Serialize a child node. Historically `toString` used `this.map(String)`,
  4955. // which leniently coerced anything — including raw arrays inserted via
  4956. // `replaceWith(array)` / `insertBefore` / `insertAfter` (e.g. Tailwind's
  4957. // `:merge()` expansion). Fall back to `String(child)` for values that are not
  4958. // parser nodes so that behaviour is preserved.
  4959. Container.prototype._stringifyChild = function (child, options, depth, max) {
  4960. return typeof child._stringify === "function"
  4961. ? child._stringify(options, depth, max)
  4962. : String(child);
  4963. };
  4964. return Container;
  4965. }(node_1.default));
  4966. container$1.default = Container;
  4967. return container$1;
  4968. }
  4969. var hasRequiredRoot$1;
  4970. function requireRoot$1 () {
  4971. if (hasRequiredRoot$1) return root$1;
  4972. hasRequiredRoot$1 = 1;
  4973. var __extends = (root$1 && root$1.__extends) || (function () {
  4974. var extendStatics = function (d, b) {
  4975. extendStatics = Object.setPrototypeOf ||
  4976. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4977. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  4978. return extendStatics(d, b);
  4979. };
  4980. return function (d, b) {
  4981. if (typeof b !== "function" && b !== null)
  4982. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  4983. extendStatics(d, b);
  4984. function __() { this.constructor = d; }
  4985. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4986. };
  4987. })();
  4988. var __importDefault = (root$1 && root$1.__importDefault) || function (mod) {
  4989. return (mod && mod.__esModule) ? mod : { "default": mod };
  4990. };
  4991. Object.defineProperty(root$1, "__esModule", { value: true });
  4992. var container_1 = __importDefault(/*@__PURE__*/ requireContainer$1());
  4993. var types_1 = /*@__PURE__*/ requireTypes$1();
  4994. var Root = /** @class */ (function (_super) {
  4995. __extends(Root, _super);
  4996. function Root(opts) {
  4997. var _this = _super.call(this, opts) || this;
  4998. _this.type = types_1.ROOT;
  4999. return _this;
  5000. }
  5001. Root.prototype._stringify = function (options, depth, max) {
  5002. var _this = this;
  5003. var str = this.reduce(function (memo, selector) {
  5004. memo.push(_this._stringifyChild(selector, options, depth, max));
  5005. return memo;
  5006. }, []).join(",");
  5007. return this.trailingComma ? str + "," : str;
  5008. };
  5009. Root.prototype.error = function (message, options) {
  5010. if (this._error) {
  5011. return this._error(message, options);
  5012. }
  5013. else {
  5014. return new Error(message);
  5015. }
  5016. };
  5017. Object.defineProperty(Root.prototype, "errorGenerator", {
  5018. set: function (handler) {
  5019. this._error = handler;
  5020. },
  5021. enumerable: false,
  5022. configurable: true
  5023. });
  5024. return Root;
  5025. }(container_1.default));
  5026. root$1.default = Root;
  5027. return root$1;
  5028. }
  5029. var selector$1 = {};
  5030. var hasRequiredSelector$1;
  5031. function requireSelector$1 () {
  5032. if (hasRequiredSelector$1) return selector$1;
  5033. hasRequiredSelector$1 = 1;
  5034. var __extends = (selector$1 && selector$1.__extends) || (function () {
  5035. var extendStatics = function (d, b) {
  5036. extendStatics = Object.setPrototypeOf ||
  5037. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  5038. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  5039. return extendStatics(d, b);
  5040. };
  5041. return function (d, b) {
  5042. if (typeof b !== "function" && b !== null)
  5043. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  5044. extendStatics(d, b);
  5045. function __() { this.constructor = d; }
  5046. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  5047. };
  5048. })();
  5049. var __importDefault = (selector$1 && selector$1.__importDefault) || function (mod) {
  5050. return (mod && mod.__esModule) ? mod : { "default": mod };
  5051. };
  5052. Object.defineProperty(selector$1, "__esModule", { value: true });
  5053. var container_1 = __importDefault(/*@__PURE__*/ requireContainer$1());
  5054. var types_1 = /*@__PURE__*/ requireTypes$1();
  5055. var Selector = /** @class */ (function (_super) {
  5056. __extends(Selector, _super);
  5057. function Selector(opts) {
  5058. var _this = _super.call(this, opts) || this;
  5059. _this.type = types_1.SELECTOR;
  5060. return _this;
  5061. }
  5062. return Selector;
  5063. }(container_1.default));
  5064. selector$1.default = Selector;
  5065. return selector$1;
  5066. }
  5067. var className$1 = {};
  5068. /*! https://mths.be/cssesc v3.0.0 by @mathias */
  5069. var cssesc_1;
  5070. var hasRequiredCssesc;
  5071. function requireCssesc () {
  5072. if (hasRequiredCssesc) return cssesc_1;
  5073. hasRequiredCssesc = 1;
  5074. var object = {};
  5075. var hasOwnProperty = object.hasOwnProperty;
  5076. var merge = function merge(options, defaults) {
  5077. if (!options) {
  5078. return defaults;
  5079. }
  5080. var result = {};
  5081. for (var key in defaults) {
  5082. // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
  5083. // only recognized option names are used.
  5084. result[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key];
  5085. }
  5086. return result;
  5087. };
  5088. var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
  5089. var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
  5090. var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  5091. // https://mathiasbynens.be/notes/css-escapes#css
  5092. var cssesc = function cssesc(string, options) {
  5093. options = merge(options, cssesc.options);
  5094. if (options.quotes != 'single' && options.quotes != 'double') {
  5095. options.quotes = 'single';
  5096. }
  5097. var quote = options.quotes == 'double' ? '"' : '\'';
  5098. var isIdentifier = options.isIdentifier;
  5099. var firstChar = string.charAt(0);
  5100. var output = '';
  5101. var counter = 0;
  5102. var length = string.length;
  5103. while (counter < length) {
  5104. var character = string.charAt(counter++);
  5105. var codePoint = character.charCodeAt();
  5106. var value = void 0;
  5107. // If it’s not a printable ASCII character…
  5108. if (codePoint < 0x20 || codePoint > 0x7E) {
  5109. if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
  5110. // It’s a high surrogate, and there is a next character.
  5111. var extra = string.charCodeAt(counter++);
  5112. if ((extra & 0xFC00) == 0xDC00) {
  5113. // next character is low surrogate
  5114. codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
  5115. } else {
  5116. // It’s an unmatched surrogate; only append this code unit, in case
  5117. // the next code unit is the high surrogate of a surrogate pair.
  5118. counter--;
  5119. }
  5120. }
  5121. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  5122. } else {
  5123. if (options.escapeEverything) {
  5124. if (regexAnySingleEscape.test(character)) {
  5125. value = '\\' + character;
  5126. } else {
  5127. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  5128. }
  5129. } else if (/[\t\n\f\r\x0B]/.test(character)) {
  5130. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  5131. } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
  5132. value = '\\' + character;
  5133. } else {
  5134. value = character;
  5135. }
  5136. }
  5137. output += value;
  5138. }
  5139. if (isIdentifier) {
  5140. if (/^-[-\d]/.test(output)) {
  5141. output = '\\-' + output.slice(1);
  5142. } else if (/\d/.test(firstChar)) {
  5143. output = '\\3' + firstChar + ' ' + output.slice(1);
  5144. }
  5145. }
  5146. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  5147. // since they’re redundant. Note that this is only possible if the escape
  5148. // sequence isn’t preceded by an odd number of backslashes.
  5149. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
  5150. if ($1 && $1.length % 2) {
  5151. // It’s not safe to remove the space, so don’t.
  5152. return $0;
  5153. }
  5154. // Strip the space.
  5155. return ($1 || '') + $2;
  5156. });
  5157. if (!isIdentifier && options.wrap) {
  5158. return quote + output + quote;
  5159. }
  5160. return output;
  5161. };
  5162. // Expose default options (so they can be overridden globally).
  5163. cssesc.options = {
  5164. 'escapeEverything': false,
  5165. 'isIdentifier': false,
  5166. 'quotes': 'single',
  5167. 'wrap': false
  5168. };
  5169. cssesc.version = '3.0.0';
  5170. cssesc_1 = cssesc;
  5171. return cssesc_1;
  5172. }
  5173. var hasRequiredClassName$1;
  5174. function requireClassName$1 () {
  5175. if (hasRequiredClassName$1) return className$1;
  5176. hasRequiredClassName$1 = 1;
  5177. var __extends = (className$1 && className$1.__extends) || (function () {
  5178. var extendStatics = function (d, b) {
  5179. extendStatics = Object.setPrototypeOf ||
  5180. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  5181. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  5182. return extendStatics(d, b);
  5183. };
  5184. return function (d, b) {
  5185. if (typeof b !== "function" && b !== null)
  5186. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  5187. extendStatics(d, b);
  5188. function __() { this.constructor = d; }
  5189. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  5190. };
  5191. })();
  5192. var __importDefault = (className$1 && className$1.__importDefault) || function (mod) {
  5193. return (mod && mod.__esModule) ? mod : { "default": mod };
  5194. };
  5195. Object.defineProperty(className$1, "__esModule", { value: true });
  5196. var cssesc_1 = __importDefault(/*@__PURE__*/ requireCssesc());
  5197. var util_1 = /*@__PURE__*/ requireUtil$2();
  5198. var node_1 = __importDefault(/*@__PURE__*/ requireNode$2());
  5199. var types_1 = /*@__PURE__*/ requireTypes$1();
  5200. var ClassName = /** @class */ (function (_super) {
  5201. __extends(ClassName, _super);
  5202. function ClassName(opts) {
  5203. var _this = _super.call(this, opts) || this;
  5204. _this.type = types_1.CLASS;
  5205. _this._constructed = true;
  5206. return _this;
  5207. }
  5208. Object.defineProperty(ClassName.prototype, "value", {
  5209. get: function () {
  5210. return this._value;
  5211. },
  5212. set: function (v) {
  5213. if (this._constructed) {
  5214. var escaped = (0, cssesc_1.default)(v, { isIdentifier: true });
  5215. if (escaped !== v) {
  5216. (0, util_1.ensureObject)(this, "raws");
  5217. this.raws.value = escaped;
  5218. }
  5219. else if (this.raws) {
  5220. delete this.raws.value;
  5221. }
  5222. }
  5223. this._value = v;
  5224. },
  5225. enumerable: false,
  5226. configurable: true
  5227. });
  5228. ClassName.prototype.valueToString = function () {
  5229. return "." + _super.prototype.valueToString.call(this);
  5230. };
  5231. return ClassName;
  5232. }(node_1.default));
  5233. className$1.default = ClassName;
  5234. return className$1;
  5235. }
  5236. var comment$1 = {};
  5237. var hasRequiredComment$1;
  5238. function requireComment$1 () {
  5239. if (hasRequiredComment$1) return comment$1;
  5240. hasRequiredComment$1 = 1;
  5241. var __extends = (comment$1 && comment$1.__extends) || (function () {
  5242. var extendStatics = function (d, b) {
  5243. extendStatics = Object.setPrototypeOf ||
  5244. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  5245. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  5246. return extendStatics(d, b);
  5247. };
  5248. return function (d, b) {
  5249. if (typeof b !== "function" && b !== null)
  5250. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  5251. extendStatics(d, b);
  5252. function __() { this.constructor = d; }
  5253. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  5254. };
  5255. })();
  5256. var __importDefault = (comment$1 && comment$1.__importDefault) || function (mod) {
  5257. return (mod && mod.__esModule) ? mod : { "default": mod };
  5258. };
  5259. Object.defineProperty(comment$1, "__esModule", { value: true });
  5260. var node_1 = __importDefault(/*@__PURE__*/ requireNode$2());
  5261. var types_1 = /*@__PURE__*/ requireTypes$1();
  5262. var Comment = /** @class */ (function (_super) {
  5263. __extends(Comment, _super);
  5264. function Comment(opts) {
  5265. var _this = _super.call(this, opts) || this;
  5266. _this.type = types_1.COMMENT;
  5267. return _this;
  5268. }
  5269. return Comment;
  5270. }(node_1.default));
  5271. comment$1.default = Comment;
  5272. return comment$1;
  5273. }
  5274. var id$1 = {};
  5275. var hasRequiredId$1;
  5276. function requireId$1 () {
  5277. if (hasRequiredId$1) return id$1;
  5278. hasRequiredId$1 = 1;
  5279. var __extends = (id$1 && id$1.__extends) || (function () {
  5280. var extendStatics = function (d, b) {
  5281. extendStatics = Object.setPrototypeOf ||
  5282. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  5283. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  5284. return extendStatics(d, b);
  5285. };
  5286. return function (d, b) {
  5287. if (typeof b !== "function" && b !== null)
  5288. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  5289. extendStatics(d, b);
  5290. function __() { this.constructor = d; }
  5291. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  5292. };
  5293. })();
  5294. var __importDefault = (id$1 && id$1.__importDefault) || function (mod) {
  5295. return (mod && mod.__esModule) ? mod : { "default": mod };
  5296. };
  5297. Object.defineProperty(id$1, "__esModule", { value: true });
  5298. var node_1 = __importDefault(/*@__PURE__*/ requireNode$2());
  5299. var types_1 = /*@__PURE__*/ requireTypes$1();
  5300. var ID = /** @class */ (function (_super) {
  5301. __extends(ID, _super);
  5302. function ID(opts) {
  5303. var _this = _super.call(this, opts) || this;
  5304. _this.type = types_1.ID;
  5305. return _this;
  5306. }
  5307. ID.prototype.valueToString = function () {
  5308. return "#" + _super.prototype.valueToString.call(this);
  5309. };
  5310. return ID;
  5311. }(node_1.default));
  5312. id$1.default = ID;
  5313. return id$1;
  5314. }
  5315. var tag$1 = {};
  5316. var namespace$1 = {};
  5317. var hasRequiredNamespace$1;
  5318. function requireNamespace$1 () {
  5319. if (hasRequiredNamespace$1) return namespace$1;
  5320. hasRequiredNamespace$1 = 1;
  5321. var __extends = (namespace$1 && namespace$1.__extends) || (function () {
  5322. var extendStatics = function (d, b) {
  5323. extendStatics = Object.setPrototypeOf ||
  5324. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  5325. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  5326. return extendStatics(d, b);
  5327. };
  5328. return function (d, b) {
  5329. if (typeof b !== "function" && b !== null)
  5330. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  5331. extendStatics(d, b);
  5332. function __() { this.constructor = d; }
  5333. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  5334. };
  5335. })();
  5336. var __importDefault = (namespace$1 && namespace$1.__importDefault) || function (mod) {
  5337. return (mod && mod.__esModule) ? mod : { "default": mod };
  5338. };
  5339. Object.defineProperty(namespace$1, "__esModule", { value: true });
  5340. var cssesc_1 = __importDefault(/*@__PURE__*/ requireCssesc());
  5341. var util_1 = /*@__PURE__*/ requireUtil$2();
  5342. var node_1 = __importDefault(/*@__PURE__*/ requireNode$2());
  5343. var Namespace = /** @class */ (function (_super) {
  5344. __extends(Namespace, _super);
  5345. function Namespace() {
  5346. return _super !== null && _super.apply(this, arguments) || this;
  5347. }
  5348. Object.defineProperty(Namespace.prototype, "namespace", {
  5349. get: function () {
  5350. return this._namespace;
  5351. },
  5352. set: function (namespace) {
  5353. if (namespace === true || namespace === "*" || namespace === "&") {
  5354. this._namespace = namespace;
  5355. if (this.raws) {
  5356. delete this.raws.namespace;
  5357. }
  5358. return;
  5359. }
  5360. var escaped = (0, cssesc_1.default)(namespace, { isIdentifier: true });
  5361. this._namespace = namespace;
  5362. if (escaped !== namespace) {
  5363. (0, util_1.ensureObject)(this, "raws");
  5364. this.raws.namespace = escaped;
  5365. }
  5366. else if (this.raws) {
  5367. delete this.raws.namespace;
  5368. }
  5369. },
  5370. enumerable: false,
  5371. configurable: true
  5372. });
  5373. Object.defineProperty(Namespace.prototype, "ns", {
  5374. get: function () {
  5375. return this._namespace;
  5376. },
  5377. set: function (namespace) {
  5378. this.namespace = namespace;
  5379. },
  5380. enumerable: false,
  5381. configurable: true
  5382. });
  5383. Object.defineProperty(Namespace.prototype, "namespaceString", {
  5384. get: function () {
  5385. if (this.namespace) {
  5386. var ns = this.stringifyProperty("namespace");
  5387. if (ns === true) {
  5388. return "";
  5389. }
  5390. else {
  5391. return ns;
  5392. }
  5393. }
  5394. else {
  5395. return "";
  5396. }
  5397. },
  5398. enumerable: false,
  5399. configurable: true
  5400. });
  5401. Namespace.prototype.qualifiedName = function (value) {
  5402. if (this.namespace) {
  5403. return "".concat(this.namespaceString, "|").concat(value);
  5404. }
  5405. else {
  5406. return value;
  5407. }
  5408. };
  5409. Namespace.prototype.valueToString = function () {
  5410. return this.qualifiedName(_super.prototype.valueToString.call(this));
  5411. };
  5412. return Namespace;
  5413. }(node_1.default));
  5414. namespace$1.default = Namespace;
  5415. return namespace$1;
  5416. }
  5417. var hasRequiredTag$1;
  5418. function requireTag$1 () {
  5419. if (hasRequiredTag$1) return tag$1;
  5420. hasRequiredTag$1 = 1;
  5421. var __extends = (tag$1 && tag$1.__extends) || (function () {
  5422. var extendStatics = function (d, b) {
  5423. extendStatics = Object.setPrototypeOf ||
  5424. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  5425. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  5426. return extendStatics(d, b);
  5427. };
  5428. return function (d, b) {
  5429. if (typeof b !== "function" && b !== null)
  5430. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  5431. extendStatics(d, b);
  5432. function __() { this.constructor = d; }
  5433. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  5434. };
  5435. })();
  5436. var __importDefault = (tag$1 && tag$1.__importDefault) || function (mod) {
  5437. return (mod && mod.__esModule) ? mod : { "default": mod };
  5438. };
  5439. Object.defineProperty(tag$1, "__esModule", { value: true });
  5440. var namespace_1 = __importDefault(/*@__PURE__*/ requireNamespace$1());
  5441. var types_1 = /*@__PURE__*/ requireTypes$1();
  5442. var Tag = /** @class */ (function (_super) {
  5443. __extends(Tag, _super);
  5444. function Tag(opts) {
  5445. var _this = _super.call(this, opts) || this;
  5446. _this.type = types_1.TAG;
  5447. return _this;
  5448. }
  5449. return Tag;
  5450. }(namespace_1.default));
  5451. tag$1.default = Tag;
  5452. return tag$1;
  5453. }
  5454. var string$1 = {};
  5455. var hasRequiredString$1;
  5456. function requireString$1 () {
  5457. if (hasRequiredString$1) return string$1;
  5458. hasRequiredString$1 = 1;
  5459. var __extends = (string$1 && string$1.__extends) || (function () {
  5460. var extendStatics = function (d, b) {
  5461. extendStatics = Object.setPrototypeOf ||
  5462. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  5463. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  5464. return extendStatics(d, b);
  5465. };
  5466. return function (d, b) {
  5467. if (typeof b !== "function" && b !== null)
  5468. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  5469. extendStatics(d, b);
  5470. function __() { this.constructor = d; }
  5471. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  5472. };
  5473. })();
  5474. var __importDefault = (string$1 && string$1.__importDefault) || function (mod) {
  5475. return (mod && mod.__esModule) ? mod : { "default": mod };
  5476. };
  5477. Object.defineProperty(string$1, "__esModule", { value: true });
  5478. var node_1 = __importDefault(/*@__PURE__*/ requireNode$2());
  5479. var types_1 = /*@__PURE__*/ requireTypes$1();
  5480. var String = /** @class */ (function (_super) {
  5481. __extends(String, _super);
  5482. function String(opts) {
  5483. var _this = _super.call(this, opts) || this;
  5484. _this.type = types_1.STRING;
  5485. return _this;
  5486. }
  5487. return String;
  5488. }(node_1.default));
  5489. string$1.default = String;
  5490. return string$1;
  5491. }
  5492. var pseudo$1 = {};
  5493. var hasRequiredPseudo$1;
  5494. function requirePseudo$1 () {
  5495. if (hasRequiredPseudo$1) return pseudo$1;
  5496. hasRequiredPseudo$1 = 1;
  5497. var __extends = (pseudo$1 && pseudo$1.__extends) || (function () {
  5498. var extendStatics = function (d, b) {
  5499. extendStatics = Object.setPrototypeOf ||
  5500. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  5501. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  5502. return extendStatics(d, b);
  5503. };
  5504. return function (d, b) {
  5505. if (typeof b !== "function" && b !== null)
  5506. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  5507. extendStatics(d, b);
  5508. function __() { this.constructor = d; }
  5509. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  5510. };
  5511. })();
  5512. var __importDefault = (pseudo$1 && pseudo$1.__importDefault) || function (mod) {
  5513. return (mod && mod.__esModule) ? mod : { "default": mod };
  5514. };
  5515. Object.defineProperty(pseudo$1, "__esModule", { value: true });
  5516. var container_1 = __importDefault(/*@__PURE__*/ requireContainer$1());
  5517. var types_1 = /*@__PURE__*/ requireTypes$1();
  5518. var Pseudo = /** @class */ (function (_super) {
  5519. __extends(Pseudo, _super);
  5520. function Pseudo(opts) {
  5521. var _this = _super.call(this, opts) || this;
  5522. _this.type = types_1.PSEUDO;
  5523. return _this;
  5524. }
  5525. Pseudo.prototype._stringify = function (options, depth, max) {
  5526. var _this = this;
  5527. if (depth >= max) {
  5528. throw new Error("Cannot serialize selector: nesting depth exceeds the maximum of ".concat(max, "."));
  5529. }
  5530. var params = this.length
  5531. ? "(" +
  5532. this.map(function (child) { return _this._stringifyChild(child, options, depth + 1, max); }).join(",") +
  5533. ")"
  5534. : "";
  5535. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join("");
  5536. };
  5537. return Pseudo;
  5538. }(container_1.default));
  5539. pseudo$1.default = Pseudo;
  5540. return pseudo$1;
  5541. }
  5542. var attribute$1 = {};
  5543. var node$1;
  5544. var hasRequiredNode$1;
  5545. function requireNode$1 () {
  5546. if (hasRequiredNode$1) return node$1;
  5547. hasRequiredNode$1 = 1;
  5548. /**
  5549. * For Node.js, simply re-export the core `util.deprecate` function.
  5550. */
  5551. node$1 = require$$2.deprecate;
  5552. return node$1;
  5553. }
  5554. var hasRequiredAttribute$1;
  5555. function requireAttribute$1 () {
  5556. if (hasRequiredAttribute$1) return attribute$1;
  5557. hasRequiredAttribute$1 = 1;
  5558. var __extends = (attribute$1 && attribute$1.__extends) || (function () {
  5559. var extendStatics = function (d, b) {
  5560. extendStatics = Object.setPrototypeOf ||
  5561. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  5562. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  5563. return extendStatics(d, b);
  5564. };
  5565. return function (d, b) {
  5566. if (typeof b !== "function" && b !== null)
  5567. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  5568. extendStatics(d, b);
  5569. function __() { this.constructor = d; }
  5570. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  5571. };
  5572. })();
  5573. var __importDefault = (attribute$1 && attribute$1.__importDefault) || function (mod) {
  5574. return (mod && mod.__esModule) ? mod : { "default": mod };
  5575. };
  5576. var _a;
  5577. Object.defineProperty(attribute$1, "__esModule", { value: true });
  5578. attribute$1.unescapeValue = unescapeValue;
  5579. var cssesc_1 = __importDefault(/*@__PURE__*/ requireCssesc());
  5580. var unesc_1 = __importDefault(/*@__PURE__*/ requireUnesc$1());
  5581. var namespace_1 = __importDefault(/*@__PURE__*/ requireNamespace$1());
  5582. var types_1 = /*@__PURE__*/ requireTypes$1();
  5583. var deprecate = /*@__PURE__*/ requireNode$1();
  5584. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  5585. var warnOfDeprecatedValueAssignment = deprecate(function () { }, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " +
  5586. "Call attribute.setValue() instead.");
  5587. var warnOfDeprecatedQuotedAssignment = deprecate(function () { }, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  5588. var warnOfDeprecatedConstructor = deprecate(function () { }, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  5589. function unescapeValue(value) {
  5590. var deprecatedUsage = false;
  5591. var quoteMark = null;
  5592. var unescaped = value;
  5593. var m = unescaped.match(WRAPPED_IN_QUOTES);
  5594. if (m) {
  5595. quoteMark = m[1];
  5596. unescaped = m[2];
  5597. }
  5598. unescaped = (0, unesc_1.default)(unescaped);
  5599. if (unescaped !== value) {
  5600. deprecatedUsage = true;
  5601. }
  5602. return {
  5603. deprecatedUsage: deprecatedUsage,
  5604. unescaped: unescaped,
  5605. quoteMark: quoteMark,
  5606. };
  5607. }
  5608. function handleDeprecatedContructorOpts(opts) {
  5609. if (opts.quoteMark !== undefined) {
  5610. return opts;
  5611. }
  5612. if (opts.value === undefined) {
  5613. return opts;
  5614. }
  5615. warnOfDeprecatedConstructor();
  5616. var _a = unescapeValue(opts.value), quoteMark = _a.quoteMark, unescaped = _a.unescaped;
  5617. if (!opts.raws) {
  5618. opts.raws = {};
  5619. }
  5620. if (opts.raws.value === undefined) {
  5621. opts.raws.value = opts.value;
  5622. }
  5623. opts.value = unescaped;
  5624. opts.quoteMark = quoteMark;
  5625. return opts;
  5626. }
  5627. var Attribute = /** @class */ (function (_super) {
  5628. __extends(Attribute, _super);
  5629. function Attribute(opts) {
  5630. if (opts === void 0) { opts = {}; }
  5631. var _this = _super.call(this, handleDeprecatedContructorOpts(opts)) || this;
  5632. _this.type = types_1.ATTRIBUTE;
  5633. _this.raws = _this.raws || {};
  5634. Object.defineProperty(_this.raws, "unquoted", {
  5635. get: deprecate(function () { return _this.value; }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  5636. set: deprecate(function () { return _this.value; }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now."),
  5637. });
  5638. _this._constructed = true;
  5639. return _this;
  5640. }
  5641. /**
  5642. * Returns the Attribute's value quoted such that it would be legal to use
  5643. * in the value of a css file. The original value's quotation setting
  5644. * used for stringification is left unchanged. See `setValue(value, options)`
  5645. * if you want to control the quote settings of a new value for the attribute.
  5646. *
  5647. * You can also change the quotation used for the current value by setting quoteMark.
  5648. *
  5649. * Options:
  5650. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  5651. * option is not set, the original value for quoteMark will be used. If
  5652. * indeterminate, a double quote is used. The legal values are:
  5653. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  5654. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  5655. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  5656. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  5657. * over the quoteMark option value.
  5658. * * smart {boolean} - if true, will select a quote mark based on the value
  5659. * and the other options specified here. See the `smartQuoteMark()`
  5660. * method.
  5661. **/
  5662. Attribute.prototype.getQuotedValue = function (options) {
  5663. if (options === void 0) { options = {}; }
  5664. var quoteMark = this._determineQuoteMark(options);
  5665. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  5666. var escaped = (0, cssesc_1.default)(this._value, cssescopts);
  5667. return escaped;
  5668. };
  5669. Attribute.prototype._determineQuoteMark = function (options) {
  5670. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  5671. };
  5672. /**
  5673. * Set the unescaped value with the specified quotation options. The value
  5674. * provided must not include any wrapping quote marks -- those quotes will
  5675. * be interpreted as part of the value and escaped accordingly.
  5676. */
  5677. Attribute.prototype.setValue = function (value, options) {
  5678. if (options === void 0) { options = {}; }
  5679. this._value = value;
  5680. this._quoteMark = this._determineQuoteMark(options);
  5681. this._syncRawValue();
  5682. };
  5683. /**
  5684. * Intelligently select a quoteMark value based on the value's contents. If
  5685. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  5686. * mark will be picked that minimizes the number of escapes.
  5687. *
  5688. * If there's no clear winner, the quote mark from these options is used,
  5689. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  5690. * true). If the quoteMark is unspecified, a double quote is used.
  5691. *
  5692. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  5693. * from the quoteValue method.
  5694. */
  5695. Attribute.prototype.smartQuoteMark = function (options) {
  5696. var v = this.value;
  5697. var numSingleQuotes = v.replace(/[^']/g, "").length;
  5698. var numDoubleQuotes = v.replace(/[^"]/g, "").length;
  5699. if (numSingleQuotes + numDoubleQuotes === 0) {
  5700. var escaped = (0, cssesc_1.default)(v, { isIdentifier: true });
  5701. if (escaped === v) {
  5702. return Attribute.NO_QUOTE;
  5703. }
  5704. else {
  5705. var pref = this.preferredQuoteMark(options);
  5706. if (pref === Attribute.NO_QUOTE) {
  5707. // pick a quote mark that isn't none and see if it's smaller
  5708. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  5709. var opts = CSSESC_QUOTE_OPTIONS[quote];
  5710. var quoteValue = (0, cssesc_1.default)(v, opts);
  5711. if (quoteValue.length < escaped.length) {
  5712. return quote;
  5713. }
  5714. }
  5715. return pref;
  5716. }
  5717. }
  5718. else if (numDoubleQuotes === numSingleQuotes) {
  5719. return this.preferredQuoteMark(options);
  5720. }
  5721. else if (numDoubleQuotes < numSingleQuotes) {
  5722. return Attribute.DOUBLE_QUOTE;
  5723. }
  5724. else {
  5725. return Attribute.SINGLE_QUOTE;
  5726. }
  5727. };
  5728. /**
  5729. * Selects the preferred quote mark based on the options and the current quote mark value.
  5730. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  5731. * instead.
  5732. */
  5733. Attribute.prototype.preferredQuoteMark = function (options) {
  5734. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  5735. if (quoteMark === undefined) {
  5736. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  5737. }
  5738. if (quoteMark === undefined) {
  5739. quoteMark = Attribute.DOUBLE_QUOTE;
  5740. }
  5741. return quoteMark;
  5742. };
  5743. Object.defineProperty(Attribute.prototype, "quoted", {
  5744. get: function () {
  5745. var qm = this.quoteMark;
  5746. return qm === "'" || qm === '"';
  5747. },
  5748. set: function (value) {
  5749. warnOfDeprecatedQuotedAssignment();
  5750. },
  5751. enumerable: false,
  5752. configurable: true
  5753. });
  5754. Object.defineProperty(Attribute.prototype, "quoteMark", {
  5755. /**
  5756. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  5757. * returns `null` if the value is not quoted.
  5758. * returns `undefined` if the quotation state is unknown (this can happen when
  5759. * the attribute is constructed without specifying a quote mark.)
  5760. */
  5761. get: function () {
  5762. return this._quoteMark;
  5763. },
  5764. /**
  5765. * Set the quote mark to be used by this attribute's value.
  5766. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  5767. * value is updated accordingly.
  5768. *
  5769. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  5770. */
  5771. set: function (quoteMark) {
  5772. if (!this._constructed) {
  5773. this._quoteMark = quoteMark;
  5774. return;
  5775. }
  5776. if (this._quoteMark !== quoteMark) {
  5777. this._quoteMark = quoteMark;
  5778. this._syncRawValue();
  5779. }
  5780. },
  5781. enumerable: false,
  5782. configurable: true
  5783. });
  5784. Attribute.prototype._syncRawValue = function () {
  5785. var rawValue = (0, cssesc_1.default)(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  5786. if (rawValue === this._value) {
  5787. if (this.raws) {
  5788. delete this.raws.value;
  5789. }
  5790. }
  5791. else {
  5792. this.raws.value = rawValue;
  5793. }
  5794. };
  5795. Object.defineProperty(Attribute.prototype, "qualifiedAttribute", {
  5796. get: function () {
  5797. return this.qualifiedName(this.raws.attribute || this.attribute);
  5798. },
  5799. enumerable: false,
  5800. configurable: true
  5801. });
  5802. Object.defineProperty(Attribute.prototype, "insensitiveFlag", {
  5803. get: function () {
  5804. return this.insensitive ? "i" : "";
  5805. },
  5806. enumerable: false,
  5807. configurable: true
  5808. });
  5809. Object.defineProperty(Attribute.prototype, "value", {
  5810. get: function () {
  5811. return this._value;
  5812. },
  5813. /**
  5814. * Before 3.0, the value had to be set to an escaped value including any wrapped
  5815. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  5816. * is unescaped during parsing and any quote marks are removed.
  5817. *
  5818. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  5819. * a deprecation warning is raised when the new value contains any characters that would
  5820. * require escaping (including if it contains wrapped quotes).
  5821. *
  5822. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  5823. * how the new value is quoted.
  5824. */
  5825. set: function (v) {
  5826. if (this._constructed) {
  5827. var _a = unescapeValue(v), deprecatedUsage = _a.deprecatedUsage, unescaped = _a.unescaped, quoteMark = _a.quoteMark;
  5828. if (deprecatedUsage) {
  5829. warnOfDeprecatedValueAssignment();
  5830. }
  5831. if (unescaped === this._value && quoteMark === this._quoteMark) {
  5832. return;
  5833. }
  5834. this._value = unescaped;
  5835. this._quoteMark = quoteMark;
  5836. this._syncRawValue();
  5837. }
  5838. else {
  5839. this._value = v;
  5840. }
  5841. },
  5842. enumerable: false,
  5843. configurable: true
  5844. });
  5845. Object.defineProperty(Attribute.prototype, "insensitive", {
  5846. get: function () {
  5847. return this._insensitive;
  5848. },
  5849. /**
  5850. * Set the case insensitive flag.
  5851. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  5852. * of the attribute is updated accordingly.
  5853. *
  5854. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  5855. */
  5856. set: function (insensitive) {
  5857. if (!insensitive) {
  5858. this._insensitive = false;
  5859. // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  5860. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  5861. if (this.raws && (this.raws.insensitiveFlag === "I" || this.raws.insensitiveFlag === "i")) {
  5862. this.raws.insensitiveFlag = undefined;
  5863. }
  5864. }
  5865. this._insensitive = insensitive;
  5866. },
  5867. enumerable: false,
  5868. configurable: true
  5869. });
  5870. Object.defineProperty(Attribute.prototype, "attribute", {
  5871. get: function () {
  5872. return this._attribute;
  5873. },
  5874. set: function (name) {
  5875. this._handleEscapes("attribute", name);
  5876. this._attribute = name;
  5877. },
  5878. enumerable: false,
  5879. configurable: true
  5880. });
  5881. Attribute.prototype._handleEscapes = function (prop, value) {
  5882. if (this._constructed) {
  5883. var escaped = (0, cssesc_1.default)(value, { isIdentifier: true });
  5884. if (escaped !== value) {
  5885. this.raws[prop] = escaped;
  5886. }
  5887. else {
  5888. delete this.raws[prop];
  5889. }
  5890. }
  5891. };
  5892. Attribute.prototype._spacesFor = function (name) {
  5893. var attrSpaces = { before: "", after: "" };
  5894. var spaces = this.spaces[name] || {};
  5895. var rawSpaces = (this.raws.spaces && this.raws.spaces[name]) || {};
  5896. return Object.assign(attrSpaces, spaces, rawSpaces);
  5897. };
  5898. Attribute.prototype._stringFor = function (name, spaceName, concat) {
  5899. if (spaceName === void 0) { spaceName = name; }
  5900. if (concat === void 0) { concat = defaultAttrConcat; }
  5901. var attrSpaces = this._spacesFor(spaceName);
  5902. return concat(this.stringifyProperty(name), attrSpaces);
  5903. };
  5904. /**
  5905. * returns the offset of the attribute part specified relative to the
  5906. * start of the node of the output string.
  5907. *
  5908. * * "ns" - alias for "namespace"
  5909. * * "namespace" - the namespace if it exists.
  5910. * * "attribute" - the attribute name
  5911. * * "attributeNS" - the start of the attribute or its namespace
  5912. * * "operator" - the match operator of the attribute
  5913. * * "value" - The value (string or identifier)
  5914. * * "insensitive" - the case insensitivity flag;
  5915. * @param part One of the possible values inside an attribute.
  5916. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  5917. */
  5918. Attribute.prototype.offsetOf = function (name) {
  5919. var count = 1;
  5920. var attributeSpaces = this._spacesFor("attribute");
  5921. count += attributeSpaces.before.length;
  5922. if (name === "namespace" || name === "ns") {
  5923. return this.namespace ? count : -1;
  5924. }
  5925. if (name === "attributeNS") {
  5926. return count;
  5927. }
  5928. count += this.namespaceString.length;
  5929. if (this.namespace) {
  5930. count += 1;
  5931. }
  5932. if (name === "attribute") {
  5933. return count;
  5934. }
  5935. count += this.stringifyProperty("attribute").length;
  5936. count += attributeSpaces.after.length;
  5937. var operatorSpaces = this._spacesFor("operator");
  5938. count += operatorSpaces.before.length;
  5939. var operator = this.stringifyProperty("operator");
  5940. if (name === "operator") {
  5941. return operator ? count : -1;
  5942. }
  5943. count += operator.length;
  5944. count += operatorSpaces.after.length;
  5945. var valueSpaces = this._spacesFor("value");
  5946. count += valueSpaces.before.length;
  5947. var value = this.stringifyProperty("value");
  5948. if (name === "value") {
  5949. return value ? count : -1;
  5950. }
  5951. count += value.length;
  5952. count += valueSpaces.after.length;
  5953. var insensitiveSpaces = this._spacesFor("insensitive");
  5954. count += insensitiveSpaces.before.length;
  5955. if (name === "insensitive") {
  5956. return this.insensitive ? count : -1;
  5957. }
  5958. return -1;
  5959. };
  5960. Attribute.prototype.toString = function () {
  5961. var _this = this;
  5962. var selector = [this.rawSpaceBefore, "["];
  5963. selector.push(this._stringFor("qualifiedAttribute", "attribute"));
  5964. if (this.operator && (this.value || this.value === "")) {
  5965. selector.push(this._stringFor("operator"));
  5966. selector.push(this._stringFor("value"));
  5967. selector.push(this._stringFor("insensitiveFlag", "insensitive", function (attrValue, attrSpaces) {
  5968. if (attrValue.length > 0 &&
  5969. !_this.quoted &&
  5970. attrSpaces.before.length === 0 &&
  5971. !(_this.spaces.value && _this.spaces.value.after)) {
  5972. attrSpaces.before = " ";
  5973. }
  5974. return defaultAttrConcat(attrValue, attrSpaces);
  5975. }));
  5976. }
  5977. selector.push("]");
  5978. selector.push(this.rawSpaceAfter);
  5979. return selector.join("");
  5980. };
  5981. Attribute.NO_QUOTE = null;
  5982. Attribute.SINGLE_QUOTE = "'";
  5983. Attribute.DOUBLE_QUOTE = '"';
  5984. return Attribute;
  5985. }(namespace_1.default));
  5986. attribute$1.default = Attribute;
  5987. var CSSESC_QUOTE_OPTIONS = (_a = {
  5988. "'": { quotes: "single", wrap: true },
  5989. '"': { quotes: "double", wrap: true }
  5990. },
  5991. _a[null] = { isIdentifier: true },
  5992. _a);
  5993. function defaultAttrConcat(attrValue, attrSpaces) {
  5994. return "".concat(attrSpaces.before).concat(attrValue).concat(attrSpaces.after);
  5995. }
  5996. return attribute$1;
  5997. }
  5998. var universal$1 = {};
  5999. var hasRequiredUniversal$1;
  6000. function requireUniversal$1 () {
  6001. if (hasRequiredUniversal$1) return universal$1;
  6002. hasRequiredUniversal$1 = 1;
  6003. var __extends = (universal$1 && universal$1.__extends) || (function () {
  6004. var extendStatics = function (d, b) {
  6005. extendStatics = Object.setPrototypeOf ||
  6006. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  6007. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  6008. return extendStatics(d, b);
  6009. };
  6010. return function (d, b) {
  6011. if (typeof b !== "function" && b !== null)
  6012. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  6013. extendStatics(d, b);
  6014. function __() { this.constructor = d; }
  6015. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  6016. };
  6017. })();
  6018. var __importDefault = (universal$1 && universal$1.__importDefault) || function (mod) {
  6019. return (mod && mod.__esModule) ? mod : { "default": mod };
  6020. };
  6021. Object.defineProperty(universal$1, "__esModule", { value: true });
  6022. var namespace_1 = __importDefault(/*@__PURE__*/ requireNamespace$1());
  6023. var types_1 = /*@__PURE__*/ requireTypes$1();
  6024. var Universal = /** @class */ (function (_super) {
  6025. __extends(Universal, _super);
  6026. function Universal(opts) {
  6027. var _this = _super.call(this, opts) || this;
  6028. _this.type = types_1.UNIVERSAL;
  6029. _this.value = "*";
  6030. return _this;
  6031. }
  6032. return Universal;
  6033. }(namespace_1.default));
  6034. universal$1.default = Universal;
  6035. return universal$1;
  6036. }
  6037. var combinator$1 = {};
  6038. var hasRequiredCombinator$1;
  6039. function requireCombinator$1 () {
  6040. if (hasRequiredCombinator$1) return combinator$1;
  6041. hasRequiredCombinator$1 = 1;
  6042. var __extends = (combinator$1 && combinator$1.__extends) || (function () {
  6043. var extendStatics = function (d, b) {
  6044. extendStatics = Object.setPrototypeOf ||
  6045. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  6046. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  6047. return extendStatics(d, b);
  6048. };
  6049. return function (d, b) {
  6050. if (typeof b !== "function" && b !== null)
  6051. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  6052. extendStatics(d, b);
  6053. function __() { this.constructor = d; }
  6054. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  6055. };
  6056. })();
  6057. var __importDefault = (combinator$1 && combinator$1.__importDefault) || function (mod) {
  6058. return (mod && mod.__esModule) ? mod : { "default": mod };
  6059. };
  6060. Object.defineProperty(combinator$1, "__esModule", { value: true });
  6061. var node_1 = __importDefault(/*@__PURE__*/ requireNode$2());
  6062. var types_1 = /*@__PURE__*/ requireTypes$1();
  6063. var Combinator = /** @class */ (function (_super) {
  6064. __extends(Combinator, _super);
  6065. function Combinator(opts) {
  6066. var _this = _super.call(this, opts) || this;
  6067. _this.type = types_1.COMBINATOR;
  6068. return _this;
  6069. }
  6070. return Combinator;
  6071. }(node_1.default));
  6072. combinator$1.default = Combinator;
  6073. return combinator$1;
  6074. }
  6075. var nesting$1 = {};
  6076. var hasRequiredNesting$1;
  6077. function requireNesting$1 () {
  6078. if (hasRequiredNesting$1) return nesting$1;
  6079. hasRequiredNesting$1 = 1;
  6080. var __extends = (nesting$1 && nesting$1.__extends) || (function () {
  6081. var extendStatics = function (d, b) {
  6082. extendStatics = Object.setPrototypeOf ||
  6083. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  6084. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  6085. return extendStatics(d, b);
  6086. };
  6087. return function (d, b) {
  6088. if (typeof b !== "function" && b !== null)
  6089. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  6090. extendStatics(d, b);
  6091. function __() { this.constructor = d; }
  6092. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  6093. };
  6094. })();
  6095. var __importDefault = (nesting$1 && nesting$1.__importDefault) || function (mod) {
  6096. return (mod && mod.__esModule) ? mod : { "default": mod };
  6097. };
  6098. Object.defineProperty(nesting$1, "__esModule", { value: true });
  6099. var node_1 = __importDefault(/*@__PURE__*/ requireNode$2());
  6100. var types_1 = /*@__PURE__*/ requireTypes$1();
  6101. var Nesting = /** @class */ (function (_super) {
  6102. __extends(Nesting, _super);
  6103. function Nesting(opts) {
  6104. var _this = _super.call(this, opts) || this;
  6105. _this.type = types_1.NESTING;
  6106. _this.value = "&";
  6107. return _this;
  6108. }
  6109. return Nesting;
  6110. }(node_1.default));
  6111. nesting$1.default = Nesting;
  6112. return nesting$1;
  6113. }
  6114. var sortAscending$1 = {};
  6115. var hasRequiredSortAscending$1;
  6116. function requireSortAscending$1 () {
  6117. if (hasRequiredSortAscending$1) return sortAscending$1;
  6118. hasRequiredSortAscending$1 = 1;
  6119. Object.defineProperty(sortAscending$1, "__esModule", { value: true });
  6120. sortAscending$1.default = sortAscending;
  6121. function sortAscending(list) {
  6122. return list.sort(function (a, b) { return a - b; });
  6123. }
  6124. return sortAscending$1;
  6125. }
  6126. var tokenize$1 = {};
  6127. var tokenTypes$1 = {};
  6128. var hasRequiredTokenTypes$1;
  6129. function requireTokenTypes$1 () {
  6130. if (hasRequiredTokenTypes$1) return tokenTypes$1;
  6131. hasRequiredTokenTypes$1 = 1;
  6132. (function (exports) {
  6133. Object.defineProperty(exports, "__esModule", { value: true });
  6134. 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;
  6135. exports.ampersand = 38; // `&`.charCodeAt(0);
  6136. exports.asterisk = 42; // `*`.charCodeAt(0);
  6137. exports.at = 64; // `@`.charCodeAt(0);
  6138. exports.comma = 44; // `,`.charCodeAt(0);
  6139. exports.colon = 58; // `:`.charCodeAt(0);
  6140. exports.semicolon = 59; // `;`.charCodeAt(0);
  6141. exports.openParenthesis = 40; // `(`.charCodeAt(0);
  6142. exports.closeParenthesis = 41; // `)`.charCodeAt(0);
  6143. exports.openSquare = 91; // `[`.charCodeAt(0);
  6144. exports.closeSquare = 93; // `]`.charCodeAt(0);
  6145. exports.dollar = 36; // `$`.charCodeAt(0);
  6146. exports.tilde = 126; // `~`.charCodeAt(0);
  6147. exports.caret = 94; // `^`.charCodeAt(0);
  6148. exports.plus = 43; // `+`.charCodeAt(0);
  6149. exports.equals = 61; // `=`.charCodeAt(0);
  6150. exports.pipe = 124; // `|`.charCodeAt(0);
  6151. exports.greaterThan = 62; // `>`.charCodeAt(0);
  6152. exports.space = 32; // ` `.charCodeAt(0);
  6153. exports.singleQuote = 39; // `'`.charCodeAt(0);
  6154. exports.doubleQuote = 34; // `"`.charCodeAt(0);
  6155. exports.slash = 47; // `/`.charCodeAt(0);
  6156. exports.bang = 33; // `!`.charCodeAt(0);
  6157. exports.backslash = 92; // '\\'.charCodeAt(0);
  6158. exports.cr = 13; // '\r'.charCodeAt(0);
  6159. exports.feed = 12; // '\f'.charCodeAt(0);
  6160. exports.newline = 10; // '\n'.charCodeAt(0);
  6161. exports.tab = 9; // '\t'.charCodeAt(0);
  6162. // Expose aliases primarily for readability.
  6163. exports.str = exports.singleQuote;
  6164. // No good single character representation!
  6165. exports.comment = -1;
  6166. exports.word = -2;
  6167. exports.combinator = -3;
  6168. } (tokenTypes$1));
  6169. return tokenTypes$1;
  6170. }
  6171. var hasRequiredTokenize$1;
  6172. function requireTokenize$1 () {
  6173. if (hasRequiredTokenize$1) return tokenize$1;
  6174. hasRequiredTokenize$1 = 1;
  6175. var __createBinding = (tokenize$1 && tokenize$1.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  6176. if (k2 === undefined) k2 = k;
  6177. var desc = Object.getOwnPropertyDescriptor(m, k);
  6178. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  6179. desc = { enumerable: true, get: function() { return m[k]; } };
  6180. }
  6181. Object.defineProperty(o, k2, desc);
  6182. }) : (function(o, m, k, k2) {
  6183. if (k2 === undefined) k2 = k;
  6184. o[k2] = m[k];
  6185. }));
  6186. var __setModuleDefault = (tokenize$1 && tokenize$1.__setModuleDefault) || (Object.create ? (function(o, v) {
  6187. Object.defineProperty(o, "default", { enumerable: true, value: v });
  6188. }) : function(o, v) {
  6189. o["default"] = v;
  6190. });
  6191. var __importStar = (tokenize$1 && tokenize$1.__importStar) || (function () {
  6192. var ownKeys = function(o) {
  6193. ownKeys = Object.getOwnPropertyNames || function (o) {
  6194. var ar = [];
  6195. for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
  6196. return ar;
  6197. };
  6198. return ownKeys(o);
  6199. };
  6200. return function (mod) {
  6201. if (mod && mod.__esModule) return mod;
  6202. var result = {};
  6203. if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
  6204. __setModuleDefault(result, mod);
  6205. return result;
  6206. };
  6207. })();
  6208. var _a, _b;
  6209. Object.defineProperty(tokenize$1, "__esModule", { value: true });
  6210. tokenize$1.FIELDS = void 0;
  6211. tokenize$1.default = tokenize;
  6212. var t = __importStar(/*@__PURE__*/ requireTokenTypes$1());
  6213. var unescapable = (_a = {},
  6214. _a[t.tab] = true,
  6215. _a[t.newline] = true,
  6216. _a[t.cr] = true,
  6217. _a[t.feed] = true,
  6218. _a);
  6219. var wordDelimiters = (_b = {},
  6220. _b[t.space] = true,
  6221. _b[t.tab] = true,
  6222. _b[t.newline] = true,
  6223. _b[t.cr] = true,
  6224. _b[t.feed] = true,
  6225. _b[t.ampersand] = true,
  6226. _b[t.asterisk] = true,
  6227. _b[t.bang] = true,
  6228. _b[t.comma] = true,
  6229. _b[t.colon] = true,
  6230. _b[t.semicolon] = true,
  6231. _b[t.openParenthesis] = true,
  6232. _b[t.closeParenthesis] = true,
  6233. _b[t.openSquare] = true,
  6234. _b[t.closeSquare] = true,
  6235. _b[t.singleQuote] = true,
  6236. _b[t.doubleQuote] = true,
  6237. _b[t.plus] = true,
  6238. _b[t.pipe] = true,
  6239. _b[t.tilde] = true,
  6240. _b[t.greaterThan] = true,
  6241. _b[t.equals] = true,
  6242. _b[t.dollar] = true,
  6243. _b[t.caret] = true,
  6244. _b[t.slash] = true,
  6245. _b);
  6246. var hex = {};
  6247. var hexChars = "0123456789abcdefABCDEF";
  6248. for (var i = 0; i < hexChars.length; i++) {
  6249. hex[hexChars.charCodeAt(i)] = true;
  6250. }
  6251. /**
  6252. * Returns the last index of the bar css word
  6253. * @param {string} css The string in which the word begins
  6254. * @param {number} start The index into the string where word's first letter occurs
  6255. */
  6256. function consumeWord(css, start) {
  6257. var next = start;
  6258. var code;
  6259. do {
  6260. code = css.charCodeAt(next);
  6261. if (wordDelimiters[code]) {
  6262. return next - 1;
  6263. }
  6264. else if (code === t.backslash) {
  6265. next = consumeEscape(css, next) + 1;
  6266. }
  6267. else {
  6268. // All other characters are part of the word
  6269. next++;
  6270. }
  6271. } while (next < css.length);
  6272. return next - 1;
  6273. }
  6274. /**
  6275. * Returns the last index of the escape sequence
  6276. * @param {string} css The string in which the sequence begins
  6277. * @param {number} start The index into the string where escape character (`\`) occurs.
  6278. */
  6279. function consumeEscape(css, start) {
  6280. var next = start;
  6281. var code = css.charCodeAt(next + 1);
  6282. if (unescapable[code]) ;
  6283. else if (hex[code]) {
  6284. var hexDigits = 0;
  6285. // consume up to 6 hex chars
  6286. do {
  6287. next++;
  6288. hexDigits++;
  6289. code = css.charCodeAt(next + 1);
  6290. } while (hex[code] && hexDigits < 6);
  6291. // if fewer than 6 hex chars, a trailing space ends the escape
  6292. if (hexDigits < 6 && code === t.space) {
  6293. next++;
  6294. }
  6295. }
  6296. else {
  6297. // the next char is part of the current word
  6298. next++;
  6299. }
  6300. return next;
  6301. }
  6302. tokenize$1.FIELDS = {
  6303. TYPE: 0,
  6304. START_LINE: 1,
  6305. START_COL: 2,
  6306. END_LINE: 3,
  6307. END_COL: 4,
  6308. START_POS: 5,
  6309. END_POS: 6,
  6310. };
  6311. function tokenize(input) {
  6312. var tokens = [];
  6313. var css = input.css.valueOf();
  6314. var length = css.length;
  6315. var offset = -1;
  6316. var line = 1;
  6317. var start = 0;
  6318. var end = 0;
  6319. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  6320. function unclosed(what, fix) {
  6321. if (input.safe) {
  6322. // fyi: this is never set to true.
  6323. css += fix;
  6324. next = css.length - 1;
  6325. }
  6326. else {
  6327. throw input.error("Unclosed " + what, line, start - offset, start);
  6328. }
  6329. }
  6330. while (start < length) {
  6331. code = css.charCodeAt(start);
  6332. if (code === t.newline) {
  6333. offset = start;
  6334. line += 1;
  6335. }
  6336. switch (code) {
  6337. case t.space:
  6338. case t.tab:
  6339. case t.newline:
  6340. case t.cr:
  6341. case t.feed:
  6342. next = start;
  6343. do {
  6344. next += 1;
  6345. code = css.charCodeAt(next);
  6346. if (code === t.newline) {
  6347. offset = next;
  6348. line += 1;
  6349. }
  6350. } while (code === t.space ||
  6351. code === t.newline ||
  6352. code === t.tab ||
  6353. code === t.cr ||
  6354. code === t.feed);
  6355. tokenType = t.space;
  6356. endLine = line;
  6357. endColumn = next - offset - 1;
  6358. end = next;
  6359. break;
  6360. case t.plus:
  6361. case t.greaterThan:
  6362. case t.tilde:
  6363. case t.pipe:
  6364. next = start;
  6365. do {
  6366. next += 1;
  6367. code = css.charCodeAt(next);
  6368. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  6369. tokenType = t.combinator;
  6370. endLine = line;
  6371. endColumn = start - offset;
  6372. end = next;
  6373. break;
  6374. // Consume these characters as single tokens.
  6375. case t.asterisk:
  6376. case t.ampersand:
  6377. case t.bang:
  6378. case t.comma:
  6379. case t.equals:
  6380. case t.dollar:
  6381. case t.caret:
  6382. case t.openSquare:
  6383. case t.closeSquare:
  6384. case t.colon:
  6385. case t.semicolon:
  6386. case t.openParenthesis:
  6387. case t.closeParenthesis:
  6388. next = start;
  6389. tokenType = code;
  6390. endLine = line;
  6391. endColumn = start - offset;
  6392. end = next + 1;
  6393. break;
  6394. case t.singleQuote:
  6395. case t.doubleQuote:
  6396. quote = code === t.singleQuote ? "'" : '"';
  6397. next = start;
  6398. do {
  6399. escaped = false;
  6400. next = css.indexOf(quote, next + 1);
  6401. if (next === -1) {
  6402. unclosed("quote", quote);
  6403. }
  6404. escapePos = next;
  6405. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  6406. escapePos -= 1;
  6407. escaped = !escaped;
  6408. }
  6409. } while (escaped);
  6410. tokenType = t.str;
  6411. endLine = line;
  6412. endColumn = start - offset;
  6413. end = next + 1;
  6414. break;
  6415. default:
  6416. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  6417. next = css.indexOf("*/", start + 2) + 1;
  6418. if (next === 0) {
  6419. unclosed("comment", "*/");
  6420. }
  6421. content = css.slice(start, next + 1);
  6422. lines = content.split("\n");
  6423. last = lines.length - 1;
  6424. if (last > 0) {
  6425. nextLine = line + last;
  6426. nextOffset = next - lines[last].length;
  6427. }
  6428. else {
  6429. nextLine = line;
  6430. nextOffset = offset;
  6431. }
  6432. tokenType = t.comment;
  6433. line = nextLine;
  6434. endLine = nextLine;
  6435. endColumn = next - nextOffset;
  6436. }
  6437. else if (code === t.slash) {
  6438. next = start;
  6439. tokenType = code;
  6440. endLine = line;
  6441. endColumn = start - offset;
  6442. end = next + 1;
  6443. }
  6444. else {
  6445. next = consumeWord(css, start);
  6446. tokenType = t.word;
  6447. endLine = line;
  6448. endColumn = next - offset;
  6449. }
  6450. end = next + 1;
  6451. break;
  6452. }
  6453. // Ensure that the token structure remains consistent
  6454. tokens.push([
  6455. tokenType, // [0] Token type
  6456. line, // [1] Starting line
  6457. start - offset, // [2] Starting column
  6458. endLine, // [3] Ending line
  6459. endColumn, // [4] Ending column
  6460. start, // [5] Start position / Source index
  6461. end, // [6] End position
  6462. ]);
  6463. // Reset offset for the next token
  6464. if (nextOffset) {
  6465. offset = nextOffset;
  6466. nextOffset = null;
  6467. }
  6468. start = end;
  6469. }
  6470. return tokens;
  6471. }
  6472. return tokenize$1;
  6473. }
  6474. var hasRequiredParser$2;
  6475. function requireParser$2 () {
  6476. if (hasRequiredParser$2) return parser$1;
  6477. hasRequiredParser$2 = 1;
  6478. var __assign = (parser$1 && parser$1.__assign) || function () {
  6479. __assign = Object.assign || function(t) {
  6480. for (var s, i = 1, n = arguments.length; i < n; i++) {
  6481. s = arguments[i];
  6482. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  6483. t[p] = s[p];
  6484. }
  6485. return t;
  6486. };
  6487. return __assign.apply(this, arguments);
  6488. };
  6489. var __createBinding = (parser$1 && parser$1.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  6490. if (k2 === undefined) k2 = k;
  6491. var desc = Object.getOwnPropertyDescriptor(m, k);
  6492. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  6493. desc = { enumerable: true, get: function() { return m[k]; } };
  6494. }
  6495. Object.defineProperty(o, k2, desc);
  6496. }) : (function(o, m, k, k2) {
  6497. if (k2 === undefined) k2 = k;
  6498. o[k2] = m[k];
  6499. }));
  6500. var __setModuleDefault = (parser$1 && parser$1.__setModuleDefault) || (Object.create ? (function(o, v) {
  6501. Object.defineProperty(o, "default", { enumerable: true, value: v });
  6502. }) : function(o, v) {
  6503. o["default"] = v;
  6504. });
  6505. var __importStar = (parser$1 && parser$1.__importStar) || (function () {
  6506. var ownKeys = function(o) {
  6507. ownKeys = Object.getOwnPropertyNames || function (o) {
  6508. var ar = [];
  6509. for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
  6510. return ar;
  6511. };
  6512. return ownKeys(o);
  6513. };
  6514. return function (mod) {
  6515. if (mod && mod.__esModule) return mod;
  6516. var result = {};
  6517. if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
  6518. __setModuleDefault(result, mod);
  6519. return result;
  6520. };
  6521. })();
  6522. var __read = (parser$1 && parser$1.__read) || function (o, n) {
  6523. var m = typeof Symbol === "function" && o[Symbol.iterator];
  6524. if (!m) return o;
  6525. var i = m.call(o), r, ar = [], e;
  6526. try {
  6527. while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  6528. }
  6529. catch (error) { e = { error: error }; }
  6530. finally {
  6531. try {
  6532. if (r && !r.done && (m = i["return"])) m.call(i);
  6533. }
  6534. finally { if (e) throw e.error; }
  6535. }
  6536. return ar;
  6537. };
  6538. var __spreadArray = (parser$1 && parser$1.__spreadArray) || function (to, from, pack) {
  6539. if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
  6540. if (ar || !(i in from)) {
  6541. if (!ar) ar = Array.prototype.slice.call(from, 0, i);
  6542. ar[i] = from[i];
  6543. }
  6544. }
  6545. return to.concat(ar || Array.prototype.slice.call(from));
  6546. };
  6547. var __importDefault = (parser$1 && parser$1.__importDefault) || function (mod) {
  6548. return (mod && mod.__esModule) ? mod : { "default": mod };
  6549. };
  6550. var _a, _b;
  6551. Object.defineProperty(parser$1, "__esModule", { value: true });
  6552. var root_1 = __importDefault(/*@__PURE__*/ requireRoot$1());
  6553. var selector_1 = __importDefault(/*@__PURE__*/ requireSelector$1());
  6554. var className_1 = __importDefault(/*@__PURE__*/ requireClassName$1());
  6555. var comment_1 = __importDefault(/*@__PURE__*/ requireComment$1());
  6556. var id_1 = __importDefault(/*@__PURE__*/ requireId$1());
  6557. var tag_1 = __importDefault(/*@__PURE__*/ requireTag$1());
  6558. var string_1 = __importDefault(/*@__PURE__*/ requireString$1());
  6559. var pseudo_1 = __importDefault(/*@__PURE__*/ requirePseudo$1());
  6560. var attribute_1 = __importStar(/*@__PURE__*/ requireAttribute$1());
  6561. var universal_1 = __importDefault(/*@__PURE__*/ requireUniversal$1());
  6562. var combinator_1 = __importDefault(/*@__PURE__*/ requireCombinator$1());
  6563. var nesting_1 = __importDefault(/*@__PURE__*/ requireNesting$1());
  6564. var sortAscending_1 = __importDefault(/*@__PURE__*/ requireSortAscending$1());
  6565. var tokenize_1 = __importStar(/*@__PURE__*/ requireTokenize$1());
  6566. var tokens = __importStar(/*@__PURE__*/ requireTokenTypes$1());
  6567. var types = __importStar(/*@__PURE__*/ requireTypes$1());
  6568. var util_1 = /*@__PURE__*/ requireUtil$2();
  6569. var WHITESPACE_TOKENS = (_a = {},
  6570. _a[tokens.space] = true,
  6571. _a[tokens.cr] = true,
  6572. _a[tokens.feed] = true,
  6573. _a[tokens.newline] = true,
  6574. _a[tokens.tab] = true,
  6575. _a);
  6576. var WHITESPACE_EQUIV_TOKENS = __assign(__assign({}, WHITESPACE_TOKENS), (_b = {}, _b[tokens.comment] = true, _b));
  6577. function tokenStart(token) {
  6578. return {
  6579. line: token[tokenize_1.FIELDS.START_LINE],
  6580. column: token[tokenize_1.FIELDS.START_COL],
  6581. };
  6582. }
  6583. function tokenEnd(token) {
  6584. return {
  6585. line: token[tokenize_1.FIELDS.END_LINE],
  6586. column: token[tokenize_1.FIELDS.END_COL],
  6587. };
  6588. }
  6589. function getSource(startLine, startColumn, endLine, endColumn) {
  6590. return {
  6591. start: {
  6592. line: startLine,
  6593. column: startColumn,
  6594. },
  6595. end: {
  6596. line: endLine,
  6597. column: endColumn,
  6598. },
  6599. };
  6600. }
  6601. function getTokenSource(token) {
  6602. 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]);
  6603. }
  6604. function getTokenSourceSpan(startToken, endToken) {
  6605. if (!startToken) {
  6606. return undefined;
  6607. }
  6608. 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]);
  6609. }
  6610. function unescapeProp(node, prop) {
  6611. var value = node[prop];
  6612. if (typeof value !== "string") {
  6613. return;
  6614. }
  6615. if (value.indexOf("\\") !== -1) {
  6616. (0, util_1.ensureObject)(node, "raws");
  6617. node[prop] = (0, util_1.unesc)(value);
  6618. if (node.raws[prop] === undefined) {
  6619. node.raws[prop] = value;
  6620. }
  6621. }
  6622. return node;
  6623. }
  6624. function indexesOf(array, item) {
  6625. var i = -1;
  6626. var indexes = [];
  6627. while ((i = array.indexOf(item, i + 1)) !== -1) {
  6628. indexes.push(i);
  6629. }
  6630. return indexes;
  6631. }
  6632. function uniqs() {
  6633. var list = Array.prototype.concat.apply([], arguments);
  6634. return list.filter(function (item, i) { return i === list.indexOf(item); });
  6635. }
  6636. var Parser = /** @class */ (function () {
  6637. function Parser(rule, options) {
  6638. if (options === void 0) { options = {}; }
  6639. this.rule = rule;
  6640. this.options = Object.assign({ lossy: false, safe: false }, options);
  6641. this.position = 0;
  6642. this.nestingDepth = 0;
  6643. this.maxNestingDepth = (0, util_1.resolveMaxNestingDepth)(this.options.maxNestingDepth);
  6644. this.css = typeof this.rule === "string" ? this.rule : this.rule.selector;
  6645. this.tokens = (0, tokenize_1.default)({
  6646. css: this.css,
  6647. error: this._errorGenerator(),
  6648. safe: this.options.safe,
  6649. });
  6650. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  6651. this.root = new root_1.default({ source: rootSource });
  6652. this.root.errorGenerator = this._errorGenerator();
  6653. var selector = new selector_1.default({
  6654. source: { start: { line: 1, column: 1 } },
  6655. sourceIndex: 0,
  6656. });
  6657. this.root.append(selector);
  6658. this.current = selector;
  6659. this.loop();
  6660. }
  6661. Parser.prototype._errorGenerator = function () {
  6662. var _this = this;
  6663. return function (message, errorOptions) {
  6664. if (typeof _this.rule === "string") {
  6665. return new Error(message);
  6666. }
  6667. return _this.rule.error(message, errorOptions);
  6668. };
  6669. };
  6670. Parser.prototype.attribute = function () {
  6671. var attr = [];
  6672. var startingToken = this.currToken;
  6673. this.position++;
  6674. while (this.position < this.tokens.length &&
  6675. this.currToken[tokenize_1.FIELDS.TYPE] !== tokens.closeSquare) {
  6676. attr.push(this.currToken);
  6677. this.position++;
  6678. }
  6679. if (this.currToken[tokenize_1.FIELDS.TYPE] !== tokens.closeSquare) {
  6680. return this.expected("closing square bracket", this.currToken[tokenize_1.FIELDS.START_POS]);
  6681. }
  6682. var len = attr.length;
  6683. var node = {
  6684. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  6685. sourceIndex: startingToken[tokenize_1.FIELDS.START_POS],
  6686. };
  6687. if (len === 1 && !~[tokens.word].indexOf(attr[0][tokenize_1.FIELDS.TYPE])) {
  6688. return this.expected("attribute", attr[0][tokenize_1.FIELDS.START_POS]);
  6689. }
  6690. var pos = 0;
  6691. var spaceBefore = "";
  6692. var commentBefore = "";
  6693. var lastAdded = null;
  6694. var spaceAfterMeaningfulToken = false;
  6695. while (pos < len) {
  6696. var token = attr[pos];
  6697. var content = this.content(token);
  6698. var next = attr[pos + 1];
  6699. switch (token[tokenize_1.FIELDS.TYPE]) {
  6700. case tokens.space:
  6701. // if (
  6702. // len === 1 ||
  6703. // pos === 0 && this.content(next) === '|'
  6704. // ) {
  6705. // return this.expected('attribute', token[TOKEN.START_POS], content);
  6706. // }
  6707. spaceAfterMeaningfulToken = true;
  6708. if (this.options.lossy) {
  6709. break;
  6710. }
  6711. if (lastAdded) {
  6712. (0, util_1.ensureObject)(node, "spaces", lastAdded);
  6713. var prevContent = node.spaces[lastAdded].after || "";
  6714. node.spaces[lastAdded].after = prevContent + content;
  6715. var existingComment = (0, util_1.getProp)(node, "raws", "spaces", lastAdded, "after") || null;
  6716. if (existingComment) {
  6717. node.raws.spaces[lastAdded].after = existingComment + content;
  6718. }
  6719. }
  6720. else {
  6721. spaceBefore = spaceBefore + content;
  6722. commentBefore = commentBefore + content;
  6723. }
  6724. break;
  6725. case tokens.asterisk:
  6726. if (next[tokenize_1.FIELDS.TYPE] === tokens.equals) {
  6727. node.operator = content;
  6728. lastAdded = "operator";
  6729. }
  6730. else if ((!node.namespace || (lastAdded === "namespace" && !spaceAfterMeaningfulToken)) &&
  6731. next) {
  6732. if (spaceBefore) {
  6733. (0, util_1.ensureObject)(node, "spaces", "attribute");
  6734. node.spaces.attribute.before = spaceBefore;
  6735. spaceBefore = "";
  6736. }
  6737. if (commentBefore) {
  6738. (0, util_1.ensureObject)(node, "raws", "spaces", "attribute");
  6739. node.raws.spaces.attribute.before = spaceBefore;
  6740. commentBefore = "";
  6741. }
  6742. node.namespace = (node.namespace || "") + content;
  6743. var rawValue = (0, util_1.getProp)(node, "raws", "namespace") || null;
  6744. if (rawValue) {
  6745. node.raws.namespace += content;
  6746. }
  6747. lastAdded = "namespace";
  6748. }
  6749. spaceAfterMeaningfulToken = false;
  6750. break;
  6751. case tokens.dollar:
  6752. if (lastAdded === "value") {
  6753. var oldRawValue = (0, util_1.getProp)(node, "raws", "value");
  6754. node.value += "$";
  6755. if (oldRawValue) {
  6756. node.raws.value = oldRawValue + "$";
  6757. }
  6758. break;
  6759. }
  6760. // Falls through
  6761. case tokens.caret:
  6762. if (next[tokenize_1.FIELDS.TYPE] === tokens.equals) {
  6763. node.operator = content;
  6764. lastAdded = "operator";
  6765. }
  6766. spaceAfterMeaningfulToken = false;
  6767. break;
  6768. case tokens.combinator:
  6769. if (content === "~" && next[tokenize_1.FIELDS.TYPE] === tokens.equals) {
  6770. node.operator = content;
  6771. lastAdded = "operator";
  6772. }
  6773. if (content !== "|") {
  6774. spaceAfterMeaningfulToken = false;
  6775. break;
  6776. }
  6777. if (next[tokenize_1.FIELDS.TYPE] === tokens.equals) {
  6778. node.operator = content;
  6779. lastAdded = "operator";
  6780. }
  6781. else if (!node.namespace && !node.attribute) {
  6782. node.namespace = true;
  6783. }
  6784. spaceAfterMeaningfulToken = false;
  6785. break;
  6786. case tokens.word:
  6787. if (next &&
  6788. this.content(next) === "|" &&
  6789. attr[pos + 2] &&
  6790. attr[pos + 2][tokenize_1.FIELDS.TYPE] !== tokens.equals && // this look-ahead probably fails with comment nodes involved.
  6791. !node.operator &&
  6792. !node.namespace) {
  6793. node.namespace = content;
  6794. lastAdded = "namespace";
  6795. }
  6796. else if (!node.attribute || (lastAdded === "attribute" && !spaceAfterMeaningfulToken)) {
  6797. if (spaceBefore) {
  6798. (0, util_1.ensureObject)(node, "spaces", "attribute");
  6799. node.spaces.attribute.before = spaceBefore;
  6800. spaceBefore = "";
  6801. }
  6802. if (commentBefore) {
  6803. (0, util_1.ensureObject)(node, "raws", "spaces", "attribute");
  6804. node.raws.spaces.attribute.before = commentBefore;
  6805. commentBefore = "";
  6806. }
  6807. node.attribute = (node.attribute || "") + content;
  6808. var rawValue = (0, util_1.getProp)(node, "raws", "attribute") || null;
  6809. if (rawValue) {
  6810. node.raws.attribute += content;
  6811. }
  6812. lastAdded = "attribute";
  6813. }
  6814. else if ((!node.value && node.value !== "") ||
  6815. (lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark))) {
  6816. var unescaped_1 = (0, util_1.unesc)(content);
  6817. var oldRawValue = (0, util_1.getProp)(node, "raws", "value") || "";
  6818. var oldValue = node.value || "";
  6819. node.value = oldValue + unescaped_1;
  6820. node.quoteMark = null;
  6821. if (unescaped_1 !== content || oldRawValue) {
  6822. (0, util_1.ensureObject)(node, "raws");
  6823. node.raws.value = (oldRawValue || oldValue) + content;
  6824. }
  6825. lastAdded = "value";
  6826. }
  6827. else {
  6828. var insensitive = content === "i" || content === "I";
  6829. if ((node.value || node.value === "") &&
  6830. (node.quoteMark || spaceAfterMeaningfulToken)) {
  6831. node.insensitive = insensitive;
  6832. if (!insensitive || content === "I") {
  6833. (0, util_1.ensureObject)(node, "raws");
  6834. node.raws.insensitiveFlag = content;
  6835. }
  6836. lastAdded = "insensitive";
  6837. if (spaceBefore) {
  6838. (0, util_1.ensureObject)(node, "spaces", "insensitive");
  6839. node.spaces.insensitive.before = spaceBefore;
  6840. spaceBefore = "";
  6841. }
  6842. if (commentBefore) {
  6843. (0, util_1.ensureObject)(node, "raws", "spaces", "insensitive");
  6844. node.raws.spaces.insensitive.before = commentBefore;
  6845. commentBefore = "";
  6846. }
  6847. }
  6848. else if (node.value || node.value === "") {
  6849. lastAdded = "value";
  6850. node.value += content;
  6851. if (node.raws.value) {
  6852. node.raws.value += content;
  6853. }
  6854. }
  6855. }
  6856. spaceAfterMeaningfulToken = false;
  6857. break;
  6858. case tokens.str:
  6859. if (!node.attribute || !node.operator) {
  6860. return this.error("Expected an attribute followed by an operator preceding the string.", {
  6861. index: token[tokenize_1.FIELDS.START_POS],
  6862. });
  6863. }
  6864. var _a = (0, attribute_1.unescapeValue)(content), unescaped = _a.unescaped, quoteMark = _a.quoteMark;
  6865. node.value = unescaped;
  6866. node.quoteMark = quoteMark;
  6867. lastAdded = "value";
  6868. (0, util_1.ensureObject)(node, "raws");
  6869. node.raws.value = content;
  6870. spaceAfterMeaningfulToken = false;
  6871. break;
  6872. case tokens.equals:
  6873. if (!node.attribute) {
  6874. return this.expected("attribute", token[tokenize_1.FIELDS.START_POS], content);
  6875. }
  6876. if (node.value) {
  6877. return this.error('Unexpected "=" found; an operator was already defined.', {
  6878. index: token[tokenize_1.FIELDS.START_POS],
  6879. });
  6880. }
  6881. node.operator = node.operator ? node.operator + content : content;
  6882. lastAdded = "operator";
  6883. spaceAfterMeaningfulToken = false;
  6884. break;
  6885. case tokens.comment:
  6886. if (lastAdded) {
  6887. if (spaceAfterMeaningfulToken ||
  6888. (next && next[tokenize_1.FIELDS.TYPE] === tokens.space) ||
  6889. lastAdded === "insensitive") {
  6890. var lastComment = (0, util_1.getProp)(node, "spaces", lastAdded, "after") || "";
  6891. var rawLastComment = (0, util_1.getProp)(node, "raws", "spaces", lastAdded, "after") || lastComment;
  6892. (0, util_1.ensureObject)(node, "raws", "spaces", lastAdded);
  6893. node.raws.spaces[lastAdded].after = rawLastComment + content;
  6894. }
  6895. else {
  6896. var lastValue = node[lastAdded] || "";
  6897. var rawLastValue = (0, util_1.getProp)(node, "raws", lastAdded) || lastValue;
  6898. (0, util_1.ensureObject)(node, "raws");
  6899. node.raws[lastAdded] = rawLastValue + content;
  6900. }
  6901. }
  6902. else {
  6903. commentBefore = commentBefore + content;
  6904. }
  6905. break;
  6906. default:
  6907. return this.error("Unexpected \"".concat(content, "\" found."), { index: token[tokenize_1.FIELDS.START_POS] });
  6908. }
  6909. pos++;
  6910. }
  6911. unescapeProp(node, "attribute");
  6912. unescapeProp(node, "namespace");
  6913. this.newNode(new attribute_1.default(node));
  6914. this.position++;
  6915. };
  6916. /**
  6917. * return a node containing meaningless garbage up to (but not including) the specified token position.
  6918. * if the token position is negative, all remaining tokens are consumed.
  6919. *
  6920. * This returns an array containing a single string node if all whitespace,
  6921. * otherwise an array of comment nodes with space before and after.
  6922. *
  6923. * These tokens are not added to the current selector, the caller can add them or use them to amend
  6924. * a previous node's space metadata.
  6925. *
  6926. * In lossy mode, this returns only comments.
  6927. */
  6928. Parser.prototype.parseWhitespaceEquivalentTokens = function (stopPosition) {
  6929. if (stopPosition < 0) {
  6930. stopPosition = this.tokens.length;
  6931. }
  6932. var startPosition = this.position;
  6933. var nodes = [];
  6934. var space = "";
  6935. var lastComment = undefined;
  6936. do {
  6937. if (WHITESPACE_TOKENS[this.currToken[tokenize_1.FIELDS.TYPE]]) {
  6938. if (!this.options.lossy) {
  6939. space += this.content();
  6940. }
  6941. }
  6942. else if (this.currToken[tokenize_1.FIELDS.TYPE] === tokens.comment) {
  6943. var spaces = {};
  6944. if (space) {
  6945. spaces.before = space;
  6946. space = "";
  6947. }
  6948. lastComment = new comment_1.default({
  6949. value: this.content(),
  6950. source: getTokenSource(this.currToken),
  6951. sourceIndex: this.currToken[tokenize_1.FIELDS.START_POS],
  6952. spaces: spaces,
  6953. });
  6954. nodes.push(lastComment);
  6955. }
  6956. } while (++this.position < stopPosition);
  6957. if (space) {
  6958. if (lastComment) {
  6959. lastComment.spaces.after = space;
  6960. }
  6961. else if (!this.options.lossy) {
  6962. var firstToken = this.tokens[startPosition];
  6963. var lastToken = this.tokens[this.position - 1];
  6964. nodes.push(new string_1.default({
  6965. value: "",
  6966. 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]),
  6967. sourceIndex: firstToken[tokenize_1.FIELDS.START_POS],
  6968. spaces: { before: space, after: "" },
  6969. }));
  6970. }
  6971. }
  6972. return nodes;
  6973. };
  6974. /**
  6975. *
  6976. * @param {*} nodes
  6977. */
  6978. Parser.prototype.convertWhitespaceNodesToSpace = function (nodes, requiredSpace) {
  6979. var _this = this;
  6980. if (requiredSpace === void 0) { requiredSpace = false; }
  6981. var space = "";
  6982. var rawSpace = "";
  6983. nodes.forEach(function (n) {
  6984. var spaceBefore = _this.lossySpace(n.spaces.before, requiredSpace);
  6985. var rawSpaceBefore = _this.lossySpace(n.rawSpaceBefore, requiredSpace);
  6986. space +=
  6987. spaceBefore + _this.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  6988. rawSpace +=
  6989. spaceBefore +
  6990. n.value +
  6991. _this.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  6992. });
  6993. if (rawSpace === space) {
  6994. rawSpace = undefined;
  6995. }
  6996. var result = { space: space, rawSpace: rawSpace };
  6997. return result;
  6998. };
  6999. Parser.prototype.isNamedCombinator = function (position) {
  7000. if (position === void 0) { position = this.position; }
  7001. return (this.tokens[position + 0] &&
  7002. this.tokens[position + 0][tokenize_1.FIELDS.TYPE] === tokens.slash &&
  7003. this.tokens[position + 1] &&
  7004. this.tokens[position + 1][tokenize_1.FIELDS.TYPE] === tokens.word &&
  7005. this.tokens[position + 2] &&
  7006. this.tokens[position + 2][tokenize_1.FIELDS.TYPE] === tokens.slash);
  7007. };
  7008. Parser.prototype.namedCombinator = function () {
  7009. if (this.isNamedCombinator()) {
  7010. var nameRaw = this.content(this.tokens[this.position + 1]);
  7011. var name = (0, util_1.unesc)(nameRaw).toLowerCase();
  7012. var raws = {};
  7013. if (name !== nameRaw) {
  7014. raws.value = "/".concat(nameRaw, "/");
  7015. }
  7016. var node = new combinator_1.default({
  7017. value: "/".concat(name, "/"),
  7018. 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]),
  7019. sourceIndex: this.currToken[tokenize_1.FIELDS.START_POS],
  7020. raws: raws,
  7021. });
  7022. this.position = this.position + 3;
  7023. return node;
  7024. }
  7025. else {
  7026. this.unexpected();
  7027. }
  7028. };
  7029. Parser.prototype.combinator = function () {
  7030. var _this = this;
  7031. if (this.content() === "|") {
  7032. return this.namespace();
  7033. }
  7034. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  7035. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  7036. if (nextSigTokenPos < 0 ||
  7037. this.tokens[nextSigTokenPos][tokenize_1.FIELDS.TYPE] === tokens.comma ||
  7038. this.tokens[nextSigTokenPos][tokenize_1.FIELDS.TYPE] === tokens.closeParenthesis) {
  7039. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  7040. if (nodes.length > 0) {
  7041. var last = this.current.last;
  7042. if (last) {
  7043. var _a = this.convertWhitespaceNodesToSpace(nodes), space = _a.space, rawSpace = _a.rawSpace;
  7044. if (rawSpace !== undefined) {
  7045. last.rawSpaceAfter += rawSpace;
  7046. }
  7047. last.spaces.after += space;
  7048. }
  7049. else {
  7050. nodes.forEach(function (n) { return _this.newNode(n); });
  7051. }
  7052. }
  7053. return;
  7054. }
  7055. var firstToken = this.currToken;
  7056. var spaceOrDescendantSelectorNodes = undefined;
  7057. if (nextSigTokenPos > this.position) {
  7058. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  7059. }
  7060. var node;
  7061. if (this.isNamedCombinator()) {
  7062. node = this.namedCombinator();
  7063. }
  7064. else if (this.currToken[tokenize_1.FIELDS.TYPE] === tokens.combinator) {
  7065. node = new combinator_1.default({
  7066. value: this.content(),
  7067. source: getTokenSource(this.currToken),
  7068. sourceIndex: this.currToken[tokenize_1.FIELDS.START_POS],
  7069. });
  7070. this.position++;
  7071. }
  7072. else if (WHITESPACE_TOKENS[this.currToken[tokenize_1.FIELDS.TYPE]]) ;
  7073. else if (!spaceOrDescendantSelectorNodes) {
  7074. this.unexpected();
  7075. }
  7076. if (node) {
  7077. if (spaceOrDescendantSelectorNodes) {
  7078. var _b = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes), space = _b.space, rawSpace = _b.rawSpace;
  7079. node.spaces.before = space;
  7080. node.rawSpaceBefore = rawSpace;
  7081. }
  7082. }
  7083. else {
  7084. // descendant combinator
  7085. var _c = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true), space = _c.space, rawSpace = _c.rawSpace;
  7086. if (!rawSpace) {
  7087. rawSpace = space;
  7088. }
  7089. var spaces = {};
  7090. var raws = { spaces: {} };
  7091. if (space.endsWith(" ") && rawSpace.endsWith(" ")) {
  7092. spaces.before = space.slice(0, space.length - 1);
  7093. raws.spaces.before = rawSpace.slice(0, rawSpace.length - 1);
  7094. }
  7095. else if (space[0] === " " && rawSpace[0] === " ") {
  7096. spaces.after = space.slice(1);
  7097. raws.spaces.after = rawSpace.slice(1);
  7098. }
  7099. else {
  7100. raws.value = rawSpace;
  7101. }
  7102. node = new combinator_1.default({
  7103. value: " ",
  7104. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  7105. sourceIndex: firstToken[tokenize_1.FIELDS.START_POS],
  7106. spaces: spaces,
  7107. raws: raws,
  7108. });
  7109. }
  7110. if (this.currToken && this.currToken[tokenize_1.FIELDS.TYPE] === tokens.space) {
  7111. node.spaces.after = this.optionalSpace(this.content());
  7112. this.position++;
  7113. }
  7114. return this.newNode(node);
  7115. };
  7116. Parser.prototype.comma = function () {
  7117. if (this.position === this.tokens.length - 1) {
  7118. this.root.trailingComma = true;
  7119. this.position++;
  7120. return;
  7121. }
  7122. this.current._inferEndPosition();
  7123. var selector = new selector_1.default({
  7124. source: {
  7125. start: tokenStart(this.tokens[this.position + 1]),
  7126. },
  7127. sourceIndex: this.tokens[this.position + 1][tokenize_1.FIELDS.START_POS],
  7128. });
  7129. this.current.parent.append(selector);
  7130. this.current = selector;
  7131. this.position++;
  7132. };
  7133. Parser.prototype.comment = function () {
  7134. var current = this.currToken;
  7135. this.newNode(new comment_1.default({
  7136. value: this.content(),
  7137. source: getTokenSource(current),
  7138. sourceIndex: current[tokenize_1.FIELDS.START_POS],
  7139. }));
  7140. this.position++;
  7141. };
  7142. Parser.prototype.error = function (message, opts) {
  7143. throw this.root.error(message, opts);
  7144. };
  7145. Parser.prototype.missingBackslash = function () {
  7146. return this.error("Expected a backslash preceding the semicolon.", {
  7147. index: this.currToken[tokenize_1.FIELDS.START_POS],
  7148. });
  7149. };
  7150. Parser.prototype.missingParenthesis = function () {
  7151. return this.expected("opening parenthesis", this.currToken[tokenize_1.FIELDS.START_POS]);
  7152. };
  7153. Parser.prototype.missingSquareBracket = function () {
  7154. return this.expected("opening square bracket", this.currToken[tokenize_1.FIELDS.START_POS]);
  7155. };
  7156. Parser.prototype.unexpected = function () {
  7157. return this.error("Unexpected '".concat(this.content(), "'. Escaping special characters with \\ may help."), this.currToken[tokenize_1.FIELDS.START_POS]);
  7158. };
  7159. Parser.prototype.unexpectedPipe = function () {
  7160. return this.error("Unexpected '|'.", this.currToken[tokenize_1.FIELDS.START_POS]);
  7161. };
  7162. Parser.prototype.namespace = function () {
  7163. var before = (this.prevToken && this.content(this.prevToken)) || true;
  7164. if (this.nextToken[tokenize_1.FIELDS.TYPE] === tokens.word) {
  7165. this.position++;
  7166. return this.word(before);
  7167. }
  7168. else if (this.nextToken[tokenize_1.FIELDS.TYPE] === tokens.asterisk) {
  7169. this.position++;
  7170. return this.universal(before);
  7171. }
  7172. this.unexpectedPipe();
  7173. };
  7174. Parser.prototype.nesting = function () {
  7175. if (this.nextToken) {
  7176. var nextContent = this.content(this.nextToken);
  7177. if (nextContent === "|") {
  7178. this.position++;
  7179. return;
  7180. }
  7181. }
  7182. var current = this.currToken;
  7183. this.newNode(new nesting_1.default({
  7184. value: this.content(),
  7185. source: getTokenSource(current),
  7186. sourceIndex: current[tokenize_1.FIELDS.START_POS],
  7187. }));
  7188. this.position++;
  7189. };
  7190. Parser.prototype.parentheses = function () {
  7191. var last = this.current.last;
  7192. var unbalanced = 1;
  7193. this.position++;
  7194. if (last && last.type === types.PSEUDO) {
  7195. var selector = new selector_1.default({
  7196. source: { start: tokenStart(this.tokens[this.position]) },
  7197. sourceIndex: this.tokens[this.position][tokenize_1.FIELDS.START_POS],
  7198. });
  7199. var cache = this.current;
  7200. last.append(selector);
  7201. this.current = selector;
  7202. // Track nesting depth so deeply nested pseudo selectors raise a
  7203. // catchable error instead of overflowing the call stack. The
  7204. // counter is restored in `finally` so the parser is never left in
  7205. // an inconsistent state, even on the error path.
  7206. this.nestingDepth++;
  7207. try {
  7208. if (this.nestingDepth > this.maxNestingDepth) {
  7209. this.error("Cannot parse selector: nesting depth exceeds the maximum of ".concat(this.maxNestingDepth, "."), { index: this.currToken[tokenize_1.FIELDS.START_POS] });
  7210. }
  7211. while (this.position < this.tokens.length && unbalanced) {
  7212. if (this.currToken[tokenize_1.FIELDS.TYPE] === tokens.openParenthesis) {
  7213. unbalanced++;
  7214. }
  7215. if (this.currToken[tokenize_1.FIELDS.TYPE] === tokens.closeParenthesis) {
  7216. unbalanced--;
  7217. }
  7218. if (unbalanced) {
  7219. this.parse();
  7220. }
  7221. else {
  7222. this.current.source.end = tokenEnd(this.currToken);
  7223. this.current.parent.source.end = tokenEnd(this.currToken);
  7224. this.position++;
  7225. }
  7226. }
  7227. }
  7228. finally {
  7229. this.nestingDepth--;
  7230. }
  7231. this.current = cache;
  7232. }
  7233. else {
  7234. // I think this case should be an error. It's used to implement a basic parse of media queries
  7235. // but I don't think it's a good idea.
  7236. var parenStart = this.currToken;
  7237. var parenValue = "(";
  7238. var parenEnd = void 0;
  7239. while (this.position < this.tokens.length && unbalanced) {
  7240. if (this.currToken[tokenize_1.FIELDS.TYPE] === tokens.openParenthesis) {
  7241. unbalanced++;
  7242. }
  7243. if (this.currToken[tokenize_1.FIELDS.TYPE] === tokens.closeParenthesis) {
  7244. unbalanced--;
  7245. }
  7246. parenEnd = this.currToken;
  7247. parenValue += this.parseParenthesisToken(this.currToken);
  7248. this.position++;
  7249. }
  7250. if (last) {
  7251. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  7252. }
  7253. else {
  7254. this.newNode(new string_1.default({
  7255. value: parenValue,
  7256. 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]),
  7257. sourceIndex: parenStart[tokenize_1.FIELDS.START_POS],
  7258. }));
  7259. }
  7260. }
  7261. if (unbalanced) {
  7262. return this.expected("closing parenthesis", this.currToken[tokenize_1.FIELDS.START_POS]);
  7263. }
  7264. };
  7265. Parser.prototype.pseudo = function () {
  7266. var _this = this;
  7267. var pseudoStr = "";
  7268. var startingToken = this.currToken;
  7269. while (this.currToken && this.currToken[tokenize_1.FIELDS.TYPE] === tokens.colon) {
  7270. pseudoStr += this.content();
  7271. this.position++;
  7272. }
  7273. if (!this.currToken) {
  7274. return this.expected(["pseudo-class", "pseudo-element"], this.position - 1);
  7275. }
  7276. if (this.currToken[tokenize_1.FIELDS.TYPE] === tokens.word) {
  7277. this.splitWord(false, function (first, length) {
  7278. pseudoStr += first;
  7279. _this.newNode(new pseudo_1.default({
  7280. value: pseudoStr,
  7281. source: getTokenSourceSpan(startingToken, _this.currToken),
  7282. sourceIndex: startingToken[tokenize_1.FIELDS.START_POS],
  7283. }));
  7284. if (length > 1 && _this.nextToken && _this.nextToken[tokenize_1.FIELDS.TYPE] === tokens.openParenthesis) {
  7285. _this.error("Misplaced parenthesis.", {
  7286. index: _this.nextToken[tokenize_1.FIELDS.START_POS],
  7287. });
  7288. }
  7289. });
  7290. }
  7291. else {
  7292. return this.expected(["pseudo-class", "pseudo-element"], this.currToken[tokenize_1.FIELDS.START_POS]);
  7293. }
  7294. };
  7295. Parser.prototype.space = function () {
  7296. var content = this.content();
  7297. // Handle space before and after the selector
  7298. if (this.position === 0 ||
  7299. this.prevToken[tokenize_1.FIELDS.TYPE] === tokens.comma ||
  7300. this.prevToken[tokenize_1.FIELDS.TYPE] === tokens.openParenthesis ||
  7301. this.current.nodes.every(function (node) { return node.type === "comment"; })) {
  7302. this.spaces = this.optionalSpace(content);
  7303. this.position++;
  7304. }
  7305. else if (this.position === this.tokens.length - 1 ||
  7306. this.nextToken[tokenize_1.FIELDS.TYPE] === tokens.comma ||
  7307. this.nextToken[tokenize_1.FIELDS.TYPE] === tokens.closeParenthesis) {
  7308. this.current.last.spaces.after = this.optionalSpace(content);
  7309. this.position++;
  7310. }
  7311. else {
  7312. this.combinator();
  7313. }
  7314. };
  7315. Parser.prototype.string = function () {
  7316. var current = this.currToken;
  7317. this.newNode(new string_1.default({
  7318. value: this.content(),
  7319. source: getTokenSource(current),
  7320. sourceIndex: current[tokenize_1.FIELDS.START_POS],
  7321. }));
  7322. this.position++;
  7323. };
  7324. Parser.prototype.universal = function (namespace) {
  7325. var nextToken = this.nextToken;
  7326. if (nextToken && this.content(nextToken) === "|") {
  7327. this.position++;
  7328. return this.namespace();
  7329. }
  7330. var current = this.currToken;
  7331. this.newNode(new universal_1.default({
  7332. value: this.content(),
  7333. source: getTokenSource(current),
  7334. sourceIndex: current[tokenize_1.FIELDS.START_POS],
  7335. }), namespace);
  7336. this.position++;
  7337. };
  7338. Parser.prototype.splitWord = function (namespace, firstCallback) {
  7339. var _this = this;
  7340. var nextToken = this.nextToken;
  7341. var word = this.content();
  7342. while (nextToken &&
  7343. ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[tokenize_1.FIELDS.TYPE])) {
  7344. this.position++;
  7345. var current = this.content();
  7346. word += current;
  7347. if (current.lastIndexOf("\\") === current.length - 1) {
  7348. var next = this.nextToken;
  7349. if (next && next[tokenize_1.FIELDS.TYPE] === tokens.space) {
  7350. word += this.requiredSpace(this.content(next));
  7351. this.position++;
  7352. }
  7353. }
  7354. nextToken = this.nextToken;
  7355. }
  7356. var hasClass = indexesOf(word, ".").filter(function (i) {
  7357. // Allow escaped dot within class name
  7358. var escapedDot = word[i - 1] === "\\";
  7359. // Allow decimal numbers percent in @keyframes
  7360. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  7361. return !escapedDot && !isKeyframesPercent;
  7362. });
  7363. var hasId = indexesOf(word, "#").filter(function (i) { return word[i - 1] !== "\\"; });
  7364. // Eliminate Sass interpolations from the list of id indexes
  7365. var interpolations = indexesOf(word, "#{");
  7366. if (interpolations.length) {
  7367. hasId = hasId.filter(function (hashIndex) { return !~interpolations.indexOf(hashIndex); });
  7368. }
  7369. var indices = (0, sortAscending_1.default)(uniqs(__spreadArray(__spreadArray([0], __read(hasClass), false), __read(hasId), false)));
  7370. indices.forEach(function (ind, i) {
  7371. var index = indices[i + 1] || word.length;
  7372. var value = word.slice(ind, index);
  7373. if (i === 0 && firstCallback) {
  7374. return firstCallback.call(_this, value, indices.length);
  7375. }
  7376. var node;
  7377. var current = _this.currToken;
  7378. var sourceIndex = current[tokenize_1.FIELDS.START_POS] + indices[i];
  7379. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  7380. if (~hasClass.indexOf(ind)) {
  7381. var classNameOpts = {
  7382. value: value.slice(1),
  7383. source: source,
  7384. sourceIndex: sourceIndex,
  7385. };
  7386. node = new className_1.default(unescapeProp(classNameOpts, "value"));
  7387. }
  7388. else if (~hasId.indexOf(ind)) {
  7389. var idOpts = {
  7390. value: value.slice(1),
  7391. source: source,
  7392. sourceIndex: sourceIndex,
  7393. };
  7394. node = new id_1.default(unescapeProp(idOpts, "value"));
  7395. }
  7396. else {
  7397. var tagOpts = {
  7398. value: value,
  7399. source: source,
  7400. sourceIndex: sourceIndex,
  7401. };
  7402. unescapeProp(tagOpts, "value");
  7403. node = new tag_1.default(tagOpts);
  7404. }
  7405. _this.newNode(node, namespace);
  7406. // Ensure that the namespace is used only once
  7407. namespace = null;
  7408. });
  7409. this.position++;
  7410. };
  7411. Parser.prototype.word = function (namespace) {
  7412. var nextToken = this.nextToken;
  7413. if (nextToken && this.content(nextToken) === "|") {
  7414. this.position++;
  7415. return this.namespace();
  7416. }
  7417. return this.splitWord(namespace);
  7418. };
  7419. Parser.prototype.loop = function () {
  7420. while (this.position < this.tokens.length) {
  7421. this.parse(true);
  7422. }
  7423. this.current._inferEndPosition();
  7424. return this.root;
  7425. };
  7426. Parser.prototype.parse = function (throwOnParenthesis) {
  7427. switch (this.currToken[tokenize_1.FIELDS.TYPE]) {
  7428. case tokens.space:
  7429. this.space();
  7430. break;
  7431. case tokens.comment:
  7432. this.comment();
  7433. break;
  7434. case tokens.openParenthesis:
  7435. this.parentheses();
  7436. break;
  7437. case tokens.closeParenthesis:
  7438. if (throwOnParenthesis) {
  7439. this.missingParenthesis();
  7440. }
  7441. break;
  7442. case tokens.openSquare:
  7443. this.attribute();
  7444. break;
  7445. case tokens.dollar:
  7446. case tokens.caret:
  7447. case tokens.equals:
  7448. case tokens.word:
  7449. this.word();
  7450. break;
  7451. case tokens.colon:
  7452. this.pseudo();
  7453. break;
  7454. case tokens.comma:
  7455. this.comma();
  7456. break;
  7457. case tokens.asterisk:
  7458. this.universal();
  7459. break;
  7460. case tokens.ampersand:
  7461. this.nesting();
  7462. break;
  7463. case tokens.slash:
  7464. case tokens.combinator:
  7465. this.combinator();
  7466. break;
  7467. case tokens.str:
  7468. this.string();
  7469. break;
  7470. // These cases throw; no break needed.
  7471. case tokens.closeSquare:
  7472. this.missingSquareBracket();
  7473. case tokens.semicolon:
  7474. this.missingBackslash();
  7475. default:
  7476. this.unexpected();
  7477. }
  7478. };
  7479. /**
  7480. * Helpers
  7481. */
  7482. Parser.prototype.expected = function (description, index, found) {
  7483. if (Array.isArray(description)) {
  7484. var last = description.pop();
  7485. description = "".concat(description.join(", "), " or ").concat(last);
  7486. }
  7487. var an = /^[aeiou]/.test(description[0]) ? "an" : "a";
  7488. if (!found) {
  7489. return this.error("Expected ".concat(an, " ").concat(description, "."), { index: index });
  7490. }
  7491. return this.error("Expected ".concat(an, " ").concat(description, ", found \"").concat(found, "\" instead."), { index: index });
  7492. };
  7493. Parser.prototype.requiredSpace = function (space) {
  7494. return this.options.lossy ? " " : space;
  7495. };
  7496. Parser.prototype.optionalSpace = function (space) {
  7497. return this.options.lossy ? "" : space;
  7498. };
  7499. Parser.prototype.lossySpace = function (space, required) {
  7500. if (this.options.lossy) {
  7501. return required ? " " : "";
  7502. }
  7503. else {
  7504. return space;
  7505. }
  7506. };
  7507. Parser.prototype.parseParenthesisToken = function (token) {
  7508. var content = this.content(token);
  7509. if (token[tokenize_1.FIELDS.TYPE] === tokens.space) {
  7510. return this.requiredSpace(content);
  7511. }
  7512. else {
  7513. return content;
  7514. }
  7515. };
  7516. Parser.prototype.newNode = function (node, namespace) {
  7517. if (namespace) {
  7518. if (/^ +$/.test(namespace)) {
  7519. if (!this.options.lossy) {
  7520. this.spaces = (this.spaces || "") + namespace;
  7521. }
  7522. namespace = true;
  7523. }
  7524. node.namespace = namespace;
  7525. unescapeProp(node, "namespace");
  7526. }
  7527. if (this.spaces) {
  7528. node.spaces.before = this.spaces;
  7529. this.spaces = "";
  7530. }
  7531. return this.current.append(node);
  7532. };
  7533. Parser.prototype.content = function (token) {
  7534. if (token === void 0) { token = this.currToken; }
  7535. return this.css.slice(token[tokenize_1.FIELDS.START_POS], token[tokenize_1.FIELDS.END_POS]);
  7536. };
  7537. Object.defineProperty(Parser.prototype, "currToken", {
  7538. get: function () {
  7539. return this.tokens[this.position];
  7540. },
  7541. enumerable: false,
  7542. configurable: true
  7543. });
  7544. Object.defineProperty(Parser.prototype, "nextToken", {
  7545. get: function () {
  7546. return this.tokens[this.position + 1];
  7547. },
  7548. enumerable: false,
  7549. configurable: true
  7550. });
  7551. Object.defineProperty(Parser.prototype, "prevToken", {
  7552. get: function () {
  7553. return this.tokens[this.position - 1];
  7554. },
  7555. enumerable: false,
  7556. configurable: true
  7557. });
  7558. /**
  7559. * returns the index of the next non-whitespace, non-comment token.
  7560. * returns -1 if no meaningful token is found.
  7561. */
  7562. Parser.prototype.locateNextMeaningfulToken = function (startPosition) {
  7563. if (startPosition === void 0) { startPosition = this.position + 1; }
  7564. var searchPosition = startPosition;
  7565. while (searchPosition < this.tokens.length) {
  7566. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][tokenize_1.FIELDS.TYPE]]) {
  7567. searchPosition++;
  7568. continue;
  7569. }
  7570. else {
  7571. return searchPosition;
  7572. }
  7573. }
  7574. return -1;
  7575. };
  7576. return Parser;
  7577. }());
  7578. parser$1.default = Parser;
  7579. return parser$1;
  7580. }
  7581. var hasRequiredProcessor$1;
  7582. function requireProcessor$1 () {
  7583. if (hasRequiredProcessor$1) return processor$1;
  7584. hasRequiredProcessor$1 = 1;
  7585. var __importDefault = (processor$1 && processor$1.__importDefault) || function (mod) {
  7586. return (mod && mod.__esModule) ? mod : { "default": mod };
  7587. };
  7588. Object.defineProperty(processor$1, "__esModule", { value: true });
  7589. var parser_1 = __importDefault(/*@__PURE__*/ requireParser$2());
  7590. var Processor = /** @class */ (function () {
  7591. function Processor(func, options) {
  7592. this.func = func || function noop() { };
  7593. this.funcRes = null;
  7594. this.options = options;
  7595. }
  7596. Processor.prototype._shouldUpdateSelector = function (rule, options) {
  7597. if (options === void 0) { options = {}; }
  7598. var merged = Object.assign({}, this.options, options);
  7599. if (merged.updateSelector === false) {
  7600. return false;
  7601. }
  7602. else {
  7603. return typeof rule !== "string";
  7604. }
  7605. };
  7606. Processor.prototype._isLossy = function (options) {
  7607. if (options === void 0) { options = {}; }
  7608. var merged = Object.assign({}, this.options, options);
  7609. if (merged.lossless === false) {
  7610. return true;
  7611. }
  7612. else {
  7613. return false;
  7614. }
  7615. };
  7616. Processor.prototype._root = function (rule, options) {
  7617. if (options === void 0) { options = {}; }
  7618. var parser = new parser_1.default(rule, this._parseOptions(options));
  7619. return parser.root;
  7620. };
  7621. Processor.prototype._parseOptions = function (options) {
  7622. var merged = Object.assign({}, this.options, options);
  7623. return {
  7624. lossy: this._isLossy(merged),
  7625. maxNestingDepth: merged.maxNestingDepth,
  7626. };
  7627. };
  7628. Processor.prototype._stringifyOptions = function (options) {
  7629. var merged = Object.assign({}, this.options, options);
  7630. return {
  7631. maxNestingDepth: merged.maxNestingDepth,
  7632. };
  7633. };
  7634. Processor.prototype._run = function (rule, options) {
  7635. var _this = this;
  7636. if (options === void 0) { options = {}; }
  7637. return new Promise(function (resolve, reject) {
  7638. try {
  7639. var root_1 = _this._root(rule, options);
  7640. Promise.resolve(_this.func(root_1))
  7641. .then(function (transform) {
  7642. var string = undefined;
  7643. if (_this._shouldUpdateSelector(rule, options)) {
  7644. string = root_1.toString(_this._stringifyOptions(options));
  7645. rule.selector = string;
  7646. }
  7647. return { transform: transform, root: root_1, string: string };
  7648. })
  7649. .then(resolve, reject);
  7650. }
  7651. catch (e) {
  7652. reject(e);
  7653. return;
  7654. }
  7655. });
  7656. };
  7657. Processor.prototype._runSync = function (rule, options) {
  7658. if (options === void 0) { options = {}; }
  7659. var root = this._root(rule, options);
  7660. var transform = this.func(root);
  7661. if (transform && typeof transform.then === "function") {
  7662. throw new Error("Selector processor returned a promise to a synchronous call.");
  7663. }
  7664. var string = undefined;
  7665. if (options.updateSelector && typeof rule !== "string") {
  7666. string = root.toString(this._stringifyOptions(options));
  7667. rule.selector = string;
  7668. }
  7669. return { transform: transform, root: root, string: string };
  7670. };
  7671. /**
  7672. * Process rule into a selector AST.
  7673. *
  7674. * @param rule {postcss.Rule | string} The css selector to be processed
  7675. * @param options The options for processing
  7676. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  7677. */
  7678. Processor.prototype.ast = function (rule, options) {
  7679. return this._run(rule, options).then(function (result) { return result.root; });
  7680. };
  7681. /**
  7682. * Process rule into a selector AST synchronously.
  7683. *
  7684. * @param rule {postcss.Rule | string} The css selector to be processed
  7685. * @param options The options for processing
  7686. * @returns {parser.Root} The AST of the selector after processing it.
  7687. */
  7688. Processor.prototype.astSync = function (rule, options) {
  7689. return this._runSync(rule, options).root;
  7690. };
  7691. /**
  7692. * Process a selector into a transformed value asynchronously
  7693. *
  7694. * @param rule {postcss.Rule | string} The css selector to be processed
  7695. * @param options The options for processing
  7696. * @returns {Promise<any>} The value returned by the processor.
  7697. */
  7698. Processor.prototype.transform = function (rule, options) {
  7699. return this._run(rule, options).then(function (result) { return result.transform; });
  7700. };
  7701. /**
  7702. * Process a selector into a transformed value synchronously.
  7703. *
  7704. * @param rule {postcss.Rule | string} The css selector to be processed
  7705. * @param options The options for processing
  7706. * @returns {any} The value returned by the processor.
  7707. */
  7708. Processor.prototype.transformSync = function (rule, options) {
  7709. return this._runSync(rule, options).transform;
  7710. };
  7711. /**
  7712. * Process a selector into a new selector string asynchronously.
  7713. *
  7714. * @param rule {postcss.Rule | string} The css selector to be processed
  7715. * @param options The options for processing
  7716. * @returns {string} the selector after processing.
  7717. */
  7718. Processor.prototype.process = function (rule, options) {
  7719. var _this = this;
  7720. return this._run(rule, options).then(function (result) { return result.string || result.root.toString(_this._stringifyOptions(options)); });
  7721. };
  7722. /**
  7723. * Process a selector into a new selector string synchronously.
  7724. *
  7725. * @param rule {postcss.Rule | string} The css selector to be processed
  7726. * @param options The options for processing
  7727. * @returns {string} the selector after processing.
  7728. */
  7729. Processor.prototype.processSync = function (rule, options) {
  7730. var result = this._runSync(rule, options);
  7731. return result.string || result.root.toString(this._stringifyOptions(options));
  7732. };
  7733. return Processor;
  7734. }());
  7735. processor$1.default = Processor;
  7736. return processor$1;
  7737. }
  7738. var selectors$1 = {};
  7739. var constructors$1 = {};
  7740. var hasRequiredConstructors$1;
  7741. function requireConstructors$1 () {
  7742. if (hasRequiredConstructors$1) return constructors$1;
  7743. hasRequiredConstructors$1 = 1;
  7744. var __importDefault = (constructors$1 && constructors$1.__importDefault) || function (mod) {
  7745. return (mod && mod.__esModule) ? mod : { "default": mod };
  7746. };
  7747. Object.defineProperty(constructors$1, "__esModule", { value: true });
  7748. constructors$1.universal = constructors$1.tag = constructors$1.string = constructors$1.selector = constructors$1.root = constructors$1.pseudo = constructors$1.nesting = constructors$1.id = constructors$1.comment = constructors$1.combinator = constructors$1.className = constructors$1.attribute = void 0;
  7749. var attribute_1 = __importDefault(/*@__PURE__*/ requireAttribute$1());
  7750. var className_1 = __importDefault(/*@__PURE__*/ requireClassName$1());
  7751. var combinator_1 = __importDefault(/*@__PURE__*/ requireCombinator$1());
  7752. var comment_1 = __importDefault(/*@__PURE__*/ requireComment$1());
  7753. var id_1 = __importDefault(/*@__PURE__*/ requireId$1());
  7754. var nesting_1 = __importDefault(/*@__PURE__*/ requireNesting$1());
  7755. var pseudo_1 = __importDefault(/*@__PURE__*/ requirePseudo$1());
  7756. var root_1 = __importDefault(/*@__PURE__*/ requireRoot$1());
  7757. var selector_1 = __importDefault(/*@__PURE__*/ requireSelector$1());
  7758. var string_1 = __importDefault(/*@__PURE__*/ requireString$1());
  7759. var tag_1 = __importDefault(/*@__PURE__*/ requireTag$1());
  7760. var universal_1 = __importDefault(/*@__PURE__*/ requireUniversal$1());
  7761. var attribute = function (opts) { return new attribute_1.default(opts); };
  7762. constructors$1.attribute = attribute;
  7763. var className = function (opts) { return new className_1.default(opts); };
  7764. constructors$1.className = className;
  7765. var combinator = function (opts) { return new combinator_1.default(opts); };
  7766. constructors$1.combinator = combinator;
  7767. var comment = function (opts) { return new comment_1.default(opts); };
  7768. constructors$1.comment = comment;
  7769. var id = function (opts) { return new id_1.default(opts); };
  7770. constructors$1.id = id;
  7771. var nesting = function (opts) { return new nesting_1.default(opts); };
  7772. constructors$1.nesting = nesting;
  7773. var pseudo = function (opts) { return new pseudo_1.default(opts); };
  7774. constructors$1.pseudo = pseudo;
  7775. var root = function (opts) { return new root_1.default(opts); };
  7776. constructors$1.root = root;
  7777. var selector = function (opts) { return new selector_1.default(opts); };
  7778. constructors$1.selector = selector;
  7779. var string = function (opts) { return new string_1.default(opts); };
  7780. constructors$1.string = string;
  7781. var tag = function (opts) { return new tag_1.default(opts); };
  7782. constructors$1.tag = tag;
  7783. var universal = function (opts) { return new universal_1.default(opts); };
  7784. constructors$1.universal = universal;
  7785. return constructors$1;
  7786. }
  7787. var guards$1 = {};
  7788. var hasRequiredGuards$1;
  7789. function requireGuards$1 () {
  7790. if (hasRequiredGuards$1) return guards$1;
  7791. hasRequiredGuards$1 = 1;
  7792. (function (exports) {
  7793. var _a;
  7794. Object.defineProperty(exports, "__esModule", { value: true });
  7795. 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;
  7796. exports.isNode = isNode;
  7797. exports.isPseudoElement = isPseudoElement;
  7798. exports.isPseudoClass = isPseudoClass;
  7799. exports.isContainer = isContainer;
  7800. exports.isNamespace = isNamespace;
  7801. var types_1 = /*@__PURE__*/ requireTypes$1();
  7802. var IS_TYPE = (_a = {},
  7803. _a[types_1.ATTRIBUTE] = true,
  7804. _a[types_1.CLASS] = true,
  7805. _a[types_1.COMBINATOR] = true,
  7806. _a[types_1.COMMENT] = true,
  7807. _a[types_1.ID] = true,
  7808. _a[types_1.NESTING] = true,
  7809. _a[types_1.PSEUDO] = true,
  7810. _a[types_1.ROOT] = true,
  7811. _a[types_1.SELECTOR] = true,
  7812. _a[types_1.STRING] = true,
  7813. _a[types_1.TAG] = true,
  7814. _a[types_1.UNIVERSAL] = true,
  7815. _a);
  7816. function isNode(node) {
  7817. return typeof node === "object" && IS_TYPE[node.type];
  7818. }
  7819. function isNodeType(type, node) {
  7820. return isNode(node) && node.type === type;
  7821. }
  7822. exports.isAttribute = isNodeType.bind(null, types_1.ATTRIBUTE);
  7823. exports.isClassName = isNodeType.bind(null, types_1.CLASS);
  7824. exports.isCombinator = isNodeType.bind(null, types_1.COMBINATOR);
  7825. exports.isComment = isNodeType.bind(null, types_1.COMMENT);
  7826. exports.isIdentifier = isNodeType.bind(null, types_1.ID);
  7827. exports.isNesting = isNodeType.bind(null, types_1.NESTING);
  7828. exports.isPseudo = isNodeType.bind(null, types_1.PSEUDO);
  7829. exports.isRoot = isNodeType.bind(null, types_1.ROOT);
  7830. exports.isSelector = isNodeType.bind(null, types_1.SELECTOR);
  7831. exports.isString = isNodeType.bind(null, types_1.STRING);
  7832. exports.isTag = isNodeType.bind(null, types_1.TAG);
  7833. exports.isUniversal = isNodeType.bind(null, types_1.UNIVERSAL);
  7834. function isPseudoElement(node) {
  7835. return ((0, exports.isPseudo)(node) &&
  7836. node.value &&
  7837. (node.value.startsWith("::") ||
  7838. node.value.toLowerCase() === ":before" ||
  7839. node.value.toLowerCase() === ":after" ||
  7840. node.value.toLowerCase() === ":first-letter" ||
  7841. node.value.toLowerCase() === ":first-line"));
  7842. }
  7843. function isPseudoClass(node) {
  7844. return (0, exports.isPseudo)(node) && !isPseudoElement(node);
  7845. }
  7846. function isContainer(node) {
  7847. return !!(isNode(node) && node.walk);
  7848. }
  7849. function isNamespace(node) {
  7850. return (0, exports.isAttribute)(node) || (0, exports.isTag)(node);
  7851. }
  7852. } (guards$1));
  7853. return guards$1;
  7854. }
  7855. var hasRequiredSelectors$1;
  7856. function requireSelectors$1 () {
  7857. if (hasRequiredSelectors$1) return selectors$1;
  7858. hasRequiredSelectors$1 = 1;
  7859. (function (exports) {
  7860. var __createBinding = (selectors$1 && selectors$1.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  7861. if (k2 === undefined) k2 = k;
  7862. var desc = Object.getOwnPropertyDescriptor(m, k);
  7863. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  7864. desc = { enumerable: true, get: function() { return m[k]; } };
  7865. }
  7866. Object.defineProperty(o, k2, desc);
  7867. }) : (function(o, m, k, k2) {
  7868. if (k2 === undefined) k2 = k;
  7869. o[k2] = m[k];
  7870. }));
  7871. var __exportStar = (selectors$1 && selectors$1.__exportStar) || function(m, exports) {
  7872. for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
  7873. };
  7874. Object.defineProperty(exports, "__esModule", { value: true });
  7875. __exportStar(/*@__PURE__*/ requireTypes$1(), exports);
  7876. __exportStar(/*@__PURE__*/ requireConstructors$1(), exports);
  7877. __exportStar(/*@__PURE__*/ requireGuards$1(), exports);
  7878. } (selectors$1));
  7879. return selectors$1;
  7880. }
  7881. var dist$1;
  7882. var hasRequiredDist$1;
  7883. function requireDist$1 () {
  7884. if (hasRequiredDist$1) return dist$1;
  7885. hasRequiredDist$1 = 1;
  7886. var __createBinding = (dist$1 && dist$1.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  7887. if (k2 === undefined) k2 = k;
  7888. var desc = Object.getOwnPropertyDescriptor(m, k);
  7889. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  7890. desc = { enumerable: true, get: function() { return m[k]; } };
  7891. }
  7892. Object.defineProperty(o, k2, desc);
  7893. }) : (function(o, m, k, k2) {
  7894. if (k2 === undefined) k2 = k;
  7895. o[k2] = m[k];
  7896. }));
  7897. var __setModuleDefault = (dist$1 && dist$1.__setModuleDefault) || (Object.create ? (function(o, v) {
  7898. Object.defineProperty(o, "default", { enumerable: true, value: v });
  7899. }) : function(o, v) {
  7900. o["default"] = v;
  7901. });
  7902. var __importStar = (dist$1 && dist$1.__importStar) || (function () {
  7903. var ownKeys = function(o) {
  7904. ownKeys = Object.getOwnPropertyNames || function (o) {
  7905. var ar = [];
  7906. for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
  7907. return ar;
  7908. };
  7909. return ownKeys(o);
  7910. };
  7911. return function (mod) {
  7912. if (mod && mod.__esModule) return mod;
  7913. var result = {};
  7914. if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
  7915. __setModuleDefault(result, mod);
  7916. return result;
  7917. };
  7918. })();
  7919. var __importDefault = (dist$1 && dist$1.__importDefault) || function (mod) {
  7920. return (mod && mod.__esModule) ? mod : { "default": mod };
  7921. };
  7922. var processor_1 = __importDefault(/*@__PURE__*/ requireProcessor$1());
  7923. var selectors = __importStar(/*@__PURE__*/ requireSelectors$1());
  7924. var parser = function (processor) { return new processor_1.default(processor); };
  7925. Object.assign(parser, selectors);
  7926. delete parser.__esModule;
  7927. dist$1 = parser;
  7928. return dist$1;
  7929. }
  7930. var distExports = /*@__PURE__*/ requireDist$1();
  7931. var selectorParser = /*@__PURE__*/getDefaultExportFromCjs(distExports);
  7932. const animationNameRE = /^(?:-\w+-)?animation-name$/;
  7933. const animationRE = /^(?:-\w+-)?animation$/;
  7934. const keyframesRE = /^(?:-\w+-)?keyframes$/;
  7935. const scopedPlugin = (id = "") => {
  7936. const keyframes = /* @__PURE__ */ Object.create(null);
  7937. const shortId = id.replace(/^data-v-/, "");
  7938. return {
  7939. postcssPlugin: "vue-sfc-scoped",
  7940. Rule(rule) {
  7941. processRule(id, rule);
  7942. },
  7943. AtRule(node) {
  7944. if (keyframesRE.test(node.name) && !node.params.endsWith(`-${shortId}`)) {
  7945. keyframes[node.params] = node.params = node.params + "-" + shortId;
  7946. }
  7947. },
  7948. OnceExit(root) {
  7949. if (Object.keys(keyframes).length) {
  7950. root.walkDecls((decl) => {
  7951. if (animationNameRE.test(decl.prop)) {
  7952. decl.value = decl.value.split(",").map((v) => keyframes[v.trim()] || v.trim()).join(",");
  7953. }
  7954. if (animationRE.test(decl.prop)) {
  7955. decl.value = decl.value.split(",").map((v) => {
  7956. const vals = v.trim().split(/\s+/);
  7957. const i = vals.findIndex((val) => keyframes[val]);
  7958. if (i !== -1) {
  7959. vals.splice(i, 1, keyframes[vals[i]]);
  7960. return vals.join(" ");
  7961. } else {
  7962. return v;
  7963. }
  7964. }).join(",");
  7965. }
  7966. });
  7967. }
  7968. }
  7969. };
  7970. };
  7971. const processedRules = /* @__PURE__ */ new WeakSet();
  7972. function processRule(id, rule) {
  7973. if (processedRules.has(rule) || rule.parent && rule.parent.type === "atrule" && keyframesRE.test(rule.parent.name)) {
  7974. return;
  7975. }
  7976. processedRules.add(rule);
  7977. let deep = false;
  7978. let parent = rule.parent;
  7979. while (parent && parent.type !== "root") {
  7980. if (parent.__deep) {
  7981. deep = true;
  7982. break;
  7983. }
  7984. parent = parent.parent;
  7985. }
  7986. rule.selector = selectorParser((selectorRoot) => {
  7987. selectorRoot.each((selector) => {
  7988. rewriteSelector(id, rule, selector, selectorRoot, deep);
  7989. });
  7990. }).processSync(rule.selector);
  7991. }
  7992. function rewriteSelector(id, rule, selector, selectorRoot, deep, slotted = false) {
  7993. let node = null;
  7994. let shouldInject = !deep;
  7995. let hasNestedDeep = false;
  7996. let splitForNestedDeep = false;
  7997. selector.each((n) => {
  7998. if (n.type === "combinator" && (n.value === ">>>" || n.value === "/deep/")) {
  7999. n.value = " ";
  8000. n.spaces.before = n.spaces.after = "";
  8001. warn(
  8002. `the >>> and /deep/ combinators have been deprecated. Use :deep() instead.`
  8003. );
  8004. return false;
  8005. }
  8006. if (n.type === "pseudo") {
  8007. const { value } = n;
  8008. if (isDeepContainerPseudo(n)) {
  8009. const hasDeepSelectors = n.nodes.some(
  8010. (selector2) => selector2.some(isDeepSelector)
  8011. );
  8012. if (hasDeepSelectors) {
  8013. const hasScopeAnchor = !!node;
  8014. const hasMixedSelectors = n.nodes.some(
  8015. (selector2) => !selector2.some(isDeepSelector)
  8016. );
  8017. const hasTrailingNodes = selector.index(n) < selector.length - 1;
  8018. if (canSplitDeepContainerPseudo(n) && !deep && !hasScopeAnchor && hasMixedSelectors && hasTrailingNodes) {
  8019. splitSelectorForNestedDeep(
  8020. id,
  8021. rule,
  8022. selector,
  8023. selectorRoot,
  8024. n,
  8025. deep,
  8026. slotted
  8027. );
  8028. splitForNestedDeep = true;
  8029. return false;
  8030. }
  8031. if (value === ":not" && !deep && !hasScopeAnchor && hasMixedSelectors && hasTrailingNodes) {
  8032. return;
  8033. }
  8034. n.nodes.forEach(
  8035. (selector2) => rewriteSelector(
  8036. id,
  8037. rule,
  8038. selector2,
  8039. selectorRoot,
  8040. deep || hasScopeAnchor,
  8041. slotted
  8042. )
  8043. );
  8044. if (!hasScopeAnchor) {
  8045. node = n;
  8046. shouldInject = false;
  8047. }
  8048. hasNestedDeep = true;
  8049. }
  8050. }
  8051. if (value === ":deep" || value === "::v-deep") {
  8052. rule.__deep = true;
  8053. if (n.nodes.length) {
  8054. let last = n;
  8055. n.nodes[0].each((ss) => {
  8056. selector.insertAfter(last, ss);
  8057. last = ss;
  8058. });
  8059. const prev = selector.at(selector.index(n) - 1);
  8060. if (!prev || !isSpaceCombinator(prev)) {
  8061. selector.insertAfter(
  8062. n,
  8063. selectorParser.combinator({
  8064. value: " "
  8065. })
  8066. );
  8067. }
  8068. selector.removeChild(n);
  8069. } else {
  8070. warn(
  8071. `${value} usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead of ${value} <inner-selector>.`
  8072. );
  8073. const prev = selector.at(selector.index(n) - 1);
  8074. if (prev && isSpaceCombinator(prev)) {
  8075. selector.removeChild(prev);
  8076. }
  8077. selector.removeChild(n);
  8078. }
  8079. return false;
  8080. }
  8081. if (value === ":slotted" || value === "::v-slotted") {
  8082. rewriteSelector(
  8083. id,
  8084. rule,
  8085. n.nodes[0],
  8086. selectorRoot,
  8087. deep,
  8088. true
  8089. );
  8090. let last = n;
  8091. n.nodes[0].each((ss) => {
  8092. selector.insertAfter(last, ss);
  8093. last = ss;
  8094. });
  8095. selector.removeChild(n);
  8096. shouldInject = false;
  8097. return false;
  8098. }
  8099. if (value === ":global" || value === "::v-global") {
  8100. selector.replaceWith(n.nodes[0]);
  8101. return false;
  8102. }
  8103. }
  8104. if (n.type === "universal") {
  8105. const prev = selector.at(selector.index(n) - 1);
  8106. const next = selector.at(selector.index(n) + 1);
  8107. if (!prev) {
  8108. if (next) {
  8109. if (next.type === "combinator" && next.value === " ") {
  8110. selector.removeChild(next);
  8111. }
  8112. selector.removeChild(n);
  8113. return;
  8114. } else {
  8115. node = selectorParser.combinator({
  8116. value: ""
  8117. });
  8118. selector.insertBefore(n, node);
  8119. selector.removeChild(n);
  8120. return false;
  8121. }
  8122. }
  8123. if (node) return;
  8124. }
  8125. if (!hasNestedDeep && (n.type !== "pseudo" && n.type !== "combinator" || n.type === "pseudo" && (n.value === ":is" || n.value === ":where") && !node)) {
  8126. node = n;
  8127. }
  8128. });
  8129. if (splitForNestedDeep) {
  8130. return;
  8131. }
  8132. if (rule.nodes.some((node2) => node2.type === "rule")) {
  8133. const deep2 = rule.__deep;
  8134. if (!deep2) {
  8135. extractAndWrapNodes(rule);
  8136. const atruleNodes = rule.nodes.filter((node2) => node2.type === "atrule");
  8137. for (const atnode of atruleNodes) {
  8138. extractAndWrapNodes(atnode);
  8139. }
  8140. }
  8141. shouldInject = deep2;
  8142. }
  8143. if (node && !hasNestedDeep) {
  8144. const { type, value } = node;
  8145. if (type === "pseudo" && (value === ":is" || value === ":where")) {
  8146. node.nodes.forEach(
  8147. (value2) => rewriteSelector(id, rule, value2, selectorRoot, deep, slotted)
  8148. );
  8149. shouldInject = false;
  8150. }
  8151. }
  8152. if (node) {
  8153. node.spaces.after = "";
  8154. } else {
  8155. selector.first.spaces.before = "";
  8156. }
  8157. if (shouldInject) {
  8158. const idToAdd = slotted ? id + "-s" : id;
  8159. selector.insertAfter(
  8160. // If node is null it means we need to inject [id] at the start
  8161. // insertAfter can handle `null` here
  8162. node,
  8163. selectorParser.attribute({
  8164. attribute: idToAdd,
  8165. value: idToAdd,
  8166. raws: {},
  8167. quoteMark: `"`
  8168. })
  8169. );
  8170. }
  8171. }
  8172. function isSpaceCombinator(node) {
  8173. return node.type === "combinator" && /^\s+$/.test(node.value);
  8174. }
  8175. function isDeepSelector(node) {
  8176. var _a;
  8177. if (node.type === "pseudo" && (node.value === ":deep" || node.value === "::v-deep")) {
  8178. return true;
  8179. }
  8180. return !!((_a = node.nodes) == null ? void 0 : _a.some((child) => isDeepSelector(child)));
  8181. }
  8182. function isDeepContainerPseudo(node) {
  8183. return node.type === "pseudo" && (node.value === ":is" || node.value === ":where" || node.value === ":has" || node.value === ":not");
  8184. }
  8185. function canSplitDeepContainerPseudo(node) {
  8186. return node.value === ":is" || node.value === ":where" || node.value === ":has";
  8187. }
  8188. function splitSelectorForNestedDeep(id, rule, selector, selectorRoot, pseudo, deep, slotted) {
  8189. const pseudoIndex = selector.index(pseudo);
  8190. const selectors = pseudo.nodes.map((branch, index) => {
  8191. const branchSelector = selector.clone();
  8192. if (branchSelector.first) {
  8193. branchSelector.first.spaces.before = index === 0 ? selector.first.spaces.before : " ";
  8194. }
  8195. const branchPseudo = branchSelector.at(pseudoIndex);
  8196. const branchClone = branch.clone();
  8197. if (branchClone.first) {
  8198. branchClone.first.spaces.before = "";
  8199. }
  8200. branchPseudo.removeAll();
  8201. branchPseudo.append(branchClone);
  8202. rewriteSelector(id, rule, branchSelector, selectorRoot, deep, slotted);
  8203. return branchSelector;
  8204. });
  8205. selector.replaceWith(...selectors);
  8206. }
  8207. function extractAndWrapNodes(parentNode) {
  8208. if (!parentNode.nodes) return;
  8209. const nodes = parentNode.nodes.filter(
  8210. (node) => node.type === "decl" || node.type === "comment"
  8211. );
  8212. if (nodes.length) {
  8213. for (const node of nodes) {
  8214. parentNode.removeChild(node);
  8215. }
  8216. const wrappedRule = new require$$0$1.Rule({
  8217. nodes,
  8218. selector: "&"
  8219. });
  8220. parentNode.prepend(wrappedRule);
  8221. }
  8222. }
  8223. scopedPlugin.postcss = true;
  8224. var sourceMap = {};
  8225. var sourceMapGenerator = {};
  8226. var base64Vlq = {};
  8227. var base64 = {};
  8228. /* -*- Mode: js; js-indent-level: 2; -*- */
  8229. var hasRequiredBase64;
  8230. function requireBase64 () {
  8231. if (hasRequiredBase64) return base64;
  8232. hasRequiredBase64 = 1;
  8233. /*
  8234. * Copyright 2011 Mozilla Foundation and contributors
  8235. * Licensed under the New BSD license. See LICENSE or:
  8236. * http://opensource.org/licenses/BSD-3-Clause
  8237. */
  8238. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  8239. /**
  8240. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  8241. */
  8242. base64.encode = function (number) {
  8243. if (0 <= number && number < intToCharMap.length) {
  8244. return intToCharMap[number];
  8245. }
  8246. throw new TypeError("Must be between 0 and 63: " + number);
  8247. };
  8248. /**
  8249. * Decode a single base 64 character code digit to an integer. Returns -1 on
  8250. * failure.
  8251. */
  8252. base64.decode = function (charCode) {
  8253. var bigA = 65; // 'A'
  8254. var bigZ = 90; // 'Z'
  8255. var littleA = 97; // 'a'
  8256. var littleZ = 122; // 'z'
  8257. var zero = 48; // '0'
  8258. var nine = 57; // '9'
  8259. var plus = 43; // '+'
  8260. var slash = 47; // '/'
  8261. var littleOffset = 26;
  8262. var numberOffset = 52;
  8263. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  8264. if (bigA <= charCode && charCode <= bigZ) {
  8265. return (charCode - bigA);
  8266. }
  8267. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  8268. if (littleA <= charCode && charCode <= littleZ) {
  8269. return (charCode - littleA + littleOffset);
  8270. }
  8271. // 52 - 61: 0123456789
  8272. if (zero <= charCode && charCode <= nine) {
  8273. return (charCode - zero + numberOffset);
  8274. }
  8275. // 62: +
  8276. if (charCode == plus) {
  8277. return 62;
  8278. }
  8279. // 63: /
  8280. if (charCode == slash) {
  8281. return 63;
  8282. }
  8283. // Invalid base64 digit.
  8284. return -1;
  8285. };
  8286. return base64;
  8287. }
  8288. /* -*- Mode: js; js-indent-level: 2; -*- */
  8289. var hasRequiredBase64Vlq;
  8290. function requireBase64Vlq () {
  8291. if (hasRequiredBase64Vlq) return base64Vlq;
  8292. hasRequiredBase64Vlq = 1;
  8293. /*
  8294. * Copyright 2011 Mozilla Foundation and contributors
  8295. * Licensed under the New BSD license. See LICENSE or:
  8296. * http://opensource.org/licenses/BSD-3-Clause
  8297. *
  8298. * Based on the Base 64 VLQ implementation in Closure Compiler:
  8299. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  8300. *
  8301. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  8302. * Redistribution and use in source and binary forms, with or without
  8303. * modification, are permitted provided that the following conditions are
  8304. * met:
  8305. *
  8306. * * Redistributions of source code must retain the above copyright
  8307. * notice, this list of conditions and the following disclaimer.
  8308. * * Redistributions in binary form must reproduce the above
  8309. * copyright notice, this list of conditions and the following
  8310. * disclaimer in the documentation and/or other materials provided
  8311. * with the distribution.
  8312. * * Neither the name of Google Inc. nor the names of its
  8313. * contributors may be used to endorse or promote products derived
  8314. * from this software without specific prior written permission.
  8315. *
  8316. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  8317. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  8318. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8319. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  8320. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8321. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  8322. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  8323. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  8324. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  8325. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  8326. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  8327. */
  8328. var base64 = /*@__PURE__*/ requireBase64();
  8329. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  8330. // length quantities we use in the source map spec, the first bit is the sign,
  8331. // the next four bits are the actual value, and the 6th bit is the
  8332. // continuation bit. The continuation bit tells us whether there are more
  8333. // digits in this value following this digit.
  8334. //
  8335. // Continuation
  8336. // | Sign
  8337. // | |
  8338. // V V
  8339. // 101011
  8340. var VLQ_BASE_SHIFT = 5;
  8341. // binary: 100000
  8342. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  8343. // binary: 011111
  8344. var VLQ_BASE_MASK = VLQ_BASE - 1;
  8345. // binary: 100000
  8346. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  8347. /**
  8348. * Converts from a two-complement value to a value where the sign bit is
  8349. * placed in the least significant bit. For example, as decimals:
  8350. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  8351. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  8352. */
  8353. function toVLQSigned(aValue) {
  8354. return aValue < 0
  8355. ? ((-aValue) << 1) + 1
  8356. : (aValue << 1) + 0;
  8357. }
  8358. /**
  8359. * Converts to a two-complement value from a value where the sign bit is
  8360. * placed in the least significant bit. For example, as decimals:
  8361. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  8362. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  8363. */
  8364. function fromVLQSigned(aValue) {
  8365. var isNegative = (aValue & 1) === 1;
  8366. var shifted = aValue >> 1;
  8367. return isNegative
  8368. ? -shifted
  8369. : shifted;
  8370. }
  8371. /**
  8372. * Returns the base 64 VLQ encoded value.
  8373. */
  8374. base64Vlq.encode = function base64VLQ_encode(aValue) {
  8375. var encoded = "";
  8376. var digit;
  8377. var vlq = toVLQSigned(aValue);
  8378. do {
  8379. digit = vlq & VLQ_BASE_MASK;
  8380. vlq >>>= VLQ_BASE_SHIFT;
  8381. if (vlq > 0) {
  8382. // There are still more digits in this value, so we must make sure the
  8383. // continuation bit is marked.
  8384. digit |= VLQ_CONTINUATION_BIT;
  8385. }
  8386. encoded += base64.encode(digit);
  8387. } while (vlq > 0);
  8388. return encoded;
  8389. };
  8390. /**
  8391. * Decodes the next base 64 VLQ value from the given string and returns the
  8392. * value and the rest of the string via the out parameter.
  8393. */
  8394. base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  8395. var strLen = aStr.length;
  8396. var result = 0;
  8397. var shift = 0;
  8398. var continuation, digit;
  8399. do {
  8400. if (aIndex >= strLen) {
  8401. throw new Error("Expected more digits in base 64 VLQ value.");
  8402. }
  8403. digit = base64.decode(aStr.charCodeAt(aIndex++));
  8404. if (digit === -1) {
  8405. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  8406. }
  8407. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  8408. digit &= VLQ_BASE_MASK;
  8409. result = result + (digit << shift);
  8410. shift += VLQ_BASE_SHIFT;
  8411. } while (continuation);
  8412. aOutParam.value = fromVLQSigned(result);
  8413. aOutParam.rest = aIndex;
  8414. };
  8415. return base64Vlq;
  8416. }
  8417. var util$1 = {};
  8418. /* -*- Mode: js; js-indent-level: 2; -*- */
  8419. var hasRequiredUtil$1;
  8420. function requireUtil$1 () {
  8421. if (hasRequiredUtil$1) return util$1;
  8422. hasRequiredUtil$1 = 1;
  8423. (function (exports) {
  8424. /*
  8425. * Copyright 2011 Mozilla Foundation and contributors
  8426. * Licensed under the New BSD license. See LICENSE or:
  8427. * http://opensource.org/licenses/BSD-3-Clause
  8428. */
  8429. /**
  8430. * This is a helper function for getting values from parameter/options
  8431. * objects.
  8432. *
  8433. * @param args The object we are extracting values from
  8434. * @param name The name of the property we are getting.
  8435. * @param defaultValue An optional value to return if the property is missing
  8436. * from the object. If this is not specified and the property is missing, an
  8437. * error will be thrown.
  8438. */
  8439. function getArg(aArgs, aName, aDefaultValue) {
  8440. if (aName in aArgs) {
  8441. return aArgs[aName];
  8442. } else if (arguments.length === 3) {
  8443. return aDefaultValue;
  8444. } else {
  8445. throw new Error('"' + aName + '" is a required argument.');
  8446. }
  8447. }
  8448. exports.getArg = getArg;
  8449. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  8450. var dataUrlRegexp = /^data:.+\,.+$/;
  8451. function urlParse(aUrl) {
  8452. var match = aUrl.match(urlRegexp);
  8453. if (!match) {
  8454. return null;
  8455. }
  8456. return {
  8457. scheme: match[1],
  8458. auth: match[2],
  8459. host: match[3],
  8460. port: match[4],
  8461. path: match[5]
  8462. };
  8463. }
  8464. exports.urlParse = urlParse;
  8465. function urlGenerate(aParsedUrl) {
  8466. var url = '';
  8467. if (aParsedUrl.scheme) {
  8468. url += aParsedUrl.scheme + ':';
  8469. }
  8470. url += '//';
  8471. if (aParsedUrl.auth) {
  8472. url += aParsedUrl.auth + '@';
  8473. }
  8474. if (aParsedUrl.host) {
  8475. url += aParsedUrl.host;
  8476. }
  8477. if (aParsedUrl.port) {
  8478. url += ":" + aParsedUrl.port;
  8479. }
  8480. if (aParsedUrl.path) {
  8481. url += aParsedUrl.path;
  8482. }
  8483. return url;
  8484. }
  8485. exports.urlGenerate = urlGenerate;
  8486. /**
  8487. * Normalizes a path, or the path portion of a URL:
  8488. *
  8489. * - Replaces consecutive slashes with one slash.
  8490. * - Removes unnecessary '.' parts.
  8491. * - Removes unnecessary '<dir>/..' parts.
  8492. *
  8493. * Based on code in the Node.js 'path' core module.
  8494. *
  8495. * @param aPath The path or url to normalize.
  8496. */
  8497. function normalize(aPath) {
  8498. var path = aPath;
  8499. var url = urlParse(aPath);
  8500. if (url) {
  8501. if (!url.path) {
  8502. return aPath;
  8503. }
  8504. path = url.path;
  8505. }
  8506. var isAbsolute = exports.isAbsolute(path);
  8507. var parts = path.split(/\/+/);
  8508. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  8509. part = parts[i];
  8510. if (part === '.') {
  8511. parts.splice(i, 1);
  8512. } else if (part === '..') {
  8513. up++;
  8514. } else if (up > 0) {
  8515. if (part === '') {
  8516. // The first part is blank if the path is absolute. Trying to go
  8517. // above the root is a no-op. Therefore we can remove all '..' parts
  8518. // directly after the root.
  8519. parts.splice(i + 1, up);
  8520. up = 0;
  8521. } else {
  8522. parts.splice(i, 2);
  8523. up--;
  8524. }
  8525. }
  8526. }
  8527. path = parts.join('/');
  8528. if (path === '') {
  8529. path = isAbsolute ? '/' : '.';
  8530. }
  8531. if (url) {
  8532. url.path = path;
  8533. return urlGenerate(url);
  8534. }
  8535. return path;
  8536. }
  8537. exports.normalize = normalize;
  8538. /**
  8539. * Joins two paths/URLs.
  8540. *
  8541. * @param aRoot The root path or URL.
  8542. * @param aPath The path or URL to be joined with the root.
  8543. *
  8544. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  8545. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  8546. * first.
  8547. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  8548. * is updated with the result and aRoot is returned. Otherwise the result
  8549. * is returned.
  8550. * - If aPath is absolute, the result is aPath.
  8551. * - Otherwise the two paths are joined with a slash.
  8552. * - Joining for example 'http://' and 'www.example.com' is also supported.
  8553. */
  8554. function join(aRoot, aPath) {
  8555. if (aRoot === "") {
  8556. aRoot = ".";
  8557. }
  8558. if (aPath === "") {
  8559. aPath = ".";
  8560. }
  8561. var aPathUrl = urlParse(aPath);
  8562. var aRootUrl = urlParse(aRoot);
  8563. if (aRootUrl) {
  8564. aRoot = aRootUrl.path || '/';
  8565. }
  8566. // `join(foo, '//www.example.org')`
  8567. if (aPathUrl && !aPathUrl.scheme) {
  8568. if (aRootUrl) {
  8569. aPathUrl.scheme = aRootUrl.scheme;
  8570. }
  8571. return urlGenerate(aPathUrl);
  8572. }
  8573. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  8574. return aPath;
  8575. }
  8576. // `join('http://', 'www.example.com')`
  8577. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  8578. aRootUrl.host = aPath;
  8579. return urlGenerate(aRootUrl);
  8580. }
  8581. var joined = aPath.charAt(0) === '/'
  8582. ? aPath
  8583. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  8584. if (aRootUrl) {
  8585. aRootUrl.path = joined;
  8586. return urlGenerate(aRootUrl);
  8587. }
  8588. return joined;
  8589. }
  8590. exports.join = join;
  8591. exports.isAbsolute = function (aPath) {
  8592. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  8593. };
  8594. /**
  8595. * Make a path relative to a URL or another path.
  8596. *
  8597. * @param aRoot The root path or URL.
  8598. * @param aPath The path or URL to be made relative to aRoot.
  8599. */
  8600. function relative(aRoot, aPath) {
  8601. if (aRoot === "") {
  8602. aRoot = ".";
  8603. }
  8604. aRoot = aRoot.replace(/\/$/, '');
  8605. // It is possible for the path to be above the root. In this case, simply
  8606. // checking whether the root is a prefix of the path won't work. Instead, we
  8607. // need to remove components from the root one by one, until either we find
  8608. // a prefix that fits, or we run out of components to remove.
  8609. var level = 0;
  8610. while (aPath.indexOf(aRoot + '/') !== 0) {
  8611. var index = aRoot.lastIndexOf("/");
  8612. if (index < 0) {
  8613. return aPath;
  8614. }
  8615. // If the only part of the root that is left is the scheme (i.e. http://,
  8616. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  8617. // have exhausted all components, so the path is not relative to the root.
  8618. aRoot = aRoot.slice(0, index);
  8619. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  8620. return aPath;
  8621. }
  8622. ++level;
  8623. }
  8624. // Make sure we add a "../" for each component we removed from the root.
  8625. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  8626. }
  8627. exports.relative = relative;
  8628. var supportsNullProto = (function () {
  8629. var obj = Object.create(null);
  8630. return !('__proto__' in obj);
  8631. }());
  8632. function identity (s) {
  8633. return s;
  8634. }
  8635. /**
  8636. * Because behavior goes wacky when you set `__proto__` on objects, we
  8637. * have to prefix all the strings in our set with an arbitrary character.
  8638. *
  8639. * See https://github.com/mozilla/source-map/pull/31 and
  8640. * https://github.com/mozilla/source-map/issues/30
  8641. *
  8642. * @param String aStr
  8643. */
  8644. function toSetString(aStr) {
  8645. if (isProtoString(aStr)) {
  8646. return '$' + aStr;
  8647. }
  8648. return aStr;
  8649. }
  8650. exports.toSetString = supportsNullProto ? identity : toSetString;
  8651. function fromSetString(aStr) {
  8652. if (isProtoString(aStr)) {
  8653. return aStr.slice(1);
  8654. }
  8655. return aStr;
  8656. }
  8657. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  8658. function isProtoString(s) {
  8659. if (!s) {
  8660. return false;
  8661. }
  8662. var length = s.length;
  8663. if (length < 9 /* "__proto__".length */) {
  8664. return false;
  8665. }
  8666. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  8667. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  8668. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  8669. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  8670. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  8671. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  8672. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  8673. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  8674. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  8675. return false;
  8676. }
  8677. for (var i = length - 10; i >= 0; i--) {
  8678. if (s.charCodeAt(i) !== 36 /* '$' */) {
  8679. return false;
  8680. }
  8681. }
  8682. return true;
  8683. }
  8684. /**
  8685. * Comparator between two mappings where the original positions are compared.
  8686. *
  8687. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  8688. * mappings with the same original source/line/column, but different generated
  8689. * line and column the same. Useful when searching for a mapping with a
  8690. * stubbed out mapping.
  8691. */
  8692. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  8693. var cmp = strcmp(mappingA.source, mappingB.source);
  8694. if (cmp !== 0) {
  8695. return cmp;
  8696. }
  8697. cmp = mappingA.originalLine - mappingB.originalLine;
  8698. if (cmp !== 0) {
  8699. return cmp;
  8700. }
  8701. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8702. if (cmp !== 0 || onlyCompareOriginal) {
  8703. return cmp;
  8704. }
  8705. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8706. if (cmp !== 0) {
  8707. return cmp;
  8708. }
  8709. cmp = mappingA.generatedLine - mappingB.generatedLine;
  8710. if (cmp !== 0) {
  8711. return cmp;
  8712. }
  8713. return strcmp(mappingA.name, mappingB.name);
  8714. }
  8715. exports.compareByOriginalPositions = compareByOriginalPositions;
  8716. /**
  8717. * Comparator between two mappings with deflated source and name indices where
  8718. * the generated positions are compared.
  8719. *
  8720. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  8721. * mappings with the same generated line and column, but different
  8722. * source/name/original line and column the same. Useful when searching for a
  8723. * mapping with a stubbed out mapping.
  8724. */
  8725. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  8726. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  8727. if (cmp !== 0) {
  8728. return cmp;
  8729. }
  8730. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8731. if (cmp !== 0 || onlyCompareGenerated) {
  8732. return cmp;
  8733. }
  8734. cmp = strcmp(mappingA.source, mappingB.source);
  8735. if (cmp !== 0) {
  8736. return cmp;
  8737. }
  8738. cmp = mappingA.originalLine - mappingB.originalLine;
  8739. if (cmp !== 0) {
  8740. return cmp;
  8741. }
  8742. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8743. if (cmp !== 0) {
  8744. return cmp;
  8745. }
  8746. return strcmp(mappingA.name, mappingB.name);
  8747. }
  8748. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  8749. function strcmp(aStr1, aStr2) {
  8750. if (aStr1 === aStr2) {
  8751. return 0;
  8752. }
  8753. if (aStr1 === null) {
  8754. return 1; // aStr2 !== null
  8755. }
  8756. if (aStr2 === null) {
  8757. return -1; // aStr1 !== null
  8758. }
  8759. if (aStr1 > aStr2) {
  8760. return 1;
  8761. }
  8762. return -1;
  8763. }
  8764. /**
  8765. * Comparator between two mappings with inflated source and name strings where
  8766. * the generated positions are compared.
  8767. */
  8768. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  8769. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  8770. if (cmp !== 0) {
  8771. return cmp;
  8772. }
  8773. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8774. if (cmp !== 0) {
  8775. return cmp;
  8776. }
  8777. cmp = strcmp(mappingA.source, mappingB.source);
  8778. if (cmp !== 0) {
  8779. return cmp;
  8780. }
  8781. cmp = mappingA.originalLine - mappingB.originalLine;
  8782. if (cmp !== 0) {
  8783. return cmp;
  8784. }
  8785. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8786. if (cmp !== 0) {
  8787. return cmp;
  8788. }
  8789. return strcmp(mappingA.name, mappingB.name);
  8790. }
  8791. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  8792. /**
  8793. * Strip any JSON XSSI avoidance prefix from the string (as documented
  8794. * in the source maps specification), and then parse the string as
  8795. * JSON.
  8796. */
  8797. function parseSourceMapInput(str) {
  8798. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  8799. }
  8800. exports.parseSourceMapInput = parseSourceMapInput;
  8801. /**
  8802. * Compute the URL of a source given the the source root, the source's
  8803. * URL, and the source map's URL.
  8804. */
  8805. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  8806. sourceURL = sourceURL || '';
  8807. if (sourceRoot) {
  8808. // This follows what Chrome does.
  8809. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  8810. sourceRoot += '/';
  8811. }
  8812. // The spec says:
  8813. // Line 4: An optional source root, useful for relocating source
  8814. // files on a server or removing repeated values in the
  8815. // “sources” entry. This value is prepended to the individual
  8816. // entries in the “source” field.
  8817. sourceURL = sourceRoot + sourceURL;
  8818. }
  8819. // Historically, SourceMapConsumer did not take the sourceMapURL as
  8820. // a parameter. This mode is still somewhat supported, which is why
  8821. // this code block is conditional. However, it's preferable to pass
  8822. // the source map URL to SourceMapConsumer, so that this function
  8823. // can implement the source URL resolution algorithm as outlined in
  8824. // the spec. This block is basically the equivalent of:
  8825. // new URL(sourceURL, sourceMapURL).toString()
  8826. // ... except it avoids using URL, which wasn't available in the
  8827. // older releases of node still supported by this library.
  8828. //
  8829. // The spec says:
  8830. // If the sources are not absolute URLs after prepending of the
  8831. // “sourceRoot”, the sources are resolved relative to the
  8832. // SourceMap (like resolving script src in a html document).
  8833. if (sourceMapURL) {
  8834. var parsed = urlParse(sourceMapURL);
  8835. if (!parsed) {
  8836. throw new Error("sourceMapURL could not be parsed");
  8837. }
  8838. if (parsed.path) {
  8839. // Strip the last path component, but keep the "/".
  8840. var index = parsed.path.lastIndexOf('/');
  8841. if (index >= 0) {
  8842. parsed.path = parsed.path.substring(0, index + 1);
  8843. }
  8844. }
  8845. sourceURL = join(urlGenerate(parsed), sourceURL);
  8846. }
  8847. return normalize(sourceURL);
  8848. }
  8849. exports.computeSourceURL = computeSourceURL;
  8850. } (util$1));
  8851. return util$1;
  8852. }
  8853. var arraySet = {};
  8854. /* -*- Mode: js; js-indent-level: 2; -*- */
  8855. var hasRequiredArraySet;
  8856. function requireArraySet () {
  8857. if (hasRequiredArraySet) return arraySet;
  8858. hasRequiredArraySet = 1;
  8859. /*
  8860. * Copyright 2011 Mozilla Foundation and contributors
  8861. * Licensed under the New BSD license. See LICENSE or:
  8862. * http://opensource.org/licenses/BSD-3-Clause
  8863. */
  8864. var util = /*@__PURE__*/ requireUtil$1();
  8865. var has = Object.prototype.hasOwnProperty;
  8866. var hasNativeMap = typeof Map !== "undefined";
  8867. /**
  8868. * A data structure which is a combination of an array and a set. Adding a new
  8869. * member is O(1), testing for membership is O(1), and finding the index of an
  8870. * element is O(1). Removing elements from the set is not supported. Only
  8871. * strings are supported for membership.
  8872. */
  8873. function ArraySet() {
  8874. this._array = [];
  8875. this._set = hasNativeMap ? new Map() : Object.create(null);
  8876. }
  8877. /**
  8878. * Static method for creating ArraySet instances from an existing array.
  8879. */
  8880. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  8881. var set = new ArraySet();
  8882. for (var i = 0, len = aArray.length; i < len; i++) {
  8883. set.add(aArray[i], aAllowDuplicates);
  8884. }
  8885. return set;
  8886. };
  8887. /**
  8888. * Return how many unique items are in this ArraySet. If duplicates have been
  8889. * added, than those do not count towards the size.
  8890. *
  8891. * @returns Number
  8892. */
  8893. ArraySet.prototype.size = function ArraySet_size() {
  8894. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  8895. };
  8896. /**
  8897. * Add the given string to this set.
  8898. *
  8899. * @param String aStr
  8900. */
  8901. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  8902. var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
  8903. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  8904. var idx = this._array.length;
  8905. if (!isDuplicate || aAllowDuplicates) {
  8906. this._array.push(aStr);
  8907. }
  8908. if (!isDuplicate) {
  8909. if (hasNativeMap) {
  8910. this._set.set(aStr, idx);
  8911. } else {
  8912. this._set[sStr] = idx;
  8913. }
  8914. }
  8915. };
  8916. /**
  8917. * Is the given string a member of this set?
  8918. *
  8919. * @param String aStr
  8920. */
  8921. ArraySet.prototype.has = function ArraySet_has(aStr) {
  8922. if (hasNativeMap) {
  8923. return this._set.has(aStr);
  8924. } else {
  8925. var sStr = util.toSetString(aStr);
  8926. return has.call(this._set, sStr);
  8927. }
  8928. };
  8929. /**
  8930. * What is the index of the given string in the array?
  8931. *
  8932. * @param String aStr
  8933. */
  8934. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  8935. if (hasNativeMap) {
  8936. var idx = this._set.get(aStr);
  8937. if (idx >= 0) {
  8938. return idx;
  8939. }
  8940. } else {
  8941. var sStr = util.toSetString(aStr);
  8942. if (has.call(this._set, sStr)) {
  8943. return this._set[sStr];
  8944. }
  8945. }
  8946. throw new Error('"' + aStr + '" is not in the set.');
  8947. };
  8948. /**
  8949. * What is the element at the given index?
  8950. *
  8951. * @param Number aIdx
  8952. */
  8953. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  8954. if (aIdx >= 0 && aIdx < this._array.length) {
  8955. return this._array[aIdx];
  8956. }
  8957. throw new Error('No element indexed by ' + aIdx);
  8958. };
  8959. /**
  8960. * Returns the array representation of this set (which has the proper indices
  8961. * indicated by indexOf). Note that this is a copy of the internal array used
  8962. * for storing the members so that no one can mess with internal state.
  8963. */
  8964. ArraySet.prototype.toArray = function ArraySet_toArray() {
  8965. return this._array.slice();
  8966. };
  8967. arraySet.ArraySet = ArraySet;
  8968. return arraySet;
  8969. }
  8970. var mappingList = {};
  8971. /* -*- Mode: js; js-indent-level: 2; -*- */
  8972. var hasRequiredMappingList;
  8973. function requireMappingList () {
  8974. if (hasRequiredMappingList) return mappingList;
  8975. hasRequiredMappingList = 1;
  8976. /*
  8977. * Copyright 2014 Mozilla Foundation and contributors
  8978. * Licensed under the New BSD license. See LICENSE or:
  8979. * http://opensource.org/licenses/BSD-3-Clause
  8980. */
  8981. var util = /*@__PURE__*/ requireUtil$1();
  8982. /**
  8983. * Determine whether mappingB is after mappingA with respect to generated
  8984. * position.
  8985. */
  8986. function generatedPositionAfter(mappingA, mappingB) {
  8987. // Optimized for most common case
  8988. var lineA = mappingA.generatedLine;
  8989. var lineB = mappingB.generatedLine;
  8990. var columnA = mappingA.generatedColumn;
  8991. var columnB = mappingB.generatedColumn;
  8992. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  8993. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  8994. }
  8995. /**
  8996. * A data structure to provide a sorted view of accumulated mappings in a
  8997. * performance conscious manner. It trades a neglibable overhead in general
  8998. * case for a large speedup in case of mappings being added in order.
  8999. */
  9000. function MappingList() {
  9001. this._array = [];
  9002. this._sorted = true;
  9003. // Serves as infimum
  9004. this._last = {generatedLine: -1, generatedColumn: 0};
  9005. }
  9006. /**
  9007. * Iterate through internal items. This method takes the same arguments that
  9008. * `Array.prototype.forEach` takes.
  9009. *
  9010. * NOTE: The order of the mappings is NOT guaranteed.
  9011. */
  9012. MappingList.prototype.unsortedForEach =
  9013. function MappingList_forEach(aCallback, aThisArg) {
  9014. this._array.forEach(aCallback, aThisArg);
  9015. };
  9016. /**
  9017. * Add the given source mapping.
  9018. *
  9019. * @param Object aMapping
  9020. */
  9021. MappingList.prototype.add = function MappingList_add(aMapping) {
  9022. if (generatedPositionAfter(this._last, aMapping)) {
  9023. this._last = aMapping;
  9024. this._array.push(aMapping);
  9025. } else {
  9026. this._sorted = false;
  9027. this._array.push(aMapping);
  9028. }
  9029. };
  9030. /**
  9031. * Returns the flat, sorted array of mappings. The mappings are sorted by
  9032. * generated position.
  9033. *
  9034. * WARNING: This method returns internal data without copying, for
  9035. * performance. The return value must NOT be mutated, and should be treated as
  9036. * an immutable borrow. If you want to take ownership, you must make your own
  9037. * copy.
  9038. */
  9039. MappingList.prototype.toArray = function MappingList_toArray() {
  9040. if (!this._sorted) {
  9041. this._array.sort(util.compareByGeneratedPositionsInflated);
  9042. this._sorted = true;
  9043. }
  9044. return this._array;
  9045. };
  9046. mappingList.MappingList = MappingList;
  9047. return mappingList;
  9048. }
  9049. /* -*- Mode: js; js-indent-level: 2; -*- */
  9050. var hasRequiredSourceMapGenerator;
  9051. function requireSourceMapGenerator () {
  9052. if (hasRequiredSourceMapGenerator) return sourceMapGenerator;
  9053. hasRequiredSourceMapGenerator = 1;
  9054. /*
  9055. * Copyright 2011 Mozilla Foundation and contributors
  9056. * Licensed under the New BSD license. See LICENSE or:
  9057. * http://opensource.org/licenses/BSD-3-Clause
  9058. */
  9059. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  9060. var util = /*@__PURE__*/ requireUtil$1();
  9061. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  9062. var MappingList = /*@__PURE__*/ requireMappingList().MappingList;
  9063. /**
  9064. * An instance of the SourceMapGenerator represents a source map which is
  9065. * being built incrementally. You may pass an object with the following
  9066. * properties:
  9067. *
  9068. * - file: The filename of the generated source.
  9069. * - sourceRoot: A root for all relative URLs in this source map.
  9070. */
  9071. function SourceMapGenerator(aArgs) {
  9072. if (!aArgs) {
  9073. aArgs = {};
  9074. }
  9075. this._file = util.getArg(aArgs, 'file', null);
  9076. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  9077. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  9078. this._sources = new ArraySet();
  9079. this._names = new ArraySet();
  9080. this._mappings = new MappingList();
  9081. this._sourcesContents = null;
  9082. }
  9083. SourceMapGenerator.prototype._version = 3;
  9084. /**
  9085. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  9086. *
  9087. * @param aSourceMapConsumer The SourceMap.
  9088. */
  9089. SourceMapGenerator.fromSourceMap =
  9090. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  9091. var sourceRoot = aSourceMapConsumer.sourceRoot;
  9092. var generator = new SourceMapGenerator({
  9093. file: aSourceMapConsumer.file,
  9094. sourceRoot: sourceRoot
  9095. });
  9096. aSourceMapConsumer.eachMapping(function (mapping) {
  9097. var newMapping = {
  9098. generated: {
  9099. line: mapping.generatedLine,
  9100. column: mapping.generatedColumn
  9101. }
  9102. };
  9103. if (mapping.source != null) {
  9104. newMapping.source = mapping.source;
  9105. if (sourceRoot != null) {
  9106. newMapping.source = util.relative(sourceRoot, newMapping.source);
  9107. }
  9108. newMapping.original = {
  9109. line: mapping.originalLine,
  9110. column: mapping.originalColumn
  9111. };
  9112. if (mapping.name != null) {
  9113. newMapping.name = mapping.name;
  9114. }
  9115. }
  9116. generator.addMapping(newMapping);
  9117. });
  9118. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  9119. var sourceRelative = sourceFile;
  9120. if (sourceRoot !== null) {
  9121. sourceRelative = util.relative(sourceRoot, sourceFile);
  9122. }
  9123. if (!generator._sources.has(sourceRelative)) {
  9124. generator._sources.add(sourceRelative);
  9125. }
  9126. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  9127. if (content != null) {
  9128. generator.setSourceContent(sourceFile, content);
  9129. }
  9130. });
  9131. return generator;
  9132. };
  9133. /**
  9134. * Add a single mapping from original source line and column to the generated
  9135. * source's line and column for this source map being created. The mapping
  9136. * object should have the following properties:
  9137. *
  9138. * - generated: An object with the generated line and column positions.
  9139. * - original: An object with the original line and column positions.
  9140. * - source: The original source file (relative to the sourceRoot).
  9141. * - name: An optional original token name for this mapping.
  9142. */
  9143. SourceMapGenerator.prototype.addMapping =
  9144. function SourceMapGenerator_addMapping(aArgs) {
  9145. var generated = util.getArg(aArgs, 'generated');
  9146. var original = util.getArg(aArgs, 'original', null);
  9147. var source = util.getArg(aArgs, 'source', null);
  9148. var name = util.getArg(aArgs, 'name', null);
  9149. if (!this._skipValidation) {
  9150. this._validateMapping(generated, original, source, name);
  9151. }
  9152. if (source != null) {
  9153. source = String(source);
  9154. if (!this._sources.has(source)) {
  9155. this._sources.add(source);
  9156. }
  9157. }
  9158. if (name != null) {
  9159. name = String(name);
  9160. if (!this._names.has(name)) {
  9161. this._names.add(name);
  9162. }
  9163. }
  9164. this._mappings.add({
  9165. generatedLine: generated.line,
  9166. generatedColumn: generated.column,
  9167. originalLine: original != null && original.line,
  9168. originalColumn: original != null && original.column,
  9169. source: source,
  9170. name: name
  9171. });
  9172. };
  9173. /**
  9174. * Set the source content for a source file.
  9175. */
  9176. SourceMapGenerator.prototype.setSourceContent =
  9177. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  9178. var source = aSourceFile;
  9179. if (this._sourceRoot != null) {
  9180. source = util.relative(this._sourceRoot, source);
  9181. }
  9182. if (aSourceContent != null) {
  9183. // Add the source content to the _sourcesContents map.
  9184. // Create a new _sourcesContents map if the property is null.
  9185. if (!this._sourcesContents) {
  9186. this._sourcesContents = Object.create(null);
  9187. }
  9188. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  9189. } else if (this._sourcesContents) {
  9190. // Remove the source file from the _sourcesContents map.
  9191. // If the _sourcesContents map is empty, set the property to null.
  9192. delete this._sourcesContents[util.toSetString(source)];
  9193. if (Object.keys(this._sourcesContents).length === 0) {
  9194. this._sourcesContents = null;
  9195. }
  9196. }
  9197. };
  9198. /**
  9199. * Applies the mappings of a sub-source-map for a specific source file to the
  9200. * source map being generated. Each mapping to the supplied source file is
  9201. * rewritten using the supplied source map. Note: The resolution for the
  9202. * resulting mappings is the minimium of this map and the supplied map.
  9203. *
  9204. * @param aSourceMapConsumer The source map to be applied.
  9205. * @param aSourceFile Optional. The filename of the source file.
  9206. * If omitted, SourceMapConsumer's file property will be used.
  9207. * @param aSourceMapPath Optional. The dirname of the path to the source map
  9208. * to be applied. If relative, it is relative to the SourceMapConsumer.
  9209. * This parameter is needed when the two source maps aren't in the same
  9210. * directory, and the source map to be applied contains relative source
  9211. * paths. If so, those relative source paths need to be rewritten
  9212. * relative to the SourceMapGenerator.
  9213. */
  9214. SourceMapGenerator.prototype.applySourceMap =
  9215. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  9216. var sourceFile = aSourceFile;
  9217. // If aSourceFile is omitted, we will use the file property of the SourceMap
  9218. if (aSourceFile == null) {
  9219. if (aSourceMapConsumer.file == null) {
  9220. throw new Error(
  9221. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  9222. 'or the source map\'s "file" property. Both were omitted.'
  9223. );
  9224. }
  9225. sourceFile = aSourceMapConsumer.file;
  9226. }
  9227. var sourceRoot = this._sourceRoot;
  9228. // Make "sourceFile" relative if an absolute Url is passed.
  9229. if (sourceRoot != null) {
  9230. sourceFile = util.relative(sourceRoot, sourceFile);
  9231. }
  9232. // Applying the SourceMap can add and remove items from the sources and
  9233. // the names array.
  9234. var newSources = new ArraySet();
  9235. var newNames = new ArraySet();
  9236. // Find mappings for the "sourceFile"
  9237. this._mappings.unsortedForEach(function (mapping) {
  9238. if (mapping.source === sourceFile && mapping.originalLine != null) {
  9239. // Check if it can be mapped by the source map, then update the mapping.
  9240. var original = aSourceMapConsumer.originalPositionFor({
  9241. line: mapping.originalLine,
  9242. column: mapping.originalColumn
  9243. });
  9244. if (original.source != null) {
  9245. // Copy mapping
  9246. mapping.source = original.source;
  9247. if (aSourceMapPath != null) {
  9248. mapping.source = util.join(aSourceMapPath, mapping.source);
  9249. }
  9250. if (sourceRoot != null) {
  9251. mapping.source = util.relative(sourceRoot, mapping.source);
  9252. }
  9253. mapping.originalLine = original.line;
  9254. mapping.originalColumn = original.column;
  9255. if (original.name != null) {
  9256. mapping.name = original.name;
  9257. }
  9258. }
  9259. }
  9260. var source = mapping.source;
  9261. if (source != null && !newSources.has(source)) {
  9262. newSources.add(source);
  9263. }
  9264. var name = mapping.name;
  9265. if (name != null && !newNames.has(name)) {
  9266. newNames.add(name);
  9267. }
  9268. }, this);
  9269. this._sources = newSources;
  9270. this._names = newNames;
  9271. // Copy sourcesContents of applied map.
  9272. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  9273. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  9274. if (content != null) {
  9275. if (aSourceMapPath != null) {
  9276. sourceFile = util.join(aSourceMapPath, sourceFile);
  9277. }
  9278. if (sourceRoot != null) {
  9279. sourceFile = util.relative(sourceRoot, sourceFile);
  9280. }
  9281. this.setSourceContent(sourceFile, content);
  9282. }
  9283. }, this);
  9284. };
  9285. /**
  9286. * A mapping can have one of the three levels of data:
  9287. *
  9288. * 1. Just the generated position.
  9289. * 2. The Generated position, original position, and original source.
  9290. * 3. Generated and original position, original source, as well as a name
  9291. * token.
  9292. *
  9293. * To maintain consistency, we validate that any new mapping being added falls
  9294. * in to one of these categories.
  9295. */
  9296. SourceMapGenerator.prototype._validateMapping =
  9297. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  9298. aName) {
  9299. // When aOriginal is truthy but has empty values for .line and .column,
  9300. // it is most likely a programmer error. In this case we throw a very
  9301. // specific error message to try to guide them the right way.
  9302. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  9303. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  9304. throw new Error(
  9305. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  9306. 'the original mapping entirely and only map the generated position. If so, pass ' +
  9307. 'null for the original mapping instead of an object with empty or null values.'
  9308. );
  9309. }
  9310. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  9311. && aGenerated.line > 0 && aGenerated.column >= 0
  9312. && !aOriginal && !aSource && !aName) {
  9313. // Case 1.
  9314. return;
  9315. }
  9316. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  9317. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  9318. && aGenerated.line > 0 && aGenerated.column >= 0
  9319. && aOriginal.line > 0 && aOriginal.column >= 0
  9320. && aSource) {
  9321. // Cases 2 and 3.
  9322. return;
  9323. }
  9324. else {
  9325. throw new Error('Invalid mapping: ' + JSON.stringify({
  9326. generated: aGenerated,
  9327. source: aSource,
  9328. original: aOriginal,
  9329. name: aName
  9330. }));
  9331. }
  9332. };
  9333. /**
  9334. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  9335. * specified by the source map format.
  9336. */
  9337. SourceMapGenerator.prototype._serializeMappings =
  9338. function SourceMapGenerator_serializeMappings() {
  9339. var previousGeneratedColumn = 0;
  9340. var previousGeneratedLine = 1;
  9341. var previousOriginalColumn = 0;
  9342. var previousOriginalLine = 0;
  9343. var previousName = 0;
  9344. var previousSource = 0;
  9345. var result = '';
  9346. var next;
  9347. var mapping;
  9348. var nameIdx;
  9349. var sourceIdx;
  9350. var mappings = this._mappings.toArray();
  9351. for (var i = 0, len = mappings.length; i < len; i++) {
  9352. mapping = mappings[i];
  9353. next = '';
  9354. if (mapping.generatedLine !== previousGeneratedLine) {
  9355. previousGeneratedColumn = 0;
  9356. while (mapping.generatedLine !== previousGeneratedLine) {
  9357. next += ';';
  9358. previousGeneratedLine++;
  9359. }
  9360. }
  9361. else {
  9362. if (i > 0) {
  9363. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  9364. continue;
  9365. }
  9366. next += ',';
  9367. }
  9368. }
  9369. next += base64VLQ.encode(mapping.generatedColumn
  9370. - previousGeneratedColumn);
  9371. previousGeneratedColumn = mapping.generatedColumn;
  9372. if (mapping.source != null) {
  9373. sourceIdx = this._sources.indexOf(mapping.source);
  9374. next += base64VLQ.encode(sourceIdx - previousSource);
  9375. previousSource = sourceIdx;
  9376. // lines are stored 0-based in SourceMap spec version 3
  9377. next += base64VLQ.encode(mapping.originalLine - 1
  9378. - previousOriginalLine);
  9379. previousOriginalLine = mapping.originalLine - 1;
  9380. next += base64VLQ.encode(mapping.originalColumn
  9381. - previousOriginalColumn);
  9382. previousOriginalColumn = mapping.originalColumn;
  9383. if (mapping.name != null) {
  9384. nameIdx = this._names.indexOf(mapping.name);
  9385. next += base64VLQ.encode(nameIdx - previousName);
  9386. previousName = nameIdx;
  9387. }
  9388. }
  9389. result += next;
  9390. }
  9391. return result;
  9392. };
  9393. SourceMapGenerator.prototype._generateSourcesContent =
  9394. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  9395. return aSources.map(function (source) {
  9396. if (!this._sourcesContents) {
  9397. return null;
  9398. }
  9399. if (aSourceRoot != null) {
  9400. source = util.relative(aSourceRoot, source);
  9401. }
  9402. var key = util.toSetString(source);
  9403. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  9404. ? this._sourcesContents[key]
  9405. : null;
  9406. }, this);
  9407. };
  9408. /**
  9409. * Externalize the source map.
  9410. */
  9411. SourceMapGenerator.prototype.toJSON =
  9412. function SourceMapGenerator_toJSON() {
  9413. var map = {
  9414. version: this._version,
  9415. sources: this._sources.toArray(),
  9416. names: this._names.toArray(),
  9417. mappings: this._serializeMappings()
  9418. };
  9419. if (this._file != null) {
  9420. map.file = this._file;
  9421. }
  9422. if (this._sourceRoot != null) {
  9423. map.sourceRoot = this._sourceRoot;
  9424. }
  9425. if (this._sourcesContents) {
  9426. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  9427. }
  9428. return map;
  9429. };
  9430. /**
  9431. * Render the source map being generated to a string.
  9432. */
  9433. SourceMapGenerator.prototype.toString =
  9434. function SourceMapGenerator_toString() {
  9435. return JSON.stringify(this.toJSON());
  9436. };
  9437. sourceMapGenerator.SourceMapGenerator = SourceMapGenerator;
  9438. return sourceMapGenerator;
  9439. }
  9440. var sourceMapConsumer = {};
  9441. var binarySearch = {};
  9442. /* -*- Mode: js; js-indent-level: 2; -*- */
  9443. var hasRequiredBinarySearch;
  9444. function requireBinarySearch () {
  9445. if (hasRequiredBinarySearch) return binarySearch;
  9446. hasRequiredBinarySearch = 1;
  9447. (function (exports) {
  9448. /*
  9449. * Copyright 2011 Mozilla Foundation and contributors
  9450. * Licensed under the New BSD license. See LICENSE or:
  9451. * http://opensource.org/licenses/BSD-3-Clause
  9452. */
  9453. exports.GREATEST_LOWER_BOUND = 1;
  9454. exports.LEAST_UPPER_BOUND = 2;
  9455. /**
  9456. * Recursive implementation of binary search.
  9457. *
  9458. * @param aLow Indices here and lower do not contain the needle.
  9459. * @param aHigh Indices here and higher do not contain the needle.
  9460. * @param aNeedle The element being searched for.
  9461. * @param aHaystack The non-empty array being searched.
  9462. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  9463. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  9464. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  9465. * closest element that is smaller than or greater than the one we are
  9466. * searching for, respectively, if the exact element cannot be found.
  9467. */
  9468. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  9469. // This function terminates when one of the following is true:
  9470. //
  9471. // 1. We find the exact element we are looking for.
  9472. //
  9473. // 2. We did not find the exact element, but we can return the index of
  9474. // the next-closest element.
  9475. //
  9476. // 3. We did not find the exact element, and there is no next-closest
  9477. // element than the one we are searching for, so we return -1.
  9478. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  9479. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  9480. if (cmp === 0) {
  9481. // Found the element we are looking for.
  9482. return mid;
  9483. }
  9484. else if (cmp > 0) {
  9485. // Our needle is greater than aHaystack[mid].
  9486. if (aHigh - mid > 1) {
  9487. // The element is in the upper half.
  9488. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  9489. }
  9490. // The exact needle element was not found in this haystack. Determine if
  9491. // we are in termination case (3) or (2) and return the appropriate thing.
  9492. if (aBias == exports.LEAST_UPPER_BOUND) {
  9493. return aHigh < aHaystack.length ? aHigh : -1;
  9494. } else {
  9495. return mid;
  9496. }
  9497. }
  9498. else {
  9499. // Our needle is less than aHaystack[mid].
  9500. if (mid - aLow > 1) {
  9501. // The element is in the lower half.
  9502. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  9503. }
  9504. // we are in termination case (3) or (2) and return the appropriate thing.
  9505. if (aBias == exports.LEAST_UPPER_BOUND) {
  9506. return mid;
  9507. } else {
  9508. return aLow < 0 ? -1 : aLow;
  9509. }
  9510. }
  9511. }
  9512. /**
  9513. * This is an implementation of binary search which will always try and return
  9514. * the index of the closest element if there is no exact hit. This is because
  9515. * mappings between original and generated line/col pairs are single points,
  9516. * and there is an implicit region between each of them, so a miss just means
  9517. * that you aren't on the very start of a region.
  9518. *
  9519. * @param aNeedle The element you are looking for.
  9520. * @param aHaystack The array that is being searched.
  9521. * @param aCompare A function which takes the needle and an element in the
  9522. * array and returns -1, 0, or 1 depending on whether the needle is less
  9523. * than, equal to, or greater than the element, respectively.
  9524. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  9525. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  9526. * closest element that is smaller than or greater than the one we are
  9527. * searching for, respectively, if the exact element cannot be found.
  9528. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  9529. */
  9530. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  9531. if (aHaystack.length === 0) {
  9532. return -1;
  9533. }
  9534. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  9535. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  9536. if (index < 0) {
  9537. return -1;
  9538. }
  9539. // We have found either the exact element, or the next-closest element than
  9540. // the one we are searching for. However, there may be more than one such
  9541. // element. Make sure we always return the smallest of these.
  9542. while (index - 1 >= 0) {
  9543. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  9544. break;
  9545. }
  9546. --index;
  9547. }
  9548. return index;
  9549. };
  9550. } (binarySearch));
  9551. return binarySearch;
  9552. }
  9553. var quickSort = {};
  9554. /* -*- Mode: js; js-indent-level: 2; -*- */
  9555. var hasRequiredQuickSort;
  9556. function requireQuickSort () {
  9557. if (hasRequiredQuickSort) return quickSort;
  9558. hasRequiredQuickSort = 1;
  9559. /*
  9560. * Copyright 2011 Mozilla Foundation and contributors
  9561. * Licensed under the New BSD license. See LICENSE or:
  9562. * http://opensource.org/licenses/BSD-3-Clause
  9563. */
  9564. // It turns out that some (most?) JavaScript engines don't self-host
  9565. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  9566. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  9567. // custom comparator function, calling back and forth between the VM's C++ and
  9568. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  9569. // worse generated code for the comparator function than would be optimal. In
  9570. // fact, when sorting with a comparator, these costs outweigh the benefits of
  9571. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  9572. // a ~3500ms mean speed-up in `bench/bench.html`.
  9573. /**
  9574. * Swap the elements indexed by `x` and `y` in the array `ary`.
  9575. *
  9576. * @param {Array} ary
  9577. * The array.
  9578. * @param {Number} x
  9579. * The index of the first item.
  9580. * @param {Number} y
  9581. * The index of the second item.
  9582. */
  9583. function swap(ary, x, y) {
  9584. var temp = ary[x];
  9585. ary[x] = ary[y];
  9586. ary[y] = temp;
  9587. }
  9588. /**
  9589. * Returns a random integer within the range `low .. high` inclusive.
  9590. *
  9591. * @param {Number} low
  9592. * The lower bound on the range.
  9593. * @param {Number} high
  9594. * The upper bound on the range.
  9595. */
  9596. function randomIntInRange(low, high) {
  9597. return Math.round(low + (Math.random() * (high - low)));
  9598. }
  9599. /**
  9600. * The Quick Sort algorithm.
  9601. *
  9602. * @param {Array} ary
  9603. * An array to sort.
  9604. * @param {function} comparator
  9605. * Function to use to compare two items.
  9606. * @param {Number} p
  9607. * Start index of the array
  9608. * @param {Number} r
  9609. * End index of the array
  9610. */
  9611. function doQuickSort(ary, comparator, p, r) {
  9612. // If our lower bound is less than our upper bound, we (1) partition the
  9613. // array into two pieces and (2) recurse on each half. If it is not, this is
  9614. // the empty array and our base case.
  9615. if (p < r) {
  9616. // (1) Partitioning.
  9617. //
  9618. // The partitioning chooses a pivot between `p` and `r` and moves all
  9619. // elements that are less than or equal to the pivot to the before it, and
  9620. // all the elements that are greater than it after it. The effect is that
  9621. // once partition is done, the pivot is in the exact place it will be when
  9622. // the array is put in sorted order, and it will not need to be moved
  9623. // again. This runs in O(n) time.
  9624. // Always choose a random pivot so that an input array which is reverse
  9625. // sorted does not cause O(n^2) running time.
  9626. var pivotIndex = randomIntInRange(p, r);
  9627. var i = p - 1;
  9628. swap(ary, pivotIndex, r);
  9629. var pivot = ary[r];
  9630. // Immediately after `j` is incremented in this loop, the following hold
  9631. // true:
  9632. //
  9633. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  9634. //
  9635. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  9636. for (var j = p; j < r; j++) {
  9637. if (comparator(ary[j], pivot) <= 0) {
  9638. i += 1;
  9639. swap(ary, i, j);
  9640. }
  9641. }
  9642. swap(ary, i + 1, j);
  9643. var q = i + 1;
  9644. // (2) Recurse on each half.
  9645. doQuickSort(ary, comparator, p, q - 1);
  9646. doQuickSort(ary, comparator, q + 1, r);
  9647. }
  9648. }
  9649. /**
  9650. * Sort the given array in-place with the given comparator function.
  9651. *
  9652. * @param {Array} ary
  9653. * An array to sort.
  9654. * @param {function} comparator
  9655. * Function to use to compare two items.
  9656. */
  9657. quickSort.quickSort = function (ary, comparator) {
  9658. doQuickSort(ary, comparator, 0, ary.length - 1);
  9659. };
  9660. return quickSort;
  9661. }
  9662. /* -*- Mode: js; js-indent-level: 2; -*- */
  9663. var hasRequiredSourceMapConsumer;
  9664. function requireSourceMapConsumer () {
  9665. if (hasRequiredSourceMapConsumer) return sourceMapConsumer;
  9666. hasRequiredSourceMapConsumer = 1;
  9667. /*
  9668. * Copyright 2011 Mozilla Foundation and contributors
  9669. * Licensed under the New BSD license. See LICENSE or:
  9670. * http://opensource.org/licenses/BSD-3-Clause
  9671. */
  9672. var util = /*@__PURE__*/ requireUtil$1();
  9673. var binarySearch = /*@__PURE__*/ requireBinarySearch();
  9674. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  9675. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  9676. var quickSort = /*@__PURE__*/ requireQuickSort().quickSort;
  9677. function SourceMapConsumer(aSourceMap, aSourceMapURL) {
  9678. var sourceMap = aSourceMap;
  9679. if (typeof aSourceMap === 'string') {
  9680. sourceMap = util.parseSourceMapInput(aSourceMap);
  9681. }
  9682. return sourceMap.sections != null
  9683. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  9684. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  9685. }
  9686. SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  9687. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  9688. };
  9689. /**
  9690. * The version of the source mapping spec that we are consuming.
  9691. */
  9692. SourceMapConsumer.prototype._version = 3;
  9693. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  9694. // parsed mapping coordinates from the source map's "mappings" attribute. They
  9695. // are lazily instantiated, accessed via the `_generatedMappings` and
  9696. // `_originalMappings` getters respectively, and we only parse the mappings
  9697. // and create these arrays once queried for a source location. We jump through
  9698. // these hoops because there can be many thousands of mappings, and parsing
  9699. // them is expensive, so we only want to do it if we must.
  9700. //
  9701. // Each object in the arrays is of the form:
  9702. //
  9703. // {
  9704. // generatedLine: The line number in the generated code,
  9705. // generatedColumn: The column number in the generated code,
  9706. // source: The path to the original source file that generated this
  9707. // chunk of code,
  9708. // originalLine: The line number in the original source that
  9709. // corresponds to this chunk of generated code,
  9710. // originalColumn: The column number in the original source that
  9711. // corresponds to this chunk of generated code,
  9712. // name: The name of the original symbol which generated this chunk of
  9713. // code.
  9714. // }
  9715. //
  9716. // All properties except for `generatedLine` and `generatedColumn` can be
  9717. // `null`.
  9718. //
  9719. // `_generatedMappings` is ordered by the generated positions.
  9720. //
  9721. // `_originalMappings` is ordered by the original positions.
  9722. SourceMapConsumer.prototype.__generatedMappings = null;
  9723. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  9724. configurable: true,
  9725. enumerable: true,
  9726. get: function () {
  9727. if (!this.__generatedMappings) {
  9728. this._parseMappings(this._mappings, this.sourceRoot);
  9729. }
  9730. return this.__generatedMappings;
  9731. }
  9732. });
  9733. SourceMapConsumer.prototype.__originalMappings = null;
  9734. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  9735. configurable: true,
  9736. enumerable: true,
  9737. get: function () {
  9738. if (!this.__originalMappings) {
  9739. this._parseMappings(this._mappings, this.sourceRoot);
  9740. }
  9741. return this.__originalMappings;
  9742. }
  9743. });
  9744. SourceMapConsumer.prototype._charIsMappingSeparator =
  9745. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  9746. var c = aStr.charAt(index);
  9747. return c === ";" || c === ",";
  9748. };
  9749. /**
  9750. * Parse the mappings in a string in to a data structure which we can easily
  9751. * query (the ordered arrays in the `this.__generatedMappings` and
  9752. * `this.__originalMappings` properties).
  9753. */
  9754. SourceMapConsumer.prototype._parseMappings =
  9755. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9756. throw new Error("Subclasses must implement _parseMappings");
  9757. };
  9758. SourceMapConsumer.GENERATED_ORDER = 1;
  9759. SourceMapConsumer.ORIGINAL_ORDER = 2;
  9760. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  9761. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  9762. /**
  9763. * Iterate over each mapping between an original source/line/column and a
  9764. * generated line/column in this source map.
  9765. *
  9766. * @param Function aCallback
  9767. * The function that is called with each mapping.
  9768. * @param Object aContext
  9769. * Optional. If specified, this object will be the value of `this` every
  9770. * time that `aCallback` is called.
  9771. * @param aOrder
  9772. * Either `SourceMapConsumer.GENERATED_ORDER` or
  9773. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  9774. * iterate over the mappings sorted by the generated file's line/column
  9775. * order or the original's source/line/column order, respectively. Defaults to
  9776. * `SourceMapConsumer.GENERATED_ORDER`.
  9777. */
  9778. SourceMapConsumer.prototype.eachMapping =
  9779. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  9780. var context = aContext || null;
  9781. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  9782. var mappings;
  9783. switch (order) {
  9784. case SourceMapConsumer.GENERATED_ORDER:
  9785. mappings = this._generatedMappings;
  9786. break;
  9787. case SourceMapConsumer.ORIGINAL_ORDER:
  9788. mappings = this._originalMappings;
  9789. break;
  9790. default:
  9791. throw new Error("Unknown order of iteration.");
  9792. }
  9793. var sourceRoot = this.sourceRoot;
  9794. mappings.map(function (mapping) {
  9795. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  9796. source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  9797. return {
  9798. source: source,
  9799. generatedLine: mapping.generatedLine,
  9800. generatedColumn: mapping.generatedColumn,
  9801. originalLine: mapping.originalLine,
  9802. originalColumn: mapping.originalColumn,
  9803. name: mapping.name === null ? null : this._names.at(mapping.name)
  9804. };
  9805. }, this).forEach(aCallback, context);
  9806. };
  9807. /**
  9808. * Returns all generated line and column information for the original source,
  9809. * line, and column provided. If no column is provided, returns all mappings
  9810. * corresponding to a either the line we are searching for or the next
  9811. * closest line that has any mappings. Otherwise, returns all mappings
  9812. * corresponding to the given line and either the column we are searching for
  9813. * or the next closest column that has any offsets.
  9814. *
  9815. * The only argument is an object with the following properties:
  9816. *
  9817. * - source: The filename of the original source.
  9818. * - line: The line number in the original source. The line number is 1-based.
  9819. * - column: Optional. the column number in the original source.
  9820. * The column number is 0-based.
  9821. *
  9822. * and an array of objects is returned, each with the following properties:
  9823. *
  9824. * - line: The line number in the generated source, or null. The
  9825. * line number is 1-based.
  9826. * - column: The column number in the generated source, or null.
  9827. * The column number is 0-based.
  9828. */
  9829. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  9830. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  9831. var line = util.getArg(aArgs, 'line');
  9832. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  9833. // returns the index of the closest mapping less than the needle. By
  9834. // setting needle.originalColumn to 0, we thus find the last mapping for
  9835. // the given line, provided such a mapping exists.
  9836. var needle = {
  9837. source: util.getArg(aArgs, 'source'),
  9838. originalLine: line,
  9839. originalColumn: util.getArg(aArgs, 'column', 0)
  9840. };
  9841. needle.source = this._findSourceIndex(needle.source);
  9842. if (needle.source < 0) {
  9843. return [];
  9844. }
  9845. var mappings = [];
  9846. var index = this._findMapping(needle,
  9847. this._originalMappings,
  9848. "originalLine",
  9849. "originalColumn",
  9850. util.compareByOriginalPositions,
  9851. binarySearch.LEAST_UPPER_BOUND);
  9852. if (index >= 0) {
  9853. var mapping = this._originalMappings[index];
  9854. if (aArgs.column === undefined) {
  9855. var originalLine = mapping.originalLine;
  9856. // Iterate until either we run out of mappings, or we run into
  9857. // a mapping for a different line than the one we found. Since
  9858. // mappings are sorted, this is guaranteed to find all mappings for
  9859. // the line we found.
  9860. while (mapping && mapping.originalLine === originalLine) {
  9861. mappings.push({
  9862. line: util.getArg(mapping, 'generatedLine', null),
  9863. column: util.getArg(mapping, 'generatedColumn', null),
  9864. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9865. });
  9866. mapping = this._originalMappings[++index];
  9867. }
  9868. } else {
  9869. var originalColumn = mapping.originalColumn;
  9870. // Iterate until either we run out of mappings, or we run into
  9871. // a mapping for a different line than the one we were searching for.
  9872. // Since mappings are sorted, this is guaranteed to find all mappings for
  9873. // the line we are searching for.
  9874. while (mapping &&
  9875. mapping.originalLine === line &&
  9876. mapping.originalColumn == originalColumn) {
  9877. mappings.push({
  9878. line: util.getArg(mapping, 'generatedLine', null),
  9879. column: util.getArg(mapping, 'generatedColumn', null),
  9880. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9881. });
  9882. mapping = this._originalMappings[++index];
  9883. }
  9884. }
  9885. }
  9886. return mappings;
  9887. };
  9888. sourceMapConsumer.SourceMapConsumer = SourceMapConsumer;
  9889. /**
  9890. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  9891. * query for information about the original file positions by giving it a file
  9892. * position in the generated source.
  9893. *
  9894. * The first parameter is the raw source map (either as a JSON string, or
  9895. * already parsed to an object). According to the spec, source maps have the
  9896. * following attributes:
  9897. *
  9898. * - version: Which version of the source map spec this map is following.
  9899. * - sources: An array of URLs to the original source files.
  9900. * - names: An array of identifiers which can be referrenced by individual mappings.
  9901. * - sourceRoot: Optional. The URL root from which all sources are relative.
  9902. * - sourcesContent: Optional. An array of contents of the original source files.
  9903. * - mappings: A string of base64 VLQs which contain the actual mappings.
  9904. * - file: Optional. The generated file this source map is associated with.
  9905. *
  9906. * Here is an example source map, taken from the source map spec[0]:
  9907. *
  9908. * {
  9909. * version : 3,
  9910. * file: "out.js",
  9911. * sourceRoot : "",
  9912. * sources: ["foo.js", "bar.js"],
  9913. * names: ["src", "maps", "are", "fun"],
  9914. * mappings: "AA,AB;;ABCDE;"
  9915. * }
  9916. *
  9917. * The second parameter, if given, is a string whose value is the URL
  9918. * at which the source map was found. This URL is used to compute the
  9919. * sources array.
  9920. *
  9921. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  9922. */
  9923. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  9924. var sourceMap = aSourceMap;
  9925. if (typeof aSourceMap === 'string') {
  9926. sourceMap = util.parseSourceMapInput(aSourceMap);
  9927. }
  9928. var version = util.getArg(sourceMap, 'version');
  9929. var sources = util.getArg(sourceMap, 'sources');
  9930. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  9931. // requires the array) to play nice here.
  9932. var names = util.getArg(sourceMap, 'names', []);
  9933. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  9934. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  9935. var mappings = util.getArg(sourceMap, 'mappings');
  9936. var file = util.getArg(sourceMap, 'file', null);
  9937. // Once again, Sass deviates from the spec and supplies the version as a
  9938. // string rather than a number, so we use loose equality checking here.
  9939. if (version != this._version) {
  9940. throw new Error('Unsupported version: ' + version);
  9941. }
  9942. if (sourceRoot) {
  9943. sourceRoot = util.normalize(sourceRoot);
  9944. }
  9945. sources = sources
  9946. .map(String)
  9947. // Some source maps produce relative source paths like "./foo.js" instead of
  9948. // "foo.js". Normalize these first so that future comparisons will succeed.
  9949. // See bugzil.la/1090768.
  9950. .map(util.normalize)
  9951. // Always ensure that absolute sources are internally stored relative to
  9952. // the source root, if the source root is absolute. Not doing this would
  9953. // be particularly problematic when the source root is a prefix of the
  9954. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  9955. .map(function (source) {
  9956. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  9957. ? util.relative(sourceRoot, source)
  9958. : source;
  9959. });
  9960. // Pass `true` below to allow duplicate names and sources. While source maps
  9961. // are intended to be compressed and deduplicated, the TypeScript compiler
  9962. // sometimes generates source maps with duplicates in them. See Github issue
  9963. // #72 and bugzil.la/889492.
  9964. this._names = ArraySet.fromArray(names.map(String), true);
  9965. this._sources = ArraySet.fromArray(sources, true);
  9966. this._absoluteSources = this._sources.toArray().map(function (s) {
  9967. return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
  9968. });
  9969. this.sourceRoot = sourceRoot;
  9970. this.sourcesContent = sourcesContent;
  9971. this._mappings = mappings;
  9972. this._sourceMapURL = aSourceMapURL;
  9973. this.file = file;
  9974. }
  9975. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  9976. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  9977. /**
  9978. * Utility function to find the index of a source. Returns -1 if not
  9979. * found.
  9980. */
  9981. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  9982. var relativeSource = aSource;
  9983. if (this.sourceRoot != null) {
  9984. relativeSource = util.relative(this.sourceRoot, relativeSource);
  9985. }
  9986. if (this._sources.has(relativeSource)) {
  9987. return this._sources.indexOf(relativeSource);
  9988. }
  9989. // Maybe aSource is an absolute URL as returned by |sources|. In
  9990. // this case we can't simply undo the transform.
  9991. var i;
  9992. for (i = 0; i < this._absoluteSources.length; ++i) {
  9993. if (this._absoluteSources[i] == aSource) {
  9994. return i;
  9995. }
  9996. }
  9997. return -1;
  9998. };
  9999. /**
  10000. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  10001. *
  10002. * @param SourceMapGenerator aSourceMap
  10003. * The source map that will be consumed.
  10004. * @param String aSourceMapURL
  10005. * The URL at which the source map can be found (optional)
  10006. * @returns BasicSourceMapConsumer
  10007. */
  10008. BasicSourceMapConsumer.fromSourceMap =
  10009. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  10010. var smc = Object.create(BasicSourceMapConsumer.prototype);
  10011. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  10012. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  10013. smc.sourceRoot = aSourceMap._sourceRoot;
  10014. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  10015. smc.sourceRoot);
  10016. smc.file = aSourceMap._file;
  10017. smc._sourceMapURL = aSourceMapURL;
  10018. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  10019. return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  10020. });
  10021. // Because we are modifying the entries (by converting string sources and
  10022. // names to indices into the sources and names ArraySets), we have to make
  10023. // a copy of the entry or else bad things happen. Shared mutable state
  10024. // strikes again! See github issue #191.
  10025. var generatedMappings = aSourceMap._mappings.toArray().slice();
  10026. var destGeneratedMappings = smc.__generatedMappings = [];
  10027. var destOriginalMappings = smc.__originalMappings = [];
  10028. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  10029. var srcMapping = generatedMappings[i];
  10030. var destMapping = new Mapping;
  10031. destMapping.generatedLine = srcMapping.generatedLine;
  10032. destMapping.generatedColumn = srcMapping.generatedColumn;
  10033. if (srcMapping.source) {
  10034. destMapping.source = sources.indexOf(srcMapping.source);
  10035. destMapping.originalLine = srcMapping.originalLine;
  10036. destMapping.originalColumn = srcMapping.originalColumn;
  10037. if (srcMapping.name) {
  10038. destMapping.name = names.indexOf(srcMapping.name);
  10039. }
  10040. destOriginalMappings.push(destMapping);
  10041. }
  10042. destGeneratedMappings.push(destMapping);
  10043. }
  10044. quickSort(smc.__originalMappings, util.compareByOriginalPositions);
  10045. return smc;
  10046. };
  10047. /**
  10048. * The version of the source mapping spec that we are consuming.
  10049. */
  10050. BasicSourceMapConsumer.prototype._version = 3;
  10051. /**
  10052. * The list of original sources.
  10053. */
  10054. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  10055. get: function () {
  10056. return this._absoluteSources.slice();
  10057. }
  10058. });
  10059. /**
  10060. * Provide the JIT with a nice shape / hidden class.
  10061. */
  10062. function Mapping() {
  10063. this.generatedLine = 0;
  10064. this.generatedColumn = 0;
  10065. this.source = null;
  10066. this.originalLine = null;
  10067. this.originalColumn = null;
  10068. this.name = null;
  10069. }
  10070. /**
  10071. * Parse the mappings in a string in to a data structure which we can easily
  10072. * query (the ordered arrays in the `this.__generatedMappings` and
  10073. * `this.__originalMappings` properties).
  10074. */
  10075. BasicSourceMapConsumer.prototype._parseMappings =
  10076. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  10077. var generatedLine = 1;
  10078. var previousGeneratedColumn = 0;
  10079. var previousOriginalLine = 0;
  10080. var previousOriginalColumn = 0;
  10081. var previousSource = 0;
  10082. var previousName = 0;
  10083. var length = aStr.length;
  10084. var index = 0;
  10085. var cachedSegments = {};
  10086. var temp = {};
  10087. var originalMappings = [];
  10088. var generatedMappings = [];
  10089. var mapping, str, segment, end, value;
  10090. while (index < length) {
  10091. if (aStr.charAt(index) === ';') {
  10092. generatedLine++;
  10093. index++;
  10094. previousGeneratedColumn = 0;
  10095. }
  10096. else if (aStr.charAt(index) === ',') {
  10097. index++;
  10098. }
  10099. else {
  10100. mapping = new Mapping();
  10101. mapping.generatedLine = generatedLine;
  10102. // Because each offset is encoded relative to the previous one,
  10103. // many segments often have the same encoding. We can exploit this
  10104. // fact by caching the parsed variable length fields of each segment,
  10105. // allowing us to avoid a second parse if we encounter the same
  10106. // segment again.
  10107. for (end = index; end < length; end++) {
  10108. if (this._charIsMappingSeparator(aStr, end)) {
  10109. break;
  10110. }
  10111. }
  10112. str = aStr.slice(index, end);
  10113. segment = cachedSegments[str];
  10114. if (segment) {
  10115. index += str.length;
  10116. } else {
  10117. segment = [];
  10118. while (index < end) {
  10119. base64VLQ.decode(aStr, index, temp);
  10120. value = temp.value;
  10121. index = temp.rest;
  10122. segment.push(value);
  10123. }
  10124. if (segment.length === 2) {
  10125. throw new Error('Found a source, but no line and column');
  10126. }
  10127. if (segment.length === 3) {
  10128. throw new Error('Found a source and line, but no column');
  10129. }
  10130. cachedSegments[str] = segment;
  10131. }
  10132. // Generated column.
  10133. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  10134. previousGeneratedColumn = mapping.generatedColumn;
  10135. if (segment.length > 1) {
  10136. // Original source.
  10137. mapping.source = previousSource + segment[1];
  10138. previousSource += segment[1];
  10139. // Original line.
  10140. mapping.originalLine = previousOriginalLine + segment[2];
  10141. previousOriginalLine = mapping.originalLine;
  10142. // Lines are stored 0-based
  10143. mapping.originalLine += 1;
  10144. // Original column.
  10145. mapping.originalColumn = previousOriginalColumn + segment[3];
  10146. previousOriginalColumn = mapping.originalColumn;
  10147. if (segment.length > 4) {
  10148. // Original name.
  10149. mapping.name = previousName + segment[4];
  10150. previousName += segment[4];
  10151. }
  10152. }
  10153. generatedMappings.push(mapping);
  10154. if (typeof mapping.originalLine === 'number') {
  10155. originalMappings.push(mapping);
  10156. }
  10157. }
  10158. }
  10159. quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
  10160. this.__generatedMappings = generatedMappings;
  10161. quickSort(originalMappings, util.compareByOriginalPositions);
  10162. this.__originalMappings = originalMappings;
  10163. };
  10164. /**
  10165. * Find the mapping that best matches the hypothetical "needle" mapping that
  10166. * we are searching for in the given "haystack" of mappings.
  10167. */
  10168. BasicSourceMapConsumer.prototype._findMapping =
  10169. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  10170. aColumnName, aComparator, aBias) {
  10171. // To return the position we are searching for, we must first find the
  10172. // mapping for the given position and then return the opposite position it
  10173. // points to. Because the mappings are sorted, we can use binary search to
  10174. // find the best mapping.
  10175. if (aNeedle[aLineName] <= 0) {
  10176. throw new TypeError('Line must be greater than or equal to 1, got '
  10177. + aNeedle[aLineName]);
  10178. }
  10179. if (aNeedle[aColumnName] < 0) {
  10180. throw new TypeError('Column must be greater than or equal to 0, got '
  10181. + aNeedle[aColumnName]);
  10182. }
  10183. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  10184. };
  10185. /**
  10186. * Compute the last column for each generated mapping. The last column is
  10187. * inclusive.
  10188. */
  10189. BasicSourceMapConsumer.prototype.computeColumnSpans =
  10190. function SourceMapConsumer_computeColumnSpans() {
  10191. for (var index = 0; index < this._generatedMappings.length; ++index) {
  10192. var mapping = this._generatedMappings[index];
  10193. // Mappings do not contain a field for the last generated columnt. We
  10194. // can come up with an optimistic estimate, however, by assuming that
  10195. // mappings are contiguous (i.e. given two consecutive mappings, the
  10196. // first mapping ends where the second one starts).
  10197. if (index + 1 < this._generatedMappings.length) {
  10198. var nextMapping = this._generatedMappings[index + 1];
  10199. if (mapping.generatedLine === nextMapping.generatedLine) {
  10200. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  10201. continue;
  10202. }
  10203. }
  10204. // The last mapping for each line spans the entire line.
  10205. mapping.lastGeneratedColumn = Infinity;
  10206. }
  10207. };
  10208. /**
  10209. * Returns the original source, line, and column information for the generated
  10210. * source's line and column positions provided. The only argument is an object
  10211. * with the following properties:
  10212. *
  10213. * - line: The line number in the generated source. The line number
  10214. * is 1-based.
  10215. * - column: The column number in the generated source. The column
  10216. * number is 0-based.
  10217. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  10218. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  10219. * closest element that is smaller than or greater than the one we are
  10220. * searching for, respectively, if the exact element cannot be found.
  10221. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  10222. *
  10223. * and an object is returned with the following properties:
  10224. *
  10225. * - source: The original source file, or null.
  10226. * - line: The line number in the original source, or null. The
  10227. * line number is 1-based.
  10228. * - column: The column number in the original source, or null. The
  10229. * column number is 0-based.
  10230. * - name: The original identifier, or null.
  10231. */
  10232. BasicSourceMapConsumer.prototype.originalPositionFor =
  10233. function SourceMapConsumer_originalPositionFor(aArgs) {
  10234. var needle = {
  10235. generatedLine: util.getArg(aArgs, 'line'),
  10236. generatedColumn: util.getArg(aArgs, 'column')
  10237. };
  10238. var index = this._findMapping(
  10239. needle,
  10240. this._generatedMappings,
  10241. "generatedLine",
  10242. "generatedColumn",
  10243. util.compareByGeneratedPositionsDeflated,
  10244. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  10245. );
  10246. if (index >= 0) {
  10247. var mapping = this._generatedMappings[index];
  10248. if (mapping.generatedLine === needle.generatedLine) {
  10249. var source = util.getArg(mapping, 'source', null);
  10250. if (source !== null) {
  10251. source = this._sources.at(source);
  10252. source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  10253. }
  10254. var name = util.getArg(mapping, 'name', null);
  10255. if (name !== null) {
  10256. name = this._names.at(name);
  10257. }
  10258. return {
  10259. source: source,
  10260. line: util.getArg(mapping, 'originalLine', null),
  10261. column: util.getArg(mapping, 'originalColumn', null),
  10262. name: name
  10263. };
  10264. }
  10265. }
  10266. return {
  10267. source: null,
  10268. line: null,
  10269. column: null,
  10270. name: null
  10271. };
  10272. };
  10273. /**
  10274. * Return true if we have the source content for every source in the source
  10275. * map, false otherwise.
  10276. */
  10277. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  10278. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  10279. if (!this.sourcesContent) {
  10280. return false;
  10281. }
  10282. return this.sourcesContent.length >= this._sources.size() &&
  10283. !this.sourcesContent.some(function (sc) { return sc == null; });
  10284. };
  10285. /**
  10286. * Returns the original source content. The only argument is the url of the
  10287. * original source file. Returns null if no original source content is
  10288. * available.
  10289. */
  10290. BasicSourceMapConsumer.prototype.sourceContentFor =
  10291. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  10292. if (!this.sourcesContent) {
  10293. return null;
  10294. }
  10295. var index = this._findSourceIndex(aSource);
  10296. if (index >= 0) {
  10297. return this.sourcesContent[index];
  10298. }
  10299. var relativeSource = aSource;
  10300. if (this.sourceRoot != null) {
  10301. relativeSource = util.relative(this.sourceRoot, relativeSource);
  10302. }
  10303. var url;
  10304. if (this.sourceRoot != null
  10305. && (url = util.urlParse(this.sourceRoot))) {
  10306. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  10307. // many users. We can help them out when they expect file:// URIs to
  10308. // behave like it would if they were running a local HTTP server. See
  10309. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  10310. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  10311. if (url.scheme == "file"
  10312. && this._sources.has(fileUriAbsPath)) {
  10313. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  10314. }
  10315. if ((!url.path || url.path == "/")
  10316. && this._sources.has("/" + relativeSource)) {
  10317. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  10318. }
  10319. }
  10320. // This function is used recursively from
  10321. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  10322. // don't want to throw if we can't find the source - we just want to
  10323. // return null, so we provide a flag to exit gracefully.
  10324. if (nullOnMissing) {
  10325. return null;
  10326. }
  10327. else {
  10328. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  10329. }
  10330. };
  10331. /**
  10332. * Returns the generated line and column information for the original source,
  10333. * line, and column positions provided. The only argument is an object with
  10334. * the following properties:
  10335. *
  10336. * - source: The filename of the original source.
  10337. * - line: The line number in the original source. The line number
  10338. * is 1-based.
  10339. * - column: The column number in the original source. The column
  10340. * number is 0-based.
  10341. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  10342. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  10343. * closest element that is smaller than or greater than the one we are
  10344. * searching for, respectively, if the exact element cannot be found.
  10345. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  10346. *
  10347. * and an object is returned with the following properties:
  10348. *
  10349. * - line: The line number in the generated source, or null. The
  10350. * line number is 1-based.
  10351. * - column: The column number in the generated source, or null.
  10352. * The column number is 0-based.
  10353. */
  10354. BasicSourceMapConsumer.prototype.generatedPositionFor =
  10355. function SourceMapConsumer_generatedPositionFor(aArgs) {
  10356. var source = util.getArg(aArgs, 'source');
  10357. source = this._findSourceIndex(source);
  10358. if (source < 0) {
  10359. return {
  10360. line: null,
  10361. column: null,
  10362. lastColumn: null
  10363. };
  10364. }
  10365. var needle = {
  10366. source: source,
  10367. originalLine: util.getArg(aArgs, 'line'),
  10368. originalColumn: util.getArg(aArgs, 'column')
  10369. };
  10370. var index = this._findMapping(
  10371. needle,
  10372. this._originalMappings,
  10373. "originalLine",
  10374. "originalColumn",
  10375. util.compareByOriginalPositions,
  10376. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  10377. );
  10378. if (index >= 0) {
  10379. var mapping = this._originalMappings[index];
  10380. if (mapping.source === needle.source) {
  10381. return {
  10382. line: util.getArg(mapping, 'generatedLine', null),
  10383. column: util.getArg(mapping, 'generatedColumn', null),
  10384. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  10385. };
  10386. }
  10387. }
  10388. return {
  10389. line: null,
  10390. column: null,
  10391. lastColumn: null
  10392. };
  10393. };
  10394. sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer;
  10395. /**
  10396. * An IndexedSourceMapConsumer instance represents a parsed source map which
  10397. * we can query for information. It differs from BasicSourceMapConsumer in
  10398. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  10399. * input.
  10400. *
  10401. * The first parameter is a raw source map (either as a JSON string, or already
  10402. * parsed to an object). According to the spec for indexed source maps, they
  10403. * have the following attributes:
  10404. *
  10405. * - version: Which version of the source map spec this map is following.
  10406. * - file: Optional. The generated file this source map is associated with.
  10407. * - sections: A list of section definitions.
  10408. *
  10409. * Each value under the "sections" field has two fields:
  10410. * - offset: The offset into the original specified at which this section
  10411. * begins to apply, defined as an object with a "line" and "column"
  10412. * field.
  10413. * - map: A source map definition. This source map could also be indexed,
  10414. * but doesn't have to be.
  10415. *
  10416. * Instead of the "map" field, it's also possible to have a "url" field
  10417. * specifying a URL to retrieve a source map from, but that's currently
  10418. * unsupported.
  10419. *
  10420. * Here's an example source map, taken from the source map spec[0], but
  10421. * modified to omit a section which uses the "url" field.
  10422. *
  10423. * {
  10424. * version : 3,
  10425. * file: "app.js",
  10426. * sections: [{
  10427. * offset: {line:100, column:10},
  10428. * map: {
  10429. * version : 3,
  10430. * file: "section.js",
  10431. * sources: ["foo.js", "bar.js"],
  10432. * names: ["src", "maps", "are", "fun"],
  10433. * mappings: "AAAA,E;;ABCDE;"
  10434. * }
  10435. * }],
  10436. * }
  10437. *
  10438. * The second parameter, if given, is a string whose value is the URL
  10439. * at which the source map was found. This URL is used to compute the
  10440. * sources array.
  10441. *
  10442. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  10443. */
  10444. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  10445. var sourceMap = aSourceMap;
  10446. if (typeof aSourceMap === 'string') {
  10447. sourceMap = util.parseSourceMapInput(aSourceMap);
  10448. }
  10449. var version = util.getArg(sourceMap, 'version');
  10450. var sections = util.getArg(sourceMap, 'sections');
  10451. if (version != this._version) {
  10452. throw new Error('Unsupported version: ' + version);
  10453. }
  10454. this._sources = new ArraySet();
  10455. this._names = new ArraySet();
  10456. var lastOffset = {
  10457. line: -1,
  10458. column: 0
  10459. };
  10460. this._sections = sections.map(function (s) {
  10461. if (s.url) {
  10462. // The url field will require support for asynchronicity.
  10463. // See https://github.com/mozilla/source-map/issues/16
  10464. throw new Error('Support for url field in sections not implemented.');
  10465. }
  10466. var offset = util.getArg(s, 'offset');
  10467. var offsetLine = util.getArg(offset, 'line');
  10468. var offsetColumn = util.getArg(offset, 'column');
  10469. if (offsetLine < lastOffset.line ||
  10470. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  10471. throw new Error('Section offsets must be ordered and non-overlapping.');
  10472. }
  10473. lastOffset = offset;
  10474. return {
  10475. generatedOffset: {
  10476. // The offset fields are 0-based, but we use 1-based indices when
  10477. // encoding/decoding from VLQ.
  10478. generatedLine: offsetLine + 1,
  10479. generatedColumn: offsetColumn + 1
  10480. },
  10481. consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
  10482. }
  10483. });
  10484. }
  10485. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  10486. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  10487. /**
  10488. * The version of the source mapping spec that we are consuming.
  10489. */
  10490. IndexedSourceMapConsumer.prototype._version = 3;
  10491. /**
  10492. * The list of original sources.
  10493. */
  10494. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  10495. get: function () {
  10496. var sources = [];
  10497. for (var i = 0; i < this._sections.length; i++) {
  10498. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  10499. sources.push(this._sections[i].consumer.sources[j]);
  10500. }
  10501. }
  10502. return sources;
  10503. }
  10504. });
  10505. /**
  10506. * Returns the original source, line, and column information for the generated
  10507. * source's line and column positions provided. The only argument is an object
  10508. * with the following properties:
  10509. *
  10510. * - line: The line number in the generated source. The line number
  10511. * is 1-based.
  10512. * - column: The column number in the generated source. The column
  10513. * number is 0-based.
  10514. *
  10515. * and an object is returned with the following properties:
  10516. *
  10517. * - source: The original source file, or null.
  10518. * - line: The line number in the original source, or null. The
  10519. * line number is 1-based.
  10520. * - column: The column number in the original source, or null. The
  10521. * column number is 0-based.
  10522. * - name: The original identifier, or null.
  10523. */
  10524. IndexedSourceMapConsumer.prototype.originalPositionFor =
  10525. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  10526. var needle = {
  10527. generatedLine: util.getArg(aArgs, 'line'),
  10528. generatedColumn: util.getArg(aArgs, 'column')
  10529. };
  10530. // Find the section containing the generated position we're trying to map
  10531. // to an original position.
  10532. var sectionIndex = binarySearch.search(needle, this._sections,
  10533. function(needle, section) {
  10534. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  10535. if (cmp) {
  10536. return cmp;
  10537. }
  10538. return (needle.generatedColumn -
  10539. section.generatedOffset.generatedColumn);
  10540. });
  10541. var section = this._sections[sectionIndex];
  10542. if (!section) {
  10543. return {
  10544. source: null,
  10545. line: null,
  10546. column: null,
  10547. name: null
  10548. };
  10549. }
  10550. return section.consumer.originalPositionFor({
  10551. line: needle.generatedLine -
  10552. (section.generatedOffset.generatedLine - 1),
  10553. column: needle.generatedColumn -
  10554. (section.generatedOffset.generatedLine === needle.generatedLine
  10555. ? section.generatedOffset.generatedColumn - 1
  10556. : 0),
  10557. bias: aArgs.bias
  10558. });
  10559. };
  10560. /**
  10561. * Return true if we have the source content for every source in the source
  10562. * map, false otherwise.
  10563. */
  10564. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  10565. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  10566. return this._sections.every(function (s) {
  10567. return s.consumer.hasContentsOfAllSources();
  10568. });
  10569. };
  10570. /**
  10571. * Returns the original source content. The only argument is the url of the
  10572. * original source file. Returns null if no original source content is
  10573. * available.
  10574. */
  10575. IndexedSourceMapConsumer.prototype.sourceContentFor =
  10576. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  10577. for (var i = 0; i < this._sections.length; i++) {
  10578. var section = this._sections[i];
  10579. var content = section.consumer.sourceContentFor(aSource, true);
  10580. if (content) {
  10581. return content;
  10582. }
  10583. }
  10584. if (nullOnMissing) {
  10585. return null;
  10586. }
  10587. else {
  10588. throw new Error('"' + aSource + '" is not in the SourceMap.');
  10589. }
  10590. };
  10591. /**
  10592. * Returns the generated line and column information for the original source,
  10593. * line, and column positions provided. The only argument is an object with
  10594. * the following properties:
  10595. *
  10596. * - source: The filename of the original source.
  10597. * - line: The line number in the original source. The line number
  10598. * is 1-based.
  10599. * - column: The column number in the original source. The column
  10600. * number is 0-based.
  10601. *
  10602. * and an object is returned with the following properties:
  10603. *
  10604. * - line: The line number in the generated source, or null. The
  10605. * line number is 1-based.
  10606. * - column: The column number in the generated source, or null.
  10607. * The column number is 0-based.
  10608. */
  10609. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  10610. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  10611. for (var i = 0; i < this._sections.length; i++) {
  10612. var section = this._sections[i];
  10613. // Only consider this section if the requested source is in the list of
  10614. // sources of the consumer.
  10615. if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
  10616. continue;
  10617. }
  10618. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  10619. if (generatedPosition) {
  10620. var ret = {
  10621. line: generatedPosition.line +
  10622. (section.generatedOffset.generatedLine - 1),
  10623. column: generatedPosition.column +
  10624. (section.generatedOffset.generatedLine === generatedPosition.line
  10625. ? section.generatedOffset.generatedColumn - 1
  10626. : 0)
  10627. };
  10628. return ret;
  10629. }
  10630. }
  10631. return {
  10632. line: null,
  10633. column: null
  10634. };
  10635. };
  10636. /**
  10637. * Parse the mappings in a string in to a data structure which we can easily
  10638. * query (the ordered arrays in the `this.__generatedMappings` and
  10639. * `this.__originalMappings` properties).
  10640. */
  10641. IndexedSourceMapConsumer.prototype._parseMappings =
  10642. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  10643. this.__generatedMappings = [];
  10644. this.__originalMappings = [];
  10645. for (var i = 0; i < this._sections.length; i++) {
  10646. var section = this._sections[i];
  10647. var sectionMappings = section.consumer._generatedMappings;
  10648. for (var j = 0; j < sectionMappings.length; j++) {
  10649. var mapping = sectionMappings[j];
  10650. var source = section.consumer._sources.at(mapping.source);
  10651. source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  10652. this._sources.add(source);
  10653. source = this._sources.indexOf(source);
  10654. var name = null;
  10655. if (mapping.name) {
  10656. name = section.consumer._names.at(mapping.name);
  10657. this._names.add(name);
  10658. name = this._names.indexOf(name);
  10659. }
  10660. // The mappings coming from the consumer for the section have
  10661. // generated positions relative to the start of the section, so we
  10662. // need to offset them to be relative to the start of the concatenated
  10663. // generated file.
  10664. var adjustedMapping = {
  10665. source: source,
  10666. generatedLine: mapping.generatedLine +
  10667. (section.generatedOffset.generatedLine - 1),
  10668. generatedColumn: mapping.generatedColumn +
  10669. (section.generatedOffset.generatedLine === mapping.generatedLine
  10670. ? section.generatedOffset.generatedColumn - 1
  10671. : 0),
  10672. originalLine: mapping.originalLine,
  10673. originalColumn: mapping.originalColumn,
  10674. name: name
  10675. };
  10676. this.__generatedMappings.push(adjustedMapping);
  10677. if (typeof adjustedMapping.originalLine === 'number') {
  10678. this.__originalMappings.push(adjustedMapping);
  10679. }
  10680. }
  10681. }
  10682. quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  10683. quickSort(this.__originalMappings, util.compareByOriginalPositions);
  10684. };
  10685. sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  10686. return sourceMapConsumer;
  10687. }
  10688. var sourceNode = {};
  10689. /* -*- Mode: js; js-indent-level: 2; -*- */
  10690. var hasRequiredSourceNode;
  10691. function requireSourceNode () {
  10692. if (hasRequiredSourceNode) return sourceNode;
  10693. hasRequiredSourceNode = 1;
  10694. /*
  10695. * Copyright 2011 Mozilla Foundation and contributors
  10696. * Licensed under the New BSD license. See LICENSE or:
  10697. * http://opensource.org/licenses/BSD-3-Clause
  10698. */
  10699. var SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  10700. var util = /*@__PURE__*/ requireUtil$1();
  10701. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  10702. // operating systems these days (capturing the result).
  10703. var REGEX_NEWLINE = /(\r?\n)/;
  10704. // Newline character code for charCodeAt() comparisons
  10705. var NEWLINE_CODE = 10;
  10706. // Private symbol for identifying `SourceNode`s when multiple versions of
  10707. // the source-map library are loaded. This MUST NOT CHANGE across
  10708. // versions!
  10709. var isSourceNode = "$$$isSourceNode$$$";
  10710. /**
  10711. * SourceNodes provide a way to abstract over interpolating/concatenating
  10712. * snippets of generated JavaScript source code while maintaining the line and
  10713. * column information associated with the original source code.
  10714. *
  10715. * @param aLine The original line number.
  10716. * @param aColumn The original column number.
  10717. * @param aSource The original source's filename.
  10718. * @param aChunks Optional. An array of strings which are snippets of
  10719. * generated JS, or other SourceNodes.
  10720. * @param aName The original identifier.
  10721. */
  10722. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  10723. this.children = [];
  10724. this.sourceContents = {};
  10725. this.line = aLine == null ? null : aLine;
  10726. this.column = aColumn == null ? null : aColumn;
  10727. this.source = aSource == null ? null : aSource;
  10728. this.name = aName == null ? null : aName;
  10729. this[isSourceNode] = true;
  10730. if (aChunks != null) this.add(aChunks);
  10731. }
  10732. /**
  10733. * Creates a SourceNode from generated code and a SourceMapConsumer.
  10734. *
  10735. * @param aGeneratedCode The generated code
  10736. * @param aSourceMapConsumer The SourceMap for the generated code
  10737. * @param aRelativePath Optional. The path that relative sources in the
  10738. * SourceMapConsumer should be relative to.
  10739. */
  10740. SourceNode.fromStringWithSourceMap =
  10741. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  10742. // The SourceNode we want to fill with the generated code
  10743. // and the SourceMap
  10744. var node = new SourceNode();
  10745. // All even indices of this array are one line of the generated code,
  10746. // while all odd indices are the newlines between two adjacent lines
  10747. // (since `REGEX_NEWLINE` captures its match).
  10748. // Processed fragments are accessed by calling `shiftNextLine`.
  10749. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  10750. var remainingLinesIndex = 0;
  10751. var shiftNextLine = function() {
  10752. var lineContents = getNextLine();
  10753. // The last line of a file might not have a newline.
  10754. var newLine = getNextLine() || "";
  10755. return lineContents + newLine;
  10756. function getNextLine() {
  10757. return remainingLinesIndex < remainingLines.length ?
  10758. remainingLines[remainingLinesIndex++] : undefined;
  10759. }
  10760. };
  10761. // We need to remember the position of "remainingLines"
  10762. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  10763. // The generate SourceNodes we need a code range.
  10764. // To extract it current and last mapping is used.
  10765. // Here we store the last mapping.
  10766. var lastMapping = null;
  10767. aSourceMapConsumer.eachMapping(function (mapping) {
  10768. if (lastMapping !== null) {
  10769. // We add the code from "lastMapping" to "mapping":
  10770. // First check if there is a new line in between.
  10771. if (lastGeneratedLine < mapping.generatedLine) {
  10772. // Associate first line with "lastMapping"
  10773. addMappingWithCode(lastMapping, shiftNextLine());
  10774. lastGeneratedLine++;
  10775. lastGeneratedColumn = 0;
  10776. // The remaining code is added without mapping
  10777. } else {
  10778. // There is no new line in between.
  10779. // Associate the code between "lastGeneratedColumn" and
  10780. // "mapping.generatedColumn" with "lastMapping"
  10781. var nextLine = remainingLines[remainingLinesIndex] || '';
  10782. var code = nextLine.substr(0, mapping.generatedColumn -
  10783. lastGeneratedColumn);
  10784. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  10785. lastGeneratedColumn);
  10786. lastGeneratedColumn = mapping.generatedColumn;
  10787. addMappingWithCode(lastMapping, code);
  10788. // No more remaining code, continue
  10789. lastMapping = mapping;
  10790. return;
  10791. }
  10792. }
  10793. // We add the generated code until the first mapping
  10794. // to the SourceNode without any mapping.
  10795. // Each line is added as separate string.
  10796. while (lastGeneratedLine < mapping.generatedLine) {
  10797. node.add(shiftNextLine());
  10798. lastGeneratedLine++;
  10799. }
  10800. if (lastGeneratedColumn < mapping.generatedColumn) {
  10801. var nextLine = remainingLines[remainingLinesIndex] || '';
  10802. node.add(nextLine.substr(0, mapping.generatedColumn));
  10803. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  10804. lastGeneratedColumn = mapping.generatedColumn;
  10805. }
  10806. lastMapping = mapping;
  10807. }, this);
  10808. // We have processed all mappings.
  10809. if (remainingLinesIndex < remainingLines.length) {
  10810. if (lastMapping) {
  10811. // Associate the remaining code in the current line with "lastMapping"
  10812. addMappingWithCode(lastMapping, shiftNextLine());
  10813. }
  10814. // and add the remaining lines without any mapping
  10815. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  10816. }
  10817. // Copy sourcesContent into SourceNode
  10818. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  10819. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  10820. if (content != null) {
  10821. if (aRelativePath != null) {
  10822. sourceFile = util.join(aRelativePath, sourceFile);
  10823. }
  10824. node.setSourceContent(sourceFile, content);
  10825. }
  10826. });
  10827. return node;
  10828. function addMappingWithCode(mapping, code) {
  10829. if (mapping === null || mapping.source === undefined) {
  10830. node.add(code);
  10831. } else {
  10832. var source = aRelativePath
  10833. ? util.join(aRelativePath, mapping.source)
  10834. : mapping.source;
  10835. node.add(new SourceNode(mapping.originalLine,
  10836. mapping.originalColumn,
  10837. source,
  10838. code,
  10839. mapping.name));
  10840. }
  10841. }
  10842. };
  10843. /**
  10844. * Add a chunk of generated JS to this source node.
  10845. *
  10846. * @param aChunk A string snippet of generated JS code, another instance of
  10847. * SourceNode, or an array where each member is one of those things.
  10848. */
  10849. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  10850. if (Array.isArray(aChunk)) {
  10851. aChunk.forEach(function (chunk) {
  10852. this.add(chunk);
  10853. }, this);
  10854. }
  10855. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10856. if (aChunk) {
  10857. this.children.push(aChunk);
  10858. }
  10859. }
  10860. else {
  10861. throw new TypeError(
  10862. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10863. );
  10864. }
  10865. return this;
  10866. };
  10867. /**
  10868. * Add a chunk of generated JS to the beginning of this source node.
  10869. *
  10870. * @param aChunk A string snippet of generated JS code, another instance of
  10871. * SourceNode, or an array where each member is one of those things.
  10872. */
  10873. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  10874. if (Array.isArray(aChunk)) {
  10875. for (var i = aChunk.length-1; i >= 0; i--) {
  10876. this.prepend(aChunk[i]);
  10877. }
  10878. }
  10879. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10880. this.children.unshift(aChunk);
  10881. }
  10882. else {
  10883. throw new TypeError(
  10884. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10885. );
  10886. }
  10887. return this;
  10888. };
  10889. /**
  10890. * Walk over the tree of JS snippets in this node and its children. The
  10891. * walking function is called once for each snippet of JS and is passed that
  10892. * snippet and the its original associated source's line/column location.
  10893. *
  10894. * @param aFn The traversal function.
  10895. */
  10896. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  10897. var chunk;
  10898. for (var i = 0, len = this.children.length; i < len; i++) {
  10899. chunk = this.children[i];
  10900. if (chunk[isSourceNode]) {
  10901. chunk.walk(aFn);
  10902. }
  10903. else {
  10904. if (chunk !== '') {
  10905. aFn(chunk, { source: this.source,
  10906. line: this.line,
  10907. column: this.column,
  10908. name: this.name });
  10909. }
  10910. }
  10911. }
  10912. };
  10913. /**
  10914. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  10915. * each of `this.children`.
  10916. *
  10917. * @param aSep The separator.
  10918. */
  10919. SourceNode.prototype.join = function SourceNode_join(aSep) {
  10920. var newChildren;
  10921. var i;
  10922. var len = this.children.length;
  10923. if (len > 0) {
  10924. newChildren = [];
  10925. for (i = 0; i < len-1; i++) {
  10926. newChildren.push(this.children[i]);
  10927. newChildren.push(aSep);
  10928. }
  10929. newChildren.push(this.children[i]);
  10930. this.children = newChildren;
  10931. }
  10932. return this;
  10933. };
  10934. /**
  10935. * Call String.prototype.replace on the very right-most source snippet. Useful
  10936. * for trimming whitespace from the end of a source node, etc.
  10937. *
  10938. * @param aPattern The pattern to replace.
  10939. * @param aReplacement The thing to replace the pattern with.
  10940. */
  10941. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  10942. var lastChild = this.children[this.children.length - 1];
  10943. if (lastChild[isSourceNode]) {
  10944. lastChild.replaceRight(aPattern, aReplacement);
  10945. }
  10946. else if (typeof lastChild === 'string') {
  10947. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  10948. }
  10949. else {
  10950. this.children.push(''.replace(aPattern, aReplacement));
  10951. }
  10952. return this;
  10953. };
  10954. /**
  10955. * Set the source content for a source file. This will be added to the SourceMapGenerator
  10956. * in the sourcesContent field.
  10957. *
  10958. * @param aSourceFile The filename of the source file
  10959. * @param aSourceContent The content of the source file
  10960. */
  10961. SourceNode.prototype.setSourceContent =
  10962. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  10963. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  10964. };
  10965. /**
  10966. * Walk over the tree of SourceNodes. The walking function is called for each
  10967. * source file content and is passed the filename and source content.
  10968. *
  10969. * @param aFn The traversal function.
  10970. */
  10971. SourceNode.prototype.walkSourceContents =
  10972. function SourceNode_walkSourceContents(aFn) {
  10973. for (var i = 0, len = this.children.length; i < len; i++) {
  10974. if (this.children[i][isSourceNode]) {
  10975. this.children[i].walkSourceContents(aFn);
  10976. }
  10977. }
  10978. var sources = Object.keys(this.sourceContents);
  10979. for (var i = 0, len = sources.length; i < len; i++) {
  10980. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  10981. }
  10982. };
  10983. /**
  10984. * Return the string representation of this source node. Walks over the tree
  10985. * and concatenates all the various snippets together to one string.
  10986. */
  10987. SourceNode.prototype.toString = function SourceNode_toString() {
  10988. var str = "";
  10989. this.walk(function (chunk) {
  10990. str += chunk;
  10991. });
  10992. return str;
  10993. };
  10994. /**
  10995. * Returns the string representation of this source node along with a source
  10996. * map.
  10997. */
  10998. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  10999. var generated = {
  11000. code: "",
  11001. line: 1,
  11002. column: 0
  11003. };
  11004. var map = new SourceMapGenerator(aArgs);
  11005. var sourceMappingActive = false;
  11006. var lastOriginalSource = null;
  11007. var lastOriginalLine = null;
  11008. var lastOriginalColumn = null;
  11009. var lastOriginalName = null;
  11010. this.walk(function (chunk, original) {
  11011. generated.code += chunk;
  11012. if (original.source !== null
  11013. && original.line !== null
  11014. && original.column !== null) {
  11015. if(lastOriginalSource !== original.source
  11016. || lastOriginalLine !== original.line
  11017. || lastOriginalColumn !== original.column
  11018. || lastOriginalName !== original.name) {
  11019. map.addMapping({
  11020. source: original.source,
  11021. original: {
  11022. line: original.line,
  11023. column: original.column
  11024. },
  11025. generated: {
  11026. line: generated.line,
  11027. column: generated.column
  11028. },
  11029. name: original.name
  11030. });
  11031. }
  11032. lastOriginalSource = original.source;
  11033. lastOriginalLine = original.line;
  11034. lastOriginalColumn = original.column;
  11035. lastOriginalName = original.name;
  11036. sourceMappingActive = true;
  11037. } else if (sourceMappingActive) {
  11038. map.addMapping({
  11039. generated: {
  11040. line: generated.line,
  11041. column: generated.column
  11042. }
  11043. });
  11044. lastOriginalSource = null;
  11045. sourceMappingActive = false;
  11046. }
  11047. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  11048. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  11049. generated.line++;
  11050. generated.column = 0;
  11051. // Mappings end at eol
  11052. if (idx + 1 === length) {
  11053. lastOriginalSource = null;
  11054. sourceMappingActive = false;
  11055. } else if (sourceMappingActive) {
  11056. map.addMapping({
  11057. source: original.source,
  11058. original: {
  11059. line: original.line,
  11060. column: original.column
  11061. },
  11062. generated: {
  11063. line: generated.line,
  11064. column: generated.column
  11065. },
  11066. name: original.name
  11067. });
  11068. }
  11069. } else {
  11070. generated.column++;
  11071. }
  11072. }
  11073. });
  11074. this.walkSourceContents(function (sourceFile, sourceContent) {
  11075. map.setSourceContent(sourceFile, sourceContent);
  11076. });
  11077. return { code: generated.code, map: map };
  11078. };
  11079. sourceNode.SourceNode = SourceNode;
  11080. return sourceNode;
  11081. }
  11082. /*
  11083. * Copyright 2009-2011 Mozilla Foundation and contributors
  11084. * Licensed under the New BSD license. See LICENSE.txt or:
  11085. * http://opensource.org/licenses/BSD-3-Clause
  11086. */
  11087. var hasRequiredSourceMap;
  11088. function requireSourceMap () {
  11089. if (hasRequiredSourceMap) return sourceMap;
  11090. hasRequiredSourceMap = 1;
  11091. sourceMap.SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  11092. sourceMap.SourceMapConsumer = /*@__PURE__*/ requireSourceMapConsumer().SourceMapConsumer;
  11093. sourceMap.SourceNode = /*@__PURE__*/ requireSourceNode().SourceNode;
  11094. return sourceMap;
  11095. }
  11096. var mergeSourceMap;
  11097. var hasRequiredMergeSourceMap;
  11098. function requireMergeSourceMap () {
  11099. if (hasRequiredMergeSourceMap) return mergeSourceMap;
  11100. hasRequiredMergeSourceMap = 1;
  11101. var sourceMap = /*@__PURE__*/ requireSourceMap();
  11102. var SourceMapConsumer = sourceMap.SourceMapConsumer;
  11103. var SourceMapGenerator = sourceMap.SourceMapGenerator;
  11104. mergeSourceMap = merge;
  11105. /**
  11106. * Merge old source map and new source map and return merged.
  11107. * If old or new source map value is falsy, return another one as it is.
  11108. *
  11109. * @param {object|string} [oldMap] old source map object
  11110. * @param {object|string} [newmap] new source map object
  11111. * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
  11112. */
  11113. function merge(oldMap, newMap) {
  11114. if (!oldMap) return newMap
  11115. if (!newMap) return oldMap
  11116. var oldMapConsumer = new SourceMapConsumer(oldMap);
  11117. var newMapConsumer = new SourceMapConsumer(newMap);
  11118. var mergedMapGenerator = new SourceMapGenerator();
  11119. // iterate on new map and overwrite original position of new map with one of old map
  11120. newMapConsumer.eachMapping(function(m) {
  11121. // pass when `originalLine` is null.
  11122. // It occurs in case that the node does not have origin in original code.
  11123. if (m.originalLine == null) return
  11124. var origPosInOldMap = oldMapConsumer.originalPositionFor({
  11125. line: m.originalLine,
  11126. column: m.originalColumn
  11127. });
  11128. if (origPosInOldMap.source == null) return
  11129. mergedMapGenerator.addMapping({
  11130. original: {
  11131. line: origPosInOldMap.line,
  11132. column: origPosInOldMap.column
  11133. },
  11134. generated: {
  11135. line: m.generatedLine,
  11136. column: m.generatedColumn
  11137. },
  11138. source: origPosInOldMap.source,
  11139. name: origPosInOldMap.name
  11140. });
  11141. });
  11142. var consumers = [oldMapConsumer, newMapConsumer];
  11143. consumers.forEach(function(consumer) {
  11144. consumer.sources.forEach(function(sourceFile) {
  11145. mergedMapGenerator._sources.add(sourceFile);
  11146. var sourceContent = consumer.sourceContentFor(sourceFile);
  11147. if (sourceContent != null) {
  11148. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  11149. }
  11150. });
  11151. });
  11152. mergedMapGenerator._sourceRoot = oldMap.sourceRoot;
  11153. mergedMapGenerator._file = oldMap.file;
  11154. return JSON.parse(mergedMapGenerator.toString())
  11155. }
  11156. return mergeSourceMap;
  11157. }
  11158. var mergeSourceMapExports = /*@__PURE__*/ requireMergeSourceMap();
  11159. var merge = /*@__PURE__*/getDefaultExportFromCjs(mergeSourceMapExports);
  11160. const scss = (source, map, options, load = require) => {
  11161. const nodeSass = load("sass");
  11162. const { compileString, renderSync } = nodeSass;
  11163. const data = getSource(source, options.filename, options.additionalData);
  11164. let css;
  11165. let dependencies;
  11166. let sourceMap;
  11167. try {
  11168. if (compileString) {
  11169. const { pathToFileURL, fileURLToPath } = load("url");
  11170. const result = compileString(data, {
  11171. ...options,
  11172. url: pathToFileURL(options.filename),
  11173. sourceMap: !!map
  11174. });
  11175. css = result.css;
  11176. dependencies = result.loadedUrls.map((url) => fileURLToPath(url));
  11177. sourceMap = map ? result.sourceMap : void 0;
  11178. } else {
  11179. const result = renderSync({
  11180. ...options,
  11181. data,
  11182. file: options.filename,
  11183. outFile: options.filename,
  11184. sourceMap: !!map
  11185. });
  11186. css = result.css.toString();
  11187. dependencies = result.stats.includedFiles;
  11188. sourceMap = map ? JSON.parse(result.map.toString()) : void 0;
  11189. }
  11190. if (map) {
  11191. return {
  11192. code: css,
  11193. errors: [],
  11194. dependencies,
  11195. map: merge(map, sourceMap)
  11196. };
  11197. }
  11198. return { code: css, errors: [], dependencies };
  11199. } catch (e) {
  11200. return { code: "", errors: [e], dependencies: [] };
  11201. }
  11202. };
  11203. const sass = (source, map, options, load) => scss(
  11204. source,
  11205. map,
  11206. {
  11207. ...options,
  11208. indentedSyntax: true
  11209. },
  11210. load
  11211. );
  11212. const less = (source, map, options, load = require) => {
  11213. const nodeLess = load("less");
  11214. let result;
  11215. let error = null;
  11216. nodeLess.render(
  11217. getSource(source, options.filename, options.additionalData),
  11218. { ...options, syncImport: true },
  11219. (err, output) => {
  11220. error = err;
  11221. result = output;
  11222. }
  11223. );
  11224. if (error) return { code: "", errors: [error], dependencies: [] };
  11225. const dependencies = result.imports;
  11226. if (map) {
  11227. return {
  11228. code: result.css.toString(),
  11229. map: merge(map, result.map),
  11230. errors: [],
  11231. dependencies
  11232. };
  11233. }
  11234. return {
  11235. code: result.css.toString(),
  11236. errors: [],
  11237. dependencies
  11238. };
  11239. };
  11240. const styl = (source, map, options, load = require) => {
  11241. const nodeStylus = load("stylus");
  11242. try {
  11243. const ref = nodeStylus(source, options);
  11244. if (map) ref.set("sourcemap", { inline: false, comment: false });
  11245. const result = ref.render();
  11246. const dependencies = ref.deps();
  11247. if (map) {
  11248. return {
  11249. code: result,
  11250. map: merge(map, ref.sourcemap),
  11251. errors: [],
  11252. dependencies
  11253. };
  11254. }
  11255. return { code: result, errors: [], dependencies };
  11256. } catch (e) {
  11257. return { code: "", errors: [e], dependencies: [] };
  11258. }
  11259. };
  11260. function getSource(source, filename, additionalData) {
  11261. if (!additionalData) return source;
  11262. if (shared.isFunction(additionalData)) {
  11263. return additionalData(source, filename);
  11264. }
  11265. return additionalData + source;
  11266. }
  11267. const processors = {
  11268. less,
  11269. sass,
  11270. scss,
  11271. styl,
  11272. stylus: styl
  11273. };
  11274. var build = {exports: {}};
  11275. var fs = {};
  11276. var hasRequiredFs;
  11277. function requireFs () {
  11278. if (hasRequiredFs) return fs;
  11279. hasRequiredFs = 1;
  11280. Object.defineProperty(fs, "__esModule", {
  11281. value: true
  11282. });
  11283. fs.getFileSystem = getFileSystem;
  11284. fs.setFileSystem = setFileSystem;
  11285. let fileSystem = {
  11286. readFile: () => {
  11287. throw Error("readFile not implemented");
  11288. },
  11289. writeFile: () => {
  11290. throw Error("writeFile not implemented");
  11291. }
  11292. };
  11293. function setFileSystem(fs) {
  11294. fileSystem.readFile = fs.readFile;
  11295. fileSystem.writeFile = fs.writeFile;
  11296. }
  11297. function getFileSystem() {
  11298. return fileSystem;
  11299. }
  11300. return fs;
  11301. }
  11302. var pluginFactory = {};
  11303. var unquote = {};
  11304. var hasRequiredUnquote;
  11305. function requireUnquote () {
  11306. if (hasRequiredUnquote) return unquote;
  11307. hasRequiredUnquote = 1;
  11308. Object.defineProperty(unquote, "__esModule", {
  11309. value: true
  11310. });
  11311. unquote.default = unquote$1;
  11312. // copied from https://github.com/lakenen/node-unquote
  11313. const reg = /['"]/;
  11314. function unquote$1(str) {
  11315. if (!str) {
  11316. return "";
  11317. }
  11318. if (reg.test(str.charAt(0))) {
  11319. str = str.substr(1);
  11320. }
  11321. if (reg.test(str.charAt(str.length - 1))) {
  11322. str = str.substr(0, str.length - 1);
  11323. }
  11324. return str;
  11325. }
  11326. return unquote;
  11327. }
  11328. var Parser = {};
  11329. var replaceValueSymbols_1;
  11330. var hasRequiredReplaceValueSymbols;
  11331. function requireReplaceValueSymbols () {
  11332. if (hasRequiredReplaceValueSymbols) return replaceValueSymbols_1;
  11333. hasRequiredReplaceValueSymbols = 1;
  11334. const matchValueName = /[$]?[\w-]+/g;
  11335. const replaceValueSymbols = (value, replacements) => {
  11336. let matches;
  11337. while ((matches = matchValueName.exec(value))) {
  11338. const replacement = replacements[matches[0]];
  11339. if (replacement) {
  11340. value =
  11341. value.slice(0, matches.index) +
  11342. replacement +
  11343. value.slice(matchValueName.lastIndex);
  11344. matchValueName.lastIndex -= matches[0].length - replacement.length;
  11345. }
  11346. }
  11347. return value;
  11348. };
  11349. replaceValueSymbols_1 = replaceValueSymbols;
  11350. return replaceValueSymbols_1;
  11351. }
  11352. var replaceSymbols_1;
  11353. var hasRequiredReplaceSymbols;
  11354. function requireReplaceSymbols () {
  11355. if (hasRequiredReplaceSymbols) return replaceSymbols_1;
  11356. hasRequiredReplaceSymbols = 1;
  11357. const replaceValueSymbols = /*@__PURE__*/ requireReplaceValueSymbols();
  11358. const replaceSymbols = (css, replacements) => {
  11359. css.walk((node) => {
  11360. if (node.type === "decl" && node.value) {
  11361. node.value = replaceValueSymbols(node.value.toString(), replacements);
  11362. } else if (node.type === "rule" && node.selector) {
  11363. node.selector = replaceValueSymbols(
  11364. node.selector.toString(),
  11365. replacements
  11366. );
  11367. } else if (node.type === "atrule" && node.params) {
  11368. node.params = replaceValueSymbols(node.params.toString(), replacements);
  11369. }
  11370. });
  11371. };
  11372. replaceSymbols_1 = replaceSymbols;
  11373. return replaceSymbols_1;
  11374. }
  11375. var extractICSS_1;
  11376. var hasRequiredExtractICSS;
  11377. function requireExtractICSS () {
  11378. if (hasRequiredExtractICSS) return extractICSS_1;
  11379. hasRequiredExtractICSS = 1;
  11380. const importPattern = /^:import\(("[^"]*"|'[^']*'|[^"']+)\)$/;
  11381. const balancedQuotes = /^("[^"]*"|'[^']*'|[^"']+)$/;
  11382. const getDeclsObject = (rule) => {
  11383. const object = {};
  11384. rule.walkDecls((decl) => {
  11385. const before = decl.raws.before ? decl.raws.before.trim() : "";
  11386. object[before + decl.prop] = decl.value;
  11387. });
  11388. return object;
  11389. };
  11390. /**
  11391. *
  11392. * @param {string} css
  11393. * @param {boolean} removeRules
  11394. * @param {'auto' | 'rule' | 'at-rule'} mode
  11395. */
  11396. const extractICSS = (css, removeRules = true, mode = "auto") => {
  11397. const icssImports = {};
  11398. const icssExports = {};
  11399. function addImports(node, path) {
  11400. const unquoted = path.replace(/'|"/g, "");
  11401. icssImports[unquoted] = Object.assign(
  11402. icssImports[unquoted] || {},
  11403. getDeclsObject(node)
  11404. );
  11405. if (removeRules) {
  11406. node.remove();
  11407. }
  11408. }
  11409. function addExports(node) {
  11410. Object.assign(icssExports, getDeclsObject(node));
  11411. if (removeRules) {
  11412. node.remove();
  11413. }
  11414. }
  11415. css.each((node) => {
  11416. if (node.type === "rule" && mode !== "at-rule") {
  11417. if (node.selector.slice(0, 7) === ":import") {
  11418. const matches = importPattern.exec(node.selector);
  11419. if (matches) {
  11420. addImports(node, matches[1]);
  11421. }
  11422. }
  11423. if (node.selector === ":export") {
  11424. addExports(node);
  11425. }
  11426. }
  11427. if (node.type === "atrule" && mode !== "rule") {
  11428. if (node.name === "icss-import") {
  11429. const matches = balancedQuotes.exec(node.params);
  11430. if (matches) {
  11431. addImports(node, matches[1]);
  11432. }
  11433. }
  11434. if (node.name === "icss-export") {
  11435. addExports(node);
  11436. }
  11437. }
  11438. });
  11439. return { icssImports, icssExports };
  11440. };
  11441. extractICSS_1 = extractICSS;
  11442. return extractICSS_1;
  11443. }
  11444. var createICSSRules_1;
  11445. var hasRequiredCreateICSSRules;
  11446. function requireCreateICSSRules () {
  11447. if (hasRequiredCreateICSSRules) return createICSSRules_1;
  11448. hasRequiredCreateICSSRules = 1;
  11449. const createImports = (imports, postcss, mode = "rule") => {
  11450. return Object.keys(imports).map((path) => {
  11451. const aliases = imports[path];
  11452. const declarations = Object.keys(aliases).map((key) =>
  11453. postcss.decl({
  11454. prop: key,
  11455. value: aliases[key],
  11456. raws: { before: "\n " },
  11457. })
  11458. );
  11459. const hasDeclarations = declarations.length > 0;
  11460. const rule =
  11461. mode === "rule"
  11462. ? postcss.rule({
  11463. selector: `:import('${path}')`,
  11464. raws: { after: hasDeclarations ? "\n" : "" },
  11465. })
  11466. : postcss.atRule({
  11467. name: "icss-import",
  11468. params: `'${path}'`,
  11469. raws: { after: hasDeclarations ? "\n" : "" },
  11470. });
  11471. if (hasDeclarations) {
  11472. rule.append(declarations);
  11473. }
  11474. return rule;
  11475. });
  11476. };
  11477. const createExports = (exports, postcss, mode = "rule") => {
  11478. const declarations = Object.keys(exports).map((key) =>
  11479. postcss.decl({
  11480. prop: key,
  11481. value: exports[key],
  11482. raws: { before: "\n " },
  11483. })
  11484. );
  11485. if (declarations.length === 0) {
  11486. return [];
  11487. }
  11488. const rule =
  11489. mode === "rule"
  11490. ? postcss.rule({
  11491. selector: `:export`,
  11492. raws: { after: "\n" },
  11493. })
  11494. : postcss.atRule({
  11495. name: "icss-export",
  11496. raws: { after: "\n" },
  11497. });
  11498. rule.append(declarations);
  11499. return [rule];
  11500. };
  11501. const createICSSRules = (imports, exports, postcss, mode) => [
  11502. ...createImports(imports, postcss, mode),
  11503. ...createExports(exports, postcss, mode),
  11504. ];
  11505. createICSSRules_1 = createICSSRules;
  11506. return createICSSRules_1;
  11507. }
  11508. var src$4;
  11509. var hasRequiredSrc$4;
  11510. function requireSrc$4 () {
  11511. if (hasRequiredSrc$4) return src$4;
  11512. hasRequiredSrc$4 = 1;
  11513. const replaceValueSymbols = /*@__PURE__*/ requireReplaceValueSymbols();
  11514. const replaceSymbols = /*@__PURE__*/ requireReplaceSymbols();
  11515. const extractICSS = /*@__PURE__*/ requireExtractICSS();
  11516. const createICSSRules = /*@__PURE__*/ requireCreateICSSRules();
  11517. src$4 = {
  11518. replaceValueSymbols,
  11519. replaceSymbols,
  11520. extractICSS,
  11521. createICSSRules,
  11522. };
  11523. return src$4;
  11524. }
  11525. var hasRequiredParser$1;
  11526. function requireParser$1 () {
  11527. if (hasRequiredParser$1) return Parser;
  11528. hasRequiredParser$1 = 1;
  11529. Object.defineProperty(Parser, "__esModule", {
  11530. value: true
  11531. });
  11532. Parser.default = void 0;
  11533. var _icssUtils = /*@__PURE__*/ requireSrc$4();
  11534. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  11535. const importRegexp = /^:import\((.+)\)$/;
  11536. let Parser$1 = class Parser {
  11537. constructor(pathFetcher, trace) {
  11538. this.pathFetcher = pathFetcher;
  11539. this.plugin = this.plugin.bind(this);
  11540. this.exportTokens = {};
  11541. this.translations = {};
  11542. this.trace = trace;
  11543. }
  11544. plugin() {
  11545. const parser = this;
  11546. return {
  11547. postcssPlugin: "css-modules-parser",
  11548. async OnceExit(css) {
  11549. await Promise.all(parser.fetchAllImports(css));
  11550. parser.linkImportedSymbols(css);
  11551. return parser.extractExports(css);
  11552. }
  11553. };
  11554. }
  11555. fetchAllImports(css) {
  11556. let imports = [];
  11557. css.each(node => {
  11558. if (node.type == "rule" && node.selector.match(importRegexp)) {
  11559. imports.push(this.fetchImport(node, css.source.input.from, imports.length));
  11560. }
  11561. });
  11562. return imports;
  11563. }
  11564. linkImportedSymbols(css) {
  11565. (0, _icssUtils.replaceSymbols)(css, this.translations);
  11566. }
  11567. extractExports(css) {
  11568. css.each(node => {
  11569. if (node.type == "rule" && node.selector == ":export") this.handleExport(node);
  11570. });
  11571. }
  11572. handleExport(exportNode) {
  11573. exportNode.each(decl => {
  11574. if (decl.type == "decl") {
  11575. Object.keys(this.translations).forEach(translation => {
  11576. decl.value = decl.value.replace(translation, this.translations[translation]);
  11577. });
  11578. this.exportTokens[decl.prop] = decl.value;
  11579. }
  11580. });
  11581. exportNode.remove();
  11582. }
  11583. async fetchImport(importNode, relativeTo, depNr) {
  11584. const file = importNode.selector.match(importRegexp)[1];
  11585. const depTrace = this.trace + String.fromCharCode(depNr);
  11586. const exports = await this.pathFetcher(file, relativeTo, depTrace);
  11587. try {
  11588. importNode.each(decl => {
  11589. if (decl.type == "decl") {
  11590. this.translations[decl.prop] = exports[decl.value];
  11591. }
  11592. });
  11593. importNode.remove();
  11594. } catch (err) {
  11595. console.log(err);
  11596. }
  11597. }
  11598. };
  11599. Parser.default = Parser$1;
  11600. return Parser;
  11601. }
  11602. var saveJSON = {};
  11603. var hasRequiredSaveJSON;
  11604. function requireSaveJSON () {
  11605. if (hasRequiredSaveJSON) return saveJSON;
  11606. hasRequiredSaveJSON = 1;
  11607. Object.defineProperty(saveJSON, "__esModule", {
  11608. value: true
  11609. });
  11610. saveJSON.default = saveJSON$1;
  11611. var _fs = /*@__PURE__*/ requireFs();
  11612. function saveJSON$1(cssFile, json) {
  11613. return new Promise((resolve, reject) => {
  11614. const {
  11615. writeFile
  11616. } = (0, _fs.getFileSystem)();
  11617. writeFile(`${cssFile}.json`, JSON.stringify(json), e => e ? reject(e) : resolve(json));
  11618. });
  11619. }
  11620. return saveJSON;
  11621. }
  11622. var localsConvention = {};
  11623. /**
  11624. * lodash (Custom Build) <https://lodash.com/>
  11625. * Build: `lodash modularize exports="npm" -o ./`
  11626. * Copyright jQuery Foundation and other contributors <https://jquery.org/>
  11627. * Released under MIT license <https://lodash.com/license>
  11628. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  11629. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11630. */
  11631. var lodash_camelcase;
  11632. var hasRequiredLodash_camelcase;
  11633. function requireLodash_camelcase () {
  11634. if (hasRequiredLodash_camelcase) return lodash_camelcase;
  11635. hasRequiredLodash_camelcase = 1;
  11636. /** `Object#toString` result references. */
  11637. var symbolTag = '[object Symbol]';
  11638. /** Used to match words composed of alphanumeric characters. */
  11639. var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
  11640. /** Used to match Latin Unicode letters (excluding mathematical operators). */
  11641. var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
  11642. /** Used to compose unicode character classes. */
  11643. var rsAstralRange = '\\ud800-\\udfff',
  11644. rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23',
  11645. rsComboSymbolsRange = '\\u20d0-\\u20f0',
  11646. rsDingbatRange = '\\u2700-\\u27bf',
  11647. rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
  11648. rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
  11649. rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
  11650. rsPunctuationRange = '\\u2000-\\u206f',
  11651. rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',
  11652. rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
  11653. rsVarRange = '\\ufe0e\\ufe0f',
  11654. rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
  11655. /** Used to compose unicode capture groups. */
  11656. var rsApos = "['\u2019]",
  11657. rsAstral = '[' + rsAstralRange + ']',
  11658. rsBreak = '[' + rsBreakRange + ']',
  11659. rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']',
  11660. rsDigits = '\\d+',
  11661. rsDingbat = '[' + rsDingbatRange + ']',
  11662. rsLower = '[' + rsLowerRange + ']',
  11663. rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
  11664. rsFitz = '\\ud83c[\\udffb-\\udfff]',
  11665. rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
  11666. rsNonAstral = '[^' + rsAstralRange + ']',
  11667. rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
  11668. rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
  11669. rsUpper = '[' + rsUpperRange + ']',
  11670. rsZWJ = '\\u200d';
  11671. /** Used to compose unicode regexes. */
  11672. var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')',
  11673. rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')',
  11674. rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
  11675. rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
  11676. reOptMod = rsModifier + '?',
  11677. rsOptVar = '[' + rsVarRange + ']?',
  11678. rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
  11679. rsSeq = rsOptVar + reOptMod + rsOptJoin,
  11680. rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
  11681. rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
  11682. /** Used to match apostrophes. */
  11683. var reApos = RegExp(rsApos, 'g');
  11684. /**
  11685. * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
  11686. * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
  11687. */
  11688. var reComboMark = RegExp(rsCombo, 'g');
  11689. /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
  11690. var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
  11691. /** Used to match complex or compound words. */
  11692. var reUnicodeWord = RegExp([
  11693. rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
  11694. rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')',
  11695. rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr,
  11696. rsUpper + '+' + rsOptUpperContr,
  11697. rsDigits,
  11698. rsEmoji
  11699. ].join('|'), 'g');
  11700. /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
  11701. var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']');
  11702. /** Used to detect strings that need a more robust regexp to match words. */
  11703. var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
  11704. /** Used to map Latin Unicode letters to basic Latin letters. */
  11705. var deburredLetters = {
  11706. // Latin-1 Supplement block.
  11707. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
  11708. '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
  11709. '\xc7': 'C', '\xe7': 'c',
  11710. '\xd0': 'D', '\xf0': 'd',
  11711. '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
  11712. '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
  11713. '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
  11714. '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
  11715. '\xd1': 'N', '\xf1': 'n',
  11716. '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
  11717. '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
  11718. '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
  11719. '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
  11720. '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
  11721. '\xc6': 'Ae', '\xe6': 'ae',
  11722. '\xde': 'Th', '\xfe': 'th',
  11723. '\xdf': 'ss',
  11724. // Latin Extended-A block.
  11725. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
  11726. '\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
  11727. '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
  11728. '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
  11729. '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
  11730. '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
  11731. '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
  11732. '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
  11733. '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
  11734. '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
  11735. '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
  11736. '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
  11737. '\u0134': 'J', '\u0135': 'j',
  11738. '\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
  11739. '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
  11740. '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
  11741. '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
  11742. '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
  11743. '\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
  11744. '\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
  11745. '\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
  11746. '\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
  11747. '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
  11748. '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
  11749. '\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
  11750. '\u0163': 't', '\u0165': 't', '\u0167': 't',
  11751. '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
  11752. '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
  11753. '\u0174': 'W', '\u0175': 'w',
  11754. '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
  11755. '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
  11756. '\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
  11757. '\u0132': 'IJ', '\u0133': 'ij',
  11758. '\u0152': 'Oe', '\u0153': 'oe',
  11759. '\u0149': "'n", '\u017f': 'ss'
  11760. };
  11761. /** Detect free variable `global` from Node.js. */
  11762. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
  11763. /** Detect free variable `self`. */
  11764. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  11765. /** Used as a reference to the global object. */
  11766. var root = freeGlobal || freeSelf || Function('return this')();
  11767. /**
  11768. * A specialized version of `_.reduce` for arrays without support for
  11769. * iteratee shorthands.
  11770. *
  11771. * @private
  11772. * @param {Array} [array] The array to iterate over.
  11773. * @param {Function} iteratee The function invoked per iteration.
  11774. * @param {*} [accumulator] The initial value.
  11775. * @param {boolean} [initAccum] Specify using the first element of `array` as
  11776. * the initial value.
  11777. * @returns {*} Returns the accumulated value.
  11778. */
  11779. function arrayReduce(array, iteratee, accumulator, initAccum) {
  11780. var index = -1,
  11781. length = array ? array.length : 0;
  11782. while (++index < length) {
  11783. accumulator = iteratee(accumulator, array[index], index, array);
  11784. }
  11785. return accumulator;
  11786. }
  11787. /**
  11788. * Converts an ASCII `string` to an array.
  11789. *
  11790. * @private
  11791. * @param {string} string The string to convert.
  11792. * @returns {Array} Returns the converted array.
  11793. */
  11794. function asciiToArray(string) {
  11795. return string.split('');
  11796. }
  11797. /**
  11798. * Splits an ASCII `string` into an array of its words.
  11799. *
  11800. * @private
  11801. * @param {string} The string to inspect.
  11802. * @returns {Array} Returns the words of `string`.
  11803. */
  11804. function asciiWords(string) {
  11805. return string.match(reAsciiWord) || [];
  11806. }
  11807. /**
  11808. * The base implementation of `_.propertyOf` without support for deep paths.
  11809. *
  11810. * @private
  11811. * @param {Object} object The object to query.
  11812. * @returns {Function} Returns the new accessor function.
  11813. */
  11814. function basePropertyOf(object) {
  11815. return function(key) {
  11816. return object == null ? undefined : object[key];
  11817. };
  11818. }
  11819. /**
  11820. * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
  11821. * letters to basic Latin letters.
  11822. *
  11823. * @private
  11824. * @param {string} letter The matched letter to deburr.
  11825. * @returns {string} Returns the deburred letter.
  11826. */
  11827. var deburrLetter = basePropertyOf(deburredLetters);
  11828. /**
  11829. * Checks if `string` contains Unicode symbols.
  11830. *
  11831. * @private
  11832. * @param {string} string The string to inspect.
  11833. * @returns {boolean} Returns `true` if a symbol is found, else `false`.
  11834. */
  11835. function hasUnicode(string) {
  11836. return reHasUnicode.test(string);
  11837. }
  11838. /**
  11839. * Checks if `string` contains a word composed of Unicode symbols.
  11840. *
  11841. * @private
  11842. * @param {string} string The string to inspect.
  11843. * @returns {boolean} Returns `true` if a word is found, else `false`.
  11844. */
  11845. function hasUnicodeWord(string) {
  11846. return reHasUnicodeWord.test(string);
  11847. }
  11848. /**
  11849. * Converts `string` to an array.
  11850. *
  11851. * @private
  11852. * @param {string} string The string to convert.
  11853. * @returns {Array} Returns the converted array.
  11854. */
  11855. function stringToArray(string) {
  11856. return hasUnicode(string)
  11857. ? unicodeToArray(string)
  11858. : asciiToArray(string);
  11859. }
  11860. /**
  11861. * Converts a Unicode `string` to an array.
  11862. *
  11863. * @private
  11864. * @param {string} string The string to convert.
  11865. * @returns {Array} Returns the converted array.
  11866. */
  11867. function unicodeToArray(string) {
  11868. return string.match(reUnicode) || [];
  11869. }
  11870. /**
  11871. * Splits a Unicode `string` into an array of its words.
  11872. *
  11873. * @private
  11874. * @param {string} The string to inspect.
  11875. * @returns {Array} Returns the words of `string`.
  11876. */
  11877. function unicodeWords(string) {
  11878. return string.match(reUnicodeWord) || [];
  11879. }
  11880. /** Used for built-in method references. */
  11881. var objectProto = Object.prototype;
  11882. /**
  11883. * Used to resolve the
  11884. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  11885. * of values.
  11886. */
  11887. var objectToString = objectProto.toString;
  11888. /** Built-in value references. */
  11889. var Symbol = root.Symbol;
  11890. /** Used to convert symbols to primitives and strings. */
  11891. var symbolProto = Symbol ? Symbol.prototype : undefined,
  11892. symbolToString = symbolProto ? symbolProto.toString : undefined;
  11893. /**
  11894. * The base implementation of `_.slice` without an iteratee call guard.
  11895. *
  11896. * @private
  11897. * @param {Array} array The array to slice.
  11898. * @param {number} [start=0] The start position.
  11899. * @param {number} [end=array.length] The end position.
  11900. * @returns {Array} Returns the slice of `array`.
  11901. */
  11902. function baseSlice(array, start, end) {
  11903. var index = -1,
  11904. length = array.length;
  11905. if (start < 0) {
  11906. start = -start > length ? 0 : (length + start);
  11907. }
  11908. end = end > length ? length : end;
  11909. if (end < 0) {
  11910. end += length;
  11911. }
  11912. length = start > end ? 0 : ((end - start) >>> 0);
  11913. start >>>= 0;
  11914. var result = Array(length);
  11915. while (++index < length) {
  11916. result[index] = array[index + start];
  11917. }
  11918. return result;
  11919. }
  11920. /**
  11921. * The base implementation of `_.toString` which doesn't convert nullish
  11922. * values to empty strings.
  11923. *
  11924. * @private
  11925. * @param {*} value The value to process.
  11926. * @returns {string} Returns the string.
  11927. */
  11928. function baseToString(value) {
  11929. // Exit early for strings to avoid a performance hit in some environments.
  11930. if (typeof value == 'string') {
  11931. return value;
  11932. }
  11933. if (isSymbol(value)) {
  11934. return symbolToString ? symbolToString.call(value) : '';
  11935. }
  11936. var result = (value + '');
  11937. return (result == '0' && (1 / value) == -Infinity) ? '-0' : result;
  11938. }
  11939. /**
  11940. * Casts `array` to a slice if it's needed.
  11941. *
  11942. * @private
  11943. * @param {Array} array The array to inspect.
  11944. * @param {number} start The start position.
  11945. * @param {number} [end=array.length] The end position.
  11946. * @returns {Array} Returns the cast slice.
  11947. */
  11948. function castSlice(array, start, end) {
  11949. var length = array.length;
  11950. end = end === undefined ? length : end;
  11951. return (!start && end >= length) ? array : baseSlice(array, start, end);
  11952. }
  11953. /**
  11954. * Creates a function like `_.lowerFirst`.
  11955. *
  11956. * @private
  11957. * @param {string} methodName The name of the `String` case method to use.
  11958. * @returns {Function} Returns the new case function.
  11959. */
  11960. function createCaseFirst(methodName) {
  11961. return function(string) {
  11962. string = toString(string);
  11963. var strSymbols = hasUnicode(string)
  11964. ? stringToArray(string)
  11965. : undefined;
  11966. var chr = strSymbols
  11967. ? strSymbols[0]
  11968. : string.charAt(0);
  11969. var trailing = strSymbols
  11970. ? castSlice(strSymbols, 1).join('')
  11971. : string.slice(1);
  11972. return chr[methodName]() + trailing;
  11973. };
  11974. }
  11975. /**
  11976. * Creates a function like `_.camelCase`.
  11977. *
  11978. * @private
  11979. * @param {Function} callback The function to combine each word.
  11980. * @returns {Function} Returns the new compounder function.
  11981. */
  11982. function createCompounder(callback) {
  11983. return function(string) {
  11984. return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
  11985. };
  11986. }
  11987. /**
  11988. * Checks if `value` is object-like. A value is object-like if it's not `null`
  11989. * and has a `typeof` result of "object".
  11990. *
  11991. * @static
  11992. * @memberOf _
  11993. * @since 4.0.0
  11994. * @category Lang
  11995. * @param {*} value The value to check.
  11996. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  11997. * @example
  11998. *
  11999. * _.isObjectLike({});
  12000. * // => true
  12001. *
  12002. * _.isObjectLike([1, 2, 3]);
  12003. * // => true
  12004. *
  12005. * _.isObjectLike(_.noop);
  12006. * // => false
  12007. *
  12008. * _.isObjectLike(null);
  12009. * // => false
  12010. */
  12011. function isObjectLike(value) {
  12012. return !!value && typeof value == 'object';
  12013. }
  12014. /**
  12015. * Checks if `value` is classified as a `Symbol` primitive or object.
  12016. *
  12017. * @static
  12018. * @memberOf _
  12019. * @since 4.0.0
  12020. * @category Lang
  12021. * @param {*} value The value to check.
  12022. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  12023. * @example
  12024. *
  12025. * _.isSymbol(Symbol.iterator);
  12026. * // => true
  12027. *
  12028. * _.isSymbol('abc');
  12029. * // => false
  12030. */
  12031. function isSymbol(value) {
  12032. return typeof value == 'symbol' ||
  12033. (isObjectLike(value) && objectToString.call(value) == symbolTag);
  12034. }
  12035. /**
  12036. * Converts `value` to a string. An empty string is returned for `null`
  12037. * and `undefined` values. The sign of `-0` is preserved.
  12038. *
  12039. * @static
  12040. * @memberOf _
  12041. * @since 4.0.0
  12042. * @category Lang
  12043. * @param {*} value The value to process.
  12044. * @returns {string} Returns the string.
  12045. * @example
  12046. *
  12047. * _.toString(null);
  12048. * // => ''
  12049. *
  12050. * _.toString(-0);
  12051. * // => '-0'
  12052. *
  12053. * _.toString([1, 2, 3]);
  12054. * // => '1,2,3'
  12055. */
  12056. function toString(value) {
  12057. return value == null ? '' : baseToString(value);
  12058. }
  12059. /**
  12060. * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
  12061. *
  12062. * @static
  12063. * @memberOf _
  12064. * @since 3.0.0
  12065. * @category String
  12066. * @param {string} [string=''] The string to convert.
  12067. * @returns {string} Returns the camel cased string.
  12068. * @example
  12069. *
  12070. * _.camelCase('Foo Bar');
  12071. * // => 'fooBar'
  12072. *
  12073. * _.camelCase('--foo-bar--');
  12074. * // => 'fooBar'
  12075. *
  12076. * _.camelCase('__FOO_BAR__');
  12077. * // => 'fooBar'
  12078. */
  12079. var camelCase = createCompounder(function(result, word, index) {
  12080. word = word.toLowerCase();
  12081. return result + (index ? capitalize(word) : word);
  12082. });
  12083. /**
  12084. * Converts the first character of `string` to upper case and the remaining
  12085. * to lower case.
  12086. *
  12087. * @static
  12088. * @memberOf _
  12089. * @since 3.0.0
  12090. * @category String
  12091. * @param {string} [string=''] The string to capitalize.
  12092. * @returns {string} Returns the capitalized string.
  12093. * @example
  12094. *
  12095. * _.capitalize('FRED');
  12096. * // => 'Fred'
  12097. */
  12098. function capitalize(string) {
  12099. return upperFirst(toString(string).toLowerCase());
  12100. }
  12101. /**
  12102. * Deburrs `string` by converting
  12103. * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
  12104. * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
  12105. * letters to basic Latin letters and removing
  12106. * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
  12107. *
  12108. * @static
  12109. * @memberOf _
  12110. * @since 3.0.0
  12111. * @category String
  12112. * @param {string} [string=''] The string to deburr.
  12113. * @returns {string} Returns the deburred string.
  12114. * @example
  12115. *
  12116. * _.deburr('déjà vu');
  12117. * // => 'deja vu'
  12118. */
  12119. function deburr(string) {
  12120. string = toString(string);
  12121. return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
  12122. }
  12123. /**
  12124. * Converts the first character of `string` to upper case.
  12125. *
  12126. * @static
  12127. * @memberOf _
  12128. * @since 4.0.0
  12129. * @category String
  12130. * @param {string} [string=''] The string to convert.
  12131. * @returns {string} Returns the converted string.
  12132. * @example
  12133. *
  12134. * _.upperFirst('fred');
  12135. * // => 'Fred'
  12136. *
  12137. * _.upperFirst('FRED');
  12138. * // => 'FRED'
  12139. */
  12140. var upperFirst = createCaseFirst('toUpperCase');
  12141. /**
  12142. * Splits `string` into an array of its words.
  12143. *
  12144. * @static
  12145. * @memberOf _
  12146. * @since 3.0.0
  12147. * @category String
  12148. * @param {string} [string=''] The string to inspect.
  12149. * @param {RegExp|string} [pattern] The pattern to match words.
  12150. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  12151. * @returns {Array} Returns the words of `string`.
  12152. * @example
  12153. *
  12154. * _.words('fred, barney, & pebbles');
  12155. * // => ['fred', 'barney', 'pebbles']
  12156. *
  12157. * _.words('fred, barney, & pebbles', /[^, ]+/g);
  12158. * // => ['fred', 'barney', '&', 'pebbles']
  12159. */
  12160. function words(string, pattern, guard) {
  12161. string = toString(string);
  12162. pattern = pattern;
  12163. if (pattern === undefined) {
  12164. return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
  12165. }
  12166. return string.match(pattern) || [];
  12167. }
  12168. lodash_camelcase = camelCase;
  12169. return lodash_camelcase;
  12170. }
  12171. var hasRequiredLocalsConvention;
  12172. function requireLocalsConvention () {
  12173. if (hasRequiredLocalsConvention) return localsConvention;
  12174. hasRequiredLocalsConvention = 1;
  12175. Object.defineProperty(localsConvention, "__esModule", {
  12176. value: true
  12177. });
  12178. localsConvention.makeLocalsConventionReducer = makeLocalsConventionReducer;
  12179. var _lodash = _interopRequireDefault(/*@__PURE__*/ requireLodash_camelcase());
  12180. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12181. function dashesCamelCase(string) {
  12182. return string.replace(/-+(\w)/g, (_, firstLetter) => firstLetter.toUpperCase());
  12183. }
  12184. function makeLocalsConventionReducer(localsConvention, inputFile) {
  12185. const isFunc = typeof localsConvention === "function";
  12186. return (tokens, [className, value]) => {
  12187. if (isFunc) {
  12188. const convention = localsConvention(className, value, inputFile);
  12189. tokens[convention] = value;
  12190. return tokens;
  12191. }
  12192. switch (localsConvention) {
  12193. case "camelCase":
  12194. tokens[className] = value;
  12195. tokens[(0, _lodash.default)(className)] = value;
  12196. break;
  12197. case "camelCaseOnly":
  12198. tokens[(0, _lodash.default)(className)] = value;
  12199. break;
  12200. case "dashes":
  12201. tokens[className] = value;
  12202. tokens[dashesCamelCase(className)] = value;
  12203. break;
  12204. case "dashesOnly":
  12205. tokens[dashesCamelCase(className)] = value;
  12206. break;
  12207. }
  12208. return tokens;
  12209. };
  12210. }
  12211. return localsConvention;
  12212. }
  12213. var FileSystemLoader = {};
  12214. var hasRequiredFileSystemLoader;
  12215. function requireFileSystemLoader () {
  12216. if (hasRequiredFileSystemLoader) return FileSystemLoader;
  12217. hasRequiredFileSystemLoader = 1;
  12218. Object.defineProperty(FileSystemLoader, "__esModule", {
  12219. value: true
  12220. });
  12221. FileSystemLoader.default = void 0;
  12222. var _postcss = _interopRequireDefault(require$$0$1);
  12223. var _path = _interopRequireDefault(path$1);
  12224. var _Parser = _interopRequireDefault(/*@__PURE__*/ requireParser$1());
  12225. var _fs = /*@__PURE__*/ requireFs();
  12226. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12227. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  12228. class Core {
  12229. constructor(plugins) {
  12230. this.plugins = plugins || Core.defaultPlugins;
  12231. }
  12232. async load(sourceString, sourcePath, trace, pathFetcher) {
  12233. const parser = new _Parser.default(pathFetcher, trace);
  12234. const plugins = this.plugins.concat([parser.plugin()]);
  12235. const result = await (0, _postcss.default)(plugins).process(sourceString, {
  12236. from: sourcePath
  12237. });
  12238. return {
  12239. injectableSource: result.css,
  12240. exportTokens: parser.exportTokens
  12241. };
  12242. }
  12243. } // Sorts dependencies in the following way:
  12244. // AAA comes before AA and A
  12245. // AB comes after AA and before A
  12246. // All Bs come after all As
  12247. // This ensures that the files are always returned in the following order:
  12248. // - In the order they were required, except
  12249. // - After all their dependencies
  12250. const traceKeySorter = (a, b) => {
  12251. if (a.length < b.length) {
  12252. return a < b.substring(0, a.length) ? -1 : 1;
  12253. }
  12254. if (a.length > b.length) {
  12255. return a.substring(0, b.length) <= b ? -1 : 1;
  12256. }
  12257. return a < b ? -1 : 1;
  12258. };
  12259. let FileSystemLoader$1 = class FileSystemLoader {
  12260. constructor(root, plugins, fileResolve) {
  12261. if (root === "/" && process.platform === "win32") {
  12262. const cwdDrive = process.cwd().slice(0, 3);
  12263. if (!/^[A-Za-z]:\\$/.test(cwdDrive)) {
  12264. throw new Error(`Failed to obtain root from "${process.cwd()}".`);
  12265. }
  12266. root = cwdDrive;
  12267. }
  12268. this.root = root;
  12269. this.fileResolve = fileResolve;
  12270. this.sources = {};
  12271. this.traces = {};
  12272. this.importNr = 0;
  12273. this.core = new Core(plugins);
  12274. this.tokensByFile = {};
  12275. this.fs = (0, _fs.getFileSystem)();
  12276. }
  12277. async fetch(_newPath, relativeTo, _trace) {
  12278. const newPath = _newPath.replace(/^["']|["']$/g, "");
  12279. const trace = _trace || String.fromCharCode(this.importNr++);
  12280. const useFileResolve = typeof this.fileResolve === "function";
  12281. const fileResolvedPath = useFileResolve ? await this.fileResolve(newPath, relativeTo) : await Promise.resolve();
  12282. if (fileResolvedPath && !_path.default.isAbsolute(fileResolvedPath)) {
  12283. throw new Error('The returned path from the "fileResolve" option must be absolute.');
  12284. }
  12285. const relativeDir = _path.default.dirname(relativeTo);
  12286. const rootRelativePath = fileResolvedPath || _path.default.resolve(relativeDir, newPath);
  12287. let fileRelativePath = fileResolvedPath || _path.default.resolve(_path.default.resolve(this.root, relativeDir), newPath); // if the path is not relative or absolute, try to resolve it in node_modules
  12288. if (!useFileResolve && newPath[0] !== "." && !_path.default.isAbsolute(newPath)) {
  12289. try {
  12290. fileRelativePath = require.resolve(newPath);
  12291. } catch (e) {// noop
  12292. }
  12293. }
  12294. const tokens = this.tokensByFile[fileRelativePath];
  12295. if (tokens) return tokens;
  12296. return new Promise((resolve, reject) => {
  12297. this.fs.readFile(fileRelativePath, "utf-8", async (err, source) => {
  12298. if (err) reject(err);
  12299. const {
  12300. injectableSource,
  12301. exportTokens
  12302. } = await this.core.load(source, rootRelativePath, trace, this.fetch.bind(this));
  12303. this.sources[fileRelativePath] = injectableSource;
  12304. this.traces[trace] = fileRelativePath;
  12305. this.tokensByFile[fileRelativePath] = exportTokens;
  12306. resolve(exportTokens);
  12307. });
  12308. });
  12309. }
  12310. get finalSource() {
  12311. const traces = this.traces;
  12312. const sources = this.sources;
  12313. let written = new Set();
  12314. return Object.keys(traces).sort(traceKeySorter).map(key => {
  12315. const filename = traces[key];
  12316. if (written.has(filename)) {
  12317. return null;
  12318. }
  12319. written.add(filename);
  12320. return sources[filename];
  12321. }).join("");
  12322. }
  12323. };
  12324. FileSystemLoader.default = FileSystemLoader$1;
  12325. return FileSystemLoader;
  12326. }
  12327. var scoping = {};
  12328. var src$3 = {exports: {}};
  12329. var topologicalSort_1;
  12330. var hasRequiredTopologicalSort;
  12331. function requireTopologicalSort () {
  12332. if (hasRequiredTopologicalSort) return topologicalSort_1;
  12333. hasRequiredTopologicalSort = 1;
  12334. const PERMANENT_MARKER = 2;
  12335. const TEMPORARY_MARKER = 1;
  12336. function createError(node, graph) {
  12337. const er = new Error("Nondeterministic import's order");
  12338. const related = graph[node];
  12339. const relatedNode = related.find(
  12340. (relatedNode) => graph[relatedNode].indexOf(node) > -1
  12341. );
  12342. er.nodes = [node, relatedNode];
  12343. return er;
  12344. }
  12345. function walkGraph(node, graph, state, result, strict) {
  12346. if (state[node] === PERMANENT_MARKER) {
  12347. return;
  12348. }
  12349. if (state[node] === TEMPORARY_MARKER) {
  12350. if (strict) {
  12351. return createError(node, graph);
  12352. }
  12353. return;
  12354. }
  12355. state[node] = TEMPORARY_MARKER;
  12356. const children = graph[node];
  12357. const length = children.length;
  12358. for (let i = 0; i < length; ++i) {
  12359. const error = walkGraph(children[i], graph, state, result, strict);
  12360. if (error instanceof Error) {
  12361. return error;
  12362. }
  12363. }
  12364. state[node] = PERMANENT_MARKER;
  12365. result.push(node);
  12366. }
  12367. function topologicalSort(graph, strict) {
  12368. const result = [];
  12369. const state = {};
  12370. const nodes = Object.keys(graph);
  12371. const length = nodes.length;
  12372. for (let i = 0; i < length; ++i) {
  12373. const er = walkGraph(nodes[i], graph, state, result, strict);
  12374. if (er instanceof Error) {
  12375. return er;
  12376. }
  12377. }
  12378. return result;
  12379. }
  12380. topologicalSort_1 = topologicalSort;
  12381. return topologicalSort_1;
  12382. }
  12383. var hasRequiredSrc$3;
  12384. function requireSrc$3 () {
  12385. if (hasRequiredSrc$3) return src$3.exports;
  12386. hasRequiredSrc$3 = 1;
  12387. const topologicalSort = /*@__PURE__*/ requireTopologicalSort();
  12388. const matchImports = /^(.+?)\s+from\s+(?:"([^"]+)"|'([^']+)'|(global))$/;
  12389. const icssImport = /^:import\((?:"([^"]+)"|'([^']+)')\)/;
  12390. const VISITED_MARKER = 1;
  12391. /**
  12392. * :import('G') {}
  12393. *
  12394. * Rule
  12395. * composes: ... from 'A'
  12396. * composes: ... from 'B'
  12397. * Rule
  12398. * composes: ... from 'A'
  12399. * composes: ... from 'A'
  12400. * composes: ... from 'C'
  12401. *
  12402. * Results in:
  12403. *
  12404. * graph: {
  12405. * G: [],
  12406. * A: [],
  12407. * B: ['A'],
  12408. * C: ['A'],
  12409. * }
  12410. */
  12411. function addImportToGraph(importId, parentId, graph, visited) {
  12412. const siblingsId = parentId + "_" + "siblings";
  12413. const visitedId = parentId + "_" + importId;
  12414. if (visited[visitedId] !== VISITED_MARKER) {
  12415. if (!Array.isArray(visited[siblingsId])) {
  12416. visited[siblingsId] = [];
  12417. }
  12418. const siblings = visited[siblingsId];
  12419. if (Array.isArray(graph[importId])) {
  12420. graph[importId] = graph[importId].concat(siblings);
  12421. } else {
  12422. graph[importId] = siblings.slice();
  12423. }
  12424. visited[visitedId] = VISITED_MARKER;
  12425. siblings.push(importId);
  12426. }
  12427. }
  12428. src$3.exports = (options = {}) => {
  12429. let importIndex = 0;
  12430. const createImportedName =
  12431. typeof options.createImportedName !== "function"
  12432. ? (importName /*, path*/) =>
  12433. `i__imported_${importName.replace(/\W/g, "_")}_${importIndex++}`
  12434. : options.createImportedName;
  12435. const failOnWrongOrder = options.failOnWrongOrder;
  12436. return {
  12437. postcssPlugin: "postcss-modules-extract-imports",
  12438. prepare() {
  12439. const graph = {};
  12440. const visited = {};
  12441. const existingImports = {};
  12442. const importDecls = {};
  12443. const imports = {};
  12444. return {
  12445. Once(root, postcss) {
  12446. // Check the existing imports order and save refs
  12447. root.walkRules((rule) => {
  12448. const matches = icssImport.exec(rule.selector);
  12449. if (matches) {
  12450. const [, /*match*/ doubleQuotePath, singleQuotePath] = matches;
  12451. const importPath = doubleQuotePath || singleQuotePath;
  12452. addImportToGraph(importPath, "root", graph, visited);
  12453. existingImports[importPath] = rule;
  12454. }
  12455. });
  12456. root.walkDecls(/^composes$/, (declaration) => {
  12457. const multiple = declaration.value.split(",");
  12458. const values = [];
  12459. multiple.forEach((value) => {
  12460. const matches = value.trim().match(matchImports);
  12461. if (!matches) {
  12462. values.push(value);
  12463. return;
  12464. }
  12465. let tmpSymbols;
  12466. let [
  12467. ,
  12468. /*match*/ symbols,
  12469. doubleQuotePath,
  12470. singleQuotePath,
  12471. global,
  12472. ] = matches;
  12473. if (global) {
  12474. // Composing globals simply means changing these classes to wrap them in global(name)
  12475. tmpSymbols = symbols.split(/\s+/).map((s) => `global(${s})`);
  12476. } else {
  12477. const importPath = doubleQuotePath || singleQuotePath;
  12478. let parent = declaration.parent;
  12479. let parentIndexes = "";
  12480. while (parent.type !== "root") {
  12481. parentIndexes =
  12482. parent.parent.index(parent) + "_" + parentIndexes;
  12483. parent = parent.parent;
  12484. }
  12485. const { selector } = declaration.parent;
  12486. const parentRule = `_${parentIndexes}${selector}`;
  12487. addImportToGraph(importPath, parentRule, graph, visited);
  12488. importDecls[importPath] = declaration;
  12489. imports[importPath] = imports[importPath] || {};
  12490. tmpSymbols = symbols.split(/\s+/).map((s) => {
  12491. if (!imports[importPath][s]) {
  12492. imports[importPath][s] = createImportedName(s, importPath);
  12493. }
  12494. return imports[importPath][s];
  12495. });
  12496. }
  12497. values.push(tmpSymbols.join(" "));
  12498. });
  12499. declaration.value = values.join(", ");
  12500. });
  12501. const importsOrder = topologicalSort(graph, failOnWrongOrder);
  12502. if (importsOrder instanceof Error) {
  12503. const importPath = importsOrder.nodes.find((importPath) =>
  12504. // eslint-disable-next-line no-prototype-builtins
  12505. importDecls.hasOwnProperty(importPath)
  12506. );
  12507. const decl = importDecls[importPath];
  12508. throw decl.error(
  12509. "Failed to resolve order of composed modules " +
  12510. importsOrder.nodes
  12511. .map((importPath) => "`" + importPath + "`")
  12512. .join(", ") +
  12513. ".",
  12514. {
  12515. plugin: "postcss-modules-extract-imports",
  12516. word: "composes",
  12517. }
  12518. );
  12519. }
  12520. let lastImportRule;
  12521. importsOrder.forEach((path) => {
  12522. const importedSymbols = imports[path];
  12523. let rule = existingImports[path];
  12524. if (!rule && importedSymbols) {
  12525. rule = postcss.rule({
  12526. selector: `:import("${path}")`,
  12527. raws: { after: "\n" },
  12528. });
  12529. if (lastImportRule) {
  12530. root.insertAfter(lastImportRule, rule);
  12531. } else {
  12532. root.prepend(rule);
  12533. }
  12534. }
  12535. lastImportRule = rule;
  12536. if (!importedSymbols) {
  12537. return;
  12538. }
  12539. Object.keys(importedSymbols).forEach((importedSymbol) => {
  12540. rule.append(
  12541. postcss.decl({
  12542. value: importedSymbol,
  12543. prop: importedSymbols[importedSymbol],
  12544. raws: { before: "\n " },
  12545. })
  12546. );
  12547. });
  12548. });
  12549. },
  12550. };
  12551. },
  12552. };
  12553. };
  12554. src$3.exports.postcss = true;
  12555. return src$3.exports;
  12556. }
  12557. var wasmHash = {exports: {}};
  12558. /*
  12559. MIT License http://www.opensource.org/licenses/mit-license.php
  12560. Author Tobias Koppers @sokra
  12561. */
  12562. var hasRequiredWasmHash;
  12563. function requireWasmHash () {
  12564. if (hasRequiredWasmHash) return wasmHash.exports;
  12565. hasRequiredWasmHash = 1;
  12566. // 65536 is the size of a wasm memory page
  12567. // 64 is the maximum chunk size for every possible wasm hash implementation
  12568. // 4 is the maximum number of bytes per char for string encoding (max is utf-8)
  12569. // ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64
  12570. const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & -4;
  12571. class WasmHash {
  12572. /**
  12573. * @param {WebAssembly.Instance} instance wasm instance
  12574. * @param {WebAssembly.Instance[]} instancesPool pool of instances
  12575. * @param {number} chunkSize size of data chunks passed to wasm
  12576. * @param {number} digestSize size of digest returned by wasm
  12577. */
  12578. constructor(instance, instancesPool, chunkSize, digestSize) {
  12579. const exports = /** @type {any} */ (instance.exports);
  12580. exports.init();
  12581. this.exports = exports;
  12582. this.mem = Buffer.from(exports.memory.buffer, 0, 65536);
  12583. this.buffered = 0;
  12584. this.instancesPool = instancesPool;
  12585. this.chunkSize = chunkSize;
  12586. this.digestSize = digestSize;
  12587. }
  12588. reset() {
  12589. this.buffered = 0;
  12590. this.exports.init();
  12591. }
  12592. /**
  12593. * @param {Buffer | string} data data
  12594. * @param {BufferEncoding=} encoding encoding
  12595. * @returns {this} itself
  12596. */
  12597. update(data, encoding) {
  12598. if (typeof data === "string") {
  12599. while (data.length > MAX_SHORT_STRING) {
  12600. this._updateWithShortString(data.slice(0, MAX_SHORT_STRING), encoding);
  12601. data = data.slice(MAX_SHORT_STRING);
  12602. }
  12603. this._updateWithShortString(data, encoding);
  12604. return this;
  12605. }
  12606. this._updateWithBuffer(data);
  12607. return this;
  12608. }
  12609. /**
  12610. * @param {string} data data
  12611. * @param {BufferEncoding=} encoding encoding
  12612. * @returns {void}
  12613. */
  12614. _updateWithShortString(data, encoding) {
  12615. const { exports, buffered, mem, chunkSize } = this;
  12616. let endPos;
  12617. if (data.length < 70) {
  12618. if (!encoding || encoding === "utf-8" || encoding === "utf8") {
  12619. endPos = buffered;
  12620. for (let i = 0; i < data.length; i++) {
  12621. const cc = data.charCodeAt(i);
  12622. if (cc < 0x80) {
  12623. mem[endPos++] = cc;
  12624. } else if (cc < 0x800) {
  12625. mem[endPos] = (cc >> 6) | 0xc0;
  12626. mem[endPos + 1] = (cc & 0x3f) | 0x80;
  12627. endPos += 2;
  12628. } else {
  12629. // bail-out for weird chars
  12630. endPos += mem.write(data.slice(i), endPos, encoding);
  12631. break;
  12632. }
  12633. }
  12634. } else if (encoding === "latin1") {
  12635. endPos = buffered;
  12636. for (let i = 0; i < data.length; i++) {
  12637. const cc = data.charCodeAt(i);
  12638. mem[endPos++] = cc;
  12639. }
  12640. } else {
  12641. endPos = buffered + mem.write(data, buffered, encoding);
  12642. }
  12643. } else {
  12644. endPos = buffered + mem.write(data, buffered, encoding);
  12645. }
  12646. if (endPos < chunkSize) {
  12647. this.buffered = endPos;
  12648. } else {
  12649. const l = endPos & ~(this.chunkSize - 1);
  12650. exports.update(l);
  12651. const newBuffered = endPos - l;
  12652. this.buffered = newBuffered;
  12653. if (newBuffered > 0) {
  12654. mem.copyWithin(0, l, endPos);
  12655. }
  12656. }
  12657. }
  12658. /**
  12659. * @param {Buffer} data data
  12660. * @returns {void}
  12661. */
  12662. _updateWithBuffer(data) {
  12663. const { exports, buffered, mem } = this;
  12664. const length = data.length;
  12665. if (buffered + length < this.chunkSize) {
  12666. data.copy(mem, buffered, 0, length);
  12667. this.buffered += length;
  12668. } else {
  12669. const l = (buffered + length) & ~(this.chunkSize - 1);
  12670. if (l > 65536) {
  12671. let i = 65536 - buffered;
  12672. data.copy(mem, buffered, 0, i);
  12673. exports.update(65536);
  12674. const stop = l - buffered - 65536;
  12675. while (i < stop) {
  12676. data.copy(mem, 0, i, i + 65536);
  12677. exports.update(65536);
  12678. i += 65536;
  12679. }
  12680. data.copy(mem, 0, i, l - buffered);
  12681. exports.update(l - buffered - i);
  12682. } else {
  12683. data.copy(mem, buffered, 0, l - buffered);
  12684. exports.update(l);
  12685. }
  12686. const newBuffered = length + buffered - l;
  12687. this.buffered = newBuffered;
  12688. if (newBuffered > 0) {
  12689. data.copy(mem, 0, length - newBuffered, length);
  12690. }
  12691. }
  12692. }
  12693. digest(type) {
  12694. const { exports, buffered, mem, digestSize } = this;
  12695. exports.final(buffered);
  12696. this.instancesPool.push(this);
  12697. const hex = mem.toString("latin1", 0, digestSize);
  12698. if (type === "hex") {
  12699. return hex;
  12700. }
  12701. if (type === "binary" || !type) {
  12702. return Buffer.from(hex, "hex");
  12703. }
  12704. return Buffer.from(hex, "hex").toString(type);
  12705. }
  12706. }
  12707. const create = (wasmModule, instancesPool, chunkSize, digestSize) => {
  12708. if (instancesPool.length > 0) {
  12709. const old = instancesPool.pop();
  12710. old.reset();
  12711. return old;
  12712. } else {
  12713. return new WasmHash(
  12714. new WebAssembly.Instance(wasmModule),
  12715. instancesPool,
  12716. chunkSize,
  12717. digestSize
  12718. );
  12719. }
  12720. };
  12721. wasmHash.exports = create;
  12722. wasmHash.exports.MAX_SHORT_STRING = MAX_SHORT_STRING;
  12723. return wasmHash.exports;
  12724. }
  12725. /*
  12726. MIT License http://www.opensource.org/licenses/mit-license.php
  12727. Author Tobias Koppers @sokra
  12728. */
  12729. var xxhash64_1;
  12730. var hasRequiredXxhash64;
  12731. function requireXxhash64 () {
  12732. if (hasRequiredXxhash64) return xxhash64_1;
  12733. hasRequiredXxhash64 = 1;
  12734. const create = /*@__PURE__*/ requireWasmHash();
  12735. //#region wasm code: xxhash64 (../../../assembly/hash/xxhash64.asm.ts) --initialMemory 1
  12736. const xxhash64 = new WebAssembly.Module(
  12737. Buffer.from(
  12738. // 1173 bytes
  12739. "AGFzbQEAAAABCAJgAX8AYAAAAwQDAQAABQMBAAEGGgV+AUIAC34BQgALfgFCAAt+AUIAC34BQgALByIEBGluaXQAAAZ1cGRhdGUAAQVmaW5hbAACBm1lbW9yeQIACrUIAzAAQtbrgu7q/Yn14AAkAELP1tO+0ser2UIkAUIAJAJC+erQ0OfJoeThACQDQgAkBAvUAQIBfwR+IABFBEAPCyMEIACtfCQEIwAhAiMBIQMjAiEEIwMhBQNAIAIgASkDAELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiECIAMgASkDCELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEDIAQgASkDEELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEEIAUgASkDGELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEFIAAgAUEgaiIBSw0ACyACJAAgAyQBIAQkAiAFJAMLqwYCAX8EfiMEQgBSBH4jACICQgGJIwEiA0IHiXwjAiIEQgyJfCMDIgVCEol8IAJCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0gA0LP1tO+0ser2UJ+Qh+JQoeVr6+Ytt6bnn9+hUKHla+vmLbem55/fkKdo7Xqg7GNivoAfSAEQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IAVCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0FQsXP2bLx5brqJwsjBCAArXx8IQIDQCABQQhqIABNBEAgAiABKQMAQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQhuJQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IQIgAUEIaiEBDAELCyABQQRqIABNBEACfyACIAE1AgBCh5Wvr5i23puef36FQheJQs/W077Sx6vZQn5C+fPd8Zn2masWfCECIAFBBGoLIQELA0AgACABRwRAIAIgATEAAELFz9my8eW66id+hUILiUKHla+vmLbem55/fiECIAFBAWohAQwBCwtBACACIAJCIYiFQs/W077Sx6vZQn4iAiACQh2IhUL5893xmfaZqxZ+IgIgAkIgiIUiAkIgiCIDQv//A4NCIIYgA0KAgPz/D4NCEIiEIgNC/4GAgPAfg0IQhiADQoD+g4CA4D+DQgiIhCIDQo+AvIDwgcAHg0IIhiADQvCBwIeAnoD4AINCBIiEIgNChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IANCsODAgYOGjJgwhHw3AwBBCCACQv////8PgyICQv//A4NCIIYgAkKAgPz/D4NCEIiEIgJC/4GAgPAfg0IQhiACQoD+g4CA4D+DQgiIhCICQo+AvIDwgcAHg0IIhiACQvCBwIeAnoD4AINCBIiEIgJChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IAJCsODAgYOGjJgwhHw3AwAL",
  12740. "base64"
  12741. )
  12742. );
  12743. //#endregion
  12744. xxhash64_1 = create.bind(null, xxhash64, [], 32, 16);
  12745. return xxhash64_1;
  12746. }
  12747. var BatchedHash_1;
  12748. var hasRequiredBatchedHash;
  12749. function requireBatchedHash () {
  12750. if (hasRequiredBatchedHash) return BatchedHash_1;
  12751. hasRequiredBatchedHash = 1;
  12752. const MAX_SHORT_STRING = /*@__PURE__*/ requireWasmHash().MAX_SHORT_STRING;
  12753. class BatchedHash {
  12754. constructor(hash) {
  12755. this.string = undefined;
  12756. this.encoding = undefined;
  12757. this.hash = hash;
  12758. }
  12759. /**
  12760. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  12761. * @param {string|Buffer} data data
  12762. * @param {string=} inputEncoding data encoding
  12763. * @returns {this} updated hash
  12764. */
  12765. update(data, inputEncoding) {
  12766. if (this.string !== undefined) {
  12767. if (
  12768. typeof data === "string" &&
  12769. inputEncoding === this.encoding &&
  12770. this.string.length + data.length < MAX_SHORT_STRING
  12771. ) {
  12772. this.string += data;
  12773. return this;
  12774. }
  12775. this.hash.update(this.string, this.encoding);
  12776. this.string = undefined;
  12777. }
  12778. if (typeof data === "string") {
  12779. if (
  12780. data.length < MAX_SHORT_STRING &&
  12781. // base64 encoding is not valid since it may contain padding chars
  12782. (!inputEncoding || !inputEncoding.startsWith("ba"))
  12783. ) {
  12784. this.string = data;
  12785. this.encoding = inputEncoding;
  12786. } else {
  12787. this.hash.update(data, inputEncoding);
  12788. }
  12789. } else {
  12790. this.hash.update(data);
  12791. }
  12792. return this;
  12793. }
  12794. /**
  12795. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  12796. * @param {string=} encoding encoding of the return value
  12797. * @returns {string|Buffer} digest
  12798. */
  12799. digest(encoding) {
  12800. if (this.string !== undefined) {
  12801. this.hash.update(this.string, this.encoding);
  12802. }
  12803. return this.hash.digest(encoding);
  12804. }
  12805. }
  12806. BatchedHash_1 = BatchedHash;
  12807. return BatchedHash_1;
  12808. }
  12809. /*
  12810. MIT License http://www.opensource.org/licenses/mit-license.php
  12811. Author Tobias Koppers @sokra
  12812. */
  12813. var md4_1;
  12814. var hasRequiredMd4;
  12815. function requireMd4 () {
  12816. if (hasRequiredMd4) return md4_1;
  12817. hasRequiredMd4 = 1;
  12818. const create = /*@__PURE__*/ requireWasmHash();
  12819. //#region wasm code: md4 (../../../assembly/hash/md4.asm.ts) --initialMemory 1
  12820. const md4 = new WebAssembly.Module(
  12821. Buffer.from(
  12822. // 2150 bytes
  12823. "AGFzbQEAAAABCAJgAX8AYAAAAwUEAQAAAAUDAQABBhoFfwFBAAt/AUEAC38BQQALfwFBAAt/AUEACwciBARpbml0AAAGdXBkYXRlAAIFZmluYWwAAwZtZW1vcnkCAAqFEAQmAEGBxpS6BiQBQYnXtv5+JAJB/rnrxXkkA0H2qMmBASQEQQAkAAvMCgEYfyMBIQojAiEGIwMhByMEIQgDQCAAIAVLBEAgBSgCCCINIAcgBiAFKAIEIgsgCCAHIAUoAgAiDCAKIAggBiAHIAhzcXNqakEDdyIDIAYgB3Nxc2pqQQd3IgEgAyAGc3FzampBC3chAiAFKAIUIg8gASACIAUoAhAiCSADIAEgBSgCDCIOIAYgAyACIAEgA3Nxc2pqQRN3IgQgASACc3FzampBA3ciAyACIARzcXNqakEHdyEBIAUoAiAiEiADIAEgBSgCHCIRIAQgAyAFKAIYIhAgAiAEIAEgAyAEc3FzampBC3ciAiABIANzcXNqakETdyIEIAEgAnNxc2pqQQN3IQMgBSgCLCIVIAQgAyAFKAIoIhQgAiAEIAUoAiQiEyABIAIgAyACIARzcXNqakEHdyIBIAMgBHNxc2pqQQt3IgIgASADc3FzampBE3chBCAPIBAgCSAVIBQgEyAFKAI4IhYgAiAEIAUoAjQiFyABIAIgBSgCMCIYIAMgASAEIAEgAnNxc2pqQQN3IgEgAiAEc3FzampBB3ciAiABIARzcXNqakELdyIDIAkgAiAMIAEgBSgCPCIJIAQgASADIAEgAnNxc2pqQRN3IgEgAiADcnEgAiADcXJqakGZ84nUBWpBA3ciAiABIANycSABIANxcmpqQZnzidQFakEFdyIEIAEgAnJxIAEgAnFyaiASakGZ84nUBWpBCXciAyAPIAQgCyACIBggASADIAIgBHJxIAIgBHFyampBmfOJ1AVqQQ13IgEgAyAEcnEgAyAEcXJqakGZ84nUBWpBA3ciAiABIANycSABIANxcmpqQZnzidQFakEFdyIEIAEgAnJxIAEgAnFyampBmfOJ1AVqQQl3IgMgECAEIAIgFyABIAMgAiAEcnEgAiAEcXJqakGZ84nUBWpBDXciASADIARycSADIARxcmogDWpBmfOJ1AVqQQN3IgIgASADcnEgASADcXJqakGZ84nUBWpBBXciBCABIAJycSABIAJxcmpqQZnzidQFakEJdyIDIBEgBCAOIAIgFiABIAMgAiAEcnEgAiAEcXJqakGZ84nUBWpBDXciASADIARycSADIARxcmpqQZnzidQFakEDdyICIAEgA3JxIAEgA3FyampBmfOJ1AVqQQV3IgQgASACcnEgASACcXJqakGZ84nUBWpBCXciAyAMIAIgAyAJIAEgAyACIARycSACIARxcmpqQZnzidQFakENdyIBcyAEc2pqQaHX5/YGakEDdyICIAQgASACcyADc2ogEmpBodfn9gZqQQl3IgRzIAFzampBodfn9gZqQQt3IgMgAiADIBggASADIARzIAJzampBodfn9gZqQQ93IgFzIARzaiANakGh1+f2BmpBA3ciAiAUIAQgASACcyADc2pqQaHX5/YGakEJdyIEcyABc2pqQaHX5/YGakELdyIDIAsgAiADIBYgASADIARzIAJzampBodfn9gZqQQ93IgFzIARzampBodfn9gZqQQN3IgIgEyAEIAEgAnMgA3NqakGh1+f2BmpBCXciBHMgAXNqakGh1+f2BmpBC3chAyAKIA4gAiADIBcgASADIARzIAJzampBodfn9gZqQQ93IgFzIARzampBodfn9gZqQQN3IgJqIQogBiAJIAEgESADIAIgFSAEIAEgAnMgA3NqakGh1+f2BmpBCXciBHMgAXNqakGh1+f2BmpBC3ciAyAEcyACc2pqQaHX5/YGakEPd2ohBiADIAdqIQcgBCAIaiEIIAVBQGshBQwBCwsgCiQBIAYkAiAHJAMgCCQECw0AIAAQASMAIABqJAAL/wQCA38BfiMAIABqrUIDhiEEIABByABqQUBxIgJBCGshAyAAIgFBAWohACABQYABOgAAA0AgACACSUEAIABBB3EbBEAgAEEAOgAAIABBAWohAAwBCwsDQCAAIAJJBEAgAEIANwMAIABBCGohAAwBCwsgAyAENwMAIAIQAUEAIwGtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEIIwKtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEQIwOtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEYIwStIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAAs=",
  12824. "base64"
  12825. )
  12826. );
  12827. //#endregion
  12828. md4_1 = create.bind(null, md4, [], 64, 32);
  12829. return md4_1;
  12830. }
  12831. var BulkUpdateDecorator_1;
  12832. var hasRequiredBulkUpdateDecorator;
  12833. function requireBulkUpdateDecorator () {
  12834. if (hasRequiredBulkUpdateDecorator) return BulkUpdateDecorator_1;
  12835. hasRequiredBulkUpdateDecorator = 1;
  12836. const BULK_SIZE = 2000;
  12837. // We are using an object instead of a Map as this will stay static during the runtime
  12838. // so access to it can be optimized by v8
  12839. const digestCaches = {};
  12840. class BulkUpdateDecorator {
  12841. /**
  12842. * @param {Hash | function(): Hash} hashOrFactory function to create a hash
  12843. * @param {string=} hashKey key for caching
  12844. */
  12845. constructor(hashOrFactory, hashKey) {
  12846. this.hashKey = hashKey;
  12847. if (typeof hashOrFactory === "function") {
  12848. this.hashFactory = hashOrFactory;
  12849. this.hash = undefined;
  12850. } else {
  12851. this.hashFactory = undefined;
  12852. this.hash = hashOrFactory;
  12853. }
  12854. this.buffer = "";
  12855. }
  12856. /**
  12857. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  12858. * @param {string|Buffer} data data
  12859. * @param {string=} inputEncoding data encoding
  12860. * @returns {this} updated hash
  12861. */
  12862. update(data, inputEncoding) {
  12863. if (
  12864. inputEncoding !== undefined ||
  12865. typeof data !== "string" ||
  12866. data.length > BULK_SIZE
  12867. ) {
  12868. if (this.hash === undefined) {
  12869. this.hash = this.hashFactory();
  12870. }
  12871. if (this.buffer.length > 0) {
  12872. this.hash.update(this.buffer);
  12873. this.buffer = "";
  12874. }
  12875. this.hash.update(data, inputEncoding);
  12876. } else {
  12877. this.buffer += data;
  12878. if (this.buffer.length > BULK_SIZE) {
  12879. if (this.hash === undefined) {
  12880. this.hash = this.hashFactory();
  12881. }
  12882. this.hash.update(this.buffer);
  12883. this.buffer = "";
  12884. }
  12885. }
  12886. return this;
  12887. }
  12888. /**
  12889. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  12890. * @param {string=} encoding encoding of the return value
  12891. * @returns {string|Buffer} digest
  12892. */
  12893. digest(encoding) {
  12894. let digestCache;
  12895. const buffer = this.buffer;
  12896. if (this.hash === undefined) {
  12897. // short data for hash, we can use caching
  12898. const cacheKey = `${this.hashKey}-${encoding}`;
  12899. digestCache = digestCaches[cacheKey];
  12900. if (digestCache === undefined) {
  12901. digestCache = digestCaches[cacheKey] = new Map();
  12902. }
  12903. const cacheEntry = digestCache.get(buffer);
  12904. if (cacheEntry !== undefined) {
  12905. return cacheEntry;
  12906. }
  12907. this.hash = this.hashFactory();
  12908. }
  12909. if (buffer.length > 0) {
  12910. this.hash.update(buffer);
  12911. }
  12912. const digestResult = this.hash.digest(encoding);
  12913. if (digestCache !== undefined) {
  12914. digestCache.set(buffer, digestResult);
  12915. }
  12916. return digestResult;
  12917. }
  12918. }
  12919. BulkUpdateDecorator_1 = BulkUpdateDecorator;
  12920. return BulkUpdateDecorator_1;
  12921. }
  12922. var getHashDigest_1;
  12923. var hasRequiredGetHashDigest;
  12924. function requireGetHashDigest () {
  12925. if (hasRequiredGetHashDigest) return getHashDigest_1;
  12926. hasRequiredGetHashDigest = 1;
  12927. const baseEncodeTables = {
  12928. 26: "abcdefghijklmnopqrstuvwxyz",
  12929. 32: "123456789abcdefghjkmnpqrstuvwxyz", // no 0lio
  12930. 36: "0123456789abcdefghijklmnopqrstuvwxyz",
  12931. 49: "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no lIO
  12932. 52: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12933. 58: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no 0lIO
  12934. 62: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12935. 64: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_",
  12936. };
  12937. /**
  12938. * @param {Uint32Array} uint32Array Treated as a long base-0x100000000 number, little endian
  12939. * @param {number} divisor The divisor
  12940. * @return {number} Modulo (remainder) of the division
  12941. */
  12942. function divmod32(uint32Array, divisor) {
  12943. let carry = 0;
  12944. for (let i = uint32Array.length - 1; i >= 0; i--) {
  12945. const value = carry * 0x100000000 + uint32Array[i];
  12946. carry = value % divisor;
  12947. uint32Array[i] = Math.floor(value / divisor);
  12948. }
  12949. return carry;
  12950. }
  12951. function encodeBufferToBase(buffer, base, length) {
  12952. const encodeTable = baseEncodeTables[base];
  12953. if (!encodeTable) {
  12954. throw new Error("Unknown encoding base" + base);
  12955. }
  12956. // Input bits are only enough to generate this many characters
  12957. const limit = Math.ceil((buffer.length * 8) / Math.log2(base));
  12958. length = Math.min(length, limit);
  12959. // Most of the crypto digests (if not all) has length a multiple of 4 bytes.
  12960. // Fewer numbers in the array means faster math.
  12961. const uint32Array = new Uint32Array(Math.ceil(buffer.length / 4));
  12962. // Make sure the input buffer data is copied and is not mutated by reference.
  12963. // divmod32() would corrupt the BulkUpdateDecorator cache otherwise.
  12964. buffer.copy(Buffer.from(uint32Array.buffer));
  12965. let output = "";
  12966. for (let i = 0; i < length; i++) {
  12967. output = encodeTable[divmod32(uint32Array, base)] + output;
  12968. }
  12969. return output;
  12970. }
  12971. let crypto = undefined;
  12972. let createXXHash64 = undefined;
  12973. let createMd4 = undefined;
  12974. let BatchedHash = undefined;
  12975. let BulkUpdateDecorator = undefined;
  12976. function getHashDigest(buffer, algorithm, digestType, maxLength) {
  12977. algorithm = algorithm || "xxhash64";
  12978. maxLength = maxLength || 9999;
  12979. let hash;
  12980. if (algorithm === "xxhash64") {
  12981. if (createXXHash64 === undefined) {
  12982. createXXHash64 = /*@__PURE__*/ requireXxhash64();
  12983. if (BatchedHash === undefined) {
  12984. BatchedHash = /*@__PURE__*/ requireBatchedHash();
  12985. }
  12986. }
  12987. hash = new BatchedHash(createXXHash64());
  12988. } else if (algorithm === "md4") {
  12989. if (createMd4 === undefined) {
  12990. createMd4 = /*@__PURE__*/ requireMd4();
  12991. if (BatchedHash === undefined) {
  12992. BatchedHash = /*@__PURE__*/ requireBatchedHash();
  12993. }
  12994. }
  12995. hash = new BatchedHash(createMd4());
  12996. } else if (algorithm === "native-md4") {
  12997. if (typeof crypto === "undefined") {
  12998. crypto = require("crypto");
  12999. if (BulkUpdateDecorator === undefined) {
  13000. BulkUpdateDecorator = /*@__PURE__*/ requireBulkUpdateDecorator();
  13001. }
  13002. }
  13003. hash = new BulkUpdateDecorator(() => crypto.createHash("md4"), "md4");
  13004. } else {
  13005. if (typeof crypto === "undefined") {
  13006. crypto = require("crypto");
  13007. if (BulkUpdateDecorator === undefined) {
  13008. BulkUpdateDecorator = /*@__PURE__*/ requireBulkUpdateDecorator();
  13009. }
  13010. }
  13011. hash = new BulkUpdateDecorator(
  13012. () => crypto.createHash(algorithm),
  13013. algorithm
  13014. );
  13015. }
  13016. hash.update(buffer);
  13017. if (
  13018. digestType === "base26" ||
  13019. digestType === "base32" ||
  13020. digestType === "base36" ||
  13021. digestType === "base49" ||
  13022. digestType === "base52" ||
  13023. digestType === "base58" ||
  13024. digestType === "base62" ||
  13025. digestType === "base64safe"
  13026. ) {
  13027. return encodeBufferToBase(
  13028. hash.digest(),
  13029. digestType === "base64safe" ? 64 : digestType.substr(4),
  13030. maxLength
  13031. );
  13032. }
  13033. return hash.digest(digestType || "hex").substr(0, maxLength);
  13034. }
  13035. getHashDigest_1 = getHashDigest;
  13036. return getHashDigest_1;
  13037. }
  13038. var interpolateName_1;
  13039. var hasRequiredInterpolateName;
  13040. function requireInterpolateName () {
  13041. if (hasRequiredInterpolateName) return interpolateName_1;
  13042. hasRequiredInterpolateName = 1;
  13043. const path = path$1;
  13044. const getHashDigest = /*@__PURE__*/ requireGetHashDigest();
  13045. function interpolateName(loaderContext, name, options = {}) {
  13046. let filename;
  13047. const hasQuery =
  13048. loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1;
  13049. if (typeof name === "function") {
  13050. filename = name(
  13051. loaderContext.resourcePath,
  13052. hasQuery ? loaderContext.resourceQuery : undefined
  13053. );
  13054. } else {
  13055. filename = name || "[hash].[ext]";
  13056. }
  13057. const context = options.context;
  13058. const content = options.content;
  13059. const regExp = options.regExp;
  13060. let ext = "bin";
  13061. let basename = "file";
  13062. let directory = "";
  13063. let folder = "";
  13064. let query = "";
  13065. if (loaderContext.resourcePath) {
  13066. const parsed = path.parse(loaderContext.resourcePath);
  13067. let resourcePath = loaderContext.resourcePath;
  13068. if (parsed.ext) {
  13069. ext = parsed.ext.substr(1);
  13070. }
  13071. if (parsed.dir) {
  13072. basename = parsed.name;
  13073. resourcePath = parsed.dir + path.sep;
  13074. }
  13075. if (typeof context !== "undefined") {
  13076. directory = path
  13077. .relative(context, resourcePath + "_")
  13078. .replace(/\\/g, "/")
  13079. .replace(/\.\.(\/)?/g, "_$1");
  13080. directory = directory.substr(0, directory.length - 1);
  13081. } else {
  13082. directory = resourcePath.replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
  13083. }
  13084. if (directory.length <= 1) {
  13085. directory = "";
  13086. } else {
  13087. // directory.length > 1
  13088. folder = path.basename(directory);
  13089. }
  13090. }
  13091. if (loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1) {
  13092. query = loaderContext.resourceQuery;
  13093. const hashIdx = query.indexOf("#");
  13094. if (hashIdx >= 0) {
  13095. query = query.substr(0, hashIdx);
  13096. }
  13097. }
  13098. let url = filename;
  13099. if (content) {
  13100. // Match hash template
  13101. url = url
  13102. // `hash` and `contenthash` are same in `loader-utils` context
  13103. // let's keep `hash` for backward compatibility
  13104. .replace(
  13105. /\[(?:([^[:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*(?:safe)?))?(?::(\d+))?\]/gi,
  13106. (all, hashType, digestType, maxLength) =>
  13107. getHashDigest(content, hashType, digestType, parseInt(maxLength, 10))
  13108. );
  13109. }
  13110. url = url
  13111. .replace(/\[ext\]/gi, () => ext)
  13112. .replace(/\[name\]/gi, () => basename)
  13113. .replace(/\[path\]/gi, () => directory)
  13114. .replace(/\[folder\]/gi, () => folder)
  13115. .replace(/\[query\]/gi, () => query);
  13116. if (regExp && loaderContext.resourcePath) {
  13117. const match = loaderContext.resourcePath.match(new RegExp(regExp));
  13118. match &&
  13119. match.forEach((matched, i) => {
  13120. url = url.replace(new RegExp("\\[" + i + "\\]", "ig"), matched);
  13121. });
  13122. }
  13123. if (
  13124. typeof loaderContext.options === "object" &&
  13125. typeof loaderContext.options.customInterpolateName === "function"
  13126. ) {
  13127. url = loaderContext.options.customInterpolateName.call(
  13128. loaderContext,
  13129. url,
  13130. name,
  13131. options
  13132. );
  13133. }
  13134. return url;
  13135. }
  13136. interpolateName_1 = interpolateName;
  13137. return interpolateName_1;
  13138. }
  13139. var genericNames;
  13140. var hasRequiredGenericNames;
  13141. function requireGenericNames () {
  13142. if (hasRequiredGenericNames) return genericNames;
  13143. hasRequiredGenericNames = 1;
  13144. var interpolateName = /*@__PURE__*/ requireInterpolateName();
  13145. var path = path$1;
  13146. /**
  13147. * @param {string} pattern
  13148. * @param {object} options
  13149. * @param {string} options.context
  13150. * @param {string} options.hashPrefix
  13151. * @return {function}
  13152. */
  13153. genericNames = function createGenerator(pattern, options) {
  13154. options = options || {};
  13155. var context =
  13156. options && typeof options.context === "string"
  13157. ? options.context
  13158. : process.cwd();
  13159. var hashPrefix =
  13160. options && typeof options.hashPrefix === "string" ? options.hashPrefix : "";
  13161. /**
  13162. * @param {string} localName Usually a class name
  13163. * @param {string} filepath Absolute path
  13164. * @return {string}
  13165. */
  13166. return function generate(localName, filepath) {
  13167. var name = pattern.replace(/\[local\]/gi, localName);
  13168. var loaderContext = {
  13169. resourcePath: filepath,
  13170. };
  13171. var loaderOptions = {
  13172. content:
  13173. hashPrefix +
  13174. path.relative(context, filepath).replace(/\\/g, "/") +
  13175. "\x00" +
  13176. localName,
  13177. context: context,
  13178. };
  13179. var genericName = interpolateName(loaderContext, name, loaderOptions);
  13180. return genericName
  13181. .replace(new RegExp("[^a-zA-Z0-9\\-_\u00A0-\uFFFF]", "g"), "-")
  13182. .replace(/^((-?[0-9])|--)/, "_$1");
  13183. };
  13184. };
  13185. return genericNames;
  13186. }
  13187. var src$2 = {exports: {}};
  13188. var dist = {exports: {}};
  13189. var processor = {exports: {}};
  13190. var parser = {exports: {}};
  13191. var root = {exports: {}};
  13192. var container = {exports: {}};
  13193. var node = {exports: {}};
  13194. var util = {};
  13195. var unesc = {exports: {}};
  13196. var hasRequiredUnesc;
  13197. function requireUnesc () {
  13198. if (hasRequiredUnesc) return unesc.exports;
  13199. hasRequiredUnesc = 1;
  13200. (function (module, exports) {
  13201. exports.__esModule = true;
  13202. exports["default"] = unesc;
  13203. // Many thanks for this post which made this migration much easier.
  13204. // https://mathiasbynens.be/notes/css-escapes
  13205. /**
  13206. *
  13207. * @param {string} str
  13208. * @returns {[string, number]|undefined}
  13209. */
  13210. function gobbleHex(str) {
  13211. var lower = str.toLowerCase();
  13212. var hex = '';
  13213. var spaceTerminated = false;
  13214. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  13215. var code = lower.charCodeAt(i);
  13216. // check to see if we are dealing with a valid hex char [a-f|0-9]
  13217. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
  13218. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  13219. spaceTerminated = code === 32;
  13220. if (!valid) {
  13221. break;
  13222. }
  13223. hex += lower[i];
  13224. }
  13225. if (hex.length === 0) {
  13226. return undefined;
  13227. }
  13228. var codePoint = parseInt(hex, 16);
  13229. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
  13230. // Add special case for
  13231. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  13232. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  13233. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  13234. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  13235. }
  13236. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  13237. }
  13238. var CONTAINS_ESCAPE = /\\/;
  13239. function unesc(str) {
  13240. var needToProcess = CONTAINS_ESCAPE.test(str);
  13241. if (!needToProcess) {
  13242. return str;
  13243. }
  13244. var ret = "";
  13245. for (var i = 0; i < str.length; i++) {
  13246. if (str[i] === "\\") {
  13247. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  13248. if (gobbled !== undefined) {
  13249. ret += gobbled[0];
  13250. i += gobbled[1];
  13251. continue;
  13252. }
  13253. // Retain a pair of \\ if double escaped `\\\\`
  13254. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  13255. if (str[i + 1] === "\\") {
  13256. ret += "\\";
  13257. i++;
  13258. continue;
  13259. }
  13260. // if \\ is at the end of the string retain it
  13261. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  13262. if (str.length === i + 1) {
  13263. ret += str[i];
  13264. }
  13265. continue;
  13266. }
  13267. ret += str[i];
  13268. }
  13269. return ret;
  13270. }
  13271. module.exports = exports.default;
  13272. } (unesc, unesc.exports));
  13273. return unesc.exports;
  13274. }
  13275. var getProp = {exports: {}};
  13276. var hasRequiredGetProp;
  13277. function requireGetProp () {
  13278. if (hasRequiredGetProp) return getProp.exports;
  13279. hasRequiredGetProp = 1;
  13280. (function (module, exports) {
  13281. exports.__esModule = true;
  13282. exports["default"] = getProp;
  13283. function getProp(obj) {
  13284. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  13285. props[_key - 1] = arguments[_key];
  13286. }
  13287. while (props.length > 0) {
  13288. var prop = props.shift();
  13289. if (!obj[prop]) {
  13290. return undefined;
  13291. }
  13292. obj = obj[prop];
  13293. }
  13294. return obj;
  13295. }
  13296. module.exports = exports.default;
  13297. } (getProp, getProp.exports));
  13298. return getProp.exports;
  13299. }
  13300. var ensureObject = {exports: {}};
  13301. var hasRequiredEnsureObject;
  13302. function requireEnsureObject () {
  13303. if (hasRequiredEnsureObject) return ensureObject.exports;
  13304. hasRequiredEnsureObject = 1;
  13305. (function (module, exports) {
  13306. exports.__esModule = true;
  13307. exports["default"] = ensureObject;
  13308. function ensureObject(obj) {
  13309. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  13310. props[_key - 1] = arguments[_key];
  13311. }
  13312. while (props.length > 0) {
  13313. var prop = props.shift();
  13314. if (!obj[prop]) {
  13315. obj[prop] = {};
  13316. }
  13317. obj = obj[prop];
  13318. }
  13319. }
  13320. module.exports = exports.default;
  13321. } (ensureObject, ensureObject.exports));
  13322. return ensureObject.exports;
  13323. }
  13324. var stripComments = {exports: {}};
  13325. var hasRequiredStripComments;
  13326. function requireStripComments () {
  13327. if (hasRequiredStripComments) return stripComments.exports;
  13328. hasRequiredStripComments = 1;
  13329. (function (module, exports) {
  13330. exports.__esModule = true;
  13331. exports["default"] = stripComments;
  13332. function stripComments(str) {
  13333. var s = "";
  13334. var commentStart = str.indexOf("/*");
  13335. var lastEnd = 0;
  13336. while (commentStart >= 0) {
  13337. s = s + str.slice(lastEnd, commentStart);
  13338. var commentEnd = str.indexOf("*/", commentStart + 2);
  13339. if (commentEnd < 0) {
  13340. return s;
  13341. }
  13342. lastEnd = commentEnd + 2;
  13343. commentStart = str.indexOf("/*", lastEnd);
  13344. }
  13345. s = s + str.slice(lastEnd);
  13346. return s;
  13347. }
  13348. module.exports = exports.default;
  13349. } (stripComments, stripComments.exports));
  13350. return stripComments.exports;
  13351. }
  13352. var hasRequiredUtil;
  13353. function requireUtil () {
  13354. if (hasRequiredUtil) return util;
  13355. hasRequiredUtil = 1;
  13356. util.__esModule = true;
  13357. util.unesc = util.stripComments = util.getProp = util.ensureObject = void 0;
  13358. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc());
  13359. util.unesc = _unesc["default"];
  13360. var _getProp = _interopRequireDefault(/*@__PURE__*/ requireGetProp());
  13361. util.getProp = _getProp["default"];
  13362. var _ensureObject = _interopRequireDefault(/*@__PURE__*/ requireEnsureObject());
  13363. util.ensureObject = _ensureObject["default"];
  13364. var _stripComments = _interopRequireDefault(/*@__PURE__*/ requireStripComments());
  13365. util.stripComments = _stripComments["default"];
  13366. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13367. return util;
  13368. }
  13369. var hasRequiredNode;
  13370. function requireNode () {
  13371. if (hasRequiredNode) return node.exports;
  13372. hasRequiredNode = 1;
  13373. (function (module, exports) {
  13374. exports.__esModule = true;
  13375. exports["default"] = void 0;
  13376. var _util = /*@__PURE__*/ requireUtil();
  13377. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  13378. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13379. var cloneNode = function cloneNode(obj, parent) {
  13380. if (typeof obj !== 'object' || obj === null) {
  13381. return obj;
  13382. }
  13383. var cloned = new obj.constructor();
  13384. for (var i in obj) {
  13385. if (!obj.hasOwnProperty(i)) {
  13386. continue;
  13387. }
  13388. var value = obj[i];
  13389. var type = typeof value;
  13390. if (i === 'parent' && type === 'object') {
  13391. if (parent) {
  13392. cloned[i] = parent;
  13393. }
  13394. } else if (value instanceof Array) {
  13395. cloned[i] = value.map(function (j) {
  13396. return cloneNode(j, cloned);
  13397. });
  13398. } else {
  13399. cloned[i] = cloneNode(value, cloned);
  13400. }
  13401. }
  13402. return cloned;
  13403. };
  13404. var Node = /*#__PURE__*/function () {
  13405. function Node(opts) {
  13406. if (opts === void 0) {
  13407. opts = {};
  13408. }
  13409. Object.assign(this, opts);
  13410. this.spaces = this.spaces || {};
  13411. this.spaces.before = this.spaces.before || '';
  13412. this.spaces.after = this.spaces.after || '';
  13413. }
  13414. var _proto = Node.prototype;
  13415. _proto.remove = function remove() {
  13416. if (this.parent) {
  13417. this.parent.removeChild(this);
  13418. }
  13419. this.parent = undefined;
  13420. return this;
  13421. };
  13422. _proto.replaceWith = function replaceWith() {
  13423. if (this.parent) {
  13424. for (var index in arguments) {
  13425. this.parent.insertBefore(this, arguments[index]);
  13426. }
  13427. this.remove();
  13428. }
  13429. return this;
  13430. };
  13431. _proto.next = function next() {
  13432. return this.parent.at(this.parent.index(this) + 1);
  13433. };
  13434. _proto.prev = function prev() {
  13435. return this.parent.at(this.parent.index(this) - 1);
  13436. };
  13437. _proto.clone = function clone(overrides) {
  13438. if (overrides === void 0) {
  13439. overrides = {};
  13440. }
  13441. var cloned = cloneNode(this);
  13442. for (var name in overrides) {
  13443. cloned[name] = overrides[name];
  13444. }
  13445. return cloned;
  13446. }
  13447. /**
  13448. * Some non-standard syntax doesn't follow normal escaping rules for css.
  13449. * This allows non standard syntax to be appended to an existing property
  13450. * by specifying the escaped value. By specifying the escaped value,
  13451. * illegal characters are allowed to be directly inserted into css output.
  13452. * @param {string} name the property to set
  13453. * @param {any} value the unescaped value of the property
  13454. * @param {string} valueEscaped optional. the escaped value of the property.
  13455. */;
  13456. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  13457. if (!this.raws) {
  13458. this.raws = {};
  13459. }
  13460. var originalValue = this[name];
  13461. var originalEscaped = this.raws[name];
  13462. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  13463. if (originalEscaped || valueEscaped !== value) {
  13464. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  13465. } else {
  13466. delete this.raws[name]; // delete any escaped value that was created by the setter.
  13467. }
  13468. }
  13469. /**
  13470. * Some non-standard syntax doesn't follow normal escaping rules for css.
  13471. * This allows the escaped value to be specified directly, allowing illegal
  13472. * characters to be directly inserted into css output.
  13473. * @param {string} name the property to set
  13474. * @param {any} value the unescaped value of the property
  13475. * @param {string} valueEscaped the escaped value of the property.
  13476. */;
  13477. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  13478. if (!this.raws) {
  13479. this.raws = {};
  13480. }
  13481. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  13482. this.raws[name] = valueEscaped;
  13483. }
  13484. /**
  13485. * When you want a value to passed through to CSS directly. This method
  13486. * deletes the corresponding raw value causing the stringifier to fallback
  13487. * to the unescaped value.
  13488. * @param {string} name the property to set.
  13489. * @param {any} value The value that is both escaped and unescaped.
  13490. */;
  13491. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  13492. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  13493. if (this.raws) {
  13494. delete this.raws[name];
  13495. }
  13496. }
  13497. /**
  13498. *
  13499. * @param {number} line The number (starting with 1)
  13500. * @param {number} column The column number (starting with 1)
  13501. */;
  13502. _proto.isAtPosition = function isAtPosition(line, column) {
  13503. if (this.source && this.source.start && this.source.end) {
  13504. if (this.source.start.line > line) {
  13505. return false;
  13506. }
  13507. if (this.source.end.line < line) {
  13508. return false;
  13509. }
  13510. if (this.source.start.line === line && this.source.start.column > column) {
  13511. return false;
  13512. }
  13513. if (this.source.end.line === line && this.source.end.column < column) {
  13514. return false;
  13515. }
  13516. return true;
  13517. }
  13518. return undefined;
  13519. };
  13520. _proto.stringifyProperty = function stringifyProperty(name) {
  13521. return this.raws && this.raws[name] || this[name];
  13522. };
  13523. _proto.valueToString = function valueToString() {
  13524. return String(this.stringifyProperty("value"));
  13525. };
  13526. _proto.toString = function toString() {
  13527. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  13528. };
  13529. _createClass(Node, [{
  13530. key: "rawSpaceBefore",
  13531. get: function get() {
  13532. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  13533. if (rawSpace === undefined) {
  13534. rawSpace = this.spaces && this.spaces.before;
  13535. }
  13536. return rawSpace || "";
  13537. },
  13538. set: function set(raw) {
  13539. (0, _util.ensureObject)(this, "raws", "spaces");
  13540. this.raws.spaces.before = raw;
  13541. }
  13542. }, {
  13543. key: "rawSpaceAfter",
  13544. get: function get() {
  13545. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  13546. if (rawSpace === undefined) {
  13547. rawSpace = this.spaces.after;
  13548. }
  13549. return rawSpace || "";
  13550. },
  13551. set: function set(raw) {
  13552. (0, _util.ensureObject)(this, "raws", "spaces");
  13553. this.raws.spaces.after = raw;
  13554. }
  13555. }]);
  13556. return Node;
  13557. }();
  13558. exports["default"] = Node;
  13559. module.exports = exports.default;
  13560. } (node, node.exports));
  13561. return node.exports;
  13562. }
  13563. var types$1 = {};
  13564. var hasRequiredTypes;
  13565. function requireTypes () {
  13566. if (hasRequiredTypes) return types$1;
  13567. hasRequiredTypes = 1;
  13568. types$1.__esModule = true;
  13569. types$1.UNIVERSAL = types$1.TAG = types$1.STRING = types$1.SELECTOR = types$1.ROOT = types$1.PSEUDO = types$1.NESTING = types$1.ID = types$1.COMMENT = types$1.COMBINATOR = types$1.CLASS = types$1.ATTRIBUTE = void 0;
  13570. var TAG = 'tag';
  13571. types$1.TAG = TAG;
  13572. var STRING = 'string';
  13573. types$1.STRING = STRING;
  13574. var SELECTOR = 'selector';
  13575. types$1.SELECTOR = SELECTOR;
  13576. var ROOT = 'root';
  13577. types$1.ROOT = ROOT;
  13578. var PSEUDO = 'pseudo';
  13579. types$1.PSEUDO = PSEUDO;
  13580. var NESTING = 'nesting';
  13581. types$1.NESTING = NESTING;
  13582. var ID = 'id';
  13583. types$1.ID = ID;
  13584. var COMMENT = 'comment';
  13585. types$1.COMMENT = COMMENT;
  13586. var COMBINATOR = 'combinator';
  13587. types$1.COMBINATOR = COMBINATOR;
  13588. var CLASS = 'class';
  13589. types$1.CLASS = CLASS;
  13590. var ATTRIBUTE = 'attribute';
  13591. types$1.ATTRIBUTE = ATTRIBUTE;
  13592. var UNIVERSAL = 'universal';
  13593. types$1.UNIVERSAL = UNIVERSAL;
  13594. return types$1;
  13595. }
  13596. var hasRequiredContainer;
  13597. function requireContainer () {
  13598. if (hasRequiredContainer) return container.exports;
  13599. hasRequiredContainer = 1;
  13600. (function (module, exports) {
  13601. exports.__esModule = true;
  13602. exports["default"] = void 0;
  13603. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13604. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes());
  13605. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  13606. function _interopRequireWildcard(obj, nodeInterop) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  13607. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13608. function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike) { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
  13609. function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  13610. function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
  13611. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  13612. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13613. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13614. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13615. var Container = /*#__PURE__*/function (_Node) {
  13616. _inheritsLoose(Container, _Node);
  13617. function Container(opts) {
  13618. var _this;
  13619. _this = _Node.call(this, opts) || this;
  13620. if (!_this.nodes) {
  13621. _this.nodes = [];
  13622. }
  13623. return _this;
  13624. }
  13625. var _proto = Container.prototype;
  13626. _proto.append = function append(selector) {
  13627. selector.parent = this;
  13628. this.nodes.push(selector);
  13629. return this;
  13630. };
  13631. _proto.prepend = function prepend(selector) {
  13632. selector.parent = this;
  13633. this.nodes.unshift(selector);
  13634. return this;
  13635. };
  13636. _proto.at = function at(index) {
  13637. return this.nodes[index];
  13638. };
  13639. _proto.index = function index(child) {
  13640. if (typeof child === 'number') {
  13641. return child;
  13642. }
  13643. return this.nodes.indexOf(child);
  13644. };
  13645. _proto.removeChild = function removeChild(child) {
  13646. child = this.index(child);
  13647. this.at(child).parent = undefined;
  13648. this.nodes.splice(child, 1);
  13649. var index;
  13650. for (var id in this.indexes) {
  13651. index = this.indexes[id];
  13652. if (index >= child) {
  13653. this.indexes[id] = index - 1;
  13654. }
  13655. }
  13656. return this;
  13657. };
  13658. _proto.removeAll = function removeAll() {
  13659. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  13660. var node = _step.value;
  13661. node.parent = undefined;
  13662. }
  13663. this.nodes = [];
  13664. return this;
  13665. };
  13666. _proto.empty = function empty() {
  13667. return this.removeAll();
  13668. };
  13669. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  13670. newNode.parent = this;
  13671. var oldIndex = this.index(oldNode);
  13672. this.nodes.splice(oldIndex + 1, 0, newNode);
  13673. newNode.parent = this;
  13674. var index;
  13675. for (var id in this.indexes) {
  13676. index = this.indexes[id];
  13677. if (oldIndex <= index) {
  13678. this.indexes[id] = index + 1;
  13679. }
  13680. }
  13681. return this;
  13682. };
  13683. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  13684. newNode.parent = this;
  13685. var oldIndex = this.index(oldNode);
  13686. this.nodes.splice(oldIndex, 0, newNode);
  13687. newNode.parent = this;
  13688. var index;
  13689. for (var id in this.indexes) {
  13690. index = this.indexes[id];
  13691. if (index <= oldIndex) {
  13692. this.indexes[id] = index + 1;
  13693. }
  13694. }
  13695. return this;
  13696. };
  13697. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  13698. var found = undefined;
  13699. this.each(function (node) {
  13700. if (node.atPosition) {
  13701. var foundChild = node.atPosition(line, col);
  13702. if (foundChild) {
  13703. found = foundChild;
  13704. return false;
  13705. }
  13706. } else if (node.isAtPosition(line, col)) {
  13707. found = node;
  13708. return false;
  13709. }
  13710. });
  13711. return found;
  13712. }
  13713. /**
  13714. * Return the most specific node at the line and column number given.
  13715. * The source location is based on the original parsed location, locations aren't
  13716. * updated as selector nodes are mutated.
  13717. *
  13718. * Note that this location is relative to the location of the first character
  13719. * of the selector, and not the location of the selector in the overall document
  13720. * when used in conjunction with postcss.
  13721. *
  13722. * If not found, returns undefined.
  13723. * @param {number} line The line number of the node to find. (1-based index)
  13724. * @param {number} col The column number of the node to find. (1-based index)
  13725. */;
  13726. _proto.atPosition = function atPosition(line, col) {
  13727. if (this.isAtPosition(line, col)) {
  13728. return this._findChildAtPosition(line, col) || this;
  13729. } else {
  13730. return undefined;
  13731. }
  13732. };
  13733. _proto._inferEndPosition = function _inferEndPosition() {
  13734. if (this.last && this.last.source && this.last.source.end) {
  13735. this.source = this.source || {};
  13736. this.source.end = this.source.end || {};
  13737. Object.assign(this.source.end, this.last.source.end);
  13738. }
  13739. };
  13740. _proto.each = function each(callback) {
  13741. if (!this.lastEach) {
  13742. this.lastEach = 0;
  13743. }
  13744. if (!this.indexes) {
  13745. this.indexes = {};
  13746. }
  13747. this.lastEach++;
  13748. var id = this.lastEach;
  13749. this.indexes[id] = 0;
  13750. if (!this.length) {
  13751. return undefined;
  13752. }
  13753. var index, result;
  13754. while (this.indexes[id] < this.length) {
  13755. index = this.indexes[id];
  13756. result = callback(this.at(index), index);
  13757. if (result === false) {
  13758. break;
  13759. }
  13760. this.indexes[id] += 1;
  13761. }
  13762. delete this.indexes[id];
  13763. if (result === false) {
  13764. return false;
  13765. }
  13766. };
  13767. _proto.walk = function walk(callback) {
  13768. return this.each(function (node, i) {
  13769. var result = callback(node, i);
  13770. if (result !== false && node.length) {
  13771. result = node.walk(callback);
  13772. }
  13773. if (result === false) {
  13774. return false;
  13775. }
  13776. });
  13777. };
  13778. _proto.walkAttributes = function walkAttributes(callback) {
  13779. var _this2 = this;
  13780. return this.walk(function (selector) {
  13781. if (selector.type === types.ATTRIBUTE) {
  13782. return callback.call(_this2, selector);
  13783. }
  13784. });
  13785. };
  13786. _proto.walkClasses = function walkClasses(callback) {
  13787. var _this3 = this;
  13788. return this.walk(function (selector) {
  13789. if (selector.type === types.CLASS) {
  13790. return callback.call(_this3, selector);
  13791. }
  13792. });
  13793. };
  13794. _proto.walkCombinators = function walkCombinators(callback) {
  13795. var _this4 = this;
  13796. return this.walk(function (selector) {
  13797. if (selector.type === types.COMBINATOR) {
  13798. return callback.call(_this4, selector);
  13799. }
  13800. });
  13801. };
  13802. _proto.walkComments = function walkComments(callback) {
  13803. var _this5 = this;
  13804. return this.walk(function (selector) {
  13805. if (selector.type === types.COMMENT) {
  13806. return callback.call(_this5, selector);
  13807. }
  13808. });
  13809. };
  13810. _proto.walkIds = function walkIds(callback) {
  13811. var _this6 = this;
  13812. return this.walk(function (selector) {
  13813. if (selector.type === types.ID) {
  13814. return callback.call(_this6, selector);
  13815. }
  13816. });
  13817. };
  13818. _proto.walkNesting = function walkNesting(callback) {
  13819. var _this7 = this;
  13820. return this.walk(function (selector) {
  13821. if (selector.type === types.NESTING) {
  13822. return callback.call(_this7, selector);
  13823. }
  13824. });
  13825. };
  13826. _proto.walkPseudos = function walkPseudos(callback) {
  13827. var _this8 = this;
  13828. return this.walk(function (selector) {
  13829. if (selector.type === types.PSEUDO) {
  13830. return callback.call(_this8, selector);
  13831. }
  13832. });
  13833. };
  13834. _proto.walkTags = function walkTags(callback) {
  13835. var _this9 = this;
  13836. return this.walk(function (selector) {
  13837. if (selector.type === types.TAG) {
  13838. return callback.call(_this9, selector);
  13839. }
  13840. });
  13841. };
  13842. _proto.walkUniversals = function walkUniversals(callback) {
  13843. var _this10 = this;
  13844. return this.walk(function (selector) {
  13845. if (selector.type === types.UNIVERSAL) {
  13846. return callback.call(_this10, selector);
  13847. }
  13848. });
  13849. };
  13850. _proto.split = function split(callback) {
  13851. var _this11 = this;
  13852. var current = [];
  13853. return this.reduce(function (memo, node, index) {
  13854. var split = callback.call(_this11, node);
  13855. current.push(node);
  13856. if (split) {
  13857. memo.push(current);
  13858. current = [];
  13859. } else if (index === _this11.length - 1) {
  13860. memo.push(current);
  13861. }
  13862. return memo;
  13863. }, []);
  13864. };
  13865. _proto.map = function map(callback) {
  13866. return this.nodes.map(callback);
  13867. };
  13868. _proto.reduce = function reduce(callback, memo) {
  13869. return this.nodes.reduce(callback, memo);
  13870. };
  13871. _proto.every = function every(callback) {
  13872. return this.nodes.every(callback);
  13873. };
  13874. _proto.some = function some(callback) {
  13875. return this.nodes.some(callback);
  13876. };
  13877. _proto.filter = function filter(callback) {
  13878. return this.nodes.filter(callback);
  13879. };
  13880. _proto.sort = function sort(callback) {
  13881. return this.nodes.sort(callback);
  13882. };
  13883. _proto.toString = function toString() {
  13884. return this.map(String).join('');
  13885. };
  13886. _createClass(Container, [{
  13887. key: "first",
  13888. get: function get() {
  13889. return this.at(0);
  13890. }
  13891. }, {
  13892. key: "last",
  13893. get: function get() {
  13894. return this.at(this.length - 1);
  13895. }
  13896. }, {
  13897. key: "length",
  13898. get: function get() {
  13899. return this.nodes.length;
  13900. }
  13901. }]);
  13902. return Container;
  13903. }(_node["default"]);
  13904. exports["default"] = Container;
  13905. module.exports = exports.default;
  13906. } (container, container.exports));
  13907. return container.exports;
  13908. }
  13909. var hasRequiredRoot;
  13910. function requireRoot () {
  13911. if (hasRequiredRoot) return root.exports;
  13912. hasRequiredRoot = 1;
  13913. (function (module, exports) {
  13914. exports.__esModule = true;
  13915. exports["default"] = void 0;
  13916. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13917. var _types = /*@__PURE__*/ requireTypes();
  13918. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13919. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  13920. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13921. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13922. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13923. var Root = /*#__PURE__*/function (_Container) {
  13924. _inheritsLoose(Root, _Container);
  13925. function Root(opts) {
  13926. var _this;
  13927. _this = _Container.call(this, opts) || this;
  13928. _this.type = _types.ROOT;
  13929. return _this;
  13930. }
  13931. var _proto = Root.prototype;
  13932. _proto.toString = function toString() {
  13933. var str = this.reduce(function (memo, selector) {
  13934. memo.push(String(selector));
  13935. return memo;
  13936. }, []).join(',');
  13937. return this.trailingComma ? str + ',' : str;
  13938. };
  13939. _proto.error = function error(message, options) {
  13940. if (this._error) {
  13941. return this._error(message, options);
  13942. } else {
  13943. return new Error(message);
  13944. }
  13945. };
  13946. _createClass(Root, [{
  13947. key: "errorGenerator",
  13948. set: function set(handler) {
  13949. this._error = handler;
  13950. }
  13951. }]);
  13952. return Root;
  13953. }(_container["default"]);
  13954. exports["default"] = Root;
  13955. module.exports = exports.default;
  13956. } (root, root.exports));
  13957. return root.exports;
  13958. }
  13959. var selector = {exports: {}};
  13960. var hasRequiredSelector;
  13961. function requireSelector () {
  13962. if (hasRequiredSelector) return selector.exports;
  13963. hasRequiredSelector = 1;
  13964. (function (module, exports) {
  13965. exports.__esModule = true;
  13966. exports["default"] = void 0;
  13967. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13968. var _types = /*@__PURE__*/ requireTypes();
  13969. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13970. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13971. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13972. var Selector = /*#__PURE__*/function (_Container) {
  13973. _inheritsLoose(Selector, _Container);
  13974. function Selector(opts) {
  13975. var _this;
  13976. _this = _Container.call(this, opts) || this;
  13977. _this.type = _types.SELECTOR;
  13978. return _this;
  13979. }
  13980. return Selector;
  13981. }(_container["default"]);
  13982. exports["default"] = Selector;
  13983. module.exports = exports.default;
  13984. } (selector, selector.exports));
  13985. return selector.exports;
  13986. }
  13987. var className = {exports: {}};
  13988. var hasRequiredClassName;
  13989. function requireClassName () {
  13990. if (hasRequiredClassName) return className.exports;
  13991. hasRequiredClassName = 1;
  13992. (function (module, exports) {
  13993. exports.__esModule = true;
  13994. exports["default"] = void 0;
  13995. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13996. var _util = /*@__PURE__*/ requireUtil();
  13997. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13998. var _types = /*@__PURE__*/ requireTypes();
  13999. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14000. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  14001. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  14002. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14003. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14004. var ClassName = /*#__PURE__*/function (_Node) {
  14005. _inheritsLoose(ClassName, _Node);
  14006. function ClassName(opts) {
  14007. var _this;
  14008. _this = _Node.call(this, opts) || this;
  14009. _this.type = _types.CLASS;
  14010. _this._constructed = true;
  14011. return _this;
  14012. }
  14013. var _proto = ClassName.prototype;
  14014. _proto.valueToString = function valueToString() {
  14015. return '.' + _Node.prototype.valueToString.call(this);
  14016. };
  14017. _createClass(ClassName, [{
  14018. key: "value",
  14019. get: function get() {
  14020. return this._value;
  14021. },
  14022. set: function set(v) {
  14023. if (this._constructed) {
  14024. var escaped = (0, _cssesc["default"])(v, {
  14025. isIdentifier: true
  14026. });
  14027. if (escaped !== v) {
  14028. (0, _util.ensureObject)(this, "raws");
  14029. this.raws.value = escaped;
  14030. } else if (this.raws) {
  14031. delete this.raws.value;
  14032. }
  14033. }
  14034. this._value = v;
  14035. }
  14036. }]);
  14037. return ClassName;
  14038. }(_node["default"]);
  14039. exports["default"] = ClassName;
  14040. module.exports = exports.default;
  14041. } (className, className.exports));
  14042. return className.exports;
  14043. }
  14044. var comment = {exports: {}};
  14045. var hasRequiredComment;
  14046. function requireComment () {
  14047. if (hasRequiredComment) return comment.exports;
  14048. hasRequiredComment = 1;
  14049. (function (module, exports) {
  14050. exports.__esModule = true;
  14051. exports["default"] = void 0;
  14052. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  14053. var _types = /*@__PURE__*/ requireTypes();
  14054. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14055. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14056. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14057. var Comment = /*#__PURE__*/function (_Node) {
  14058. _inheritsLoose(Comment, _Node);
  14059. function Comment(opts) {
  14060. var _this;
  14061. _this = _Node.call(this, opts) || this;
  14062. _this.type = _types.COMMENT;
  14063. return _this;
  14064. }
  14065. return Comment;
  14066. }(_node["default"]);
  14067. exports["default"] = Comment;
  14068. module.exports = exports.default;
  14069. } (comment, comment.exports));
  14070. return comment.exports;
  14071. }
  14072. var id = {exports: {}};
  14073. var hasRequiredId;
  14074. function requireId () {
  14075. if (hasRequiredId) return id.exports;
  14076. hasRequiredId = 1;
  14077. (function (module, exports) {
  14078. exports.__esModule = true;
  14079. exports["default"] = void 0;
  14080. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  14081. var _types = /*@__PURE__*/ requireTypes();
  14082. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14083. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14084. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14085. var ID = /*#__PURE__*/function (_Node) {
  14086. _inheritsLoose(ID, _Node);
  14087. function ID(opts) {
  14088. var _this;
  14089. _this = _Node.call(this, opts) || this;
  14090. _this.type = _types.ID;
  14091. return _this;
  14092. }
  14093. var _proto = ID.prototype;
  14094. _proto.valueToString = function valueToString() {
  14095. return '#' + _Node.prototype.valueToString.call(this);
  14096. };
  14097. return ID;
  14098. }(_node["default"]);
  14099. exports["default"] = ID;
  14100. module.exports = exports.default;
  14101. } (id, id.exports));
  14102. return id.exports;
  14103. }
  14104. var tag = {exports: {}};
  14105. var namespace = {exports: {}};
  14106. var hasRequiredNamespace;
  14107. function requireNamespace () {
  14108. if (hasRequiredNamespace) return namespace.exports;
  14109. hasRequiredNamespace = 1;
  14110. (function (module, exports) {
  14111. exports.__esModule = true;
  14112. exports["default"] = void 0;
  14113. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  14114. var _util = /*@__PURE__*/ requireUtil();
  14115. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  14116. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14117. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  14118. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  14119. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14120. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14121. var Namespace = /*#__PURE__*/function (_Node) {
  14122. _inheritsLoose(Namespace, _Node);
  14123. function Namespace() {
  14124. return _Node.apply(this, arguments) || this;
  14125. }
  14126. var _proto = Namespace.prototype;
  14127. _proto.qualifiedName = function qualifiedName(value) {
  14128. if (this.namespace) {
  14129. return this.namespaceString + "|" + value;
  14130. } else {
  14131. return value;
  14132. }
  14133. };
  14134. _proto.valueToString = function valueToString() {
  14135. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  14136. };
  14137. _createClass(Namespace, [{
  14138. key: "namespace",
  14139. get: function get() {
  14140. return this._namespace;
  14141. },
  14142. set: function set(namespace) {
  14143. if (namespace === true || namespace === "*" || namespace === "&") {
  14144. this._namespace = namespace;
  14145. if (this.raws) {
  14146. delete this.raws.namespace;
  14147. }
  14148. return;
  14149. }
  14150. var escaped = (0, _cssesc["default"])(namespace, {
  14151. isIdentifier: true
  14152. });
  14153. this._namespace = namespace;
  14154. if (escaped !== namespace) {
  14155. (0, _util.ensureObject)(this, "raws");
  14156. this.raws.namespace = escaped;
  14157. } else if (this.raws) {
  14158. delete this.raws.namespace;
  14159. }
  14160. }
  14161. }, {
  14162. key: "ns",
  14163. get: function get() {
  14164. return this._namespace;
  14165. },
  14166. set: function set(namespace) {
  14167. this.namespace = namespace;
  14168. }
  14169. }, {
  14170. key: "namespaceString",
  14171. get: function get() {
  14172. if (this.namespace) {
  14173. var ns = this.stringifyProperty("namespace");
  14174. if (ns === true) {
  14175. return '';
  14176. } else {
  14177. return ns;
  14178. }
  14179. } else {
  14180. return '';
  14181. }
  14182. }
  14183. }]);
  14184. return Namespace;
  14185. }(_node["default"]);
  14186. exports["default"] = Namespace;
  14187. module.exports = exports.default;
  14188. } (namespace, namespace.exports));
  14189. return namespace.exports;
  14190. }
  14191. var hasRequiredTag;
  14192. function requireTag () {
  14193. if (hasRequiredTag) return tag.exports;
  14194. hasRequiredTag = 1;
  14195. (function (module, exports) {
  14196. exports.__esModule = true;
  14197. exports["default"] = void 0;
  14198. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  14199. var _types = /*@__PURE__*/ requireTypes();
  14200. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14201. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14202. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14203. var Tag = /*#__PURE__*/function (_Namespace) {
  14204. _inheritsLoose(Tag, _Namespace);
  14205. function Tag(opts) {
  14206. var _this;
  14207. _this = _Namespace.call(this, opts) || this;
  14208. _this.type = _types.TAG;
  14209. return _this;
  14210. }
  14211. return Tag;
  14212. }(_namespace["default"]);
  14213. exports["default"] = Tag;
  14214. module.exports = exports.default;
  14215. } (tag, tag.exports));
  14216. return tag.exports;
  14217. }
  14218. var string = {exports: {}};
  14219. var hasRequiredString;
  14220. function requireString () {
  14221. if (hasRequiredString) return string.exports;
  14222. hasRequiredString = 1;
  14223. (function (module, exports) {
  14224. exports.__esModule = true;
  14225. exports["default"] = void 0;
  14226. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  14227. var _types = /*@__PURE__*/ requireTypes();
  14228. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14229. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14230. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14231. var String = /*#__PURE__*/function (_Node) {
  14232. _inheritsLoose(String, _Node);
  14233. function String(opts) {
  14234. var _this;
  14235. _this = _Node.call(this, opts) || this;
  14236. _this.type = _types.STRING;
  14237. return _this;
  14238. }
  14239. return String;
  14240. }(_node["default"]);
  14241. exports["default"] = String;
  14242. module.exports = exports.default;
  14243. } (string, string.exports));
  14244. return string.exports;
  14245. }
  14246. var pseudo = {exports: {}};
  14247. var hasRequiredPseudo;
  14248. function requirePseudo () {
  14249. if (hasRequiredPseudo) return pseudo.exports;
  14250. hasRequiredPseudo = 1;
  14251. (function (module, exports) {
  14252. exports.__esModule = true;
  14253. exports["default"] = void 0;
  14254. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  14255. var _types = /*@__PURE__*/ requireTypes();
  14256. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14257. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14258. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14259. var Pseudo = /*#__PURE__*/function (_Container) {
  14260. _inheritsLoose(Pseudo, _Container);
  14261. function Pseudo(opts) {
  14262. var _this;
  14263. _this = _Container.call(this, opts) || this;
  14264. _this.type = _types.PSEUDO;
  14265. return _this;
  14266. }
  14267. var _proto = Pseudo.prototype;
  14268. _proto.toString = function toString() {
  14269. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  14270. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  14271. };
  14272. return Pseudo;
  14273. }(_container["default"]);
  14274. exports["default"] = Pseudo;
  14275. module.exports = exports.default;
  14276. } (pseudo, pseudo.exports));
  14277. return pseudo.exports;
  14278. }
  14279. var attribute = {};
  14280. var hasRequiredAttribute;
  14281. function requireAttribute () {
  14282. if (hasRequiredAttribute) return attribute;
  14283. hasRequiredAttribute = 1;
  14284. (function (exports) {
  14285. exports.__esModule = true;
  14286. exports["default"] = void 0;
  14287. exports.unescapeValue = unescapeValue;
  14288. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  14289. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc());
  14290. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  14291. var _types = /*@__PURE__*/ requireTypes();
  14292. var _CSSESC_QUOTE_OPTIONS;
  14293. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14294. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  14295. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  14296. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14297. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14298. var deprecate = /*@__PURE__*/ requireNode$1();
  14299. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  14300. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  14301. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  14302. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  14303. function unescapeValue(value) {
  14304. var deprecatedUsage = false;
  14305. var quoteMark = null;
  14306. var unescaped = value;
  14307. var m = unescaped.match(WRAPPED_IN_QUOTES);
  14308. if (m) {
  14309. quoteMark = m[1];
  14310. unescaped = m[2];
  14311. }
  14312. unescaped = (0, _unesc["default"])(unescaped);
  14313. if (unescaped !== value) {
  14314. deprecatedUsage = true;
  14315. }
  14316. return {
  14317. deprecatedUsage: deprecatedUsage,
  14318. unescaped: unescaped,
  14319. quoteMark: quoteMark
  14320. };
  14321. }
  14322. function handleDeprecatedContructorOpts(opts) {
  14323. if (opts.quoteMark !== undefined) {
  14324. return opts;
  14325. }
  14326. if (opts.value === undefined) {
  14327. return opts;
  14328. }
  14329. warnOfDeprecatedConstructor();
  14330. var _unescapeValue = unescapeValue(opts.value),
  14331. quoteMark = _unescapeValue.quoteMark,
  14332. unescaped = _unescapeValue.unescaped;
  14333. if (!opts.raws) {
  14334. opts.raws = {};
  14335. }
  14336. if (opts.raws.value === undefined) {
  14337. opts.raws.value = opts.value;
  14338. }
  14339. opts.value = unescaped;
  14340. opts.quoteMark = quoteMark;
  14341. return opts;
  14342. }
  14343. var Attribute = /*#__PURE__*/function (_Namespace) {
  14344. _inheritsLoose(Attribute, _Namespace);
  14345. function Attribute(opts) {
  14346. var _this;
  14347. if (opts === void 0) {
  14348. opts = {};
  14349. }
  14350. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  14351. _this.type = _types.ATTRIBUTE;
  14352. _this.raws = _this.raws || {};
  14353. Object.defineProperty(_this.raws, 'unquoted', {
  14354. get: deprecate(function () {
  14355. return _this.value;
  14356. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  14357. set: deprecate(function () {
  14358. return _this.value;
  14359. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  14360. });
  14361. _this._constructed = true;
  14362. return _this;
  14363. }
  14364. /**
  14365. * Returns the Attribute's value quoted such that it would be legal to use
  14366. * in the value of a css file. The original value's quotation setting
  14367. * used for stringification is left unchanged. See `setValue(value, options)`
  14368. * if you want to control the quote settings of a new value for the attribute.
  14369. *
  14370. * You can also change the quotation used for the current value by setting quoteMark.
  14371. *
  14372. * Options:
  14373. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  14374. * option is not set, the original value for quoteMark will be used. If
  14375. * indeterminate, a double quote is used. The legal values are:
  14376. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  14377. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  14378. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  14379. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  14380. * over the quoteMark option value.
  14381. * * smart {boolean} - if true, will select a quote mark based on the value
  14382. * and the other options specified here. See the `smartQuoteMark()`
  14383. * method.
  14384. **/
  14385. var _proto = Attribute.prototype;
  14386. _proto.getQuotedValue = function getQuotedValue(options) {
  14387. if (options === void 0) {
  14388. options = {};
  14389. }
  14390. var quoteMark = this._determineQuoteMark(options);
  14391. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  14392. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  14393. return escaped;
  14394. };
  14395. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  14396. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  14397. }
  14398. /**
  14399. * Set the unescaped value with the specified quotation options. The value
  14400. * provided must not include any wrapping quote marks -- those quotes will
  14401. * be interpreted as part of the value and escaped accordingly.
  14402. */;
  14403. _proto.setValue = function setValue(value, options) {
  14404. if (options === void 0) {
  14405. options = {};
  14406. }
  14407. this._value = value;
  14408. this._quoteMark = this._determineQuoteMark(options);
  14409. this._syncRawValue();
  14410. }
  14411. /**
  14412. * Intelligently select a quoteMark value based on the value's contents. If
  14413. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  14414. * mark will be picked that minimizes the number of escapes.
  14415. *
  14416. * If there's no clear winner, the quote mark from these options is used,
  14417. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  14418. * true). If the quoteMark is unspecified, a double quote is used.
  14419. *
  14420. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  14421. * from the quoteValue method.
  14422. */;
  14423. _proto.smartQuoteMark = function smartQuoteMark(options) {
  14424. var v = this.value;
  14425. var numSingleQuotes = v.replace(/[^']/g, '').length;
  14426. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  14427. if (numSingleQuotes + numDoubleQuotes === 0) {
  14428. var escaped = (0, _cssesc["default"])(v, {
  14429. isIdentifier: true
  14430. });
  14431. if (escaped === v) {
  14432. return Attribute.NO_QUOTE;
  14433. } else {
  14434. var pref = this.preferredQuoteMark(options);
  14435. if (pref === Attribute.NO_QUOTE) {
  14436. // pick a quote mark that isn't none and see if it's smaller
  14437. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  14438. var opts = CSSESC_QUOTE_OPTIONS[quote];
  14439. var quoteValue = (0, _cssesc["default"])(v, opts);
  14440. if (quoteValue.length < escaped.length) {
  14441. return quote;
  14442. }
  14443. }
  14444. return pref;
  14445. }
  14446. } else if (numDoubleQuotes === numSingleQuotes) {
  14447. return this.preferredQuoteMark(options);
  14448. } else if (numDoubleQuotes < numSingleQuotes) {
  14449. return Attribute.DOUBLE_QUOTE;
  14450. } else {
  14451. return Attribute.SINGLE_QUOTE;
  14452. }
  14453. }
  14454. /**
  14455. * Selects the preferred quote mark based on the options and the current quote mark value.
  14456. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  14457. * instead.
  14458. */;
  14459. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  14460. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  14461. if (quoteMark === undefined) {
  14462. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  14463. }
  14464. if (quoteMark === undefined) {
  14465. quoteMark = Attribute.DOUBLE_QUOTE;
  14466. }
  14467. return quoteMark;
  14468. };
  14469. _proto._syncRawValue = function _syncRawValue() {
  14470. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  14471. if (rawValue === this._value) {
  14472. if (this.raws) {
  14473. delete this.raws.value;
  14474. }
  14475. } else {
  14476. this.raws.value = rawValue;
  14477. }
  14478. };
  14479. _proto._handleEscapes = function _handleEscapes(prop, value) {
  14480. if (this._constructed) {
  14481. var escaped = (0, _cssesc["default"])(value, {
  14482. isIdentifier: true
  14483. });
  14484. if (escaped !== value) {
  14485. this.raws[prop] = escaped;
  14486. } else {
  14487. delete this.raws[prop];
  14488. }
  14489. }
  14490. };
  14491. _proto._spacesFor = function _spacesFor(name) {
  14492. var attrSpaces = {
  14493. before: '',
  14494. after: ''
  14495. };
  14496. var spaces = this.spaces[name] || {};
  14497. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  14498. return Object.assign(attrSpaces, spaces, rawSpaces);
  14499. };
  14500. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  14501. if (spaceName === void 0) {
  14502. spaceName = name;
  14503. }
  14504. if (concat === void 0) {
  14505. concat = defaultAttrConcat;
  14506. }
  14507. var attrSpaces = this._spacesFor(spaceName);
  14508. return concat(this.stringifyProperty(name), attrSpaces);
  14509. }
  14510. /**
  14511. * returns the offset of the attribute part specified relative to the
  14512. * start of the node of the output string.
  14513. *
  14514. * * "ns" - alias for "namespace"
  14515. * * "namespace" - the namespace if it exists.
  14516. * * "attribute" - the attribute name
  14517. * * "attributeNS" - the start of the attribute or its namespace
  14518. * * "operator" - the match operator of the attribute
  14519. * * "value" - The value (string or identifier)
  14520. * * "insensitive" - the case insensitivity flag;
  14521. * @param part One of the possible values inside an attribute.
  14522. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  14523. */;
  14524. _proto.offsetOf = function offsetOf(name) {
  14525. var count = 1;
  14526. var attributeSpaces = this._spacesFor("attribute");
  14527. count += attributeSpaces.before.length;
  14528. if (name === "namespace" || name === "ns") {
  14529. return this.namespace ? count : -1;
  14530. }
  14531. if (name === "attributeNS") {
  14532. return count;
  14533. }
  14534. count += this.namespaceString.length;
  14535. if (this.namespace) {
  14536. count += 1;
  14537. }
  14538. if (name === "attribute") {
  14539. return count;
  14540. }
  14541. count += this.stringifyProperty("attribute").length;
  14542. count += attributeSpaces.after.length;
  14543. var operatorSpaces = this._spacesFor("operator");
  14544. count += operatorSpaces.before.length;
  14545. var operator = this.stringifyProperty("operator");
  14546. if (name === "operator") {
  14547. return operator ? count : -1;
  14548. }
  14549. count += operator.length;
  14550. count += operatorSpaces.after.length;
  14551. var valueSpaces = this._spacesFor("value");
  14552. count += valueSpaces.before.length;
  14553. var value = this.stringifyProperty("value");
  14554. if (name === "value") {
  14555. return value ? count : -1;
  14556. }
  14557. count += value.length;
  14558. count += valueSpaces.after.length;
  14559. var insensitiveSpaces = this._spacesFor("insensitive");
  14560. count += insensitiveSpaces.before.length;
  14561. if (name === "insensitive") {
  14562. return this.insensitive ? count : -1;
  14563. }
  14564. return -1;
  14565. };
  14566. _proto.toString = function toString() {
  14567. var _this2 = this;
  14568. var selector = [this.rawSpaceBefore, '['];
  14569. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  14570. if (this.operator && (this.value || this.value === '')) {
  14571. selector.push(this._stringFor('operator'));
  14572. selector.push(this._stringFor('value'));
  14573. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  14574. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  14575. attrSpaces.before = " ";
  14576. }
  14577. return defaultAttrConcat(attrValue, attrSpaces);
  14578. }));
  14579. }
  14580. selector.push(']');
  14581. selector.push(this.rawSpaceAfter);
  14582. return selector.join('');
  14583. };
  14584. _createClass(Attribute, [{
  14585. key: "quoted",
  14586. get: function get() {
  14587. var qm = this.quoteMark;
  14588. return qm === "'" || qm === '"';
  14589. },
  14590. set: function set(value) {
  14591. warnOfDeprecatedQuotedAssignment();
  14592. }
  14593. /**
  14594. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  14595. * returns `null` if the value is not quoted.
  14596. * returns `undefined` if the quotation state is unknown (this can happen when
  14597. * the attribute is constructed without specifying a quote mark.)
  14598. */
  14599. }, {
  14600. key: "quoteMark",
  14601. get: function get() {
  14602. return this._quoteMark;
  14603. }
  14604. /**
  14605. * Set the quote mark to be used by this attribute's value.
  14606. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  14607. * value is updated accordingly.
  14608. *
  14609. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  14610. */,
  14611. set: function set(quoteMark) {
  14612. if (!this._constructed) {
  14613. this._quoteMark = quoteMark;
  14614. return;
  14615. }
  14616. if (this._quoteMark !== quoteMark) {
  14617. this._quoteMark = quoteMark;
  14618. this._syncRawValue();
  14619. }
  14620. }
  14621. }, {
  14622. key: "qualifiedAttribute",
  14623. get: function get() {
  14624. return this.qualifiedName(this.raws.attribute || this.attribute);
  14625. }
  14626. }, {
  14627. key: "insensitiveFlag",
  14628. get: function get() {
  14629. return this.insensitive ? 'i' : '';
  14630. }
  14631. }, {
  14632. key: "value",
  14633. get: function get() {
  14634. return this._value;
  14635. },
  14636. set:
  14637. /**
  14638. * Before 3.0, the value had to be set to an escaped value including any wrapped
  14639. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  14640. * is unescaped during parsing and any quote marks are removed.
  14641. *
  14642. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  14643. * a deprecation warning is raised when the new value contains any characters that would
  14644. * require escaping (including if it contains wrapped quotes).
  14645. *
  14646. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  14647. * how the new value is quoted.
  14648. */
  14649. function set(v) {
  14650. if (this._constructed) {
  14651. var _unescapeValue2 = unescapeValue(v),
  14652. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  14653. unescaped = _unescapeValue2.unescaped,
  14654. quoteMark = _unescapeValue2.quoteMark;
  14655. if (deprecatedUsage) {
  14656. warnOfDeprecatedValueAssignment();
  14657. }
  14658. if (unescaped === this._value && quoteMark === this._quoteMark) {
  14659. return;
  14660. }
  14661. this._value = unescaped;
  14662. this._quoteMark = quoteMark;
  14663. this._syncRawValue();
  14664. } else {
  14665. this._value = v;
  14666. }
  14667. }
  14668. }, {
  14669. key: "insensitive",
  14670. get: function get() {
  14671. return this._insensitive;
  14672. }
  14673. /**
  14674. * Set the case insensitive flag.
  14675. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  14676. * of the attribute is updated accordingly.
  14677. *
  14678. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  14679. */,
  14680. set: function set(insensitive) {
  14681. if (!insensitive) {
  14682. this._insensitive = false;
  14683. // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  14684. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  14685. if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
  14686. this.raws.insensitiveFlag = undefined;
  14687. }
  14688. }
  14689. this._insensitive = insensitive;
  14690. }
  14691. }, {
  14692. key: "attribute",
  14693. get: function get() {
  14694. return this._attribute;
  14695. },
  14696. set: function set(name) {
  14697. this._handleEscapes("attribute", name);
  14698. this._attribute = name;
  14699. }
  14700. }]);
  14701. return Attribute;
  14702. }(_namespace["default"]);
  14703. exports["default"] = Attribute;
  14704. Attribute.NO_QUOTE = null;
  14705. Attribute.SINGLE_QUOTE = "'";
  14706. Attribute.DOUBLE_QUOTE = '"';
  14707. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  14708. "'": {
  14709. quotes: 'single',
  14710. wrap: true
  14711. },
  14712. '"': {
  14713. quotes: 'double',
  14714. wrap: true
  14715. }
  14716. }, _CSSESC_QUOTE_OPTIONS[null] = {
  14717. isIdentifier: true
  14718. }, _CSSESC_QUOTE_OPTIONS);
  14719. function defaultAttrConcat(attrValue, attrSpaces) {
  14720. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  14721. }
  14722. } (attribute));
  14723. return attribute;
  14724. }
  14725. var universal = {exports: {}};
  14726. var hasRequiredUniversal;
  14727. function requireUniversal () {
  14728. if (hasRequiredUniversal) return universal.exports;
  14729. hasRequiredUniversal = 1;
  14730. (function (module, exports) {
  14731. exports.__esModule = true;
  14732. exports["default"] = void 0;
  14733. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  14734. var _types = /*@__PURE__*/ requireTypes();
  14735. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14736. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14737. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14738. var Universal = /*#__PURE__*/function (_Namespace) {
  14739. _inheritsLoose(Universal, _Namespace);
  14740. function Universal(opts) {
  14741. var _this;
  14742. _this = _Namespace.call(this, opts) || this;
  14743. _this.type = _types.UNIVERSAL;
  14744. _this.value = '*';
  14745. return _this;
  14746. }
  14747. return Universal;
  14748. }(_namespace["default"]);
  14749. exports["default"] = Universal;
  14750. module.exports = exports.default;
  14751. } (universal, universal.exports));
  14752. return universal.exports;
  14753. }
  14754. var combinator = {exports: {}};
  14755. var hasRequiredCombinator;
  14756. function requireCombinator () {
  14757. if (hasRequiredCombinator) return combinator.exports;
  14758. hasRequiredCombinator = 1;
  14759. (function (module, exports) {
  14760. exports.__esModule = true;
  14761. exports["default"] = void 0;
  14762. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  14763. var _types = /*@__PURE__*/ requireTypes();
  14764. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14765. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14766. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14767. var Combinator = /*#__PURE__*/function (_Node) {
  14768. _inheritsLoose(Combinator, _Node);
  14769. function Combinator(opts) {
  14770. var _this;
  14771. _this = _Node.call(this, opts) || this;
  14772. _this.type = _types.COMBINATOR;
  14773. return _this;
  14774. }
  14775. return Combinator;
  14776. }(_node["default"]);
  14777. exports["default"] = Combinator;
  14778. module.exports = exports.default;
  14779. } (combinator, combinator.exports));
  14780. return combinator.exports;
  14781. }
  14782. var nesting = {exports: {}};
  14783. var hasRequiredNesting;
  14784. function requireNesting () {
  14785. if (hasRequiredNesting) return nesting.exports;
  14786. hasRequiredNesting = 1;
  14787. (function (module, exports) {
  14788. exports.__esModule = true;
  14789. exports["default"] = void 0;
  14790. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  14791. var _types = /*@__PURE__*/ requireTypes();
  14792. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14793. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14794. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14795. var Nesting = /*#__PURE__*/function (_Node) {
  14796. _inheritsLoose(Nesting, _Node);
  14797. function Nesting(opts) {
  14798. var _this;
  14799. _this = _Node.call(this, opts) || this;
  14800. _this.type = _types.NESTING;
  14801. _this.value = '&';
  14802. return _this;
  14803. }
  14804. return Nesting;
  14805. }(_node["default"]);
  14806. exports["default"] = Nesting;
  14807. module.exports = exports.default;
  14808. } (nesting, nesting.exports));
  14809. return nesting.exports;
  14810. }
  14811. var sortAscending = {exports: {}};
  14812. var hasRequiredSortAscending;
  14813. function requireSortAscending () {
  14814. if (hasRequiredSortAscending) return sortAscending.exports;
  14815. hasRequiredSortAscending = 1;
  14816. (function (module, exports) {
  14817. exports.__esModule = true;
  14818. exports["default"] = sortAscending;
  14819. function sortAscending(list) {
  14820. return list.sort(function (a, b) {
  14821. return a - b;
  14822. });
  14823. }
  14824. module.exports = exports.default;
  14825. } (sortAscending, sortAscending.exports));
  14826. return sortAscending.exports;
  14827. }
  14828. var tokenize = {};
  14829. var tokenTypes = {};
  14830. var hasRequiredTokenTypes;
  14831. function requireTokenTypes () {
  14832. if (hasRequiredTokenTypes) return tokenTypes;
  14833. hasRequiredTokenTypes = 1;
  14834. tokenTypes.__esModule = true;
  14835. tokenTypes.word = tokenTypes.tilde = tokenTypes.tab = tokenTypes.str = tokenTypes.space = tokenTypes.slash = tokenTypes.singleQuote = tokenTypes.semicolon = tokenTypes.plus = tokenTypes.pipe = tokenTypes.openSquare = tokenTypes.openParenthesis = tokenTypes.newline = tokenTypes.greaterThan = tokenTypes.feed = tokenTypes.equals = tokenTypes.doubleQuote = tokenTypes.dollar = tokenTypes.cr = tokenTypes.comment = tokenTypes.comma = tokenTypes.combinator = tokenTypes.colon = tokenTypes.closeSquare = tokenTypes.closeParenthesis = tokenTypes.caret = tokenTypes.bang = tokenTypes.backslash = tokenTypes.at = tokenTypes.asterisk = tokenTypes.ampersand = void 0;
  14836. var ampersand = 38; // `&`.charCodeAt(0);
  14837. tokenTypes.ampersand = ampersand;
  14838. var asterisk = 42; // `*`.charCodeAt(0);
  14839. tokenTypes.asterisk = asterisk;
  14840. var at = 64; // `@`.charCodeAt(0);
  14841. tokenTypes.at = at;
  14842. var comma = 44; // `,`.charCodeAt(0);
  14843. tokenTypes.comma = comma;
  14844. var colon = 58; // `:`.charCodeAt(0);
  14845. tokenTypes.colon = colon;
  14846. var semicolon = 59; // `;`.charCodeAt(0);
  14847. tokenTypes.semicolon = semicolon;
  14848. var openParenthesis = 40; // `(`.charCodeAt(0);
  14849. tokenTypes.openParenthesis = openParenthesis;
  14850. var closeParenthesis = 41; // `)`.charCodeAt(0);
  14851. tokenTypes.closeParenthesis = closeParenthesis;
  14852. var openSquare = 91; // `[`.charCodeAt(0);
  14853. tokenTypes.openSquare = openSquare;
  14854. var closeSquare = 93; // `]`.charCodeAt(0);
  14855. tokenTypes.closeSquare = closeSquare;
  14856. var dollar = 36; // `$`.charCodeAt(0);
  14857. tokenTypes.dollar = dollar;
  14858. var tilde = 126; // `~`.charCodeAt(0);
  14859. tokenTypes.tilde = tilde;
  14860. var caret = 94; // `^`.charCodeAt(0);
  14861. tokenTypes.caret = caret;
  14862. var plus = 43; // `+`.charCodeAt(0);
  14863. tokenTypes.plus = plus;
  14864. var equals = 61; // `=`.charCodeAt(0);
  14865. tokenTypes.equals = equals;
  14866. var pipe = 124; // `|`.charCodeAt(0);
  14867. tokenTypes.pipe = pipe;
  14868. var greaterThan = 62; // `>`.charCodeAt(0);
  14869. tokenTypes.greaterThan = greaterThan;
  14870. var space = 32; // ` `.charCodeAt(0);
  14871. tokenTypes.space = space;
  14872. var singleQuote = 39; // `'`.charCodeAt(0);
  14873. tokenTypes.singleQuote = singleQuote;
  14874. var doubleQuote = 34; // `"`.charCodeAt(0);
  14875. tokenTypes.doubleQuote = doubleQuote;
  14876. var slash = 47; // `/`.charCodeAt(0);
  14877. tokenTypes.slash = slash;
  14878. var bang = 33; // `!`.charCodeAt(0);
  14879. tokenTypes.bang = bang;
  14880. var backslash = 92; // '\\'.charCodeAt(0);
  14881. tokenTypes.backslash = backslash;
  14882. var cr = 13; // '\r'.charCodeAt(0);
  14883. tokenTypes.cr = cr;
  14884. var feed = 12; // '\f'.charCodeAt(0);
  14885. tokenTypes.feed = feed;
  14886. var newline = 10; // '\n'.charCodeAt(0);
  14887. tokenTypes.newline = newline;
  14888. var tab = 9; // '\t'.charCodeAt(0);
  14889. // Expose aliases primarily for readability.
  14890. tokenTypes.tab = tab;
  14891. var str = singleQuote;
  14892. // No good single character representation!
  14893. tokenTypes.str = str;
  14894. var comment = -1;
  14895. tokenTypes.comment = comment;
  14896. var word = -2;
  14897. tokenTypes.word = word;
  14898. var combinator = -3;
  14899. tokenTypes.combinator = combinator;
  14900. return tokenTypes;
  14901. }
  14902. var hasRequiredTokenize;
  14903. function requireTokenize () {
  14904. if (hasRequiredTokenize) return tokenize;
  14905. hasRequiredTokenize = 1;
  14906. (function (exports) {
  14907. exports.__esModule = true;
  14908. exports.FIELDS = void 0;
  14909. exports["default"] = tokenize;
  14910. var t = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes());
  14911. var _unescapable, _wordDelimiters;
  14912. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  14913. function _interopRequireWildcard(obj, nodeInterop) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  14914. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  14915. var wordDelimiters = (_wordDelimiters = {}, _wordDelimiters[t.space] = true, _wordDelimiters[t.tab] = true, _wordDelimiters[t.newline] = true, _wordDelimiters[t.cr] = true, _wordDelimiters[t.feed] = true, _wordDelimiters[t.ampersand] = true, _wordDelimiters[t.asterisk] = true, _wordDelimiters[t.bang] = true, _wordDelimiters[t.comma] = true, _wordDelimiters[t.colon] = true, _wordDelimiters[t.semicolon] = true, _wordDelimiters[t.openParenthesis] = true, _wordDelimiters[t.closeParenthesis] = true, _wordDelimiters[t.openSquare] = true, _wordDelimiters[t.closeSquare] = true, _wordDelimiters[t.singleQuote] = true, _wordDelimiters[t.doubleQuote] = true, _wordDelimiters[t.plus] = true, _wordDelimiters[t.pipe] = true, _wordDelimiters[t.tilde] = true, _wordDelimiters[t.greaterThan] = true, _wordDelimiters[t.equals] = true, _wordDelimiters[t.dollar] = true, _wordDelimiters[t.caret] = true, _wordDelimiters[t.slash] = true, _wordDelimiters);
  14916. var hex = {};
  14917. var hexChars = "0123456789abcdefABCDEF";
  14918. for (var i = 0; i < hexChars.length; i++) {
  14919. hex[hexChars.charCodeAt(i)] = true;
  14920. }
  14921. /**
  14922. * Returns the last index of the bar css word
  14923. * @param {string} css The string in which the word begins
  14924. * @param {number} start The index into the string where word's first letter occurs
  14925. */
  14926. function consumeWord(css, start) {
  14927. var next = start;
  14928. var code;
  14929. do {
  14930. code = css.charCodeAt(next);
  14931. if (wordDelimiters[code]) {
  14932. return next - 1;
  14933. } else if (code === t.backslash) {
  14934. next = consumeEscape(css, next) + 1;
  14935. } else {
  14936. // All other characters are part of the word
  14937. next++;
  14938. }
  14939. } while (next < css.length);
  14940. return next - 1;
  14941. }
  14942. /**
  14943. * Returns the last index of the escape sequence
  14944. * @param {string} css The string in which the sequence begins
  14945. * @param {number} start The index into the string where escape character (`\`) occurs.
  14946. */
  14947. function consumeEscape(css, start) {
  14948. var next = start;
  14949. var code = css.charCodeAt(next + 1);
  14950. if (unescapable[code]) ; else if (hex[code]) {
  14951. var hexDigits = 0;
  14952. // consume up to 6 hex chars
  14953. do {
  14954. next++;
  14955. hexDigits++;
  14956. code = css.charCodeAt(next + 1);
  14957. } while (hex[code] && hexDigits < 6);
  14958. // if fewer than 6 hex chars, a trailing space ends the escape
  14959. if (hexDigits < 6 && code === t.space) {
  14960. next++;
  14961. }
  14962. } else {
  14963. // the next char is part of the current word
  14964. next++;
  14965. }
  14966. return next;
  14967. }
  14968. var FIELDS = {
  14969. TYPE: 0,
  14970. START_LINE: 1,
  14971. START_COL: 2,
  14972. END_LINE: 3,
  14973. END_COL: 4,
  14974. START_POS: 5,
  14975. END_POS: 6
  14976. };
  14977. exports.FIELDS = FIELDS;
  14978. function tokenize(input) {
  14979. var tokens = [];
  14980. var css = input.css.valueOf();
  14981. var _css = css,
  14982. length = _css.length;
  14983. var offset = -1;
  14984. var line = 1;
  14985. var start = 0;
  14986. var end = 0;
  14987. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  14988. function unclosed(what, fix) {
  14989. if (input.safe) {
  14990. // fyi: this is never set to true.
  14991. css += fix;
  14992. next = css.length - 1;
  14993. } else {
  14994. throw input.error('Unclosed ' + what, line, start - offset, start);
  14995. }
  14996. }
  14997. while (start < length) {
  14998. code = css.charCodeAt(start);
  14999. if (code === t.newline) {
  15000. offset = start;
  15001. line += 1;
  15002. }
  15003. switch (code) {
  15004. case t.space:
  15005. case t.tab:
  15006. case t.newline:
  15007. case t.cr:
  15008. case t.feed:
  15009. next = start;
  15010. do {
  15011. next += 1;
  15012. code = css.charCodeAt(next);
  15013. if (code === t.newline) {
  15014. offset = next;
  15015. line += 1;
  15016. }
  15017. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  15018. tokenType = t.space;
  15019. endLine = line;
  15020. endColumn = next - offset - 1;
  15021. end = next;
  15022. break;
  15023. case t.plus:
  15024. case t.greaterThan:
  15025. case t.tilde:
  15026. case t.pipe:
  15027. next = start;
  15028. do {
  15029. next += 1;
  15030. code = css.charCodeAt(next);
  15031. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  15032. tokenType = t.combinator;
  15033. endLine = line;
  15034. endColumn = start - offset;
  15035. end = next;
  15036. break;
  15037. // Consume these characters as single tokens.
  15038. case t.asterisk:
  15039. case t.ampersand:
  15040. case t.bang:
  15041. case t.comma:
  15042. case t.equals:
  15043. case t.dollar:
  15044. case t.caret:
  15045. case t.openSquare:
  15046. case t.closeSquare:
  15047. case t.colon:
  15048. case t.semicolon:
  15049. case t.openParenthesis:
  15050. case t.closeParenthesis:
  15051. next = start;
  15052. tokenType = code;
  15053. endLine = line;
  15054. endColumn = start - offset;
  15055. end = next + 1;
  15056. break;
  15057. case t.singleQuote:
  15058. case t.doubleQuote:
  15059. quote = code === t.singleQuote ? "'" : '"';
  15060. next = start;
  15061. do {
  15062. escaped = false;
  15063. next = css.indexOf(quote, next + 1);
  15064. if (next === -1) {
  15065. unclosed('quote', quote);
  15066. }
  15067. escapePos = next;
  15068. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  15069. escapePos -= 1;
  15070. escaped = !escaped;
  15071. }
  15072. } while (escaped);
  15073. tokenType = t.str;
  15074. endLine = line;
  15075. endColumn = start - offset;
  15076. end = next + 1;
  15077. break;
  15078. default:
  15079. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  15080. next = css.indexOf('*/', start + 2) + 1;
  15081. if (next === 0) {
  15082. unclosed('comment', '*/');
  15083. }
  15084. content = css.slice(start, next + 1);
  15085. lines = content.split('\n');
  15086. last = lines.length - 1;
  15087. if (last > 0) {
  15088. nextLine = line + last;
  15089. nextOffset = next - lines[last].length;
  15090. } else {
  15091. nextLine = line;
  15092. nextOffset = offset;
  15093. }
  15094. tokenType = t.comment;
  15095. line = nextLine;
  15096. endLine = nextLine;
  15097. endColumn = next - nextOffset;
  15098. } else if (code === t.slash) {
  15099. next = start;
  15100. tokenType = code;
  15101. endLine = line;
  15102. endColumn = start - offset;
  15103. end = next + 1;
  15104. } else {
  15105. next = consumeWord(css, start);
  15106. tokenType = t.word;
  15107. endLine = line;
  15108. endColumn = next - offset;
  15109. }
  15110. end = next + 1;
  15111. break;
  15112. }
  15113. // Ensure that the token structure remains consistent
  15114. tokens.push([tokenType,
  15115. // [0] Token type
  15116. line,
  15117. // [1] Starting line
  15118. start - offset,
  15119. // [2] Starting column
  15120. endLine,
  15121. // [3] Ending line
  15122. endColumn,
  15123. // [4] Ending column
  15124. start,
  15125. // [5] Start position / Source index
  15126. end // [6] End position
  15127. ]);
  15128. // Reset offset for the next token
  15129. if (nextOffset) {
  15130. offset = nextOffset;
  15131. nextOffset = null;
  15132. }
  15133. start = end;
  15134. }
  15135. return tokens;
  15136. }
  15137. } (tokenize));
  15138. return tokenize;
  15139. }
  15140. var hasRequiredParser;
  15141. function requireParser () {
  15142. if (hasRequiredParser) return parser.exports;
  15143. hasRequiredParser = 1;
  15144. (function (module, exports) {
  15145. exports.__esModule = true;
  15146. exports["default"] = void 0;
  15147. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot());
  15148. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector());
  15149. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName());
  15150. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment());
  15151. var _id = _interopRequireDefault(/*@__PURE__*/ requireId());
  15152. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag());
  15153. var _string = _interopRequireDefault(/*@__PURE__*/ requireString());
  15154. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo());
  15155. var _attribute = _interopRequireWildcard(/*@__PURE__*/ requireAttribute());
  15156. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal());
  15157. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator());
  15158. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting());
  15159. var _sortAscending = _interopRequireDefault(/*@__PURE__*/ requireSortAscending());
  15160. var _tokenize = _interopRequireWildcard(/*@__PURE__*/ requireTokenize());
  15161. var tokens = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes());
  15162. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes());
  15163. var _util = /*@__PURE__*/ requireUtil();
  15164. var _WHITESPACE_TOKENS, _Object$assign;
  15165. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  15166. function _interopRequireWildcard(obj, nodeInterop) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  15167. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  15168. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  15169. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  15170. var WHITESPACE_TOKENS = (_WHITESPACE_TOKENS = {}, _WHITESPACE_TOKENS[tokens.space] = true, _WHITESPACE_TOKENS[tokens.cr] = true, _WHITESPACE_TOKENS[tokens.feed] = true, _WHITESPACE_TOKENS[tokens.newline] = true, _WHITESPACE_TOKENS[tokens.tab] = true, _WHITESPACE_TOKENS);
  15171. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  15172. function tokenStart(token) {
  15173. return {
  15174. line: token[_tokenize.FIELDS.START_LINE],
  15175. column: token[_tokenize.FIELDS.START_COL]
  15176. };
  15177. }
  15178. function tokenEnd(token) {
  15179. return {
  15180. line: token[_tokenize.FIELDS.END_LINE],
  15181. column: token[_tokenize.FIELDS.END_COL]
  15182. };
  15183. }
  15184. function getSource(startLine, startColumn, endLine, endColumn) {
  15185. return {
  15186. start: {
  15187. line: startLine,
  15188. column: startColumn
  15189. },
  15190. end: {
  15191. line: endLine,
  15192. column: endColumn
  15193. }
  15194. };
  15195. }
  15196. function getTokenSource(token) {
  15197. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  15198. }
  15199. function getTokenSourceSpan(startToken, endToken) {
  15200. if (!startToken) {
  15201. return undefined;
  15202. }
  15203. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  15204. }
  15205. function unescapeProp(node, prop) {
  15206. var value = node[prop];
  15207. if (typeof value !== "string") {
  15208. return;
  15209. }
  15210. if (value.indexOf("\\") !== -1) {
  15211. (0, _util.ensureObject)(node, 'raws');
  15212. node[prop] = (0, _util.unesc)(value);
  15213. if (node.raws[prop] === undefined) {
  15214. node.raws[prop] = value;
  15215. }
  15216. }
  15217. return node;
  15218. }
  15219. function indexesOf(array, item) {
  15220. var i = -1;
  15221. var indexes = [];
  15222. while ((i = array.indexOf(item, i + 1)) !== -1) {
  15223. indexes.push(i);
  15224. }
  15225. return indexes;
  15226. }
  15227. function uniqs() {
  15228. var list = Array.prototype.concat.apply([], arguments);
  15229. return list.filter(function (item, i) {
  15230. return i === list.indexOf(item);
  15231. });
  15232. }
  15233. var Parser = /*#__PURE__*/function () {
  15234. function Parser(rule, options) {
  15235. if (options === void 0) {
  15236. options = {};
  15237. }
  15238. this.rule = rule;
  15239. this.options = Object.assign({
  15240. lossy: false,
  15241. safe: false
  15242. }, options);
  15243. this.position = 0;
  15244. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  15245. this.tokens = (0, _tokenize["default"])({
  15246. css: this.css,
  15247. error: this._errorGenerator(),
  15248. safe: this.options.safe
  15249. });
  15250. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  15251. this.root = new _root["default"]({
  15252. source: rootSource
  15253. });
  15254. this.root.errorGenerator = this._errorGenerator();
  15255. var selector = new _selector["default"]({
  15256. source: {
  15257. start: {
  15258. line: 1,
  15259. column: 1
  15260. }
  15261. },
  15262. sourceIndex: 0
  15263. });
  15264. this.root.append(selector);
  15265. this.current = selector;
  15266. this.loop();
  15267. }
  15268. var _proto = Parser.prototype;
  15269. _proto._errorGenerator = function _errorGenerator() {
  15270. var _this = this;
  15271. return function (message, errorOptions) {
  15272. if (typeof _this.rule === 'string') {
  15273. return new Error(message);
  15274. }
  15275. return _this.rule.error(message, errorOptions);
  15276. };
  15277. };
  15278. _proto.attribute = function attribute() {
  15279. var attr = [];
  15280. var startingToken = this.currToken;
  15281. this.position++;
  15282. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  15283. attr.push(this.currToken);
  15284. this.position++;
  15285. }
  15286. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  15287. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  15288. }
  15289. var len = attr.length;
  15290. var node = {
  15291. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  15292. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  15293. };
  15294. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  15295. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  15296. }
  15297. var pos = 0;
  15298. var spaceBefore = '';
  15299. var commentBefore = '';
  15300. var lastAdded = null;
  15301. var spaceAfterMeaningfulToken = false;
  15302. while (pos < len) {
  15303. var token = attr[pos];
  15304. var content = this.content(token);
  15305. var next = attr[pos + 1];
  15306. switch (token[_tokenize.FIELDS.TYPE]) {
  15307. case tokens.space:
  15308. // if (
  15309. // len === 1 ||
  15310. // pos === 0 && this.content(next) === '|'
  15311. // ) {
  15312. // return this.expected('attribute', token[TOKEN.START_POS], content);
  15313. // }
  15314. spaceAfterMeaningfulToken = true;
  15315. if (this.options.lossy) {
  15316. break;
  15317. }
  15318. if (lastAdded) {
  15319. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  15320. var prevContent = node.spaces[lastAdded].after || '';
  15321. node.spaces[lastAdded].after = prevContent + content;
  15322. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  15323. if (existingComment) {
  15324. node.raws.spaces[lastAdded].after = existingComment + content;
  15325. }
  15326. } else {
  15327. spaceBefore = spaceBefore + content;
  15328. commentBefore = commentBefore + content;
  15329. }
  15330. break;
  15331. case tokens.asterisk:
  15332. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  15333. node.operator = content;
  15334. lastAdded = 'operator';
  15335. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  15336. if (spaceBefore) {
  15337. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  15338. node.spaces.attribute.before = spaceBefore;
  15339. spaceBefore = '';
  15340. }
  15341. if (commentBefore) {
  15342. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  15343. node.raws.spaces.attribute.before = spaceBefore;
  15344. commentBefore = '';
  15345. }
  15346. node.namespace = (node.namespace || "") + content;
  15347. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  15348. if (rawValue) {
  15349. node.raws.namespace += content;
  15350. }
  15351. lastAdded = 'namespace';
  15352. }
  15353. spaceAfterMeaningfulToken = false;
  15354. break;
  15355. case tokens.dollar:
  15356. if (lastAdded === "value") {
  15357. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  15358. node.value += "$";
  15359. if (oldRawValue) {
  15360. node.raws.value = oldRawValue + "$";
  15361. }
  15362. break;
  15363. }
  15364. // Falls through
  15365. case tokens.caret:
  15366. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  15367. node.operator = content;
  15368. lastAdded = 'operator';
  15369. }
  15370. spaceAfterMeaningfulToken = false;
  15371. break;
  15372. case tokens.combinator:
  15373. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  15374. node.operator = content;
  15375. lastAdded = 'operator';
  15376. }
  15377. if (content !== '|') {
  15378. spaceAfterMeaningfulToken = false;
  15379. break;
  15380. }
  15381. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  15382. node.operator = content;
  15383. lastAdded = 'operator';
  15384. } else if (!node.namespace && !node.attribute) {
  15385. node.namespace = true;
  15386. }
  15387. spaceAfterMeaningfulToken = false;
  15388. break;
  15389. case tokens.word:
  15390. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
  15391. // this look-ahead probably fails with comment nodes involved.
  15392. !node.operator && !node.namespace) {
  15393. node.namespace = content;
  15394. lastAdded = 'namespace';
  15395. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  15396. if (spaceBefore) {
  15397. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  15398. node.spaces.attribute.before = spaceBefore;
  15399. spaceBefore = '';
  15400. }
  15401. if (commentBefore) {
  15402. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  15403. node.raws.spaces.attribute.before = commentBefore;
  15404. commentBefore = '';
  15405. }
  15406. node.attribute = (node.attribute || "") + content;
  15407. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  15408. if (_rawValue) {
  15409. node.raws.attribute += content;
  15410. }
  15411. lastAdded = 'attribute';
  15412. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  15413. var _unescaped = (0, _util.unesc)(content);
  15414. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  15415. var oldValue = node.value || '';
  15416. node.value = oldValue + _unescaped;
  15417. node.quoteMark = null;
  15418. if (_unescaped !== content || _oldRawValue) {
  15419. (0, _util.ensureObject)(node, 'raws');
  15420. node.raws.value = (_oldRawValue || oldValue) + content;
  15421. }
  15422. lastAdded = 'value';
  15423. } else {
  15424. var insensitive = content === 'i' || content === "I";
  15425. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  15426. node.insensitive = insensitive;
  15427. if (!insensitive || content === "I") {
  15428. (0, _util.ensureObject)(node, 'raws');
  15429. node.raws.insensitiveFlag = content;
  15430. }
  15431. lastAdded = 'insensitive';
  15432. if (spaceBefore) {
  15433. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  15434. node.spaces.insensitive.before = spaceBefore;
  15435. spaceBefore = '';
  15436. }
  15437. if (commentBefore) {
  15438. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  15439. node.raws.spaces.insensitive.before = commentBefore;
  15440. commentBefore = '';
  15441. }
  15442. } else if (node.value || node.value === '') {
  15443. lastAdded = 'value';
  15444. node.value += content;
  15445. if (node.raws.value) {
  15446. node.raws.value += content;
  15447. }
  15448. }
  15449. }
  15450. spaceAfterMeaningfulToken = false;
  15451. break;
  15452. case tokens.str:
  15453. if (!node.attribute || !node.operator) {
  15454. return this.error("Expected an attribute followed by an operator preceding the string.", {
  15455. index: token[_tokenize.FIELDS.START_POS]
  15456. });
  15457. }
  15458. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  15459. unescaped = _unescapeValue.unescaped,
  15460. quoteMark = _unescapeValue.quoteMark;
  15461. node.value = unescaped;
  15462. node.quoteMark = quoteMark;
  15463. lastAdded = 'value';
  15464. (0, _util.ensureObject)(node, 'raws');
  15465. node.raws.value = content;
  15466. spaceAfterMeaningfulToken = false;
  15467. break;
  15468. case tokens.equals:
  15469. if (!node.attribute) {
  15470. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  15471. }
  15472. if (node.value) {
  15473. return this.error('Unexpected "=" found; an operator was already defined.', {
  15474. index: token[_tokenize.FIELDS.START_POS]
  15475. });
  15476. }
  15477. node.operator = node.operator ? node.operator + content : content;
  15478. lastAdded = 'operator';
  15479. spaceAfterMeaningfulToken = false;
  15480. break;
  15481. case tokens.comment:
  15482. if (lastAdded) {
  15483. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  15484. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  15485. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  15486. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  15487. node.raws.spaces[lastAdded].after = rawLastComment + content;
  15488. } else {
  15489. var lastValue = node[lastAdded] || '';
  15490. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  15491. (0, _util.ensureObject)(node, 'raws');
  15492. node.raws[lastAdded] = rawLastValue + content;
  15493. }
  15494. } else {
  15495. commentBefore = commentBefore + content;
  15496. }
  15497. break;
  15498. default:
  15499. return this.error("Unexpected \"" + content + "\" found.", {
  15500. index: token[_tokenize.FIELDS.START_POS]
  15501. });
  15502. }
  15503. pos++;
  15504. }
  15505. unescapeProp(node, "attribute");
  15506. unescapeProp(node, "namespace");
  15507. this.newNode(new _attribute["default"](node));
  15508. this.position++;
  15509. }
  15510. /**
  15511. * return a node containing meaningless garbage up to (but not including) the specified token position.
  15512. * if the token position is negative, all remaining tokens are consumed.
  15513. *
  15514. * This returns an array containing a single string node if all whitespace,
  15515. * otherwise an array of comment nodes with space before and after.
  15516. *
  15517. * These tokens are not added to the current selector, the caller can add them or use them to amend
  15518. * a previous node's space metadata.
  15519. *
  15520. * In lossy mode, this returns only comments.
  15521. */;
  15522. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  15523. if (stopPosition < 0) {
  15524. stopPosition = this.tokens.length;
  15525. }
  15526. var startPosition = this.position;
  15527. var nodes = [];
  15528. var space = "";
  15529. var lastComment = undefined;
  15530. do {
  15531. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  15532. if (!this.options.lossy) {
  15533. space += this.content();
  15534. }
  15535. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  15536. var spaces = {};
  15537. if (space) {
  15538. spaces.before = space;
  15539. space = "";
  15540. }
  15541. lastComment = new _comment["default"]({
  15542. value: this.content(),
  15543. source: getTokenSource(this.currToken),
  15544. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  15545. spaces: spaces
  15546. });
  15547. nodes.push(lastComment);
  15548. }
  15549. } while (++this.position < stopPosition);
  15550. if (space) {
  15551. if (lastComment) {
  15552. lastComment.spaces.after = space;
  15553. } else if (!this.options.lossy) {
  15554. var firstToken = this.tokens[startPosition];
  15555. var lastToken = this.tokens[this.position - 1];
  15556. nodes.push(new _string["default"]({
  15557. value: '',
  15558. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  15559. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  15560. spaces: {
  15561. before: space,
  15562. after: ''
  15563. }
  15564. }));
  15565. }
  15566. }
  15567. return nodes;
  15568. }
  15569. /**
  15570. *
  15571. * @param {*} nodes
  15572. */;
  15573. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  15574. var _this2 = this;
  15575. if (requiredSpace === void 0) {
  15576. requiredSpace = false;
  15577. }
  15578. var space = "";
  15579. var rawSpace = "";
  15580. nodes.forEach(function (n) {
  15581. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  15582. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  15583. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  15584. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  15585. });
  15586. if (rawSpace === space) {
  15587. rawSpace = undefined;
  15588. }
  15589. var result = {
  15590. space: space,
  15591. rawSpace: rawSpace
  15592. };
  15593. return result;
  15594. };
  15595. _proto.isNamedCombinator = function isNamedCombinator(position) {
  15596. if (position === void 0) {
  15597. position = this.position;
  15598. }
  15599. return this.tokens[position + 0] && this.tokens[position + 0][_tokenize.FIELDS.TYPE] === tokens.slash && this.tokens[position + 1] && this.tokens[position + 1][_tokenize.FIELDS.TYPE] === tokens.word && this.tokens[position + 2] && this.tokens[position + 2][_tokenize.FIELDS.TYPE] === tokens.slash;
  15600. };
  15601. _proto.namedCombinator = function namedCombinator() {
  15602. if (this.isNamedCombinator()) {
  15603. var nameRaw = this.content(this.tokens[this.position + 1]);
  15604. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  15605. var raws = {};
  15606. if (name !== nameRaw) {
  15607. raws.value = "/" + nameRaw + "/";
  15608. }
  15609. var node = new _combinator["default"]({
  15610. value: "/" + name + "/",
  15611. source: getSource(this.currToken[_tokenize.FIELDS.START_LINE], this.currToken[_tokenize.FIELDS.START_COL], this.tokens[this.position + 2][_tokenize.FIELDS.END_LINE], this.tokens[this.position + 2][_tokenize.FIELDS.END_COL]),
  15612. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  15613. raws: raws
  15614. });
  15615. this.position = this.position + 3;
  15616. return node;
  15617. } else {
  15618. this.unexpected();
  15619. }
  15620. };
  15621. _proto.combinator = function combinator() {
  15622. var _this3 = this;
  15623. if (this.content() === '|') {
  15624. return this.namespace();
  15625. }
  15626. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  15627. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  15628. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15629. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  15630. if (nodes.length > 0) {
  15631. var last = this.current.last;
  15632. if (last) {
  15633. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  15634. space = _this$convertWhitespa.space,
  15635. rawSpace = _this$convertWhitespa.rawSpace;
  15636. if (rawSpace !== undefined) {
  15637. last.rawSpaceAfter += rawSpace;
  15638. }
  15639. last.spaces.after += space;
  15640. } else {
  15641. nodes.forEach(function (n) {
  15642. return _this3.newNode(n);
  15643. });
  15644. }
  15645. }
  15646. return;
  15647. }
  15648. var firstToken = this.currToken;
  15649. var spaceOrDescendantSelectorNodes = undefined;
  15650. if (nextSigTokenPos > this.position) {
  15651. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  15652. }
  15653. var node;
  15654. if (this.isNamedCombinator()) {
  15655. node = this.namedCombinator();
  15656. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  15657. node = new _combinator["default"]({
  15658. value: this.content(),
  15659. source: getTokenSource(this.currToken),
  15660. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  15661. });
  15662. this.position++;
  15663. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  15664. this.unexpected();
  15665. }
  15666. if (node) {
  15667. if (spaceOrDescendantSelectorNodes) {
  15668. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  15669. _space = _this$convertWhitespa2.space,
  15670. _rawSpace = _this$convertWhitespa2.rawSpace;
  15671. node.spaces.before = _space;
  15672. node.rawSpaceBefore = _rawSpace;
  15673. }
  15674. } else {
  15675. // descendant combinator
  15676. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  15677. _space2 = _this$convertWhitespa3.space,
  15678. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  15679. if (!_rawSpace2) {
  15680. _rawSpace2 = _space2;
  15681. }
  15682. var spaces = {};
  15683. var raws = {
  15684. spaces: {}
  15685. };
  15686. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  15687. spaces.before = _space2.slice(0, _space2.length - 1);
  15688. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  15689. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  15690. spaces.after = _space2.slice(1);
  15691. raws.spaces.after = _rawSpace2.slice(1);
  15692. } else {
  15693. raws.value = _rawSpace2;
  15694. }
  15695. node = new _combinator["default"]({
  15696. value: ' ',
  15697. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  15698. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  15699. spaces: spaces,
  15700. raws: raws
  15701. });
  15702. }
  15703. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  15704. node.spaces.after = this.optionalSpace(this.content());
  15705. this.position++;
  15706. }
  15707. return this.newNode(node);
  15708. };
  15709. _proto.comma = function comma() {
  15710. if (this.position === this.tokens.length - 1) {
  15711. this.root.trailingComma = true;
  15712. this.position++;
  15713. return;
  15714. }
  15715. this.current._inferEndPosition();
  15716. var selector = new _selector["default"]({
  15717. source: {
  15718. start: tokenStart(this.tokens[this.position + 1])
  15719. },
  15720. sourceIndex: this.tokens[this.position + 1][_tokenize.FIELDS.START_POS]
  15721. });
  15722. this.current.parent.append(selector);
  15723. this.current = selector;
  15724. this.position++;
  15725. };
  15726. _proto.comment = function comment() {
  15727. var current = this.currToken;
  15728. this.newNode(new _comment["default"]({
  15729. value: this.content(),
  15730. source: getTokenSource(current),
  15731. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15732. }));
  15733. this.position++;
  15734. };
  15735. _proto.error = function error(message, opts) {
  15736. throw this.root.error(message, opts);
  15737. };
  15738. _proto.missingBackslash = function missingBackslash() {
  15739. return this.error('Expected a backslash preceding the semicolon.', {
  15740. index: this.currToken[_tokenize.FIELDS.START_POS]
  15741. });
  15742. };
  15743. _proto.missingParenthesis = function missingParenthesis() {
  15744. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  15745. };
  15746. _proto.missingSquareBracket = function missingSquareBracket() {
  15747. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  15748. };
  15749. _proto.unexpected = function unexpected() {
  15750. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  15751. };
  15752. _proto.unexpectedPipe = function unexpectedPipe() {
  15753. return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  15754. };
  15755. _proto.namespace = function namespace() {
  15756. var before = this.prevToken && this.content(this.prevToken) || true;
  15757. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  15758. this.position++;
  15759. return this.word(before);
  15760. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  15761. this.position++;
  15762. return this.universal(before);
  15763. }
  15764. this.unexpectedPipe();
  15765. };
  15766. _proto.nesting = function nesting() {
  15767. if (this.nextToken) {
  15768. var nextContent = this.content(this.nextToken);
  15769. if (nextContent === "|") {
  15770. this.position++;
  15771. return;
  15772. }
  15773. }
  15774. var current = this.currToken;
  15775. this.newNode(new _nesting["default"]({
  15776. value: this.content(),
  15777. source: getTokenSource(current),
  15778. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15779. }));
  15780. this.position++;
  15781. };
  15782. _proto.parentheses = function parentheses() {
  15783. var last = this.current.last;
  15784. var unbalanced = 1;
  15785. this.position++;
  15786. if (last && last.type === types.PSEUDO) {
  15787. var selector = new _selector["default"]({
  15788. source: {
  15789. start: tokenStart(this.tokens[this.position])
  15790. },
  15791. sourceIndex: this.tokens[this.position][_tokenize.FIELDS.START_POS]
  15792. });
  15793. var cache = this.current;
  15794. last.append(selector);
  15795. this.current = selector;
  15796. while (this.position < this.tokens.length && unbalanced) {
  15797. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15798. unbalanced++;
  15799. }
  15800. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15801. unbalanced--;
  15802. }
  15803. if (unbalanced) {
  15804. this.parse();
  15805. } else {
  15806. this.current.source.end = tokenEnd(this.currToken);
  15807. this.current.parent.source.end = tokenEnd(this.currToken);
  15808. this.position++;
  15809. }
  15810. }
  15811. this.current = cache;
  15812. } else {
  15813. // I think this case should be an error. It's used to implement a basic parse of media queries
  15814. // but I don't think it's a good idea.
  15815. var parenStart = this.currToken;
  15816. var parenValue = "(";
  15817. var parenEnd;
  15818. while (this.position < this.tokens.length && unbalanced) {
  15819. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15820. unbalanced++;
  15821. }
  15822. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15823. unbalanced--;
  15824. }
  15825. parenEnd = this.currToken;
  15826. parenValue += this.parseParenthesisToken(this.currToken);
  15827. this.position++;
  15828. }
  15829. if (last) {
  15830. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  15831. } else {
  15832. this.newNode(new _string["default"]({
  15833. value: parenValue,
  15834. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  15835. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  15836. }));
  15837. }
  15838. }
  15839. if (unbalanced) {
  15840. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  15841. }
  15842. };
  15843. _proto.pseudo = function pseudo() {
  15844. var _this4 = this;
  15845. var pseudoStr = '';
  15846. var startingToken = this.currToken;
  15847. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  15848. pseudoStr += this.content();
  15849. this.position++;
  15850. }
  15851. if (!this.currToken) {
  15852. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  15853. }
  15854. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  15855. this.splitWord(false, function (first, length) {
  15856. pseudoStr += first;
  15857. _this4.newNode(new _pseudo["default"]({
  15858. value: pseudoStr,
  15859. source: getTokenSourceSpan(startingToken, _this4.currToken),
  15860. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  15861. }));
  15862. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15863. _this4.error('Misplaced parenthesis.', {
  15864. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  15865. });
  15866. }
  15867. });
  15868. } else {
  15869. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  15870. }
  15871. };
  15872. _proto.space = function space() {
  15873. var content = this.content();
  15874. // Handle space before and after the selector
  15875. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  15876. return node.type === 'comment';
  15877. })) {
  15878. this.spaces = this.optionalSpace(content);
  15879. this.position++;
  15880. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15881. this.current.last.spaces.after = this.optionalSpace(content);
  15882. this.position++;
  15883. } else {
  15884. this.combinator();
  15885. }
  15886. };
  15887. _proto.string = function string() {
  15888. var current = this.currToken;
  15889. this.newNode(new _string["default"]({
  15890. value: this.content(),
  15891. source: getTokenSource(current),
  15892. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15893. }));
  15894. this.position++;
  15895. };
  15896. _proto.universal = function universal(namespace) {
  15897. var nextToken = this.nextToken;
  15898. if (nextToken && this.content(nextToken) === '|') {
  15899. this.position++;
  15900. return this.namespace();
  15901. }
  15902. var current = this.currToken;
  15903. this.newNode(new _universal["default"]({
  15904. value: this.content(),
  15905. source: getTokenSource(current),
  15906. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15907. }), namespace);
  15908. this.position++;
  15909. };
  15910. _proto.splitWord = function splitWord(namespace, firstCallback) {
  15911. var _this5 = this;
  15912. var nextToken = this.nextToken;
  15913. var word = this.content();
  15914. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  15915. this.position++;
  15916. var current = this.content();
  15917. word += current;
  15918. if (current.lastIndexOf('\\') === current.length - 1) {
  15919. var next = this.nextToken;
  15920. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  15921. word += this.requiredSpace(this.content(next));
  15922. this.position++;
  15923. }
  15924. }
  15925. nextToken = this.nextToken;
  15926. }
  15927. var hasClass = indexesOf(word, '.').filter(function (i) {
  15928. // Allow escaped dot within class name
  15929. var escapedDot = word[i - 1] === '\\';
  15930. // Allow decimal numbers percent in @keyframes
  15931. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  15932. return !escapedDot && !isKeyframesPercent;
  15933. });
  15934. var hasId = indexesOf(word, '#').filter(function (i) {
  15935. return word[i - 1] !== '\\';
  15936. });
  15937. // Eliminate Sass interpolations from the list of id indexes
  15938. var interpolations = indexesOf(word, '#{');
  15939. if (interpolations.length) {
  15940. hasId = hasId.filter(function (hashIndex) {
  15941. return !~interpolations.indexOf(hashIndex);
  15942. });
  15943. }
  15944. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  15945. indices.forEach(function (ind, i) {
  15946. var index = indices[i + 1] || word.length;
  15947. var value = word.slice(ind, index);
  15948. if (i === 0 && firstCallback) {
  15949. return firstCallback.call(_this5, value, indices.length);
  15950. }
  15951. var node;
  15952. var current = _this5.currToken;
  15953. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  15954. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  15955. if (~hasClass.indexOf(ind)) {
  15956. var classNameOpts = {
  15957. value: value.slice(1),
  15958. source: source,
  15959. sourceIndex: sourceIndex
  15960. };
  15961. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  15962. } else if (~hasId.indexOf(ind)) {
  15963. var idOpts = {
  15964. value: value.slice(1),
  15965. source: source,
  15966. sourceIndex: sourceIndex
  15967. };
  15968. node = new _id["default"](unescapeProp(idOpts, "value"));
  15969. } else {
  15970. var tagOpts = {
  15971. value: value,
  15972. source: source,
  15973. sourceIndex: sourceIndex
  15974. };
  15975. unescapeProp(tagOpts, "value");
  15976. node = new _tag["default"](tagOpts);
  15977. }
  15978. _this5.newNode(node, namespace);
  15979. // Ensure that the namespace is used only once
  15980. namespace = null;
  15981. });
  15982. this.position++;
  15983. };
  15984. _proto.word = function word(namespace) {
  15985. var nextToken = this.nextToken;
  15986. if (nextToken && this.content(nextToken) === '|') {
  15987. this.position++;
  15988. return this.namespace();
  15989. }
  15990. return this.splitWord(namespace);
  15991. };
  15992. _proto.loop = function loop() {
  15993. while (this.position < this.tokens.length) {
  15994. this.parse(true);
  15995. }
  15996. this.current._inferEndPosition();
  15997. return this.root;
  15998. };
  15999. _proto.parse = function parse(throwOnParenthesis) {
  16000. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  16001. case tokens.space:
  16002. this.space();
  16003. break;
  16004. case tokens.comment:
  16005. this.comment();
  16006. break;
  16007. case tokens.openParenthesis:
  16008. this.parentheses();
  16009. break;
  16010. case tokens.closeParenthesis:
  16011. if (throwOnParenthesis) {
  16012. this.missingParenthesis();
  16013. }
  16014. break;
  16015. case tokens.openSquare:
  16016. this.attribute();
  16017. break;
  16018. case tokens.dollar:
  16019. case tokens.caret:
  16020. case tokens.equals:
  16021. case tokens.word:
  16022. this.word();
  16023. break;
  16024. case tokens.colon:
  16025. this.pseudo();
  16026. break;
  16027. case tokens.comma:
  16028. this.comma();
  16029. break;
  16030. case tokens.asterisk:
  16031. this.universal();
  16032. break;
  16033. case tokens.ampersand:
  16034. this.nesting();
  16035. break;
  16036. case tokens.slash:
  16037. case tokens.combinator:
  16038. this.combinator();
  16039. break;
  16040. case tokens.str:
  16041. this.string();
  16042. break;
  16043. // These cases throw; no break needed.
  16044. case tokens.closeSquare:
  16045. this.missingSquareBracket();
  16046. case tokens.semicolon:
  16047. this.missingBackslash();
  16048. default:
  16049. this.unexpected();
  16050. }
  16051. }
  16052. /**
  16053. * Helpers
  16054. */;
  16055. _proto.expected = function expected(description, index, found) {
  16056. if (Array.isArray(description)) {
  16057. var last = description.pop();
  16058. description = description.join(', ') + " or " + last;
  16059. }
  16060. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  16061. if (!found) {
  16062. return this.error("Expected " + an + " " + description + ".", {
  16063. index: index
  16064. });
  16065. }
  16066. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  16067. index: index
  16068. });
  16069. };
  16070. _proto.requiredSpace = function requiredSpace(space) {
  16071. return this.options.lossy ? ' ' : space;
  16072. };
  16073. _proto.optionalSpace = function optionalSpace(space) {
  16074. return this.options.lossy ? '' : space;
  16075. };
  16076. _proto.lossySpace = function lossySpace(space, required) {
  16077. if (this.options.lossy) {
  16078. return required ? ' ' : '';
  16079. } else {
  16080. return space;
  16081. }
  16082. };
  16083. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  16084. var content = this.content(token);
  16085. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  16086. return this.requiredSpace(content);
  16087. } else {
  16088. return content;
  16089. }
  16090. };
  16091. _proto.newNode = function newNode(node, namespace) {
  16092. if (namespace) {
  16093. if (/^ +$/.test(namespace)) {
  16094. if (!this.options.lossy) {
  16095. this.spaces = (this.spaces || '') + namespace;
  16096. }
  16097. namespace = true;
  16098. }
  16099. node.namespace = namespace;
  16100. unescapeProp(node, "namespace");
  16101. }
  16102. if (this.spaces) {
  16103. node.spaces.before = this.spaces;
  16104. this.spaces = '';
  16105. }
  16106. return this.current.append(node);
  16107. };
  16108. _proto.content = function content(token) {
  16109. if (token === void 0) {
  16110. token = this.currToken;
  16111. }
  16112. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  16113. };
  16114. /**
  16115. * returns the index of the next non-whitespace, non-comment token.
  16116. * returns -1 if no meaningful token is found.
  16117. */
  16118. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  16119. if (startPosition === void 0) {
  16120. startPosition = this.position + 1;
  16121. }
  16122. var searchPosition = startPosition;
  16123. while (searchPosition < this.tokens.length) {
  16124. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  16125. searchPosition++;
  16126. continue;
  16127. } else {
  16128. return searchPosition;
  16129. }
  16130. }
  16131. return -1;
  16132. };
  16133. _createClass(Parser, [{
  16134. key: "currToken",
  16135. get: function get() {
  16136. return this.tokens[this.position];
  16137. }
  16138. }, {
  16139. key: "nextToken",
  16140. get: function get() {
  16141. return this.tokens[this.position + 1];
  16142. }
  16143. }, {
  16144. key: "prevToken",
  16145. get: function get() {
  16146. return this.tokens[this.position - 1];
  16147. }
  16148. }]);
  16149. return Parser;
  16150. }();
  16151. exports["default"] = Parser;
  16152. module.exports = exports.default;
  16153. } (parser, parser.exports));
  16154. return parser.exports;
  16155. }
  16156. var hasRequiredProcessor;
  16157. function requireProcessor () {
  16158. if (hasRequiredProcessor) return processor.exports;
  16159. hasRequiredProcessor = 1;
  16160. (function (module, exports) {
  16161. exports.__esModule = true;
  16162. exports["default"] = void 0;
  16163. var _parser = _interopRequireDefault(/*@__PURE__*/ requireParser());
  16164. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  16165. var Processor = /*#__PURE__*/function () {
  16166. function Processor(func, options) {
  16167. this.func = func || function noop() {};
  16168. this.funcRes = null;
  16169. this.options = options;
  16170. }
  16171. var _proto = Processor.prototype;
  16172. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  16173. if (options === void 0) {
  16174. options = {};
  16175. }
  16176. var merged = Object.assign({}, this.options, options);
  16177. if (merged.updateSelector === false) {
  16178. return false;
  16179. } else {
  16180. return typeof rule !== "string";
  16181. }
  16182. };
  16183. _proto._isLossy = function _isLossy(options) {
  16184. if (options === void 0) {
  16185. options = {};
  16186. }
  16187. var merged = Object.assign({}, this.options, options);
  16188. if (merged.lossless === false) {
  16189. return true;
  16190. } else {
  16191. return false;
  16192. }
  16193. };
  16194. _proto._root = function _root(rule, options) {
  16195. if (options === void 0) {
  16196. options = {};
  16197. }
  16198. var parser = new _parser["default"](rule, this._parseOptions(options));
  16199. return parser.root;
  16200. };
  16201. _proto._parseOptions = function _parseOptions(options) {
  16202. return {
  16203. lossy: this._isLossy(options)
  16204. };
  16205. };
  16206. _proto._run = function _run(rule, options) {
  16207. var _this = this;
  16208. if (options === void 0) {
  16209. options = {};
  16210. }
  16211. return new Promise(function (resolve, reject) {
  16212. try {
  16213. var root = _this._root(rule, options);
  16214. Promise.resolve(_this.func(root)).then(function (transform) {
  16215. var string = undefined;
  16216. if (_this._shouldUpdateSelector(rule, options)) {
  16217. string = root.toString();
  16218. rule.selector = string;
  16219. }
  16220. return {
  16221. transform: transform,
  16222. root: root,
  16223. string: string
  16224. };
  16225. }).then(resolve, reject);
  16226. } catch (e) {
  16227. reject(e);
  16228. return;
  16229. }
  16230. });
  16231. };
  16232. _proto._runSync = function _runSync(rule, options) {
  16233. if (options === void 0) {
  16234. options = {};
  16235. }
  16236. var root = this._root(rule, options);
  16237. var transform = this.func(root);
  16238. if (transform && typeof transform.then === "function") {
  16239. throw new Error("Selector processor returned a promise to a synchronous call.");
  16240. }
  16241. var string = undefined;
  16242. if (options.updateSelector && typeof rule !== "string") {
  16243. string = root.toString();
  16244. rule.selector = string;
  16245. }
  16246. return {
  16247. transform: transform,
  16248. root: root,
  16249. string: string
  16250. };
  16251. }
  16252. /**
  16253. * Process rule into a selector AST.
  16254. *
  16255. * @param rule {postcss.Rule | string} The css selector to be processed
  16256. * @param options The options for processing
  16257. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  16258. */;
  16259. _proto.ast = function ast(rule, options) {
  16260. return this._run(rule, options).then(function (result) {
  16261. return result.root;
  16262. });
  16263. }
  16264. /**
  16265. * Process rule into a selector AST synchronously.
  16266. *
  16267. * @param rule {postcss.Rule | string} The css selector to be processed
  16268. * @param options The options for processing
  16269. * @returns {parser.Root} The AST of the selector after processing it.
  16270. */;
  16271. _proto.astSync = function astSync(rule, options) {
  16272. return this._runSync(rule, options).root;
  16273. }
  16274. /**
  16275. * Process a selector into a transformed value asynchronously
  16276. *
  16277. * @param rule {postcss.Rule | string} The css selector to be processed
  16278. * @param options The options for processing
  16279. * @returns {Promise<any>} The value returned by the processor.
  16280. */;
  16281. _proto.transform = function transform(rule, options) {
  16282. return this._run(rule, options).then(function (result) {
  16283. return result.transform;
  16284. });
  16285. }
  16286. /**
  16287. * Process a selector into a transformed value synchronously.
  16288. *
  16289. * @param rule {postcss.Rule | string} The css selector to be processed
  16290. * @param options The options for processing
  16291. * @returns {any} The value returned by the processor.
  16292. */;
  16293. _proto.transformSync = function transformSync(rule, options) {
  16294. return this._runSync(rule, options).transform;
  16295. }
  16296. /**
  16297. * Process a selector into a new selector string asynchronously.
  16298. *
  16299. * @param rule {postcss.Rule | string} The css selector to be processed
  16300. * @param options The options for processing
  16301. * @returns {string} the selector after processing.
  16302. */;
  16303. _proto.process = function process(rule, options) {
  16304. return this._run(rule, options).then(function (result) {
  16305. return result.string || result.root.toString();
  16306. });
  16307. }
  16308. /**
  16309. * Process a selector into a new selector string synchronously.
  16310. *
  16311. * @param rule {postcss.Rule | string} The css selector to be processed
  16312. * @param options The options for processing
  16313. * @returns {string} the selector after processing.
  16314. */;
  16315. _proto.processSync = function processSync(rule, options) {
  16316. var result = this._runSync(rule, options);
  16317. return result.string || result.root.toString();
  16318. };
  16319. return Processor;
  16320. }();
  16321. exports["default"] = Processor;
  16322. module.exports = exports.default;
  16323. } (processor, processor.exports));
  16324. return processor.exports;
  16325. }
  16326. var selectors = {};
  16327. var constructors = {};
  16328. var hasRequiredConstructors;
  16329. function requireConstructors () {
  16330. if (hasRequiredConstructors) return constructors;
  16331. hasRequiredConstructors = 1;
  16332. constructors.__esModule = true;
  16333. 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;
  16334. var _attribute = _interopRequireDefault(/*@__PURE__*/ requireAttribute());
  16335. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName());
  16336. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator());
  16337. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment());
  16338. var _id = _interopRequireDefault(/*@__PURE__*/ requireId());
  16339. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting());
  16340. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo());
  16341. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot());
  16342. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector());
  16343. var _string = _interopRequireDefault(/*@__PURE__*/ requireString());
  16344. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag());
  16345. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal());
  16346. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  16347. var attribute = function attribute(opts) {
  16348. return new _attribute["default"](opts);
  16349. };
  16350. constructors.attribute = attribute;
  16351. var className = function className(opts) {
  16352. return new _className["default"](opts);
  16353. };
  16354. constructors.className = className;
  16355. var combinator = function combinator(opts) {
  16356. return new _combinator["default"](opts);
  16357. };
  16358. constructors.combinator = combinator;
  16359. var comment = function comment(opts) {
  16360. return new _comment["default"](opts);
  16361. };
  16362. constructors.comment = comment;
  16363. var id = function id(opts) {
  16364. return new _id["default"](opts);
  16365. };
  16366. constructors.id = id;
  16367. var nesting = function nesting(opts) {
  16368. return new _nesting["default"](opts);
  16369. };
  16370. constructors.nesting = nesting;
  16371. var pseudo = function pseudo(opts) {
  16372. return new _pseudo["default"](opts);
  16373. };
  16374. constructors.pseudo = pseudo;
  16375. var root = function root(opts) {
  16376. return new _root["default"](opts);
  16377. };
  16378. constructors.root = root;
  16379. var selector = function selector(opts) {
  16380. return new _selector["default"](opts);
  16381. };
  16382. constructors.selector = selector;
  16383. var string = function string(opts) {
  16384. return new _string["default"](opts);
  16385. };
  16386. constructors.string = string;
  16387. var tag = function tag(opts) {
  16388. return new _tag["default"](opts);
  16389. };
  16390. constructors.tag = tag;
  16391. var universal = function universal(opts) {
  16392. return new _universal["default"](opts);
  16393. };
  16394. constructors.universal = universal;
  16395. return constructors;
  16396. }
  16397. var guards = {};
  16398. var hasRequiredGuards;
  16399. function requireGuards () {
  16400. if (hasRequiredGuards) return guards;
  16401. hasRequiredGuards = 1;
  16402. guards.__esModule = true;
  16403. guards.isComment = guards.isCombinator = guards.isClassName = guards.isAttribute = void 0;
  16404. guards.isContainer = isContainer;
  16405. guards.isIdentifier = void 0;
  16406. guards.isNamespace = isNamespace;
  16407. guards.isNesting = void 0;
  16408. guards.isNode = isNode;
  16409. guards.isPseudo = void 0;
  16410. guards.isPseudoClass = isPseudoClass;
  16411. guards.isPseudoElement = isPseudoElement;
  16412. guards.isUniversal = guards.isTag = guards.isString = guards.isSelector = guards.isRoot = void 0;
  16413. var _types = /*@__PURE__*/ requireTypes();
  16414. var _IS_TYPE;
  16415. var IS_TYPE = (_IS_TYPE = {}, _IS_TYPE[_types.ATTRIBUTE] = true, _IS_TYPE[_types.CLASS] = true, _IS_TYPE[_types.COMBINATOR] = true, _IS_TYPE[_types.COMMENT] = true, _IS_TYPE[_types.ID] = true, _IS_TYPE[_types.NESTING] = true, _IS_TYPE[_types.PSEUDO] = true, _IS_TYPE[_types.ROOT] = true, _IS_TYPE[_types.SELECTOR] = true, _IS_TYPE[_types.STRING] = true, _IS_TYPE[_types.TAG] = true, _IS_TYPE[_types.UNIVERSAL] = true, _IS_TYPE);
  16416. function isNode(node) {
  16417. return typeof node === "object" && IS_TYPE[node.type];
  16418. }
  16419. function isNodeType(type, node) {
  16420. return isNode(node) && node.type === type;
  16421. }
  16422. var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  16423. guards.isAttribute = isAttribute;
  16424. var isClassName = isNodeType.bind(null, _types.CLASS);
  16425. guards.isClassName = isClassName;
  16426. var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  16427. guards.isCombinator = isCombinator;
  16428. var isComment = isNodeType.bind(null, _types.COMMENT);
  16429. guards.isComment = isComment;
  16430. var isIdentifier = isNodeType.bind(null, _types.ID);
  16431. guards.isIdentifier = isIdentifier;
  16432. var isNesting = isNodeType.bind(null, _types.NESTING);
  16433. guards.isNesting = isNesting;
  16434. var isPseudo = isNodeType.bind(null, _types.PSEUDO);
  16435. guards.isPseudo = isPseudo;
  16436. var isRoot = isNodeType.bind(null, _types.ROOT);
  16437. guards.isRoot = isRoot;
  16438. var isSelector = isNodeType.bind(null, _types.SELECTOR);
  16439. guards.isSelector = isSelector;
  16440. var isString = isNodeType.bind(null, _types.STRING);
  16441. guards.isString = isString;
  16442. var isTag = isNodeType.bind(null, _types.TAG);
  16443. guards.isTag = isTag;
  16444. var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  16445. guards.isUniversal = isUniversal;
  16446. function isPseudoElement(node) {
  16447. return isPseudo(node) && node.value && (node.value.startsWith("::") || node.value.toLowerCase() === ":before" || node.value.toLowerCase() === ":after" || node.value.toLowerCase() === ":first-letter" || node.value.toLowerCase() === ":first-line");
  16448. }
  16449. function isPseudoClass(node) {
  16450. return isPseudo(node) && !isPseudoElement(node);
  16451. }
  16452. function isContainer(node) {
  16453. return !!(isNode(node) && node.walk);
  16454. }
  16455. function isNamespace(node) {
  16456. return isAttribute(node) || isTag(node);
  16457. }
  16458. return guards;
  16459. }
  16460. var hasRequiredSelectors;
  16461. function requireSelectors () {
  16462. if (hasRequiredSelectors) return selectors;
  16463. hasRequiredSelectors = 1;
  16464. (function (exports) {
  16465. exports.__esModule = true;
  16466. var _types = /*@__PURE__*/ requireTypes();
  16467. Object.keys(_types).forEach(function (key) {
  16468. if (key === "default" || key === "__esModule") return;
  16469. if (key in exports && exports[key] === _types[key]) return;
  16470. exports[key] = _types[key];
  16471. });
  16472. var _constructors = /*@__PURE__*/ requireConstructors();
  16473. Object.keys(_constructors).forEach(function (key) {
  16474. if (key === "default" || key === "__esModule") return;
  16475. if (key in exports && exports[key] === _constructors[key]) return;
  16476. exports[key] = _constructors[key];
  16477. });
  16478. var _guards = /*@__PURE__*/ requireGuards();
  16479. Object.keys(_guards).forEach(function (key) {
  16480. if (key === "default" || key === "__esModule") return;
  16481. if (key in exports && exports[key] === _guards[key]) return;
  16482. exports[key] = _guards[key];
  16483. });
  16484. } (selectors));
  16485. return selectors;
  16486. }
  16487. var hasRequiredDist;
  16488. function requireDist () {
  16489. if (hasRequiredDist) return dist.exports;
  16490. hasRequiredDist = 1;
  16491. (function (module, exports) {
  16492. exports.__esModule = true;
  16493. exports["default"] = void 0;
  16494. var _processor = _interopRequireDefault(/*@__PURE__*/ requireProcessor());
  16495. var selectors = _interopRequireWildcard(/*@__PURE__*/ requireSelectors());
  16496. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  16497. function _interopRequireWildcard(obj, nodeInterop) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  16498. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  16499. var parser = function parser(processor) {
  16500. return new _processor["default"](processor);
  16501. };
  16502. Object.assign(parser, selectors);
  16503. delete parser.__esModule;
  16504. var _default = parser;
  16505. exports["default"] = _default;
  16506. module.exports = exports.default;
  16507. } (dist, dist.exports));
  16508. return dist.exports;
  16509. }
  16510. var parse;
  16511. var hasRequiredParse;
  16512. function requireParse () {
  16513. if (hasRequiredParse) return parse;
  16514. hasRequiredParse = 1;
  16515. var openParentheses = "(".charCodeAt(0);
  16516. var closeParentheses = ")".charCodeAt(0);
  16517. var singleQuote = "'".charCodeAt(0);
  16518. var doubleQuote = '"'.charCodeAt(0);
  16519. var backslash = "\\".charCodeAt(0);
  16520. var slash = "/".charCodeAt(0);
  16521. var comma = ",".charCodeAt(0);
  16522. var colon = ":".charCodeAt(0);
  16523. var star = "*".charCodeAt(0);
  16524. var uLower = "u".charCodeAt(0);
  16525. var uUpper = "U".charCodeAt(0);
  16526. var plus = "+".charCodeAt(0);
  16527. var isUnicodeRange = /^[a-f0-9?-]+$/i;
  16528. parse = function(input) {
  16529. var tokens = [];
  16530. var value = input;
  16531. var next,
  16532. quote,
  16533. prev,
  16534. token,
  16535. escape,
  16536. escapePos,
  16537. whitespacePos,
  16538. parenthesesOpenPos;
  16539. var pos = 0;
  16540. var code = value.charCodeAt(pos);
  16541. var max = value.length;
  16542. var stack = [{ nodes: tokens }];
  16543. var balanced = 0;
  16544. var parent;
  16545. var name = "";
  16546. var before = "";
  16547. var after = "";
  16548. while (pos < max) {
  16549. // Whitespaces
  16550. if (code <= 32) {
  16551. next = pos;
  16552. do {
  16553. next += 1;
  16554. code = value.charCodeAt(next);
  16555. } while (code <= 32);
  16556. token = value.slice(pos, next);
  16557. prev = tokens[tokens.length - 1];
  16558. if (code === closeParentheses && balanced) {
  16559. after = token;
  16560. } else if (prev && prev.type === "div") {
  16561. prev.after = token;
  16562. prev.sourceEndIndex += token.length;
  16563. } else if (
  16564. code === comma ||
  16565. code === colon ||
  16566. (code === slash &&
  16567. value.charCodeAt(next + 1) !== star &&
  16568. (!parent ||
  16569. (parent && parent.type === "function" && parent.value !== "calc")))
  16570. ) {
  16571. before = token;
  16572. } else {
  16573. tokens.push({
  16574. type: "space",
  16575. sourceIndex: pos,
  16576. sourceEndIndex: next,
  16577. value: token
  16578. });
  16579. }
  16580. pos = next;
  16581. // Quotes
  16582. } else if (code === singleQuote || code === doubleQuote) {
  16583. next = pos;
  16584. quote = code === singleQuote ? "'" : '"';
  16585. token = {
  16586. type: "string",
  16587. sourceIndex: pos,
  16588. quote: quote
  16589. };
  16590. do {
  16591. escape = false;
  16592. next = value.indexOf(quote, next + 1);
  16593. if (~next) {
  16594. escapePos = next;
  16595. while (value.charCodeAt(escapePos - 1) === backslash) {
  16596. escapePos -= 1;
  16597. escape = !escape;
  16598. }
  16599. } else {
  16600. value += quote;
  16601. next = value.length - 1;
  16602. token.unclosed = true;
  16603. }
  16604. } while (escape);
  16605. token.value = value.slice(pos + 1, next);
  16606. token.sourceEndIndex = token.unclosed ? next : next + 1;
  16607. tokens.push(token);
  16608. pos = next + 1;
  16609. code = value.charCodeAt(pos);
  16610. // Comments
  16611. } else if (code === slash && value.charCodeAt(pos + 1) === star) {
  16612. next = value.indexOf("*/", pos);
  16613. token = {
  16614. type: "comment",
  16615. sourceIndex: pos,
  16616. sourceEndIndex: next + 2
  16617. };
  16618. if (next === -1) {
  16619. token.unclosed = true;
  16620. next = value.length;
  16621. token.sourceEndIndex = next;
  16622. }
  16623. token.value = value.slice(pos + 2, next);
  16624. tokens.push(token);
  16625. pos = next + 2;
  16626. code = value.charCodeAt(pos);
  16627. // Operation within calc
  16628. } else if (
  16629. (code === slash || code === star) &&
  16630. parent &&
  16631. parent.type === "function" &&
  16632. parent.value === "calc"
  16633. ) {
  16634. token = value[pos];
  16635. tokens.push({
  16636. type: "word",
  16637. sourceIndex: pos - before.length,
  16638. sourceEndIndex: pos + token.length,
  16639. value: token
  16640. });
  16641. pos += 1;
  16642. code = value.charCodeAt(pos);
  16643. // Dividers
  16644. } else if (code === slash || code === comma || code === colon) {
  16645. token = value[pos];
  16646. tokens.push({
  16647. type: "div",
  16648. sourceIndex: pos - before.length,
  16649. sourceEndIndex: pos + token.length,
  16650. value: token,
  16651. before: before,
  16652. after: ""
  16653. });
  16654. before = "";
  16655. pos += 1;
  16656. code = value.charCodeAt(pos);
  16657. // Open parentheses
  16658. } else if (openParentheses === code) {
  16659. // Whitespaces after open parentheses
  16660. next = pos;
  16661. do {
  16662. next += 1;
  16663. code = value.charCodeAt(next);
  16664. } while (code <= 32);
  16665. parenthesesOpenPos = pos;
  16666. token = {
  16667. type: "function",
  16668. sourceIndex: pos - name.length,
  16669. value: name,
  16670. before: value.slice(parenthesesOpenPos + 1, next)
  16671. };
  16672. pos = next;
  16673. if (name === "url" && code !== singleQuote && code !== doubleQuote) {
  16674. next -= 1;
  16675. do {
  16676. escape = false;
  16677. next = value.indexOf(")", next + 1);
  16678. if (~next) {
  16679. escapePos = next;
  16680. while (value.charCodeAt(escapePos - 1) === backslash) {
  16681. escapePos -= 1;
  16682. escape = !escape;
  16683. }
  16684. } else {
  16685. value += ")";
  16686. next = value.length - 1;
  16687. token.unclosed = true;
  16688. }
  16689. } while (escape);
  16690. // Whitespaces before closed
  16691. whitespacePos = next;
  16692. do {
  16693. whitespacePos -= 1;
  16694. code = value.charCodeAt(whitespacePos);
  16695. } while (code <= 32);
  16696. if (parenthesesOpenPos < whitespacePos) {
  16697. if (pos !== whitespacePos + 1) {
  16698. token.nodes = [
  16699. {
  16700. type: "word",
  16701. sourceIndex: pos,
  16702. sourceEndIndex: whitespacePos + 1,
  16703. value: value.slice(pos, whitespacePos + 1)
  16704. }
  16705. ];
  16706. } else {
  16707. token.nodes = [];
  16708. }
  16709. if (token.unclosed && whitespacePos + 1 !== next) {
  16710. token.after = "";
  16711. token.nodes.push({
  16712. type: "space",
  16713. sourceIndex: whitespacePos + 1,
  16714. sourceEndIndex: next,
  16715. value: value.slice(whitespacePos + 1, next)
  16716. });
  16717. } else {
  16718. token.after = value.slice(whitespacePos + 1, next);
  16719. token.sourceEndIndex = next;
  16720. }
  16721. } else {
  16722. token.after = "";
  16723. token.nodes = [];
  16724. }
  16725. pos = next + 1;
  16726. token.sourceEndIndex = token.unclosed ? next : pos;
  16727. code = value.charCodeAt(pos);
  16728. tokens.push(token);
  16729. } else {
  16730. balanced += 1;
  16731. token.after = "";
  16732. token.sourceEndIndex = pos + 1;
  16733. tokens.push(token);
  16734. stack.push(token);
  16735. tokens = token.nodes = [];
  16736. parent = token;
  16737. }
  16738. name = "";
  16739. // Close parentheses
  16740. } else if (closeParentheses === code && balanced) {
  16741. pos += 1;
  16742. code = value.charCodeAt(pos);
  16743. parent.after = after;
  16744. parent.sourceEndIndex += after.length;
  16745. after = "";
  16746. balanced -= 1;
  16747. stack[stack.length - 1].sourceEndIndex = pos;
  16748. stack.pop();
  16749. parent = stack[balanced];
  16750. tokens = parent.nodes;
  16751. // Words
  16752. } else {
  16753. next = pos;
  16754. do {
  16755. if (code === backslash) {
  16756. next += 1;
  16757. }
  16758. next += 1;
  16759. code = value.charCodeAt(next);
  16760. } while (
  16761. next < max &&
  16762. !(
  16763. code <= 32 ||
  16764. code === singleQuote ||
  16765. code === doubleQuote ||
  16766. code === comma ||
  16767. code === colon ||
  16768. code === slash ||
  16769. code === openParentheses ||
  16770. (code === star &&
  16771. parent &&
  16772. parent.type === "function" &&
  16773. parent.value === "calc") ||
  16774. (code === slash &&
  16775. parent.type === "function" &&
  16776. parent.value === "calc") ||
  16777. (code === closeParentheses && balanced)
  16778. )
  16779. );
  16780. token = value.slice(pos, next);
  16781. if (openParentheses === code) {
  16782. name = token;
  16783. } else if (
  16784. (uLower === token.charCodeAt(0) || uUpper === token.charCodeAt(0)) &&
  16785. plus === token.charCodeAt(1) &&
  16786. isUnicodeRange.test(token.slice(2))
  16787. ) {
  16788. tokens.push({
  16789. type: "unicode-range",
  16790. sourceIndex: pos,
  16791. sourceEndIndex: next,
  16792. value: token
  16793. });
  16794. } else {
  16795. tokens.push({
  16796. type: "word",
  16797. sourceIndex: pos,
  16798. sourceEndIndex: next,
  16799. value: token
  16800. });
  16801. }
  16802. pos = next;
  16803. }
  16804. }
  16805. for (pos = stack.length - 1; pos; pos -= 1) {
  16806. stack[pos].unclosed = true;
  16807. stack[pos].sourceEndIndex = value.length;
  16808. }
  16809. return stack[0].nodes;
  16810. };
  16811. return parse;
  16812. }
  16813. var walk$1;
  16814. var hasRequiredWalk;
  16815. function requireWalk () {
  16816. if (hasRequiredWalk) return walk$1;
  16817. hasRequiredWalk = 1;
  16818. walk$1 = function walk(nodes, cb, bubble) {
  16819. var i, max, node, result;
  16820. for (i = 0, max = nodes.length; i < max; i += 1) {
  16821. node = nodes[i];
  16822. if (!bubble) {
  16823. result = cb(node, i, nodes);
  16824. }
  16825. if (
  16826. result !== false &&
  16827. node.type === "function" &&
  16828. Array.isArray(node.nodes)
  16829. ) {
  16830. walk(node.nodes, cb, bubble);
  16831. }
  16832. if (bubble) {
  16833. cb(node, i, nodes);
  16834. }
  16835. }
  16836. };
  16837. return walk$1;
  16838. }
  16839. var stringify_1;
  16840. var hasRequiredStringify;
  16841. function requireStringify () {
  16842. if (hasRequiredStringify) return stringify_1;
  16843. hasRequiredStringify = 1;
  16844. function stringifyNode(node, custom) {
  16845. var type = node.type;
  16846. var value = node.value;
  16847. var buf;
  16848. var customResult;
  16849. if (custom && (customResult = custom(node)) !== undefined) {
  16850. return customResult;
  16851. } else if (type === "word" || type === "space") {
  16852. return value;
  16853. } else if (type === "string") {
  16854. buf = node.quote || "";
  16855. return buf + value + (node.unclosed ? "" : buf);
  16856. } else if (type === "comment") {
  16857. return "/*" + value + (node.unclosed ? "" : "*/");
  16858. } else if (type === "div") {
  16859. return (node.before || "") + value + (node.after || "");
  16860. } else if (Array.isArray(node.nodes)) {
  16861. buf = stringify(node.nodes, custom);
  16862. if (type !== "function") {
  16863. return buf;
  16864. }
  16865. return (
  16866. value +
  16867. "(" +
  16868. (node.before || "") +
  16869. buf +
  16870. (node.after || "") +
  16871. (node.unclosed ? "" : ")")
  16872. );
  16873. }
  16874. return value;
  16875. }
  16876. function stringify(nodes, custom) {
  16877. var result, i;
  16878. if (Array.isArray(nodes)) {
  16879. result = "";
  16880. for (i = nodes.length - 1; ~i; i -= 1) {
  16881. result = stringifyNode(nodes[i], custom) + result;
  16882. }
  16883. return result;
  16884. }
  16885. return stringifyNode(nodes, custom);
  16886. }
  16887. stringify_1 = stringify;
  16888. return stringify_1;
  16889. }
  16890. var unit;
  16891. var hasRequiredUnit;
  16892. function requireUnit () {
  16893. if (hasRequiredUnit) return unit;
  16894. hasRequiredUnit = 1;
  16895. var minus = "-".charCodeAt(0);
  16896. var plus = "+".charCodeAt(0);
  16897. var dot = ".".charCodeAt(0);
  16898. var exp = "e".charCodeAt(0);
  16899. var EXP = "E".charCodeAt(0);
  16900. // Check if three code points would start a number
  16901. // https://www.w3.org/TR/css-syntax-3/#starts-with-a-number
  16902. function likeNumber(value) {
  16903. var code = value.charCodeAt(0);
  16904. var nextCode;
  16905. if (code === plus || code === minus) {
  16906. nextCode = value.charCodeAt(1);
  16907. if (nextCode >= 48 && nextCode <= 57) {
  16908. return true;
  16909. }
  16910. var nextNextCode = value.charCodeAt(2);
  16911. if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) {
  16912. return true;
  16913. }
  16914. return false;
  16915. }
  16916. if (code === dot) {
  16917. nextCode = value.charCodeAt(1);
  16918. if (nextCode >= 48 && nextCode <= 57) {
  16919. return true;
  16920. }
  16921. return false;
  16922. }
  16923. if (code >= 48 && code <= 57) {
  16924. return true;
  16925. }
  16926. return false;
  16927. }
  16928. // Consume a number
  16929. // https://www.w3.org/TR/css-syntax-3/#consume-number
  16930. unit = function(value) {
  16931. var pos = 0;
  16932. var length = value.length;
  16933. var code;
  16934. var nextCode;
  16935. var nextNextCode;
  16936. if (length === 0 || !likeNumber(value)) {
  16937. return false;
  16938. }
  16939. code = value.charCodeAt(pos);
  16940. if (code === plus || code === minus) {
  16941. pos++;
  16942. }
  16943. while (pos < length) {
  16944. code = value.charCodeAt(pos);
  16945. if (code < 48 || code > 57) {
  16946. break;
  16947. }
  16948. pos += 1;
  16949. }
  16950. code = value.charCodeAt(pos);
  16951. nextCode = value.charCodeAt(pos + 1);
  16952. if (code === dot && nextCode >= 48 && nextCode <= 57) {
  16953. pos += 2;
  16954. while (pos < length) {
  16955. code = value.charCodeAt(pos);
  16956. if (code < 48 || code > 57) {
  16957. break;
  16958. }
  16959. pos += 1;
  16960. }
  16961. }
  16962. code = value.charCodeAt(pos);
  16963. nextCode = value.charCodeAt(pos + 1);
  16964. nextNextCode = value.charCodeAt(pos + 2);
  16965. if (
  16966. (code === exp || code === EXP) &&
  16967. ((nextCode >= 48 && nextCode <= 57) ||
  16968. ((nextCode === plus || nextCode === minus) &&
  16969. nextNextCode >= 48 &&
  16970. nextNextCode <= 57))
  16971. ) {
  16972. pos += nextCode === plus || nextCode === minus ? 3 : 2;
  16973. while (pos < length) {
  16974. code = value.charCodeAt(pos);
  16975. if (code < 48 || code > 57) {
  16976. break;
  16977. }
  16978. pos += 1;
  16979. }
  16980. }
  16981. return {
  16982. number: value.slice(0, pos),
  16983. unit: value.slice(pos)
  16984. };
  16985. };
  16986. return unit;
  16987. }
  16988. var lib;
  16989. var hasRequiredLib;
  16990. function requireLib () {
  16991. if (hasRequiredLib) return lib;
  16992. hasRequiredLib = 1;
  16993. var parse = /*@__PURE__*/ requireParse();
  16994. var walk = /*@__PURE__*/ requireWalk();
  16995. var stringify = /*@__PURE__*/ requireStringify();
  16996. function ValueParser(value) {
  16997. if (this instanceof ValueParser) {
  16998. this.nodes = parse(value);
  16999. return this;
  17000. }
  17001. return new ValueParser(value);
  17002. }
  17003. ValueParser.prototype.toString = function() {
  17004. return Array.isArray(this.nodes) ? stringify(this.nodes) : "";
  17005. };
  17006. ValueParser.prototype.walk = function(cb, bubble) {
  17007. walk(this.nodes, cb, bubble);
  17008. return this;
  17009. };
  17010. ValueParser.unit = /*@__PURE__*/ requireUnit();
  17011. ValueParser.walk = walk;
  17012. ValueParser.stringify = stringify;
  17013. lib = ValueParser;
  17014. return lib;
  17015. }
  17016. var hasRequiredSrc$2;
  17017. function requireSrc$2 () {
  17018. if (hasRequiredSrc$2) return src$2.exports;
  17019. hasRequiredSrc$2 = 1;
  17020. const selectorParser = /*@__PURE__*/ requireDist();
  17021. const valueParser = /*@__PURE__*/ requireLib();
  17022. const { extractICSS } = /*@__PURE__*/ requireSrc$4();
  17023. const isSpacing = (node) => node.type === "combinator" && node.value === " ";
  17024. function normalizeNodeArray(nodes) {
  17025. const array = [];
  17026. nodes.forEach((x) => {
  17027. if (Array.isArray(x)) {
  17028. normalizeNodeArray(x).forEach((item) => {
  17029. array.push(item);
  17030. });
  17031. } else if (x) {
  17032. array.push(x);
  17033. }
  17034. });
  17035. if (array.length > 0 && isSpacing(array[array.length - 1])) {
  17036. array.pop();
  17037. }
  17038. return array;
  17039. }
  17040. function localizeNode(rule, mode, localAliasMap) {
  17041. const transform = (node, context) => {
  17042. if (context.ignoreNextSpacing && !isSpacing(node)) {
  17043. throw new Error("Missing whitespace after " + context.ignoreNextSpacing);
  17044. }
  17045. if (context.enforceNoSpacing && isSpacing(node)) {
  17046. throw new Error("Missing whitespace before " + context.enforceNoSpacing);
  17047. }
  17048. let newNodes;
  17049. switch (node.type) {
  17050. case "root": {
  17051. let resultingGlobal;
  17052. context.hasPureGlobals = false;
  17053. newNodes = node.nodes.map((n) => {
  17054. const nContext = {
  17055. global: context.global,
  17056. lastWasSpacing: true,
  17057. hasLocals: false,
  17058. explicit: false,
  17059. };
  17060. n = transform(n, nContext);
  17061. if (typeof resultingGlobal === "undefined") {
  17062. resultingGlobal = nContext.global;
  17063. } else if (resultingGlobal !== nContext.global) {
  17064. throw new Error(
  17065. 'Inconsistent rule global/local result in rule "' +
  17066. node +
  17067. '" (multiple selectors must result in the same mode for the rule)'
  17068. );
  17069. }
  17070. if (!nContext.hasLocals) {
  17071. context.hasPureGlobals = true;
  17072. }
  17073. return n;
  17074. });
  17075. context.global = resultingGlobal;
  17076. node.nodes = normalizeNodeArray(newNodes);
  17077. break;
  17078. }
  17079. case "selector": {
  17080. newNodes = node.map((childNode) => transform(childNode, context));
  17081. node = node.clone();
  17082. node.nodes = normalizeNodeArray(newNodes);
  17083. break;
  17084. }
  17085. case "combinator": {
  17086. if (isSpacing(node)) {
  17087. if (context.ignoreNextSpacing) {
  17088. context.ignoreNextSpacing = false;
  17089. context.lastWasSpacing = false;
  17090. context.enforceNoSpacing = false;
  17091. return null;
  17092. }
  17093. context.lastWasSpacing = true;
  17094. return node;
  17095. }
  17096. break;
  17097. }
  17098. case "pseudo": {
  17099. let childContext;
  17100. const isNested = !!node.length;
  17101. const isScoped = node.value === ":local" || node.value === ":global";
  17102. const isImportExport =
  17103. node.value === ":import" || node.value === ":export";
  17104. if (isImportExport) {
  17105. context.hasLocals = true;
  17106. // :local(.foo)
  17107. } else if (isNested) {
  17108. if (isScoped) {
  17109. if (node.nodes.length === 0) {
  17110. throw new Error(`${node.value}() can't be empty`);
  17111. }
  17112. if (context.inside) {
  17113. throw new Error(
  17114. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  17115. );
  17116. }
  17117. childContext = {
  17118. global: node.value === ":global",
  17119. inside: node.value,
  17120. hasLocals: false,
  17121. explicit: true,
  17122. };
  17123. newNodes = node
  17124. .map((childNode) => transform(childNode, childContext))
  17125. .reduce((acc, next) => acc.concat(next.nodes), []);
  17126. if (newNodes.length) {
  17127. const { before, after } = node.spaces;
  17128. const first = newNodes[0];
  17129. const last = newNodes[newNodes.length - 1];
  17130. first.spaces = { before, after: first.spaces.after };
  17131. last.spaces = { before: last.spaces.before, after };
  17132. }
  17133. node = newNodes;
  17134. break;
  17135. } else {
  17136. childContext = {
  17137. global: context.global,
  17138. inside: context.inside,
  17139. lastWasSpacing: true,
  17140. hasLocals: false,
  17141. explicit: context.explicit,
  17142. };
  17143. newNodes = node.map((childNode) => {
  17144. const newContext = {
  17145. ...childContext,
  17146. enforceNoSpacing: false,
  17147. };
  17148. const result = transform(childNode, newContext);
  17149. childContext.global = newContext.global;
  17150. childContext.hasLocals = newContext.hasLocals;
  17151. return result;
  17152. });
  17153. node = node.clone();
  17154. node.nodes = normalizeNodeArray(newNodes);
  17155. if (childContext.hasLocals) {
  17156. context.hasLocals = true;
  17157. }
  17158. }
  17159. break;
  17160. //:local .foo .bar
  17161. } else if (isScoped) {
  17162. if (context.inside) {
  17163. throw new Error(
  17164. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  17165. );
  17166. }
  17167. const addBackSpacing = !!node.spaces.before;
  17168. context.ignoreNextSpacing = context.lastWasSpacing
  17169. ? node.value
  17170. : false;
  17171. context.enforceNoSpacing = context.lastWasSpacing
  17172. ? false
  17173. : node.value;
  17174. context.global = node.value === ":global";
  17175. context.explicit = true;
  17176. // because this node has spacing that is lost when we remove it
  17177. // we make up for it by adding an extra combinator in since adding
  17178. // spacing on the parent selector doesn't work
  17179. return addBackSpacing
  17180. ? selectorParser.combinator({ value: " " })
  17181. : null;
  17182. }
  17183. break;
  17184. }
  17185. case "id":
  17186. case "class": {
  17187. if (!node.value) {
  17188. throw new Error("Invalid class or id selector syntax");
  17189. }
  17190. if (context.global) {
  17191. break;
  17192. }
  17193. const isImportedValue = localAliasMap.has(node.value);
  17194. const isImportedWithExplicitScope = isImportedValue && context.explicit;
  17195. if (!isImportedValue || isImportedWithExplicitScope) {
  17196. const innerNode = node.clone();
  17197. innerNode.spaces = { before: "", after: "" };
  17198. node = selectorParser.pseudo({
  17199. value: ":local",
  17200. nodes: [innerNode],
  17201. spaces: node.spaces,
  17202. });
  17203. context.hasLocals = true;
  17204. }
  17205. break;
  17206. }
  17207. case "nesting": {
  17208. if (node.value === "&") {
  17209. context.hasLocals = true;
  17210. }
  17211. }
  17212. }
  17213. context.lastWasSpacing = false;
  17214. context.ignoreNextSpacing = false;
  17215. context.enforceNoSpacing = false;
  17216. return node;
  17217. };
  17218. const rootContext = {
  17219. global: mode === "global",
  17220. hasPureGlobals: false,
  17221. };
  17222. rootContext.selector = selectorParser((root) => {
  17223. transform(root, rootContext);
  17224. }).processSync(rule, { updateSelector: false, lossless: true });
  17225. return rootContext;
  17226. }
  17227. function localizeDeclNode(node, context) {
  17228. switch (node.type) {
  17229. case "word":
  17230. if (context.localizeNextItem) {
  17231. if (!context.localAliasMap.has(node.value)) {
  17232. node.value = ":local(" + node.value + ")";
  17233. context.localizeNextItem = false;
  17234. }
  17235. }
  17236. break;
  17237. case "function":
  17238. if (
  17239. context.options &&
  17240. context.options.rewriteUrl &&
  17241. node.value.toLowerCase() === "url"
  17242. ) {
  17243. node.nodes.map((nestedNode) => {
  17244. if (nestedNode.type !== "string" && nestedNode.type !== "word") {
  17245. return;
  17246. }
  17247. let newUrl = context.options.rewriteUrl(
  17248. context.global,
  17249. nestedNode.value
  17250. );
  17251. switch (nestedNode.type) {
  17252. case "string":
  17253. if (nestedNode.quote === "'") {
  17254. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/'/g, "\\'");
  17255. }
  17256. if (nestedNode.quote === '"') {
  17257. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/"/g, '\\"');
  17258. }
  17259. break;
  17260. case "word":
  17261. newUrl = newUrl.replace(/("|'|\)|\\)/g, "\\$1");
  17262. break;
  17263. }
  17264. nestedNode.value = newUrl;
  17265. });
  17266. }
  17267. break;
  17268. }
  17269. return node;
  17270. }
  17271. // `none` is special value, other is global values
  17272. const specialKeywords = [
  17273. "none",
  17274. "inherit",
  17275. "initial",
  17276. "revert",
  17277. "revert-layer",
  17278. "unset",
  17279. ];
  17280. function localizeDeclarationValues(localize, declaration, context) {
  17281. const valueNodes = valueParser(declaration.value);
  17282. valueNodes.walk((node, index, nodes) => {
  17283. if (
  17284. node.type === "function" &&
  17285. (node.value.toLowerCase() === "var" || node.value.toLowerCase() === "env")
  17286. ) {
  17287. return false;
  17288. }
  17289. if (
  17290. node.type === "word" &&
  17291. specialKeywords.includes(node.value.toLowerCase())
  17292. ) {
  17293. return;
  17294. }
  17295. const subContext = {
  17296. options: context.options,
  17297. global: context.global,
  17298. localizeNextItem: localize && !context.global,
  17299. localAliasMap: context.localAliasMap,
  17300. };
  17301. nodes[index] = localizeDeclNode(node, subContext);
  17302. });
  17303. declaration.value = valueNodes.toString();
  17304. }
  17305. function localizeDeclaration(declaration, context) {
  17306. const isAnimation = /animation$/i.test(declaration.prop);
  17307. if (isAnimation) {
  17308. // letter
  17309. // An uppercase letter or a lowercase letter.
  17310. //
  17311. // ident-start code point
  17312. // A letter, a non-ASCII code point, or U+005F LOW LINE (_).
  17313. //
  17314. // ident code point
  17315. // An ident-start code point, a digit, or U+002D HYPHEN-MINUS (-).
  17316. // We don't validate `hex digits`, because we don't need it, it is work of linters.
  17317. const validIdent =
  17318. /^-?([a-z\u0080-\uFFFF_]|(\\[^\r\n\f])|-(?![0-9]))((\\[^\r\n\f])|[a-z\u0080-\uFFFF_0-9-])*$/i;
  17319. /*
  17320. The spec defines some keywords that you can use to describe properties such as the timing
  17321. function. These are still valid animation names, so as long as there is a property that accepts
  17322. a keyword, it is given priority. Only when all the properties that can take a keyword are
  17323. exhausted can the animation name be set to the keyword. I.e.
  17324. animation: infinite infinite;
  17325. The animation will repeat an infinite number of times from the first argument, and will have an
  17326. animation name of infinite from the second.
  17327. */
  17328. const animationKeywords = {
  17329. // animation-direction
  17330. $normal: 1,
  17331. $reverse: 1,
  17332. $alternate: 1,
  17333. "$alternate-reverse": 1,
  17334. // animation-fill-mode
  17335. $forwards: 1,
  17336. $backwards: 1,
  17337. $both: 1,
  17338. // animation-iteration-count
  17339. $infinite: 1,
  17340. // animation-play-state
  17341. $paused: 1,
  17342. $running: 1,
  17343. // animation-timing-function
  17344. $ease: 1,
  17345. "$ease-in": 1,
  17346. "$ease-out": 1,
  17347. "$ease-in-out": 1,
  17348. $linear: 1,
  17349. "$step-end": 1,
  17350. "$step-start": 1,
  17351. // Special
  17352. $none: Infinity, // No matter how many times you write none, it will never be an animation name
  17353. // Global values
  17354. $initial: Infinity,
  17355. $inherit: Infinity,
  17356. $unset: Infinity,
  17357. $revert: Infinity,
  17358. "$revert-layer": Infinity,
  17359. };
  17360. let parsedAnimationKeywords = {};
  17361. const valueNodes = valueParser(declaration.value).walk((node) => {
  17362. // If div-token appeared (represents as comma ','), a possibility of an animation-keywords should be reflesh.
  17363. if (node.type === "div") {
  17364. parsedAnimationKeywords = {};
  17365. return;
  17366. }
  17367. // Do not handle nested functions
  17368. else if (node.type === "function") {
  17369. return false;
  17370. }
  17371. // Ignore all except word
  17372. else if (node.type !== "word") {
  17373. return;
  17374. }
  17375. const value = node.type === "word" ? node.value.toLowerCase() : null;
  17376. let shouldParseAnimationName = false;
  17377. if (value && validIdent.test(value)) {
  17378. if ("$" + value in animationKeywords) {
  17379. parsedAnimationKeywords["$" + value] =
  17380. "$" + value in parsedAnimationKeywords
  17381. ? parsedAnimationKeywords["$" + value] + 1
  17382. : 0;
  17383. shouldParseAnimationName =
  17384. parsedAnimationKeywords["$" + value] >=
  17385. animationKeywords["$" + value];
  17386. } else {
  17387. shouldParseAnimationName = true;
  17388. }
  17389. }
  17390. const subContext = {
  17391. options: context.options,
  17392. global: context.global,
  17393. localizeNextItem: shouldParseAnimationName && !context.global,
  17394. localAliasMap: context.localAliasMap,
  17395. };
  17396. return localizeDeclNode(node, subContext);
  17397. });
  17398. declaration.value = valueNodes.toString();
  17399. return;
  17400. }
  17401. const isAnimationName = /animation(-name)?$/i.test(declaration.prop);
  17402. if (isAnimationName) {
  17403. return localizeDeclarationValues(true, declaration, context);
  17404. }
  17405. const hasUrl = /url\(/i.test(declaration.value);
  17406. if (hasUrl) {
  17407. return localizeDeclarationValues(false, declaration, context);
  17408. }
  17409. }
  17410. src$2.exports = (options = {}) => {
  17411. if (
  17412. options &&
  17413. options.mode &&
  17414. options.mode !== "global" &&
  17415. options.mode !== "local" &&
  17416. options.mode !== "pure"
  17417. ) {
  17418. throw new Error(
  17419. 'options.mode must be either "global", "local" or "pure" (default "local")'
  17420. );
  17421. }
  17422. const pureMode = options && options.mode === "pure";
  17423. const globalMode = options && options.mode === "global";
  17424. return {
  17425. postcssPlugin: "postcss-modules-local-by-default",
  17426. prepare() {
  17427. const localAliasMap = new Map();
  17428. return {
  17429. Once(root) {
  17430. const { icssImports } = extractICSS(root, false);
  17431. Object.keys(icssImports).forEach((key) => {
  17432. Object.keys(icssImports[key]).forEach((prop) => {
  17433. localAliasMap.set(prop, icssImports[key][prop]);
  17434. });
  17435. });
  17436. root.walkAtRules((atRule) => {
  17437. if (/keyframes$/i.test(atRule.name)) {
  17438. const globalMatch = /^\s*:global\s*\((.+)\)\s*$/.exec(
  17439. atRule.params
  17440. );
  17441. const localMatch = /^\s*:local\s*\((.+)\)\s*$/.exec(
  17442. atRule.params
  17443. );
  17444. let globalKeyframes = globalMode;
  17445. if (globalMatch) {
  17446. if (pureMode) {
  17447. throw atRule.error(
  17448. "@keyframes :global(...) is not allowed in pure mode"
  17449. );
  17450. }
  17451. atRule.params = globalMatch[1];
  17452. globalKeyframes = true;
  17453. } else if (localMatch) {
  17454. atRule.params = localMatch[0];
  17455. globalKeyframes = false;
  17456. } else if (
  17457. atRule.params &&
  17458. !globalMode &&
  17459. !localAliasMap.has(atRule.params)
  17460. ) {
  17461. atRule.params = ":local(" + atRule.params + ")";
  17462. }
  17463. atRule.walkDecls((declaration) => {
  17464. localizeDeclaration(declaration, {
  17465. localAliasMap,
  17466. options: options,
  17467. global: globalKeyframes,
  17468. });
  17469. });
  17470. } else if (/scope$/i.test(atRule.name)) {
  17471. if (atRule.params) {
  17472. atRule.params = atRule.params
  17473. .split("to")
  17474. .map((item) => {
  17475. const selector = item.trim().slice(1, -1).trim();
  17476. const context = localizeNode(
  17477. selector,
  17478. options.mode,
  17479. localAliasMap
  17480. );
  17481. context.options = options;
  17482. context.localAliasMap = localAliasMap;
  17483. if (pureMode && context.hasPureGlobals) {
  17484. throw atRule.error(
  17485. 'Selector in at-rule"' +
  17486. selector +
  17487. '" is not pure ' +
  17488. "(pure selectors must contain at least one local class or id)"
  17489. );
  17490. }
  17491. return `(${context.selector})`;
  17492. })
  17493. .join(" to ");
  17494. }
  17495. atRule.nodes.forEach((declaration) => {
  17496. if (declaration.type === "decl") {
  17497. localizeDeclaration(declaration, {
  17498. localAliasMap,
  17499. options: options,
  17500. global: globalMode,
  17501. });
  17502. }
  17503. });
  17504. } else if (atRule.nodes) {
  17505. atRule.nodes.forEach((declaration) => {
  17506. if (declaration.type === "decl") {
  17507. localizeDeclaration(declaration, {
  17508. localAliasMap,
  17509. options: options,
  17510. global: globalMode,
  17511. });
  17512. }
  17513. });
  17514. }
  17515. });
  17516. root.walkRules((rule) => {
  17517. if (
  17518. rule.parent &&
  17519. rule.parent.type === "atrule" &&
  17520. /keyframes$/i.test(rule.parent.name)
  17521. ) {
  17522. // ignore keyframe rules
  17523. return;
  17524. }
  17525. const context = localizeNode(rule, options.mode, localAliasMap);
  17526. context.options = options;
  17527. context.localAliasMap = localAliasMap;
  17528. if (pureMode && context.hasPureGlobals) {
  17529. throw rule.error(
  17530. 'Selector "' +
  17531. rule.selector +
  17532. '" is not pure ' +
  17533. "(pure selectors must contain at least one local class or id)"
  17534. );
  17535. }
  17536. rule.selector = context.selector;
  17537. // Less-syntax mixins parse as rules with no nodes
  17538. if (rule.nodes) {
  17539. rule.nodes.forEach((declaration) =>
  17540. localizeDeclaration(declaration, context)
  17541. );
  17542. }
  17543. });
  17544. },
  17545. };
  17546. },
  17547. };
  17548. };
  17549. src$2.exports.postcss = true;
  17550. return src$2.exports;
  17551. }
  17552. var src$1;
  17553. var hasRequiredSrc$1;
  17554. function requireSrc$1 () {
  17555. if (hasRequiredSrc$1) return src$1;
  17556. hasRequiredSrc$1 = 1;
  17557. const selectorParser = /*@__PURE__*/ requireDist();
  17558. const hasOwnProperty = Object.prototype.hasOwnProperty;
  17559. function isNestedRule(rule) {
  17560. if (!rule.parent || rule.parent.type === "root") {
  17561. return false;
  17562. }
  17563. if (rule.parent.type === "rule") {
  17564. return true;
  17565. }
  17566. return isNestedRule(rule.parent);
  17567. }
  17568. function getSingleLocalNamesForComposes(root, rule) {
  17569. if (isNestedRule(rule)) {
  17570. throw new Error(`composition is not allowed in nested rule \n\n${rule}`);
  17571. }
  17572. return root.nodes.map((node) => {
  17573. if (node.type !== "selector" || node.nodes.length !== 1) {
  17574. throw new Error(
  17575. `composition is only allowed when selector is single :local class name not in "${root}"`
  17576. );
  17577. }
  17578. node = node.nodes[0];
  17579. if (
  17580. node.type !== "pseudo" ||
  17581. node.value !== ":local" ||
  17582. node.nodes.length !== 1
  17583. ) {
  17584. throw new Error(
  17585. 'composition is only allowed when selector is single :local class name not in "' +
  17586. root +
  17587. '", "' +
  17588. node +
  17589. '" is weird'
  17590. );
  17591. }
  17592. node = node.first;
  17593. if (node.type !== "selector" || node.length !== 1) {
  17594. throw new Error(
  17595. 'composition is only allowed when selector is single :local class name not in "' +
  17596. root +
  17597. '", "' +
  17598. node +
  17599. '" is weird'
  17600. );
  17601. }
  17602. node = node.first;
  17603. if (node.type !== "class") {
  17604. // 'id' is not possible, because you can't compose ids
  17605. throw new Error(
  17606. 'composition is only allowed when selector is single :local class name not in "' +
  17607. root +
  17608. '", "' +
  17609. node +
  17610. '" is weird'
  17611. );
  17612. }
  17613. return node.value;
  17614. });
  17615. }
  17616. const whitespace = "[\\x20\\t\\r\\n\\f]";
  17617. const unescapeRegExp = new RegExp(
  17618. "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)",
  17619. "ig"
  17620. );
  17621. function unescape(str) {
  17622. return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => {
  17623. const high = "0x" + escaped - 0x10000;
  17624. // NaN means non-codepoint
  17625. // Workaround erroneous numeric interpretation of +"0x"
  17626. return high !== high || escapedWhitespace
  17627. ? escaped
  17628. : high < 0
  17629. ? // BMP codepoint
  17630. String.fromCharCode(high + 0x10000)
  17631. : // Supplemental Plane codepoint (surrogate pair)
  17632. String.fromCharCode((high >> 10) | 0xd800, (high & 0x3ff) | 0xdc00);
  17633. });
  17634. }
  17635. const plugin = (options = {}) => {
  17636. const generateScopedName =
  17637. (options && options.generateScopedName) || plugin.generateScopedName;
  17638. const generateExportEntry =
  17639. (options && options.generateExportEntry) || plugin.generateExportEntry;
  17640. const exportGlobals = options && options.exportGlobals;
  17641. return {
  17642. postcssPlugin: "postcss-modules-scope",
  17643. Once(root, { rule }) {
  17644. const exports = Object.create(null);
  17645. function exportScopedName(name, rawName, node) {
  17646. const scopedName = generateScopedName(
  17647. rawName ? rawName : name,
  17648. root.source.input.from,
  17649. root.source.input.css,
  17650. node
  17651. );
  17652. const exportEntry = generateExportEntry(
  17653. rawName ? rawName : name,
  17654. scopedName,
  17655. root.source.input.from,
  17656. root.source.input.css,
  17657. node
  17658. );
  17659. const { key, value } = exportEntry;
  17660. exports[key] = exports[key] || [];
  17661. if (exports[key].indexOf(value) < 0) {
  17662. exports[key].push(value);
  17663. }
  17664. return scopedName;
  17665. }
  17666. function localizeNode(node) {
  17667. switch (node.type) {
  17668. case "selector":
  17669. node.nodes = node.map((item) => localizeNode(item));
  17670. return node;
  17671. case "class":
  17672. return selectorParser.className({
  17673. value: exportScopedName(
  17674. node.value,
  17675. node.raws && node.raws.value ? node.raws.value : null,
  17676. node
  17677. ),
  17678. });
  17679. case "id": {
  17680. return selectorParser.id({
  17681. value: exportScopedName(
  17682. node.value,
  17683. node.raws && node.raws.value ? node.raws.value : null,
  17684. node
  17685. ),
  17686. });
  17687. }
  17688. case "attribute": {
  17689. if (node.attribute === "class" && node.operator === "=") {
  17690. return selectorParser.attribute({
  17691. attribute: node.attribute,
  17692. operator: node.operator,
  17693. quoteMark: "'",
  17694. value: exportScopedName(node.value, null, null),
  17695. });
  17696. }
  17697. }
  17698. }
  17699. throw new Error(
  17700. `${node.type} ("${node}") is not allowed in a :local block`
  17701. );
  17702. }
  17703. function traverseNode(node) {
  17704. switch (node.type) {
  17705. case "pseudo":
  17706. if (node.value === ":local") {
  17707. if (node.nodes.length !== 1) {
  17708. throw new Error('Unexpected comma (",") in :local block');
  17709. }
  17710. const selector = localizeNode(node.first);
  17711. // move the spaces that were around the pseudo selector to the first
  17712. // non-container node
  17713. selector.first.spaces = node.spaces;
  17714. const nextNode = node.next();
  17715. if (
  17716. nextNode &&
  17717. nextNode.type === "combinator" &&
  17718. nextNode.value === " " &&
  17719. /\\[A-F0-9]{1,6}$/.test(selector.last.value)
  17720. ) {
  17721. selector.last.spaces.after = " ";
  17722. }
  17723. node.replaceWith(selector);
  17724. return;
  17725. }
  17726. /* falls through */
  17727. case "root":
  17728. case "selector": {
  17729. node.each((item) => traverseNode(item));
  17730. break;
  17731. }
  17732. case "id":
  17733. case "class":
  17734. if (exportGlobals) {
  17735. exports[node.value] = [node.value];
  17736. }
  17737. break;
  17738. }
  17739. return node;
  17740. }
  17741. // Find any :import and remember imported names
  17742. const importedNames = {};
  17743. root.walkRules(/^:import\(.+\)$/, (rule) => {
  17744. rule.walkDecls((decl) => {
  17745. importedNames[decl.prop] = true;
  17746. });
  17747. });
  17748. // Find any :local selectors
  17749. root.walkRules((rule) => {
  17750. let parsedSelector = selectorParser().astSync(rule);
  17751. rule.selector = traverseNode(parsedSelector.clone()).toString();
  17752. rule.walkDecls(/^(composes|compose-with)$/i, (decl) => {
  17753. const localNames = getSingleLocalNamesForComposes(
  17754. parsedSelector,
  17755. decl.parent
  17756. );
  17757. const multiple = decl.value.split(",");
  17758. multiple.forEach((value) => {
  17759. const classes = value.trim().split(/\s+/);
  17760. classes.forEach((className) => {
  17761. const global = /^global\(([^)]+)\)$/.exec(className);
  17762. if (global) {
  17763. localNames.forEach((exportedName) => {
  17764. exports[exportedName].push(global[1]);
  17765. });
  17766. } else if (hasOwnProperty.call(importedNames, className)) {
  17767. localNames.forEach((exportedName) => {
  17768. exports[exportedName].push(className);
  17769. });
  17770. } else if (hasOwnProperty.call(exports, className)) {
  17771. localNames.forEach((exportedName) => {
  17772. exports[className].forEach((item) => {
  17773. exports[exportedName].push(item);
  17774. });
  17775. });
  17776. } else {
  17777. throw decl.error(
  17778. `referenced class name "${className}" in ${decl.prop} not found`
  17779. );
  17780. }
  17781. });
  17782. });
  17783. decl.remove();
  17784. });
  17785. // Find any :local values
  17786. rule.walkDecls((decl) => {
  17787. if (!/:local\s*\((.+?)\)/.test(decl.value)) {
  17788. return;
  17789. }
  17790. let tokens = decl.value.split(/(,|'[^']*'|"[^"]*")/);
  17791. tokens = tokens.map((token, idx) => {
  17792. if (idx === 0 || tokens[idx - 1] === ",") {
  17793. let result = token;
  17794. const localMatch = /:local\s*\((.+?)\)/.exec(token);
  17795. if (localMatch) {
  17796. const input = localMatch.input;
  17797. const matchPattern = localMatch[0];
  17798. const matchVal = localMatch[1];
  17799. const newVal = exportScopedName(matchVal);
  17800. result = input.replace(matchPattern, newVal);
  17801. } else {
  17802. return token;
  17803. }
  17804. return result;
  17805. } else {
  17806. return token;
  17807. }
  17808. });
  17809. decl.value = tokens.join("");
  17810. });
  17811. });
  17812. // Find any :local keyframes
  17813. root.walkAtRules(/keyframes$/i, (atRule) => {
  17814. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(atRule.params);
  17815. if (!localMatch) {
  17816. return;
  17817. }
  17818. atRule.params = exportScopedName(localMatch[1]);
  17819. });
  17820. root.walkAtRules(/scope$/i, (atRule) => {
  17821. if (atRule.params) {
  17822. atRule.params = atRule.params
  17823. .split("to")
  17824. .map((item) => {
  17825. const selector = item.trim().slice(1, -1).trim();
  17826. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(selector);
  17827. if (!localMatch) {
  17828. return `(${selector})`;
  17829. }
  17830. let parsedSelector = selectorParser().astSync(selector);
  17831. return `(${traverseNode(parsedSelector).toString()})`;
  17832. })
  17833. .join(" to ");
  17834. }
  17835. });
  17836. // If we found any :locals, insert an :export rule
  17837. const exportedNames = Object.keys(exports);
  17838. if (exportedNames.length > 0) {
  17839. const exportRule = rule({ selector: ":export" });
  17840. exportedNames.forEach((exportedName) =>
  17841. exportRule.append({
  17842. prop: exportedName,
  17843. value: exports[exportedName].join(" "),
  17844. raws: { before: "\n " },
  17845. })
  17846. );
  17847. root.append(exportRule);
  17848. }
  17849. },
  17850. };
  17851. };
  17852. plugin.postcss = true;
  17853. plugin.generateScopedName = function (name, path) {
  17854. const sanitisedPath = path
  17855. .replace(/\.[^./\\]+$/, "")
  17856. .replace(/[\W_]+/g, "_")
  17857. .replace(/^_|_$/g, "");
  17858. return `_${sanitisedPath}__${name}`.trim();
  17859. };
  17860. plugin.generateExportEntry = function (name, scopedName) {
  17861. return {
  17862. key: unescape(name),
  17863. value: unescape(scopedName),
  17864. };
  17865. };
  17866. src$1 = plugin;
  17867. return src$1;
  17868. }
  17869. var stringHash;
  17870. var hasRequiredStringHash;
  17871. function requireStringHash () {
  17872. if (hasRequiredStringHash) return stringHash;
  17873. hasRequiredStringHash = 1;
  17874. function hash(str) {
  17875. var hash = 5381,
  17876. i = str.length;
  17877. while(i) {
  17878. hash = (hash * 33) ^ str.charCodeAt(--i);
  17879. }
  17880. /* JavaScript does bitwise operations (like XOR, above) on 32-bit signed
  17881. * integers. Since we want the results to be always positive, convert the
  17882. * signed int to an unsigned by doing an unsigned bitshift. */
  17883. return hash >>> 0;
  17884. }
  17885. stringHash = hash;
  17886. return stringHash;
  17887. }
  17888. var src = {exports: {}};
  17889. var hasRequiredSrc;
  17890. function requireSrc () {
  17891. if (hasRequiredSrc) return src.exports;
  17892. hasRequiredSrc = 1;
  17893. const ICSSUtils = /*@__PURE__*/ requireSrc$4();
  17894. const matchImports = /^(.+?|\([\s\S]+?\))\s+from\s+("[^"]*"|'[^']*'|[\w-]+)$/;
  17895. const matchValueDefinition = /(?:\s+|^)([\w-]+):?(.*?)$/;
  17896. const matchImport = /^([\w-]+)(?:\s+as\s+([\w-]+))?/;
  17897. src.exports = (options) => {
  17898. let importIndex = 0;
  17899. const createImportedName =
  17900. (options && options.createImportedName) ||
  17901. ((importName /*, path*/) =>
  17902. `i__const_${importName.replace(/\W/g, "_")}_${importIndex++}`);
  17903. return {
  17904. postcssPlugin: "postcss-modules-values",
  17905. prepare(result) {
  17906. const importAliases = [];
  17907. const definitions = {};
  17908. return {
  17909. Once(root, postcss) {
  17910. root.walkAtRules(/value/i, (atRule) => {
  17911. const matches = atRule.params.match(matchImports);
  17912. if (matches) {
  17913. let [, /*match*/ aliases, path] = matches;
  17914. // We can use constants for path names
  17915. if (definitions[path]) {
  17916. path = definitions[path];
  17917. }
  17918. const imports = aliases
  17919. .replace(/^\(\s*([\s\S]+)\s*\)$/, "$1")
  17920. .split(/\s*,\s*/)
  17921. .map((alias) => {
  17922. const tokens = matchImport.exec(alias);
  17923. if (tokens) {
  17924. const [, /*match*/ theirName, myName = theirName] = tokens;
  17925. const importedName = createImportedName(myName);
  17926. definitions[myName] = importedName;
  17927. return { theirName, importedName };
  17928. } else {
  17929. throw new Error(`@import statement "${alias}" is invalid!`);
  17930. }
  17931. });
  17932. importAliases.push({ path, imports });
  17933. atRule.remove();
  17934. return;
  17935. }
  17936. if (atRule.params.indexOf("@value") !== -1) {
  17937. result.warn("Invalid value definition: " + atRule.params);
  17938. }
  17939. let [, key, value] = `${atRule.params}${atRule.raws.between}`.match(
  17940. matchValueDefinition
  17941. );
  17942. const normalizedValue = value.replace(/\/\*((?!\*\/).*?)\*\//g, "");
  17943. if (normalizedValue.length === 0) {
  17944. result.warn("Invalid value definition: " + atRule.params);
  17945. atRule.remove();
  17946. return;
  17947. }
  17948. let isOnlySpace = /^\s+$/.test(normalizedValue);
  17949. if (!isOnlySpace) {
  17950. value = value.trim();
  17951. }
  17952. // Add to the definitions, knowing that values can refer to each other
  17953. definitions[key] = ICSSUtils.replaceValueSymbols(
  17954. value,
  17955. definitions
  17956. );
  17957. atRule.remove();
  17958. });
  17959. /* If we have no definitions, don't continue */
  17960. if (!Object.keys(definitions).length) {
  17961. return;
  17962. }
  17963. /* Perform replacements */
  17964. ICSSUtils.replaceSymbols(root, definitions);
  17965. /* We want to export anything defined by now, but don't add it to the CSS yet or it well get picked up by the replacement stuff */
  17966. const exportDeclarations = Object.keys(definitions).map((key) =>
  17967. postcss.decl({
  17968. value: definitions[key],
  17969. prop: key,
  17970. raws: { before: "\n " },
  17971. })
  17972. );
  17973. /* Add export rules if any */
  17974. if (exportDeclarations.length > 0) {
  17975. const exportRule = postcss.rule({
  17976. selector: ":export",
  17977. raws: { after: "\n" },
  17978. });
  17979. exportRule.append(exportDeclarations);
  17980. root.prepend(exportRule);
  17981. }
  17982. /* Add import rules */
  17983. importAliases.reverse().forEach(({ path, imports }) => {
  17984. const importRule = postcss.rule({
  17985. selector: `:import(${path})`,
  17986. raws: { after: "\n" },
  17987. });
  17988. imports.forEach(({ theirName, importedName }) => {
  17989. importRule.append({
  17990. value: theirName,
  17991. prop: importedName,
  17992. raws: { before: "\n " },
  17993. });
  17994. });
  17995. root.prepend(importRule);
  17996. });
  17997. },
  17998. };
  17999. },
  18000. };
  18001. };
  18002. src.exports.postcss = true;
  18003. return src.exports;
  18004. }
  18005. var hasRequiredScoping;
  18006. function requireScoping () {
  18007. if (hasRequiredScoping) return scoping;
  18008. hasRequiredScoping = 1;
  18009. Object.defineProperty(scoping, "__esModule", {
  18010. value: true
  18011. });
  18012. scoping.behaviours = void 0;
  18013. scoping.getDefaultPlugins = getDefaultPlugins;
  18014. scoping.getDefaultScopeBehaviour = getDefaultScopeBehaviour;
  18015. scoping.getScopedNameGenerator = getScopedNameGenerator;
  18016. var _postcssModulesExtractImports = _interopRequireDefault(/*@__PURE__*/ requireSrc$3());
  18017. var _genericNames = _interopRequireDefault(/*@__PURE__*/ requireGenericNames());
  18018. var _postcssModulesLocalByDefault = _interopRequireDefault(/*@__PURE__*/ requireSrc$2());
  18019. var _postcssModulesScope = _interopRequireDefault(/*@__PURE__*/ requireSrc$1());
  18020. var _stringHash = _interopRequireDefault(/*@__PURE__*/ requireStringHash());
  18021. var _postcssModulesValues = _interopRequireDefault(/*@__PURE__*/ requireSrc());
  18022. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  18023. const behaviours = {
  18024. LOCAL: "local",
  18025. GLOBAL: "global"
  18026. };
  18027. scoping.behaviours = behaviours;
  18028. function getDefaultPlugins({
  18029. behaviour,
  18030. generateScopedName,
  18031. exportGlobals
  18032. }) {
  18033. const scope = (0, _postcssModulesScope.default)({
  18034. generateScopedName,
  18035. exportGlobals
  18036. });
  18037. const plugins = {
  18038. [behaviours.LOCAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  18039. mode: "local"
  18040. }), _postcssModulesExtractImports.default, scope],
  18041. [behaviours.GLOBAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  18042. mode: "global"
  18043. }), _postcssModulesExtractImports.default, scope]
  18044. };
  18045. return plugins[behaviour];
  18046. }
  18047. function isValidBehaviour(behaviour) {
  18048. return Object.keys(behaviours).map(key => behaviours[key]).indexOf(behaviour) > -1;
  18049. }
  18050. function getDefaultScopeBehaviour(scopeBehaviour) {
  18051. return scopeBehaviour && isValidBehaviour(scopeBehaviour) ? scopeBehaviour : behaviours.LOCAL;
  18052. }
  18053. function generateScopedNameDefault(name, filename, css) {
  18054. const i = css.indexOf(`.${name}`);
  18055. const lineNumber = css.substr(0, i).split(/[\r\n]/).length;
  18056. const hash = (0, _stringHash.default)(css).toString(36).substr(0, 5);
  18057. return `_${name}_${hash}_${lineNumber}`;
  18058. }
  18059. function getScopedNameGenerator(generateScopedName, hashPrefix) {
  18060. const scopedNameGenerator = generateScopedName || generateScopedNameDefault;
  18061. if (typeof scopedNameGenerator === "function") {
  18062. return scopedNameGenerator;
  18063. }
  18064. return (0, _genericNames.default)(scopedNameGenerator, {
  18065. context: process.cwd(),
  18066. hashPrefix: hashPrefix
  18067. });
  18068. }
  18069. return scoping;
  18070. }
  18071. var hasRequiredPluginFactory;
  18072. function requirePluginFactory () {
  18073. if (hasRequiredPluginFactory) return pluginFactory;
  18074. hasRequiredPluginFactory = 1;
  18075. Object.defineProperty(pluginFactory, "__esModule", {
  18076. value: true
  18077. });
  18078. pluginFactory.makePlugin = makePlugin;
  18079. var _postcss = _interopRequireDefault(require$$0$1);
  18080. var _unquote = _interopRequireDefault(/*@__PURE__*/ requireUnquote());
  18081. var _Parser = _interopRequireDefault(/*@__PURE__*/ requireParser$1());
  18082. var _saveJSON = _interopRequireDefault(/*@__PURE__*/ requireSaveJSON());
  18083. var _localsConvention = /*@__PURE__*/ requireLocalsConvention();
  18084. var _FileSystemLoader = _interopRequireDefault(/*@__PURE__*/ requireFileSystemLoader());
  18085. var _scoping = /*@__PURE__*/ requireScoping();
  18086. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  18087. const PLUGIN_NAME = "postcss-modules";
  18088. function isGlobalModule(globalModules, inputFile) {
  18089. return globalModules.some(regex => inputFile.match(regex));
  18090. }
  18091. function getDefaultPluginsList(opts, inputFile) {
  18092. const globalModulesList = opts.globalModulePaths || null;
  18093. const exportGlobals = opts.exportGlobals || false;
  18094. const defaultBehaviour = (0, _scoping.getDefaultScopeBehaviour)(opts.scopeBehaviour);
  18095. const generateScopedName = (0, _scoping.getScopedNameGenerator)(opts.generateScopedName, opts.hashPrefix);
  18096. if (globalModulesList && isGlobalModule(globalModulesList, inputFile)) {
  18097. return (0, _scoping.getDefaultPlugins)({
  18098. behaviour: _scoping.behaviours.GLOBAL,
  18099. generateScopedName,
  18100. exportGlobals
  18101. });
  18102. }
  18103. return (0, _scoping.getDefaultPlugins)({
  18104. behaviour: defaultBehaviour,
  18105. generateScopedName,
  18106. exportGlobals
  18107. });
  18108. }
  18109. function getLoader(opts, plugins) {
  18110. const root = typeof opts.root === "undefined" ? "/" : opts.root;
  18111. return typeof opts.Loader === "function" ? new opts.Loader(root, plugins, opts.resolve) : new _FileSystemLoader.default(root, plugins, opts.resolve);
  18112. }
  18113. function isOurPlugin(plugin) {
  18114. return plugin.postcssPlugin === PLUGIN_NAME;
  18115. }
  18116. function makePlugin(opts) {
  18117. return {
  18118. postcssPlugin: PLUGIN_NAME,
  18119. async OnceExit(css, {
  18120. result
  18121. }) {
  18122. const getJSON = opts.getJSON || _saveJSON.default;
  18123. const inputFile = css.source.input.file;
  18124. const pluginList = getDefaultPluginsList(opts, inputFile);
  18125. const resultPluginIndex = result.processor.plugins.findIndex(plugin => isOurPlugin(plugin));
  18126. if (resultPluginIndex === -1) {
  18127. throw new Error("Plugin missing from options.");
  18128. }
  18129. const earlierPlugins = result.processor.plugins.slice(0, resultPluginIndex);
  18130. const loaderPlugins = [...earlierPlugins, ...pluginList];
  18131. const loader = getLoader(opts, loaderPlugins);
  18132. const fetcher = async (file, relativeTo, depTrace) => {
  18133. const unquoteFile = (0, _unquote.default)(file);
  18134. return loader.fetch.call(loader, unquoteFile, relativeTo, depTrace);
  18135. };
  18136. const parser = new _Parser.default(fetcher);
  18137. await (0, _postcss.default)([...pluginList, parser.plugin()]).process(css, {
  18138. from: inputFile
  18139. });
  18140. const out = loader.finalSource;
  18141. if (out) css.prepend(out);
  18142. if (opts.localsConvention) {
  18143. const reducer = (0, _localsConvention.makeLocalsConventionReducer)(opts.localsConvention, inputFile);
  18144. parser.exportTokens = Object.entries(parser.exportTokens).reduce(reducer, {});
  18145. }
  18146. result.messages.push({
  18147. type: "export",
  18148. plugin: "postcss-modules",
  18149. exportTokens: parser.exportTokens
  18150. }); // getJSON may return a promise
  18151. return getJSON(css.source.input.file, parser.exportTokens, result.opts.to);
  18152. }
  18153. };
  18154. }
  18155. return pluginFactory;
  18156. }
  18157. var hasRequiredBuild;
  18158. function requireBuild () {
  18159. if (hasRequiredBuild) return build.exports;
  18160. hasRequiredBuild = 1;
  18161. var _fs = require$$0;
  18162. var _fs2 = /*@__PURE__*/ requireFs();
  18163. var _pluginFactory = /*@__PURE__*/ requirePluginFactory();
  18164. (0, _fs2.setFileSystem)({
  18165. readFile: _fs.readFile,
  18166. writeFile: _fs.writeFile
  18167. });
  18168. build.exports = (opts = {}) => (0, _pluginFactory.makePlugin)(opts);
  18169. build.exports.postcss = true;
  18170. return build.exports;
  18171. }
  18172. var buildExports = /*@__PURE__*/ requireBuild();
  18173. var postcssModules = /*@__PURE__*/getDefaultExportFromCjs(buildExports);
  18174. function compileStyle(options) {
  18175. return doCompileStyle({
  18176. ...options,
  18177. isAsync: false
  18178. });
  18179. }
  18180. function compileStyleAsync(options) {
  18181. return doCompileStyle({
  18182. ...options,
  18183. isAsync: true
  18184. });
  18185. }
  18186. function doCompileStyle(options) {
  18187. const {
  18188. filename,
  18189. id,
  18190. scoped = false,
  18191. trim = true,
  18192. isProd = false,
  18193. modules = false,
  18194. modulesOptions = {},
  18195. preprocessLang,
  18196. postcssOptions,
  18197. postcssPlugins
  18198. } = options;
  18199. const preprocessor = preprocessLang && processors[preprocessLang];
  18200. const preProcessedSource = preprocessor && preprocess(options, preprocessor);
  18201. const map = preProcessedSource ? preProcessedSource.map : options.inMap || options.map;
  18202. const source = preProcessedSource ? preProcessedSource.code : options.source;
  18203. const shortId = id.replace(/^data-v-/, "");
  18204. const longId = `data-v-${shortId}`;
  18205. const plugins = (postcssPlugins || []).slice();
  18206. plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
  18207. if (trim) {
  18208. plugins.push(trimPlugin());
  18209. }
  18210. if (scoped) {
  18211. plugins.push(scopedPlugin(longId));
  18212. }
  18213. let cssModules;
  18214. if (modules) {
  18215. if (!options.isAsync) {
  18216. throw new Error(
  18217. "[@vue/compiler-sfc] `modules` option can only be used with compileStyleAsync()."
  18218. );
  18219. }
  18220. plugins.push(
  18221. postcssModules({
  18222. ...modulesOptions,
  18223. getJSON: (_cssFileName, json) => {
  18224. cssModules = json;
  18225. }
  18226. })
  18227. );
  18228. }
  18229. const postCSSOptions = {
  18230. ...postcssOptions,
  18231. to: filename,
  18232. from: filename
  18233. };
  18234. if (map) {
  18235. postCSSOptions.map = {
  18236. inline: false,
  18237. annotation: false,
  18238. prev: map
  18239. };
  18240. }
  18241. let result;
  18242. let code;
  18243. let outMap;
  18244. const dependencies = new Set(
  18245. preProcessedSource ? preProcessedSource.dependencies : []
  18246. );
  18247. dependencies.delete(filename);
  18248. const errors = [];
  18249. if (preProcessedSource && preProcessedSource.errors.length) {
  18250. errors.push(...preProcessedSource.errors);
  18251. }
  18252. const recordPlainCssDependencies = (messages) => {
  18253. messages.forEach((msg) => {
  18254. if (msg.type === "dependency") {
  18255. dependencies.add(msg.file);
  18256. }
  18257. });
  18258. return dependencies;
  18259. };
  18260. try {
  18261. result = require$$0$1(plugins).process(source, postCSSOptions);
  18262. if (options.isAsync) {
  18263. return result.then((result2) => ({
  18264. code: result2.css || "",
  18265. map: result2.map && result2.map.toJSON(),
  18266. errors,
  18267. modules: cssModules,
  18268. rawResult: result2,
  18269. dependencies: recordPlainCssDependencies(result2.messages)
  18270. })).catch((error) => ({
  18271. code: "",
  18272. map: void 0,
  18273. errors: [...errors, error],
  18274. rawResult: void 0,
  18275. dependencies
  18276. }));
  18277. }
  18278. recordPlainCssDependencies(result.messages);
  18279. code = result.css;
  18280. outMap = result.map;
  18281. } catch (e) {
  18282. errors.push(e);
  18283. }
  18284. return {
  18285. code: code || ``,
  18286. map: outMap && outMap.toJSON(),
  18287. errors,
  18288. rawResult: result,
  18289. dependencies
  18290. };
  18291. }
  18292. function preprocess(options, preprocessor) {
  18293. return preprocessor(
  18294. options.source,
  18295. options.inMap || options.map,
  18296. {
  18297. filename: options.filename,
  18298. ...options.preprocessOptions
  18299. },
  18300. options.preprocessCustomRequire
  18301. );
  18302. }
  18303. const UNKNOWN_TYPE = "Unknown";
  18304. function resolveObjectKey(node, computed) {
  18305. switch (node.type) {
  18306. case "StringLiteral":
  18307. case "NumericLiteral":
  18308. return String(node.value);
  18309. case "Identifier":
  18310. if (!computed) return node.name;
  18311. }
  18312. return void 0;
  18313. }
  18314. function concatStrings(strs) {
  18315. return strs.filter((s) => !!s).join(", ");
  18316. }
  18317. function isLiteralNode(node) {
  18318. return node.type.endsWith("Literal");
  18319. }
  18320. function isCallOf(node, test) {
  18321. return !!(node && test && node.type === "CallExpression" && node.callee.type === "Identifier" && (typeof test === "string" ? node.callee.name === test : test(node.callee.name)));
  18322. }
  18323. function toRuntimeTypeString(types) {
  18324. return types.length > 1 ? `[${types.join(", ")}]` : types[0];
  18325. }
  18326. function getImportedName(specifier) {
  18327. if (specifier.type === "ImportSpecifier")
  18328. return specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
  18329. else if (specifier.type === "ImportNamespaceSpecifier") return "*";
  18330. return "default";
  18331. }
  18332. function getId(node) {
  18333. return node.type === "Identifier" ? node.name : node.type === "StringLiteral" ? node.value : null;
  18334. }
  18335. function getStringLiteralKey(node) {
  18336. 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;
  18337. }
  18338. const identity = (str) => str;
  18339. const fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
  18340. const toLowerCase = (str) => str.toLowerCase();
  18341. function toFileNameLowerCase(x) {
  18342. return fileNameLowerCaseRegExp.test(x) ? x.replace(fileNameLowerCaseRegExp, toLowerCase) : x;
  18343. }
  18344. function createGetCanonicalFileName(useCaseSensitiveFileNames) {
  18345. return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
  18346. }
  18347. const normalize = (path$1.posix || path$1).normalize;
  18348. const windowsSlashRE = /\\/g;
  18349. function normalizePath(p) {
  18350. return normalize(p.replace(windowsSlashRE, "/"));
  18351. }
  18352. const joinPaths = (path$1.posix || path$1).join;
  18353. const propNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~\-]/;
  18354. function getEscapedPropName(key) {
  18355. return propNameEscapeSymbolsRE.test(key) ? JSON.stringify(key) : key;
  18356. }
  18357. const isJS = (...langs) => langs.some((lang) => lang === "js" || lang === "jsx");
  18358. const isTS = (...langs) => langs.some((lang) => lang === "ts" || lang === "tsx");
  18359. function analyzeScriptBindings(ast) {
  18360. for (const node of ast) {
  18361. if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "ObjectExpression") {
  18362. return analyzeBindingsFromOptions(node.declaration);
  18363. }
  18364. }
  18365. return {};
  18366. }
  18367. function analyzeBindingsFromOptions(node) {
  18368. const bindings = {};
  18369. Object.defineProperty(bindings, "__isScriptSetup", {
  18370. enumerable: false,
  18371. value: false
  18372. });
  18373. for (const property of node.properties) {
  18374. if (property.type === "ObjectProperty" && !property.computed && property.key.type === "Identifier") {
  18375. if (property.key.name === "props") {
  18376. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  18377. bindings[key] = "props";
  18378. }
  18379. } else if (property.key.name === "inject") {
  18380. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  18381. bindings[key] = "options";
  18382. }
  18383. } else if (property.value.type === "ObjectExpression" && (property.key.name === "computed" || property.key.name === "methods")) {
  18384. for (const key of getObjectExpressionKeys(property.value)) {
  18385. bindings[key] = "options";
  18386. }
  18387. }
  18388. } else if (property.type === "ObjectMethod" && property.key.type === "Identifier" && (property.key.name === "setup" || property.key.name === "data")) {
  18389. for (const bodyItem of property.body.body) {
  18390. if (bodyItem.type === "ReturnStatement" && bodyItem.argument && bodyItem.argument.type === "ObjectExpression") {
  18391. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  18392. bindings[key] = property.key.name === "setup" ? "setup-maybe-ref" : "data";
  18393. }
  18394. }
  18395. }
  18396. }
  18397. }
  18398. return bindings;
  18399. }
  18400. function getObjectExpressionKeys(node) {
  18401. const keys = [];
  18402. for (const prop of node.properties) {
  18403. if (prop.type === "SpreadElement") continue;
  18404. const key = resolveObjectKey(prop.key, prop.computed);
  18405. if (key) keys.push(String(key));
  18406. }
  18407. return keys;
  18408. }
  18409. function getArrayExpressionKeys(node) {
  18410. const keys = [];
  18411. for (const element of node.elements) {
  18412. if (element && element.type === "StringLiteral") {
  18413. keys.push(element.value);
  18414. }
  18415. }
  18416. return keys;
  18417. }
  18418. function getObjectOrArrayExpressionKeys(value) {
  18419. if (value.type === "ArrayExpression") {
  18420. return getArrayExpressionKeys(value);
  18421. }
  18422. if (value.type === "ObjectExpression") {
  18423. return getObjectExpressionKeys(value);
  18424. }
  18425. return [];
  18426. }
  18427. var _a$1, _b;
  18428. class ScriptCompileContext {
  18429. constructor(descriptor, options) {
  18430. this.descriptor = descriptor;
  18431. this.options = options;
  18432. this.isCE = false;
  18433. this.source = this.descriptor.source;
  18434. this.filename = this.descriptor.filename;
  18435. this.s = new MagicString(this.source);
  18436. this.startOffset = (_a$1 = this.descriptor.scriptSetup) == null ? void 0 : _a$1.loc.start.offset;
  18437. this.endOffset = (_b = this.descriptor.scriptSetup) == null ? void 0 : _b.loc.end.offset;
  18438. this.userImports = /* @__PURE__ */ Object.create(null);
  18439. // macros presence check
  18440. this.hasDefinePropsCall = false;
  18441. this.hasDefineEmitCall = false;
  18442. this.hasDefineExposeCall = false;
  18443. this.hasDefaultExportName = false;
  18444. this.hasDefaultExportRender = false;
  18445. this.hasDefineOptionsCall = false;
  18446. this.hasDefineSlotsCall = false;
  18447. this.hasDefineModelCall = false;
  18448. this.propsDestructuredBindings = /* @__PURE__ */ Object.create(null);
  18449. // defineModel
  18450. this.modelDecls = /* @__PURE__ */ Object.create(null);
  18451. // codegen
  18452. this.bindingMetadata = {};
  18453. this.helperImports = /* @__PURE__ */ new Set();
  18454. const { script, scriptSetup } = descriptor;
  18455. const scriptLang = script && script.lang;
  18456. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  18457. this.isJS = isJS(scriptLang, scriptSetupLang);
  18458. this.isTS = isTS(scriptLang, scriptSetupLang);
  18459. const customElement = options.customElement;
  18460. const filename = this.descriptor.filename;
  18461. if (customElement) {
  18462. this.isCE = typeof customElement === "boolean" ? customElement : customElement(filename);
  18463. }
  18464. const plugins = resolveParserPlugins(
  18465. scriptLang || scriptSetupLang,
  18466. options.babelParserPlugins
  18467. );
  18468. function parse(input, offset) {
  18469. try {
  18470. return parser$2.parse(input, {
  18471. plugins,
  18472. sourceType: "module"
  18473. }).program;
  18474. } catch (e) {
  18475. e.message = `[vue/compiler-sfc] ${e.message}
  18476. ${descriptor.filename}
  18477. ${shared.generateCodeFrame(
  18478. descriptor.source,
  18479. e.pos + offset,
  18480. e.pos + offset + 1
  18481. )}`;
  18482. throw e;
  18483. }
  18484. }
  18485. this.scriptAst = descriptor.script && parse(descriptor.script.content, descriptor.script.loc.start.offset);
  18486. this.scriptSetupAst = descriptor.scriptSetup && parse(descriptor.scriptSetup.content, this.startOffset);
  18487. }
  18488. helper(key) {
  18489. this.helperImports.add(key);
  18490. return `_${key}`;
  18491. }
  18492. getString(node, scriptSetup = true) {
  18493. const block = scriptSetup ? this.descriptor.scriptSetup : this.descriptor.script;
  18494. return block.content.slice(node.start, node.end);
  18495. }
  18496. warn(msg, node, scope) {
  18497. warn(generateError(msg, node, this, scope));
  18498. }
  18499. error(msg, node, scope) {
  18500. throw new Error(
  18501. `[@vue/compiler-sfc] ${generateError(msg, node, this, scope)}`
  18502. );
  18503. }
  18504. }
  18505. function generateError(msg, node, ctx, scope) {
  18506. const offset = scope ? scope.offset : ctx.startOffset;
  18507. return `${msg}
  18508. ${(scope || ctx.descriptor).filename}
  18509. ${shared.generateCodeFrame(
  18510. (scope || ctx.descriptor).source,
  18511. node.start + offset,
  18512. node.end + offset
  18513. )}`;
  18514. }
  18515. function resolveParserPlugins(lang, userPlugins, dts = false) {
  18516. const plugins = [];
  18517. if (!userPlugins || !userPlugins.some(
  18518. (p) => p === "importAssertions" || p === "importAttributes" || shared.isArray(p) && p[0] === "importAttributes"
  18519. )) {
  18520. plugins.push("importAttributes");
  18521. }
  18522. if (lang === "jsx" || lang === "tsx" || lang === "mtsx") {
  18523. plugins.push("jsx");
  18524. } else if (userPlugins) {
  18525. userPlugins = userPlugins.filter((p) => p !== "jsx");
  18526. }
  18527. if (lang === "ts" || lang === "mts" || lang === "tsx" || lang === "cts" || lang === "mtsx") {
  18528. plugins.push(["typescript", { dts }], "explicitResourceManagement");
  18529. if (!userPlugins || !userPlugins.includes("decorators")) {
  18530. plugins.push("decorators-legacy");
  18531. }
  18532. }
  18533. if (userPlugins) {
  18534. plugins.push(...userPlugins);
  18535. }
  18536. return plugins;
  18537. }
  18538. function rewriteDefault(input, as, parserPlugins) {
  18539. const ast = parser$2.parse(input, {
  18540. sourceType: "module",
  18541. plugins: resolveParserPlugins("js", parserPlugins)
  18542. }).program.body;
  18543. const s = new MagicString(input);
  18544. rewriteDefaultAST(ast, s, as);
  18545. return s.toString();
  18546. }
  18547. function rewriteDefaultAST(ast, s, as) {
  18548. if (!hasDefaultExport(ast)) {
  18549. s.append(`
  18550. const ${as} = {}`);
  18551. return;
  18552. }
  18553. ast.forEach((node) => {
  18554. if (node.type === "ExportDefaultDeclaration") {
  18555. if (node.declaration.type === "ClassDeclaration" && node.declaration.id) {
  18556. const start = node.declaration.decorators && node.declaration.decorators.length > 0 ? node.declaration.decorators[node.declaration.decorators.length - 1].end : node.start;
  18557. s.overwrite(start, node.declaration.id.start, ` class `);
  18558. s.append(`
  18559. const ${as} = ${node.declaration.id.name}`);
  18560. } else {
  18561. s.overwrite(node.start, node.declaration.start, `const ${as} = `);
  18562. }
  18563. } else if (node.type === "ExportNamedDeclaration") {
  18564. for (const specifier of node.specifiers) {
  18565. if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier" && specifier.exported.name === "default") {
  18566. if (node.source) {
  18567. if (specifier.local.name === "default") {
  18568. s.prepend(
  18569. `import { default as __VUE_DEFAULT__ } from '${node.source.value}'
  18570. `
  18571. );
  18572. const end2 = specifierEnd(s, specifier.local.end, node.end);
  18573. s.remove(specifier.start, end2);
  18574. s.append(`
  18575. const ${as} = __VUE_DEFAULT__`);
  18576. continue;
  18577. } else {
  18578. s.prepend(
  18579. `import { ${s.slice(
  18580. specifier.local.start,
  18581. specifier.local.end
  18582. )} as __VUE_DEFAULT__ } from '${node.source.value}'
  18583. `
  18584. );
  18585. const end2 = specifierEnd(s, specifier.exported.end, node.end);
  18586. s.remove(specifier.start, end2);
  18587. s.append(`
  18588. const ${as} = __VUE_DEFAULT__`);
  18589. continue;
  18590. }
  18591. }
  18592. const end = specifierEnd(s, specifier.end, node.end);
  18593. s.remove(specifier.start, end);
  18594. s.append(`
  18595. const ${as} = ${specifier.local.name}`);
  18596. }
  18597. }
  18598. }
  18599. });
  18600. }
  18601. function hasDefaultExport(ast) {
  18602. for (const stmt of ast) {
  18603. if (stmt.type === "ExportDefaultDeclaration") {
  18604. return true;
  18605. } else if (stmt.type === "ExportNamedDeclaration" && stmt.specifiers.some(
  18606. (spec) => spec.exported.name === "default"
  18607. )) {
  18608. return true;
  18609. }
  18610. }
  18611. return false;
  18612. }
  18613. function specifierEnd(s, end, nodeEnd) {
  18614. let hasCommas = false;
  18615. let oldEnd = end;
  18616. while (end < nodeEnd) {
  18617. if (/\s/.test(s.slice(end, end + 1))) {
  18618. end++;
  18619. } else if (s.slice(end, end + 1) === ",") {
  18620. end++;
  18621. hasCommas = true;
  18622. break;
  18623. } else if (s.slice(end, end + 1) === "}") {
  18624. break;
  18625. }
  18626. }
  18627. return hasCommas ? end : oldEnd;
  18628. }
  18629. const normalScriptDefaultVar = `__default__`;
  18630. function processNormalScript(ctx, scopeId) {
  18631. var _a;
  18632. const script = ctx.descriptor.script;
  18633. try {
  18634. let content = script.content;
  18635. let map = script.map;
  18636. const scriptAst = ctx.scriptAst;
  18637. const bindings = analyzeScriptBindings(scriptAst.body);
  18638. const { cssVars } = ctx.descriptor;
  18639. const { genDefaultAs, isProd } = ctx.options;
  18640. if (cssVars.length || genDefaultAs) {
  18641. const defaultVar = genDefaultAs || normalScriptDefaultVar;
  18642. const s = new MagicString(content);
  18643. rewriteDefaultAST(scriptAst.body, s, defaultVar);
  18644. content = s.toString();
  18645. if (cssVars.length && !((_a = ctx.options.templateOptions) == null ? void 0 : _a.ssr)) {
  18646. content += genNormalScriptCssVarsCode(
  18647. cssVars,
  18648. bindings,
  18649. scopeId,
  18650. !!isProd,
  18651. defaultVar
  18652. );
  18653. }
  18654. if (!genDefaultAs) {
  18655. content += `
  18656. export default ${defaultVar}`;
  18657. }
  18658. }
  18659. return {
  18660. ...script,
  18661. content,
  18662. map,
  18663. bindings,
  18664. scriptAst: scriptAst.body
  18665. };
  18666. } catch (e) {
  18667. return script;
  18668. }
  18669. }
  18670. const balanced = (a, b, str) => {
  18671. const ma = a instanceof RegExp ? maybeMatch(a, str) : a;
  18672. const mb = b instanceof RegExp ? maybeMatch(b, str) : b;
  18673. const r = ma !== null && mb != null && range(ma, mb, str);
  18674. return (r && {
  18675. start: r[0],
  18676. end: r[1],
  18677. pre: str.slice(0, r[0]),
  18678. body: str.slice(r[0] + ma.length, r[1]),
  18679. post: str.slice(r[1] + mb.length),
  18680. });
  18681. };
  18682. const maybeMatch = (reg, str) => {
  18683. const m = str.match(reg);
  18684. return m ? m[0] : null;
  18685. };
  18686. const range = (a, b, str) => {
  18687. let begs, beg, left, right = undefined, result;
  18688. let ai = str.indexOf(a);
  18689. let bi = str.indexOf(b, ai + 1);
  18690. let i = ai;
  18691. if (ai >= 0 && bi > 0) {
  18692. if (a === b) {
  18693. return [ai, bi];
  18694. }
  18695. begs = [];
  18696. left = str.length;
  18697. while (i >= 0 && !result) {
  18698. if (i === ai) {
  18699. begs.push(i);
  18700. ai = str.indexOf(a, i + 1);
  18701. }
  18702. else if (begs.length === 1) {
  18703. const r = begs.pop();
  18704. if (r !== undefined)
  18705. result = [r, bi];
  18706. }
  18707. else {
  18708. beg = begs.pop();
  18709. if (beg !== undefined && beg < left) {
  18710. left = beg;
  18711. right = bi;
  18712. }
  18713. bi = str.indexOf(b, i + 1);
  18714. }
  18715. i = ai < bi && ai >= 0 ? ai : bi;
  18716. }
  18717. if (begs.length && right !== undefined) {
  18718. result = [left, right];
  18719. }
  18720. }
  18721. return result;
  18722. };
  18723. const escSlash = '\0SLASH' + Math.random() + '\0';
  18724. const escOpen = '\0OPEN' + Math.random() + '\0';
  18725. const escClose = '\0CLOSE' + Math.random() + '\0';
  18726. const escComma = '\0COMMA' + Math.random() + '\0';
  18727. const escPeriod = '\0PERIOD' + Math.random() + '\0';
  18728. const escSlashPattern = new RegExp(escSlash, 'g');
  18729. const escOpenPattern = new RegExp(escOpen, 'g');
  18730. const escClosePattern = new RegExp(escClose, 'g');
  18731. const escCommaPattern = new RegExp(escComma, 'g');
  18732. const escPeriodPattern = new RegExp(escPeriod, 'g');
  18733. const slashPattern = /\\\\/g;
  18734. const openPattern = /\\{/g;
  18735. const closePattern = /\\}/g;
  18736. const commaPattern = /\\,/g;
  18737. const periodPattern = /\\\./g;
  18738. const EXPANSION_MAX = 100_000;
  18739. // `EXPANSION_MAX` caps the *number* of expansions, but not their length. An
  18740. // input like `'{a,b}'.repeat(1500)` stays under that count - its output is
  18741. // truncated to 100k results - while making every result ~1500 characters
  18742. // long. The result set, and the intermediate arrays built while combining
  18743. // brace sets, then grow large enough to exhaust memory and crash the process
  18744. // (CVE-2026-14257). `EXPANSION_MAX_LENGTH` bounds the total number of
  18745. // characters the accumulator may hold at any point, so memory stays flat no
  18746. // matter how many brace groups are chained. The limit sits well above any
  18747. // realistic expansion (100k results hitting `EXPANSION_MAX` measure ~1M
  18748. // characters) so legitimate input is unaffected.
  18749. const EXPANSION_MAX_LENGTH = 4_000_000;
  18750. function numeric(str) {
  18751. return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0);
  18752. }
  18753. function escapeBraces(str) {
  18754. return str
  18755. .replace(slashPattern, escSlash)
  18756. .replace(openPattern, escOpen)
  18757. .replace(closePattern, escClose)
  18758. .replace(commaPattern, escComma)
  18759. .replace(periodPattern, escPeriod);
  18760. }
  18761. function unescapeBraces(str) {
  18762. return str
  18763. .replace(escSlashPattern, '\\')
  18764. .replace(escOpenPattern, '{')
  18765. .replace(escClosePattern, '}')
  18766. .replace(escCommaPattern, ',')
  18767. .replace(escPeriodPattern, '.');
  18768. }
  18769. /**
  18770. * Basically just str.split(","), but handling cases
  18771. * where we have nested braced sections, which should be
  18772. * treated as individual members, like {a,{b,c},d}
  18773. */
  18774. function parseCommaParts(str) {
  18775. if (!str) {
  18776. return [''];
  18777. }
  18778. const parts = [];
  18779. const m = balanced('{', '}', str);
  18780. if (!m) {
  18781. return str.split(',');
  18782. }
  18783. const { pre, body, post } = m;
  18784. const p = pre.split(',');
  18785. p[p.length - 1] += '{' + body + '}';
  18786. const postParts = parseCommaParts(post);
  18787. if (post.length) {
  18788. p[p.length - 1] += postParts.shift();
  18789. p.push.apply(p, postParts);
  18790. }
  18791. parts.push.apply(parts, p);
  18792. return parts;
  18793. }
  18794. function expand(str, options = {}) {
  18795. if (!str) {
  18796. return [];
  18797. }
  18798. const { max = EXPANSION_MAX, maxLength = EXPANSION_MAX_LENGTH } = options;
  18799. // I don't know why Bash 4.3 does this, but it does.
  18800. // Anything starting with {} will have the first two bytes preserved
  18801. // but *only* at the top level, so {},a}b will not expand to anything,
  18802. // but a{},b}c will be expanded to [a}c,abc].
  18803. // One could argue that this is a bug in Bash, but since the goal of
  18804. // this module is to match Bash's rules, we escape a leading {}
  18805. if (str.slice(0, 2) === '{}') {
  18806. str = '\\{\\}' + str.slice(2);
  18807. }
  18808. return expand_(escapeBraces(str), max, maxLength, true).map(unescapeBraces);
  18809. }
  18810. function embrace(str) {
  18811. return '{' + str + '}';
  18812. }
  18813. function isPadded(el) {
  18814. return /^-?0\d/.test(el);
  18815. }
  18816. function lte(i, y) {
  18817. return i <= y;
  18818. }
  18819. function gte(i, y) {
  18820. return i >= y;
  18821. }
  18822. // Build `{ acc[a] + pre + values[v] }` for every combination, capping the
  18823. // number of results at `max` and the total number of characters at `maxLength`.
  18824. // This is the one place output grows, so bounding it here keeps the single
  18825. // accumulator - and therefore memory - flat regardless of how many brace groups
  18826. // are combined (CVE-2026-14257).
  18827. function combine(acc, pre, values, max, maxLength, dropEmpties) {
  18828. const out = [];
  18829. let length = 0;
  18830. for (let a = 0; a < acc.length; a++) {
  18831. for (let v = 0; v < values.length; v++) {
  18832. if (out.length >= max)
  18833. return out;
  18834. const expansion = acc[a] + pre + values[v];
  18835. // Bash drops empty results at the top level. Skip them before they count
  18836. // against `max`, so `max` bounds the number of *kept* results.
  18837. if (dropEmpties && !expansion)
  18838. continue;
  18839. if (length + expansion.length > maxLength)
  18840. return out;
  18841. out.push(expansion);
  18842. length += expansion.length;
  18843. }
  18844. }
  18845. return out;
  18846. }
  18847. // The expansion values of a single numeric (`1..5`) or alphabetic (`a..e..2`)
  18848. // sequence body.
  18849. function expandSequence(body, isAlphaSequence, max, maxLength) {
  18850. const n = body.split(/\.\./);
  18851. const N = [];
  18852. // A sequence body always splits into two or three parts, but the compiler
  18853. // can't know that.
  18854. /* c8 ignore start */
  18855. if (n[0] === undefined || n[1] === undefined) {
  18856. return N;
  18857. }
  18858. /* c8 ignore stop */
  18859. const x = numeric(n[0]);
  18860. const y = numeric(n[1]);
  18861. const width = Math.max(n[0].length, n[1].length);
  18862. let incr = n.length === 3 && n[2] !== undefined ?
  18863. Math.max(Math.abs(numeric(n[2])), 1)
  18864. : 1;
  18865. let test = lte;
  18866. const reverse = y < x;
  18867. if (reverse) {
  18868. incr *= -1;
  18869. test = gte;
  18870. }
  18871. const pad = n.some(isPadded);
  18872. let length = 0;
  18873. for (let i = x; test(i, y) && N.length < max; i += incr) {
  18874. let c;
  18875. if (isAlphaSequence) {
  18876. c = String.fromCharCode(i);
  18877. if (c === '\\') {
  18878. c = '';
  18879. }
  18880. }
  18881. else {
  18882. c = String(i);
  18883. if (pad) {
  18884. const need = width - c.length;
  18885. if (need > 0) {
  18886. const z = new Array(need + 1).join('0');
  18887. if (i < 0) {
  18888. c = '-' + z + c.slice(1);
  18889. }
  18890. else {
  18891. c = z + c;
  18892. }
  18893. }
  18894. }
  18895. }
  18896. if (length + c.length > maxLength)
  18897. break;
  18898. N.push(c);
  18899. length += c.length;
  18900. }
  18901. return N;
  18902. }
  18903. function expand_(str, max, maxLength, isTop) {
  18904. // Consume the string's top-level brace groups left to right, threading a
  18905. // running set of combined prefixes (`acc`). Expanding the tail iteratively -
  18906. // rather than recursing on `m.post` once per group - keeps the native stack
  18907. // depth constant, so deeply chained input (`'{a,b}'.repeat(3000)`) can no
  18908. // longer overflow the stack, and leaves a single accumulator whose size
  18909. // `maxLength` bounds directly (CVE-2026-14257).
  18910. let acc = [''];
  18911. // Bash drops empty results, but only when the *first* top-level group is a
  18912. // comma set - a sequence like `{a..\}` may legitimately yield ''. The drop
  18913. // is on the final strings, so it is applied to whichever `combine` produces
  18914. // them (the one with no brace set left in the tail).
  18915. let dropEmpties = false;
  18916. let firstGroup = true;
  18917. for (;;) {
  18918. const m = balanced('{', '}', str);
  18919. // No brace set left: the rest of the string is literal.
  18920. if (!m) {
  18921. return combine(acc, str, [''], max, maxLength, dropEmpties);
  18922. }
  18923. // no need to expand pre, since it is guaranteed to be free of brace-sets
  18924. const pre = m.pre;
  18925. if (/\$$/.test(pre)) {
  18926. acc = combine(acc, pre + '{' + m.body + '}', [''], max, maxLength, dropEmpties && !m.post.length);
  18927. firstGroup = false;
  18928. if (!m.post.length)
  18929. break;
  18930. str = m.post;
  18931. continue;
  18932. }
  18933. const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  18934. const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  18935. const isSequence = isNumericSequence || isAlphaSequence;
  18936. const isOptions = m.body.indexOf(',') >= 0;
  18937. if (!isSequence && !isOptions) {
  18938. // {a},b}
  18939. if (m.post.match(/,(?!,).*\}/)) {
  18940. str = m.pre + '{' + m.body + escClose + m.post;
  18941. isTop = true;
  18942. continue;
  18943. }
  18944. // Nothing here expands, so the whole remaining string is literal.
  18945. return combine(acc, pre + '{' + m.body + '}' + m.post, [''], max, maxLength, dropEmpties);
  18946. }
  18947. if (firstGroup) {
  18948. dropEmpties = isTop && !isSequence;
  18949. firstGroup = false;
  18950. }
  18951. let values;
  18952. if (isSequence) {
  18953. values = expandSequence(m.body, isAlphaSequence, max, maxLength);
  18954. }
  18955. else {
  18956. let n = parseCommaParts(m.body);
  18957. if (n.length === 1 && n[0] !== undefined) {
  18958. // x{{a,b}}y ==> x{a}y x{b}y
  18959. n = expand_(n[0], max, maxLength, false).map(embrace);
  18960. //XXX is this necessary? Can't seem to hit it in tests.
  18961. /* c8 ignore start */
  18962. if (n.length === 1) {
  18963. acc = combine(acc, pre + n[0], [''], max, maxLength, dropEmpties && !m.post.length);
  18964. if (!m.post.length)
  18965. break;
  18966. str = m.post;
  18967. continue;
  18968. }
  18969. /* c8 ignore stop */
  18970. }
  18971. // Values that `combine` is going to drop as empty produce no result, so
  18972. // they must not count against `max` - otherwise `{a,,b}` with `max: 2`
  18973. // would stop at `['a', '']` and yield one result instead of two. Skipping
  18974. // them outright keeps `values` bounded while leaving `max` a bound on
  18975. // *kept* results.
  18976. let dropsEmpties = dropEmpties && !m.post.length && !pre;
  18977. for (let d = 0; dropsEmpties && d < acc.length; d++) {
  18978. if (acc[d]) {
  18979. dropsEmpties = false;
  18980. }
  18981. }
  18982. values = [];
  18983. let valuesLength = 0;
  18984. outer: for (let j = 0; j < n.length; j++) {
  18985. const expanded = expand_(n[j], max, maxLength, false);
  18986. for (let k = 0; k < expanded.length; k++) {
  18987. const v = expanded[k];
  18988. if (dropsEmpties && !v)
  18989. continue;
  18990. if (values.length >= max || valuesLength + v.length > maxLength) {
  18991. break outer;
  18992. }
  18993. values.push(v);
  18994. valuesLength += v.length;
  18995. }
  18996. }
  18997. }
  18998. acc = combine(acc, pre, values, max, maxLength, dropEmpties && !m.post.length);
  18999. if (!m.post.length)
  19000. break;
  19001. str = m.post;
  19002. }
  19003. return acc;
  19004. }
  19005. const MAX_PATTERN_LENGTH = 1024 * 64;
  19006. const assertValidPattern = (pattern) => {
  19007. if (typeof pattern !== 'string') {
  19008. throw new TypeError('invalid pattern');
  19009. }
  19010. if (pattern.length > MAX_PATTERN_LENGTH) {
  19011. throw new TypeError('pattern is too long');
  19012. }
  19013. };
  19014. // translate the various posix character classes into unicode properties
  19015. // this works across all unicode locales
  19016. // { <posix class>: [<translation>, /u flag required, negated]
  19017. const posixClasses = {
  19018. '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
  19019. '[:alpha:]': ['\\p{L}\\p{Nl}', true],
  19020. '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
  19021. '[:blank:]': ['\\p{Zs}\\t', true],
  19022. '[:cntrl:]': ['\\p{Cc}', true],
  19023. '[:digit:]': ['\\p{Nd}', true],
  19024. '[:graph:]': ['\\p{Z}\\p{C}', true, true],
  19025. '[:lower:]': ['\\p{Ll}', true],
  19026. '[:print:]': ['\\p{C}', true],
  19027. '[:punct:]': ['\\p{P}', true],
  19028. '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
  19029. '[:upper:]': ['\\p{Lu}', true],
  19030. '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
  19031. '[:xdigit:]': ['A-Fa-f0-9', false],
  19032. };
  19033. // only need to escape a few things inside of brace expressions
  19034. // escapes: [ \ ] -
  19035. const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
  19036. // escape all regexp magic characters
  19037. const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  19038. // everything has already been escaped, we just have to join
  19039. const rangesToString = (ranges) => ranges.join('');
  19040. // takes a glob string at a posix brace expression, and returns
  19041. // an equivalent regular expression source, and boolean indicating
  19042. // whether the /u flag needs to be applied, and the number of chars
  19043. // consumed to parse the character class.
  19044. // This also removes out of order ranges, and returns ($.) if the
  19045. // entire class just no good.
  19046. const parseClass = (glob, position) => {
  19047. const pos = position;
  19048. /* c8 ignore start */
  19049. if (glob.charAt(pos) !== '[') {
  19050. throw new Error('not in a brace expression');
  19051. }
  19052. /* c8 ignore stop */
  19053. const ranges = [];
  19054. const negs = [];
  19055. let i = pos + 1;
  19056. let sawStart = false;
  19057. let uflag = false;
  19058. let escaping = false;
  19059. let negate = false;
  19060. let endPos = pos;
  19061. let rangeStart = '';
  19062. WHILE: while (i < glob.length) {
  19063. const c = glob.charAt(i);
  19064. if ((c === '!' || c === '^') && i === pos + 1) {
  19065. negate = true;
  19066. i++;
  19067. continue;
  19068. }
  19069. if (c === ']' && sawStart && !escaping) {
  19070. endPos = i + 1;
  19071. break;
  19072. }
  19073. sawStart = true;
  19074. if (c === '\\') {
  19075. if (!escaping) {
  19076. escaping = true;
  19077. i++;
  19078. continue;
  19079. }
  19080. // escaped \ char, fall through and treat like normal char
  19081. }
  19082. if (c === '[' && !escaping) {
  19083. // either a posix class, a collation equivalent, or just a [
  19084. for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
  19085. if (glob.startsWith(cls, i)) {
  19086. // invalid, [a-[] is fine, but not [a-[:alpha]]
  19087. if (rangeStart) {
  19088. return ['$.', false, glob.length - pos, true];
  19089. }
  19090. i += cls.length;
  19091. if (neg)
  19092. negs.push(unip);
  19093. else
  19094. ranges.push(unip);
  19095. uflag = uflag || u;
  19096. continue WHILE;
  19097. }
  19098. }
  19099. }
  19100. // now it's just a normal character, effectively
  19101. escaping = false;
  19102. if (rangeStart) {
  19103. // throw this range away if it's not valid, but others
  19104. // can still match.
  19105. if (c > rangeStart) {
  19106. ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
  19107. }
  19108. else if (c === rangeStart) {
  19109. ranges.push(braceEscape(c));
  19110. }
  19111. rangeStart = '';
  19112. i++;
  19113. continue;
  19114. }
  19115. // now might be the start of a range.
  19116. // can be either c-d or c-] or c<more...>] or c] at this point
  19117. if (glob.startsWith('-]', i + 1)) {
  19118. ranges.push(braceEscape(c + '-'));
  19119. i += 2;
  19120. continue;
  19121. }
  19122. if (glob.startsWith('-', i + 1)) {
  19123. rangeStart = c;
  19124. i += 2;
  19125. continue;
  19126. }
  19127. // not the start of a range, just a single character
  19128. ranges.push(braceEscape(c));
  19129. i++;
  19130. }
  19131. if (endPos < i) {
  19132. // didn't see the end of the class, not a valid class,
  19133. // but might still be valid as a literal match.
  19134. return ['', false, 0, false];
  19135. }
  19136. // if we got no ranges and no negates, then we have a range that
  19137. // cannot possibly match anything, and that poisons the whole glob
  19138. if (!ranges.length && !negs.length) {
  19139. return ['$.', false, glob.length - pos, true];
  19140. }
  19141. // if we got one positive range, and it's a single character, then that's
  19142. // not actually a magic pattern, it's just that one literal character.
  19143. // we should not treat that as "magic", we should just return the literal
  19144. // character. [_] is a perfectly valid way to escape glob magic chars.
  19145. if (negs.length === 0 &&
  19146. ranges.length === 1 &&
  19147. /^\\?.$/.test(ranges[0]) &&
  19148. !negate) {
  19149. const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
  19150. return [regexpEscape(r), false, endPos - pos, false];
  19151. }
  19152. const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
  19153. const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
  19154. const comb = ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'
  19155. : ranges.length ? sranges
  19156. : snegs;
  19157. return [comb, uflag, endPos - pos, true];
  19158. };
  19159. /**
  19160. * Un-escape a string that has been escaped with {@link escape}.
  19161. *
  19162. * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then
  19163. * square-bracket escapes are removed, but not backslash escapes.
  19164. *
  19165. * For example, it will turn the string `'[*]'` into `*`, but it will not
  19166. * turn `'\\*'` into `'*'`, because `\` is a path separator in
  19167. * `windowsPathsNoEscape` mode.
  19168. *
  19169. * When `windowsPathsNoEscape` is not set, then both square-bracket escapes and
  19170. * backslash escapes are removed.
  19171. *
  19172. * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
  19173. * or unescaped.
  19174. *
  19175. * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be
  19176. * unescaped.
  19177. */
  19178. const unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true, } = {}) => {
  19179. if (magicalBraces) {
  19180. return windowsPathsNoEscape ?
  19181. s.replace(/\[([^/\\])\]/g, '$1')
  19182. : s
  19183. .replace(/((?!\\).|^)\[([^/\\])\]/g, '$1$2')
  19184. .replace(/\\([^/])/g, '$1');
  19185. }
  19186. return windowsPathsNoEscape ?
  19187. s.replace(/\[([^/\\{}])\]/g, '$1')
  19188. : s
  19189. .replace(/((?!\\).|^)\[([^/\\{}])\]/g, '$1$2')
  19190. .replace(/\\([^/{}])/g, '$1');
  19191. };
  19192. // parse a single path portion
  19193. var _a;
  19194. const types = new Set(['!', '?', '+', '*', '@']);
  19195. const isExtglobType = (c) => types.has(c);
  19196. const isExtglobAST = (c) => isExtglobType(c.type);
  19197. // Map of which extglob types can adopt the children of a nested extglob
  19198. //
  19199. // anything but ! can adopt a matching type:
  19200. // +(a|+(b|c)|d) => +(a|b|c|d)
  19201. // *(a|*(b|c)|d) => *(a|b|c|d)
  19202. // @(a|@(b|c)|d) => @(a|b|c|d)
  19203. // ?(a|?(b|c)|d) => ?(a|b|c|d)
  19204. //
  19205. // * can adopt anything, because 0 or repetition is allowed
  19206. // *(a|?(b|c)|d) => *(a|b|c|d)
  19207. // *(a|+(b|c)|d) => *(a|b|c|d)
  19208. // *(a|@(b|c)|d) => *(a|b|c|d)
  19209. //
  19210. // + can adopt @, because 1 or repetition is allowed
  19211. // +(a|@(b|c)|d) => +(a|b|c|d)
  19212. //
  19213. // + and @ CANNOT adopt *, because 0 would be allowed
  19214. // +(a|*(b|c)|d) => would match "", on *(b|c)
  19215. // @(a|*(b|c)|d) => would match "", on *(b|c)
  19216. //
  19217. // + and @ CANNOT adopt ?, because 0 would be allowed
  19218. // +(a|?(b|c)|d) => would match "", on ?(b|c)
  19219. // @(a|?(b|c)|d) => would match "", on ?(b|c)
  19220. //
  19221. // ? can adopt @, because 0 or 1 is allowed
  19222. // ?(a|@(b|c)|d) => ?(a|b|c|d)
  19223. //
  19224. // ? and @ CANNOT adopt * or +, because >1 would be allowed
  19225. // ?(a|*(b|c)|d) => would match bbb on *(b|c)
  19226. // @(a|*(b|c)|d) => would match bbb on *(b|c)
  19227. // ?(a|+(b|c)|d) => would match bbb on +(b|c)
  19228. // @(a|+(b|c)|d) => would match bbb on +(b|c)
  19229. //
  19230. // ! CANNOT adopt ! (nothing else can either)
  19231. // !(a|!(b|c)|d) => !(a|b|c|d) would fail to match on b (not not b|c)
  19232. //
  19233. // ! can adopt @
  19234. // !(a|@(b|c)|d) => !(a|b|c|d)
  19235. //
  19236. // ! CANNOT adopt *
  19237. // !(a|*(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed
  19238. //
  19239. // ! CANNOT adopt +
  19240. // !(a|+(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed
  19241. //
  19242. // ! CANNOT adopt ?
  19243. // x!(a|?(b|c)|d) => x!(a|b|c|d) would fail to match "x"
  19244. const adoptionMap = new Map([
  19245. ['!', ['@']],
  19246. ['?', ['?', '@']],
  19247. ['@', ['@']],
  19248. ['*', ['*', '+', '?', '@']],
  19249. ['+', ['+', '@']],
  19250. ]);
  19251. // nested extglobs that can be adopted in, but with the addition of
  19252. // a blank '' element.
  19253. const adoptionWithSpaceMap = new Map([
  19254. ['!', ['?']],
  19255. ['@', ['?']],
  19256. ['+', ['?', '*']],
  19257. ]);
  19258. // union of the previous two maps
  19259. const adoptionAnyMap = new Map([
  19260. ['!', ['?', '@']],
  19261. ['?', ['?', '@']],
  19262. ['@', ['?', '@']],
  19263. ['*', ['*', '+', '?', '@']],
  19264. ['+', ['+', '@', '?', '*']],
  19265. ]);
  19266. // Extglobs that can take over their parent if they are the only child
  19267. // the key is parent, value maps child to resulting extglob parent type
  19268. // '@' is omitted because it's a special case. An `@` extglob with a single
  19269. // member can always be usurped by that subpattern.
  19270. const usurpMap = new Map([
  19271. ['!', new Map([['!', '@']])],
  19272. [
  19273. '?',
  19274. new Map([
  19275. ['*', '*'],
  19276. ['+', '*'],
  19277. ]),
  19278. ],
  19279. [
  19280. '@',
  19281. new Map([
  19282. ['!', '!'],
  19283. ['?', '?'],
  19284. ['@', '@'],
  19285. ['*', '*'],
  19286. ['+', '+'],
  19287. ]),
  19288. ],
  19289. [
  19290. '+',
  19291. new Map([
  19292. ['?', '*'],
  19293. ['*', '*'],
  19294. ]),
  19295. ],
  19296. ]);
  19297. // Patterns that get prepended to bind to the start of either the
  19298. // entire string, or just a single path portion, to prevent dots
  19299. // and/or traversal patterns, when needed.
  19300. // Exts don't need the ^ or / bit, because the root binds that already.
  19301. const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
  19302. const startNoDot = '(?!\\.)';
  19303. // characters that indicate a start of pattern needs the "no dots" bit,
  19304. // because a dot *might* be matched. ( is not in the list, because in
  19305. // the case of a child extglob, it will handle the prevention itself.
  19306. const addPatternStart = new Set(['[', '.']);
  19307. // cases where traversal is A-OK, no dot prevention needed
  19308. const justDots = new Set(['..', '.']);
  19309. const reSpecials = new Set('().*{}+?[]^$\\!');
  19310. const regExpEscape$1 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  19311. // any single thing other than /
  19312. const qmark$1 = '[^/]';
  19313. // * => any number of characters
  19314. const star$1 = qmark$1 + '*?';
  19315. // use + when we need to ensure that *something* matches, because the * is
  19316. // the only thing in the path portion.
  19317. const starNoEmpty = qmark$1 + '+?';
  19318. // remove the \ chars that we added if we end up doing a nonmagic compare
  19319. // const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
  19320. let ID = 0;
  19321. class AST {
  19322. type;
  19323. #root;
  19324. #hasMagic;
  19325. #uflag = false;
  19326. #parts = [];
  19327. #parent;
  19328. #parentIndex;
  19329. #negs;
  19330. #filledNegs = false;
  19331. #options;
  19332. #toString;
  19333. // set to true if it's an extglob with no children
  19334. // (which really means one child of '')
  19335. #emptyExt = false;
  19336. id = ++ID;
  19337. get depth() {
  19338. return (this.#parent?.depth ?? -1) + 1;
  19339. }
  19340. [Symbol.for('nodejs.util.inspect.custom')]() {
  19341. return {
  19342. '@@type': 'AST',
  19343. id: this.id,
  19344. type: this.type,
  19345. root: this.#root.id,
  19346. parent: this.#parent?.id,
  19347. depth: this.depth,
  19348. partsLength: this.#parts.length,
  19349. parts: this.#parts,
  19350. };
  19351. }
  19352. constructor(type, parent, options = {}) {
  19353. this.type = type;
  19354. // extglobs are inherently magical
  19355. if (type)
  19356. this.#hasMagic = true;
  19357. this.#parent = parent;
  19358. this.#root = this.#parent ? this.#parent.#root : this;
  19359. this.#options = this.#root === this ? options : this.#root.#options;
  19360. this.#negs = this.#root === this ? [] : this.#root.#negs;
  19361. if (type === '!' && !this.#root.#filledNegs)
  19362. this.#negs.push(this);
  19363. this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
  19364. }
  19365. get hasMagic() {
  19366. /* c8 ignore start */
  19367. if (this.#hasMagic !== undefined)
  19368. return this.#hasMagic;
  19369. /* c8 ignore stop */
  19370. for (const p of this.#parts) {
  19371. if (typeof p === 'string')
  19372. continue;
  19373. if (p.type || p.hasMagic)
  19374. return (this.#hasMagic = true);
  19375. }
  19376. // note: will be undefined until we generate the regexp src and find out
  19377. return this.#hasMagic;
  19378. }
  19379. // reconstructs the pattern
  19380. toString() {
  19381. return (this.#toString !== undefined ? this.#toString
  19382. : !this.type ?
  19383. (this.#toString = this.#parts.map(p => String(p)).join(''))
  19384. : (this.#toString =
  19385. this.type +
  19386. '(' +
  19387. this.#parts.map(p => String(p)).join('|') +
  19388. ')'));
  19389. }
  19390. #fillNegs() {
  19391. /* c8 ignore start */
  19392. if (this !== this.#root)
  19393. throw new Error('should only call on root');
  19394. if (this.#filledNegs)
  19395. return this;
  19396. /* c8 ignore stop */
  19397. // call toString() once to fill this out
  19398. this.toString();
  19399. this.#filledNegs = true;
  19400. let n;
  19401. while ((n = this.#negs.pop())) {
  19402. if (n.type !== '!')
  19403. continue;
  19404. // walk up the tree, appending everthing that comes AFTER parentIndex
  19405. let p = n;
  19406. let pp = p.#parent;
  19407. while (pp) {
  19408. for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
  19409. for (const part of n.#parts) {
  19410. /* c8 ignore start */
  19411. if (typeof part === 'string') {
  19412. throw new Error('string part in extglob AST??');
  19413. }
  19414. /* c8 ignore stop */
  19415. part.copyIn(pp.#parts[i]);
  19416. }
  19417. }
  19418. p = pp;
  19419. pp = p.#parent;
  19420. }
  19421. }
  19422. return this;
  19423. }
  19424. push(...parts) {
  19425. for (const p of parts) {
  19426. if (p === '')
  19427. continue;
  19428. /* c8 ignore start */
  19429. if (typeof p !== 'string' &&
  19430. !(p instanceof _a && p.#parent === this)) {
  19431. throw new Error('invalid part: ' + p);
  19432. }
  19433. /* c8 ignore stop */
  19434. this.#parts.push(p);
  19435. }
  19436. }
  19437. toJSON() {
  19438. const ret = this.type === null ?
  19439. this.#parts
  19440. .slice()
  19441. .map(p => (typeof p === 'string' ? p : p.toJSON()))
  19442. : [this.type, ...this.#parts.map(p => p.toJSON())];
  19443. if (this.isStart() && !this.type)
  19444. ret.unshift([]);
  19445. if (this.isEnd() &&
  19446. (this === this.#root ||
  19447. (this.#root.#filledNegs && this.#parent?.type === '!'))) {
  19448. ret.push({});
  19449. }
  19450. return ret;
  19451. }
  19452. isStart() {
  19453. if (this.#root === this)
  19454. return true;
  19455. // if (this.type) return !!this.#parent?.isStart()
  19456. if (!this.#parent?.isStart())
  19457. return false;
  19458. if (this.#parentIndex === 0)
  19459. return true;
  19460. // if everything AHEAD of this is a negation, then it's still the "start"
  19461. const p = this.#parent;
  19462. for (let i = 0; i < this.#parentIndex; i++) {
  19463. const pp = p.#parts[i];
  19464. if (!(pp instanceof _a && pp.type === '!')) {
  19465. return false;
  19466. }
  19467. }
  19468. return true;
  19469. }
  19470. isEnd() {
  19471. if (this.#root === this)
  19472. return true;
  19473. if (this.#parent?.type === '!')
  19474. return true;
  19475. if (!this.#parent?.isEnd())
  19476. return false;
  19477. if (!this.type)
  19478. return this.#parent?.isEnd();
  19479. // if not root, it'll always have a parent
  19480. /* c8 ignore start */
  19481. const pl = this.#parent ? this.#parent.#parts.length : 0;
  19482. /* c8 ignore stop */
  19483. return this.#parentIndex === pl - 1;
  19484. }
  19485. copyIn(part) {
  19486. if (typeof part === 'string')
  19487. this.push(part);
  19488. else
  19489. this.push(part.clone(this));
  19490. }
  19491. clone(parent) {
  19492. const c = new _a(this.type, parent);
  19493. for (const p of this.#parts) {
  19494. c.copyIn(p);
  19495. }
  19496. return c;
  19497. }
  19498. static #parseAST(str, ast, pos, opt, extDepth) {
  19499. const maxDepth = opt.maxExtglobRecursion ?? 2;
  19500. let escaping = false;
  19501. let inBrace = false;
  19502. let braceStart = -1;
  19503. let braceNeg = false;
  19504. if (ast.type === null) {
  19505. // outside of a extglob, append until we find a start
  19506. let i = pos;
  19507. let acc = '';
  19508. while (i < str.length) {
  19509. const c = str.charAt(i++);
  19510. // still accumulate escapes at this point, but we do ignore
  19511. // starts that are escaped
  19512. if (escaping || c === '\\') {
  19513. escaping = !escaping;
  19514. acc += c;
  19515. continue;
  19516. }
  19517. if (inBrace) {
  19518. if (i === braceStart + 1) {
  19519. if (c === '^' || c === '!') {
  19520. braceNeg = true;
  19521. }
  19522. }
  19523. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  19524. inBrace = false;
  19525. }
  19526. acc += c;
  19527. continue;
  19528. }
  19529. else if (c === '[') {
  19530. inBrace = true;
  19531. braceStart = i;
  19532. braceNeg = false;
  19533. acc += c;
  19534. continue;
  19535. }
  19536. // we don't have to check for adoption here, because that's
  19537. // done at the other recursion point.
  19538. const doRecurse = !opt.noext &&
  19539. isExtglobType(c) &&
  19540. str.charAt(i) === '(' &&
  19541. extDepth <= maxDepth;
  19542. if (doRecurse) {
  19543. ast.push(acc);
  19544. acc = '';
  19545. const ext = new _a(c, ast);
  19546. i = _a.#parseAST(str, ext, i, opt, extDepth + 1);
  19547. ast.push(ext);
  19548. continue;
  19549. }
  19550. acc += c;
  19551. }
  19552. ast.push(acc);
  19553. return i;
  19554. }
  19555. // some kind of extglob, pos is at the (
  19556. // find the next | or )
  19557. let i = pos + 1;
  19558. let part = new _a(null, ast);
  19559. const parts = [];
  19560. let acc = '';
  19561. while (i < str.length) {
  19562. const c = str.charAt(i++);
  19563. // still accumulate escapes at this point, but we do ignore
  19564. // starts that are escaped
  19565. if (escaping || c === '\\') {
  19566. escaping = !escaping;
  19567. acc += c;
  19568. continue;
  19569. }
  19570. if (inBrace) {
  19571. if (i === braceStart + 1) {
  19572. if (c === '^' || c === '!') {
  19573. braceNeg = true;
  19574. }
  19575. }
  19576. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  19577. inBrace = false;
  19578. }
  19579. acc += c;
  19580. continue;
  19581. }
  19582. else if (c === '[') {
  19583. inBrace = true;
  19584. braceStart = i;
  19585. braceNeg = false;
  19586. acc += c;
  19587. continue;
  19588. }
  19589. const doRecurse = !opt.noext &&
  19590. isExtglobType(c) &&
  19591. str.charAt(i) === '(' &&
  19592. /* c8 ignore start - the maxDepth is sufficient here */
  19593. (extDepth <= maxDepth || (ast && ast.#canAdoptType(c)));
  19594. /* c8 ignore stop */
  19595. if (doRecurse) {
  19596. const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1;
  19597. part.push(acc);
  19598. acc = '';
  19599. const ext = new _a(c, part);
  19600. part.push(ext);
  19601. i = _a.#parseAST(str, ext, i, opt, extDepth + depthAdd);
  19602. continue;
  19603. }
  19604. if (c === '|') {
  19605. part.push(acc);
  19606. acc = '';
  19607. parts.push(part);
  19608. part = new _a(null, ast);
  19609. continue;
  19610. }
  19611. if (c === ')') {
  19612. if (acc === '' && ast.#parts.length === 0) {
  19613. ast.#emptyExt = true;
  19614. }
  19615. part.push(acc);
  19616. acc = '';
  19617. ast.push(...parts, part);
  19618. return i;
  19619. }
  19620. acc += c;
  19621. }
  19622. // unfinished extglob
  19623. // if we got here, it was a malformed extglob! not an extglob, but
  19624. // maybe something else in there.
  19625. ast.type = null;
  19626. ast.#hasMagic = undefined;
  19627. ast.#parts = [str.substring(pos - 1)];
  19628. return i;
  19629. }
  19630. #canAdoptWithSpace(child) {
  19631. return this.#canAdopt(child, adoptionWithSpaceMap);
  19632. }
  19633. #canAdopt(child, map = adoptionMap) {
  19634. if (!child ||
  19635. typeof child !== 'object' ||
  19636. child.type !== null ||
  19637. child.#parts.length !== 1 ||
  19638. this.type === null) {
  19639. return false;
  19640. }
  19641. const gc = child.#parts[0];
  19642. if (!gc || typeof gc !== 'object' || gc.type === null) {
  19643. return false;
  19644. }
  19645. return this.#canAdoptType(gc.type, map);
  19646. }
  19647. #canAdoptType(c, map = adoptionAnyMap) {
  19648. return !!map.get(this.type)?.includes(c);
  19649. }
  19650. #adoptWithSpace(child, index) {
  19651. const gc = child.#parts[0];
  19652. const blank = new _a(null, gc, this.options);
  19653. blank.#parts.push('');
  19654. gc.push(blank);
  19655. this.#adopt(child, index);
  19656. }
  19657. #adopt(child, index) {
  19658. const gc = child.#parts[0];
  19659. this.#parts.splice(index, 1, ...gc.#parts);
  19660. for (const p of gc.#parts) {
  19661. if (typeof p === 'object')
  19662. p.#parent = this;
  19663. }
  19664. this.#toString = undefined;
  19665. }
  19666. #canUsurpType(c) {
  19667. const m = usurpMap.get(this.type);
  19668. return !!m?.has(c);
  19669. }
  19670. #canUsurp(child) {
  19671. if (!child ||
  19672. typeof child !== 'object' ||
  19673. child.type !== null ||
  19674. child.#parts.length !== 1 ||
  19675. this.type === null ||
  19676. this.#parts.length !== 1) {
  19677. return false;
  19678. }
  19679. const gc = child.#parts[0];
  19680. if (!gc || typeof gc !== 'object' || gc.type === null) {
  19681. return false;
  19682. }
  19683. return this.#canUsurpType(gc.type);
  19684. }
  19685. #usurp(child) {
  19686. const m = usurpMap.get(this.type);
  19687. const gc = child.#parts[0];
  19688. const nt = m?.get(gc.type);
  19689. /* c8 ignore start - impossible */
  19690. if (!nt)
  19691. return false;
  19692. /* c8 ignore stop */
  19693. this.#parts = gc.#parts;
  19694. for (const p of this.#parts) {
  19695. if (typeof p === 'object') {
  19696. p.#parent = this;
  19697. }
  19698. }
  19699. this.type = nt;
  19700. this.#toString = undefined;
  19701. this.#emptyExt = false;
  19702. }
  19703. static fromGlob(pattern, options = {}) {
  19704. const ast = new _a(null, undefined, options);
  19705. _a.#parseAST(pattern, ast, 0, options, 0);
  19706. return ast;
  19707. }
  19708. // returns the regular expression if there's magic, or the unescaped
  19709. // string if not.
  19710. toMMPattern() {
  19711. // should only be called on root
  19712. /* c8 ignore start */
  19713. if (this !== this.#root)
  19714. return this.#root.toMMPattern();
  19715. /* c8 ignore stop */
  19716. const glob = this.toString();
  19717. const [re, body, hasMagic, uflag] = this.toRegExpSource();
  19718. // if we're in nocase mode, and not nocaseMagicOnly, then we do
  19719. // still need a regular expression if we have to case-insensitively
  19720. // match capital/lowercase characters.
  19721. const anyMagic = hasMagic ||
  19722. this.#hasMagic ||
  19723. (this.#options.nocase &&
  19724. !this.#options.nocaseMagicOnly &&
  19725. glob.toUpperCase() !== glob.toLowerCase());
  19726. if (!anyMagic) {
  19727. return body;
  19728. }
  19729. const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
  19730. return Object.assign(new RegExp(`^${re}$`, flags), {
  19731. _src: re,
  19732. _glob: glob,
  19733. });
  19734. }
  19735. get options() {
  19736. return this.#options;
  19737. }
  19738. // returns the string match, the regexp source, whether there's magic
  19739. // in the regexp (so a regular expression is required) and whether or
  19740. // not the uflag is needed for the regular expression (for posix classes)
  19741. // TODO: instead of injecting the start/end at this point, just return
  19742. // the BODY of the regexp, along with the start/end portions suitable
  19743. // for binding the start/end in either a joined full-path makeRe context
  19744. // (where we bind to (^|/), or a standalone matchPart context (where
  19745. // we bind to ^, and not /). Otherwise slashes get duped!
  19746. //
  19747. // In part-matching mode, the start is:
  19748. // - if not isStart: nothing
  19749. // - if traversal possible, but not allowed: ^(?!\.\.?$)
  19750. // - if dots allowed or not possible: ^
  19751. // - if dots possible and not allowed: ^(?!\.)
  19752. // end is:
  19753. // - if not isEnd(): nothing
  19754. // - else: $
  19755. //
  19756. // In full-path matching mode, we put the slash at the START of the
  19757. // pattern, so start is:
  19758. // - if first pattern: same as part-matching mode
  19759. // - if not isStart(): nothing
  19760. // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
  19761. // - if dots allowed or not possible: /
  19762. // - if dots possible and not allowed: /(?!\.)
  19763. // end is:
  19764. // - if last pattern, same as part-matching mode
  19765. // - else nothing
  19766. //
  19767. // Always put the (?:$|/) on negated tails, though, because that has to be
  19768. // there to bind the end of the negated pattern portion, and it's easier to
  19769. // just stick it in now rather than try to inject it later in the middle of
  19770. // the pattern.
  19771. //
  19772. // We can just always return the same end, and leave it up to the caller
  19773. // to know whether it's going to be used joined or in parts.
  19774. // And, if the start is adjusted slightly, can do the same there:
  19775. // - if not isStart: nothing
  19776. // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
  19777. // - if dots allowed or not possible: (?:/|^)
  19778. // - if dots possible and not allowed: (?:/|^)(?!\.)
  19779. //
  19780. // But it's better to have a simpler binding without a conditional, for
  19781. // performance, so probably better to return both start options.
  19782. //
  19783. // Then the caller just ignores the end if it's not the first pattern,
  19784. // and the start always gets applied.
  19785. //
  19786. // But that's always going to be $ if it's the ending pattern, or nothing,
  19787. // so the caller can just attach $ at the end of the pattern when building.
  19788. //
  19789. // So the todo is:
  19790. // - better detect what kind of start is needed
  19791. // - return both flavors of starting pattern
  19792. // - attach $ at the end of the pattern when creating the actual RegExp
  19793. //
  19794. // Ah, but wait, no, that all only applies to the root when the first pattern
  19795. // is not an extglob. If the first pattern IS an extglob, then we need all
  19796. // that dot prevention biz to live in the extglob portions, because eg
  19797. // +(*|.x*) can match .xy but not .yx.
  19798. //
  19799. // So, return the two flavors if it's #root and the first child is not an
  19800. // AST, otherwise leave it to the child AST to handle it, and there,
  19801. // use the (?:^|/) style of start binding.
  19802. //
  19803. // Even simplified further:
  19804. // - Since the start for a join is eg /(?!\.) and the start for a part
  19805. // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
  19806. // or start or whatever) and prepend ^ or / at the Regexp construction.
  19807. toRegExpSource(allowDot) {
  19808. const dot = allowDot ?? !!this.#options.dot;
  19809. if (this.#root === this) {
  19810. this.#flatten();
  19811. this.#fillNegs();
  19812. }
  19813. if (!isExtglobAST(this)) {
  19814. const noEmpty = this.isStart() &&
  19815. this.isEnd() &&
  19816. !this.#parts.some(s => typeof s !== 'string');
  19817. const src = this.#parts
  19818. .map(p => {
  19819. const [re, _, hasMagic, uflag] = typeof p === 'string' ?
  19820. _a.#parseGlob(p, this.#hasMagic, noEmpty)
  19821. : p.toRegExpSource(allowDot);
  19822. this.#hasMagic = this.#hasMagic || hasMagic;
  19823. this.#uflag = this.#uflag || uflag;
  19824. return re;
  19825. })
  19826. .join('');
  19827. let start = '';
  19828. if (this.isStart()) {
  19829. if (typeof this.#parts[0] === 'string') {
  19830. // this is the string that will match the start of the pattern,
  19831. // so we need to protect against dots and such.
  19832. // '.' and '..' cannot match unless the pattern is that exactly,
  19833. // even if it starts with . or dot:true is set.
  19834. const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
  19835. if (!dotTravAllowed) {
  19836. const aps = addPatternStart;
  19837. // check if we have a possibility of matching . or ..,
  19838. // and prevent that.
  19839. const needNoTrav =
  19840. // dots are allowed, and the pattern starts with [ or .
  19841. (dot && aps.has(src.charAt(0))) ||
  19842. // the pattern starts with \., and then [ or .
  19843. (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
  19844. // the pattern starts with \.\., and then [ or .
  19845. (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
  19846. // no need to prevent dots if it can't match a dot, or if a
  19847. // sub-pattern will be preventing it anyway.
  19848. const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
  19849. start =
  19850. needNoTrav ? startNoTraversal
  19851. : needNoDot ? startNoDot
  19852. : '';
  19853. }
  19854. }
  19855. }
  19856. // append the "end of path portion" pattern to negation tails
  19857. let end = '';
  19858. if (this.isEnd() &&
  19859. this.#root.#filledNegs &&
  19860. this.#parent?.type === '!') {
  19861. end = '(?:$|\\/)';
  19862. }
  19863. const final = start + src + end;
  19864. return [
  19865. final,
  19866. unescape(src),
  19867. (this.#hasMagic = !!this.#hasMagic),
  19868. this.#uflag,
  19869. ];
  19870. }
  19871. // We need to calculate the body *twice* if it's a repeat pattern
  19872. // at the start, once in nodot mode, then again in dot mode, so a
  19873. // pattern like *(?) can match 'x.y'
  19874. const repeated = this.type === '*' || this.type === '+';
  19875. // some kind of extglob
  19876. const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
  19877. let body = this.#partsToRegExp(dot);
  19878. if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
  19879. // invalid extglob, has to at least be *something* present, if it's
  19880. // the entire path portion.
  19881. const s = this.toString();
  19882. const me = this;
  19883. me.#parts = [s];
  19884. me.type = null;
  19885. me.#hasMagic = undefined;
  19886. return [s, unescape(this.toString()), false, false];
  19887. }
  19888. let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ?
  19889. ''
  19890. : this.#partsToRegExp(true);
  19891. if (bodyDotAllowed === body) {
  19892. bodyDotAllowed = '';
  19893. }
  19894. if (bodyDotAllowed) {
  19895. body = `(?:${body})(?:${bodyDotAllowed})*?`;
  19896. }
  19897. // an empty !() is exactly equivalent to a starNoEmpty
  19898. let final = '';
  19899. if (this.type === '!' && this.#emptyExt) {
  19900. final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
  19901. }
  19902. else {
  19903. const close = this.type === '!' ?
  19904. // !() must match something,but !(x) can match ''
  19905. '))' +
  19906. (this.isStart() && !dot && !allowDot ? startNoDot : '') +
  19907. star$1 +
  19908. ')'
  19909. : this.type === '@' ? ')'
  19910. : this.type === '?' ? ')?'
  19911. : this.type === '+' && bodyDotAllowed ? ')'
  19912. : this.type === '*' && bodyDotAllowed ? `)?`
  19913. : `)${this.type}`;
  19914. final = start + body + close;
  19915. }
  19916. return [
  19917. final,
  19918. unescape(body),
  19919. (this.#hasMagic = !!this.#hasMagic),
  19920. this.#uflag,
  19921. ];
  19922. }
  19923. #flatten() {
  19924. if (!isExtglobAST(this)) {
  19925. for (const p of this.#parts) {
  19926. if (typeof p === 'object') {
  19927. p.#flatten();
  19928. }
  19929. }
  19930. }
  19931. else {
  19932. // do up to 10 passes to flatten as much as possible
  19933. let iterations = 0;
  19934. let done = false;
  19935. do {
  19936. done = true;
  19937. for (let i = 0; i < this.#parts.length; i++) {
  19938. const c = this.#parts[i];
  19939. if (typeof c === 'object') {
  19940. c.#flatten();
  19941. if (this.#canAdopt(c)) {
  19942. done = false;
  19943. this.#adopt(c, i);
  19944. }
  19945. else if (this.#canAdoptWithSpace(c)) {
  19946. done = false;
  19947. this.#adoptWithSpace(c, i);
  19948. }
  19949. else if (this.#canUsurp(c)) {
  19950. done = false;
  19951. this.#usurp(c);
  19952. }
  19953. }
  19954. }
  19955. } while (!done && ++iterations < 10);
  19956. }
  19957. this.#toString = undefined;
  19958. }
  19959. #partsToRegExp(dot) {
  19960. return this.#parts
  19961. .map(p => {
  19962. // extglob ASTs should only contain parent ASTs
  19963. /* c8 ignore start */
  19964. if (typeof p === 'string') {
  19965. throw new Error('string type in extglob ast??');
  19966. }
  19967. /* c8 ignore stop */
  19968. // can ignore hasMagic, because extglobs are already always magic
  19969. const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
  19970. this.#uflag = this.#uflag || uflag;
  19971. return re;
  19972. })
  19973. .filter(p => !(this.isStart() && this.isEnd()) || !!p)
  19974. .join('|');
  19975. }
  19976. static #parseGlob(glob, hasMagic, noEmpty = false) {
  19977. let escaping = false;
  19978. let re = '';
  19979. let uflag = false;
  19980. // multiple stars that aren't globstars coalesce into one *
  19981. let inStar = false;
  19982. for (let i = 0; i < glob.length; i++) {
  19983. const c = glob.charAt(i);
  19984. if (escaping) {
  19985. escaping = false;
  19986. re += (reSpecials.has(c) ? '\\' : '') + c;
  19987. continue;
  19988. }
  19989. if (c === '*') {
  19990. if (inStar)
  19991. continue;
  19992. inStar = true;
  19993. re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star$1;
  19994. hasMagic = true;
  19995. continue;
  19996. }
  19997. else {
  19998. inStar = false;
  19999. }
  20000. if (c === '\\') {
  20001. if (i === glob.length - 1) {
  20002. re += '\\\\';
  20003. }
  20004. else {
  20005. escaping = true;
  20006. }
  20007. continue;
  20008. }
  20009. if (c === '[') {
  20010. const [src, needUflag, consumed, magic] = parseClass(glob, i);
  20011. if (consumed) {
  20012. re += src;
  20013. uflag = uflag || needUflag;
  20014. i += consumed - 1;
  20015. hasMagic = hasMagic || magic;
  20016. continue;
  20017. }
  20018. }
  20019. if (c === '?') {
  20020. re += qmark$1;
  20021. hasMagic = true;
  20022. continue;
  20023. }
  20024. re += regExpEscape$1(c);
  20025. }
  20026. return [re, unescape(glob), !!hasMagic, uflag];
  20027. }
  20028. }
  20029. _a = AST;
  20030. /**
  20031. * Escape all magic characters in a glob pattern.
  20032. *
  20033. * If the {@link MinimatchOptions.windowsPathsNoEscape}
  20034. * option is used, then characters are escaped by wrapping in `[]`, because
  20035. * a magic character wrapped in a character class can only be satisfied by
  20036. * that exact character. In this mode, `\` is _not_ escaped, because it is
  20037. * not interpreted as a magic character, but instead as a path separator.
  20038. *
  20039. * If the {@link MinimatchOptions.magicalBraces} option is used,
  20040. * then braces (`{` and `}`) will be escaped.
  20041. */
  20042. const escape = (s, { windowsPathsNoEscape = false, magicalBraces = false, } = {}) => {
  20043. // don't need to escape +@! because we escape the parens
  20044. // that make those magic, and escaping ! as [!] isn't valid,
  20045. // because [!]] is a valid glob class meaning not ']'.
  20046. if (magicalBraces) {
  20047. return windowsPathsNoEscape ?
  20048. s.replace(/[?*()[\]{}]/g, '[$&]')
  20049. : s.replace(/[?*()[\]\\{}]/g, '\\$&');
  20050. }
  20051. return windowsPathsNoEscape ?
  20052. s.replace(/[?*()[\]]/g, '[$&]')
  20053. : s.replace(/[?*()[\]\\]/g, '\\$&');
  20054. };
  20055. const minimatch = (p, pattern, options = {}) => {
  20056. assertValidPattern(pattern);
  20057. // shortcut: comments match nothing.
  20058. if (!options.nocomment && pattern.charAt(0) === '#') {
  20059. return false;
  20060. }
  20061. return new Minimatch(pattern, options).match(p);
  20062. };
  20063. // Optimized checking for the most common glob patterns.
  20064. const starDotExtRE = /^\*+([^+@!?*[(]*)$/;
  20065. const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
  20066. const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
  20067. const starDotExtTestNocase = (ext) => {
  20068. ext = ext.toLowerCase();
  20069. return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
  20070. };
  20071. const starDotExtTestNocaseDot = (ext) => {
  20072. ext = ext.toLowerCase();
  20073. return (f) => f.toLowerCase().endsWith(ext);
  20074. };
  20075. const starDotStarRE = /^\*+\.\*+$/;
  20076. const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
  20077. const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
  20078. const dotStarRE = /^\.\*+$/;
  20079. const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
  20080. const starRE = /^\*+$/;
  20081. const starTest = (f) => f.length !== 0 && !f.startsWith('.');
  20082. const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
  20083. const qmarksRE = /^\?+([^+@!?*[(]*)?$/;
  20084. const qmarksTestNocase = ([$0, ext = '']) => {
  20085. const noext = qmarksTestNoExt([$0]);
  20086. if (!ext)
  20087. return noext;
  20088. ext = ext.toLowerCase();
  20089. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  20090. };
  20091. const qmarksTestNocaseDot = ([$0, ext = '']) => {
  20092. const noext = qmarksTestNoExtDot([$0]);
  20093. if (!ext)
  20094. return noext;
  20095. ext = ext.toLowerCase();
  20096. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  20097. };
  20098. const qmarksTestDot = ([$0, ext = '']) => {
  20099. const noext = qmarksTestNoExtDot([$0]);
  20100. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  20101. };
  20102. const qmarksTest = ([$0, ext = '']) => {
  20103. const noext = qmarksTestNoExt([$0]);
  20104. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  20105. };
  20106. const qmarksTestNoExt = ([$0]) => {
  20107. const len = $0.length;
  20108. return (f) => f.length === len && !f.startsWith('.');
  20109. };
  20110. const qmarksTestNoExtDot = ([$0]) => {
  20111. const len = $0.length;
  20112. return (f) => f.length === len && f !== '.' && f !== '..';
  20113. };
  20114. /* c8 ignore start */
  20115. const defaultPlatform = (typeof process === 'object' && process ?
  20116. (typeof process.env === 'object' &&
  20117. process.env &&
  20118. process.env.__MINIMATCH_TESTING_PLATFORM__) ||
  20119. process.platform
  20120. : 'posix');
  20121. const path = {
  20122. win32: { sep: '\\' },
  20123. posix: { sep: '/' },
  20124. };
  20125. /* c8 ignore stop */
  20126. const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
  20127. minimatch.sep = sep;
  20128. const GLOBSTAR = Symbol('globstar **');
  20129. minimatch.GLOBSTAR = GLOBSTAR;
  20130. // any single thing other than /
  20131. // don't need to escape / when using new RegExp()
  20132. const qmark = '[^/]';
  20133. // * => any number of characters
  20134. const star = qmark + '*?';
  20135. // ** when dots are allowed. Anything goes, except .. and .
  20136. // not (^ or / followed by one or two dots followed by $ or /),
  20137. // followed by anything, any number of times.
  20138. const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
  20139. // not a ^ or / followed by a dot,
  20140. // followed by anything, any number of times.
  20141. const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
  20142. const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
  20143. minimatch.filter = filter;
  20144. const ext = (a, b = {}) => Object.assign({}, a, b);
  20145. const defaults = (def) => {
  20146. if (!def || typeof def !== 'object' || !Object.keys(def).length) {
  20147. return minimatch;
  20148. }
  20149. const orig = minimatch;
  20150. const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
  20151. return Object.assign(m, {
  20152. Minimatch: class Minimatch extends orig.Minimatch {
  20153. constructor(pattern, options = {}) {
  20154. super(pattern, ext(def, options));
  20155. }
  20156. static defaults(options) {
  20157. return orig.defaults(ext(def, options)).Minimatch;
  20158. }
  20159. },
  20160. AST: class AST extends orig.AST {
  20161. /* c8 ignore start */
  20162. constructor(type, parent, options = {}) {
  20163. super(type, parent, ext(def, options));
  20164. }
  20165. /* c8 ignore stop */
  20166. static fromGlob(pattern, options = {}) {
  20167. return orig.AST.fromGlob(pattern, ext(def, options));
  20168. }
  20169. },
  20170. unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
  20171. escape: (s, options = {}) => orig.escape(s, ext(def, options)),
  20172. filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
  20173. defaults: (options) => orig.defaults(ext(def, options)),
  20174. makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
  20175. braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
  20176. match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
  20177. sep: orig.sep,
  20178. GLOBSTAR: GLOBSTAR,
  20179. });
  20180. };
  20181. minimatch.defaults = defaults;
  20182. // Brace expansion:
  20183. // a{b,c}d -> abd acd
  20184. // a{b,}c -> abc ac
  20185. // a{0..3}d -> a0d a1d a2d a3d
  20186. // a{b,c{d,e}f}g -> abg acdfg acefg
  20187. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  20188. //
  20189. // Invalid sets are not expanded.
  20190. // a{2..}b -> a{2..}b
  20191. // a{b}c -> a{b}c
  20192. const braceExpand = (pattern, options = {}) => {
  20193. assertValidPattern(pattern);
  20194. // Thanks to Yeting Li <https://github.com/yetingli> for
  20195. // improving this regexp to avoid a ReDOS vulnerability.
  20196. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
  20197. // shortcut. no need to expand.
  20198. return [pattern];
  20199. }
  20200. return expand(pattern, { max: options.braceExpandMax });
  20201. };
  20202. minimatch.braceExpand = braceExpand;
  20203. // parse a component of the expanded set.
  20204. // At this point, no pattern may contain "/" in it
  20205. // so we're going to return a 2d array, where each entry is the full
  20206. // pattern, split on '/', and then turned into a regular expression.
  20207. // A regexp is made at the end which joins each array with an
  20208. // escaped /, and another full one which joins each regexp with |.
  20209. //
  20210. // Following the lead of Bash 4.1, note that "**" only has special meaning
  20211. // when it is the *only* thing in a path portion. Otherwise, any series
  20212. // of * is equivalent to a single *. Globstar behavior is enabled by
  20213. // default, and can be disabled by setting options.noglobstar.
  20214. const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
  20215. minimatch.makeRe = makeRe;
  20216. const match = (list, pattern, options = {}) => {
  20217. const mm = new Minimatch(pattern, options);
  20218. list = list.filter(f => mm.match(f));
  20219. if (mm.options.nonull && !list.length) {
  20220. list.push(pattern);
  20221. }
  20222. return list;
  20223. };
  20224. minimatch.match = match;
  20225. // replace stuff like \* with *
  20226. const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
  20227. const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  20228. class Minimatch {
  20229. options;
  20230. set;
  20231. pattern;
  20232. windowsPathsNoEscape;
  20233. nonegate;
  20234. negate;
  20235. comment;
  20236. empty;
  20237. preserveMultipleSlashes;
  20238. partial;
  20239. globSet;
  20240. globParts;
  20241. nocase;
  20242. isWindows;
  20243. platform;
  20244. windowsNoMagicRoot;
  20245. maxGlobstarRecursion;
  20246. regexp;
  20247. constructor(pattern, options = {}) {
  20248. assertValidPattern(pattern);
  20249. options = options || {};
  20250. this.options = options;
  20251. this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? 200;
  20252. this.pattern = pattern;
  20253. this.platform = options.platform || defaultPlatform;
  20254. this.isWindows = this.platform === 'win32';
  20255. // avoid the annoying deprecation flag lol
  20256. const awe = ('allowWindow' + 'sEscape');
  20257. this.windowsPathsNoEscape =
  20258. !!options.windowsPathsNoEscape || options[awe] === false;
  20259. if (this.windowsPathsNoEscape) {
  20260. this.pattern = this.pattern.replace(/\\/g, '/');
  20261. }
  20262. this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
  20263. this.regexp = null;
  20264. this.negate = false;
  20265. this.nonegate = !!options.nonegate;
  20266. this.comment = false;
  20267. this.empty = false;
  20268. this.partial = !!options.partial;
  20269. this.nocase = !!this.options.nocase;
  20270. this.windowsNoMagicRoot =
  20271. options.windowsNoMagicRoot !== undefined ?
  20272. options.windowsNoMagicRoot
  20273. : !!(this.isWindows && this.nocase);
  20274. this.globSet = [];
  20275. this.globParts = [];
  20276. this.set = [];
  20277. // make the set of regexps etc.
  20278. this.make();
  20279. }
  20280. hasMagic() {
  20281. if (this.options.magicalBraces && this.set.length > 1) {
  20282. return true;
  20283. }
  20284. for (const pattern of this.set) {
  20285. for (const part of pattern) {
  20286. if (typeof part !== 'string')
  20287. return true;
  20288. }
  20289. }
  20290. return false;
  20291. }
  20292. debug(..._) { }
  20293. make() {
  20294. const pattern = this.pattern;
  20295. const options = this.options;
  20296. // empty patterns and comments match nothing.
  20297. if (!options.nocomment && pattern.charAt(0) === '#') {
  20298. this.comment = true;
  20299. return;
  20300. }
  20301. if (!pattern) {
  20302. this.empty = true;
  20303. return;
  20304. }
  20305. // step 1: figure out negation, etc.
  20306. this.parseNegate();
  20307. // step 2: expand braces
  20308. this.globSet = [...new Set(this.braceExpand())];
  20309. if (options.debug) {
  20310. //oxlint-disable-next-line no-console
  20311. this.debug = (...args) => console.error(...args);
  20312. }
  20313. this.debug(this.pattern, this.globSet);
  20314. // step 3: now we have a set, so turn each one into a series of
  20315. // path-portion matching patterns.
  20316. // These will be regexps, except in the case of "**", which is
  20317. // set to the GLOBSTAR object for globstar behavior,
  20318. // and will not contain any / characters
  20319. //
  20320. // First, we preprocess to make the glob pattern sets a bit simpler
  20321. // and deduped. There are some perf-killing patterns that can cause
  20322. // problems with a glob walk, but we can simplify them down a bit.
  20323. const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
  20324. this.globParts = this.preprocess(rawGlobParts);
  20325. this.debug(this.pattern, this.globParts);
  20326. // glob --> regexps
  20327. let set = this.globParts.map((s, _, __) => {
  20328. if (this.isWindows && this.windowsNoMagicRoot) {
  20329. // check if it's a drive or unc path.
  20330. const isUNC = s[0] === '' &&
  20331. s[1] === '' &&
  20332. (s[2] === '?' || !globMagic.test(s[2])) &&
  20333. !globMagic.test(s[3]);
  20334. const isDrive = /^[a-z]:/i.test(s[0]);
  20335. if (isUNC) {
  20336. return [
  20337. ...s.slice(0, 4),
  20338. ...s.slice(4).map(ss => this.parse(ss)),
  20339. ];
  20340. }
  20341. else if (isDrive) {
  20342. return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
  20343. }
  20344. }
  20345. return s.map(ss => this.parse(ss));
  20346. });
  20347. this.debug(this.pattern, set);
  20348. // filter out everything that didn't compile properly.
  20349. this.set = set.filter(s => s.indexOf(false) === -1);
  20350. // do not treat the ? in UNC paths as magic
  20351. if (this.isWindows) {
  20352. for (let i = 0; i < this.set.length; i++) {
  20353. const p = this.set[i];
  20354. if (p[0] === '' &&
  20355. p[1] === '' &&
  20356. this.globParts[i][2] === '?' &&
  20357. typeof p[3] === 'string' &&
  20358. /^[a-z]:$/i.test(p[3])) {
  20359. p[2] = '?';
  20360. }
  20361. }
  20362. }
  20363. this.debug(this.pattern, this.set);
  20364. }
  20365. // various transforms to equivalent pattern sets that are
  20366. // faster to process in a filesystem walk. The goal is to
  20367. // eliminate what we can, and push all ** patterns as far
  20368. // to the right as possible, even if it increases the number
  20369. // of patterns that we have to process.
  20370. preprocess(globParts) {
  20371. // if we're not in globstar mode, then turn ** into *
  20372. if (this.options.noglobstar) {
  20373. for (const partset of globParts) {
  20374. for (let j = 0; j < partset.length; j++) {
  20375. if (partset[j] === '**') {
  20376. partset[j] = '*';
  20377. }
  20378. }
  20379. }
  20380. }
  20381. const { optimizationLevel = 1 } = this.options;
  20382. if (optimizationLevel >= 2) {
  20383. // aggressive optimization for the purpose of fs walking
  20384. globParts = this.firstPhasePreProcess(globParts);
  20385. globParts = this.secondPhasePreProcess(globParts);
  20386. }
  20387. else if (optimizationLevel >= 1) {
  20388. // just basic optimizations to remove some .. parts
  20389. globParts = this.levelOneOptimize(globParts);
  20390. }
  20391. else {
  20392. // just collapse multiple ** portions into one
  20393. globParts = this.adjascentGlobstarOptimize(globParts);
  20394. }
  20395. return globParts;
  20396. }
  20397. // just get rid of adjascent ** portions
  20398. adjascentGlobstarOptimize(globParts) {
  20399. return globParts.map(parts => {
  20400. let gs = -1;
  20401. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  20402. let i = gs;
  20403. while (parts[i + 1] === '**') {
  20404. i++;
  20405. }
  20406. if (i !== gs) {
  20407. parts.splice(gs, i - gs);
  20408. }
  20409. }
  20410. return parts;
  20411. });
  20412. }
  20413. // get rid of adjascent ** and resolve .. portions
  20414. levelOneOptimize(globParts) {
  20415. return globParts.map(parts => {
  20416. parts = parts.reduce((set, part) => {
  20417. const prev = set[set.length - 1];
  20418. if (part === '**' && prev === '**') {
  20419. return set;
  20420. }
  20421. if (part === '..') {
  20422. if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
  20423. set.pop();
  20424. return set;
  20425. }
  20426. }
  20427. set.push(part);
  20428. return set;
  20429. }, []);
  20430. return parts.length === 0 ? [''] : parts;
  20431. });
  20432. }
  20433. levelTwoFileOptimize(parts) {
  20434. if (!Array.isArray(parts)) {
  20435. parts = this.slashSplit(parts);
  20436. }
  20437. let didSomething = false;
  20438. do {
  20439. didSomething = false;
  20440. // <pre>/<e>/<rest> -> <pre>/<rest>
  20441. if (!this.preserveMultipleSlashes) {
  20442. for (let i = 1; i < parts.length - 1; i++) {
  20443. const p = parts[i];
  20444. // don't squeeze out UNC patterns
  20445. if (i === 1 && p === '' && parts[0] === '')
  20446. continue;
  20447. if (p === '.' || p === '') {
  20448. didSomething = true;
  20449. parts.splice(i, 1);
  20450. i--;
  20451. }
  20452. }
  20453. if (parts[0] === '.' &&
  20454. parts.length === 2 &&
  20455. (parts[1] === '.' || parts[1] === '')) {
  20456. didSomething = true;
  20457. parts.pop();
  20458. }
  20459. }
  20460. // <pre>/<p>/../<rest> -> <pre>/<rest>
  20461. let dd = 0;
  20462. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  20463. const p = parts[dd - 1];
  20464. if (p &&
  20465. p !== '.' &&
  20466. p !== '..' &&
  20467. p !== '**' &&
  20468. !(this.isWindows && /^[a-z]:$/i.test(p))) {
  20469. didSomething = true;
  20470. parts.splice(dd - 1, 2);
  20471. dd -= 2;
  20472. }
  20473. }
  20474. } while (didSomething);
  20475. return parts.length === 0 ? [''] : parts;
  20476. }
  20477. // First phase: single-pattern processing
  20478. // <pre> is 1 or more portions
  20479. // <rest> is 1 or more portions
  20480. // <p> is any portion other than ., .., '', or **
  20481. // <e> is . or ''
  20482. //
  20483. // **/.. is *brutal* for filesystem walking performance, because
  20484. // it effectively resets the recursive walk each time it occurs,
  20485. // and ** cannot be reduced out by a .. pattern part like a regexp
  20486. // or most strings (other than .., ., and '') can be.
  20487. //
  20488. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  20489. // <pre>/<e>/<rest> -> <pre>/<rest>
  20490. // <pre>/<p>/../<rest> -> <pre>/<rest>
  20491. // **/**/<rest> -> **/<rest>
  20492. //
  20493. // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
  20494. // this WOULD be allowed if ** did follow symlinks, or * didn't
  20495. firstPhasePreProcess(globParts) {
  20496. let didSomething = false;
  20497. do {
  20498. didSomething = false;
  20499. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  20500. for (let parts of globParts) {
  20501. let gs = -1;
  20502. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  20503. let gss = gs;
  20504. while (parts[gss + 1] === '**') {
  20505. // <pre>/**/**/<rest> -> <pre>/**/<rest>
  20506. gss++;
  20507. }
  20508. // eg, if gs is 2 and gss is 4, that means we have 3 **
  20509. // parts, and can remove 2 of them.
  20510. if (gss > gs) {
  20511. parts.splice(gs + 1, gss - gs);
  20512. }
  20513. let next = parts[gs + 1];
  20514. const p = parts[gs + 2];
  20515. const p2 = parts[gs + 3];
  20516. if (next !== '..')
  20517. continue;
  20518. if (!p ||
  20519. p === '.' ||
  20520. p === '..' ||
  20521. !p2 ||
  20522. p2 === '.' ||
  20523. p2 === '..') {
  20524. continue;
  20525. }
  20526. didSomething = true;
  20527. // edit parts in place, and push the new one
  20528. parts.splice(gs, 1);
  20529. const other = parts.slice(0);
  20530. other[gs] = '**';
  20531. globParts.push(other);
  20532. gs--;
  20533. }
  20534. // <pre>/<e>/<rest> -> <pre>/<rest>
  20535. if (!this.preserveMultipleSlashes) {
  20536. for (let i = 1; i < parts.length - 1; i++) {
  20537. const p = parts[i];
  20538. // don't squeeze out UNC patterns
  20539. if (i === 1 && p === '' && parts[0] === '')
  20540. continue;
  20541. if (p === '.' || p === '') {
  20542. didSomething = true;
  20543. parts.splice(i, 1);
  20544. i--;
  20545. }
  20546. }
  20547. if (parts[0] === '.' &&
  20548. parts.length === 2 &&
  20549. (parts[1] === '.' || parts[1] === '')) {
  20550. didSomething = true;
  20551. parts.pop();
  20552. }
  20553. }
  20554. // <pre>/<p>/../<rest> -> <pre>/<rest>
  20555. let dd = 0;
  20556. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  20557. const p = parts[dd - 1];
  20558. if (p && p !== '.' && p !== '..' && p !== '**') {
  20559. didSomething = true;
  20560. const needDot = dd === 1 && parts[dd + 1] === '**';
  20561. const splin = needDot ? ['.'] : [];
  20562. parts.splice(dd - 1, 2, ...splin);
  20563. if (parts.length === 0)
  20564. parts.push('');
  20565. dd -= 2;
  20566. }
  20567. }
  20568. }
  20569. } while (didSomething);
  20570. return globParts;
  20571. }
  20572. // second phase: multi-pattern dedupes
  20573. // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
  20574. // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
  20575. // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
  20576. //
  20577. // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
  20578. // ^-- not valid because ** doens't follow symlinks
  20579. secondPhasePreProcess(globParts) {
  20580. for (let i = 0; i < globParts.length - 1; i++) {
  20581. for (let j = i + 1; j < globParts.length; j++) {
  20582. const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
  20583. if (matched) {
  20584. globParts[i] = [];
  20585. globParts[j] = matched;
  20586. break;
  20587. }
  20588. }
  20589. }
  20590. return globParts.filter(gs => gs.length);
  20591. }
  20592. partsMatch(a, b, emptyGSMatch = false) {
  20593. let ai = 0;
  20594. let bi = 0;
  20595. let result = [];
  20596. let which = '';
  20597. while (ai < a.length && bi < b.length) {
  20598. if (a[ai] === b[bi]) {
  20599. result.push(which === 'b' ? b[bi] : a[ai]);
  20600. ai++;
  20601. bi++;
  20602. }
  20603. else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
  20604. result.push(a[ai]);
  20605. ai++;
  20606. }
  20607. else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
  20608. result.push(b[bi]);
  20609. bi++;
  20610. }
  20611. else if (a[ai] === '*' &&
  20612. b[bi] &&
  20613. (this.options.dot || !b[bi].startsWith('.')) &&
  20614. b[bi] !== '**') {
  20615. if (which === 'b')
  20616. return false;
  20617. which = 'a';
  20618. result.push(a[ai]);
  20619. ai++;
  20620. bi++;
  20621. }
  20622. else if (b[bi] === '*' &&
  20623. a[ai] &&
  20624. (this.options.dot || !a[ai].startsWith('.')) &&
  20625. a[ai] !== '**') {
  20626. if (which === 'a')
  20627. return false;
  20628. which = 'b';
  20629. result.push(b[bi]);
  20630. ai++;
  20631. bi++;
  20632. }
  20633. else {
  20634. return false;
  20635. }
  20636. }
  20637. // if we fall out of the loop, it means they two are identical
  20638. // as long as their lengths match
  20639. return a.length === b.length && result;
  20640. }
  20641. parseNegate() {
  20642. if (this.nonegate)
  20643. return;
  20644. const pattern = this.pattern;
  20645. let negate = false;
  20646. let negateOffset = 0;
  20647. for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
  20648. negate = !negate;
  20649. negateOffset++;
  20650. }
  20651. if (negateOffset)
  20652. this.pattern = pattern.slice(negateOffset);
  20653. this.negate = negate;
  20654. }
  20655. // set partial to true to test if, for example,
  20656. // "/a/b" matches the start of "/*/b/*/d"
  20657. // Partial means, if you run out of file before you run
  20658. // out of pattern, then that's fine, as long as all
  20659. // the parts match.
  20660. matchOne(file, pattern, partial = false) {
  20661. let fileStartIndex = 0;
  20662. let patternStartIndex = 0;
  20663. // UNC paths like //?/X:/... can match X:/... and vice versa
  20664. // Drive letters in absolute drive or unc paths are always compared
  20665. // case-insensitively.
  20666. if (this.isWindows) {
  20667. const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
  20668. const fileUNC = !fileDrive &&
  20669. file[0] === '' &&
  20670. file[1] === '' &&
  20671. file[2] === '?' &&
  20672. /^[a-z]:$/i.test(file[3]);
  20673. const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
  20674. const patternUNC = !patternDrive &&
  20675. pattern[0] === '' &&
  20676. pattern[1] === '' &&
  20677. pattern[2] === '?' &&
  20678. typeof pattern[3] === 'string' &&
  20679. /^[a-z]:$/i.test(pattern[3]);
  20680. const fdi = fileUNC ? 3
  20681. : fileDrive ? 0
  20682. : undefined;
  20683. const pdi = patternUNC ? 3
  20684. : patternDrive ? 0
  20685. : undefined;
  20686. if (typeof fdi === 'number' && typeof pdi === 'number') {
  20687. const [fd, pd] = [
  20688. file[fdi],
  20689. pattern[pdi],
  20690. ];
  20691. // start matching at the drive letter index of each
  20692. if (fd.toLowerCase() === pd.toLowerCase()) {
  20693. pattern[pdi] = fd;
  20694. patternStartIndex = pdi;
  20695. fileStartIndex = fdi;
  20696. }
  20697. }
  20698. }
  20699. // resolve and reduce . and .. portions in the file as well.
  20700. // don't need to do the second phase, because it's only one string[]
  20701. const { optimizationLevel = 1 } = this.options;
  20702. if (optimizationLevel >= 2) {
  20703. file = this.levelTwoFileOptimize(file);
  20704. }
  20705. if (pattern.includes(GLOBSTAR)) {
  20706. return this.#matchGlobstar(file, pattern, partial, fileStartIndex, patternStartIndex);
  20707. }
  20708. return this.#matchOne(file, pattern, partial, fileStartIndex, patternStartIndex);
  20709. }
  20710. #matchGlobstar(file, pattern, partial, fileIndex, patternIndex) {
  20711. // split the pattern into head, tail, and middle of ** delimited parts
  20712. const firstgs = pattern.indexOf(GLOBSTAR, patternIndex);
  20713. const lastgs = pattern.lastIndexOf(GLOBSTAR);
  20714. // split the pattern up into globstar-delimited sections
  20715. // the tail has to be at the end, and the others just have
  20716. // to be found in order from the head.
  20717. const [head, body, tail] = partial ?
  20718. [
  20719. pattern.slice(patternIndex, firstgs),
  20720. pattern.slice(firstgs + 1),
  20721. [],
  20722. ]
  20723. : [
  20724. pattern.slice(patternIndex, firstgs),
  20725. pattern.slice(firstgs + 1, lastgs),
  20726. pattern.slice(lastgs + 1),
  20727. ];
  20728. // check the head, from the current file/pattern index.
  20729. if (head.length) {
  20730. const fileHead = file.slice(fileIndex, fileIndex + head.length);
  20731. if (!this.#matchOne(fileHead, head, partial, 0, 0)) {
  20732. return false;
  20733. }
  20734. fileIndex += head.length;
  20735. patternIndex += head.length;
  20736. }
  20737. // now we know the head matches!
  20738. // if the last portion is not empty, it MUST match the end
  20739. // check the tail
  20740. let fileTailMatch = 0;
  20741. if (tail.length) {
  20742. // if head + tail > file, then we cannot possibly match
  20743. if (tail.length + fileIndex > file.length)
  20744. return false;
  20745. // try to match the tail
  20746. let tailStart = file.length - tail.length;
  20747. if (this.#matchOne(file, tail, partial, tailStart, 0)) {
  20748. fileTailMatch = tail.length;
  20749. }
  20750. else {
  20751. // affordance for stuff like a/**/* matching a/b/
  20752. // if the last file portion is '', and there's more to the pattern
  20753. // then try without the '' bit.
  20754. if (file[file.length - 1] !== '' ||
  20755. fileIndex + tail.length === file.length) {
  20756. return false;
  20757. }
  20758. tailStart--;
  20759. if (!this.#matchOne(file, tail, partial, tailStart, 0)) {
  20760. return false;
  20761. }
  20762. fileTailMatch = tail.length + 1;
  20763. }
  20764. }
  20765. // now we know the tail matches!
  20766. // the middle is zero or more portions wrapped in **, possibly
  20767. // containing more ** sections.
  20768. // so a/**/b/**/c/**/d has become **/b/**/c/**
  20769. // if it's empty, it means a/**/b, just verify we have no bad dots
  20770. // if there's no tail, so it ends on /**, then we must have *something*
  20771. // after the head, or it's not a matc
  20772. if (!body.length) {
  20773. let sawSome = !!fileTailMatch;
  20774. for (let i = fileIndex; i < file.length - fileTailMatch; i++) {
  20775. const f = String(file[i]);
  20776. sawSome = true;
  20777. if (f === '.' ||
  20778. f === '..' ||
  20779. (!this.options.dot && f.startsWith('.'))) {
  20780. return false;
  20781. }
  20782. }
  20783. // in partial mode, we just need to get past all file parts
  20784. return partial || sawSome;
  20785. }
  20786. // now we know that there's one or more body sections, which can
  20787. // be matched anywhere from the 0 index (because the head was pruned)
  20788. // through to the length-fileTailMatch index.
  20789. // split the body up into sections, and note the minimum index it can
  20790. // be found at (start with the length of all previous segments)
  20791. // [section, before, after]
  20792. const bodySegments = [[[], 0]];
  20793. let currentBody = bodySegments[0];
  20794. let nonGsParts = 0;
  20795. const nonGsPartsSums = [0];
  20796. for (const b of body) {
  20797. if (b === GLOBSTAR) {
  20798. nonGsPartsSums.push(nonGsParts);
  20799. currentBody = [[], 0];
  20800. bodySegments.push(currentBody);
  20801. }
  20802. else {
  20803. currentBody[0].push(b);
  20804. nonGsParts++;
  20805. }
  20806. }
  20807. let i = bodySegments.length - 1;
  20808. const fileLength = file.length - fileTailMatch;
  20809. for (const b of bodySegments) {
  20810. b[1] = fileLength - (nonGsPartsSums[i--] + b[0].length);
  20811. }
  20812. return !!this.#matchGlobStarBodySections(file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch);
  20813. }
  20814. // return false for "nope, not matching"
  20815. // return null for "not matching, cannot keep trying"
  20816. #matchGlobStarBodySections(file,
  20817. // pattern section, last possible position for it
  20818. bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail) {
  20819. // take the first body segment, and walk from fileIndex to its "after"
  20820. // value at the end
  20821. // If it doesn't match at that position, we increment, until we hit
  20822. // that final possible position, and give up.
  20823. // If it does match, then advance and try to rest.
  20824. // If any of them fail we keep walking forward.
  20825. // this is still a bit recursively painful, but it's more constrained
  20826. // than previous implementations, because we never test something that
  20827. // can't possibly be a valid matching condition.
  20828. const bs = bodySegments[bodyIndex];
  20829. if (!bs) {
  20830. // just make sure that there's no bad dots
  20831. for (let i = fileIndex; i < file.length; i++) {
  20832. sawTail = true;
  20833. const f = file[i];
  20834. if (f === '.' ||
  20835. f === '..' ||
  20836. (!this.options.dot && f.startsWith('.'))) {
  20837. return false;
  20838. }
  20839. }
  20840. return sawTail;
  20841. }
  20842. // have a non-globstar body section to test
  20843. const [body, after] = bs;
  20844. while (fileIndex <= after) {
  20845. const m = this.#matchOne(file.slice(0, fileIndex + body.length), body, partial, fileIndex, 0);
  20846. // if limit exceeded, no match. intentional false negative,
  20847. // acceptable break in correctness for security.
  20848. if (m && globStarDepth < this.maxGlobstarRecursion) {
  20849. // match! see if the rest match. if so, we're done!
  20850. const sub = this.#matchGlobStarBodySections(file, bodySegments, fileIndex + body.length, bodyIndex + 1, partial, globStarDepth + 1, sawTail);
  20851. if (sub !== false) {
  20852. return sub;
  20853. }
  20854. }
  20855. const f = file[fileIndex];
  20856. if (f === '.' ||
  20857. f === '..' ||
  20858. (!this.options.dot && f.startsWith('.'))) {
  20859. return false;
  20860. }
  20861. fileIndex++;
  20862. }
  20863. // walked off. no point continuing
  20864. return partial || null;
  20865. }
  20866. #matchOne(file, pattern, partial, fileIndex, patternIndex) {
  20867. let fi;
  20868. let pi;
  20869. let pl;
  20870. let fl;
  20871. for (fi = fileIndex,
  20872. pi = patternIndex,
  20873. fl = file.length,
  20874. pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
  20875. this.debug('matchOne loop');
  20876. let p = pattern[pi];
  20877. let f = file[fi];
  20878. this.debug(pattern, p, f);
  20879. // should be impossible.
  20880. // some invalid regexp stuff in the set.
  20881. /* c8 ignore start */
  20882. if (p === false || p === GLOBSTAR) {
  20883. return false;
  20884. }
  20885. /* c8 ignore stop */
  20886. // something other than **
  20887. // non-magic patterns just have to match exactly
  20888. // patterns with magic have been turned into regexps.
  20889. let hit;
  20890. if (typeof p === 'string') {
  20891. hit = f === p;
  20892. this.debug('string match', p, f, hit);
  20893. }
  20894. else {
  20895. hit = p.test(f);
  20896. this.debug('pattern match', p, f, hit);
  20897. }
  20898. if (!hit)
  20899. return false;
  20900. }
  20901. // Note: ending in / means that we'll get a final ""
  20902. // at the end of the pattern. This can only match a
  20903. // corresponding "" at the end of the file.
  20904. // If the file ends in /, then it can only match a
  20905. // a pattern that ends in /, unless the pattern just
  20906. // doesn't have any more for it. But, a/b/ should *not*
  20907. // match "a/b/*", even though "" matches against the
  20908. // [^/]*? pattern, except in partial mode, where it might
  20909. // simply not be reached yet.
  20910. // However, a/b/ should still satisfy a/*
  20911. // now either we fell off the end of the pattern, or we're done.
  20912. if (fi === fl && pi === pl) {
  20913. // ran out of pattern and filename at the same time.
  20914. // an exact hit!
  20915. return true;
  20916. }
  20917. else if (fi === fl) {
  20918. // ran out of file, but still had pattern left.
  20919. // this is ok if we're doing the match as part of
  20920. // a glob fs traversal.
  20921. return partial;
  20922. }
  20923. else if (pi === pl) {
  20924. // ran out of pattern, still have file left.
  20925. // this is only acceptable if we're on the very last
  20926. // empty segment of a file with a trailing slash.
  20927. // a/* should match a/b/
  20928. return fi === fl - 1 && file[fi] === '';
  20929. /* c8 ignore start */
  20930. }
  20931. else {
  20932. // should be unreachable.
  20933. throw new Error('wtf?');
  20934. }
  20935. /* c8 ignore stop */
  20936. }
  20937. braceExpand() {
  20938. return braceExpand(this.pattern, this.options);
  20939. }
  20940. parse(pattern) {
  20941. assertValidPattern(pattern);
  20942. const options = this.options;
  20943. // shortcuts
  20944. if (pattern === '**')
  20945. return GLOBSTAR;
  20946. if (pattern === '')
  20947. return '';
  20948. // far and away, the most common glob pattern parts are
  20949. // *, *.*, and *.<ext> Add a fast check method for those.
  20950. let m;
  20951. let fastTest = null;
  20952. if ((m = pattern.match(starRE))) {
  20953. fastTest = options.dot ? starTestDot : starTest;
  20954. }
  20955. else if ((m = pattern.match(starDotExtRE))) {
  20956. fastTest = (options.nocase ?
  20957. options.dot ?
  20958. starDotExtTestNocaseDot
  20959. : starDotExtTestNocase
  20960. : options.dot ? starDotExtTestDot
  20961. : starDotExtTest)(m[1]);
  20962. }
  20963. else if ((m = pattern.match(qmarksRE))) {
  20964. fastTest = (options.nocase ?
  20965. options.dot ?
  20966. qmarksTestNocaseDot
  20967. : qmarksTestNocase
  20968. : options.dot ? qmarksTestDot
  20969. : qmarksTest)(m);
  20970. }
  20971. else if ((m = pattern.match(starDotStarRE))) {
  20972. fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
  20973. }
  20974. else if ((m = pattern.match(dotStarRE))) {
  20975. fastTest = dotStarTest;
  20976. }
  20977. const re = AST.fromGlob(pattern, this.options).toMMPattern();
  20978. if (fastTest && typeof re === 'object') {
  20979. // Avoids overriding in frozen environments
  20980. Reflect.defineProperty(re, 'test', { value: fastTest });
  20981. }
  20982. return re;
  20983. }
  20984. makeRe() {
  20985. if (this.regexp || this.regexp === false)
  20986. return this.regexp;
  20987. // at this point, this.set is a 2d array of partial
  20988. // pattern strings, or "**".
  20989. //
  20990. // It's better to use .match(). This function shouldn't
  20991. // be used, really, but it's pretty convenient sometimes,
  20992. // when you just want to work with a regex.
  20993. const set = this.set;
  20994. if (!set.length) {
  20995. this.regexp = false;
  20996. return this.regexp;
  20997. }
  20998. const options = this.options;
  20999. const twoStar = options.noglobstar ? star
  21000. : options.dot ? twoStarDot
  21001. : twoStarNoDot;
  21002. const flags = new Set(options.nocase ? ['i'] : []);
  21003. // regexpify non-globstar patterns
  21004. // if ** is only item, then we just do one twoStar
  21005. // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
  21006. // if ** is last, append (\/twoStar|) to previous
  21007. // if ** is in the middle, append (\/|\/twoStar\/) to previous
  21008. // then filter out GLOBSTAR symbols
  21009. let re = set
  21010. .map(pattern => {
  21011. const pp = pattern.map(p => {
  21012. if (p instanceof RegExp) {
  21013. for (const f of p.flags.split(''))
  21014. flags.add(f);
  21015. }
  21016. return (typeof p === 'string' ? regExpEscape(p)
  21017. : p === GLOBSTAR ? GLOBSTAR
  21018. : p._src);
  21019. });
  21020. pp.forEach((p, i) => {
  21021. const next = pp[i + 1];
  21022. const prev = pp[i - 1];
  21023. if (p !== GLOBSTAR || prev === GLOBSTAR) {
  21024. return;
  21025. }
  21026. if (prev === undefined) {
  21027. if (next !== undefined && next !== GLOBSTAR) {
  21028. pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
  21029. }
  21030. else {
  21031. pp[i] = twoStar;
  21032. }
  21033. }
  21034. else if (next === undefined) {
  21035. pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + ')?';
  21036. }
  21037. else if (next !== GLOBSTAR) {
  21038. pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
  21039. pp[i + 1] = GLOBSTAR;
  21040. }
  21041. });
  21042. const filtered = pp.filter(p => p !== GLOBSTAR);
  21043. // For partial matches, we need to make the pattern match
  21044. // any prefix of the full path. We do this by generating
  21045. // alternative patterns that match progressively longer prefixes.
  21046. if (this.partial && filtered.length >= 1) {
  21047. const prefixes = [];
  21048. for (let i = 1; i <= filtered.length; i++) {
  21049. prefixes.push(filtered.slice(0, i).join('/'));
  21050. }
  21051. return '(?:' + prefixes.join('|') + ')';
  21052. }
  21053. return filtered.join('/');
  21054. })
  21055. .join('|');
  21056. // need to wrap in parens if we had more than one thing with |,
  21057. // otherwise only the first will be anchored to ^ and the last to $
  21058. const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
  21059. // must match entire pattern
  21060. // ending in a * or ** will make it less strict.
  21061. re = '^' + open + re + close + '$';
  21062. // In partial mode, '/' should always match as it's a valid prefix for any pattern
  21063. if (this.partial) {
  21064. re = '^(?:\\/|' + open + re.slice(1, -1) + close + ')$';
  21065. }
  21066. // can match anything, as long as it's not this.
  21067. if (this.negate)
  21068. re = '^(?!' + re + ').+$';
  21069. try {
  21070. this.regexp = new RegExp(re, [...flags].join(''));
  21071. /* c8 ignore start */
  21072. }
  21073. catch {
  21074. // should be impossible
  21075. this.regexp = false;
  21076. }
  21077. /* c8 ignore stop */
  21078. return this.regexp;
  21079. }
  21080. slashSplit(p) {
  21081. // if p starts with // on windows, we preserve that
  21082. // so that UNC paths aren't broken. Otherwise, any number of
  21083. // / characters are coalesced into one, unless
  21084. // preserveMultipleSlashes is set to true.
  21085. if (this.preserveMultipleSlashes) {
  21086. return p.split('/');
  21087. }
  21088. else if (this.isWindows && /^\/\/[^/]+/.test(p)) {
  21089. // add an extra '' for the one we lose
  21090. return ['', ...p.split(/\/+/)];
  21091. }
  21092. else {
  21093. return p.split(/\/+/);
  21094. }
  21095. }
  21096. match(f, partial = this.partial) {
  21097. this.debug('match', f, this.pattern);
  21098. // short-circuit in the case of busted things.
  21099. // comments, etc.
  21100. if (this.comment) {
  21101. return false;
  21102. }
  21103. if (this.empty) {
  21104. return f === '';
  21105. }
  21106. if (f === '/' && partial) {
  21107. return true;
  21108. }
  21109. const options = this.options;
  21110. // windows: need to use /, not \
  21111. if (this.isWindows) {
  21112. f = f.split('\\').join('/');
  21113. }
  21114. // treat the test path as a set of pathparts.
  21115. const ff = this.slashSplit(f);
  21116. this.debug(this.pattern, 'split', ff);
  21117. // just ONE of the pattern sets in this.set needs to match
  21118. // in order for it to be valid. If negating, then just one
  21119. // match means that we have failed.
  21120. // Either way, return on the first hit.
  21121. const set = this.set;
  21122. this.debug(this.pattern, 'set', set);
  21123. // Find the basename of the path by looking for the last non-empty segment
  21124. let filename = ff[ff.length - 1];
  21125. if (!filename) {
  21126. for (let i = ff.length - 2; !filename && i >= 0; i--) {
  21127. filename = ff[i];
  21128. }
  21129. }
  21130. for (const pattern of set) {
  21131. let file = ff;
  21132. if (options.matchBase && pattern.length === 1) {
  21133. file = [filename];
  21134. }
  21135. const hit = this.matchOne(file, pattern, partial);
  21136. if (hit) {
  21137. if (options.flipNegate) {
  21138. return true;
  21139. }
  21140. return !this.negate;
  21141. }
  21142. }
  21143. // didn't get any hits. this is success if it's a negative
  21144. // pattern, failure otherwise.
  21145. if (options.flipNegate) {
  21146. return false;
  21147. }
  21148. return this.negate;
  21149. }
  21150. static defaults(def) {
  21151. return minimatch.defaults(def).Minimatch;
  21152. }
  21153. }
  21154. /* c8 ignore stop */
  21155. minimatch.AST = AST;
  21156. minimatch.Minimatch = Minimatch;
  21157. minimatch.escape = escape;
  21158. minimatch.unescape = unescape;
  21159. class TypeScope {
  21160. constructor(filename, source, offset = 0, imports = /* @__PURE__ */ Object.create(null), types = /* @__PURE__ */ Object.create(null), declares = /* @__PURE__ */ Object.create(null)) {
  21161. this.filename = filename;
  21162. this.source = source;
  21163. this.offset = offset;
  21164. this.imports = imports;
  21165. this.types = types;
  21166. this.declares = declares;
  21167. this.isGenericScope = false;
  21168. this.resolvedImportSources = /* @__PURE__ */ Object.create(null);
  21169. this.exportedTypes = /* @__PURE__ */ Object.create(null);
  21170. this.exportedDeclares = /* @__PURE__ */ Object.create(null);
  21171. }
  21172. }
  21173. function recordScopeDep(ctx, scope) {
  21174. if (scope && scope.filename !== ctx.filename) {
  21175. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(scope.filename);
  21176. }
  21177. }
  21178. function recordResolvedElementDeps(ctx, { props }) {
  21179. for (const key in props) {
  21180. recordScopeDep(ctx, props[key]._ownerScope);
  21181. }
  21182. }
  21183. function resolveTypeElements(ctx, node, scope, typeParameters) {
  21184. const canCache = !typeParameters;
  21185. if (canCache && node._resolvedElements) {
  21186. recordResolvedElementDeps(ctx, node._resolvedElements);
  21187. return node._resolvedElements;
  21188. }
  21189. const resolved = innerResolveTypeElements(
  21190. ctx,
  21191. node,
  21192. node._ownerScope || scope || ctxToScope(ctx),
  21193. typeParameters
  21194. );
  21195. return canCache ? node._resolvedElements = resolved : resolved;
  21196. }
  21197. function innerResolveTypeElements(ctx, node, scope, typeParameters) {
  21198. var _a, _b;
  21199. if (hasVueIgnore(node)) {
  21200. if ((node.type === "TSIntersectionType" || node.type === "TSUnionType") && node.types.length > 1) {
  21201. return mergeElements(
  21202. [
  21203. { props: {} },
  21204. ...node.types.slice(1).map((t) => resolveTypeElements(ctx, t, scope, typeParameters))
  21205. ],
  21206. node.type
  21207. );
  21208. }
  21209. return { props: {} };
  21210. }
  21211. switch (node.type) {
  21212. case "TSTypeLiteral":
  21213. return typeElementsToMap(ctx, node.members, scope, typeParameters);
  21214. case "TSInterfaceDeclaration":
  21215. return resolveInterfaceMembers(ctx, node, scope, typeParameters);
  21216. case "TSTypeAliasDeclaration":
  21217. case "TSTypeAnnotation":
  21218. case "TSParenthesizedType":
  21219. return resolveTypeElements(
  21220. ctx,
  21221. node.typeAnnotation,
  21222. scope,
  21223. typeParameters
  21224. );
  21225. case "TSFunctionType": {
  21226. return { props: {}, calls: [node] };
  21227. }
  21228. case "TSUnionType":
  21229. case "TSIntersectionType":
  21230. return mergeElements(
  21231. node.types.map((t) => resolveTypeElements(ctx, t, scope, typeParameters)),
  21232. node.type
  21233. );
  21234. case "TSMappedType":
  21235. return resolveMappedType(ctx, node, scope, typeParameters);
  21236. case "TSIndexedAccessType": {
  21237. const types = resolveIndexType(ctx, node, scope);
  21238. return mergeElements(
  21239. types.map((t) => resolveTypeElements(ctx, t, t._ownerScope)),
  21240. "TSUnionType"
  21241. );
  21242. }
  21243. case "TSExpressionWithTypeArguments":
  21244. // referenced by interface extends
  21245. case "TSTypeReference": {
  21246. const typeName = getReferenceName(node);
  21247. if ((typeName === "ExtractPropTypes" || typeName === "ExtractPublicPropTypes") && node.typeParameters && ((_a = scope.imports[typeName]) == null ? void 0 : _a.source) === "vue") {
  21248. return resolveExtractPropTypes(
  21249. resolveTypeElements(
  21250. ctx,
  21251. node.typeParameters.params[0],
  21252. scope,
  21253. typeParameters
  21254. ),
  21255. scope
  21256. );
  21257. }
  21258. const resolved = resolveTypeReference(ctx, node, scope);
  21259. if (resolved) {
  21260. let typeParams;
  21261. if ((resolved.type === "TSTypeAliasDeclaration" || resolved.type === "TSInterfaceDeclaration") && resolved.typeParameters && node.typeParameters) {
  21262. typeParams = /* @__PURE__ */ Object.create(null);
  21263. resolved.typeParameters.params.forEach((p, i) => {
  21264. let param = typeParameters && typeParameters[p.name];
  21265. if (!param) param = node.typeParameters.params[i];
  21266. typeParams[p.name] = param;
  21267. });
  21268. }
  21269. return resolveTypeElements(
  21270. ctx,
  21271. resolved,
  21272. resolved._ownerScope,
  21273. typeParams
  21274. );
  21275. } else {
  21276. if (typeof typeName === "string") {
  21277. if (typeParameters && typeParameters[typeName]) {
  21278. return resolveTypeElements(
  21279. ctx,
  21280. typeParameters[typeName],
  21281. scope,
  21282. typeParameters
  21283. );
  21284. }
  21285. if (
  21286. // @ts-expect-error
  21287. SupportedBuiltinsSet.has(typeName)
  21288. ) {
  21289. return resolveBuiltin(
  21290. ctx,
  21291. node,
  21292. typeName,
  21293. scope,
  21294. typeParameters
  21295. );
  21296. } else if (typeName === "ReturnType" && node.typeParameters) {
  21297. const ret = resolveReturnType(
  21298. ctx,
  21299. node.typeParameters.params[0],
  21300. scope
  21301. );
  21302. if (ret) {
  21303. return resolveTypeElements(ctx, ret, scope);
  21304. }
  21305. }
  21306. }
  21307. return ctx.error(
  21308. `Unresolvable type reference or unsupported built-in utility type`,
  21309. node,
  21310. scope
  21311. );
  21312. }
  21313. }
  21314. case "TSImportType": {
  21315. if (getId(node.argument) === "vue" && ((_b = node.qualifier) == null ? void 0 : _b.type) === "Identifier" && node.qualifier.name === "ExtractPropTypes" && node.typeParameters) {
  21316. return resolveExtractPropTypes(
  21317. resolveTypeElements(ctx, node.typeParameters.params[0], scope),
  21318. scope
  21319. );
  21320. }
  21321. const sourceScope = importSourceToScope(
  21322. ctx,
  21323. node.argument,
  21324. scope,
  21325. node.argument.value
  21326. );
  21327. const resolved = resolveTypeReference(ctx, node, sourceScope);
  21328. if (resolved) {
  21329. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  21330. }
  21331. break;
  21332. }
  21333. case "TSTypeQuery":
  21334. {
  21335. const resolved = resolveTypeReference(ctx, node, scope);
  21336. if (resolved) {
  21337. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  21338. }
  21339. }
  21340. break;
  21341. }
  21342. return ctx.error(`Unresolvable type: ${node.type}`, node, scope);
  21343. }
  21344. function typeElementsToMap(ctx, elements, scope = ctxToScope(ctx), typeParameters) {
  21345. const res = { props: {} };
  21346. for (const e of elements) {
  21347. if (e.type === "TSPropertySignature" || e.type === "TSMethodSignature") {
  21348. if (typeParameters) {
  21349. scope = createChildScope(scope);
  21350. scope.isGenericScope = true;
  21351. Object.assign(scope.types, typeParameters);
  21352. }
  21353. e._ownerScope = scope;
  21354. const name = getStringLiteralKey(e);
  21355. if (name !== null) {
  21356. res.props[name] = e;
  21357. } else {
  21358. ctx.error(
  21359. `Unsupported computed key in type referenced by a macro`,
  21360. e.key,
  21361. scope
  21362. );
  21363. }
  21364. } else if (e.type === "TSCallSignatureDeclaration") {
  21365. (res.calls || (res.calls = [])).push(e);
  21366. }
  21367. }
  21368. return res;
  21369. }
  21370. function hasVueIgnore(node) {
  21371. return !!(node.leadingComments && node.leadingComments.some((c) => c.value.includes("@vue-ignore")));
  21372. }
  21373. function mergeElements(maps, type) {
  21374. if (maps.length === 1) return maps[0];
  21375. const res = { props: {} };
  21376. const { props: baseProps } = res;
  21377. for (const { props, calls } of maps) {
  21378. for (const key in props) {
  21379. if (!shared.hasOwn(baseProps, key)) {
  21380. baseProps[key] = props[key];
  21381. } else {
  21382. baseProps[key] = createProperty(
  21383. baseProps[key].key,
  21384. {
  21385. type,
  21386. // @ts-expect-error
  21387. types: [baseProps[key], props[key]]
  21388. },
  21389. baseProps[key]._ownerScope,
  21390. baseProps[key].optional || props[key].optional
  21391. );
  21392. }
  21393. }
  21394. if (calls) {
  21395. (res.calls || (res.calls = [])).push(...calls);
  21396. }
  21397. }
  21398. return res;
  21399. }
  21400. function createProperty(key, typeAnnotation, scope, optional) {
  21401. return {
  21402. type: "TSPropertySignature",
  21403. key,
  21404. kind: "get",
  21405. optional,
  21406. typeAnnotation: {
  21407. type: "TSTypeAnnotation",
  21408. typeAnnotation
  21409. },
  21410. _ownerScope: scope
  21411. };
  21412. }
  21413. function resolveInterfaceMembers(ctx, node, scope, typeParameters) {
  21414. const base = typeElementsToMap(
  21415. ctx,
  21416. node.body.body,
  21417. node._ownerScope,
  21418. typeParameters
  21419. );
  21420. if (node.extends) {
  21421. for (const ext of node.extends) {
  21422. try {
  21423. const { props, calls } = resolveTypeElements(ctx, ext, scope);
  21424. for (const key in props) {
  21425. if (!shared.hasOwn(base.props, key)) {
  21426. base.props[key] = props[key];
  21427. }
  21428. }
  21429. if (calls) {
  21430. ;
  21431. (base.calls || (base.calls = [])).push(...calls);
  21432. }
  21433. } catch (e) {
  21434. if (!ctx.silentOnExtendsFailure) {
  21435. ctx.error(
  21436. `Failed to resolve extends base type.
  21437. If this previously worked in 3.2, you can instruct the compiler to ignore this extend by adding /* @vue-ignore */ before it, for example:
  21438. interface Props extends /* @vue-ignore */ Base {}
  21439. Note: both in 3.2 or with the ignore, the properties in the base type are treated as fallthrough attrs at runtime.`,
  21440. ext,
  21441. scope
  21442. );
  21443. }
  21444. }
  21445. }
  21446. }
  21447. return base;
  21448. }
  21449. function resolveMappedType(ctx, node, scope, typeParameters) {
  21450. const res = { props: {} };
  21451. let keys;
  21452. if (node.nameType) {
  21453. const { name, constraint } = node.typeParameter;
  21454. scope = createChildScope(scope);
  21455. Object.assign(scope.types, { ...typeParameters, [name]: constraint });
  21456. keys = resolveStringType(ctx, node.nameType, scope);
  21457. } else {
  21458. keys = resolveStringType(ctx, node.typeParameter.constraint, scope);
  21459. }
  21460. for (const key of keys) {
  21461. res.props[key] = createProperty(
  21462. {
  21463. type: "Identifier",
  21464. name: key
  21465. },
  21466. node.typeAnnotation,
  21467. scope,
  21468. !!node.optional
  21469. );
  21470. }
  21471. return res;
  21472. }
  21473. function resolveIndexType(ctx, node, scope) {
  21474. var _a, _b;
  21475. if (node.indexType.type === "TSNumberKeyword") {
  21476. return resolveArrayElementType(ctx, node.objectType, scope);
  21477. }
  21478. const { indexType, objectType } = node;
  21479. const types = [];
  21480. let keys;
  21481. let resolved;
  21482. if (indexType.type === "TSStringKeyword") {
  21483. resolved = resolveTypeElements(ctx, objectType, scope);
  21484. keys = Object.keys(resolved.props);
  21485. } else {
  21486. keys = resolveStringType(ctx, indexType, scope);
  21487. resolved = resolveTypeElements(ctx, objectType, scope);
  21488. }
  21489. for (const key of keys) {
  21490. const targetType = (_b = (_a = resolved.props[key]) == null ? void 0 : _a.typeAnnotation) == null ? void 0 : _b.typeAnnotation;
  21491. if (targetType) {
  21492. targetType._ownerScope = resolved.props[key]._ownerScope;
  21493. types.push(targetType);
  21494. }
  21495. }
  21496. return types;
  21497. }
  21498. function resolveArrayElementType(ctx, node, scope) {
  21499. if (node.type === "TSArrayType") {
  21500. return [node.elementType];
  21501. }
  21502. if (node.type === "TSTupleType") {
  21503. return node.elementTypes.map(
  21504. (t) => t.type === "TSNamedTupleMember" ? t.elementType : t
  21505. );
  21506. }
  21507. if (node.type === "TSTypeReference") {
  21508. if (getReferenceName(node) === "Array" && node.typeParameters) {
  21509. return node.typeParameters.params;
  21510. } else {
  21511. const resolved = resolveTypeReference(ctx, node, scope);
  21512. if (resolved) {
  21513. return resolveArrayElementType(ctx, resolved, scope);
  21514. }
  21515. }
  21516. }
  21517. return ctx.error(
  21518. "Failed to resolve element type from target type",
  21519. node,
  21520. scope
  21521. );
  21522. }
  21523. function resolveStringType(ctx, node, scope, typeParameters) {
  21524. switch (node.type) {
  21525. case "StringLiteral":
  21526. return [node.value];
  21527. case "TSLiteralType":
  21528. return resolveStringType(ctx, node.literal, scope, typeParameters);
  21529. case "TSUnionType":
  21530. return node.types.map((t) => resolveStringType(ctx, t, scope, typeParameters)).flat();
  21531. case "TemplateLiteral": {
  21532. return resolveTemplateKeys(ctx, node, scope);
  21533. }
  21534. case "TSTypeReference": {
  21535. const resolved = resolveTypeReference(ctx, node, scope);
  21536. if (resolved) {
  21537. return resolveStringType(ctx, resolved, scope, typeParameters);
  21538. }
  21539. if (node.typeName.type === "Identifier") {
  21540. const name = node.typeName.name;
  21541. if (typeParameters && typeParameters[name]) {
  21542. return resolveStringType(
  21543. ctx,
  21544. typeParameters[name],
  21545. scope,
  21546. typeParameters
  21547. );
  21548. }
  21549. const getParam = (index = 0) => resolveStringType(
  21550. ctx,
  21551. node.typeParameters.params[index],
  21552. scope,
  21553. typeParameters
  21554. );
  21555. switch (name) {
  21556. case "Extract":
  21557. return getParam(1);
  21558. case "Exclude": {
  21559. const excluded = getParam(1);
  21560. return getParam().filter((s) => !excluded.includes(s));
  21561. }
  21562. case "Uppercase":
  21563. return getParam().map((s) => s.toUpperCase());
  21564. case "Lowercase":
  21565. return getParam().map((s) => s.toLowerCase());
  21566. case "Capitalize":
  21567. return getParam().map(shared.capitalize);
  21568. case "Uncapitalize":
  21569. return getParam().map((s) => s[0].toLowerCase() + s.slice(1));
  21570. default:
  21571. ctx.error(
  21572. "Unsupported type when resolving index type",
  21573. node.typeName,
  21574. scope
  21575. );
  21576. }
  21577. }
  21578. }
  21579. }
  21580. return ctx.error("Failed to resolve index type into finite keys", node, scope);
  21581. }
  21582. function resolveTemplateKeys(ctx, node, scope) {
  21583. if (!node.expressions.length) {
  21584. return [node.quasis[0].value.raw];
  21585. }
  21586. const res = [];
  21587. const e = node.expressions[0];
  21588. const q = node.quasis[0];
  21589. const leading = q ? q.value.raw : ``;
  21590. const resolved = resolveStringType(ctx, e, scope);
  21591. const restResolved = resolveTemplateKeys(
  21592. ctx,
  21593. {
  21594. ...node,
  21595. expressions: node.expressions.slice(1),
  21596. quasis: q ? node.quasis.slice(1) : node.quasis
  21597. },
  21598. scope
  21599. );
  21600. for (const r of resolved) {
  21601. for (const rr of restResolved) {
  21602. res.push(leading + r + rr);
  21603. }
  21604. }
  21605. return res;
  21606. }
  21607. const SupportedBuiltinsSet = /* @__PURE__ */ new Set([
  21608. "Partial",
  21609. "Required",
  21610. "Readonly",
  21611. "Pick",
  21612. "Omit"
  21613. ]);
  21614. function resolveBuiltin(ctx, node, name, scope, typeParameters) {
  21615. const t = resolveTypeElements(
  21616. ctx,
  21617. node.typeParameters.params[0],
  21618. scope,
  21619. typeParameters
  21620. );
  21621. switch (name) {
  21622. case "Partial": {
  21623. const res2 = { props: {}, calls: t.calls };
  21624. Object.keys(t.props).forEach((key) => {
  21625. res2.props[key] = { ...t.props[key], optional: true };
  21626. });
  21627. return res2;
  21628. }
  21629. case "Required": {
  21630. const res2 = { props: {}, calls: t.calls };
  21631. Object.keys(t.props).forEach((key) => {
  21632. res2.props[key] = { ...t.props[key], optional: false };
  21633. });
  21634. return res2;
  21635. }
  21636. case "Readonly":
  21637. return t;
  21638. case "Pick": {
  21639. const picked = resolveStringType(
  21640. ctx,
  21641. node.typeParameters.params[1],
  21642. scope,
  21643. typeParameters
  21644. );
  21645. const res2 = { props: {}, calls: t.calls };
  21646. for (const key of picked) {
  21647. res2.props[key] = t.props[key];
  21648. }
  21649. return res2;
  21650. }
  21651. case "Omit":
  21652. const omitted = resolveStringType(
  21653. ctx,
  21654. node.typeParameters.params[1],
  21655. scope,
  21656. typeParameters
  21657. );
  21658. const res = { props: {}, calls: t.calls };
  21659. for (const key in t.props) {
  21660. if (!omitted.includes(key)) {
  21661. res.props[key] = t.props[key];
  21662. }
  21663. }
  21664. return res;
  21665. }
  21666. }
  21667. function resolveTypeReference(ctx, node, scope, name, onlyExported = false) {
  21668. const canCache = !(scope == null ? void 0 : scope.isGenericScope);
  21669. if (canCache && node._resolvedReference) {
  21670. recordScopeDep(ctx, node._resolvedReference._ownerScope);
  21671. return node._resolvedReference;
  21672. }
  21673. const resolved = innerResolveTypeReference(
  21674. ctx,
  21675. scope || ctxToScope(ctx),
  21676. name || getReferenceName(node),
  21677. node,
  21678. onlyExported
  21679. );
  21680. return canCache ? node._resolvedReference = resolved : resolved;
  21681. }
  21682. function innerResolveTypeReference(ctx, scope, name, node, onlyExported) {
  21683. if (typeof name === "string") {
  21684. if (scope.imports[name]) {
  21685. return resolveTypeFromImport(ctx, node, name, scope);
  21686. } else {
  21687. const lookupSource = node.type === "TSTypeQuery" ? onlyExported ? scope.exportedDeclares : scope.declares : onlyExported ? scope.exportedTypes : scope.types;
  21688. if (lookupSource[name]) {
  21689. return lookupSource[name];
  21690. } else {
  21691. const globalScopes = resolveGlobalScope(ctx);
  21692. if (globalScopes) {
  21693. for (const s of globalScopes) {
  21694. const src = node.type === "TSTypeQuery" ? s.declares : s.types;
  21695. if (src[name]) {
  21696. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(s.filename);
  21697. const resolved = src[name];
  21698. if (resolved._ownerScope && resolved._ownerScope !== s) {
  21699. ctx.deps.add(resolved._ownerScope.filename);
  21700. }
  21701. return resolved;
  21702. }
  21703. }
  21704. }
  21705. }
  21706. }
  21707. } else {
  21708. let ns = innerResolveTypeReference(ctx, scope, name[0], node, onlyExported);
  21709. if (ns) {
  21710. if (ns.type !== "TSModuleDeclaration") {
  21711. ns = ns._ns;
  21712. }
  21713. if (ns) {
  21714. const childScope = moduleDeclToScope(ctx, ns, ns._ownerScope || scope);
  21715. return innerResolveTypeReference(
  21716. ctx,
  21717. childScope,
  21718. name.length > 2 ? name.slice(1) : name[name.length - 1],
  21719. node,
  21720. !ns.declare
  21721. );
  21722. }
  21723. }
  21724. }
  21725. }
  21726. function getReferenceName(node) {
  21727. const ref = node.type === "TSTypeReference" ? node.typeName : node.type === "TSExpressionWithTypeArguments" ? node.expression : node.type === "TSImportType" ? node.qualifier : node.exprName;
  21728. if ((ref == null ? void 0 : ref.type) === "Identifier") {
  21729. return ref.name;
  21730. } else if ((ref == null ? void 0 : ref.type) === "TSQualifiedName") {
  21731. return qualifiedNameToPath(ref);
  21732. } else {
  21733. return "default";
  21734. }
  21735. }
  21736. function qualifiedNameToPath(node) {
  21737. if (node.type === "Identifier") {
  21738. return [node.name];
  21739. } else {
  21740. return [...qualifiedNameToPath(node.left), node.right.name];
  21741. }
  21742. }
  21743. function resolveGlobalScope(ctx) {
  21744. if (ctx.options.globalTypeFiles) {
  21745. const fs = resolveFS(ctx);
  21746. if (!fs) {
  21747. throw new Error("[vue/compiler-sfc] globalTypeFiles requires fs access.");
  21748. }
  21749. return ctx.options.globalTypeFiles.map(
  21750. (file) => fileToScope(ctx, normalizePath(file), true)
  21751. );
  21752. }
  21753. }
  21754. let ts;
  21755. let loadTS;
  21756. function registerTS(_loadTS) {
  21757. loadTS = () => {
  21758. try {
  21759. return _loadTS();
  21760. } catch (err) {
  21761. if (typeof err.message === "string" && err.message.includes("Cannot find module")) {
  21762. throw new Error(
  21763. 'Failed to load TypeScript, which is required for resolving imported types. Please make sure "TypeScript" is installed as a project dependency.'
  21764. );
  21765. } else {
  21766. throw new Error(
  21767. "Failed to load TypeScript for resolving imported types."
  21768. );
  21769. }
  21770. }
  21771. };
  21772. }
  21773. function resolveFS(ctx) {
  21774. if (ctx.fs) {
  21775. return ctx.fs;
  21776. }
  21777. if (!ts && loadTS) {
  21778. ts = loadTS();
  21779. }
  21780. const fs = ctx.options.fs || (ts == null ? void 0 : ts.sys);
  21781. if (!fs) {
  21782. return;
  21783. }
  21784. return ctx.fs = {
  21785. fileExists(file) {
  21786. if (file.endsWith(".vue.ts") && !file.endsWith(".d.vue.ts")) {
  21787. file = file.replace(/\.ts$/, "");
  21788. }
  21789. return fs.fileExists(file);
  21790. },
  21791. readFile(file) {
  21792. if (file.endsWith(".vue.ts") && !file.endsWith(".d.vue.ts")) {
  21793. file = file.replace(/\.ts$/, "");
  21794. }
  21795. return fs.readFile(file);
  21796. },
  21797. realpath: fs.realpath
  21798. };
  21799. }
  21800. function resolveTypeFromImport(ctx, node, name, scope) {
  21801. const { source, imported } = scope.imports[name];
  21802. const sourceScope = importSourceToScope(ctx, node, scope, source);
  21803. return resolveTypeReference(ctx, node, sourceScope, imported, true);
  21804. }
  21805. function importSourceToScope(ctx, node, scope, source, trackDep = true) {
  21806. let fs;
  21807. try {
  21808. fs = resolveFS(ctx);
  21809. } catch (err) {
  21810. return ctx.error(err.message, node, scope);
  21811. }
  21812. if (!fs) {
  21813. return ctx.error(
  21814. `No fs option provided to \`compileScript\` in non-Node environment. File system access is required for resolving imported types.`,
  21815. node,
  21816. scope
  21817. );
  21818. }
  21819. let resolved = scope.resolvedImportSources[source];
  21820. if (!resolved) {
  21821. if (source.startsWith("..")) {
  21822. const osSpecificJoinFn = process__namespace.platform === "win32" ? path$1.join : joinPaths;
  21823. const filename = osSpecificJoinFn(path$1.dirname(scope.filename), source);
  21824. resolved = resolveExt(filename, fs);
  21825. } else if (source[0] === ".") {
  21826. const filename = joinPaths(path$1.dirname(scope.filename), source);
  21827. resolved = resolveExt(filename, fs);
  21828. } else {
  21829. if (!ts) {
  21830. if (loadTS) ts = loadTS();
  21831. if (!ts) {
  21832. return ctx.error(
  21833. `Failed to resolve import source ${JSON.stringify(source)}. TypeScript is required as a peer dep for vue in order to support resolving types from module imports.`,
  21834. node,
  21835. scope
  21836. );
  21837. }
  21838. }
  21839. resolved = resolveWithTS(scope.filename, source, ts, fs);
  21840. }
  21841. if (!resolved && source[0] === "." && true) {
  21842. if (!ts) {
  21843. if (loadTS) ts = loadTS();
  21844. }
  21845. if (ts) {
  21846. resolved = resolveWithTS(scope.filename, source, ts, fs);
  21847. }
  21848. }
  21849. if (resolved) {
  21850. resolved = scope.resolvedImportSources[source] = normalizePath(resolved);
  21851. }
  21852. }
  21853. if (resolved) {
  21854. if (trackDep) {
  21855. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(resolved);
  21856. }
  21857. return fileToScope(ctx, resolved);
  21858. } else {
  21859. return ctx.error(
  21860. `Failed to resolve import source ${JSON.stringify(source)}.`,
  21861. node,
  21862. scope
  21863. );
  21864. }
  21865. }
  21866. function resolveExt(filename, fs) {
  21867. let moduleType = "u";
  21868. if (filename.endsWith(".mjs")) {
  21869. moduleType = "m";
  21870. } else if (filename.endsWith(".cjs")) {
  21871. moduleType = "c";
  21872. }
  21873. filename = filename.replace(/\.[cm]?jsx?$/, "");
  21874. const tryResolve = (filename2) => {
  21875. if (fs.fileExists(filename2)) return filename2;
  21876. };
  21877. const resolveTs = () => tryResolve(filename + `.ts`) || tryResolve(filename + `.tsx`) || tryResolve(filename + `.d.ts`);
  21878. const resolveMts = () => tryResolve(filename + `.mts`) || tryResolve(filename + `.d.mts`);
  21879. const resolveCts = () => tryResolve(filename + `.cts`) || tryResolve(filename + `.d.cts`);
  21880. return tryResolve(filename) || // For explicit .mjs/.cjs imports, prefer .mts/.cts declarations first.
  21881. (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`));
  21882. }
  21883. const tsConfigCache = createCache();
  21884. const tsConfigRefMap = /* @__PURE__ */ new Map();
  21885. function resolveWithTS(containingFile, source, ts2, fs) {
  21886. var _a, _b;
  21887. const configPath = ts2.findConfigFile(containingFile, fs.fileExists);
  21888. let tsCompilerOptions;
  21889. let tsResolveCache;
  21890. if (configPath) {
  21891. let configs;
  21892. const normalizedConfigPath = normalizePath(configPath);
  21893. const cached = tsConfigCache.get(normalizedConfigPath);
  21894. if (!cached) {
  21895. configs = loadTSConfig(configPath, ts2, fs).map((config) => ({ config }));
  21896. tsConfigCache.set(normalizedConfigPath, configs);
  21897. } else {
  21898. configs = cached;
  21899. }
  21900. let matchedConfig;
  21901. if (configs.length === 1) {
  21902. matchedConfig = configs[0];
  21903. } else {
  21904. const [major, minor] = ts2.versionMajorMinor.split(".").map(Number);
  21905. const getPattern = (base, p) => {
  21906. const supportsConfigDir = major > 5 || major === 5 && minor >= 5;
  21907. return p.startsWith("${configDir}") && supportsConfigDir ? normalizePath(p.replace("${configDir}", path$1.dirname(configPath))) : joinPaths(base, p);
  21908. };
  21909. for (const c of configs) {
  21910. const base = normalizePath(
  21911. c.config.options.pathsBasePath || path$1.dirname(c.config.options.configFilePath)
  21912. );
  21913. const included = (_a = c.config.raw) == null ? void 0 : _a.include;
  21914. const excluded = (_b = c.config.raw) == null ? void 0 : _b.exclude;
  21915. if (!included && (!base || containingFile.startsWith(base)) || (included == null ? void 0 : included.some((p) => minimatch(containingFile, getPattern(base, p))))) {
  21916. if (excluded && excluded.some((p) => minimatch(containingFile, getPattern(base, p)))) {
  21917. continue;
  21918. }
  21919. matchedConfig = c;
  21920. break;
  21921. }
  21922. }
  21923. if (!matchedConfig) {
  21924. matchedConfig = configs[configs.length - 1];
  21925. }
  21926. }
  21927. tsCompilerOptions = matchedConfig.config.options;
  21928. tsResolveCache = matchedConfig.cache || (matchedConfig.cache = ts2.createModuleResolutionCache(
  21929. process__namespace.cwd(),
  21930. createGetCanonicalFileName(ts2.sys.useCaseSensitiveFileNames),
  21931. tsCompilerOptions
  21932. ));
  21933. } else {
  21934. tsCompilerOptions = {};
  21935. }
  21936. const res = ts2.resolveModuleName(
  21937. source,
  21938. containingFile,
  21939. tsCompilerOptions,
  21940. fs,
  21941. tsResolveCache
  21942. );
  21943. if (res.resolvedModule) {
  21944. let filename = res.resolvedModule.resolvedFileName;
  21945. if (filename.endsWith(".vue.ts") && !filename.endsWith(".d.vue.ts")) {
  21946. filename = filename.replace(/\.ts$/, "");
  21947. }
  21948. return fs.realpath ? fs.realpath(filename) : filename;
  21949. }
  21950. }
  21951. function loadTSConfig(configPath, ts2, fs, visited = /* @__PURE__ */ new Set()) {
  21952. const parseConfigHost = ts2.sys;
  21953. const config = ts2.parseJsonConfigFileContent(
  21954. ts2.readConfigFile(configPath, fs.readFile).config,
  21955. parseConfigHost,
  21956. path$1.dirname(configPath),
  21957. void 0,
  21958. configPath
  21959. );
  21960. const res = [config];
  21961. visited.add(configPath);
  21962. if (config.projectReferences) {
  21963. for (const ref of config.projectReferences) {
  21964. const refPath = ts2.resolveProjectReferencePath(ref);
  21965. if (visited.has(refPath) || !fs.fileExists(refPath)) {
  21966. continue;
  21967. }
  21968. tsConfigRefMap.set(refPath, configPath);
  21969. res.unshift(...loadTSConfig(refPath, ts2, fs, visited));
  21970. }
  21971. }
  21972. return res;
  21973. }
  21974. const fileToScopeCache = createCache();
  21975. const fileToGlobalScopeCache = createCache();
  21976. function invalidateTypeCache(filename) {
  21977. filename = normalizePath(filename);
  21978. fileToScopeCache.delete(filename);
  21979. fileToGlobalScopeCache.delete(filename);
  21980. tsConfigCache.delete(filename);
  21981. const affectedConfig = tsConfigRefMap.get(filename);
  21982. if (affectedConfig) tsConfigCache.delete(affectedConfig);
  21983. }
  21984. function fileToScope(ctx, filename, asGlobal = false) {
  21985. const cache = asGlobal ? fileToGlobalScopeCache : fileToScopeCache;
  21986. const cached = cache.get(filename);
  21987. if (cached) {
  21988. return cached;
  21989. }
  21990. const fs = resolveFS(ctx);
  21991. const source = fs.readFile(filename) || "";
  21992. const body = parseFile(filename, source, fs, ctx.options.babelParserPlugins);
  21993. const scope = new TypeScope(filename, source, 0, recordImports(body));
  21994. recordTypes(ctx, body, scope, asGlobal);
  21995. cache.set(filename, scope);
  21996. return scope;
  21997. }
  21998. function parseFile(filename, content, fs, parserPlugins) {
  21999. const ext = path$1.extname(filename);
  22000. if (ext === ".ts" || ext === ".mts" || ext === ".tsx" || ext === ".cts" || ext === ".mtsx") {
  22001. return parser$2.parse(content, {
  22002. plugins: resolveParserPlugins(
  22003. ext.slice(1),
  22004. parserPlugins,
  22005. /\.d\.[cm]?ts$/.test(filename)
  22006. ),
  22007. sourceType: "module"
  22008. }).program.body;
  22009. }
  22010. const isUnknownTypeSource = !/\.[cm]?[tj]sx?$/.test(filename);
  22011. const arbitraryTypeSource = `${filename.slice(0, -ext.length)}.d${ext}.ts`;
  22012. const hasArbitraryTypeDeclaration = isUnknownTypeSource && fs.fileExists(arbitraryTypeSource);
  22013. if (hasArbitraryTypeDeclaration) {
  22014. return parser$2.parse(fs.readFile(arbitraryTypeSource), {
  22015. plugins: resolveParserPlugins("ts", parserPlugins, true),
  22016. sourceType: "module"
  22017. }).program.body;
  22018. }
  22019. if (ext === ".vue") {
  22020. const {
  22021. descriptor: { script, scriptSetup }
  22022. } = parse$1(content);
  22023. if (!script && !scriptSetup) {
  22024. return [];
  22025. }
  22026. const scriptOffset = script ? script.loc.start.offset : Infinity;
  22027. const scriptSetupOffset = scriptSetup ? scriptSetup.loc.start.offset : Infinity;
  22028. const firstBlock = scriptOffset < scriptSetupOffset ? script : scriptSetup;
  22029. const secondBlock = scriptOffset < scriptSetupOffset ? scriptSetup : script;
  22030. let scriptContent = " ".repeat(Math.min(scriptOffset, scriptSetupOffset)) + firstBlock.content;
  22031. if (secondBlock) {
  22032. scriptContent += " ".repeat(secondBlock.loc.start.offset - script.loc.end.offset) + secondBlock.content;
  22033. }
  22034. const lang = (script == null ? void 0 : script.lang) || (scriptSetup == null ? void 0 : scriptSetup.lang);
  22035. return parser$2.parse(scriptContent, {
  22036. plugins: resolveParserPlugins(lang, parserPlugins),
  22037. sourceType: "module"
  22038. }).program.body;
  22039. }
  22040. return [];
  22041. }
  22042. function ctxToScope(ctx) {
  22043. if (ctx.scope) {
  22044. return ctx.scope;
  22045. }
  22046. const body = "ast" in ctx ? ctx.ast : ctx.scriptAst ? [...ctx.scriptAst.body, ...ctx.scriptSetupAst.body] : ctx.scriptSetupAst.body;
  22047. const scope = new TypeScope(
  22048. ctx.filename,
  22049. ctx.source,
  22050. "startOffset" in ctx ? ctx.startOffset : 0,
  22051. "userImports" in ctx ? Object.create(ctx.userImports) : recordImports(body)
  22052. );
  22053. recordTypes(ctx, body, scope);
  22054. return ctx.scope = scope;
  22055. }
  22056. function moduleDeclToScope(ctx, node, parentScope) {
  22057. if (node._resolvedChildScope) {
  22058. return node._resolvedChildScope;
  22059. }
  22060. const scope = createChildScope(parentScope);
  22061. if (node.body.type === "TSModuleDeclaration") {
  22062. const decl = node.body;
  22063. decl._ownerScope = scope;
  22064. const id = getId(decl.id);
  22065. scope.types[id] = scope.exportedTypes[id] = decl;
  22066. } else {
  22067. recordTypes(ctx, node.body.body, scope);
  22068. }
  22069. return node._resolvedChildScope = scope;
  22070. }
  22071. function createChildScope(parentScope) {
  22072. return new TypeScope(
  22073. parentScope.filename,
  22074. parentScope.source,
  22075. parentScope.offset,
  22076. Object.create(parentScope.imports),
  22077. Object.create(parentScope.types),
  22078. Object.create(parentScope.declares)
  22079. );
  22080. }
  22081. const importExportRE = /^Import|^Export/;
  22082. function recordTypes(ctx, body, scope, asGlobal = false) {
  22083. const { types, declares, exportedTypes, exportedDeclares, imports } = scope;
  22084. const isAmbient = asGlobal ? !body.some((s) => importExportRE.test(s.type)) : false;
  22085. for (const stmt of body) {
  22086. if (asGlobal) {
  22087. if (isAmbient) {
  22088. if (stmt.declare) {
  22089. recordType(stmt, types, declares);
  22090. }
  22091. } else if (stmt.type === "TSModuleDeclaration" && stmt.global) {
  22092. for (const s of stmt.body.body) {
  22093. if (s.type === "ExportNamedDeclaration") {
  22094. if (s.declaration) {
  22095. recordType(s.declaration, types, declares);
  22096. } else if (s.source) {
  22097. const sourceScope = importSourceToScope(
  22098. ctx,
  22099. s.source,
  22100. scope,
  22101. s.source.value,
  22102. false
  22103. );
  22104. for (const spec of s.specifiers) {
  22105. if (spec.type === "ExportSpecifier") {
  22106. const exported = getId(spec.exported);
  22107. const local = spec.local.name;
  22108. if (sourceScope.exportedTypes[local]) {
  22109. types[exported] = sourceScope.exportedTypes[local];
  22110. }
  22111. if (sourceScope.exportedDeclares[local]) {
  22112. declares[exported] = sourceScope.exportedDeclares[local];
  22113. }
  22114. }
  22115. }
  22116. }
  22117. } else if (s.type === "ExportAllDeclaration" && s.source) {
  22118. const sourceScope = importSourceToScope(
  22119. ctx,
  22120. s.source,
  22121. scope,
  22122. s.source.value,
  22123. false
  22124. );
  22125. Object.assign(types, sourceScope.exportedTypes);
  22126. Object.assign(declares, sourceScope.exportedDeclares);
  22127. } else {
  22128. recordType(s, types, declares);
  22129. }
  22130. }
  22131. }
  22132. } else {
  22133. recordType(stmt, types, declares);
  22134. }
  22135. }
  22136. if (!asGlobal) {
  22137. for (const stmt of body) {
  22138. if (stmt.type === "ExportNamedDeclaration") {
  22139. if (stmt.declaration) {
  22140. recordType(stmt.declaration, types, declares);
  22141. recordType(stmt.declaration, exportedTypes, exportedDeclares);
  22142. } else {
  22143. for (const spec of stmt.specifiers) {
  22144. if (spec.type === "ExportSpecifier") {
  22145. const local = spec.local.name;
  22146. const exported = getId(spec.exported);
  22147. if (stmt.source) {
  22148. imports[exported] = {
  22149. source: stmt.source.value,
  22150. imported: local
  22151. };
  22152. exportedTypes[exported] = {
  22153. type: "TSTypeReference",
  22154. typeName: {
  22155. type: "Identifier",
  22156. name: local
  22157. },
  22158. _ownerScope: scope
  22159. };
  22160. } else if (types[local]) {
  22161. exportedTypes[exported] = types[local];
  22162. }
  22163. }
  22164. }
  22165. }
  22166. } else if (stmt.type === "ExportAllDeclaration") {
  22167. const sourceScope = importSourceToScope(
  22168. ctx,
  22169. stmt.source,
  22170. scope,
  22171. stmt.source.value
  22172. );
  22173. Object.assign(scope.exportedTypes, sourceScope.exportedTypes);
  22174. } else if (stmt.type === "ExportDefaultDeclaration" && stmt.declaration) {
  22175. if (stmt.declaration.type !== "Identifier") {
  22176. recordType(stmt.declaration, types, declares, "default");
  22177. recordType(
  22178. stmt.declaration,
  22179. exportedTypes,
  22180. exportedDeclares,
  22181. "default"
  22182. );
  22183. } else if (types[stmt.declaration.name]) {
  22184. exportedTypes["default"] = types[stmt.declaration.name];
  22185. }
  22186. }
  22187. }
  22188. }
  22189. for (const key of Object.keys(types)) {
  22190. const node = types[key];
  22191. if (!node._ownerScope) node._ownerScope = scope;
  22192. if (node._ns && !node._ns._ownerScope) node._ns._ownerScope = scope;
  22193. }
  22194. for (const key of Object.keys(declares)) {
  22195. if (!declares[key]._ownerScope) declares[key]._ownerScope = scope;
  22196. }
  22197. }
  22198. function recordType(node, types, declares, overwriteId) {
  22199. switch (node.type) {
  22200. case "TSInterfaceDeclaration":
  22201. case "TSEnumDeclaration":
  22202. case "TSModuleDeclaration": {
  22203. if (node.type === "TSModuleDeclaration" && node.global) {
  22204. const body = node.body;
  22205. for (const s of body.body) {
  22206. if (s.type === "ExportNamedDeclaration" && s.declaration) {
  22207. recordType(s.declaration, types, declares);
  22208. } else {
  22209. recordType(s, types, declares);
  22210. }
  22211. }
  22212. break;
  22213. }
  22214. const id = overwriteId || getId(node.id);
  22215. let existing = types[id];
  22216. if (existing) {
  22217. if (node.type === "TSModuleDeclaration") {
  22218. if (existing.type === "TSModuleDeclaration") {
  22219. mergeNamespaces(existing, node);
  22220. } else {
  22221. attachNamespace(existing, node);
  22222. }
  22223. break;
  22224. }
  22225. if (existing.type === "TSModuleDeclaration") {
  22226. types[id] = node;
  22227. attachNamespace(node, existing);
  22228. break;
  22229. }
  22230. if (existing.type !== node.type) {
  22231. break;
  22232. }
  22233. if (node.type === "TSInterfaceDeclaration") {
  22234. existing.body.body.push(...node.body.body);
  22235. } else {
  22236. existing.members.push(...node.members);
  22237. }
  22238. } else {
  22239. types[id] = node;
  22240. }
  22241. break;
  22242. }
  22243. case "ClassDeclaration":
  22244. if (overwriteId || node.id) types[overwriteId || getId(node.id)] = node;
  22245. break;
  22246. case "TSTypeAliasDeclaration":
  22247. types[node.id.name] = node.typeParameters ? node : node.typeAnnotation;
  22248. break;
  22249. case "TSDeclareFunction":
  22250. if (node.id) declares[node.id.name] = node;
  22251. break;
  22252. case "VariableDeclaration": {
  22253. if (node.declare) {
  22254. for (const decl of node.declarations) {
  22255. if (decl.id.type === "Identifier" && decl.id.typeAnnotation) {
  22256. declares[decl.id.name] = decl.id.typeAnnotation.typeAnnotation;
  22257. }
  22258. }
  22259. }
  22260. break;
  22261. }
  22262. }
  22263. }
  22264. function mergeNamespaces(to, from) {
  22265. const toBody = to.body;
  22266. const fromBody = from.body;
  22267. if (toBody.type === "TSModuleDeclaration") {
  22268. if (fromBody.type === "TSModuleDeclaration") {
  22269. mergeNamespaces(toBody, fromBody);
  22270. } else {
  22271. fromBody.body.push({
  22272. type: "ExportNamedDeclaration",
  22273. declaration: toBody,
  22274. exportKind: "type",
  22275. specifiers: []
  22276. });
  22277. }
  22278. } else if (fromBody.type === "TSModuleDeclaration") {
  22279. toBody.body.push({
  22280. type: "ExportNamedDeclaration",
  22281. declaration: fromBody,
  22282. exportKind: "type",
  22283. specifiers: []
  22284. });
  22285. } else {
  22286. toBody.body.push(...fromBody.body);
  22287. }
  22288. }
  22289. function attachNamespace(to, ns) {
  22290. if (!to._ns) {
  22291. to._ns = ns;
  22292. } else {
  22293. mergeNamespaces(to._ns, ns);
  22294. }
  22295. }
  22296. function recordImports(body) {
  22297. const imports = /* @__PURE__ */ Object.create(null);
  22298. for (const s of body) {
  22299. recordImport(s, imports);
  22300. }
  22301. return imports;
  22302. }
  22303. function recordImport(node, imports) {
  22304. if (node.type !== "ImportDeclaration") {
  22305. return;
  22306. }
  22307. for (const s of node.specifiers) {
  22308. imports[s.local.name] = {
  22309. imported: getImportedName(s),
  22310. source: node.source.value
  22311. };
  22312. }
  22313. }
  22314. function inferRuntimeType(ctx, node, scope = node._ownerScope || ctxToScope(ctx), isKeyOf = false, typeParameters) {
  22315. if (node.leadingComments && node.leadingComments.some((c) => c.value.includes("@vue-ignore"))) {
  22316. return [UNKNOWN_TYPE];
  22317. }
  22318. const prevSilent = ctx.silentOnExtendsFailure;
  22319. ctx.silentOnExtendsFailure = true;
  22320. try {
  22321. switch (node.type) {
  22322. case "TSStringKeyword":
  22323. return ["String"];
  22324. case "TSNumberKeyword":
  22325. return ["Number"];
  22326. case "TSBooleanKeyword":
  22327. return ["Boolean"];
  22328. case "TSObjectKeyword":
  22329. return ["Object"];
  22330. case "TSNullKeyword":
  22331. return ["null"];
  22332. case "TSTypeLiteral":
  22333. case "TSInterfaceDeclaration": {
  22334. const types = /* @__PURE__ */ new Set();
  22335. const members = node.type === "TSTypeLiteral" ? node.members : node.body.body;
  22336. for (const m of members) {
  22337. if (isKeyOf) {
  22338. if (m.type === "TSPropertySignature" && m.key.type === "NumericLiteral") {
  22339. types.add("Number");
  22340. } else if (m.type === "TSIndexSignature") {
  22341. const annotation = m.parameters[0].typeAnnotation;
  22342. if (annotation && annotation.type !== "Noop") {
  22343. const type = inferRuntimeType(
  22344. ctx,
  22345. annotation.typeAnnotation,
  22346. scope
  22347. )[0];
  22348. if (type === UNKNOWN_TYPE) return [UNKNOWN_TYPE];
  22349. types.add(type);
  22350. }
  22351. } else {
  22352. types.add("String");
  22353. }
  22354. } else if (m.type === "TSCallSignatureDeclaration" || m.type === "TSConstructSignatureDeclaration") {
  22355. types.add("Function");
  22356. } else {
  22357. types.add("Object");
  22358. }
  22359. }
  22360. return types.size ? Array.from(types) : [isKeyOf ? UNKNOWN_TYPE : "Object"];
  22361. }
  22362. case "TSPropertySignature":
  22363. if (node.typeAnnotation) {
  22364. return inferRuntimeType(
  22365. ctx,
  22366. node.typeAnnotation.typeAnnotation,
  22367. scope
  22368. );
  22369. }
  22370. break;
  22371. case "TSMethodSignature":
  22372. case "TSFunctionType":
  22373. return ["Function"];
  22374. case "TSArrayType":
  22375. case "TSTupleType":
  22376. return ["Array"];
  22377. case "TSLiteralType":
  22378. switch (node.literal.type) {
  22379. case "StringLiteral":
  22380. return ["String"];
  22381. case "BooleanLiteral":
  22382. return ["Boolean"];
  22383. case "NumericLiteral":
  22384. case "BigIntLiteral":
  22385. return ["Number"];
  22386. default:
  22387. return [UNKNOWN_TYPE];
  22388. }
  22389. case "TSTypeReference": {
  22390. let resolved;
  22391. try {
  22392. resolved = resolveTypeReference(ctx, node, scope);
  22393. } catch {
  22394. }
  22395. if (resolved) {
  22396. if (resolved.type === "TSTypeAliasDeclaration") {
  22397. if (resolved.typeAnnotation.type === "TSFunctionType") {
  22398. return ["Function"];
  22399. }
  22400. if (node.typeParameters) {
  22401. const typeParams = /* @__PURE__ */ Object.create(null);
  22402. if (resolved.typeParameters) {
  22403. resolved.typeParameters.params.forEach((p, i) => {
  22404. typeParams[p.name] = node.typeParameters.params[i];
  22405. });
  22406. }
  22407. return inferRuntimeType(
  22408. ctx,
  22409. resolved.typeAnnotation,
  22410. resolved._ownerScope,
  22411. isKeyOf,
  22412. typeParams
  22413. );
  22414. }
  22415. }
  22416. return inferRuntimeType(ctx, resolved, resolved._ownerScope, isKeyOf);
  22417. }
  22418. if (node.typeName.type === "Identifier") {
  22419. if (typeParameters && typeParameters[node.typeName.name]) {
  22420. return inferRuntimeType(
  22421. ctx,
  22422. typeParameters[node.typeName.name],
  22423. scope,
  22424. isKeyOf,
  22425. typeParameters
  22426. );
  22427. }
  22428. if (isKeyOf) {
  22429. switch (node.typeName.name) {
  22430. case "String":
  22431. case "Array":
  22432. case "ArrayLike":
  22433. case "Parameters":
  22434. case "ConstructorParameters":
  22435. case "ReadonlyArray":
  22436. return ["String", "Number"];
  22437. // TS built-in utility types
  22438. case "Record":
  22439. case "Partial":
  22440. case "Required":
  22441. case "Readonly":
  22442. if (node.typeParameters && node.typeParameters.params[0]) {
  22443. return inferRuntimeType(
  22444. ctx,
  22445. node.typeParameters.params[0],
  22446. scope,
  22447. true
  22448. );
  22449. }
  22450. break;
  22451. case "Pick":
  22452. case "Extract":
  22453. if (node.typeParameters && node.typeParameters.params[1]) {
  22454. return inferRuntimeType(
  22455. ctx,
  22456. node.typeParameters.params[1],
  22457. scope
  22458. );
  22459. }
  22460. break;
  22461. case "Function":
  22462. case "Object":
  22463. case "Set":
  22464. case "Map":
  22465. case "WeakSet":
  22466. case "WeakMap":
  22467. case "Date":
  22468. case "Promise":
  22469. case "Error":
  22470. case "Uppercase":
  22471. case "Lowercase":
  22472. case "Capitalize":
  22473. case "Uncapitalize":
  22474. case "ReadonlyMap":
  22475. case "ReadonlySet":
  22476. return ["String"];
  22477. }
  22478. } else {
  22479. switch (node.typeName.name) {
  22480. case "Array":
  22481. case "Function":
  22482. case "Object":
  22483. case "Set":
  22484. case "Map":
  22485. case "WeakSet":
  22486. case "WeakMap":
  22487. case "Date":
  22488. case "Promise":
  22489. case "Error":
  22490. return [node.typeName.name];
  22491. // TS built-in utility types
  22492. // https://www.typescriptlang.org/docs/handbook/utility-types.html
  22493. case "Partial":
  22494. case "Required":
  22495. case "Readonly":
  22496. case "Record":
  22497. case "Pick":
  22498. case "Omit":
  22499. case "InstanceType":
  22500. return ["Object"];
  22501. case "Uppercase":
  22502. case "Lowercase":
  22503. case "Capitalize":
  22504. case "Uncapitalize":
  22505. return ["String"];
  22506. case "Parameters":
  22507. case "ConstructorParameters":
  22508. case "ReadonlyArray":
  22509. return ["Array"];
  22510. case "ReadonlyMap":
  22511. return ["Map"];
  22512. case "ReadonlySet":
  22513. return ["Set"];
  22514. // Vue ref wrapper types — handled here so that runtime type
  22515. // inference still works when `vue` types cannot be resolved
  22516. // (e.g. consumed as built artifacts in another package). #14729
  22517. case "Ref":
  22518. case "ShallowRef":
  22519. case "ComputedRef":
  22520. case "WritableComputedRef":
  22521. return ["Object"];
  22522. case "MaybeRef":
  22523. case "MaybeRefOrGetter": {
  22524. const types = /* @__PURE__ */ new Set(["Object"]);
  22525. if (node.typeName.name === "MaybeRefOrGetter") {
  22526. types.add("Function");
  22527. }
  22528. if (node.typeParameters && node.typeParameters.params[0]) {
  22529. for (const t of inferRuntimeType(
  22530. ctx,
  22531. node.typeParameters.params[0],
  22532. scope,
  22533. false,
  22534. typeParameters
  22535. )) {
  22536. types.add(t);
  22537. }
  22538. }
  22539. return Array.from(types);
  22540. }
  22541. case "NonNullable":
  22542. if (node.typeParameters && node.typeParameters.params[0]) {
  22543. return inferRuntimeType(
  22544. ctx,
  22545. node.typeParameters.params[0],
  22546. scope
  22547. ).filter((t) => t !== "null");
  22548. }
  22549. break;
  22550. case "Extract":
  22551. if (node.typeParameters && node.typeParameters.params[1]) {
  22552. return inferRuntimeType(
  22553. ctx,
  22554. node.typeParameters.params[1],
  22555. scope
  22556. );
  22557. }
  22558. break;
  22559. case "Exclude":
  22560. case "OmitThisParameter":
  22561. if (node.typeParameters && node.typeParameters.params[0]) {
  22562. return inferRuntimeType(
  22563. ctx,
  22564. node.typeParameters.params[0],
  22565. scope
  22566. );
  22567. }
  22568. break;
  22569. }
  22570. }
  22571. }
  22572. break;
  22573. }
  22574. case "TSParenthesizedType":
  22575. return inferRuntimeType(ctx, node.typeAnnotation, scope);
  22576. case "TSUnionType":
  22577. return flattenTypes(ctx, node.types, scope, isKeyOf, typeParameters);
  22578. case "TSIntersectionType": {
  22579. return flattenTypes(
  22580. ctx,
  22581. node.types,
  22582. scope,
  22583. isKeyOf,
  22584. typeParameters
  22585. ).filter((t) => t !== UNKNOWN_TYPE);
  22586. }
  22587. case "TSMappedType": {
  22588. const { typeAnnotation, typeParameter } = node;
  22589. if (typeAnnotation && typeAnnotation.type === "TSIndexedAccessType" && typeParameter && typeParameter.constraint && typeParameters) {
  22590. const constraint = typeParameter.constraint;
  22591. if (constraint.type === "TSTypeOperator" && constraint.operator === "keyof" && constraint.typeAnnotation && constraint.typeAnnotation.type === "TSTypeReference" && constraint.typeAnnotation.typeName.type === "Identifier") {
  22592. const typeName = constraint.typeAnnotation.typeName.name;
  22593. const index = typeAnnotation.indexType;
  22594. const obj = typeAnnotation.objectType;
  22595. 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) {
  22596. const targetType = typeParameters[typeName];
  22597. if (targetType) {
  22598. return inferRuntimeType(ctx, targetType, scope);
  22599. }
  22600. }
  22601. }
  22602. }
  22603. return [UNKNOWN_TYPE];
  22604. }
  22605. case "TSEnumDeclaration":
  22606. return inferEnumType(node);
  22607. case "TSSymbolKeyword":
  22608. return ["Symbol"];
  22609. case "TSIndexedAccessType": {
  22610. const types = resolveIndexType(ctx, node, scope);
  22611. return flattenTypes(ctx, types, scope, isKeyOf);
  22612. }
  22613. case "ClassDeclaration":
  22614. return ["Object"];
  22615. case "TSImportType": {
  22616. const sourceScope = importSourceToScope(
  22617. ctx,
  22618. node.argument,
  22619. scope,
  22620. node.argument.value
  22621. );
  22622. const resolved = resolveTypeReference(ctx, node, sourceScope);
  22623. if (resolved) {
  22624. return inferRuntimeType(ctx, resolved, resolved._ownerScope);
  22625. }
  22626. break;
  22627. }
  22628. case "TSTypeQuery": {
  22629. const id = node.exprName;
  22630. if (id.type === "Identifier") {
  22631. const matched = scope.declares[id.name];
  22632. if (matched) {
  22633. return inferRuntimeType(ctx, matched, matched._ownerScope, isKeyOf);
  22634. }
  22635. }
  22636. break;
  22637. }
  22638. // e.g. readonly
  22639. case "TSTypeOperator": {
  22640. return inferRuntimeType(
  22641. ctx,
  22642. node.typeAnnotation,
  22643. scope,
  22644. node.operator === "keyof"
  22645. );
  22646. }
  22647. case "TSAnyKeyword": {
  22648. if (isKeyOf) {
  22649. return ["String", "Number", "Symbol"];
  22650. }
  22651. break;
  22652. }
  22653. }
  22654. } catch (e) {
  22655. } finally {
  22656. ctx.silentOnExtendsFailure = prevSilent;
  22657. }
  22658. return [UNKNOWN_TYPE];
  22659. }
  22660. function flattenTypes(ctx, types, scope, isKeyOf = false, typeParameters = void 0) {
  22661. if (types.length === 1) {
  22662. return inferRuntimeType(
  22663. ctx,
  22664. types[0],
  22665. types[0]._ownerScope || scope,
  22666. isKeyOf,
  22667. typeParameters
  22668. );
  22669. }
  22670. return [
  22671. ...new Set(
  22672. [].concat(
  22673. ...types.map(
  22674. (t) => inferRuntimeType(
  22675. ctx,
  22676. t,
  22677. t._ownerScope || scope,
  22678. isKeyOf,
  22679. typeParameters
  22680. )
  22681. )
  22682. )
  22683. )
  22684. ];
  22685. }
  22686. function inferEnumType(node) {
  22687. const types = /* @__PURE__ */ new Set();
  22688. for (const m of node.members) {
  22689. if (m.initializer) {
  22690. switch (m.initializer.type) {
  22691. case "StringLiteral":
  22692. types.add("String");
  22693. break;
  22694. case "NumericLiteral":
  22695. types.add("Number");
  22696. break;
  22697. }
  22698. }
  22699. }
  22700. return types.size ? [...types] : ["Number"];
  22701. }
  22702. function resolveExtractPropTypes({ props }, scope) {
  22703. const res = { props: {} };
  22704. for (const key in props) {
  22705. const raw = props[key];
  22706. res.props[key] = reverseInferType(
  22707. raw.key,
  22708. raw.typeAnnotation.typeAnnotation,
  22709. scope
  22710. );
  22711. }
  22712. return res;
  22713. }
  22714. function reverseInferType(key, node, scope, optional = true, checkObjectSyntax = true) {
  22715. if (checkObjectSyntax && node.type === "TSTypeLiteral") {
  22716. const typeType = findStaticPropertyType(node, "type");
  22717. if (typeType) {
  22718. const requiredType = findStaticPropertyType(node, "required");
  22719. const optional2 = requiredType && requiredType.type === "TSLiteralType" && requiredType.literal.type === "BooleanLiteral" ? !requiredType.literal.value : true;
  22720. return reverseInferType(key, typeType, scope, optional2, false);
  22721. }
  22722. } else if (node.type === "TSTypeReference" && node.typeName.type === "Identifier") {
  22723. if (node.typeName.name.endsWith("Constructor")) {
  22724. return createProperty(
  22725. key,
  22726. ctorToType(node.typeName.name),
  22727. scope,
  22728. optional
  22729. );
  22730. } else if (node.typeName.name === "PropType" && node.typeParameters) {
  22731. return createProperty(key, node.typeParameters.params[0], scope, optional);
  22732. }
  22733. }
  22734. if ((node.type === "TSTypeReference" || node.type === "TSImportType") && node.typeParameters) {
  22735. for (const t of node.typeParameters.params) {
  22736. const inferred = reverseInferType(key, t, scope, optional);
  22737. if (inferred) return inferred;
  22738. }
  22739. }
  22740. return createProperty(key, { type: `TSNullKeyword` }, scope, optional);
  22741. }
  22742. function ctorToType(ctorType) {
  22743. const ctor = ctorType.slice(0, -11);
  22744. switch (ctor) {
  22745. case "String":
  22746. case "Number":
  22747. case "Boolean":
  22748. return { type: `TS${ctor}Keyword` };
  22749. case "Array":
  22750. case "Function":
  22751. case "Object":
  22752. case "Set":
  22753. case "Map":
  22754. case "WeakSet":
  22755. case "WeakMap":
  22756. case "Date":
  22757. case "Promise":
  22758. return {
  22759. type: "TSTypeReference",
  22760. typeName: { type: "Identifier", name: ctor }
  22761. };
  22762. }
  22763. return { type: `TSNullKeyword` };
  22764. }
  22765. function findStaticPropertyType(node, key) {
  22766. const prop = node.members.find(
  22767. (m) => m.type === "TSPropertySignature" && getStringLiteralKey(m) === key && m.typeAnnotation
  22768. );
  22769. return prop && prop.typeAnnotation.typeAnnotation;
  22770. }
  22771. function resolveReturnType(ctx, arg, scope) {
  22772. var _a;
  22773. let resolved = arg;
  22774. if (arg.type === "TSTypeReference" || arg.type === "TSTypeQuery" || arg.type === "TSImportType") {
  22775. resolved = resolveTypeReference(ctx, arg, scope);
  22776. }
  22777. if (!resolved) return;
  22778. if (resolved.type === "TSFunctionType") {
  22779. return (_a = resolved.typeAnnotation) == null ? void 0 : _a.typeAnnotation;
  22780. }
  22781. if (resolved.type === "TSDeclareFunction") {
  22782. return resolved.returnType;
  22783. }
  22784. }
  22785. function resolveUnionType(ctx, node, scope) {
  22786. if (node.type === "TSTypeReference") {
  22787. const resolved = resolveTypeReference(ctx, node, scope);
  22788. if (resolved) node = resolved;
  22789. }
  22790. let types;
  22791. if (node.type === "TSUnionType") {
  22792. types = node.types.flatMap((node2) => resolveUnionType(ctx, node2, scope));
  22793. } else {
  22794. types = [node];
  22795. }
  22796. return types;
  22797. }
  22798. const DEFINE_MODEL = "defineModel";
  22799. function processDefineModel(ctx, node, declId) {
  22800. if (!isCallOf(node, DEFINE_MODEL)) {
  22801. return false;
  22802. }
  22803. ctx.hasDefineModelCall = true;
  22804. const type = node.typeParameters && node.typeParameters.params[0] || void 0;
  22805. let modelName;
  22806. let options;
  22807. const arg0 = node.arguments[0] && CompilerDOM.unwrapTSNode(node.arguments[0]);
  22808. const hasName = arg0 && (arg0.type === "StringLiteral" || arg0.type === "TemplateLiteral" && arg0.expressions.length === 0);
  22809. if (hasName) {
  22810. modelName = arg0.type === "StringLiteral" ? arg0.value : arg0.quasis[0].value.cooked;
  22811. options = node.arguments[1];
  22812. } else {
  22813. modelName = "modelValue";
  22814. options = arg0;
  22815. }
  22816. if (ctx.modelDecls[modelName]) {
  22817. ctx.error(`duplicate model name ${JSON.stringify(modelName)}`, node);
  22818. }
  22819. let optionsString = options && ctx.getString(options);
  22820. let optionsRemoved = !options;
  22821. const runtimeOptionNodes = [];
  22822. if (options && options.type === "ObjectExpression" && !options.properties.some((p) => p.type === "SpreadElement" || p.computed)) {
  22823. let removed = 0;
  22824. for (let i = options.properties.length - 1; i >= 0; i--) {
  22825. const p = options.properties[i];
  22826. const next = options.properties[i + 1];
  22827. const start = p.start;
  22828. const end = next ? next.start : options.end - 1;
  22829. 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"))) {
  22830. optionsString = optionsString.slice(0, start - options.start) + optionsString.slice(end - options.start);
  22831. } else {
  22832. removed++;
  22833. ctx.s.remove(ctx.startOffset + start, ctx.startOffset + end);
  22834. runtimeOptionNodes.push(p);
  22835. }
  22836. }
  22837. if (removed === options.properties.length) {
  22838. optionsRemoved = true;
  22839. ctx.s.remove(
  22840. ctx.startOffset + (hasName ? arg0.end : options.start),
  22841. ctx.startOffset + options.end
  22842. );
  22843. }
  22844. }
  22845. ctx.modelDecls[modelName] = {
  22846. type,
  22847. options: optionsString,
  22848. runtimeOptionNodes,
  22849. identifier: declId && declId.type === "Identifier" ? declId.name : void 0
  22850. };
  22851. ctx.bindingMetadata[modelName] = "props";
  22852. ctx.s.overwrite(
  22853. ctx.startOffset + node.callee.start,
  22854. ctx.startOffset + node.callee.end,
  22855. ctx.helper("useModel")
  22856. );
  22857. ctx.s.appendLeft(
  22858. ctx.startOffset + (node.arguments.length ? node.arguments[0].start : node.end - 1),
  22859. `__props, ` + (hasName ? `` : `${JSON.stringify(modelName)}${optionsRemoved ? `` : `, `}`)
  22860. );
  22861. return true;
  22862. }
  22863. function genModelProps(ctx) {
  22864. if (!ctx.hasDefineModelCall) return;
  22865. const isProd = !!ctx.options.isProd;
  22866. let modelPropsDecl = "";
  22867. for (const [name, { type, options: runtimeOptions }] of Object.entries(
  22868. ctx.modelDecls
  22869. )) {
  22870. let skipCheck = false;
  22871. let codegenOptions = ``;
  22872. let runtimeTypes = type && inferRuntimeType(ctx, type);
  22873. if (runtimeTypes) {
  22874. const hasBoolean = runtimeTypes.includes("Boolean");
  22875. const hasFunction = runtimeTypes.includes("Function");
  22876. const hasUnknownType = runtimeTypes.includes(UNKNOWN_TYPE);
  22877. if (hasUnknownType) {
  22878. if (hasBoolean || hasFunction) {
  22879. runtimeTypes = runtimeTypes.filter((t) => t !== UNKNOWN_TYPE);
  22880. skipCheck = true;
  22881. } else {
  22882. runtimeTypes = ["null"];
  22883. }
  22884. }
  22885. if (!isProd) {
  22886. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}` + (skipCheck ? ", skipCheck: true" : "");
  22887. } else if (hasBoolean || runtimeOptions && hasFunction) {
  22888. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}`;
  22889. } else ;
  22890. }
  22891. let decl;
  22892. if (codegenOptions && runtimeOptions) {
  22893. decl = ctx.isTS ? `{ ${codegenOptions}, ...${runtimeOptions} }` : `Object.assign({ ${codegenOptions} }, ${runtimeOptions})`;
  22894. } else if (codegenOptions) {
  22895. decl = `{ ${codegenOptions} }`;
  22896. } else if (runtimeOptions) {
  22897. decl = runtimeOptions;
  22898. } else {
  22899. decl = `{}`;
  22900. }
  22901. modelPropsDecl += `
  22902. ${JSON.stringify(name)}: ${decl},`;
  22903. const modifierPropName = JSON.stringify(
  22904. name === "modelValue" ? `modelModifiers` : `${name}Modifiers`
  22905. );
  22906. modelPropsDecl += `
  22907. ${modifierPropName}: {},`;
  22908. }
  22909. return `{${modelPropsDecl}
  22910. }`;
  22911. }
  22912. const DEFINE_PROPS = "defineProps";
  22913. const WITH_DEFAULTS = "withDefaults";
  22914. function processDefineProps(ctx, node, declId, isWithDefaults = false) {
  22915. if (!isCallOf(node, DEFINE_PROPS)) {
  22916. return processWithDefaults(ctx, node, declId);
  22917. }
  22918. if (ctx.hasDefinePropsCall) {
  22919. ctx.error(`duplicate ${DEFINE_PROPS}() call`, node);
  22920. }
  22921. ctx.hasDefinePropsCall = true;
  22922. ctx.propsRuntimeDecl = node.arguments[0];
  22923. if (ctx.propsRuntimeDecl) {
  22924. for (const key of getObjectOrArrayExpressionKeys(ctx.propsRuntimeDecl)) {
  22925. if (!(key in ctx.bindingMetadata)) {
  22926. ctx.bindingMetadata[key] = "props";
  22927. }
  22928. }
  22929. }
  22930. if (node.typeParameters) {
  22931. if (ctx.propsRuntimeDecl) {
  22932. ctx.error(
  22933. `${DEFINE_PROPS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  22934. node
  22935. );
  22936. }
  22937. ctx.propsTypeDecl = node.typeParameters.params[0];
  22938. }
  22939. if (!isWithDefaults && declId && declId.type === "ObjectPattern") {
  22940. processPropsDestructure(ctx, declId);
  22941. }
  22942. ctx.propsCall = node;
  22943. ctx.propsDecl = declId;
  22944. return true;
  22945. }
  22946. function processWithDefaults(ctx, node, declId) {
  22947. if (!isCallOf(node, WITH_DEFAULTS)) {
  22948. return false;
  22949. }
  22950. if (!processDefineProps(
  22951. ctx,
  22952. node.arguments[0],
  22953. declId,
  22954. true
  22955. )) {
  22956. ctx.error(
  22957. `${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`,
  22958. node.arguments[0] || node
  22959. );
  22960. }
  22961. if (ctx.propsRuntimeDecl) {
  22962. ctx.error(
  22963. `${WITH_DEFAULTS} can only be used with type-based ${DEFINE_PROPS} declaration.`,
  22964. node
  22965. );
  22966. }
  22967. if (declId && declId.type === "ObjectPattern") {
  22968. ctx.warn(
  22969. `${WITH_DEFAULTS}() is unnecessary when using destructure with ${DEFINE_PROPS}().
  22970. Reactive destructure will be disabled when using withDefaults().
  22971. Prefer using destructure default values, e.g. const { foo = 1 } = defineProps(...). `,
  22972. node.callee
  22973. );
  22974. }
  22975. ctx.propsRuntimeDefaults = node.arguments[1];
  22976. if (!ctx.propsRuntimeDefaults) {
  22977. ctx.error(`The 2nd argument of ${WITH_DEFAULTS} is required.`, node);
  22978. }
  22979. ctx.propsCall = node;
  22980. return true;
  22981. }
  22982. function genRuntimeProps(ctx) {
  22983. let propsDecls;
  22984. if (ctx.propsRuntimeDecl) {
  22985. propsDecls = ctx.getString(ctx.propsRuntimeDecl).trim();
  22986. if (ctx.propsDestructureDecl) {
  22987. const defaults = [];
  22988. for (const key in ctx.propsDestructuredBindings) {
  22989. const d = genDestructuredDefaultValue(ctx, key);
  22990. const finalKey = getEscapedPropName(key);
  22991. if (d)
  22992. defaults.push(
  22993. `${finalKey}: ${d.valueString}${d.needSkipFactory ? `, __skip_${finalKey}: true` : ``}`
  22994. );
  22995. }
  22996. if (defaults.length) {
  22997. propsDecls = `/*@__PURE__*/${ctx.helper(
  22998. `mergeDefaults`
  22999. )}(${propsDecls}, {
  23000. ${defaults.join(",\n ")}
  23001. })`;
  23002. }
  23003. }
  23004. } else if (ctx.propsTypeDecl) {
  23005. propsDecls = extractRuntimeProps(ctx);
  23006. }
  23007. const modelsDecls = genModelProps(ctx);
  23008. if (propsDecls && modelsDecls) {
  23009. return `/*@__PURE__*/${ctx.helper(
  23010. "mergeModels"
  23011. )}(${propsDecls}, ${modelsDecls})`;
  23012. } else {
  23013. return modelsDecls || propsDecls;
  23014. }
  23015. }
  23016. function extractRuntimeProps(ctx) {
  23017. const props = resolveRuntimePropsFromType(ctx, ctx.propsTypeDecl);
  23018. if (!props.length) {
  23019. return;
  23020. }
  23021. const propStrings = [];
  23022. const hasStaticDefaults = hasStaticWithDefaults(ctx);
  23023. for (const prop of props) {
  23024. propStrings.push(genRuntimePropFromType(ctx, prop, hasStaticDefaults));
  23025. if ("bindingMetadata" in ctx && !(prop.key in ctx.bindingMetadata)) {
  23026. ctx.bindingMetadata[prop.key] = "props";
  23027. }
  23028. }
  23029. let propsDecls = `{
  23030. ${propStrings.join(",\n ")}
  23031. }`;
  23032. if (ctx.propsRuntimeDefaults && !hasStaticDefaults) {
  23033. propsDecls = `/*@__PURE__*/${ctx.helper(
  23034. "mergeDefaults"
  23035. )}(${propsDecls}, ${ctx.getString(ctx.propsRuntimeDefaults)})`;
  23036. }
  23037. return propsDecls;
  23038. }
  23039. function resolveRuntimePropsFromType(ctx, node) {
  23040. const props = [];
  23041. const elements = resolveTypeElements(ctx, node);
  23042. for (const key in elements.props) {
  23043. const e = elements.props[key];
  23044. let type = inferRuntimeType(ctx, e);
  23045. let skipCheck = false;
  23046. if (type.includes(UNKNOWN_TYPE)) {
  23047. if (type.includes("Boolean") || type.includes("Function")) {
  23048. type = type.filter((t) => t !== UNKNOWN_TYPE);
  23049. skipCheck = true;
  23050. } else {
  23051. type = ["null"];
  23052. }
  23053. }
  23054. props.push({
  23055. key,
  23056. required: !e.optional,
  23057. type: type || [`null`],
  23058. skipCheck
  23059. });
  23060. }
  23061. return props;
  23062. }
  23063. function genRuntimePropFromType(ctx, { key, required, type, skipCheck }, hasStaticDefaults) {
  23064. let defaultString;
  23065. const destructured = genDestructuredDefaultValue(ctx, key, type);
  23066. if (destructured) {
  23067. defaultString = `default: ${destructured.valueString}${destructured.needSkipFactory ? `, skipFactory: true` : ``}`;
  23068. } else if (hasStaticDefaults) {
  23069. const prop = ctx.propsRuntimeDefaults.properties.find(
  23070. (node) => {
  23071. if (node.type === "SpreadElement") return false;
  23072. return resolveObjectKey(node.key, node.computed) === key;
  23073. }
  23074. );
  23075. if (prop) {
  23076. if (prop.type === "ObjectProperty") {
  23077. defaultString = `default: ${ctx.getString(prop.value)}`;
  23078. } else {
  23079. let paramsString = "";
  23080. if (prop.params.length) {
  23081. const start = prop.params[0].start;
  23082. const end = prop.params[prop.params.length - 1].end;
  23083. paramsString = ctx.getString({ start, end });
  23084. }
  23085. defaultString = `${prop.async ? "async " : ""}${prop.kind !== "method" ? `${prop.kind} ` : ""}default(${paramsString}) ${ctx.getString(prop.body)}`;
  23086. }
  23087. }
  23088. }
  23089. const finalKey = getEscapedPropName(key);
  23090. if (!ctx.options.isProd) {
  23091. return `${finalKey}: { ${concatStrings([
  23092. `type: ${toRuntimeTypeString(type)}`,
  23093. `required: ${required}`,
  23094. skipCheck && "skipCheck: true",
  23095. defaultString
  23096. ])} }`;
  23097. } else if (type.some(
  23098. (el) => el === "Boolean" || (!hasStaticDefaults || defaultString) && el === "Function"
  23099. )) {
  23100. return `${finalKey}: { ${concatStrings([
  23101. `type: ${toRuntimeTypeString(type)}`,
  23102. defaultString
  23103. ])} }`;
  23104. } else {
  23105. if (ctx.isCE) {
  23106. if (defaultString) {
  23107. return `${finalKey}: ${`{ ${defaultString}, type: ${toRuntimeTypeString(
  23108. type
  23109. )} }`}`;
  23110. } else {
  23111. return `${finalKey}: {type: ${toRuntimeTypeString(type)}}`;
  23112. }
  23113. }
  23114. return `${finalKey}: ${defaultString ? `{ ${defaultString} }` : `{}`}`;
  23115. }
  23116. }
  23117. function hasStaticWithDefaults(ctx) {
  23118. return !!(ctx.propsRuntimeDefaults && ctx.propsRuntimeDefaults.type === "ObjectExpression" && ctx.propsRuntimeDefaults.properties.every(
  23119. (node) => node.type !== "SpreadElement" && (!node.computed || node.key.type.endsWith("Literal"))
  23120. ));
  23121. }
  23122. function genDestructuredDefaultValue(ctx, key, inferredType) {
  23123. const destructured = ctx.propsDestructuredBindings[key];
  23124. const defaultVal = destructured && destructured.default;
  23125. if (defaultVal) {
  23126. const value = ctx.getString(defaultVal);
  23127. const unwrapped = CompilerDOM.unwrapTSNode(defaultVal);
  23128. if (inferredType && inferredType.length && !inferredType.includes("null")) {
  23129. const valueType = inferValueType(unwrapped);
  23130. if (valueType && !inferredType.includes(valueType)) {
  23131. ctx.error(
  23132. `Default value of prop "${key}" does not match declared type.`,
  23133. unwrapped
  23134. );
  23135. }
  23136. }
  23137. const needSkipFactory = !inferredType && (CompilerDOM.isFunctionType(unwrapped) || unwrapped.type === "Identifier");
  23138. const needFactoryWrap = !needSkipFactory && !isLiteralNode(unwrapped) && !(inferredType == null ? void 0 : inferredType.includes("Function"));
  23139. return {
  23140. valueString: needFactoryWrap ? `() => (${value})` : value,
  23141. needSkipFactory
  23142. };
  23143. }
  23144. }
  23145. function inferValueType(node) {
  23146. switch (node.type) {
  23147. case "StringLiteral":
  23148. return "String";
  23149. case "NumericLiteral":
  23150. return "Number";
  23151. case "BooleanLiteral":
  23152. return "Boolean";
  23153. case "ObjectExpression":
  23154. return "Object";
  23155. case "ArrayExpression":
  23156. return "Array";
  23157. case "FunctionExpression":
  23158. case "ArrowFunctionExpression":
  23159. return "Function";
  23160. }
  23161. }
  23162. function processPropsDestructure(ctx, declId) {
  23163. if (ctx.options.propsDestructure === "error") {
  23164. ctx.error(`Props destructure is explicitly prohibited via config.`, declId);
  23165. } else if (ctx.options.propsDestructure === false) {
  23166. return;
  23167. }
  23168. ctx.propsDestructureDecl = declId;
  23169. const registerBinding = (key, local, defaultValue) => {
  23170. ctx.propsDestructuredBindings[key] = { local, default: defaultValue };
  23171. if (local !== key) {
  23172. ctx.bindingMetadata[local] = "props-aliased";
  23173. (ctx.bindingMetadata.__propsAliases || (ctx.bindingMetadata.__propsAliases = {}))[local] = key;
  23174. }
  23175. };
  23176. for (const prop of declId.properties) {
  23177. if (prop.type === "ObjectProperty") {
  23178. const propKey = resolveObjectKey(prop.key, prop.computed);
  23179. if (!propKey) {
  23180. ctx.error(
  23181. `${DEFINE_PROPS}() destructure cannot use computed key.`,
  23182. prop.key
  23183. );
  23184. }
  23185. if (prop.value.type === "AssignmentPattern") {
  23186. const { left, right } = prop.value;
  23187. if (left.type !== "Identifier") {
  23188. ctx.error(
  23189. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  23190. left
  23191. );
  23192. }
  23193. registerBinding(propKey, left.name, right);
  23194. } else if (prop.value.type === "Identifier") {
  23195. registerBinding(propKey, prop.value.name);
  23196. } else {
  23197. ctx.error(
  23198. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  23199. prop.value
  23200. );
  23201. }
  23202. } else {
  23203. ctx.propsDestructureRestId = prop.argument.name;
  23204. ctx.bindingMetadata[ctx.propsDestructureRestId] = "setup-reactive-const";
  23205. }
  23206. }
  23207. }
  23208. function transformDestructuredProps(ctx, vueImportAliases) {
  23209. if (ctx.options.propsDestructure === false) {
  23210. return;
  23211. }
  23212. const rootScope = /* @__PURE__ */ Object.create(null);
  23213. const scopeStack = [rootScope];
  23214. const functionScopeStack = [rootScope];
  23215. let currentScope = rootScope;
  23216. const excludedIds = /* @__PURE__ */ new WeakSet();
  23217. const parentStack = [];
  23218. const propsLocalToPublicMap = /* @__PURE__ */ Object.create(null);
  23219. for (const key in ctx.propsDestructuredBindings) {
  23220. const { local } = ctx.propsDestructuredBindings[key];
  23221. rootScope[local] = true;
  23222. propsLocalToPublicMap[local] = key;
  23223. }
  23224. function pushScope(isFunctionScope = false) {
  23225. const scope = currentScope = Object.create(currentScope);
  23226. scopeStack.push(scope);
  23227. if (isFunctionScope) {
  23228. functionScopeStack.push(scope);
  23229. }
  23230. }
  23231. function popScope(isFunctionScope = false) {
  23232. scopeStack.pop();
  23233. if (isFunctionScope) {
  23234. functionScopeStack.pop();
  23235. }
  23236. currentScope = scopeStack[scopeStack.length - 1] || null;
  23237. }
  23238. function registerLocalBinding(id, scope = currentScope) {
  23239. excludedIds.add(id);
  23240. if (scope) {
  23241. scope[id.name] = false;
  23242. } else {
  23243. ctx.error(
  23244. "registerBinding called without active scope, something is wrong.",
  23245. id
  23246. );
  23247. }
  23248. }
  23249. function walkScope(node, isRoot = false) {
  23250. for (const stmt of node.body) {
  23251. if (stmt.type === "VariableDeclaration") {
  23252. walkVariableDeclaration(stmt, isRoot);
  23253. } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
  23254. if (stmt.declare || !stmt.id) continue;
  23255. registerLocalBinding(stmt.id);
  23256. } else if (stmt.type === "ExportNamedDeclaration" && stmt.declaration && stmt.declaration.type === "VariableDeclaration") {
  23257. walkVariableDeclaration(stmt.declaration, isRoot);
  23258. } else if (stmt.type === "LabeledStatement" && stmt.body.type === "VariableDeclaration") {
  23259. walkVariableDeclaration(stmt.body, isRoot);
  23260. }
  23261. }
  23262. }
  23263. function walkVariableDeclaration(stmt, isRoot = false, scope = stmt.kind === "var" ? functionScopeStack[functionScopeStack.length - 1] : currentScope) {
  23264. if (stmt.declare) {
  23265. return;
  23266. }
  23267. for (const decl of stmt.declarations) {
  23268. const isDefineProps = isRoot && decl.init && isCallOf(CompilerDOM.unwrapTSNode(decl.init), "defineProps");
  23269. for (const id of CompilerDOM.extractIdentifiers(decl.id)) {
  23270. if (isDefineProps) {
  23271. excludedIds.add(id);
  23272. } else {
  23273. registerLocalBinding(id, scope);
  23274. }
  23275. }
  23276. }
  23277. }
  23278. function walkFunctionScopeVarDeclarations(scopeNode, isRoot = false) {
  23279. const scope = functionScopeStack[functionScopeStack.length - 1];
  23280. estreeWalker.walk(scopeNode, {
  23281. enter(node, parent) {
  23282. if (parent && parent.type.startsWith("TS") && !CompilerDOM.TS_NODE_TYPES.includes(parent.type)) {
  23283. return this.skip();
  23284. }
  23285. if (CompilerDOM.isFunctionType(node) || node.type === "ClassDeclaration" || node.type === "ClassExpression") {
  23286. return this.skip();
  23287. }
  23288. if (node.type === "VariableDeclaration" && node.kind === "var") {
  23289. walkVariableDeclaration(node, isRoot && parent === scopeNode, scope);
  23290. }
  23291. }
  23292. });
  23293. }
  23294. function rewriteId(id, parent, parentStack2) {
  23295. if (parent.type === "AssignmentExpression" && id === parent.left || parent.type === "UpdateExpression") {
  23296. ctx.error(`Cannot assign to destructured props as they are readonly.`, id);
  23297. }
  23298. if (CompilerDOM.isStaticProperty(parent) && parent.shorthand) {
  23299. if (!parent.inPattern || CompilerDOM.isInDestructureAssignment(parent, parentStack2)) {
  23300. ctx.s.appendLeft(
  23301. id.end + ctx.startOffset,
  23302. `: ${shared.genPropsAccessExp(propsLocalToPublicMap[id.name])}`
  23303. );
  23304. }
  23305. } else {
  23306. ctx.s.overwrite(
  23307. id.start + ctx.startOffset,
  23308. id.end + ctx.startOffset,
  23309. shared.genPropsAccessExp(propsLocalToPublicMap[id.name])
  23310. );
  23311. }
  23312. }
  23313. function checkUsage(node, method, alias = method) {
  23314. if (isCallOf(node, alias)) {
  23315. const arg = CompilerDOM.unwrapTSNode(node.arguments[0]);
  23316. if (arg.type === "Identifier" && currentScope[arg.name]) {
  23317. ctx.error(
  23318. `"${arg.name}" is a destructured prop and should not be passed directly to ${method}(). Pass a getter () => ${arg.name} instead.`,
  23319. arg
  23320. );
  23321. }
  23322. }
  23323. }
  23324. const ast = ctx.scriptSetupAst;
  23325. walkFunctionScopeVarDeclarations(ast, true);
  23326. walkScope(ast, true);
  23327. estreeWalker.walk(ast, {
  23328. enter(node, parent) {
  23329. parent && parentStack.push(parent);
  23330. if (parent && parent.type.startsWith("TS") && !CompilerDOM.TS_NODE_TYPES.includes(parent.type)) {
  23331. return this.skip();
  23332. }
  23333. checkUsage(node, "watch", vueImportAliases.watch);
  23334. checkUsage(node, "toRef", vueImportAliases.toRef);
  23335. if (CompilerDOM.isFunctionType(node)) {
  23336. pushScope(true);
  23337. CompilerDOM.walkFunctionParams(node, registerLocalBinding);
  23338. if (node.body.type === "BlockStatement") {
  23339. walkFunctionScopeVarDeclarations(node.body);
  23340. walkScope(node.body);
  23341. }
  23342. return;
  23343. }
  23344. if (node.type === "CatchClause") {
  23345. pushScope();
  23346. if (node.param && node.param.type === "Identifier") {
  23347. registerLocalBinding(node.param);
  23348. }
  23349. walkScope(node.body);
  23350. return;
  23351. }
  23352. if (node.type === "ForOfStatement" || node.type === "ForInStatement" || node.type === "ForStatement") {
  23353. pushScope();
  23354. const varDecl = node.type === "ForStatement" ? node.init : node.left;
  23355. if (varDecl && varDecl.type === "VariableDeclaration") {
  23356. walkVariableDeclaration(varDecl);
  23357. }
  23358. if (node.body.type === "BlockStatement") {
  23359. walkScope(node.body);
  23360. }
  23361. return;
  23362. }
  23363. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent)) {
  23364. pushScope();
  23365. walkScope(node);
  23366. return;
  23367. }
  23368. if (node.type === "Identifier") {
  23369. if (CompilerDOM.isReferencedIdentifier(node, parent, parentStack) && !excludedIds.has(node)) {
  23370. if (currentScope[node.name]) {
  23371. rewriteId(node, parent, parentStack);
  23372. }
  23373. }
  23374. }
  23375. },
  23376. leave(node, parent) {
  23377. parent && parentStack.pop();
  23378. if (CompilerDOM.isFunctionType(node)) {
  23379. popScope(true);
  23380. } else if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent)) {
  23381. popScope();
  23382. } else if (node.type === "CatchClause" || node.type === "ForOfStatement" || node.type === "ForInStatement" || node.type === "ForStatement") {
  23383. popScope();
  23384. }
  23385. }
  23386. });
  23387. }
  23388. const DEFINE_EMITS = "defineEmits";
  23389. function processDefineEmits(ctx, node, declId) {
  23390. if (!isCallOf(node, DEFINE_EMITS)) {
  23391. return false;
  23392. }
  23393. if (ctx.hasDefineEmitCall) {
  23394. ctx.error(`duplicate ${DEFINE_EMITS}() call`, node);
  23395. }
  23396. ctx.hasDefineEmitCall = true;
  23397. ctx.emitsRuntimeDecl = node.arguments[0];
  23398. if (node.typeParameters) {
  23399. if (ctx.emitsRuntimeDecl) {
  23400. ctx.error(
  23401. `${DEFINE_EMITS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  23402. node
  23403. );
  23404. }
  23405. ctx.emitsTypeDecl = node.typeParameters.params[0];
  23406. }
  23407. ctx.emitDecl = declId;
  23408. return true;
  23409. }
  23410. function genRuntimeEmits(ctx) {
  23411. let emitsDecl = "";
  23412. if (ctx.emitsRuntimeDecl) {
  23413. emitsDecl = ctx.getString(ctx.emitsRuntimeDecl).trim();
  23414. } else if (ctx.emitsTypeDecl) {
  23415. const typeDeclaredEmits = extractRuntimeEmits(ctx);
  23416. emitsDecl = typeDeclaredEmits.size ? `[${Array.from(typeDeclaredEmits).map((k) => JSON.stringify(k)).join(", ")}]` : ``;
  23417. }
  23418. if (ctx.hasDefineModelCall) {
  23419. let modelEmitsDecl = `[${Object.keys(ctx.modelDecls).map((n) => JSON.stringify(`update:${n}`)).join(", ")}]`;
  23420. emitsDecl = emitsDecl ? `/*@__PURE__*/${ctx.helper(
  23421. "mergeModels"
  23422. )}(${emitsDecl}, ${modelEmitsDecl})` : modelEmitsDecl;
  23423. }
  23424. return emitsDecl;
  23425. }
  23426. function extractRuntimeEmits(ctx) {
  23427. const emits = /* @__PURE__ */ new Set();
  23428. const node = ctx.emitsTypeDecl;
  23429. if (node.type === "TSFunctionType") {
  23430. extractEventNames(ctx, node.parameters[0], emits);
  23431. return emits;
  23432. }
  23433. const { props, calls } = resolveTypeElements(ctx, node);
  23434. let hasProperty = false;
  23435. for (const key in props) {
  23436. emits.add(key);
  23437. hasProperty = true;
  23438. }
  23439. if (calls) {
  23440. if (hasProperty) {
  23441. ctx.error(
  23442. `defineEmits() type cannot mixed call signature and property syntax.`,
  23443. node
  23444. );
  23445. }
  23446. for (const call of calls) {
  23447. extractEventNames(ctx, call.parameters[0], emits);
  23448. }
  23449. }
  23450. return emits;
  23451. }
  23452. function extractEventNames(ctx, eventName, emits) {
  23453. if (eventName.type === "Identifier" && eventName.typeAnnotation && eventName.typeAnnotation.type === "TSTypeAnnotation") {
  23454. const types = resolveUnionType(ctx, eventName.typeAnnotation.typeAnnotation);
  23455. for (const type of types) {
  23456. if (type.type === "TSLiteralType") {
  23457. if (type.literal.type !== "UnaryExpression" && type.literal.type !== "TemplateLiteral") {
  23458. emits.add(String(type.literal.value));
  23459. }
  23460. }
  23461. }
  23462. }
  23463. }
  23464. const DEFINE_EXPOSE = "defineExpose";
  23465. function processDefineExpose(ctx, node) {
  23466. if (isCallOf(node, DEFINE_EXPOSE)) {
  23467. if (ctx.hasDefineExposeCall) {
  23468. ctx.error(`duplicate ${DEFINE_EXPOSE}() call`, node);
  23469. }
  23470. ctx.hasDefineExposeCall = true;
  23471. return true;
  23472. }
  23473. return false;
  23474. }
  23475. const DEFINE_SLOTS = "defineSlots";
  23476. function processDefineSlots(ctx, node, declId) {
  23477. if (!isCallOf(node, DEFINE_SLOTS)) {
  23478. return false;
  23479. }
  23480. if (ctx.hasDefineSlotsCall) {
  23481. ctx.error(`duplicate ${DEFINE_SLOTS}() call`, node);
  23482. }
  23483. ctx.hasDefineSlotsCall = true;
  23484. if (node.arguments.length > 0) {
  23485. ctx.error(`${DEFINE_SLOTS}() cannot accept arguments`, node);
  23486. }
  23487. if (declId) {
  23488. ctx.s.overwrite(
  23489. ctx.startOffset + node.start,
  23490. ctx.startOffset + node.end,
  23491. `${ctx.helper("useSlots")}()`
  23492. );
  23493. }
  23494. return true;
  23495. }
  23496. const DEFINE_OPTIONS = "defineOptions";
  23497. function processDefineOptions(ctx, node) {
  23498. if (!isCallOf(node, DEFINE_OPTIONS)) {
  23499. return false;
  23500. }
  23501. if (ctx.hasDefineOptionsCall) {
  23502. ctx.error(`duplicate ${DEFINE_OPTIONS}() call`, node);
  23503. }
  23504. if (node.typeParameters) {
  23505. ctx.error(`${DEFINE_OPTIONS}() cannot accept type arguments`, node);
  23506. }
  23507. if (!node.arguments[0]) return true;
  23508. ctx.hasDefineOptionsCall = true;
  23509. ctx.optionsRuntimeDecl = CompilerDOM.unwrapTSNode(node.arguments[0]);
  23510. let propsOption = void 0;
  23511. let emitsOption = void 0;
  23512. let exposeOption = void 0;
  23513. let slotsOption = void 0;
  23514. if (ctx.optionsRuntimeDecl.type === "ObjectExpression") {
  23515. for (const prop of ctx.optionsRuntimeDecl.properties) {
  23516. if ((prop.type === "ObjectProperty" || prop.type === "ObjectMethod") && prop.key.type === "Identifier") {
  23517. switch (prop.key.name) {
  23518. case "props":
  23519. propsOption = prop;
  23520. break;
  23521. case "emits":
  23522. emitsOption = prop;
  23523. break;
  23524. case "expose":
  23525. exposeOption = prop;
  23526. break;
  23527. case "slots":
  23528. slotsOption = prop;
  23529. break;
  23530. }
  23531. }
  23532. }
  23533. }
  23534. if (propsOption) {
  23535. ctx.error(
  23536. `${DEFINE_OPTIONS}() cannot be used to declare props. Use ${DEFINE_PROPS}() instead.`,
  23537. propsOption
  23538. );
  23539. }
  23540. if (emitsOption) {
  23541. ctx.error(
  23542. `${DEFINE_OPTIONS}() cannot be used to declare emits. Use ${DEFINE_EMITS}() instead.`,
  23543. emitsOption
  23544. );
  23545. }
  23546. if (exposeOption) {
  23547. ctx.error(
  23548. `${DEFINE_OPTIONS}() cannot be used to declare expose. Use ${DEFINE_EXPOSE}() instead.`,
  23549. exposeOption
  23550. );
  23551. }
  23552. if (slotsOption) {
  23553. ctx.error(
  23554. `${DEFINE_OPTIONS}() cannot be used to declare slots. Use ${DEFINE_SLOTS}() instead.`,
  23555. slotsOption
  23556. );
  23557. }
  23558. return true;
  23559. }
  23560. function processAwait(ctx, node, needSemi, isStatement) {
  23561. const argumentStart = node.argument.extra && node.argument.extra.parenthesized ? node.argument.extra.parenStart : node.argument.start;
  23562. const startOffset = ctx.startOffset;
  23563. const argumentStr = ctx.descriptor.source.slice(
  23564. argumentStart + startOffset,
  23565. node.argument.end + startOffset
  23566. );
  23567. const containsNestedAwait = /\bawait\b/.test(argumentStr);
  23568. ctx.s.overwrite(
  23569. node.start + startOffset,
  23570. argumentStart + startOffset,
  23571. `${needSemi ? `;` : ``}(
  23572. ([__temp,__restore] = ${ctx.helper(
  23573. `withAsyncContext`
  23574. )}(${containsNestedAwait ? `async ` : ``}() => `
  23575. );
  23576. ctx.s.appendLeft(
  23577. node.end + startOffset,
  23578. `)),
  23579. ${isStatement ? `` : `__temp = `}await __temp,
  23580. __restore()${isStatement ? `` : `,
  23581. __temp`}
  23582. )`
  23583. );
  23584. }
  23585. const MACROS = [
  23586. DEFINE_PROPS,
  23587. DEFINE_EMITS,
  23588. DEFINE_EXPOSE,
  23589. DEFINE_OPTIONS,
  23590. DEFINE_SLOTS,
  23591. DEFINE_MODEL,
  23592. WITH_DEFAULTS
  23593. ];
  23594. function compileScript(sfc, options) {
  23595. var _a, _b, _c;
  23596. if (!options.id) {
  23597. warnOnce(
  23598. `compileScript now requires passing the \`id\` option.
  23599. Upgrade your vite or vue-loader version for compatibility with the latest experimental proposals.`
  23600. );
  23601. }
  23602. const { script, scriptSetup, source, filename } = sfc;
  23603. const hoistStatic = options.hoistStatic !== false && !script;
  23604. const scopeId = options.id ? options.id.replace(/^data-v-/, "") : "";
  23605. const scriptLang = script && script.lang;
  23606. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  23607. const isJSOrTS = isJS(scriptLang, scriptSetupLang) || isTS(scriptLang, scriptSetupLang);
  23608. if (script && scriptSetup && scriptLang !== scriptSetupLang) {
  23609. throw new Error(
  23610. `[@vue/compiler-sfc] <script> and <script setup> must have the same language type.`
  23611. );
  23612. }
  23613. if (!scriptSetup) {
  23614. if (!script) {
  23615. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
  23616. }
  23617. if (script.lang && !isJSOrTS) {
  23618. return script;
  23619. }
  23620. const ctx2 = new ScriptCompileContext(sfc, options);
  23621. return processNormalScript(ctx2, scopeId);
  23622. }
  23623. if (scriptSetupLang && !isJSOrTS) {
  23624. return scriptSetup;
  23625. }
  23626. const ctx = new ScriptCompileContext(sfc, options);
  23627. const scriptBindings = /* @__PURE__ */ Object.create(null);
  23628. const setupBindings = /* @__PURE__ */ Object.create(null);
  23629. let defaultExport;
  23630. let hasAwait = false;
  23631. let hasInlinedSsrRenderFn = false;
  23632. const startOffset = ctx.startOffset;
  23633. const endOffset = ctx.endOffset;
  23634. const scriptStartOffset = script && script.loc.start.offset;
  23635. const scriptEndOffset = script && script.loc.end.offset;
  23636. function hoistNode(node) {
  23637. const start = node.start + startOffset;
  23638. let end = node.end + startOffset;
  23639. if (node.trailingComments && node.trailingComments.length > 0) {
  23640. const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
  23641. end = lastCommentNode.end + startOffset;
  23642. }
  23643. while (end <= source.length) {
  23644. if (!/\s/.test(source.charAt(end))) {
  23645. break;
  23646. }
  23647. end++;
  23648. }
  23649. ctx.s.move(start, end, 0);
  23650. }
  23651. function registerUserImport(source2, local, imported, isType, isFromSetup, needTemplateUsageCheck) {
  23652. let isUsedInTemplate = needTemplateUsageCheck;
  23653. if (needTemplateUsageCheck && ctx.isTS && sfc.template && !sfc.template.src && !sfc.template.lang) {
  23654. isUsedInTemplate = isImportUsed(local, sfc, options.templateOptions);
  23655. }
  23656. ctx.userImports[local] = {
  23657. isType,
  23658. imported,
  23659. local,
  23660. source: source2,
  23661. isFromSetup,
  23662. isUsedInTemplate
  23663. };
  23664. }
  23665. function checkInvalidScopeReference(node, method) {
  23666. if (!node) return;
  23667. CompilerDOM.walkIdentifiers(node, (id) => {
  23668. const binding = setupBindings[id.name];
  23669. if (binding && binding !== "literal-const") {
  23670. ctx.error(
  23671. `\`${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.`,
  23672. id
  23673. );
  23674. }
  23675. });
  23676. }
  23677. const scriptAst = ctx.scriptAst;
  23678. const scriptSetupAst = ctx.scriptSetupAst;
  23679. if (scriptAst) {
  23680. for (const node of scriptAst.body) {
  23681. if (node.type === "ImportDeclaration") {
  23682. for (const specifier of node.specifiers) {
  23683. const imported = getImportedName(specifier);
  23684. registerUserImport(
  23685. node.source.value,
  23686. specifier.local.name,
  23687. imported,
  23688. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  23689. false,
  23690. !options.inlineTemplate
  23691. );
  23692. }
  23693. }
  23694. }
  23695. }
  23696. for (const node of scriptSetupAst.body) {
  23697. if (node.type === "ImportDeclaration") {
  23698. hoistNode(node);
  23699. let removed = 0;
  23700. const removeSpecifier = (i) => {
  23701. const removeLeft = i > removed;
  23702. removed++;
  23703. const current = node.specifiers[i];
  23704. const next = node.specifiers[i + 1];
  23705. ctx.s.remove(
  23706. removeLeft ? node.specifiers[i - 1].end + startOffset : current.start + startOffset,
  23707. next && !removeLeft ? next.start + startOffset : current.end + startOffset
  23708. );
  23709. };
  23710. for (let i = 0; i < node.specifiers.length; i++) {
  23711. const specifier = node.specifiers[i];
  23712. const local = specifier.local.name;
  23713. const imported = getImportedName(specifier);
  23714. const source2 = node.source.value;
  23715. const existing = ctx.userImports[local];
  23716. if (source2 === "vue" && MACROS.includes(imported)) {
  23717. if (local === imported) {
  23718. warnOnce(
  23719. `\`${imported}\` is a compiler macro and no longer needs to be imported.`
  23720. );
  23721. } else {
  23722. ctx.error(
  23723. `\`${imported}\` is a compiler macro and cannot be aliased to a different name.`,
  23724. specifier
  23725. );
  23726. }
  23727. removeSpecifier(i);
  23728. } else if (existing) {
  23729. if (existing.source === source2 && existing.imported === imported) {
  23730. removeSpecifier(i);
  23731. } else {
  23732. ctx.error(
  23733. `different imports aliased to same local name.`,
  23734. specifier
  23735. );
  23736. }
  23737. } else {
  23738. registerUserImport(
  23739. source2,
  23740. local,
  23741. imported,
  23742. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  23743. true,
  23744. !options.inlineTemplate
  23745. );
  23746. }
  23747. }
  23748. if (node.specifiers.length && removed === node.specifiers.length) {
  23749. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  23750. }
  23751. }
  23752. }
  23753. const vueImportAliases = {};
  23754. for (const key in ctx.userImports) {
  23755. const { source: source2, imported, local } = ctx.userImports[key];
  23756. if (source2 === "vue") vueImportAliases[imported] = local;
  23757. }
  23758. if (script && scriptAst) {
  23759. for (const node of scriptAst.body) {
  23760. if (node.type === "ExportDefaultDeclaration") {
  23761. defaultExport = node;
  23762. let optionProperties;
  23763. if (defaultExport.declaration.type === "ObjectExpression") {
  23764. optionProperties = defaultExport.declaration.properties;
  23765. } else if (defaultExport.declaration.type === "CallExpression" && defaultExport.declaration.arguments[0] && defaultExport.declaration.arguments[0].type === "ObjectExpression") {
  23766. optionProperties = defaultExport.declaration.arguments[0].properties;
  23767. }
  23768. if (optionProperties) {
  23769. for (const p of optionProperties) {
  23770. if (p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name") {
  23771. ctx.hasDefaultExportName = true;
  23772. }
  23773. if ((p.type === "ObjectMethod" || p.type === "ObjectProperty") && p.key.type === "Identifier" && p.key.name === "render") {
  23774. ctx.hasDefaultExportRender = true;
  23775. }
  23776. }
  23777. }
  23778. const start = node.start + scriptStartOffset;
  23779. const end = node.declaration.start + scriptStartOffset;
  23780. ctx.s.overwrite(start, end, `const ${normalScriptDefaultVar} = `);
  23781. } else if (node.type === "ExportNamedDeclaration") {
  23782. const defaultSpecifier = node.specifiers.find(
  23783. (s) => s.exported.type === "Identifier" && s.exported.name === "default"
  23784. );
  23785. if (defaultSpecifier) {
  23786. defaultExport = node;
  23787. if (node.specifiers.length > 1) {
  23788. ctx.s.remove(
  23789. defaultSpecifier.start + scriptStartOffset,
  23790. defaultSpecifier.end + scriptStartOffset
  23791. );
  23792. } else {
  23793. ctx.s.remove(
  23794. node.start + scriptStartOffset,
  23795. node.end + scriptStartOffset
  23796. );
  23797. }
  23798. if (node.source) {
  23799. ctx.s.prepend(
  23800. `import { ${defaultSpecifier.local.name} as ${normalScriptDefaultVar} } from '${node.source.value}'
  23801. `
  23802. );
  23803. } else {
  23804. ctx.s.appendLeft(
  23805. scriptEndOffset,
  23806. `
  23807. const ${normalScriptDefaultVar} = ${defaultSpecifier.local.name}
  23808. `
  23809. );
  23810. }
  23811. }
  23812. if (node.declaration) {
  23813. walkDeclaration(
  23814. "script",
  23815. node.declaration,
  23816. scriptBindings,
  23817. vueImportAliases,
  23818. hoistStatic
  23819. );
  23820. }
  23821. } else if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  23822. walkDeclaration(
  23823. "script",
  23824. node,
  23825. scriptBindings,
  23826. vueImportAliases,
  23827. hoistStatic
  23828. );
  23829. }
  23830. }
  23831. if (scriptStartOffset > startOffset) {
  23832. if (!/\n$/.test(script.content.trim())) {
  23833. ctx.s.appendLeft(scriptEndOffset, `
  23834. `);
  23835. }
  23836. ctx.s.move(scriptStartOffset, scriptEndOffset, 0);
  23837. }
  23838. }
  23839. for (const node of scriptSetupAst.body) {
  23840. if (node.type === "ExpressionStatement") {
  23841. const expr = CompilerDOM.unwrapTSNode(node.expression);
  23842. if (processDefineProps(ctx, expr) || processDefineEmits(ctx, expr) || processDefineOptions(ctx, expr) || processDefineSlots(ctx, expr)) {
  23843. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  23844. } else if (processDefineExpose(ctx, expr)) {
  23845. const callee = expr.callee;
  23846. ctx.s.overwrite(
  23847. callee.start + startOffset,
  23848. callee.end + startOffset,
  23849. "__expose"
  23850. );
  23851. } else {
  23852. processDefineModel(ctx, expr);
  23853. }
  23854. }
  23855. if (node.type === "VariableDeclaration" && !node.declare) {
  23856. const total = node.declarations.length;
  23857. let left = total;
  23858. let lastNonRemoved;
  23859. for (let i = 0; i < total; i++) {
  23860. const decl = node.declarations[i];
  23861. const init = decl.init && CompilerDOM.unwrapTSNode(decl.init);
  23862. if (init) {
  23863. if (processDefineOptions(ctx, init)) {
  23864. ctx.error(
  23865. `${DEFINE_OPTIONS}() has no returning value, it cannot be assigned.`,
  23866. node
  23867. );
  23868. }
  23869. const isDefineProps = processDefineProps(ctx, init, decl.id);
  23870. if (ctx.propsDestructureRestId) {
  23871. setupBindings[ctx.propsDestructureRestId] = "setup-reactive-const";
  23872. }
  23873. const isDefineEmits = !isDefineProps && processDefineEmits(ctx, init, decl.id);
  23874. !isDefineEmits && (processDefineSlots(ctx, init, decl.id) || processDefineModel(ctx, init, decl.id));
  23875. if (isDefineProps && !ctx.propsDestructureRestId && ctx.propsDestructureDecl) {
  23876. if (left === 1) {
  23877. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  23878. } else {
  23879. let start = decl.start + startOffset;
  23880. let end = decl.end + startOffset;
  23881. if (i === total - 1) {
  23882. start = node.declarations[lastNonRemoved].end + startOffset;
  23883. } else {
  23884. end = node.declarations[i + 1].start + startOffset;
  23885. }
  23886. ctx.s.remove(start, end);
  23887. left--;
  23888. }
  23889. } else if (isDefineEmits) {
  23890. ctx.s.overwrite(
  23891. startOffset + init.start,
  23892. startOffset + init.end,
  23893. "__emit"
  23894. );
  23895. } else {
  23896. lastNonRemoved = i;
  23897. }
  23898. }
  23899. }
  23900. }
  23901. let isAllLiteral = false;
  23902. if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  23903. isAllLiteral = walkDeclaration(
  23904. "scriptSetup",
  23905. node,
  23906. setupBindings,
  23907. vueImportAliases,
  23908. hoistStatic,
  23909. !!ctx.propsDestructureDecl
  23910. );
  23911. }
  23912. if (hoistStatic && isAllLiteral) {
  23913. hoistNode(node);
  23914. }
  23915. if (node.type === "VariableDeclaration" && !node.declare || node.type.endsWith("Statement")) {
  23916. const scope = [scriptSetupAst.body];
  23917. estreeWalker.walk(node, {
  23918. enter(child, parent) {
  23919. if (CompilerDOM.isFunctionType(child)) {
  23920. this.skip();
  23921. }
  23922. if (child.type === "BlockStatement") {
  23923. scope.push(child.body);
  23924. }
  23925. if (child.type === "AwaitExpression") {
  23926. hasAwait = true;
  23927. const currentScope = scope[scope.length - 1];
  23928. const needsSemi = currentScope.some((n, i) => {
  23929. return (scope.length === 1 || i > 0) && n.type === "ExpressionStatement" && n.start === child.start;
  23930. });
  23931. processAwait(
  23932. ctx,
  23933. child,
  23934. needsSemi,
  23935. parent.type === "ExpressionStatement"
  23936. );
  23937. }
  23938. },
  23939. exit(node2) {
  23940. if (node2.type === "BlockStatement") scope.pop();
  23941. }
  23942. });
  23943. }
  23944. if (node.type === "ExportNamedDeclaration" && node.exportKind !== "type" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration") {
  23945. ctx.error(
  23946. `<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.`,
  23947. node
  23948. );
  23949. }
  23950. if (ctx.isTS) {
  23951. if (node.type.startsWith("TS") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "VariableDeclaration" && node.declare) {
  23952. if (node.type !== "TSEnumDeclaration") {
  23953. hoistNode(node);
  23954. }
  23955. }
  23956. }
  23957. }
  23958. if (ctx.propsDestructureDecl) {
  23959. transformDestructuredProps(ctx, vueImportAliases);
  23960. }
  23961. checkInvalidScopeReference(ctx.propsRuntimeDecl, DEFINE_PROPS);
  23962. checkInvalidScopeReference(ctx.propsRuntimeDefaults, DEFINE_PROPS);
  23963. checkInvalidScopeReference(ctx.propsDestructureDecl, DEFINE_PROPS);
  23964. checkInvalidScopeReference(ctx.emitsRuntimeDecl, DEFINE_EMITS);
  23965. checkInvalidScopeReference(ctx.optionsRuntimeDecl, DEFINE_OPTIONS);
  23966. for (const { runtimeOptionNodes } of Object.values(ctx.modelDecls)) {
  23967. for (const node of runtimeOptionNodes) {
  23968. checkInvalidScopeReference(node, DEFINE_MODEL);
  23969. }
  23970. }
  23971. if (script) {
  23972. if (startOffset < scriptStartOffset) {
  23973. ctx.s.remove(0, startOffset);
  23974. ctx.s.remove(endOffset, scriptStartOffset);
  23975. ctx.s.remove(scriptEndOffset, source.length);
  23976. } else {
  23977. ctx.s.remove(0, scriptStartOffset);
  23978. ctx.s.remove(scriptEndOffset, startOffset);
  23979. ctx.s.remove(endOffset, source.length);
  23980. }
  23981. } else {
  23982. ctx.s.remove(0, startOffset);
  23983. ctx.s.remove(endOffset, source.length);
  23984. }
  23985. if (scriptAst) {
  23986. Object.assign(ctx.bindingMetadata, analyzeScriptBindings(scriptAst.body));
  23987. }
  23988. for (const [key, { isType, imported, source: source2 }] of Object.entries(
  23989. ctx.userImports
  23990. )) {
  23991. if (isType) continue;
  23992. ctx.bindingMetadata[key] = imported === "*" || imported === "default" && source2.endsWith(".vue") || source2 === "vue" ? "setup-const" : "setup-maybe-ref";
  23993. }
  23994. for (const key in scriptBindings) {
  23995. ctx.bindingMetadata[key] = scriptBindings[key];
  23996. }
  23997. for (const key in setupBindings) {
  23998. ctx.bindingMetadata[key] = setupBindings[key];
  23999. }
  24000. if (sfc.template && !sfc.template.src && sfc.template.ast) {
  24001. const vModelIds = resolveTemplateVModelIdentifiers(
  24002. sfc,
  24003. options.templateOptions
  24004. );
  24005. if (vModelIds.size) {
  24006. const toDemote = /* @__PURE__ */ new Set();
  24007. for (const id of vModelIds) {
  24008. if (setupBindings[id] === "setup-reactive-const") {
  24009. toDemote.add(id);
  24010. }
  24011. }
  24012. if (toDemote.size) {
  24013. for (const node of scriptSetupAst.body) {
  24014. if (node.type === "VariableDeclaration" && node.kind === "const" && !node.declare) {
  24015. const demotedInDecl = [];
  24016. for (const decl of node.declarations) {
  24017. if (decl.id.type === "Identifier" && toDemote.has(decl.id.name)) {
  24018. demotedInDecl.push(decl.id.name);
  24019. }
  24020. }
  24021. if (demotedInDecl.length) {
  24022. ctx.s.overwrite(
  24023. node.start + startOffset,
  24024. node.start + startOffset + "const".length,
  24025. "let"
  24026. );
  24027. for (const id of demotedInDecl) {
  24028. setupBindings[id] = "setup-let";
  24029. ctx.bindingMetadata[id] = "setup-let";
  24030. warnOnce(
  24031. `\`v-model\` cannot update a \`const\` reactive binding \`${id}\`. The compiler has transformed it to \`let\` to make the update work.`
  24032. );
  24033. }
  24034. }
  24035. }
  24036. }
  24037. }
  24038. }
  24039. }
  24040. if (sfc.cssVars.length && // no need to do this when targeting SSR
  24041. !((_a = options.templateOptions) == null ? void 0 : _a.ssr)) {
  24042. ctx.helperImports.add(CSS_VARS_HELPER);
  24043. ctx.helperImports.add("unref");
  24044. ctx.s.prependLeft(
  24045. startOffset,
  24046. `
  24047. ${genCssVarsCode(
  24048. sfc.cssVars,
  24049. ctx.bindingMetadata,
  24050. scopeId,
  24051. !!options.isProd
  24052. )}
  24053. `
  24054. );
  24055. }
  24056. let args = `__props`;
  24057. if (ctx.propsTypeDecl) {
  24058. args += `: any`;
  24059. }
  24060. if (ctx.propsDecl) {
  24061. if (ctx.propsDestructureRestId) {
  24062. ctx.s.overwrite(
  24063. startOffset + ctx.propsCall.start,
  24064. startOffset + ctx.propsCall.end,
  24065. `${ctx.helper(`createPropsRestProxy`)}(__props, ${JSON.stringify(
  24066. Object.keys(ctx.propsDestructuredBindings)
  24067. )})`
  24068. );
  24069. ctx.s.overwrite(
  24070. startOffset + ctx.propsDestructureDecl.start,
  24071. startOffset + ctx.propsDestructureDecl.end,
  24072. ctx.propsDestructureRestId
  24073. );
  24074. } else if (!ctx.propsDestructureDecl) {
  24075. ctx.s.overwrite(
  24076. startOffset + ctx.propsCall.start,
  24077. startOffset + ctx.propsCall.end,
  24078. "__props"
  24079. );
  24080. }
  24081. }
  24082. if (hasAwait) {
  24083. const any = ctx.isTS ? `: any` : ``;
  24084. ctx.s.prependLeft(startOffset, `
  24085. let __temp${any}, __restore${any}
  24086. `);
  24087. }
  24088. const destructureElements = ctx.hasDefineExposeCall || !options.inlineTemplate ? [`expose: __expose`] : [];
  24089. if (ctx.emitDecl) {
  24090. destructureElements.push(`emit: __emit`);
  24091. }
  24092. if (destructureElements.length) {
  24093. args += `, { ${destructureElements.join(", ")} }`;
  24094. }
  24095. let templateMap;
  24096. let returned;
  24097. const propsDecl = genRuntimeProps(ctx);
  24098. if (!options.inlineTemplate || !sfc.template && ctx.hasDefaultExportRender) {
  24099. const allBindings = {
  24100. ...scriptBindings,
  24101. ...setupBindings
  24102. };
  24103. for (const key in ctx.userImports) {
  24104. if (!ctx.userImports[key].isType && ctx.userImports[key].isUsedInTemplate) {
  24105. allBindings[key] = true;
  24106. }
  24107. }
  24108. returned = `{ `;
  24109. for (const key in allBindings) {
  24110. if (allBindings[key] === true && ctx.userImports[key].source !== "vue" && !ctx.userImports[key].source.endsWith(".vue")) {
  24111. returned += `get ${key}() { return ${key} }, `;
  24112. } else if (ctx.bindingMetadata[key] === "setup-let") {
  24113. const setArg = key === "v" ? `_v` : `v`;
  24114. returned += `get ${key}() { return ${key} }, set ${key}(${setArg}) { ${key} = ${setArg} }, `;
  24115. } else {
  24116. returned += `${key}, `;
  24117. }
  24118. }
  24119. returned = returned.replace(/, $/, "") + ` }`;
  24120. } else {
  24121. if (sfc.template && !sfc.template.src) {
  24122. if (options.templateOptions && options.templateOptions.ssr) {
  24123. hasInlinedSsrRenderFn = true;
  24124. }
  24125. const { code, ast, preamble, tips, errors, map: map2 } = compileTemplate({
  24126. filename,
  24127. ast: sfc.template.ast,
  24128. source: sfc.template.content,
  24129. inMap: sfc.template.map,
  24130. ...options.templateOptions,
  24131. id: scopeId,
  24132. scoped: sfc.styles.some((s) => s.scoped),
  24133. isProd: options.isProd,
  24134. ssrCssVars: sfc.cssVars,
  24135. compilerOptions: {
  24136. ...options.templateOptions && options.templateOptions.compilerOptions,
  24137. inline: true,
  24138. isTS: ctx.isTS,
  24139. bindingMetadata: ctx.bindingMetadata
  24140. }
  24141. });
  24142. templateMap = map2;
  24143. if (tips.length) {
  24144. tips.forEach(warnOnce);
  24145. }
  24146. const err = errors[0];
  24147. if (typeof err === "string") {
  24148. throw new Error(err);
  24149. } else if (err) {
  24150. if (err.loc) {
  24151. err.message += `
  24152. ` + sfc.filename + "\n" + shared.generateCodeFrame(
  24153. source,
  24154. err.loc.start.offset,
  24155. err.loc.end.offset
  24156. ) + `
  24157. `;
  24158. }
  24159. throw err;
  24160. }
  24161. if (preamble) {
  24162. ctx.s.prepend(preamble);
  24163. }
  24164. if (ast && ast.helpers.has(CompilerDOM.UNREF)) {
  24165. ctx.helperImports.delete("unref");
  24166. }
  24167. returned = code;
  24168. } else {
  24169. returned = `() => {}`;
  24170. }
  24171. }
  24172. if (!options.inlineTemplate && true) {
  24173. ctx.s.appendRight(
  24174. endOffset,
  24175. `
  24176. const __returned__ = ${returned}
  24177. Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })
  24178. return __returned__
  24179. }
  24180. `
  24181. );
  24182. } else {
  24183. ctx.s.appendRight(endOffset, `
  24184. return ${returned}
  24185. }
  24186. `);
  24187. }
  24188. const genDefaultAs = options.genDefaultAs ? `const ${options.genDefaultAs} =` : `export default`;
  24189. let runtimeOptions = ``;
  24190. if (!ctx.hasDefaultExportName && filename && filename !== DEFAULT_FILENAME) {
  24191. const match = filename.match(/([^/\\]+)\.\w+$/);
  24192. if (match) {
  24193. runtimeOptions += `
  24194. __name: '${match[1]}',`;
  24195. }
  24196. }
  24197. if (hasInlinedSsrRenderFn) {
  24198. runtimeOptions += `
  24199. __ssrInlineRender: true,`;
  24200. }
  24201. if (propsDecl) runtimeOptions += `
  24202. props: ${propsDecl},`;
  24203. const emitsDecl = genRuntimeEmits(ctx);
  24204. if (emitsDecl) runtimeOptions += `
  24205. emits: ${emitsDecl},`;
  24206. let definedOptions = "";
  24207. if (ctx.optionsRuntimeDecl) {
  24208. definedOptions = scriptSetup.content.slice(ctx.optionsRuntimeDecl.start, ctx.optionsRuntimeDecl.end).trim();
  24209. }
  24210. const exposeCall = ctx.hasDefineExposeCall || options.inlineTemplate ? `` : ` __expose();
  24211. `;
  24212. if (ctx.isTS) {
  24213. const def = (defaultExport ? `
  24214. ...${normalScriptDefaultVar},` : ``) + (definedOptions ? `
  24215. ...${definedOptions},` : "");
  24216. ctx.s.prependLeft(
  24217. startOffset,
  24218. `
  24219. ${genDefaultAs} /*@__PURE__*/${ctx.helper(
  24220. `defineComponent`
  24221. )}({${def}${runtimeOptions}
  24222. ${hasAwait ? `async ` : ``}setup(${args}) {
  24223. ${exposeCall}`
  24224. );
  24225. ctx.s.appendRight(endOffset, `})`);
  24226. } else {
  24227. if (defaultExport || definedOptions) {
  24228. ctx.s.prependLeft(
  24229. startOffset,
  24230. `
  24231. ${genDefaultAs} /*@__PURE__*/Object.assign(${defaultExport ? `${normalScriptDefaultVar}, ` : ""}${definedOptions ? `${definedOptions}, ` : ""}{${runtimeOptions}
  24232. ${hasAwait ? `async ` : ``}setup(${args}) {
  24233. ${exposeCall}`
  24234. );
  24235. ctx.s.appendRight(endOffset, `})`);
  24236. } else {
  24237. ctx.s.prependLeft(
  24238. startOffset,
  24239. `
  24240. ${genDefaultAs} {${runtimeOptions}
  24241. ${hasAwait ? `async ` : ``}setup(${args}) {
  24242. ${exposeCall}`
  24243. );
  24244. ctx.s.appendRight(endOffset, `}`);
  24245. }
  24246. }
  24247. if (ctx.helperImports.size > 0) {
  24248. const runtimeModuleName = (_c = (_b = options.templateOptions) == null ? void 0 : _b.compilerOptions) == null ? void 0 : _c.runtimeModuleName;
  24249. const importSrc = runtimeModuleName ? JSON.stringify(runtimeModuleName) : `'vue'`;
  24250. ctx.s.prepend(
  24251. `import { ${[...ctx.helperImports].map((h) => `${h} as _${h}`).join(", ")} } from ${importSrc}
  24252. `
  24253. );
  24254. }
  24255. const content = ctx.s.toString();
  24256. let map = options.sourceMap !== false ? ctx.s.generateMap({
  24257. source: filename,
  24258. hires: true,
  24259. includeContent: true
  24260. }) : void 0;
  24261. if (templateMap && map) {
  24262. const offset = content.indexOf(returned);
  24263. const templateLineOffset = content.slice(0, offset).split(/\r?\n/).length - 1;
  24264. map = mergeSourceMaps(map, templateMap, templateLineOffset);
  24265. }
  24266. return {
  24267. ...scriptSetup,
  24268. bindings: ctx.bindingMetadata,
  24269. imports: ctx.userImports,
  24270. content,
  24271. map,
  24272. scriptAst: scriptAst == null ? void 0 : scriptAst.body,
  24273. scriptSetupAst: scriptSetupAst == null ? void 0 : scriptSetupAst.body,
  24274. deps: ctx.deps ? [...ctx.deps] : void 0
  24275. };
  24276. }
  24277. function registerBinding(bindings, node, type) {
  24278. bindings[node.name] = type;
  24279. }
  24280. function walkDeclaration(from, node, bindings, userImportAliases, hoistStatic, isPropsDestructureEnabled = false) {
  24281. let isAllLiteral = false;
  24282. if (node.type === "VariableDeclaration") {
  24283. const isConst = node.kind === "const";
  24284. isAllLiteral = isConst && node.declarations.every(
  24285. (decl) => decl.id.type === "Identifier" && isStaticNode(decl.init)
  24286. );
  24287. for (const { id, init: _init } of node.declarations) {
  24288. const init = _init && CompilerDOM.unwrapTSNode(_init);
  24289. const isConstMacroCall = isConst && isCallOf(
  24290. init,
  24291. (c) => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS || c === DEFINE_SLOTS
  24292. );
  24293. if (id.type === "Identifier") {
  24294. let bindingType;
  24295. const userReactiveBinding = userImportAliases["reactive"];
  24296. if ((hoistStatic || from === "script") && (isAllLiteral || isConst && isStaticNode(init))) {
  24297. bindingType = "literal-const";
  24298. } else if (isCallOf(init, userReactiveBinding)) {
  24299. bindingType = isConst ? "setup-reactive-const" : "setup-let";
  24300. } else if (
  24301. // if a declaration is a const literal, we can mark it so that
  24302. // the generated render fn code doesn't need to unref() it
  24303. isConstMacroCall || isConst && canNeverBeRef(init, userReactiveBinding)
  24304. ) {
  24305. bindingType = isCallOf(init, DEFINE_PROPS) ? "setup-reactive-const" : "setup-const";
  24306. } else if (isConst) {
  24307. if (isCallOf(
  24308. init,
  24309. (m) => m === userImportAliases["ref"] || m === userImportAliases["computed"] || m === userImportAliases["shallowRef"] || m === userImportAliases["customRef"] || m === userImportAliases["toRef"] || m === userImportAliases["useTemplateRef"] || m === DEFINE_MODEL
  24310. )) {
  24311. bindingType = "setup-ref";
  24312. } else {
  24313. bindingType = "setup-maybe-ref";
  24314. }
  24315. } else {
  24316. bindingType = "setup-let";
  24317. }
  24318. registerBinding(bindings, id, bindingType);
  24319. } else {
  24320. if (isCallOf(init, DEFINE_PROPS) && isPropsDestructureEnabled) {
  24321. continue;
  24322. }
  24323. if (id.type === "ObjectPattern") {
  24324. walkObjectPattern(id, bindings, isConst, isConstMacroCall);
  24325. } else if (id.type === "ArrayPattern") {
  24326. walkArrayPattern(id, bindings, isConst, isConstMacroCall);
  24327. }
  24328. }
  24329. }
  24330. } else if (node.type === "TSEnumDeclaration") {
  24331. isAllLiteral = node.members.every(
  24332. (member) => !member.initializer || isStaticNode(member.initializer)
  24333. );
  24334. bindings[node.id.name] = isAllLiteral ? "literal-const" : "setup-const";
  24335. } else if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
  24336. bindings[node.id.name] = "setup-const";
  24337. }
  24338. return isAllLiteral;
  24339. }
  24340. function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
  24341. for (const p of node.properties) {
  24342. if (p.type === "ObjectProperty") {
  24343. if (p.key.type === "Identifier" && p.key === p.value) {
  24344. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  24345. registerBinding(bindings, p.key, type);
  24346. } else {
  24347. walkPattern(p.value, bindings, isConst, isDefineCall);
  24348. }
  24349. } else {
  24350. const type = isConst ? "setup-const" : "setup-let";
  24351. registerBinding(bindings, p.argument, type);
  24352. }
  24353. }
  24354. }
  24355. function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
  24356. for (const e of node.elements) {
  24357. e && walkPattern(e, bindings, isConst, isDefineCall);
  24358. }
  24359. }
  24360. function walkPattern(node, bindings, isConst, isDefineCall = false) {
  24361. if (node.type === "Identifier") {
  24362. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  24363. registerBinding(bindings, node, type);
  24364. } else if (node.type === "RestElement") {
  24365. const type = isConst ? "setup-const" : "setup-let";
  24366. registerBinding(bindings, node.argument, type);
  24367. } else if (node.type === "ObjectPattern") {
  24368. walkObjectPattern(node, bindings, isConst);
  24369. } else if (node.type === "ArrayPattern") {
  24370. walkArrayPattern(node, bindings, isConst);
  24371. } else if (node.type === "AssignmentPattern") {
  24372. if (node.left.type === "Identifier") {
  24373. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  24374. registerBinding(bindings, node.left, type);
  24375. } else {
  24376. walkPattern(node.left, bindings, isConst);
  24377. }
  24378. }
  24379. }
  24380. function canNeverBeRef(node, userReactiveImport) {
  24381. if (isCallOf(node, userReactiveImport)) {
  24382. return true;
  24383. }
  24384. switch (node.type) {
  24385. case "UnaryExpression":
  24386. case "BinaryExpression":
  24387. case "ArrayExpression":
  24388. case "ObjectExpression":
  24389. case "FunctionExpression":
  24390. case "ArrowFunctionExpression":
  24391. case "UpdateExpression":
  24392. case "ClassExpression":
  24393. case "TaggedTemplateExpression":
  24394. return true;
  24395. case "SequenceExpression":
  24396. return canNeverBeRef(
  24397. node.expressions[node.expressions.length - 1],
  24398. userReactiveImport
  24399. );
  24400. default:
  24401. if (isLiteralNode(node)) {
  24402. return true;
  24403. }
  24404. return false;
  24405. }
  24406. }
  24407. function isStaticNode(node) {
  24408. node = CompilerDOM.unwrapTSNode(node);
  24409. switch (node.type) {
  24410. case "UnaryExpression":
  24411. return isStaticNode(node.argument);
  24412. case "LogicalExpression":
  24413. // 1 > 2
  24414. case "BinaryExpression":
  24415. return isStaticNode(node.left) && isStaticNode(node.right);
  24416. case "ConditionalExpression": {
  24417. return isStaticNode(node.test) && isStaticNode(node.consequent) && isStaticNode(node.alternate);
  24418. }
  24419. case "SequenceExpression":
  24420. // (1, 2)
  24421. case "TemplateLiteral":
  24422. return node.expressions.every((expr) => isStaticNode(expr));
  24423. case "ParenthesizedExpression":
  24424. return isStaticNode(node.expression);
  24425. case "StringLiteral":
  24426. case "NumericLiteral":
  24427. case "BooleanLiteral":
  24428. case "NullLiteral":
  24429. case "BigIntLiteral":
  24430. return true;
  24431. }
  24432. return false;
  24433. }
  24434. function mergeSourceMaps(scriptMap, templateMap, templateLineOffset) {
  24435. const generator = new sourceMapJs.SourceMapGenerator();
  24436. const addMapping = (map, lineOffset = 0) => {
  24437. const consumer = new sourceMapJs.SourceMapConsumer(map);
  24438. consumer.sources.forEach((sourceFile) => {
  24439. generator._sources.add(sourceFile);
  24440. const sourceContent = consumer.sourceContentFor(sourceFile);
  24441. if (sourceContent != null) {
  24442. generator.setSourceContent(sourceFile, sourceContent);
  24443. }
  24444. });
  24445. consumer.eachMapping((m) => {
  24446. if (m.originalLine == null) return;
  24447. generator.addMapping({
  24448. generated: {
  24449. line: m.generatedLine + lineOffset,
  24450. column: m.generatedColumn
  24451. },
  24452. original: {
  24453. line: m.originalLine,
  24454. column: m.originalColumn
  24455. },
  24456. source: m.source,
  24457. name: m.name
  24458. });
  24459. });
  24460. };
  24461. addMapping(scriptMap);
  24462. addMapping(templateMap, templateLineOffset);
  24463. generator._sourceRoot = scriptMap.sourceRoot;
  24464. generator._file = scriptMap.file;
  24465. return generator.toJSON();
  24466. }
  24467. const version = "3.5.42";
  24468. const parseCache = parseCache$1;
  24469. const errorMessages = {
  24470. ...CompilerDOM.errorMessages,
  24471. ...CompilerDOM.DOMErrorMessages
  24472. };
  24473. const walk = estreeWalker.walk;
  24474. const shouldTransformRef = () => false;
  24475. exports.extractIdentifiers = compilerCore.extractIdentifiers;
  24476. exports.generateCodeFrame = compilerCore.generateCodeFrame;
  24477. exports.isInDestructureAssignment = compilerCore.isInDestructureAssignment;
  24478. exports.isStaticProperty = compilerCore.isStaticProperty;
  24479. exports.walkIdentifiers = compilerCore.walkIdentifiers;
  24480. exports.MagicString = MagicString;
  24481. exports.babelParse = parser$2.parse;
  24482. exports.compileScript = compileScript;
  24483. exports.compileStyle = compileStyle;
  24484. exports.compileStyleAsync = compileStyleAsync;
  24485. exports.compileTemplate = compileTemplate;
  24486. exports.errorMessages = errorMessages;
  24487. exports.extractRuntimeEmits = extractRuntimeEmits;
  24488. exports.extractRuntimeProps = extractRuntimeProps;
  24489. exports.inferRuntimeType = inferRuntimeType;
  24490. exports.invalidateTypeCache = invalidateTypeCache;
  24491. exports.parse = parse$1;
  24492. exports.parseCache = parseCache;
  24493. exports.registerTS = registerTS;
  24494. exports.resolveTypeElements = resolveTypeElements;
  24495. exports.rewriteDefault = rewriteDefault;
  24496. exports.rewriteDefaultAST = rewriteDefaultAST;
  24497. exports.shouldTransformRef = shouldTransformRef;
  24498. exports.version = version;
  24499. exports.walk = walk;