compiler-sfc.cjs.js 841 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619
  1. /**
  2. * @vue/compiler-sfc v3.5.32
  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 isImportUsed(local, sfc) {
  1684. return resolveTemplateUsedIdentifiers(sfc).has(local);
  1685. }
  1686. const templateAnalysisCache = createCache();
  1687. function resolveTemplateVModelIdentifiers(sfc) {
  1688. return resolveTemplateAnalysisResult(sfc, false).vModelIds;
  1689. }
  1690. function resolveTemplateUsedIdentifiers(sfc) {
  1691. return resolveTemplateAnalysisResult(sfc).usedIds;
  1692. }
  1693. function resolveTemplateAnalysisResult(sfc, collectUsedIds = true) {
  1694. const { content, ast } = sfc.template;
  1695. const cached = templateAnalysisCache.get(content);
  1696. if (cached && (!collectUsedIds || cached.usedIds)) {
  1697. return cached;
  1698. }
  1699. const ids = collectUsedIds ? /* @__PURE__ */ new Set() : void 0;
  1700. const vModelIds = /* @__PURE__ */ new Set();
  1701. ast.children.forEach(walk);
  1702. function walk(node) {
  1703. var _a;
  1704. switch (node.type) {
  1705. case 1:
  1706. let tag = node.tag;
  1707. if (tag.includes(".")) tag = tag.split(".")[0].trim();
  1708. if (!CompilerDOM.parserOptions.isNativeTag(tag) && !CompilerDOM.parserOptions.isBuiltInComponent(tag)) {
  1709. if (ids) {
  1710. ids.add(shared.camelize(tag));
  1711. ids.add(shared.capitalize(shared.camelize(tag)));
  1712. }
  1713. }
  1714. for (let i = 0; i < node.props.length; i++) {
  1715. const prop = node.props[i];
  1716. if (prop.type === 7) {
  1717. if (ids) {
  1718. if (!shared.isBuiltInDirective(prop.name)) {
  1719. ids.add(`v${shared.capitalize(shared.camelize(prop.name))}`);
  1720. }
  1721. }
  1722. if (prop.name === "model") {
  1723. const exp = prop.exp;
  1724. if (exp && exp.type === 4) {
  1725. const expString = exp.content.trim();
  1726. if (CompilerDOM.isSimpleIdentifier(expString) && expString !== "undefined") {
  1727. vModelIds.add(expString);
  1728. }
  1729. }
  1730. }
  1731. if (ids && prop.arg && !prop.arg.isStatic) {
  1732. extractIdentifiers(ids, prop.arg);
  1733. }
  1734. if (ids) {
  1735. if (prop.name === "for") {
  1736. extractIdentifiers(ids, prop.forParseResult.source);
  1737. } else if (prop.exp) {
  1738. extractIdentifiers(ids, prop.exp);
  1739. } else if (prop.name === "bind" && !prop.exp) {
  1740. ids.add(shared.camelize(prop.arg.content));
  1741. }
  1742. }
  1743. }
  1744. if (ids && prop.type === 6 && prop.name === "ref" && ((_a = prop.value) == null ? void 0 : _a.content)) {
  1745. ids.add(prop.value.content);
  1746. }
  1747. }
  1748. node.children.forEach(walk);
  1749. break;
  1750. case 5:
  1751. if (ids) extractIdentifiers(ids, node.content);
  1752. break;
  1753. }
  1754. }
  1755. const result = { usedIds: ids, vModelIds };
  1756. templateAnalysisCache.set(content, result);
  1757. return result;
  1758. }
  1759. function extractIdentifiers(ids, node) {
  1760. if (node.ast) {
  1761. CompilerDOM.walkIdentifiers(node.ast, (n) => ids.add(n.name));
  1762. } else if (node.ast === null) {
  1763. ids.add(node.content);
  1764. }
  1765. }
  1766. const DEFAULT_FILENAME = "anonymous.vue";
  1767. const parseCache$1 = createCache();
  1768. function parse$1(source, options = {}) {
  1769. var _a;
  1770. const sourceKey = shared.genCacheKey(source, {
  1771. ...options,
  1772. compiler: { parse: (_a = options.compiler) == null ? void 0 : _a.parse }
  1773. });
  1774. const cache = parseCache$1.get(sourceKey);
  1775. if (cache) {
  1776. return cache;
  1777. }
  1778. const {
  1779. sourceMap = true,
  1780. filename = DEFAULT_FILENAME,
  1781. sourceRoot = "",
  1782. pad = false,
  1783. ignoreEmpty = true,
  1784. compiler = CompilerDOM__namespace,
  1785. templateParseOptions = {}
  1786. } = options;
  1787. const descriptor = {
  1788. filename,
  1789. source,
  1790. template: null,
  1791. script: null,
  1792. scriptSetup: null,
  1793. styles: [],
  1794. customBlocks: [],
  1795. cssVars: [],
  1796. slotted: false,
  1797. shouldForceReload: (prevImports) => hmrShouldReload(prevImports, descriptor)
  1798. };
  1799. const errors = [];
  1800. const ast = compiler.parse(source, {
  1801. parseMode: "sfc",
  1802. prefixIdentifiers: true,
  1803. ...templateParseOptions,
  1804. onError: (e) => {
  1805. errors.push(e);
  1806. }
  1807. });
  1808. ast.children.forEach((node) => {
  1809. if (node.type !== 1) {
  1810. return;
  1811. }
  1812. if (ignoreEmpty && node.tag !== "template" && isEmpty(node) && !hasSrc(node)) {
  1813. return;
  1814. }
  1815. switch (node.tag) {
  1816. case "template":
  1817. if (!descriptor.template) {
  1818. const templateBlock = descriptor.template = createBlock(
  1819. node,
  1820. source,
  1821. false
  1822. );
  1823. if (!templateBlock.attrs.src) {
  1824. templateBlock.ast = compilerCore.createRoot(node.children, source);
  1825. }
  1826. if (templateBlock.attrs.functional) {
  1827. const err = new SyntaxError(
  1828. `<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.`
  1829. );
  1830. err.loc = node.props.find(
  1831. (p) => p.type === 6 && p.name === "functional"
  1832. ).loc;
  1833. errors.push(err);
  1834. }
  1835. } else {
  1836. errors.push(createDuplicateBlockError(node));
  1837. }
  1838. break;
  1839. case "script":
  1840. const scriptBlock = createBlock(node, source, pad);
  1841. const isSetup = !!scriptBlock.attrs.setup;
  1842. if (isSetup && !descriptor.scriptSetup) {
  1843. descriptor.scriptSetup = scriptBlock;
  1844. break;
  1845. }
  1846. if (!isSetup && !descriptor.script) {
  1847. descriptor.script = scriptBlock;
  1848. break;
  1849. }
  1850. errors.push(createDuplicateBlockError(node, isSetup));
  1851. break;
  1852. case "style":
  1853. const styleBlock = createBlock(node, source, pad);
  1854. if (styleBlock.attrs.vars) {
  1855. errors.push(
  1856. new SyntaxError(
  1857. `<style vars> has been replaced by a new proposal: https://github.com/vuejs/rfcs/pull/231`
  1858. )
  1859. );
  1860. }
  1861. descriptor.styles.push(styleBlock);
  1862. break;
  1863. default:
  1864. descriptor.customBlocks.push(createBlock(node, source, pad));
  1865. break;
  1866. }
  1867. });
  1868. if (!descriptor.template && !descriptor.script && !descriptor.scriptSetup) {
  1869. errors.push(
  1870. new SyntaxError(
  1871. `At least one <template> or <script> is required in a single file component. ${descriptor.filename}`
  1872. )
  1873. );
  1874. }
  1875. if (descriptor.scriptSetup) {
  1876. if (descriptor.scriptSetup.src) {
  1877. errors.push(
  1878. new SyntaxError(
  1879. `<script setup> cannot use the "src" attribute because its syntax will be ambiguous outside of the component.`
  1880. )
  1881. );
  1882. descriptor.scriptSetup = null;
  1883. }
  1884. if (descriptor.script && descriptor.script.src) {
  1885. errors.push(
  1886. new SyntaxError(
  1887. `<script> cannot use the "src" attribute when <script setup> is also present because they must be processed together.`
  1888. )
  1889. );
  1890. descriptor.script = null;
  1891. }
  1892. }
  1893. let templateColumnOffset = 0;
  1894. if (descriptor.template && (descriptor.template.lang === "pug" || descriptor.template.lang === "jade")) {
  1895. [descriptor.template.content, templateColumnOffset] = dedent(
  1896. descriptor.template.content
  1897. );
  1898. }
  1899. if (sourceMap) {
  1900. const genMap = (block, columnOffset = 0) => {
  1901. if (block && !block.src) {
  1902. block.map = generateSourceMap(
  1903. filename,
  1904. source,
  1905. block.content,
  1906. sourceRoot,
  1907. !pad || block.type === "template" ? block.loc.start.line - 1 : 0,
  1908. columnOffset
  1909. );
  1910. }
  1911. };
  1912. genMap(descriptor.template, templateColumnOffset);
  1913. genMap(descriptor.script);
  1914. descriptor.styles.forEach((s) => genMap(s));
  1915. descriptor.customBlocks.forEach((s) => genMap(s));
  1916. }
  1917. descriptor.cssVars = parseCssVars(descriptor);
  1918. const slottedRE = /(?:::v-|:)slotted\(/;
  1919. descriptor.slotted = descriptor.styles.some(
  1920. (s) => s.scoped && slottedRE.test(s.content)
  1921. );
  1922. const result = {
  1923. descriptor,
  1924. errors
  1925. };
  1926. parseCache$1.set(sourceKey, result);
  1927. return result;
  1928. }
  1929. function createDuplicateBlockError(node, isScriptSetup = false) {
  1930. const err = new SyntaxError(
  1931. `Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element`
  1932. );
  1933. err.loc = node.loc;
  1934. return err;
  1935. }
  1936. function createBlock(node, source, pad) {
  1937. const type = node.tag;
  1938. const loc = node.innerLoc;
  1939. const attrs = {};
  1940. const block = {
  1941. type,
  1942. content: source.slice(loc.start.offset, loc.end.offset),
  1943. loc,
  1944. attrs
  1945. };
  1946. if (pad) {
  1947. block.content = padContent(source, block, pad) + block.content;
  1948. }
  1949. node.props.forEach((p) => {
  1950. if (p.type === 6) {
  1951. const name = p.name;
  1952. attrs[name] = p.value ? p.value.content || true : true;
  1953. if (name === "lang") {
  1954. block.lang = p.value && p.value.content;
  1955. } else if (name === "src") {
  1956. block.src = p.value && p.value.content;
  1957. } else if (type === "style") {
  1958. if (name === "scoped") {
  1959. block.scoped = true;
  1960. } else if (name === "module") {
  1961. block.module = attrs[name];
  1962. }
  1963. } else if (type === "script" && name === "setup") {
  1964. block.setup = attrs.setup;
  1965. }
  1966. }
  1967. });
  1968. return block;
  1969. }
  1970. const splitRE = /\r?\n/g;
  1971. const emptyRE = /^(?:\/\/)?\s*$/;
  1972. const replaceRE = /./g;
  1973. function generateSourceMap(filename, source, generated, sourceRoot, lineOffset, columnOffset) {
  1974. const map = new sourceMapJs.SourceMapGenerator({
  1975. file: filename.replace(/\\/g, "/"),
  1976. sourceRoot: sourceRoot.replace(/\\/g, "/")
  1977. });
  1978. map.setSourceContent(filename, source);
  1979. map._sources.add(filename);
  1980. generated.split(splitRE).forEach((line, index) => {
  1981. if (!emptyRE.test(line)) {
  1982. const originalLine = index + 1 + lineOffset;
  1983. const generatedLine = index + 1;
  1984. for (let i = 0; i < line.length; i++) {
  1985. if (!/\s/.test(line[i])) {
  1986. map._mappings.add({
  1987. originalLine,
  1988. originalColumn: i + columnOffset,
  1989. generatedLine,
  1990. generatedColumn: i,
  1991. source: filename,
  1992. name: null
  1993. });
  1994. }
  1995. }
  1996. }
  1997. });
  1998. return map.toJSON();
  1999. }
  2000. function padContent(content, block, pad) {
  2001. content = content.slice(0, block.loc.start.offset);
  2002. if (pad === "space") {
  2003. return content.replace(replaceRE, " ");
  2004. } else {
  2005. const offset = content.split(splitRE).length;
  2006. const padChar = block.type === "script" && !block.lang ? "//\n" : "\n";
  2007. return Array(offset).join(padChar);
  2008. }
  2009. }
  2010. function hasSrc(node) {
  2011. return node.props.some((p) => {
  2012. if (p.type !== 6) {
  2013. return false;
  2014. }
  2015. return p.name === "src";
  2016. });
  2017. }
  2018. function isEmpty(node) {
  2019. for (let i = 0; i < node.children.length; i++) {
  2020. const child = node.children[i];
  2021. if (child.type !== 2 || child.content.trim() !== "") {
  2022. return false;
  2023. }
  2024. }
  2025. return true;
  2026. }
  2027. function hmrShouldReload(prevImports, next) {
  2028. if (!next.scriptSetup || next.scriptSetup.lang !== "ts" && next.scriptSetup.lang !== "tsx") {
  2029. return false;
  2030. }
  2031. for (const key in prevImports) {
  2032. if (!prevImports[key].isUsedInTemplate && isImportUsed(key, next)) {
  2033. return true;
  2034. }
  2035. }
  2036. return false;
  2037. }
  2038. function dedent(s) {
  2039. const lines = s.split("\n");
  2040. const minIndent = lines.reduce(function(minIndent2, line) {
  2041. var _a, _b;
  2042. if (line.trim() === "") {
  2043. return minIndent2;
  2044. }
  2045. const indent = ((_b = (_a = line.match(/^\s*/)) == null ? void 0 : _a[0]) == null ? void 0 : _b.length) || 0;
  2046. return Math.min(indent, minIndent2);
  2047. }, Infinity);
  2048. if (minIndent === 0) {
  2049. return [s, minIndent];
  2050. }
  2051. return [
  2052. lines.map(function(line) {
  2053. return line.slice(minIndent);
  2054. }).join("\n"),
  2055. minIndent
  2056. ];
  2057. }
  2058. function isRelativeUrl(url) {
  2059. const firstChar = url.charAt(0);
  2060. return firstChar === "." || firstChar === "~" || firstChar === "@" || firstChar === "#";
  2061. }
  2062. const externalRE = /^(?:https?:)?\/\//;
  2063. function isExternalUrl(url) {
  2064. return externalRE.test(url);
  2065. }
  2066. const dataUrlRE = /^\s*data:/i;
  2067. function isDataUrl(url) {
  2068. return dataUrlRE.test(url);
  2069. }
  2070. function normalizeDecodedImportPath(source) {
  2071. try {
  2072. return decodeURIComponent(source);
  2073. } catch {
  2074. return source;
  2075. }
  2076. }
  2077. function parseUrl(url) {
  2078. const firstChar = url.charAt(0);
  2079. if (firstChar === "~") {
  2080. const secondChar = url.charAt(1);
  2081. url = url.slice(secondChar === "/" ? 2 : 1);
  2082. }
  2083. return parseUriParts(url);
  2084. }
  2085. function parseUriParts(urlString) {
  2086. return url.parse(shared.isString(urlString) ? urlString : "", false, true);
  2087. }
  2088. const resourceUrlTagConfig = {
  2089. video: ["src", "poster"],
  2090. source: ["src"],
  2091. img: ["src"],
  2092. image: ["xlink:href", "href"]
  2093. };
  2094. const defaultAssetUrlOptions = {
  2095. base: null,
  2096. includeAbsolute: false,
  2097. tags: {
  2098. ...resourceUrlTagConfig,
  2099. use: ["xlink:href", "href"]
  2100. }
  2101. };
  2102. const normalizeOptions = (options) => {
  2103. if (Object.keys(options).some((key) => shared.isArray(options[key]))) {
  2104. return {
  2105. ...defaultAssetUrlOptions,
  2106. tags: options
  2107. };
  2108. }
  2109. return {
  2110. ...defaultAssetUrlOptions,
  2111. ...options
  2112. };
  2113. };
  2114. const createAssetUrlTransformWithOptions = (options) => {
  2115. return (node, context) => transformAssetUrl(node, context, options);
  2116. };
  2117. function canTransformHashImport(tag, attrName) {
  2118. var _a;
  2119. return !!((_a = resourceUrlTagConfig[tag]) == null ? void 0 : _a.includes(attrName));
  2120. }
  2121. const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
  2122. if (node.type === 1) {
  2123. if (!node.props.length) {
  2124. return;
  2125. }
  2126. const tags = options.tags || defaultAssetUrlOptions.tags;
  2127. const attrs = tags[node.tag];
  2128. const wildCardAttrs = tags["*"];
  2129. if (!attrs && !wildCardAttrs) {
  2130. return;
  2131. }
  2132. const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
  2133. node.props.forEach((attr, index) => {
  2134. if (attr.type !== 6 || !assetAttrs.includes(attr.name) || !attr.value) {
  2135. return;
  2136. }
  2137. const urlValue = attr.value.content;
  2138. const isHashOnlyValue = urlValue[0] === "#";
  2139. if (isExternalUrl(urlValue) || isDataUrl(urlValue) || isHashOnlyValue && !canTransformHashImport(node.tag, attr.name) || !options.includeAbsolute && !isRelativeUrl(urlValue)) {
  2140. return;
  2141. }
  2142. const url = parseUrl(urlValue);
  2143. if (options.base && urlValue[0] === ".") {
  2144. const base = parseUrl(options.base);
  2145. const protocol = base.protocol || "";
  2146. const host = base.host ? protocol + "//" + base.host : "";
  2147. const basePath = base.path || "/";
  2148. attr.value.content = host + (path$1.posix || path$1).join(basePath, url.path + (url.hash || ""));
  2149. return;
  2150. }
  2151. const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
  2152. node.props[index] = {
  2153. type: 7,
  2154. name: "bind",
  2155. arg: compilerCore.createSimpleExpression(attr.name, true, attr.loc),
  2156. exp,
  2157. modifiers: [],
  2158. loc: attr.loc
  2159. };
  2160. });
  2161. }
  2162. };
  2163. function resolveOrRegisterImport(source, loc, context) {
  2164. const normalizedSource = normalizeDecodedImportPath(source);
  2165. const existingIndex = context.imports.findIndex(
  2166. (i) => i.path === normalizedSource
  2167. );
  2168. if (existingIndex > -1) {
  2169. return {
  2170. name: `_imports_${existingIndex}`,
  2171. exp: context.imports[existingIndex].exp
  2172. };
  2173. }
  2174. const name = `_imports_${context.imports.length}`;
  2175. const exp = compilerCore.createSimpleExpression(
  2176. name,
  2177. false,
  2178. loc,
  2179. 3
  2180. );
  2181. context.imports.push({
  2182. exp,
  2183. path: normalizedSource
  2184. });
  2185. return { name, exp };
  2186. }
  2187. function getImportsExpressionExp(path2, hash, loc, context) {
  2188. if (!path2 && !hash) {
  2189. return compilerCore.createSimpleExpression(`''`, false, loc, 3);
  2190. }
  2191. if (!path2 && hash) {
  2192. const { exp } = resolveOrRegisterImport(hash, loc, context);
  2193. return exp;
  2194. }
  2195. if (path2 && !hash) {
  2196. const { exp } = resolveOrRegisterImport(path2, loc, context);
  2197. return exp;
  2198. }
  2199. const { name } = resolveOrRegisterImport(path2, loc, context);
  2200. const hashExp = `${name} + '${hash}'`;
  2201. const finalExp = compilerCore.createSimpleExpression(
  2202. hashExp,
  2203. false,
  2204. loc,
  2205. 3
  2206. );
  2207. if (!context.hoistStatic) {
  2208. return finalExp;
  2209. }
  2210. const existingHoistIndex = context.hoists.findIndex((h) => {
  2211. return h && h.type === 4 && !h.isStatic && h.content === hashExp;
  2212. });
  2213. if (existingHoistIndex > -1) {
  2214. return compilerCore.createSimpleExpression(
  2215. `_hoisted_${existingHoistIndex + 1}`,
  2216. false,
  2217. loc,
  2218. 3
  2219. );
  2220. }
  2221. return context.hoist(finalExp);
  2222. }
  2223. const srcsetTags = ["img", "source"];
  2224. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  2225. const createSrcsetTransformWithOptions = (options) => {
  2226. return (node, context) => transformSrcset(node, context, options);
  2227. };
  2228. const transformSrcset = (node, context, options = defaultAssetUrlOptions) => {
  2229. if (node.type === 1) {
  2230. if (srcsetTags.includes(node.tag) && node.props.length) {
  2231. node.props.forEach((attr, index) => {
  2232. if (attr.name === "srcset" && attr.type === 6) {
  2233. if (!attr.value) return;
  2234. const value = attr.value.content;
  2235. if (!value) return;
  2236. const imageCandidates = value.split(",").map((s) => {
  2237. const [url, descriptor] = s.replace(escapedSpaceCharacters, " ").trim().split(" ", 2);
  2238. return { url, descriptor };
  2239. });
  2240. for (let i = 0; i < imageCandidates.length; i++) {
  2241. const { url } = imageCandidates[i];
  2242. if (isDataUrl(url)) {
  2243. imageCandidates[i + 1].url = url + "," + imageCandidates[i + 1].url;
  2244. imageCandidates.splice(i, 1);
  2245. }
  2246. }
  2247. const shouldProcessUrl = (url) => {
  2248. return url && !isExternalUrl(url) && !isDataUrl(url) && (options.includeAbsolute || isRelativeUrl(url));
  2249. };
  2250. if (!imageCandidates.some(({ url }) => shouldProcessUrl(url))) {
  2251. return;
  2252. }
  2253. if (options.base) {
  2254. const base = options.base;
  2255. const set = [];
  2256. let needImportTransform = false;
  2257. imageCandidates.forEach((candidate) => {
  2258. let { url, descriptor } = candidate;
  2259. descriptor = descriptor ? ` ${descriptor}` : ``;
  2260. if (url[0] === ".") {
  2261. candidate.url = (path$1.posix || path$1).join(base, url);
  2262. set.push(candidate.url + descriptor);
  2263. } else if (shouldProcessUrl(url)) {
  2264. needImportTransform = true;
  2265. } else {
  2266. set.push(url + descriptor);
  2267. }
  2268. });
  2269. if (!needImportTransform) {
  2270. attr.value.content = set.join(", ");
  2271. return;
  2272. }
  2273. }
  2274. const compoundExpression = compilerCore.createCompoundExpression([], attr.loc);
  2275. imageCandidates.forEach(({ url, descriptor }, index2) => {
  2276. if (shouldProcessUrl(url)) {
  2277. const { path: path2, hash } = parseUrl(url);
  2278. const source = path2 ? path2 : hash;
  2279. if (source) {
  2280. const normalizedSource = normalizeDecodedImportPath(source);
  2281. const existingImportsIndex = context.imports.findIndex(
  2282. (i) => i.path === normalizedSource
  2283. );
  2284. let exp2;
  2285. if (existingImportsIndex > -1) {
  2286. exp2 = compilerCore.createSimpleExpression(
  2287. `_imports_${existingImportsIndex}`,
  2288. false,
  2289. attr.loc,
  2290. 3
  2291. );
  2292. } else {
  2293. exp2 = compilerCore.createSimpleExpression(
  2294. `_imports_${context.imports.length}`,
  2295. false,
  2296. attr.loc,
  2297. 3
  2298. );
  2299. context.imports.push({ exp: exp2, path: normalizedSource });
  2300. }
  2301. if (path2 && hash) {
  2302. exp2 = compilerCore.createSimpleExpression(
  2303. `${exp2.content} + '${hash}'`,
  2304. false,
  2305. attr.loc,
  2306. 3
  2307. );
  2308. }
  2309. compoundExpression.children.push(exp2);
  2310. }
  2311. } else {
  2312. const exp2 = compilerCore.createSimpleExpression(
  2313. `"${url}"`,
  2314. false,
  2315. attr.loc,
  2316. 3
  2317. );
  2318. compoundExpression.children.push(exp2);
  2319. }
  2320. const isNotLast = imageCandidates.length - 1 > index2;
  2321. if (descriptor && isNotLast) {
  2322. compoundExpression.children.push(` + ' ${descriptor}, ' + `);
  2323. } else if (descriptor) {
  2324. compoundExpression.children.push(` + ' ${descriptor}'`);
  2325. } else if (isNotLast) {
  2326. compoundExpression.children.push(` + ', ' + `);
  2327. }
  2328. });
  2329. let exp = compoundExpression;
  2330. if (context.hoistStatic) {
  2331. exp = context.hoist(compoundExpression);
  2332. exp.constType = 3;
  2333. }
  2334. node.props[index] = {
  2335. type: 7,
  2336. name: "bind",
  2337. arg: compilerCore.createSimpleExpression("srcset", true, attr.loc),
  2338. exp,
  2339. modifiers: [],
  2340. loc: attr.loc
  2341. };
  2342. }
  2343. });
  2344. }
  2345. }
  2346. };
  2347. function commonjsRequire(path) {
  2348. 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.');
  2349. }
  2350. var consolidate$2 = {exports: {}};
  2351. var hasRequiredConsolidate$1;
  2352. function requireConsolidate$1 () {
  2353. if (hasRequiredConsolidate$1) return consolidate$2.exports;
  2354. hasRequiredConsolidate$1 = 1;
  2355. (function (module, exports$1) {
  2356. /*
  2357. * Engines which do not support caching of their file contents
  2358. * should use the `read()` function defined in consolidate.js
  2359. * On top of this, when an engine compiles to a `Function`,
  2360. * these functions should either be cached within consolidate.js
  2361. * or the engine itself via `options.cache`. This will allow
  2362. * users and frameworks to pass `options.cache = true` for
  2363. * `NODE_ENV=production`, however edit the file(s) without
  2364. * re-loading the application in development.
  2365. */
  2366. /**
  2367. * Module dependencies.
  2368. */
  2369. var fs = require$$0;
  2370. var path = path$1;
  2371. var util = require$$2;
  2372. var join = path.join;
  2373. var resolve = path.resolve;
  2374. var extname = path.extname;
  2375. var dirname = path.dirname;
  2376. var isAbsolute = path.isAbsolute;
  2377. var readCache = {};
  2378. /**
  2379. * Require cache.
  2380. */
  2381. var cacheStore = {};
  2382. /**
  2383. * Require cache.
  2384. */
  2385. var requires = {};
  2386. /**
  2387. * Clear the cache.
  2388. *
  2389. * @api public
  2390. */
  2391. exports$1.clearCache = function() {
  2392. readCache = {};
  2393. cacheStore = {};
  2394. };
  2395. /**
  2396. * Conditionally cache `compiled` template based
  2397. * on the `options` filename and `.cache` boolean.
  2398. *
  2399. * @param {Object} options
  2400. * @param {Function} compiled
  2401. * @return {Function}
  2402. * @api private
  2403. */
  2404. function cache(options, compiled) {
  2405. // cachable
  2406. if (compiled && options.filename && options.cache) {
  2407. delete readCache[options.filename];
  2408. cacheStore[options.filename] = compiled;
  2409. return compiled;
  2410. }
  2411. // check cache
  2412. if (options.filename && options.cache) {
  2413. return cacheStore[options.filename];
  2414. }
  2415. return compiled;
  2416. }
  2417. /**
  2418. * Read `path` with `options` with
  2419. * callback `(err, str)`. When `options.cache`
  2420. * is true the template string will be cached.
  2421. *
  2422. * @param {String} options
  2423. * @param {Function} cb
  2424. * @api private
  2425. */
  2426. function read(path, options, cb) {
  2427. var str = readCache[path];
  2428. var cached = options.cache && str && typeof str === 'string';
  2429. // cached (only if cached is a string and not a compiled template function)
  2430. if (cached) return cb(null, str);
  2431. // read
  2432. fs.readFile(path, 'utf8', function(err, str) {
  2433. if (err) return cb(err);
  2434. // remove extraneous utf8 BOM marker
  2435. str = str.replace(/^\uFEFF/, '');
  2436. if (options.cache) readCache[path] = str;
  2437. cb(null, str);
  2438. });
  2439. }
  2440. /**
  2441. * Read `path` with `options` with
  2442. * callback `(err, str)`. When `options.cache`
  2443. * is true the partial string will be cached.
  2444. *
  2445. * @param {String} options
  2446. * @param {Function} fn
  2447. * @api private
  2448. */
  2449. function readPartials(path, options, cb) {
  2450. if (!options.partials) return cb();
  2451. var keys = Object.keys(options.partials);
  2452. var partials = {};
  2453. function next(index) {
  2454. if (index === keys.length) return cb(null, partials);
  2455. var key = keys[index];
  2456. var partialPath = options.partials[key];
  2457. if (partialPath === undefined || partialPath === null || partialPath === false) {
  2458. return next(++index);
  2459. }
  2460. var file;
  2461. if (isAbsolute(partialPath)) {
  2462. if (extname(partialPath) !== '') {
  2463. file = partialPath;
  2464. } else {
  2465. file = join(partialPath + extname(path));
  2466. }
  2467. } else {
  2468. file = join(dirname(path), partialPath + extname(path));
  2469. }
  2470. read(file, options, function(err, str) {
  2471. if (err) return cb(err);
  2472. partials[key] = str;
  2473. next(++index);
  2474. });
  2475. }
  2476. next(0);
  2477. }
  2478. /**
  2479. * promisify
  2480. */
  2481. function promisify(cb, fn) {
  2482. return new Promise(function(resolve, reject) {
  2483. cb = cb || function(err, html) {
  2484. if (err) {
  2485. return reject(err);
  2486. }
  2487. resolve(html);
  2488. };
  2489. fn(cb);
  2490. });
  2491. }
  2492. /**
  2493. * fromStringRenderer
  2494. */
  2495. function fromStringRenderer(name) {
  2496. return function(path, options, cb) {
  2497. options.filename = path;
  2498. return promisify(cb, function(cb) {
  2499. readPartials(path, options, function(err, partials) {
  2500. var extend = (requires.extend || (requires.extend = require$$2._extend));
  2501. var opts = extend({}, options);
  2502. opts.partials = partials;
  2503. if (err) return cb(err);
  2504. if (cache(opts)) {
  2505. exports$1[name].render('', opts, cb);
  2506. } else {
  2507. read(path, opts, function(err, str) {
  2508. if (err) return cb(err);
  2509. exports$1[name].render(str, opts, cb);
  2510. });
  2511. }
  2512. });
  2513. });
  2514. };
  2515. }
  2516. /**
  2517. * velocity support.
  2518. */
  2519. exports$1.velocityjs = fromStringRenderer('velocityjs');
  2520. /**
  2521. * velocity string support.
  2522. */
  2523. exports$1.velocityjs.render = function(str, options, cb) {
  2524. return promisify(cb, function(cb) {
  2525. var engine = requires.velocityjs || (requires.velocityjs = require('velocityjs'));
  2526. try {
  2527. options.locals = options;
  2528. cb(null, engine.render(str, options).trimLeft());
  2529. } catch (err) {
  2530. cb(err);
  2531. }
  2532. });
  2533. };
  2534. /**
  2535. * Liquid support.
  2536. */
  2537. exports$1.liquid = fromStringRenderer('liquid');
  2538. /**
  2539. * Liquid string support.
  2540. */
  2541. /**
  2542. * Note that in order to get filters and custom tags we've had to push
  2543. * all user-defined locals down into @locals. However, just to make things
  2544. * backwards-compatible, any property of `options` that is left after
  2545. * processing and removing `locals`, `meta`, `filters`, `customTags` and
  2546. * `includeDir` will also become a local.
  2547. */
  2548. function _renderTinyliquid(engine, str, options, cb) {
  2549. var context = engine.newContext();
  2550. var k;
  2551. /**
  2552. * Note that there's a bug in the library that doesn't allow us to pass
  2553. * the locals to newContext(), hence looping through the keys:
  2554. */
  2555. if (options.locals) {
  2556. for (k in options.locals) {
  2557. context.setLocals(k, options.locals[k]);
  2558. }
  2559. delete options.locals;
  2560. }
  2561. if (options.meta) {
  2562. context.setLocals('page', options.meta);
  2563. delete options.meta;
  2564. }
  2565. /**
  2566. * Add any defined filters:
  2567. */
  2568. if (options.filters) {
  2569. for (k in options.filters) {
  2570. context.setFilter(k, options.filters[k]);
  2571. }
  2572. delete options.filters;
  2573. }
  2574. /**
  2575. * Set up a callback for the include directory:
  2576. */
  2577. var includeDir = options.includeDir || process.cwd();
  2578. context.onInclude(function(name, callback) {
  2579. var extname = path.extname(name) ? '' : '.liquid';
  2580. var filename = path.resolve(includeDir, name + extname);
  2581. fs.readFile(filename, {encoding: 'utf8'}, function(err, data) {
  2582. if (err) return callback(err);
  2583. callback(null, engine.parse(data));
  2584. });
  2585. });
  2586. delete options.includeDir;
  2587. /**
  2588. * The custom tag functions need to have their results pushed back
  2589. * through the parser, so set up a shim before calling the provided
  2590. * callback:
  2591. */
  2592. var compileOptions = {
  2593. customTags: {}
  2594. };
  2595. if (options.customTags) {
  2596. var tagFunctions = options.customTags;
  2597. for (k in options.customTags) {
  2598. /*Tell jshint there's no problem with having this function in the loop */
  2599. /*jshint -W083 */
  2600. compileOptions.customTags[k] = function(context, name, body) {
  2601. var tpl = tagFunctions[name](body.trim());
  2602. context.astStack.push(engine.parse(tpl));
  2603. };
  2604. /*jshint +W083 */
  2605. }
  2606. delete options.customTags;
  2607. }
  2608. /**
  2609. * Now anything left in `options` becomes a local:
  2610. */
  2611. for (k in options) {
  2612. context.setLocals(k, options[k]);
  2613. }
  2614. /**
  2615. * Finally, execute the template:
  2616. */
  2617. var tmpl = cache(context) || cache(context, engine.compile(str, compileOptions));
  2618. tmpl(context, cb);
  2619. }
  2620. exports$1.liquid.render = function(str, options, cb) {
  2621. return promisify(cb, function(cb) {
  2622. var engine = requires.liquid;
  2623. var Liquid;
  2624. try {
  2625. // set up tinyliquid engine
  2626. engine = requires.liquid = require('tinyliquid');
  2627. // use tinyliquid engine
  2628. _renderTinyliquid(engine, str, options, cb);
  2629. return;
  2630. } catch (err) {
  2631. // set up liquid-node engine
  2632. try {
  2633. Liquid = requires.liquid = require('liquid-node');
  2634. engine = new Liquid.Engine();
  2635. } catch (err) {
  2636. throw err;
  2637. }
  2638. }
  2639. // use liquid-node engine
  2640. try {
  2641. var locals = options.locals || {};
  2642. if (options.meta) {
  2643. locals.pages = options.meta;
  2644. delete options.meta;
  2645. }
  2646. /**
  2647. * Add any defined filters:
  2648. */
  2649. if (options.filters) {
  2650. engine.registerFilters(options.filters);
  2651. delete options.filters;
  2652. }
  2653. /**
  2654. * Set up a callback for the include directory:
  2655. */
  2656. var includeDir = options.includeDir || process.cwd();
  2657. engine.fileSystem = new Liquid.LocalFileSystem(includeDir, 'liquid');
  2658. delete options.includeDir;
  2659. /**
  2660. * The custom tag functions need to have their results pushed back
  2661. * through the parser, so set up a shim before calling the provided
  2662. * callback:
  2663. */
  2664. if (options.customTags) {
  2665. var tagFunctions = options.customTags;
  2666. for (k in options.customTags) {
  2667. engine.registerTag(k, tagFunctions[k]);
  2668. }
  2669. delete options.customTags;
  2670. }
  2671. /**
  2672. * Now anything left in `options` becomes a local:
  2673. */
  2674. for (var k in options) {
  2675. locals[k] = options[k];
  2676. }
  2677. /**
  2678. * Finally, execute the template:
  2679. */
  2680. return engine
  2681. .parseAndRender(str, locals)
  2682. .nodeify(function(err, result) {
  2683. if (err) {
  2684. throw new Error(err);
  2685. } else {
  2686. return cb(null, result);
  2687. }
  2688. });
  2689. } catch (err) {
  2690. cb(err);
  2691. }
  2692. });
  2693. };
  2694. /**
  2695. * Jade support.
  2696. */
  2697. exports$1.jade = function(path, options, cb) {
  2698. return promisify(cb, function(cb) {
  2699. var engine = requires.jade;
  2700. if (!engine) {
  2701. try {
  2702. engine = requires.jade = require('jade');
  2703. } catch (err) {
  2704. try {
  2705. engine = requires.jade = require('then-jade');
  2706. } catch (otherError) {
  2707. throw err;
  2708. }
  2709. }
  2710. }
  2711. try {
  2712. var tmpl = cache(options) || cache(options, engine.compileFile(path, options));
  2713. cb(null, tmpl(options));
  2714. } catch (err) {
  2715. cb(err);
  2716. }
  2717. });
  2718. };
  2719. /**
  2720. * Jade string support.
  2721. */
  2722. exports$1.jade.render = function(str, 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.compile(str, options));
  2738. cb(null, tmpl(options));
  2739. } catch (err) {
  2740. cb(err);
  2741. }
  2742. });
  2743. };
  2744. /**
  2745. * Dust support.
  2746. */
  2747. exports$1.dust = fromStringRenderer('dust');
  2748. /**
  2749. * Dust string support.
  2750. */
  2751. exports$1.dust.render = function(str, options, cb) {
  2752. return promisify(cb, function(cb) {
  2753. var engine = requires.dust;
  2754. if (!engine) {
  2755. try {
  2756. engine = requires.dust = require('dust');
  2757. } catch (err) {
  2758. try {
  2759. engine = requires.dust = require('dustjs-helpers');
  2760. } catch (err) {
  2761. engine = requires.dust = require('dustjs-linkedin');
  2762. }
  2763. }
  2764. }
  2765. var ext = 'dust';
  2766. var views = '.';
  2767. if (options) {
  2768. if (options.ext) ext = options.ext;
  2769. if (options.views) views = options.views;
  2770. if (options.settings && options.settings.views) views = options.settings.views;
  2771. }
  2772. if (!options || (options && !options.cache)) engine.cache = {};
  2773. engine.onLoad = function(path, callback) {
  2774. if (extname(path) === '') path += '.' + ext;
  2775. if (path[0] !== '/') path = views + '/' + path;
  2776. read(path, options, callback);
  2777. };
  2778. try {
  2779. var templateName;
  2780. if (options.filename) {
  2781. templateName = options.filename.replace(new RegExp('^' + views + '/'), '').replace(new RegExp('\\.' + ext), '');
  2782. }
  2783. var tmpl = cache(options) || cache(options, engine.compileFn(str, templateName));
  2784. tmpl(options, cb);
  2785. } catch (err) {
  2786. cb(err);
  2787. }
  2788. });
  2789. };
  2790. /**
  2791. * Swig support.
  2792. */
  2793. exports$1.swig = fromStringRenderer('swig');
  2794. /**
  2795. * Swig string support.
  2796. */
  2797. exports$1.swig.render = function(str, options, cb) {
  2798. return promisify(cb, function(cb) {
  2799. var engine = requires.swig;
  2800. if (!engine) {
  2801. try {
  2802. engine = requires.swig = require('swig');
  2803. } catch (err) {
  2804. try {
  2805. engine = requires.swig = require('swig-templates');
  2806. } catch (otherError) {
  2807. throw err;
  2808. }
  2809. }
  2810. }
  2811. try {
  2812. if (options.cache === true) options.cache = 'memory';
  2813. engine.setDefaults({ cache: options.cache });
  2814. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2815. cb(null, tmpl(options));
  2816. } catch (err) {
  2817. cb(err);
  2818. }
  2819. });
  2820. };
  2821. /**
  2822. * Razor support.
  2823. */
  2824. exports$1.razor = function(path, options, cb) {
  2825. return promisify(cb, function(cb) {
  2826. var engine = requires.razor;
  2827. if (!engine) {
  2828. try {
  2829. engine = requires.razor = require('razor-tmpl');
  2830. } catch (err) {
  2831. throw err;
  2832. }
  2833. }
  2834. try {
  2835. var tmpl = cache(options) || cache(options, (locals) => {
  2836. console.log('Rendering razor file', path);
  2837. return engine.renderFileSync(path, locals);
  2838. });
  2839. cb(null, tmpl(options));
  2840. } catch (err) {
  2841. cb(err);
  2842. }
  2843. });
  2844. };
  2845. /**
  2846. * razor string support.
  2847. */
  2848. exports$1.razor.render = function(str, options, cb) {
  2849. return promisify(cb, function(cb) {
  2850. try {
  2851. var engine = requires.razor = require('razor-tmpl');
  2852. } catch (err) {
  2853. throw err;
  2854. }
  2855. try {
  2856. var tf = engine.compile(str);
  2857. var tmpl = cache(options) || cache(options, tf);
  2858. cb(null, tmpl(options));
  2859. } catch (err) {
  2860. cb(err);
  2861. }
  2862. });
  2863. };
  2864. /**
  2865. * Atpl support.
  2866. */
  2867. exports$1.atpl = fromStringRenderer('atpl');
  2868. /**
  2869. * Atpl string support.
  2870. */
  2871. exports$1.atpl.render = function(str, options, cb) {
  2872. return promisify(cb, function(cb) {
  2873. var engine = requires.atpl || (requires.atpl = require('atpl'));
  2874. try {
  2875. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2876. cb(null, tmpl(options));
  2877. } catch (err) {
  2878. cb(err);
  2879. }
  2880. });
  2881. };
  2882. /**
  2883. * Liquor support,
  2884. */
  2885. exports$1.liquor = fromStringRenderer('liquor');
  2886. /**
  2887. * Liquor string support.
  2888. */
  2889. exports$1.liquor.render = function(str, options, cb) {
  2890. return promisify(cb, function(cb) {
  2891. var engine = requires.liquor || (requires.liquor = require('liquor'));
  2892. try {
  2893. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2894. cb(null, tmpl(options));
  2895. } catch (err) {
  2896. cb(err);
  2897. }
  2898. });
  2899. };
  2900. /**
  2901. * Twig support.
  2902. */
  2903. exports$1.twig = fromStringRenderer('twig');
  2904. /**
  2905. * Twig string support.
  2906. */
  2907. exports$1.twig.render = function(str, options, cb) {
  2908. return promisify(cb, function(cb) {
  2909. var engine = requires.twig || (requires.twig = require('twig').twig);
  2910. var templateData = {
  2911. data: str,
  2912. allowInlineIncludes: options.allowInlineIncludes,
  2913. namespaces: options.namespaces,
  2914. path: options.path
  2915. };
  2916. try {
  2917. var tmpl = cache(templateData) || cache(templateData, engine(templateData));
  2918. cb(null, tmpl.render(options));
  2919. } catch (err) {
  2920. cb(err);
  2921. }
  2922. });
  2923. };
  2924. /**
  2925. * EJS support.
  2926. */
  2927. exports$1.ejs = fromStringRenderer('ejs');
  2928. /**
  2929. * EJS string support.
  2930. */
  2931. exports$1.ejs.render = function(str, options, cb) {
  2932. return promisify(cb, function(cb) {
  2933. var engine = requires.ejs || (requires.ejs = require('ejs'));
  2934. try {
  2935. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2936. cb(null, tmpl(options));
  2937. } catch (err) {
  2938. cb(err);
  2939. }
  2940. });
  2941. };
  2942. /**
  2943. * Eco support.
  2944. */
  2945. exports$1.eco = fromStringRenderer('eco');
  2946. /**
  2947. * Eco string support.
  2948. */
  2949. exports$1.eco.render = function(str, options, cb) {
  2950. return promisify(cb, function(cb) {
  2951. var engine = requires.eco || (requires.eco = require('eco'));
  2952. try {
  2953. cb(null, engine.render(str, options));
  2954. } catch (err) {
  2955. cb(err);
  2956. }
  2957. });
  2958. };
  2959. /**
  2960. * Jazz support.
  2961. */
  2962. exports$1.jazz = fromStringRenderer('jazz');
  2963. /**
  2964. * Jazz string support.
  2965. */
  2966. exports$1.jazz.render = function(str, options, cb) {
  2967. return promisify(cb, function(cb) {
  2968. var engine = requires.jazz || (requires.jazz = require('jazz'));
  2969. try {
  2970. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2971. tmpl.eval(options, function(str) {
  2972. cb(null, str);
  2973. });
  2974. } catch (err) {
  2975. cb(err);
  2976. }
  2977. });
  2978. };
  2979. /**
  2980. * JQTPL support.
  2981. */
  2982. exports$1.jqtpl = fromStringRenderer('jqtpl');
  2983. /**
  2984. * JQTPL string support.
  2985. */
  2986. exports$1.jqtpl.render = function(str, options, cb) {
  2987. return promisify(cb, function(cb) {
  2988. var engine = requires.jqtpl || (requires.jqtpl = require('jqtpl'));
  2989. try {
  2990. engine.template(str, str);
  2991. cb(null, engine.tmpl(str, options));
  2992. } catch (err) {
  2993. cb(err);
  2994. }
  2995. });
  2996. };
  2997. /**
  2998. * Haml support.
  2999. */
  3000. exports$1.haml = fromStringRenderer('haml');
  3001. /**
  3002. * Haml string support.
  3003. */
  3004. exports$1.haml.render = function(str, options, cb) {
  3005. return promisify(cb, function(cb) {
  3006. var engine = requires.haml || (requires.haml = require('hamljs'));
  3007. try {
  3008. options.locals = options;
  3009. cb(null, engine.render(str, options).trimLeft());
  3010. } catch (err) {
  3011. cb(err);
  3012. }
  3013. });
  3014. };
  3015. /**
  3016. * Hamlet support.
  3017. */
  3018. exports$1.hamlet = fromStringRenderer('hamlet');
  3019. /**
  3020. * Hamlet string support.
  3021. */
  3022. exports$1.hamlet.render = function(str, options, cb) {
  3023. return promisify(cb, function(cb) {
  3024. var engine = requires.hamlet || (requires.hamlet = require('hamlet'));
  3025. try {
  3026. options.locals = options;
  3027. cb(null, engine.render(str, options).trimLeft());
  3028. } catch (err) {
  3029. cb(err);
  3030. }
  3031. });
  3032. };
  3033. /**
  3034. * Whiskers support.
  3035. */
  3036. exports$1.whiskers = function(path, options, cb) {
  3037. return promisify(cb, function(cb) {
  3038. var engine = requires.whiskers || (requires.whiskers = require('whiskers'));
  3039. engine.__express(path, options, cb);
  3040. });
  3041. };
  3042. /**
  3043. * Whiskers string support.
  3044. */
  3045. exports$1.whiskers.render = function(str, options, cb) {
  3046. return promisify(cb, function(cb) {
  3047. var engine = requires.whiskers || (requires.whiskers = require('whiskers'));
  3048. try {
  3049. cb(null, engine.render(str, options));
  3050. } catch (err) {
  3051. cb(err);
  3052. }
  3053. });
  3054. };
  3055. /**
  3056. * Coffee-HAML support.
  3057. */
  3058. exports$1['haml-coffee'] = fromStringRenderer('haml-coffee');
  3059. /**
  3060. * Coffee-HAML string support.
  3061. */
  3062. exports$1['haml-coffee'].render = function(str, options, cb) {
  3063. return promisify(cb, function(cb) {
  3064. var engine = requires['haml-coffee'] || (requires['haml-coffee'] = require('haml-coffee'));
  3065. try {
  3066. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3067. cb(null, tmpl(options));
  3068. } catch (err) {
  3069. cb(err);
  3070. }
  3071. });
  3072. };
  3073. /**
  3074. * Hogan support.
  3075. */
  3076. exports$1.hogan = fromStringRenderer('hogan');
  3077. /**
  3078. * Hogan string support.
  3079. */
  3080. exports$1.hogan.render = function(str, options, cb) {
  3081. return promisify(cb, function(cb) {
  3082. var engine = requires.hogan || (requires.hogan = require('hogan.js'));
  3083. try {
  3084. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3085. cb(null, tmpl.render(options, options.partials));
  3086. } catch (err) {
  3087. cb(err);
  3088. }
  3089. });
  3090. };
  3091. /**
  3092. * templayed.js support.
  3093. */
  3094. exports$1.templayed = fromStringRenderer('templayed');
  3095. /**
  3096. * templayed.js string support.
  3097. */
  3098. exports$1.templayed.render = function(str, options, cb) {
  3099. return promisify(cb, function(cb) {
  3100. var engine = requires.templayed || (requires.templayed = require('templayed'));
  3101. try {
  3102. var tmpl = cache(options) || cache(options, engine(str));
  3103. cb(null, tmpl(options));
  3104. } catch (err) {
  3105. cb(err);
  3106. }
  3107. });
  3108. };
  3109. /**
  3110. * Handlebars support.
  3111. */
  3112. exports$1.handlebars = fromStringRenderer('handlebars');
  3113. /**
  3114. * Handlebars string support.
  3115. */
  3116. exports$1.handlebars.render = function(str, options, cb) {
  3117. return promisify(cb, function(cb) {
  3118. var engine = requires.handlebars || (requires.handlebars = require('handlebars'));
  3119. try {
  3120. for (var partial in options.partials) {
  3121. engine.registerPartial(partial, options.partials[partial]);
  3122. }
  3123. for (var helper in options.helpers) {
  3124. engine.registerHelper(helper, options.helpers[helper]);
  3125. }
  3126. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3127. cb(null, tmpl(options));
  3128. } catch (err) {
  3129. cb(err);
  3130. }
  3131. });
  3132. };
  3133. /**
  3134. * Underscore support.
  3135. */
  3136. exports$1.underscore = fromStringRenderer('underscore');
  3137. /**
  3138. * Underscore string support.
  3139. */
  3140. exports$1.underscore.render = function(str, options, cb) {
  3141. return promisify(cb, function(cb) {
  3142. var engine = requires.underscore || (requires.underscore = require('underscore'));
  3143. try {
  3144. const partials = {};
  3145. for (var partial in options.partials) {
  3146. partials[partial] = engine.template(options.partials[partial]);
  3147. }
  3148. options.partials = partials;
  3149. var tmpl = cache(options) || cache(options, engine.template(str, null, options));
  3150. cb(null, tmpl(options).replace(/\n$/, ''));
  3151. } catch (err) {
  3152. cb(err);
  3153. }
  3154. });
  3155. };
  3156. /**
  3157. * Lodash support.
  3158. */
  3159. exports$1.lodash = fromStringRenderer('lodash');
  3160. /**
  3161. * Lodash string support.
  3162. */
  3163. exports$1.lodash.render = function(str, options, cb) {
  3164. return promisify(cb, function(cb) {
  3165. var engine = requires.lodash || (requires.lodash = require('lodash'));
  3166. try {
  3167. var tmpl = cache(options) || cache(options, engine.template(str, options));
  3168. cb(null, tmpl(options).replace(/\n$/, ''));
  3169. } catch (err) {
  3170. cb(err);
  3171. }
  3172. });
  3173. };
  3174. /**
  3175. * Pug support. (formerly Jade)
  3176. */
  3177. exports$1.pug = function(path, options, cb) {
  3178. return promisify(cb, function(cb) {
  3179. var engine = requires.pug;
  3180. if (!engine) {
  3181. try {
  3182. engine = requires.pug = require('pug');
  3183. } catch (err) {
  3184. try {
  3185. engine = requires.pug = require('then-pug');
  3186. } catch (otherError) {
  3187. throw err;
  3188. }
  3189. }
  3190. }
  3191. try {
  3192. var tmpl = cache(options) || cache(options, engine.compileFile(path, options));
  3193. cb(null, tmpl(options));
  3194. } catch (err) {
  3195. cb(err);
  3196. }
  3197. });
  3198. };
  3199. /**
  3200. * Pug string support.
  3201. */
  3202. exports$1.pug.render = function(str, 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.compile(str, options));
  3218. cb(null, tmpl(options));
  3219. } catch (err) {
  3220. cb(err);
  3221. }
  3222. });
  3223. };
  3224. /**
  3225. * QEJS support.
  3226. */
  3227. exports$1.qejs = fromStringRenderer('qejs');
  3228. /**
  3229. * QEJS string support.
  3230. */
  3231. exports$1.qejs.render = function(str, options, cb) {
  3232. return promisify(cb, function(cb) {
  3233. try {
  3234. var engine = requires.qejs || (requires.qejs = require('qejs'));
  3235. engine.render(str, options).then(function(result) {
  3236. cb(null, result);
  3237. }, function(err) {
  3238. cb(err);
  3239. }).done();
  3240. } catch (err) {
  3241. cb(err);
  3242. }
  3243. });
  3244. };
  3245. /**
  3246. * Walrus support.
  3247. */
  3248. exports$1.walrus = fromStringRenderer('walrus');
  3249. /**
  3250. * Walrus string support.
  3251. */
  3252. exports$1.walrus.render = function(str, options, cb) {
  3253. return promisify(cb, function(cb) {
  3254. var engine = requires.walrus || (requires.walrus = require('walrus'));
  3255. try {
  3256. var tmpl = cache(options) || cache(options, engine.parse(str));
  3257. cb(null, tmpl.compile(options));
  3258. } catch (err) {
  3259. cb(err);
  3260. }
  3261. });
  3262. };
  3263. /**
  3264. * Mustache support.
  3265. */
  3266. exports$1.mustache = fromStringRenderer('mustache');
  3267. /**
  3268. * Mustache string support.
  3269. */
  3270. exports$1.mustache.render = function(str, options, cb) {
  3271. return promisify(cb, function(cb) {
  3272. var engine = requires.mustache || (requires.mustache = require('mustache'));
  3273. try {
  3274. cb(null, engine.render(str, options, options.partials));
  3275. } catch (err) {
  3276. cb(err);
  3277. }
  3278. });
  3279. };
  3280. /**
  3281. * Just support.
  3282. */
  3283. exports$1.just = function(path, options, cb) {
  3284. return promisify(cb, function(cb) {
  3285. var engine = requires.just;
  3286. if (!engine) {
  3287. var JUST = require('just');
  3288. engine = requires.just = new JUST();
  3289. }
  3290. engine.configure({ useCache: options.cache });
  3291. engine.render(path, options, cb);
  3292. });
  3293. };
  3294. /**
  3295. * Just string support.
  3296. */
  3297. exports$1.just.render = function(str, options, cb) {
  3298. return promisify(cb, function(cb) {
  3299. var JUST = require('just');
  3300. var engine = new JUST({ root: { page: str }});
  3301. engine.render('page', options, cb);
  3302. });
  3303. };
  3304. /**
  3305. * ECT support.
  3306. */
  3307. exports$1.ect = function(path, options, cb) {
  3308. return promisify(cb, function(cb) {
  3309. var engine = requires.ect;
  3310. if (!engine) {
  3311. var ECT = require('ect');
  3312. engine = requires.ect = new ECT(options);
  3313. }
  3314. engine.configure({ cache: options.cache });
  3315. engine.render(path, options, cb);
  3316. });
  3317. };
  3318. /**
  3319. * ECT string support.
  3320. */
  3321. exports$1.ect.render = function(str, options, cb) {
  3322. return promisify(cb, function(cb) {
  3323. var ECT = require('ect');
  3324. var engine = new ECT({ root: { page: str }});
  3325. engine.render('page', options, cb);
  3326. });
  3327. };
  3328. /**
  3329. * mote support.
  3330. */
  3331. exports$1.mote = fromStringRenderer('mote');
  3332. /**
  3333. * mote string support.
  3334. */
  3335. exports$1.mote.render = function(str, options, cb) {
  3336. return promisify(cb, function(cb) {
  3337. var engine = requires.mote || (requires.mote = require('mote'));
  3338. try {
  3339. var tmpl = cache(options) || cache(options, engine.compile(str));
  3340. cb(null, tmpl(options));
  3341. } catch (err) {
  3342. cb(err);
  3343. }
  3344. });
  3345. };
  3346. /**
  3347. * Toffee support.
  3348. */
  3349. exports$1.toffee = function(path, options, cb) {
  3350. return promisify(cb, function(cb) {
  3351. var toffee = requires.toffee || (requires.toffee = require('toffee'));
  3352. toffee.__consolidate_engine_render(path, options, cb);
  3353. });
  3354. };
  3355. /**
  3356. * Toffee string support.
  3357. */
  3358. exports$1.toffee.render = function(str, options, cb) {
  3359. return promisify(cb, function(cb) {
  3360. var engine = requires.toffee || (requires.toffee = require('toffee'));
  3361. try {
  3362. engine.str_render(str, options, cb);
  3363. } catch (err) {
  3364. cb(err);
  3365. }
  3366. });
  3367. };
  3368. /**
  3369. * doT support.
  3370. */
  3371. exports$1.dot = fromStringRenderer('dot');
  3372. /**
  3373. * doT string support.
  3374. */
  3375. exports$1.dot.render = function(str, options, cb) {
  3376. return promisify(cb, function(cb) {
  3377. var engine = requires.dot || (requires.dot = require('dot'));
  3378. var extend = (requires.extend || (requires.extend = require$$2._extend));
  3379. try {
  3380. var settings = {};
  3381. settings = extend(settings, engine.templateSettings);
  3382. settings = extend(settings, options ? options.dot : {});
  3383. var tmpl = cache(options) || cache(options, engine.template(str, settings, options));
  3384. cb(null, tmpl(options));
  3385. } catch (err) {
  3386. cb(err);
  3387. }
  3388. });
  3389. };
  3390. /**
  3391. * bracket support.
  3392. */
  3393. exports$1.bracket = fromStringRenderer('bracket');
  3394. /**
  3395. * bracket string support.
  3396. */
  3397. exports$1.bracket.render = function(str, options, cb) {
  3398. return promisify(cb, function(cb) {
  3399. var engine = requires.bracket || (requires.bracket = require('bracket-template'));
  3400. try {
  3401. var tmpl = cache(options) || cache(options, engine.default.compile(str, options));
  3402. cb(null, tmpl(options));
  3403. } catch (err) {
  3404. cb(err);
  3405. }
  3406. });
  3407. };
  3408. /**
  3409. * Ractive support.
  3410. */
  3411. exports$1.ractive = fromStringRenderer('ractive');
  3412. /**
  3413. * Ractive string support.
  3414. */
  3415. exports$1.ractive.render = function(str, options, cb) {
  3416. return promisify(cb, function(cb) {
  3417. var Engine = requires.ractive || (requires.ractive = require('ractive'));
  3418. var template = cache(options) || cache(options, Engine.parse(str));
  3419. options.template = template;
  3420. if (options.data === null || options.data === undefined) {
  3421. var extend = (requires.extend || (requires.extend = require$$2._extend));
  3422. // Shallow clone the options object
  3423. options.data = extend({}, options);
  3424. // Remove consolidate-specific properties from the clone
  3425. var i;
  3426. var length;
  3427. var properties = ['template', 'filename', 'cache', 'partials'];
  3428. for (i = 0, length = properties.length; i < length; i++) {
  3429. var property = properties[i];
  3430. delete options.data[property];
  3431. }
  3432. }
  3433. try {
  3434. cb(null, new Engine(options).toHTML());
  3435. } catch (err) {
  3436. cb(err);
  3437. }
  3438. });
  3439. };
  3440. /**
  3441. * Nunjucks support.
  3442. */
  3443. exports$1.nunjucks = fromStringRenderer('nunjucks');
  3444. /**
  3445. * Nunjucks string support.
  3446. */
  3447. exports$1.nunjucks.render = function(str, options, cb) {
  3448. return promisify(cb, function(cb) {
  3449. try {
  3450. var engine = options.nunjucksEnv || requires.nunjucks || (requires.nunjucks = require('nunjucks'));
  3451. var env = engine;
  3452. // deprecated fallback support for express
  3453. // <https://github.com/tj/consolidate.js/pull/152>
  3454. // <https://github.com/tj/consolidate.js/pull/224>
  3455. if (options.settings && options.settings.views) {
  3456. env = engine.configure(options.settings.views);
  3457. } else if (options.nunjucks && options.nunjucks.configure) {
  3458. env = engine.configure.apply(engine, options.nunjucks.configure);
  3459. }
  3460. //
  3461. // because `renderString` does not initiate loaders
  3462. // we must manually create a loader for it based off
  3463. // either `options.settings.views` or `options.nunjucks` or `options.nunjucks.root`
  3464. //
  3465. // <https://github.com/mozilla/nunjucks/issues/730>
  3466. // <https://github.com/crocodilejs/node-email-templates/issues/182>
  3467. //
  3468. // so instead we simply check if we passed a custom loader
  3469. // otherwise we create a simple file based loader
  3470. if (options.loader) {
  3471. env = new engine.Environment(options.loader);
  3472. } else if (options.settings && options.settings.views) {
  3473. env = new engine.Environment(
  3474. new engine.FileSystemLoader(options.settings.views)
  3475. );
  3476. } else if (options.nunjucks && options.nunjucks.loader) {
  3477. if (typeof options.nunjucks.loader === 'string') {
  3478. env = new engine.Environment(new engine.FileSystemLoader(options.nunjucks.loader));
  3479. } else {
  3480. env = new engine.Environment(
  3481. new engine.FileSystemLoader(
  3482. options.nunjucks.loader[0],
  3483. options.nunjucks.loader[1]
  3484. )
  3485. );
  3486. }
  3487. }
  3488. env.renderString(str, options, cb);
  3489. } catch (err) {
  3490. throw cb(err);
  3491. }
  3492. });
  3493. };
  3494. /**
  3495. * HTMLing support.
  3496. */
  3497. exports$1.htmling = fromStringRenderer('htmling');
  3498. /**
  3499. * HTMLing string support.
  3500. */
  3501. exports$1.htmling.render = function(str, options, cb) {
  3502. return promisify(cb, function(cb) {
  3503. var engine = requires.htmling || (requires.htmling = require('htmling'));
  3504. try {
  3505. var tmpl = cache(options) || cache(options, engine.string(str));
  3506. cb(null, tmpl.render(options));
  3507. } catch (err) {
  3508. cb(err);
  3509. }
  3510. });
  3511. };
  3512. /**
  3513. * Rendering function
  3514. */
  3515. function requireReact(module, filename) {
  3516. var babel = requires.babel || (requires.babel = require('babel-core'));
  3517. var compiled = babel.transformFileSync(filename, { presets: [ 'react' ] }).code;
  3518. return module._compile(compiled, filename);
  3519. }
  3520. exports$1.requireReact = requireReact;
  3521. /**
  3522. * Converting a string into a node module.
  3523. */
  3524. function requireReactString(src, filename) {
  3525. var babel = requires.babel || (requires.babel = require('babel-core'));
  3526. if (!filename) filename = '';
  3527. var m = new module.constructor();
  3528. filename = filename || '';
  3529. // Compile Using React
  3530. var compiled = babel.transform(src, { presets: [ 'react' ] }).code;
  3531. // Compile as a module
  3532. m.paths = module.paths;
  3533. m._compile(compiled, filename);
  3534. return m.exports;
  3535. }
  3536. /**
  3537. * A naive helper to replace {{tags}} with options.tags content
  3538. */
  3539. function reactBaseTmpl(data, options) {
  3540. var exp;
  3541. var regex;
  3542. // Iterates through the keys in file object
  3543. // and interpolate / replace {{key}} with it's value
  3544. for (var k in options) {
  3545. if (options.hasOwnProperty(k)) {
  3546. exp = '{{' + k + '}}';
  3547. regex = new RegExp(exp, 'g');
  3548. if (data.match(regex)) {
  3549. data = data.replace(regex, options[k]);
  3550. }
  3551. }
  3552. }
  3553. return data;
  3554. }
  3555. /**
  3556. * Plates Support.
  3557. */
  3558. exports$1.plates = fromStringRenderer('plates');
  3559. /**
  3560. * Plates string support.
  3561. */
  3562. exports$1.plates.render = function(str, options, cb) {
  3563. return promisify(cb, function(cb) {
  3564. var engine = requires.plates || (requires.plates = require('plates'));
  3565. var map = options.map || undefined;
  3566. try {
  3567. var tmpl = engine.bind(str, options, map);
  3568. cb(null, tmpl);
  3569. } catch (err) {
  3570. cb(err);
  3571. }
  3572. });
  3573. };
  3574. /**
  3575. * The main render parser for React bsaed templates
  3576. */
  3577. function reactRenderer(type) {
  3578. if (commonjsRequire.extensions) {
  3579. // Ensure JSX is transformed on require
  3580. if (!commonjsRequire.extensions['.jsx']) {
  3581. commonjsRequire.extensions['.jsx'] = requireReact;
  3582. }
  3583. // Supporting .react extension as well as test cases
  3584. // Using .react extension is not recommended.
  3585. if (!commonjsRequire.extensions['.react']) {
  3586. commonjsRequire.extensions['.react'] = requireReact;
  3587. }
  3588. }
  3589. // Return rendering fx
  3590. return function(str, options, cb) {
  3591. return promisify(cb, function(cb) {
  3592. // React Import
  3593. var ReactDOM = requires.ReactDOM || (requires.ReactDOM = require('react-dom/server'));
  3594. var react = requires.react || (requires.react = require('react'));
  3595. // Assign HTML Base
  3596. var base = options.base;
  3597. delete options.base;
  3598. var enableCache = options.cache;
  3599. delete options.cache;
  3600. var isNonStatic = options.isNonStatic;
  3601. delete options.isNonStatic;
  3602. // Start Conversion
  3603. try {
  3604. var Code;
  3605. var Factory;
  3606. var baseStr;
  3607. var content;
  3608. var parsed;
  3609. if (!cache(options)) {
  3610. // Parsing
  3611. if (type === 'path') {
  3612. var path = resolve(str);
  3613. delete require.cache[path];
  3614. Code = commonjsRequire(path);
  3615. } else {
  3616. Code = requireReactString(str);
  3617. }
  3618. Factory = cache(options, react.createFactory(Code));
  3619. } else {
  3620. Factory = cache(options);
  3621. }
  3622. parsed = new Factory(options);
  3623. content = (isNonStatic) ? ReactDOM.renderToString(parsed) : ReactDOM.renderToStaticMarkup(parsed);
  3624. if (base) {
  3625. baseStr = readCache[str] || fs.readFileSync(resolve(base), 'utf8');
  3626. if (enableCache) {
  3627. readCache[str] = baseStr;
  3628. }
  3629. options.content = content;
  3630. content = reactBaseTmpl(baseStr, options);
  3631. }
  3632. cb(null, content);
  3633. } catch (err) {
  3634. cb(err);
  3635. }
  3636. });
  3637. };
  3638. }
  3639. /**
  3640. * React JS Support
  3641. */
  3642. exports$1.react = reactRenderer('path');
  3643. /**
  3644. * React JS string support.
  3645. */
  3646. exports$1.react.render = reactRenderer('string');
  3647. /**
  3648. * ARC-templates support.
  3649. */
  3650. exports$1['arc-templates'] = fromStringRenderer('arc-templates');
  3651. /**
  3652. * ARC-templates string support.
  3653. */
  3654. exports$1['arc-templates'].render = function(str, options, cb) {
  3655. var readFileWithOptions = util.promisify(read);
  3656. var consolidateFileSystem = {};
  3657. consolidateFileSystem.readFile = function(path) {
  3658. return readFileWithOptions(path, options);
  3659. };
  3660. return promisify(cb, function(cb) {
  3661. try {
  3662. var engine = requires['arc-templates'];
  3663. if (!engine) {
  3664. var Engine = require('arc-templates/dist/es5');
  3665. engine = requires['arc-templates'] = new Engine({ filesystem: consolidateFileSystem });
  3666. }
  3667. var compiler = cache(options) || cache(options, engine.compileString(str, options.filename));
  3668. compiler.then(function(func) { return func(options); })
  3669. .then(function(result) { cb(null, result.content); })
  3670. .catch(cb);
  3671. } catch (err) {
  3672. cb(err);
  3673. }
  3674. });
  3675. };
  3676. /**
  3677. * Vash support
  3678. */
  3679. exports$1.vash = fromStringRenderer('vash');
  3680. /**
  3681. * Vash string support
  3682. */
  3683. exports$1.vash.render = function(str, options, cb) {
  3684. return promisify(cb, function(cb) {
  3685. var engine = requires.vash || (requires.vash = require('vash'));
  3686. try {
  3687. // helper system : https://github.com/kirbysayshi/vash#helper-system
  3688. if (options.helpers) {
  3689. for (var key in options.helpers) {
  3690. if (!options.helpers.hasOwnProperty(key) || typeof options.helpers[key] !== 'function') {
  3691. continue;
  3692. }
  3693. engine.helpers[key] = options.helpers[key];
  3694. }
  3695. }
  3696. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3697. tmpl(options, function sealLayout(err, ctx) {
  3698. if (err) cb(err);
  3699. ctx.finishLayout();
  3700. cb(null, ctx.toString().replace(/\n$/, ''));
  3701. });
  3702. } catch (err) {
  3703. cb(err);
  3704. }
  3705. });
  3706. };
  3707. /**
  3708. * Slm support.
  3709. */
  3710. exports$1.slm = fromStringRenderer('slm');
  3711. /**
  3712. * Slm string support.
  3713. */
  3714. exports$1.slm.render = function(str, options, cb) {
  3715. return promisify(cb, function(cb) {
  3716. var engine = requires.slm || (requires.slm = require('slm'));
  3717. try {
  3718. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3719. cb(null, tmpl(options));
  3720. } catch (err) {
  3721. cb(err);
  3722. }
  3723. });
  3724. };
  3725. /**
  3726. * Marko support.
  3727. */
  3728. exports$1.marko = function(path, options, cb) {
  3729. return promisify(cb, function(cb) {
  3730. var engine = requires.marko || (requires.marko = require('marko'));
  3731. options.writeToDisk = !!options.cache;
  3732. try {
  3733. var tmpl = cache(options) || cache(options, engine.load(path, options));
  3734. tmpl.renderToString(options, cb);
  3735. } catch (err) {
  3736. cb(err);
  3737. }
  3738. });
  3739. };
  3740. /**
  3741. * Marko string support.
  3742. */
  3743. exports$1.marko.render = function(str, options, cb) {
  3744. return promisify(cb, function(cb) {
  3745. var engine = requires.marko || (requires.marko = require('marko'));
  3746. options.writeToDisk = !!options.cache;
  3747. options.filename = options.filename || 'string.marko';
  3748. try {
  3749. var tmpl = cache(options) || cache(options, engine.load(options.filename, str, options));
  3750. tmpl.renderToString(options, cb);
  3751. } catch (err) {
  3752. cb(err);
  3753. }
  3754. });
  3755. };
  3756. /**
  3757. * Teacup support.
  3758. */
  3759. exports$1.teacup = function(path, options, cb) {
  3760. return promisify(cb, function(cb) {
  3761. var engine = requires.teacup || (requires.teacup = require('teacup/lib/express'));
  3762. commonjsRequire.extensions['.teacup'] = commonjsRequire.extensions['.coffee'];
  3763. if (path[0] !== '/') {
  3764. path = join(process.cwd(), path);
  3765. }
  3766. if (!options.cache) {
  3767. var callback = cb;
  3768. cb = function() {
  3769. delete require.cache[path];
  3770. callback.apply(this, arguments);
  3771. };
  3772. }
  3773. engine.renderFile(path, options, cb);
  3774. });
  3775. };
  3776. /**
  3777. * Teacup string support.
  3778. */
  3779. exports$1.teacup.render = function(str, options, cb) {
  3780. var coffee = require('coffee-script');
  3781. var vm = require('vm');
  3782. var sandbox = {
  3783. module: {exports: {}},
  3784. require: commonjsRequire
  3785. };
  3786. return promisify(cb, function(cb) {
  3787. vm.runInNewContext(coffee.compile(str), sandbox);
  3788. var tmpl = sandbox.module.exports;
  3789. cb(null, tmpl(options));
  3790. });
  3791. };
  3792. /**
  3793. * Squirrelly support.
  3794. */
  3795. exports$1.squirrelly = fromStringRenderer('squirrelly');
  3796. /**
  3797. * Squirrelly string support.
  3798. */
  3799. exports$1.squirrelly.render = function(str, options, cb) {
  3800. return promisify(cb, function(cb) {
  3801. var engine = requires.squirrelly || (requires.squirrelly = require('squirrelly'));
  3802. try {
  3803. for (var partial in options.partials) {
  3804. engine.definePartial(partial, options.partials[partial]);
  3805. }
  3806. for (var helper in options.helpers) {
  3807. engine.defineHelper(helper, options.helpers[helper]);
  3808. }
  3809. var tmpl = cache(options) || cache(options, engine.Compile(str, options));
  3810. cb(null, tmpl(options, engine));
  3811. } catch (err) {
  3812. cb(err);
  3813. }
  3814. });
  3815. };
  3816. /**
  3817. * Twing support.
  3818. */
  3819. exports$1.twing = fromStringRenderer('twing');
  3820. /**
  3821. * Twing string support.
  3822. */
  3823. exports$1.twing.render = function(str, options, cb) {
  3824. return promisify(cb, function(cb) {
  3825. var engine = requires.twing || (requires.twing = require('twing'));
  3826. try {
  3827. new engine.TwingEnvironment(new engine.TwingLoaderNull()).createTemplate(str).then((twingTemplate) => {
  3828. twingTemplate.render(options).then((rendTmpl) => {
  3829. var tmpl = cache(options) || cache(options, rendTmpl);
  3830. cb(null, tmpl);
  3831. });
  3832. });
  3833. } catch (err) {
  3834. cb(err);
  3835. }
  3836. });
  3837. };
  3838. /**
  3839. * expose the instance of the engine
  3840. */
  3841. exports$1.requires = requires;
  3842. } (consolidate$2, consolidate$2.exports));
  3843. return consolidate$2.exports;
  3844. }
  3845. var consolidate$1;
  3846. var hasRequiredConsolidate;
  3847. function requireConsolidate () {
  3848. if (hasRequiredConsolidate) return consolidate$1;
  3849. hasRequiredConsolidate = 1;
  3850. consolidate$1 = /*@__PURE__*/ requireConsolidate$1();
  3851. return consolidate$1;
  3852. }
  3853. var consolidateExports = /*@__PURE__*/ requireConsolidate();
  3854. var consolidate = /*@__PURE__*/getDefaultExportFromCjs(consolidateExports);
  3855. const hasWarned = {};
  3856. function warnOnce(msg) {
  3857. const isNodeProd = typeof process !== "undefined" && process.env.NODE_ENV === "production";
  3858. if (!isNodeProd && true && !hasWarned[msg]) {
  3859. hasWarned[msg] = true;
  3860. warn(msg);
  3861. }
  3862. }
  3863. function warn(msg) {
  3864. console.warn(
  3865. `\x1B[1m\x1B[33m[@vue/compiler-sfc]\x1B[0m\x1B[33m ${msg}\x1B[0m
  3866. `
  3867. );
  3868. }
  3869. function preprocess$1({ source, filename, preprocessOptions }, preprocessor) {
  3870. let res = "";
  3871. let err = null;
  3872. preprocessor.render(
  3873. source,
  3874. { filename, ...preprocessOptions },
  3875. (_err, _res) => {
  3876. if (_err) err = _err;
  3877. res = _res;
  3878. }
  3879. );
  3880. if (err) throw err;
  3881. return res;
  3882. }
  3883. function compileTemplate(options) {
  3884. const { preprocessLang, preprocessCustomRequire } = options;
  3885. const preprocessor = preprocessLang ? preprocessCustomRequire ? preprocessCustomRequire(preprocessLang) : consolidate[preprocessLang] : false;
  3886. if (preprocessor) {
  3887. try {
  3888. return doCompileTemplate({
  3889. ...options,
  3890. source: preprocess$1(options, preprocessor),
  3891. ast: void 0
  3892. // invalidate AST if template goes through preprocessor
  3893. });
  3894. } catch (e) {
  3895. return {
  3896. code: `export default function render() {}`,
  3897. source: options.source,
  3898. tips: [],
  3899. errors: [e]
  3900. };
  3901. }
  3902. } else if (preprocessLang) {
  3903. return {
  3904. code: `export default function render() {}`,
  3905. source: options.source,
  3906. tips: [
  3907. `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
  3908. ],
  3909. errors: [
  3910. `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
  3911. ]
  3912. };
  3913. } else {
  3914. return doCompileTemplate(options);
  3915. }
  3916. }
  3917. function doCompileTemplate({
  3918. filename,
  3919. id,
  3920. scoped,
  3921. slotted,
  3922. inMap,
  3923. source,
  3924. ast: inAST,
  3925. ssr = false,
  3926. ssrCssVars,
  3927. isProd = false,
  3928. compiler,
  3929. compilerOptions = {},
  3930. transformAssetUrls
  3931. }) {
  3932. const errors = [];
  3933. const warnings = [];
  3934. let nodeTransforms = [];
  3935. if (shared.isObject(transformAssetUrls)) {
  3936. const assetOptions = normalizeOptions(transformAssetUrls);
  3937. nodeTransforms = [
  3938. createAssetUrlTransformWithOptions(assetOptions),
  3939. createSrcsetTransformWithOptions(assetOptions)
  3940. ];
  3941. } else if (transformAssetUrls !== false) {
  3942. nodeTransforms = [transformAssetUrl, transformSrcset];
  3943. }
  3944. if (ssr && !ssrCssVars) {
  3945. warnOnce(
  3946. `compileTemplate is called with \`ssr: true\` but no corresponding \`cssVars\` option.`
  3947. );
  3948. }
  3949. if (!id) {
  3950. warnOnce(`compileTemplate now requires the \`id\` option.`);
  3951. id = "";
  3952. }
  3953. const shortId = id.replace(/^data-v-/, "");
  3954. const longId = `data-v-${shortId}`;
  3955. const defaultCompiler = ssr ? CompilerSSR__namespace : CompilerDOM__namespace;
  3956. compiler = compiler || defaultCompiler;
  3957. if (compiler !== defaultCompiler) {
  3958. inAST = void 0;
  3959. }
  3960. if (inAST == null ? void 0 : inAST.transformed) {
  3961. const newAST = (ssr ? CompilerDOM__namespace : compiler).parse(inAST.source, {
  3962. prefixIdentifiers: true,
  3963. ...compilerOptions,
  3964. parseMode: "sfc",
  3965. onError: (e) => errors.push(e)
  3966. });
  3967. const template = newAST.children.find(
  3968. (node) => node.type === 1 && node.tag === "template"
  3969. );
  3970. inAST = compilerCore.createRoot(template.children, inAST.source);
  3971. }
  3972. let { code, ast, preamble, map } = compiler.compile(inAST || source, {
  3973. mode: "module",
  3974. prefixIdentifiers: true,
  3975. hoistStatic: true,
  3976. cacheHandlers: true,
  3977. ssrCssVars: ssr && ssrCssVars && ssrCssVars.length ? genCssVarsFromList(ssrCssVars, shortId, isProd, true) : "",
  3978. scopeId: scoped ? longId : void 0,
  3979. slotted,
  3980. sourceMap: true,
  3981. ...compilerOptions,
  3982. hmr: !isProd,
  3983. nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []),
  3984. filename,
  3985. onError: (e) => errors.push(e),
  3986. onWarn: (w) => warnings.push(w)
  3987. });
  3988. if (inMap && !inAST) {
  3989. if (map) {
  3990. map = mapLines(inMap, map);
  3991. }
  3992. if (errors.length) {
  3993. patchErrors(errors, source, inMap);
  3994. }
  3995. }
  3996. const tips = warnings.map((w) => {
  3997. let msg = w.message;
  3998. if (w.loc) {
  3999. msg += `
  4000. ${shared.generateCodeFrame(
  4001. (inAST == null ? void 0 : inAST.source) || source,
  4002. w.loc.start.offset,
  4003. w.loc.end.offset
  4004. )}`;
  4005. }
  4006. return msg;
  4007. });
  4008. return { code, ast, preamble, source, errors, tips, map };
  4009. }
  4010. function mapLines(oldMap, newMap) {
  4011. if (!oldMap) return newMap;
  4012. if (!newMap) return oldMap;
  4013. const oldMapConsumer = new sourceMapJs.SourceMapConsumer(oldMap);
  4014. const newMapConsumer = new sourceMapJs.SourceMapConsumer(newMap);
  4015. const mergedMapGenerator = new sourceMapJs.SourceMapGenerator();
  4016. newMapConsumer.eachMapping((m) => {
  4017. if (m.originalLine == null) {
  4018. return;
  4019. }
  4020. const origPosInOldMap = oldMapConsumer.originalPositionFor({
  4021. line: m.originalLine,
  4022. column: m.originalColumn
  4023. });
  4024. if (origPosInOldMap.source == null) {
  4025. return;
  4026. }
  4027. mergedMapGenerator.addMapping({
  4028. generated: {
  4029. line: m.generatedLine,
  4030. column: m.generatedColumn
  4031. },
  4032. original: {
  4033. line: origPosInOldMap.line,
  4034. // map line
  4035. // use current column, since the oldMap produced by @vue/compiler-sfc
  4036. // does not
  4037. column: m.originalColumn
  4038. },
  4039. source: origPosInOldMap.source,
  4040. name: origPosInOldMap.name
  4041. });
  4042. });
  4043. const generator = mergedMapGenerator;
  4044. oldMapConsumer.sources.forEach((sourceFile) => {
  4045. generator._sources.add(sourceFile);
  4046. const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
  4047. if (sourceContent != null) {
  4048. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  4049. }
  4050. });
  4051. generator._sourceRoot = oldMap.sourceRoot;
  4052. generator._file = oldMap.file;
  4053. return generator.toJSON();
  4054. }
  4055. function patchErrors(errors, source, inMap) {
  4056. const originalSource = inMap.sourcesContent[0];
  4057. const offset = originalSource.indexOf(source);
  4058. const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
  4059. errors.forEach((err) => {
  4060. if (err.loc) {
  4061. err.loc.start.line += lineOffset;
  4062. err.loc.start.offset += offset;
  4063. if (err.loc.end !== err.loc.start) {
  4064. err.loc.end.line += lineOffset;
  4065. err.loc.end.offset += offset;
  4066. }
  4067. }
  4068. });
  4069. }
  4070. const trimPlugin = () => {
  4071. return {
  4072. postcssPlugin: "vue-sfc-trim",
  4073. Once(root) {
  4074. root.walk(({ type, raws }) => {
  4075. if (type === "rule" || type === "atrule") {
  4076. if (raws.before) raws.before = "\n";
  4077. if ("after" in raws && raws.after) raws.after = "\n";
  4078. }
  4079. });
  4080. }
  4081. };
  4082. };
  4083. trimPlugin.postcss = true;
  4084. var dist$1 = {exports: {}};
  4085. var processor$1 = {exports: {}};
  4086. var parser$1 = {exports: {}};
  4087. var root$1 = {exports: {}};
  4088. var container$1 = {exports: {}};
  4089. var node$2 = {exports: {}};
  4090. var util$2 = {};
  4091. var unesc$1 = {exports: {}};
  4092. var hasRequiredUnesc$1;
  4093. function requireUnesc$1 () {
  4094. if (hasRequiredUnesc$1) return unesc$1.exports;
  4095. hasRequiredUnesc$1 = 1;
  4096. (function (module, exports$1) {
  4097. exports$1.__esModule = true;
  4098. exports$1["default"] = unesc;
  4099. // Many thanks for this post which made this migration much easier.
  4100. // https://mathiasbynens.be/notes/css-escapes
  4101. /**
  4102. *
  4103. * @param {string} str
  4104. * @returns {[string, number]|undefined}
  4105. */
  4106. function gobbleHex(str) {
  4107. var lower = str.toLowerCase();
  4108. var hex = '';
  4109. var spaceTerminated = false;
  4110. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  4111. var code = lower.charCodeAt(i);
  4112. // check to see if we are dealing with a valid hex char [a-f|0-9]
  4113. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
  4114. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  4115. spaceTerminated = code === 32;
  4116. if (!valid) {
  4117. break;
  4118. }
  4119. hex += lower[i];
  4120. }
  4121. if (hex.length === 0) {
  4122. return undefined;
  4123. }
  4124. var codePoint = parseInt(hex, 16);
  4125. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
  4126. // Add special case for
  4127. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  4128. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  4129. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  4130. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  4131. }
  4132. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  4133. }
  4134. var CONTAINS_ESCAPE = /\\/;
  4135. function unesc(str) {
  4136. var needToProcess = CONTAINS_ESCAPE.test(str);
  4137. if (!needToProcess) {
  4138. return str;
  4139. }
  4140. var ret = "";
  4141. for (var i = 0; i < str.length; i++) {
  4142. if (str[i] === "\\") {
  4143. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  4144. if (gobbled !== undefined) {
  4145. ret += gobbled[0];
  4146. i += gobbled[1];
  4147. continue;
  4148. }
  4149. // Retain a pair of \\ if double escaped `\\\\`
  4150. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  4151. if (str[i + 1] === "\\") {
  4152. ret += "\\";
  4153. i++;
  4154. continue;
  4155. }
  4156. // if \\ is at the end of the string retain it
  4157. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  4158. if (str.length === i + 1) {
  4159. ret += str[i];
  4160. }
  4161. continue;
  4162. }
  4163. ret += str[i];
  4164. }
  4165. return ret;
  4166. }
  4167. module.exports = exports$1.default;
  4168. } (unesc$1, unesc$1.exports));
  4169. return unesc$1.exports;
  4170. }
  4171. var getProp$1 = {exports: {}};
  4172. var hasRequiredGetProp$1;
  4173. function requireGetProp$1 () {
  4174. if (hasRequiredGetProp$1) return getProp$1.exports;
  4175. hasRequiredGetProp$1 = 1;
  4176. (function (module, exports$1) {
  4177. exports$1.__esModule = true;
  4178. exports$1["default"] = getProp;
  4179. function getProp(obj) {
  4180. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4181. props[_key - 1] = arguments[_key];
  4182. }
  4183. while (props.length > 0) {
  4184. var prop = props.shift();
  4185. if (!obj[prop]) {
  4186. return undefined;
  4187. }
  4188. obj = obj[prop];
  4189. }
  4190. return obj;
  4191. }
  4192. module.exports = exports$1.default;
  4193. } (getProp$1, getProp$1.exports));
  4194. return getProp$1.exports;
  4195. }
  4196. var ensureObject$1 = {exports: {}};
  4197. var hasRequiredEnsureObject$1;
  4198. function requireEnsureObject$1 () {
  4199. if (hasRequiredEnsureObject$1) return ensureObject$1.exports;
  4200. hasRequiredEnsureObject$1 = 1;
  4201. (function (module, exports$1) {
  4202. exports$1.__esModule = true;
  4203. exports$1["default"] = ensureObject;
  4204. function ensureObject(obj) {
  4205. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4206. props[_key - 1] = arguments[_key];
  4207. }
  4208. while (props.length > 0) {
  4209. var prop = props.shift();
  4210. if (!obj[prop]) {
  4211. obj[prop] = {};
  4212. }
  4213. obj = obj[prop];
  4214. }
  4215. }
  4216. module.exports = exports$1.default;
  4217. } (ensureObject$1, ensureObject$1.exports));
  4218. return ensureObject$1.exports;
  4219. }
  4220. var stripComments$1 = {exports: {}};
  4221. var hasRequiredStripComments$1;
  4222. function requireStripComments$1 () {
  4223. if (hasRequiredStripComments$1) return stripComments$1.exports;
  4224. hasRequiredStripComments$1 = 1;
  4225. (function (module, exports$1) {
  4226. exports$1.__esModule = true;
  4227. exports$1["default"] = stripComments;
  4228. function stripComments(str) {
  4229. var s = "";
  4230. var commentStart = str.indexOf("/*");
  4231. var lastEnd = 0;
  4232. while (commentStart >= 0) {
  4233. s = s + str.slice(lastEnd, commentStart);
  4234. var commentEnd = str.indexOf("*/", commentStart + 2);
  4235. if (commentEnd < 0) {
  4236. return s;
  4237. }
  4238. lastEnd = commentEnd + 2;
  4239. commentStart = str.indexOf("/*", lastEnd);
  4240. }
  4241. s = s + str.slice(lastEnd);
  4242. return s;
  4243. }
  4244. module.exports = exports$1.default;
  4245. } (stripComments$1, stripComments$1.exports));
  4246. return stripComments$1.exports;
  4247. }
  4248. var hasRequiredUtil$2;
  4249. function requireUtil$2 () {
  4250. if (hasRequiredUtil$2) return util$2;
  4251. hasRequiredUtil$2 = 1;
  4252. util$2.__esModule = true;
  4253. util$2.unesc = util$2.stripComments = util$2.getProp = util$2.ensureObject = void 0;
  4254. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc$1());
  4255. util$2.unesc = _unesc["default"];
  4256. var _getProp = _interopRequireDefault(/*@__PURE__*/ requireGetProp$1());
  4257. util$2.getProp = _getProp["default"];
  4258. var _ensureObject = _interopRequireDefault(/*@__PURE__*/ requireEnsureObject$1());
  4259. util$2.ensureObject = _ensureObject["default"];
  4260. var _stripComments = _interopRequireDefault(/*@__PURE__*/ requireStripComments$1());
  4261. util$2.stripComments = _stripComments["default"];
  4262. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4263. return util$2;
  4264. }
  4265. var hasRequiredNode$2;
  4266. function requireNode$2 () {
  4267. if (hasRequiredNode$2) return node$2.exports;
  4268. hasRequiredNode$2 = 1;
  4269. (function (module, exports$1) {
  4270. exports$1.__esModule = true;
  4271. exports$1["default"] = void 0;
  4272. var _util = /*@__PURE__*/ requireUtil$2();
  4273. 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); } }
  4274. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4275. var cloneNode = function cloneNode(obj, parent) {
  4276. if (typeof obj !== 'object' || obj === null) {
  4277. return obj;
  4278. }
  4279. var cloned = new obj.constructor();
  4280. for (var i in obj) {
  4281. if (!obj.hasOwnProperty(i)) {
  4282. continue;
  4283. }
  4284. var value = obj[i];
  4285. var type = typeof value;
  4286. if (i === 'parent' && type === 'object') {
  4287. if (parent) {
  4288. cloned[i] = parent;
  4289. }
  4290. } else if (value instanceof Array) {
  4291. cloned[i] = value.map(function (j) {
  4292. return cloneNode(j, cloned);
  4293. });
  4294. } else {
  4295. cloned[i] = cloneNode(value, cloned);
  4296. }
  4297. }
  4298. return cloned;
  4299. };
  4300. var Node = /*#__PURE__*/function () {
  4301. function Node(opts) {
  4302. if (opts === void 0) {
  4303. opts = {};
  4304. }
  4305. Object.assign(this, opts);
  4306. this.spaces = this.spaces || {};
  4307. this.spaces.before = this.spaces.before || '';
  4308. this.spaces.after = this.spaces.after || '';
  4309. }
  4310. var _proto = Node.prototype;
  4311. _proto.remove = function remove() {
  4312. if (this.parent) {
  4313. this.parent.removeChild(this);
  4314. }
  4315. this.parent = undefined;
  4316. return this;
  4317. };
  4318. _proto.replaceWith = function replaceWith() {
  4319. if (this.parent) {
  4320. for (var index in arguments) {
  4321. this.parent.insertBefore(this, arguments[index]);
  4322. }
  4323. this.remove();
  4324. }
  4325. return this;
  4326. };
  4327. _proto.next = function next() {
  4328. return this.parent.at(this.parent.index(this) + 1);
  4329. };
  4330. _proto.prev = function prev() {
  4331. return this.parent.at(this.parent.index(this) - 1);
  4332. };
  4333. _proto.clone = function clone(overrides) {
  4334. if (overrides === void 0) {
  4335. overrides = {};
  4336. }
  4337. var cloned = cloneNode(this);
  4338. for (var name in overrides) {
  4339. cloned[name] = overrides[name];
  4340. }
  4341. return cloned;
  4342. }
  4343. /**
  4344. * Some non-standard syntax doesn't follow normal escaping rules for css.
  4345. * This allows non standard syntax to be appended to an existing property
  4346. * by specifying the escaped value. By specifying the escaped value,
  4347. * illegal characters are allowed to be directly inserted into css output.
  4348. * @param {string} name the property to set
  4349. * @param {any} value the unescaped value of the property
  4350. * @param {string} valueEscaped optional. the escaped value of the property.
  4351. */;
  4352. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  4353. if (!this.raws) {
  4354. this.raws = {};
  4355. }
  4356. var originalValue = this[name];
  4357. var originalEscaped = this.raws[name];
  4358. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  4359. if (originalEscaped || valueEscaped !== value) {
  4360. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  4361. } else {
  4362. delete this.raws[name]; // delete any escaped value that was created by the setter.
  4363. }
  4364. }
  4365. /**
  4366. * Some non-standard syntax doesn't follow normal escaping rules for css.
  4367. * This allows the escaped value to be specified directly, allowing illegal
  4368. * characters to be directly inserted into css output.
  4369. * @param {string} name the property to set
  4370. * @param {any} value the unescaped value of the property
  4371. * @param {string} valueEscaped the escaped value of the property.
  4372. */;
  4373. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  4374. if (!this.raws) {
  4375. this.raws = {};
  4376. }
  4377. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  4378. this.raws[name] = valueEscaped;
  4379. }
  4380. /**
  4381. * When you want a value to passed through to CSS directly. This method
  4382. * deletes the corresponding raw value causing the stringifier to fallback
  4383. * to the unescaped value.
  4384. * @param {string} name the property to set.
  4385. * @param {any} value The value that is both escaped and unescaped.
  4386. */;
  4387. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  4388. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  4389. if (this.raws) {
  4390. delete this.raws[name];
  4391. }
  4392. }
  4393. /**
  4394. *
  4395. * @param {number} line The number (starting with 1)
  4396. * @param {number} column The column number (starting with 1)
  4397. */;
  4398. _proto.isAtPosition = function isAtPosition(line, column) {
  4399. if (this.source && this.source.start && this.source.end) {
  4400. if (this.source.start.line > line) {
  4401. return false;
  4402. }
  4403. if (this.source.end.line < line) {
  4404. return false;
  4405. }
  4406. if (this.source.start.line === line && this.source.start.column > column) {
  4407. return false;
  4408. }
  4409. if (this.source.end.line === line && this.source.end.column < column) {
  4410. return false;
  4411. }
  4412. return true;
  4413. }
  4414. return undefined;
  4415. };
  4416. _proto.stringifyProperty = function stringifyProperty(name) {
  4417. return this.raws && this.raws[name] || this[name];
  4418. };
  4419. _proto.valueToString = function valueToString() {
  4420. return String(this.stringifyProperty("value"));
  4421. };
  4422. _proto.toString = function toString() {
  4423. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  4424. };
  4425. _createClass(Node, [{
  4426. key: "rawSpaceBefore",
  4427. get: function get() {
  4428. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  4429. if (rawSpace === undefined) {
  4430. rawSpace = this.spaces && this.spaces.before;
  4431. }
  4432. return rawSpace || "";
  4433. },
  4434. set: function set(raw) {
  4435. (0, _util.ensureObject)(this, "raws", "spaces");
  4436. this.raws.spaces.before = raw;
  4437. }
  4438. }, {
  4439. key: "rawSpaceAfter",
  4440. get: function get() {
  4441. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  4442. if (rawSpace === undefined) {
  4443. rawSpace = this.spaces.after;
  4444. }
  4445. return rawSpace || "";
  4446. },
  4447. set: function set(raw) {
  4448. (0, _util.ensureObject)(this, "raws", "spaces");
  4449. this.raws.spaces.after = raw;
  4450. }
  4451. }]);
  4452. return Node;
  4453. }();
  4454. exports$1["default"] = Node;
  4455. module.exports = exports$1.default;
  4456. } (node$2, node$2.exports));
  4457. return node$2.exports;
  4458. }
  4459. var types$2 = {};
  4460. var hasRequiredTypes$1;
  4461. function requireTypes$1 () {
  4462. if (hasRequiredTypes$1) return types$2;
  4463. hasRequiredTypes$1 = 1;
  4464. types$2.__esModule = true;
  4465. types$2.UNIVERSAL = types$2.TAG = types$2.STRING = types$2.SELECTOR = types$2.ROOT = types$2.PSEUDO = types$2.NESTING = types$2.ID = types$2.COMMENT = types$2.COMBINATOR = types$2.CLASS = types$2.ATTRIBUTE = void 0;
  4466. var TAG = 'tag';
  4467. types$2.TAG = TAG;
  4468. var STRING = 'string';
  4469. types$2.STRING = STRING;
  4470. var SELECTOR = 'selector';
  4471. types$2.SELECTOR = SELECTOR;
  4472. var ROOT = 'root';
  4473. types$2.ROOT = ROOT;
  4474. var PSEUDO = 'pseudo';
  4475. types$2.PSEUDO = PSEUDO;
  4476. var NESTING = 'nesting';
  4477. types$2.NESTING = NESTING;
  4478. var ID = 'id';
  4479. types$2.ID = ID;
  4480. var COMMENT = 'comment';
  4481. types$2.COMMENT = COMMENT;
  4482. var COMBINATOR = 'combinator';
  4483. types$2.COMBINATOR = COMBINATOR;
  4484. var CLASS = 'class';
  4485. types$2.CLASS = CLASS;
  4486. var ATTRIBUTE = 'attribute';
  4487. types$2.ATTRIBUTE = ATTRIBUTE;
  4488. var UNIVERSAL = 'universal';
  4489. types$2.UNIVERSAL = UNIVERSAL;
  4490. return types$2;
  4491. }
  4492. var hasRequiredContainer$1;
  4493. function requireContainer$1 () {
  4494. if (hasRequiredContainer$1) return container$1.exports;
  4495. hasRequiredContainer$1 = 1;
  4496. (function (module, exports$1) {
  4497. exports$1.__esModule = true;
  4498. exports$1["default"] = void 0;
  4499. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  4500. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes$1());
  4501. 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); }
  4502. 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; }
  4503. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4504. 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."); }
  4505. 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); }
  4506. 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; }
  4507. 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); } }
  4508. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4509. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4510. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4511. var Container = /*#__PURE__*/function (_Node) {
  4512. _inheritsLoose(Container, _Node);
  4513. function Container(opts) {
  4514. var _this;
  4515. _this = _Node.call(this, opts) || this;
  4516. if (!_this.nodes) {
  4517. _this.nodes = [];
  4518. }
  4519. return _this;
  4520. }
  4521. var _proto = Container.prototype;
  4522. _proto.append = function append(selector) {
  4523. selector.parent = this;
  4524. this.nodes.push(selector);
  4525. return this;
  4526. };
  4527. _proto.prepend = function prepend(selector) {
  4528. selector.parent = this;
  4529. this.nodes.unshift(selector);
  4530. for (var id in this.indexes) {
  4531. this.indexes[id]++;
  4532. }
  4533. return this;
  4534. };
  4535. _proto.at = function at(index) {
  4536. return this.nodes[index];
  4537. };
  4538. _proto.index = function index(child) {
  4539. if (typeof child === 'number') {
  4540. return child;
  4541. }
  4542. return this.nodes.indexOf(child);
  4543. };
  4544. _proto.removeChild = function removeChild(child) {
  4545. child = this.index(child);
  4546. this.at(child).parent = undefined;
  4547. this.nodes.splice(child, 1);
  4548. var index;
  4549. for (var id in this.indexes) {
  4550. index = this.indexes[id];
  4551. if (index >= child) {
  4552. this.indexes[id] = index - 1;
  4553. }
  4554. }
  4555. return this;
  4556. };
  4557. _proto.removeAll = function removeAll() {
  4558. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  4559. var node = _step.value;
  4560. node.parent = undefined;
  4561. }
  4562. this.nodes = [];
  4563. return this;
  4564. };
  4565. _proto.empty = function empty() {
  4566. return this.removeAll();
  4567. };
  4568. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  4569. var _this$nodes;
  4570. newNode.parent = this;
  4571. var oldIndex = this.index(oldNode);
  4572. var resetNode = [];
  4573. for (var i = 2; i < arguments.length; i++) {
  4574. resetNode.push(arguments[i]);
  4575. }
  4576. (_this$nodes = this.nodes).splice.apply(_this$nodes, [oldIndex + 1, 0, newNode].concat(resetNode));
  4577. newNode.parent = this;
  4578. var index;
  4579. for (var id in this.indexes) {
  4580. index = this.indexes[id];
  4581. if (oldIndex < index) {
  4582. this.indexes[id] = index + arguments.length - 1;
  4583. }
  4584. }
  4585. return this;
  4586. };
  4587. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  4588. var _this$nodes2;
  4589. newNode.parent = this;
  4590. var oldIndex = this.index(oldNode);
  4591. var resetNode = [];
  4592. for (var i = 2; i < arguments.length; i++) {
  4593. resetNode.push(arguments[i]);
  4594. }
  4595. (_this$nodes2 = this.nodes).splice.apply(_this$nodes2, [oldIndex, 0, newNode].concat(resetNode));
  4596. newNode.parent = this;
  4597. var index;
  4598. for (var id in this.indexes) {
  4599. index = this.indexes[id];
  4600. if (index >= oldIndex) {
  4601. this.indexes[id] = index + arguments.length - 1;
  4602. }
  4603. }
  4604. return this;
  4605. };
  4606. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  4607. var found = undefined;
  4608. this.each(function (node) {
  4609. if (node.atPosition) {
  4610. var foundChild = node.atPosition(line, col);
  4611. if (foundChild) {
  4612. found = foundChild;
  4613. return false;
  4614. }
  4615. } else if (node.isAtPosition(line, col)) {
  4616. found = node;
  4617. return false;
  4618. }
  4619. });
  4620. return found;
  4621. }
  4622. /**
  4623. * Return the most specific node at the line and column number given.
  4624. * The source location is based on the original parsed location, locations aren't
  4625. * updated as selector nodes are mutated.
  4626. *
  4627. * Note that this location is relative to the location of the first character
  4628. * of the selector, and not the location of the selector in the overall document
  4629. * when used in conjunction with postcss.
  4630. *
  4631. * If not found, returns undefined.
  4632. * @param {number} line The line number of the node to find. (1-based index)
  4633. * @param {number} col The column number of the node to find. (1-based index)
  4634. */;
  4635. _proto.atPosition = function atPosition(line, col) {
  4636. if (this.isAtPosition(line, col)) {
  4637. return this._findChildAtPosition(line, col) || this;
  4638. } else {
  4639. return undefined;
  4640. }
  4641. };
  4642. _proto._inferEndPosition = function _inferEndPosition() {
  4643. if (this.last && this.last.source && this.last.source.end) {
  4644. this.source = this.source || {};
  4645. this.source.end = this.source.end || {};
  4646. Object.assign(this.source.end, this.last.source.end);
  4647. }
  4648. };
  4649. _proto.each = function each(callback) {
  4650. if (!this.lastEach) {
  4651. this.lastEach = 0;
  4652. }
  4653. if (!this.indexes) {
  4654. this.indexes = {};
  4655. }
  4656. this.lastEach++;
  4657. var id = this.lastEach;
  4658. this.indexes[id] = 0;
  4659. if (!this.length) {
  4660. return undefined;
  4661. }
  4662. var index, result;
  4663. while (this.indexes[id] < this.length) {
  4664. index = this.indexes[id];
  4665. result = callback(this.at(index), index);
  4666. if (result === false) {
  4667. break;
  4668. }
  4669. this.indexes[id] += 1;
  4670. }
  4671. delete this.indexes[id];
  4672. if (result === false) {
  4673. return false;
  4674. }
  4675. };
  4676. _proto.walk = function walk(callback) {
  4677. return this.each(function (node, i) {
  4678. var result = callback(node, i);
  4679. if (result !== false && node.length) {
  4680. result = node.walk(callback);
  4681. }
  4682. if (result === false) {
  4683. return false;
  4684. }
  4685. });
  4686. };
  4687. _proto.walkAttributes = function walkAttributes(callback) {
  4688. var _this2 = this;
  4689. return this.walk(function (selector) {
  4690. if (selector.type === types.ATTRIBUTE) {
  4691. return callback.call(_this2, selector);
  4692. }
  4693. });
  4694. };
  4695. _proto.walkClasses = function walkClasses(callback) {
  4696. var _this3 = this;
  4697. return this.walk(function (selector) {
  4698. if (selector.type === types.CLASS) {
  4699. return callback.call(_this3, selector);
  4700. }
  4701. });
  4702. };
  4703. _proto.walkCombinators = function walkCombinators(callback) {
  4704. var _this4 = this;
  4705. return this.walk(function (selector) {
  4706. if (selector.type === types.COMBINATOR) {
  4707. return callback.call(_this4, selector);
  4708. }
  4709. });
  4710. };
  4711. _proto.walkComments = function walkComments(callback) {
  4712. var _this5 = this;
  4713. return this.walk(function (selector) {
  4714. if (selector.type === types.COMMENT) {
  4715. return callback.call(_this5, selector);
  4716. }
  4717. });
  4718. };
  4719. _proto.walkIds = function walkIds(callback) {
  4720. var _this6 = this;
  4721. return this.walk(function (selector) {
  4722. if (selector.type === types.ID) {
  4723. return callback.call(_this6, selector);
  4724. }
  4725. });
  4726. };
  4727. _proto.walkNesting = function walkNesting(callback) {
  4728. var _this7 = this;
  4729. return this.walk(function (selector) {
  4730. if (selector.type === types.NESTING) {
  4731. return callback.call(_this7, selector);
  4732. }
  4733. });
  4734. };
  4735. _proto.walkPseudos = function walkPseudos(callback) {
  4736. var _this8 = this;
  4737. return this.walk(function (selector) {
  4738. if (selector.type === types.PSEUDO) {
  4739. return callback.call(_this8, selector);
  4740. }
  4741. });
  4742. };
  4743. _proto.walkTags = function walkTags(callback) {
  4744. var _this9 = this;
  4745. return this.walk(function (selector) {
  4746. if (selector.type === types.TAG) {
  4747. return callback.call(_this9, selector);
  4748. }
  4749. });
  4750. };
  4751. _proto.walkUniversals = function walkUniversals(callback) {
  4752. var _this10 = this;
  4753. return this.walk(function (selector) {
  4754. if (selector.type === types.UNIVERSAL) {
  4755. return callback.call(_this10, selector);
  4756. }
  4757. });
  4758. };
  4759. _proto.split = function split(callback) {
  4760. var _this11 = this;
  4761. var current = [];
  4762. return this.reduce(function (memo, node, index) {
  4763. var split = callback.call(_this11, node);
  4764. current.push(node);
  4765. if (split) {
  4766. memo.push(current);
  4767. current = [];
  4768. } else if (index === _this11.length - 1) {
  4769. memo.push(current);
  4770. }
  4771. return memo;
  4772. }, []);
  4773. };
  4774. _proto.map = function map(callback) {
  4775. return this.nodes.map(callback);
  4776. };
  4777. _proto.reduce = function reduce(callback, memo) {
  4778. return this.nodes.reduce(callback, memo);
  4779. };
  4780. _proto.every = function every(callback) {
  4781. return this.nodes.every(callback);
  4782. };
  4783. _proto.some = function some(callback) {
  4784. return this.nodes.some(callback);
  4785. };
  4786. _proto.filter = function filter(callback) {
  4787. return this.nodes.filter(callback);
  4788. };
  4789. _proto.sort = function sort(callback) {
  4790. return this.nodes.sort(callback);
  4791. };
  4792. _proto.toString = function toString() {
  4793. return this.map(String).join('');
  4794. };
  4795. _createClass(Container, [{
  4796. key: "first",
  4797. get: function get() {
  4798. return this.at(0);
  4799. }
  4800. }, {
  4801. key: "last",
  4802. get: function get() {
  4803. return this.at(this.length - 1);
  4804. }
  4805. }, {
  4806. key: "length",
  4807. get: function get() {
  4808. return this.nodes.length;
  4809. }
  4810. }]);
  4811. return Container;
  4812. }(_node["default"]);
  4813. exports$1["default"] = Container;
  4814. module.exports = exports$1.default;
  4815. } (container$1, container$1.exports));
  4816. return container$1.exports;
  4817. }
  4818. var hasRequiredRoot$1;
  4819. function requireRoot$1 () {
  4820. if (hasRequiredRoot$1) return root$1.exports;
  4821. hasRequiredRoot$1 = 1;
  4822. (function (module, exports$1) {
  4823. exports$1.__esModule = true;
  4824. exports$1["default"] = void 0;
  4825. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer$1());
  4826. var _types = /*@__PURE__*/ requireTypes$1();
  4827. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4828. 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); } }
  4829. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4830. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4831. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4832. var Root = /*#__PURE__*/function (_Container) {
  4833. _inheritsLoose(Root, _Container);
  4834. function Root(opts) {
  4835. var _this;
  4836. _this = _Container.call(this, opts) || this;
  4837. _this.type = _types.ROOT;
  4838. return _this;
  4839. }
  4840. var _proto = Root.prototype;
  4841. _proto.toString = function toString() {
  4842. var str = this.reduce(function (memo, selector) {
  4843. memo.push(String(selector));
  4844. return memo;
  4845. }, []).join(',');
  4846. return this.trailingComma ? str + ',' : str;
  4847. };
  4848. _proto.error = function error(message, options) {
  4849. if (this._error) {
  4850. return this._error(message, options);
  4851. } else {
  4852. return new Error(message);
  4853. }
  4854. };
  4855. _createClass(Root, [{
  4856. key: "errorGenerator",
  4857. set: function set(handler) {
  4858. this._error = handler;
  4859. }
  4860. }]);
  4861. return Root;
  4862. }(_container["default"]);
  4863. exports$1["default"] = Root;
  4864. module.exports = exports$1.default;
  4865. } (root$1, root$1.exports));
  4866. return root$1.exports;
  4867. }
  4868. var selector$1 = {exports: {}};
  4869. var hasRequiredSelector$1;
  4870. function requireSelector$1 () {
  4871. if (hasRequiredSelector$1) return selector$1.exports;
  4872. hasRequiredSelector$1 = 1;
  4873. (function (module, exports$1) {
  4874. exports$1.__esModule = true;
  4875. exports$1["default"] = void 0;
  4876. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer$1());
  4877. var _types = /*@__PURE__*/ requireTypes$1();
  4878. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4879. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4880. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4881. var Selector = /*#__PURE__*/function (_Container) {
  4882. _inheritsLoose(Selector, _Container);
  4883. function Selector(opts) {
  4884. var _this;
  4885. _this = _Container.call(this, opts) || this;
  4886. _this.type = _types.SELECTOR;
  4887. return _this;
  4888. }
  4889. return Selector;
  4890. }(_container["default"]);
  4891. exports$1["default"] = Selector;
  4892. module.exports = exports$1.default;
  4893. } (selector$1, selector$1.exports));
  4894. return selector$1.exports;
  4895. }
  4896. var className$1 = {exports: {}};
  4897. /*! https://mths.be/cssesc v3.0.0 by @mathias */
  4898. var cssesc_1;
  4899. var hasRequiredCssesc;
  4900. function requireCssesc () {
  4901. if (hasRequiredCssesc) return cssesc_1;
  4902. hasRequiredCssesc = 1;
  4903. var object = {};
  4904. var hasOwnProperty = object.hasOwnProperty;
  4905. var merge = function merge(options, defaults) {
  4906. if (!options) {
  4907. return defaults;
  4908. }
  4909. var result = {};
  4910. for (var key in defaults) {
  4911. // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
  4912. // only recognized option names are used.
  4913. result[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key];
  4914. }
  4915. return result;
  4916. };
  4917. var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
  4918. var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
  4919. var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  4920. // https://mathiasbynens.be/notes/css-escapes#css
  4921. var cssesc = function cssesc(string, options) {
  4922. options = merge(options, cssesc.options);
  4923. if (options.quotes != 'single' && options.quotes != 'double') {
  4924. options.quotes = 'single';
  4925. }
  4926. var quote = options.quotes == 'double' ? '"' : '\'';
  4927. var isIdentifier = options.isIdentifier;
  4928. var firstChar = string.charAt(0);
  4929. var output = '';
  4930. var counter = 0;
  4931. var length = string.length;
  4932. while (counter < length) {
  4933. var character = string.charAt(counter++);
  4934. var codePoint = character.charCodeAt();
  4935. var value = void 0;
  4936. // If it’s not a printable ASCII character…
  4937. if (codePoint < 0x20 || codePoint > 0x7E) {
  4938. if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
  4939. // It’s a high surrogate, and there is a next character.
  4940. var extra = string.charCodeAt(counter++);
  4941. if ((extra & 0xFC00) == 0xDC00) {
  4942. // next character is low surrogate
  4943. codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
  4944. } else {
  4945. // It’s an unmatched surrogate; only append this code unit, in case
  4946. // the next code unit is the high surrogate of a surrogate pair.
  4947. counter--;
  4948. }
  4949. }
  4950. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4951. } else {
  4952. if (options.escapeEverything) {
  4953. if (regexAnySingleEscape.test(character)) {
  4954. value = '\\' + character;
  4955. } else {
  4956. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4957. }
  4958. } else if (/[\t\n\f\r\x0B]/.test(character)) {
  4959. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4960. } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
  4961. value = '\\' + character;
  4962. } else {
  4963. value = character;
  4964. }
  4965. }
  4966. output += value;
  4967. }
  4968. if (isIdentifier) {
  4969. if (/^-[-\d]/.test(output)) {
  4970. output = '\\-' + output.slice(1);
  4971. } else if (/\d/.test(firstChar)) {
  4972. output = '\\3' + firstChar + ' ' + output.slice(1);
  4973. }
  4974. }
  4975. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  4976. // since they’re redundant. Note that this is only possible if the escape
  4977. // sequence isn’t preceded by an odd number of backslashes.
  4978. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
  4979. if ($1 && $1.length % 2) {
  4980. // It’s not safe to remove the space, so don’t.
  4981. return $0;
  4982. }
  4983. // Strip the space.
  4984. return ($1 || '') + $2;
  4985. });
  4986. if (!isIdentifier && options.wrap) {
  4987. return quote + output + quote;
  4988. }
  4989. return output;
  4990. };
  4991. // Expose default options (so they can be overridden globally).
  4992. cssesc.options = {
  4993. 'escapeEverything': false,
  4994. 'isIdentifier': false,
  4995. 'quotes': 'single',
  4996. 'wrap': false
  4997. };
  4998. cssesc.version = '3.0.0';
  4999. cssesc_1 = cssesc;
  5000. return cssesc_1;
  5001. }
  5002. var hasRequiredClassName$1;
  5003. function requireClassName$1 () {
  5004. if (hasRequiredClassName$1) return className$1.exports;
  5005. hasRequiredClassName$1 = 1;
  5006. (function (module, exports$1) {
  5007. exports$1.__esModule = true;
  5008. exports$1["default"] = void 0;
  5009. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  5010. var _util = /*@__PURE__*/ requireUtil$2();
  5011. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5012. var _types = /*@__PURE__*/ requireTypes$1();
  5013. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5014. 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); } }
  5015. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  5016. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5017. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5018. var ClassName = /*#__PURE__*/function (_Node) {
  5019. _inheritsLoose(ClassName, _Node);
  5020. function ClassName(opts) {
  5021. var _this;
  5022. _this = _Node.call(this, opts) || this;
  5023. _this.type = _types.CLASS;
  5024. _this._constructed = true;
  5025. return _this;
  5026. }
  5027. var _proto = ClassName.prototype;
  5028. _proto.valueToString = function valueToString() {
  5029. return '.' + _Node.prototype.valueToString.call(this);
  5030. };
  5031. _createClass(ClassName, [{
  5032. key: "value",
  5033. get: function get() {
  5034. return this._value;
  5035. },
  5036. set: function set(v) {
  5037. if (this._constructed) {
  5038. var escaped = (0, _cssesc["default"])(v, {
  5039. isIdentifier: true
  5040. });
  5041. if (escaped !== v) {
  5042. (0, _util.ensureObject)(this, "raws");
  5043. this.raws.value = escaped;
  5044. } else if (this.raws) {
  5045. delete this.raws.value;
  5046. }
  5047. }
  5048. this._value = v;
  5049. }
  5050. }]);
  5051. return ClassName;
  5052. }(_node["default"]);
  5053. exports$1["default"] = ClassName;
  5054. module.exports = exports$1.default;
  5055. } (className$1, className$1.exports));
  5056. return className$1.exports;
  5057. }
  5058. var comment$1 = {exports: {}};
  5059. var hasRequiredComment$1;
  5060. function requireComment$1 () {
  5061. if (hasRequiredComment$1) return comment$1.exports;
  5062. hasRequiredComment$1 = 1;
  5063. (function (module, exports$1) {
  5064. exports$1.__esModule = true;
  5065. exports$1["default"] = void 0;
  5066. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5067. var _types = /*@__PURE__*/ requireTypes$1();
  5068. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5069. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5070. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5071. var Comment = /*#__PURE__*/function (_Node) {
  5072. _inheritsLoose(Comment, _Node);
  5073. function Comment(opts) {
  5074. var _this;
  5075. _this = _Node.call(this, opts) || this;
  5076. _this.type = _types.COMMENT;
  5077. return _this;
  5078. }
  5079. return Comment;
  5080. }(_node["default"]);
  5081. exports$1["default"] = Comment;
  5082. module.exports = exports$1.default;
  5083. } (comment$1, comment$1.exports));
  5084. return comment$1.exports;
  5085. }
  5086. var id$1 = {exports: {}};
  5087. var hasRequiredId$1;
  5088. function requireId$1 () {
  5089. if (hasRequiredId$1) return id$1.exports;
  5090. hasRequiredId$1 = 1;
  5091. (function (module, exports$1) {
  5092. exports$1.__esModule = true;
  5093. exports$1["default"] = void 0;
  5094. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5095. var _types = /*@__PURE__*/ requireTypes$1();
  5096. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5097. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5098. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5099. var ID = /*#__PURE__*/function (_Node) {
  5100. _inheritsLoose(ID, _Node);
  5101. function ID(opts) {
  5102. var _this;
  5103. _this = _Node.call(this, opts) || this;
  5104. _this.type = _types.ID;
  5105. return _this;
  5106. }
  5107. var _proto = ID.prototype;
  5108. _proto.valueToString = function valueToString() {
  5109. return '#' + _Node.prototype.valueToString.call(this);
  5110. };
  5111. return ID;
  5112. }(_node["default"]);
  5113. exports$1["default"] = ID;
  5114. module.exports = exports$1.default;
  5115. } (id$1, id$1.exports));
  5116. return id$1.exports;
  5117. }
  5118. var tag$1 = {exports: {}};
  5119. var namespace$1 = {exports: {}};
  5120. var hasRequiredNamespace$1;
  5121. function requireNamespace$1 () {
  5122. if (hasRequiredNamespace$1) return namespace$1.exports;
  5123. hasRequiredNamespace$1 = 1;
  5124. (function (module, exports$1) {
  5125. exports$1.__esModule = true;
  5126. exports$1["default"] = void 0;
  5127. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  5128. var _util = /*@__PURE__*/ requireUtil$2();
  5129. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5130. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5131. 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); } }
  5132. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  5133. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5134. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5135. var Namespace = /*#__PURE__*/function (_Node) {
  5136. _inheritsLoose(Namespace, _Node);
  5137. function Namespace() {
  5138. return _Node.apply(this, arguments) || this;
  5139. }
  5140. var _proto = Namespace.prototype;
  5141. _proto.qualifiedName = function qualifiedName(value) {
  5142. if (this.namespace) {
  5143. return this.namespaceString + "|" + value;
  5144. } else {
  5145. return value;
  5146. }
  5147. };
  5148. _proto.valueToString = function valueToString() {
  5149. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  5150. };
  5151. _createClass(Namespace, [{
  5152. key: "namespace",
  5153. get: function get() {
  5154. return this._namespace;
  5155. },
  5156. set: function set(namespace) {
  5157. if (namespace === true || namespace === "*" || namespace === "&") {
  5158. this._namespace = namespace;
  5159. if (this.raws) {
  5160. delete this.raws.namespace;
  5161. }
  5162. return;
  5163. }
  5164. var escaped = (0, _cssesc["default"])(namespace, {
  5165. isIdentifier: true
  5166. });
  5167. this._namespace = namespace;
  5168. if (escaped !== namespace) {
  5169. (0, _util.ensureObject)(this, "raws");
  5170. this.raws.namespace = escaped;
  5171. } else if (this.raws) {
  5172. delete this.raws.namespace;
  5173. }
  5174. }
  5175. }, {
  5176. key: "ns",
  5177. get: function get() {
  5178. return this._namespace;
  5179. },
  5180. set: function set(namespace) {
  5181. this.namespace = namespace;
  5182. }
  5183. }, {
  5184. key: "namespaceString",
  5185. get: function get() {
  5186. if (this.namespace) {
  5187. var ns = this.stringifyProperty("namespace");
  5188. if (ns === true) {
  5189. return '';
  5190. } else {
  5191. return ns;
  5192. }
  5193. } else {
  5194. return '';
  5195. }
  5196. }
  5197. }]);
  5198. return Namespace;
  5199. }(_node["default"]);
  5200. exports$1["default"] = Namespace;
  5201. module.exports = exports$1.default;
  5202. } (namespace$1, namespace$1.exports));
  5203. return namespace$1.exports;
  5204. }
  5205. var hasRequiredTag$1;
  5206. function requireTag$1 () {
  5207. if (hasRequiredTag$1) return tag$1.exports;
  5208. hasRequiredTag$1 = 1;
  5209. (function (module, exports$1) {
  5210. exports$1.__esModule = true;
  5211. exports$1["default"] = void 0;
  5212. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace$1());
  5213. var _types = /*@__PURE__*/ requireTypes$1();
  5214. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5215. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5216. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5217. var Tag = /*#__PURE__*/function (_Namespace) {
  5218. _inheritsLoose(Tag, _Namespace);
  5219. function Tag(opts) {
  5220. var _this;
  5221. _this = _Namespace.call(this, opts) || this;
  5222. _this.type = _types.TAG;
  5223. return _this;
  5224. }
  5225. return Tag;
  5226. }(_namespace["default"]);
  5227. exports$1["default"] = Tag;
  5228. module.exports = exports$1.default;
  5229. } (tag$1, tag$1.exports));
  5230. return tag$1.exports;
  5231. }
  5232. var string$1 = {exports: {}};
  5233. var hasRequiredString$1;
  5234. function requireString$1 () {
  5235. if (hasRequiredString$1) return string$1.exports;
  5236. hasRequiredString$1 = 1;
  5237. (function (module, exports$1) {
  5238. exports$1.__esModule = true;
  5239. exports$1["default"] = void 0;
  5240. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5241. var _types = /*@__PURE__*/ requireTypes$1();
  5242. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5243. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5244. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5245. var String = /*#__PURE__*/function (_Node) {
  5246. _inheritsLoose(String, _Node);
  5247. function String(opts) {
  5248. var _this;
  5249. _this = _Node.call(this, opts) || this;
  5250. _this.type = _types.STRING;
  5251. return _this;
  5252. }
  5253. return String;
  5254. }(_node["default"]);
  5255. exports$1["default"] = String;
  5256. module.exports = exports$1.default;
  5257. } (string$1, string$1.exports));
  5258. return string$1.exports;
  5259. }
  5260. var pseudo$1 = {exports: {}};
  5261. var hasRequiredPseudo$1;
  5262. function requirePseudo$1 () {
  5263. if (hasRequiredPseudo$1) return pseudo$1.exports;
  5264. hasRequiredPseudo$1 = 1;
  5265. (function (module, exports$1) {
  5266. exports$1.__esModule = true;
  5267. exports$1["default"] = void 0;
  5268. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer$1());
  5269. var _types = /*@__PURE__*/ requireTypes$1();
  5270. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5271. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5272. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5273. var Pseudo = /*#__PURE__*/function (_Container) {
  5274. _inheritsLoose(Pseudo, _Container);
  5275. function Pseudo(opts) {
  5276. var _this;
  5277. _this = _Container.call(this, opts) || this;
  5278. _this.type = _types.PSEUDO;
  5279. return _this;
  5280. }
  5281. var _proto = Pseudo.prototype;
  5282. _proto.toString = function toString() {
  5283. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  5284. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  5285. };
  5286. return Pseudo;
  5287. }(_container["default"]);
  5288. exports$1["default"] = Pseudo;
  5289. module.exports = exports$1.default;
  5290. } (pseudo$1, pseudo$1.exports));
  5291. return pseudo$1.exports;
  5292. }
  5293. var attribute$1 = {};
  5294. var node$1;
  5295. var hasRequiredNode$1;
  5296. function requireNode$1 () {
  5297. if (hasRequiredNode$1) return node$1;
  5298. hasRequiredNode$1 = 1;
  5299. /**
  5300. * For Node.js, simply re-export the core `util.deprecate` function.
  5301. */
  5302. node$1 = require$$2.deprecate;
  5303. return node$1;
  5304. }
  5305. var hasRequiredAttribute$1;
  5306. function requireAttribute$1 () {
  5307. if (hasRequiredAttribute$1) return attribute$1;
  5308. hasRequiredAttribute$1 = 1;
  5309. (function (exports$1) {
  5310. exports$1.__esModule = true;
  5311. exports$1["default"] = void 0;
  5312. exports$1.unescapeValue = unescapeValue;
  5313. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  5314. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc$1());
  5315. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace$1());
  5316. var _types = /*@__PURE__*/ requireTypes$1();
  5317. var _CSSESC_QUOTE_OPTIONS;
  5318. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5319. 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); } }
  5320. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  5321. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5322. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5323. var deprecate = /*@__PURE__*/ requireNode$1();
  5324. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  5325. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  5326. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  5327. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  5328. function unescapeValue(value) {
  5329. var deprecatedUsage = false;
  5330. var quoteMark = null;
  5331. var unescaped = value;
  5332. var m = unescaped.match(WRAPPED_IN_QUOTES);
  5333. if (m) {
  5334. quoteMark = m[1];
  5335. unescaped = m[2];
  5336. }
  5337. unescaped = (0, _unesc["default"])(unescaped);
  5338. if (unescaped !== value) {
  5339. deprecatedUsage = true;
  5340. }
  5341. return {
  5342. deprecatedUsage: deprecatedUsage,
  5343. unescaped: unescaped,
  5344. quoteMark: quoteMark
  5345. };
  5346. }
  5347. function handleDeprecatedContructorOpts(opts) {
  5348. if (opts.quoteMark !== undefined) {
  5349. return opts;
  5350. }
  5351. if (opts.value === undefined) {
  5352. return opts;
  5353. }
  5354. warnOfDeprecatedConstructor();
  5355. var _unescapeValue = unescapeValue(opts.value),
  5356. quoteMark = _unescapeValue.quoteMark,
  5357. unescaped = _unescapeValue.unescaped;
  5358. if (!opts.raws) {
  5359. opts.raws = {};
  5360. }
  5361. if (opts.raws.value === undefined) {
  5362. opts.raws.value = opts.value;
  5363. }
  5364. opts.value = unescaped;
  5365. opts.quoteMark = quoteMark;
  5366. return opts;
  5367. }
  5368. var Attribute = /*#__PURE__*/function (_Namespace) {
  5369. _inheritsLoose(Attribute, _Namespace);
  5370. function Attribute(opts) {
  5371. var _this;
  5372. if (opts === void 0) {
  5373. opts = {};
  5374. }
  5375. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  5376. _this.type = _types.ATTRIBUTE;
  5377. _this.raws = _this.raws || {};
  5378. Object.defineProperty(_this.raws, 'unquoted', {
  5379. get: deprecate(function () {
  5380. return _this.value;
  5381. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  5382. set: deprecate(function () {
  5383. return _this.value;
  5384. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  5385. });
  5386. _this._constructed = true;
  5387. return _this;
  5388. }
  5389. /**
  5390. * Returns the Attribute's value quoted such that it would be legal to use
  5391. * in the value of a css file. The original value's quotation setting
  5392. * used for stringification is left unchanged. See `setValue(value, options)`
  5393. * if you want to control the quote settings of a new value for the attribute.
  5394. *
  5395. * You can also change the quotation used for the current value by setting quoteMark.
  5396. *
  5397. * Options:
  5398. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  5399. * option is not set, the original value for quoteMark will be used. If
  5400. * indeterminate, a double quote is used. The legal values are:
  5401. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  5402. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  5403. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  5404. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  5405. * over the quoteMark option value.
  5406. * * smart {boolean} - if true, will select a quote mark based on the value
  5407. * and the other options specified here. See the `smartQuoteMark()`
  5408. * method.
  5409. **/
  5410. var _proto = Attribute.prototype;
  5411. _proto.getQuotedValue = function getQuotedValue(options) {
  5412. if (options === void 0) {
  5413. options = {};
  5414. }
  5415. var quoteMark = this._determineQuoteMark(options);
  5416. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  5417. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  5418. return escaped;
  5419. };
  5420. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  5421. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  5422. }
  5423. /**
  5424. * Set the unescaped value with the specified quotation options. The value
  5425. * provided must not include any wrapping quote marks -- those quotes will
  5426. * be interpreted as part of the value and escaped accordingly.
  5427. */;
  5428. _proto.setValue = function setValue(value, options) {
  5429. if (options === void 0) {
  5430. options = {};
  5431. }
  5432. this._value = value;
  5433. this._quoteMark = this._determineQuoteMark(options);
  5434. this._syncRawValue();
  5435. }
  5436. /**
  5437. * Intelligently select a quoteMark value based on the value's contents. If
  5438. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  5439. * mark will be picked that minimizes the number of escapes.
  5440. *
  5441. * If there's no clear winner, the quote mark from these options is used,
  5442. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  5443. * true). If the quoteMark is unspecified, a double quote is used.
  5444. *
  5445. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  5446. * from the quoteValue method.
  5447. */;
  5448. _proto.smartQuoteMark = function smartQuoteMark(options) {
  5449. var v = this.value;
  5450. var numSingleQuotes = v.replace(/[^']/g, '').length;
  5451. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  5452. if (numSingleQuotes + numDoubleQuotes === 0) {
  5453. var escaped = (0, _cssesc["default"])(v, {
  5454. isIdentifier: true
  5455. });
  5456. if (escaped === v) {
  5457. return Attribute.NO_QUOTE;
  5458. } else {
  5459. var pref = this.preferredQuoteMark(options);
  5460. if (pref === Attribute.NO_QUOTE) {
  5461. // pick a quote mark that isn't none and see if it's smaller
  5462. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  5463. var opts = CSSESC_QUOTE_OPTIONS[quote];
  5464. var quoteValue = (0, _cssesc["default"])(v, opts);
  5465. if (quoteValue.length < escaped.length) {
  5466. return quote;
  5467. }
  5468. }
  5469. return pref;
  5470. }
  5471. } else if (numDoubleQuotes === numSingleQuotes) {
  5472. return this.preferredQuoteMark(options);
  5473. } else if (numDoubleQuotes < numSingleQuotes) {
  5474. return Attribute.DOUBLE_QUOTE;
  5475. } else {
  5476. return Attribute.SINGLE_QUOTE;
  5477. }
  5478. }
  5479. /**
  5480. * Selects the preferred quote mark based on the options and the current quote mark value.
  5481. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  5482. * instead.
  5483. */;
  5484. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  5485. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  5486. if (quoteMark === undefined) {
  5487. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  5488. }
  5489. if (quoteMark === undefined) {
  5490. quoteMark = Attribute.DOUBLE_QUOTE;
  5491. }
  5492. return quoteMark;
  5493. };
  5494. _proto._syncRawValue = function _syncRawValue() {
  5495. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  5496. if (rawValue === this._value) {
  5497. if (this.raws) {
  5498. delete this.raws.value;
  5499. }
  5500. } else {
  5501. this.raws.value = rawValue;
  5502. }
  5503. };
  5504. _proto._handleEscapes = function _handleEscapes(prop, value) {
  5505. if (this._constructed) {
  5506. var escaped = (0, _cssesc["default"])(value, {
  5507. isIdentifier: true
  5508. });
  5509. if (escaped !== value) {
  5510. this.raws[prop] = escaped;
  5511. } else {
  5512. delete this.raws[prop];
  5513. }
  5514. }
  5515. };
  5516. _proto._spacesFor = function _spacesFor(name) {
  5517. var attrSpaces = {
  5518. before: '',
  5519. after: ''
  5520. };
  5521. var spaces = this.spaces[name] || {};
  5522. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  5523. return Object.assign(attrSpaces, spaces, rawSpaces);
  5524. };
  5525. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  5526. if (spaceName === void 0) {
  5527. spaceName = name;
  5528. }
  5529. if (concat === void 0) {
  5530. concat = defaultAttrConcat;
  5531. }
  5532. var attrSpaces = this._spacesFor(spaceName);
  5533. return concat(this.stringifyProperty(name), attrSpaces);
  5534. }
  5535. /**
  5536. * returns the offset of the attribute part specified relative to the
  5537. * start of the node of the output string.
  5538. *
  5539. * * "ns" - alias for "namespace"
  5540. * * "namespace" - the namespace if it exists.
  5541. * * "attribute" - the attribute name
  5542. * * "attributeNS" - the start of the attribute or its namespace
  5543. * * "operator" - the match operator of the attribute
  5544. * * "value" - The value (string or identifier)
  5545. * * "insensitive" - the case insensitivity flag;
  5546. * @param part One of the possible values inside an attribute.
  5547. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  5548. */;
  5549. _proto.offsetOf = function offsetOf(name) {
  5550. var count = 1;
  5551. var attributeSpaces = this._spacesFor("attribute");
  5552. count += attributeSpaces.before.length;
  5553. if (name === "namespace" || name === "ns") {
  5554. return this.namespace ? count : -1;
  5555. }
  5556. if (name === "attributeNS") {
  5557. return count;
  5558. }
  5559. count += this.namespaceString.length;
  5560. if (this.namespace) {
  5561. count += 1;
  5562. }
  5563. if (name === "attribute") {
  5564. return count;
  5565. }
  5566. count += this.stringifyProperty("attribute").length;
  5567. count += attributeSpaces.after.length;
  5568. var operatorSpaces = this._spacesFor("operator");
  5569. count += operatorSpaces.before.length;
  5570. var operator = this.stringifyProperty("operator");
  5571. if (name === "operator") {
  5572. return operator ? count : -1;
  5573. }
  5574. count += operator.length;
  5575. count += operatorSpaces.after.length;
  5576. var valueSpaces = this._spacesFor("value");
  5577. count += valueSpaces.before.length;
  5578. var value = this.stringifyProperty("value");
  5579. if (name === "value") {
  5580. return value ? count : -1;
  5581. }
  5582. count += value.length;
  5583. count += valueSpaces.after.length;
  5584. var insensitiveSpaces = this._spacesFor("insensitive");
  5585. count += insensitiveSpaces.before.length;
  5586. if (name === "insensitive") {
  5587. return this.insensitive ? count : -1;
  5588. }
  5589. return -1;
  5590. };
  5591. _proto.toString = function toString() {
  5592. var _this2 = this;
  5593. var selector = [this.rawSpaceBefore, '['];
  5594. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  5595. if (this.operator && (this.value || this.value === '')) {
  5596. selector.push(this._stringFor('operator'));
  5597. selector.push(this._stringFor('value'));
  5598. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  5599. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  5600. attrSpaces.before = " ";
  5601. }
  5602. return defaultAttrConcat(attrValue, attrSpaces);
  5603. }));
  5604. }
  5605. selector.push(']');
  5606. selector.push(this.rawSpaceAfter);
  5607. return selector.join('');
  5608. };
  5609. _createClass(Attribute, [{
  5610. key: "quoted",
  5611. get: function get() {
  5612. var qm = this.quoteMark;
  5613. return qm === "'" || qm === '"';
  5614. },
  5615. set: function set(value) {
  5616. warnOfDeprecatedQuotedAssignment();
  5617. }
  5618. /**
  5619. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  5620. * returns `null` if the value is not quoted.
  5621. * returns `undefined` if the quotation state is unknown (this can happen when
  5622. * the attribute is constructed without specifying a quote mark.)
  5623. */
  5624. }, {
  5625. key: "quoteMark",
  5626. get: function get() {
  5627. return this._quoteMark;
  5628. }
  5629. /**
  5630. * Set the quote mark to be used by this attribute's value.
  5631. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  5632. * value is updated accordingly.
  5633. *
  5634. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  5635. */,
  5636. set: function set(quoteMark) {
  5637. if (!this._constructed) {
  5638. this._quoteMark = quoteMark;
  5639. return;
  5640. }
  5641. if (this._quoteMark !== quoteMark) {
  5642. this._quoteMark = quoteMark;
  5643. this._syncRawValue();
  5644. }
  5645. }
  5646. }, {
  5647. key: "qualifiedAttribute",
  5648. get: function get() {
  5649. return this.qualifiedName(this.raws.attribute || this.attribute);
  5650. }
  5651. }, {
  5652. key: "insensitiveFlag",
  5653. get: function get() {
  5654. return this.insensitive ? 'i' : '';
  5655. }
  5656. }, {
  5657. key: "value",
  5658. get: function get() {
  5659. return this._value;
  5660. },
  5661. set:
  5662. /**
  5663. * Before 3.0, the value had to be set to an escaped value including any wrapped
  5664. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  5665. * is unescaped during parsing and any quote marks are removed.
  5666. *
  5667. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  5668. * a deprecation warning is raised when the new value contains any characters that would
  5669. * require escaping (including if it contains wrapped quotes).
  5670. *
  5671. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  5672. * how the new value is quoted.
  5673. */
  5674. function set(v) {
  5675. if (this._constructed) {
  5676. var _unescapeValue2 = unescapeValue(v),
  5677. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  5678. unescaped = _unescapeValue2.unescaped,
  5679. quoteMark = _unescapeValue2.quoteMark;
  5680. if (deprecatedUsage) {
  5681. warnOfDeprecatedValueAssignment();
  5682. }
  5683. if (unescaped === this._value && quoteMark === this._quoteMark) {
  5684. return;
  5685. }
  5686. this._value = unescaped;
  5687. this._quoteMark = quoteMark;
  5688. this._syncRawValue();
  5689. } else {
  5690. this._value = v;
  5691. }
  5692. }
  5693. }, {
  5694. key: "insensitive",
  5695. get: function get() {
  5696. return this._insensitive;
  5697. }
  5698. /**
  5699. * Set the case insensitive flag.
  5700. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  5701. * of the attribute is updated accordingly.
  5702. *
  5703. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  5704. */,
  5705. set: function set(insensitive) {
  5706. if (!insensitive) {
  5707. this._insensitive = false;
  5708. // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  5709. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  5710. if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
  5711. this.raws.insensitiveFlag = undefined;
  5712. }
  5713. }
  5714. this._insensitive = insensitive;
  5715. }
  5716. }, {
  5717. key: "attribute",
  5718. get: function get() {
  5719. return this._attribute;
  5720. },
  5721. set: function set(name) {
  5722. this._handleEscapes("attribute", name);
  5723. this._attribute = name;
  5724. }
  5725. }]);
  5726. return Attribute;
  5727. }(_namespace["default"]);
  5728. exports$1["default"] = Attribute;
  5729. Attribute.NO_QUOTE = null;
  5730. Attribute.SINGLE_QUOTE = "'";
  5731. Attribute.DOUBLE_QUOTE = '"';
  5732. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  5733. "'": {
  5734. quotes: 'single',
  5735. wrap: true
  5736. },
  5737. '"': {
  5738. quotes: 'double',
  5739. wrap: true
  5740. }
  5741. }, _CSSESC_QUOTE_OPTIONS[null] = {
  5742. isIdentifier: true
  5743. }, _CSSESC_QUOTE_OPTIONS);
  5744. function defaultAttrConcat(attrValue, attrSpaces) {
  5745. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  5746. }
  5747. } (attribute$1));
  5748. return attribute$1;
  5749. }
  5750. var universal$1 = {exports: {}};
  5751. var hasRequiredUniversal$1;
  5752. function requireUniversal$1 () {
  5753. if (hasRequiredUniversal$1) return universal$1.exports;
  5754. hasRequiredUniversal$1 = 1;
  5755. (function (module, exports$1) {
  5756. exports$1.__esModule = true;
  5757. exports$1["default"] = void 0;
  5758. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace$1());
  5759. var _types = /*@__PURE__*/ requireTypes$1();
  5760. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5761. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5762. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5763. var Universal = /*#__PURE__*/function (_Namespace) {
  5764. _inheritsLoose(Universal, _Namespace);
  5765. function Universal(opts) {
  5766. var _this;
  5767. _this = _Namespace.call(this, opts) || this;
  5768. _this.type = _types.UNIVERSAL;
  5769. _this.value = '*';
  5770. return _this;
  5771. }
  5772. return Universal;
  5773. }(_namespace["default"]);
  5774. exports$1["default"] = Universal;
  5775. module.exports = exports$1.default;
  5776. } (universal$1, universal$1.exports));
  5777. return universal$1.exports;
  5778. }
  5779. var combinator$1 = {exports: {}};
  5780. var hasRequiredCombinator$1;
  5781. function requireCombinator$1 () {
  5782. if (hasRequiredCombinator$1) return combinator$1.exports;
  5783. hasRequiredCombinator$1 = 1;
  5784. (function (module, exports$1) {
  5785. exports$1.__esModule = true;
  5786. exports$1["default"] = void 0;
  5787. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5788. var _types = /*@__PURE__*/ requireTypes$1();
  5789. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5790. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5791. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5792. var Combinator = /*#__PURE__*/function (_Node) {
  5793. _inheritsLoose(Combinator, _Node);
  5794. function Combinator(opts) {
  5795. var _this;
  5796. _this = _Node.call(this, opts) || this;
  5797. _this.type = _types.COMBINATOR;
  5798. return _this;
  5799. }
  5800. return Combinator;
  5801. }(_node["default"]);
  5802. exports$1["default"] = Combinator;
  5803. module.exports = exports$1.default;
  5804. } (combinator$1, combinator$1.exports));
  5805. return combinator$1.exports;
  5806. }
  5807. var nesting$1 = {exports: {}};
  5808. var hasRequiredNesting$1;
  5809. function requireNesting$1 () {
  5810. if (hasRequiredNesting$1) return nesting$1.exports;
  5811. hasRequiredNesting$1 = 1;
  5812. (function (module, exports$1) {
  5813. exports$1.__esModule = true;
  5814. exports$1["default"] = void 0;
  5815. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5816. var _types = /*@__PURE__*/ requireTypes$1();
  5817. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5818. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5819. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5820. var Nesting = /*#__PURE__*/function (_Node) {
  5821. _inheritsLoose(Nesting, _Node);
  5822. function Nesting(opts) {
  5823. var _this;
  5824. _this = _Node.call(this, opts) || this;
  5825. _this.type = _types.NESTING;
  5826. _this.value = '&';
  5827. return _this;
  5828. }
  5829. return Nesting;
  5830. }(_node["default"]);
  5831. exports$1["default"] = Nesting;
  5832. module.exports = exports$1.default;
  5833. } (nesting$1, nesting$1.exports));
  5834. return nesting$1.exports;
  5835. }
  5836. var sortAscending$1 = {exports: {}};
  5837. var hasRequiredSortAscending$1;
  5838. function requireSortAscending$1 () {
  5839. if (hasRequiredSortAscending$1) return sortAscending$1.exports;
  5840. hasRequiredSortAscending$1 = 1;
  5841. (function (module, exports$1) {
  5842. exports$1.__esModule = true;
  5843. exports$1["default"] = sortAscending;
  5844. function sortAscending(list) {
  5845. return list.sort(function (a, b) {
  5846. return a - b;
  5847. });
  5848. }
  5849. module.exports = exports$1.default;
  5850. } (sortAscending$1, sortAscending$1.exports));
  5851. return sortAscending$1.exports;
  5852. }
  5853. var tokenize$1 = {};
  5854. var tokenTypes$1 = {};
  5855. var hasRequiredTokenTypes$1;
  5856. function requireTokenTypes$1 () {
  5857. if (hasRequiredTokenTypes$1) return tokenTypes$1;
  5858. hasRequiredTokenTypes$1 = 1;
  5859. tokenTypes$1.__esModule = true;
  5860. tokenTypes$1.word = tokenTypes$1.tilde = tokenTypes$1.tab = tokenTypes$1.str = tokenTypes$1.space = tokenTypes$1.slash = tokenTypes$1.singleQuote = tokenTypes$1.semicolon = tokenTypes$1.plus = tokenTypes$1.pipe = tokenTypes$1.openSquare = tokenTypes$1.openParenthesis = tokenTypes$1.newline = tokenTypes$1.greaterThan = tokenTypes$1.feed = tokenTypes$1.equals = tokenTypes$1.doubleQuote = tokenTypes$1.dollar = tokenTypes$1.cr = tokenTypes$1.comment = tokenTypes$1.comma = tokenTypes$1.combinator = tokenTypes$1.colon = tokenTypes$1.closeSquare = tokenTypes$1.closeParenthesis = tokenTypes$1.caret = tokenTypes$1.bang = tokenTypes$1.backslash = tokenTypes$1.at = tokenTypes$1.asterisk = tokenTypes$1.ampersand = void 0;
  5861. var ampersand = 38; // `&`.charCodeAt(0);
  5862. tokenTypes$1.ampersand = ampersand;
  5863. var asterisk = 42; // `*`.charCodeAt(0);
  5864. tokenTypes$1.asterisk = asterisk;
  5865. var at = 64; // `@`.charCodeAt(0);
  5866. tokenTypes$1.at = at;
  5867. var comma = 44; // `,`.charCodeAt(0);
  5868. tokenTypes$1.comma = comma;
  5869. var colon = 58; // `:`.charCodeAt(0);
  5870. tokenTypes$1.colon = colon;
  5871. var semicolon = 59; // `;`.charCodeAt(0);
  5872. tokenTypes$1.semicolon = semicolon;
  5873. var openParenthesis = 40; // `(`.charCodeAt(0);
  5874. tokenTypes$1.openParenthesis = openParenthesis;
  5875. var closeParenthesis = 41; // `)`.charCodeAt(0);
  5876. tokenTypes$1.closeParenthesis = closeParenthesis;
  5877. var openSquare = 91; // `[`.charCodeAt(0);
  5878. tokenTypes$1.openSquare = openSquare;
  5879. var closeSquare = 93; // `]`.charCodeAt(0);
  5880. tokenTypes$1.closeSquare = closeSquare;
  5881. var dollar = 36; // `$`.charCodeAt(0);
  5882. tokenTypes$1.dollar = dollar;
  5883. var tilde = 126; // `~`.charCodeAt(0);
  5884. tokenTypes$1.tilde = tilde;
  5885. var caret = 94; // `^`.charCodeAt(0);
  5886. tokenTypes$1.caret = caret;
  5887. var plus = 43; // `+`.charCodeAt(0);
  5888. tokenTypes$1.plus = plus;
  5889. var equals = 61; // `=`.charCodeAt(0);
  5890. tokenTypes$1.equals = equals;
  5891. var pipe = 124; // `|`.charCodeAt(0);
  5892. tokenTypes$1.pipe = pipe;
  5893. var greaterThan = 62; // `>`.charCodeAt(0);
  5894. tokenTypes$1.greaterThan = greaterThan;
  5895. var space = 32; // ` `.charCodeAt(0);
  5896. tokenTypes$1.space = space;
  5897. var singleQuote = 39; // `'`.charCodeAt(0);
  5898. tokenTypes$1.singleQuote = singleQuote;
  5899. var doubleQuote = 34; // `"`.charCodeAt(0);
  5900. tokenTypes$1.doubleQuote = doubleQuote;
  5901. var slash = 47; // `/`.charCodeAt(0);
  5902. tokenTypes$1.slash = slash;
  5903. var bang = 33; // `!`.charCodeAt(0);
  5904. tokenTypes$1.bang = bang;
  5905. var backslash = 92; // '\\'.charCodeAt(0);
  5906. tokenTypes$1.backslash = backslash;
  5907. var cr = 13; // '\r'.charCodeAt(0);
  5908. tokenTypes$1.cr = cr;
  5909. var feed = 12; // '\f'.charCodeAt(0);
  5910. tokenTypes$1.feed = feed;
  5911. var newline = 10; // '\n'.charCodeAt(0);
  5912. tokenTypes$1.newline = newline;
  5913. var tab = 9; // '\t'.charCodeAt(0);
  5914. // Expose aliases primarily for readability.
  5915. tokenTypes$1.tab = tab;
  5916. var str = singleQuote;
  5917. // No good single character representation!
  5918. tokenTypes$1.str = str;
  5919. var comment = -1;
  5920. tokenTypes$1.comment = comment;
  5921. var word = -2;
  5922. tokenTypes$1.word = word;
  5923. var combinator = -3;
  5924. tokenTypes$1.combinator = combinator;
  5925. return tokenTypes$1;
  5926. }
  5927. var hasRequiredTokenize$1;
  5928. function requireTokenize$1 () {
  5929. if (hasRequiredTokenize$1) return tokenize$1;
  5930. hasRequiredTokenize$1 = 1;
  5931. (function (exports$1) {
  5932. exports$1.__esModule = true;
  5933. exports$1.FIELDS = void 0;
  5934. exports$1["default"] = tokenize;
  5935. var t = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes$1());
  5936. var _unescapable, _wordDelimiters;
  5937. 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); }
  5938. 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; }
  5939. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  5940. 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);
  5941. var hex = {};
  5942. var hexChars = "0123456789abcdefABCDEF";
  5943. for (var i = 0; i < hexChars.length; i++) {
  5944. hex[hexChars.charCodeAt(i)] = true;
  5945. }
  5946. /**
  5947. * Returns the last index of the bar css word
  5948. * @param {string} css The string in which the word begins
  5949. * @param {number} start The index into the string where word's first letter occurs
  5950. */
  5951. function consumeWord(css, start) {
  5952. var next = start;
  5953. var code;
  5954. do {
  5955. code = css.charCodeAt(next);
  5956. if (wordDelimiters[code]) {
  5957. return next - 1;
  5958. } else if (code === t.backslash) {
  5959. next = consumeEscape(css, next) + 1;
  5960. } else {
  5961. // All other characters are part of the word
  5962. next++;
  5963. }
  5964. } while (next < css.length);
  5965. return next - 1;
  5966. }
  5967. /**
  5968. * Returns the last index of the escape sequence
  5969. * @param {string} css The string in which the sequence begins
  5970. * @param {number} start The index into the string where escape character (`\`) occurs.
  5971. */
  5972. function consumeEscape(css, start) {
  5973. var next = start;
  5974. var code = css.charCodeAt(next + 1);
  5975. if (unescapable[code]) ; else if (hex[code]) {
  5976. var hexDigits = 0;
  5977. // consume up to 6 hex chars
  5978. do {
  5979. next++;
  5980. hexDigits++;
  5981. code = css.charCodeAt(next + 1);
  5982. } while (hex[code] && hexDigits < 6);
  5983. // if fewer than 6 hex chars, a trailing space ends the escape
  5984. if (hexDigits < 6 && code === t.space) {
  5985. next++;
  5986. }
  5987. } else {
  5988. // the next char is part of the current word
  5989. next++;
  5990. }
  5991. return next;
  5992. }
  5993. var FIELDS = {
  5994. TYPE: 0,
  5995. START_LINE: 1,
  5996. START_COL: 2,
  5997. END_LINE: 3,
  5998. END_COL: 4,
  5999. START_POS: 5,
  6000. END_POS: 6
  6001. };
  6002. exports$1.FIELDS = FIELDS;
  6003. function tokenize(input) {
  6004. var tokens = [];
  6005. var css = input.css.valueOf();
  6006. var _css = css,
  6007. length = _css.length;
  6008. var offset = -1;
  6009. var line = 1;
  6010. var start = 0;
  6011. var end = 0;
  6012. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  6013. function unclosed(what, fix) {
  6014. if (input.safe) {
  6015. // fyi: this is never set to true.
  6016. css += fix;
  6017. next = css.length - 1;
  6018. } else {
  6019. throw input.error('Unclosed ' + what, line, start - offset, start);
  6020. }
  6021. }
  6022. while (start < length) {
  6023. code = css.charCodeAt(start);
  6024. if (code === t.newline) {
  6025. offset = start;
  6026. line += 1;
  6027. }
  6028. switch (code) {
  6029. case t.space:
  6030. case t.tab:
  6031. case t.newline:
  6032. case t.cr:
  6033. case t.feed:
  6034. next = start;
  6035. do {
  6036. next += 1;
  6037. code = css.charCodeAt(next);
  6038. if (code === t.newline) {
  6039. offset = next;
  6040. line += 1;
  6041. }
  6042. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  6043. tokenType = t.space;
  6044. endLine = line;
  6045. endColumn = next - offset - 1;
  6046. end = next;
  6047. break;
  6048. case t.plus:
  6049. case t.greaterThan:
  6050. case t.tilde:
  6051. case t.pipe:
  6052. next = start;
  6053. do {
  6054. next += 1;
  6055. code = css.charCodeAt(next);
  6056. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  6057. tokenType = t.combinator;
  6058. endLine = line;
  6059. endColumn = start - offset;
  6060. end = next;
  6061. break;
  6062. // Consume these characters as single tokens.
  6063. case t.asterisk:
  6064. case t.ampersand:
  6065. case t.bang:
  6066. case t.comma:
  6067. case t.equals:
  6068. case t.dollar:
  6069. case t.caret:
  6070. case t.openSquare:
  6071. case t.closeSquare:
  6072. case t.colon:
  6073. case t.semicolon:
  6074. case t.openParenthesis:
  6075. case t.closeParenthesis:
  6076. next = start;
  6077. tokenType = code;
  6078. endLine = line;
  6079. endColumn = start - offset;
  6080. end = next + 1;
  6081. break;
  6082. case t.singleQuote:
  6083. case t.doubleQuote:
  6084. quote = code === t.singleQuote ? "'" : '"';
  6085. next = start;
  6086. do {
  6087. escaped = false;
  6088. next = css.indexOf(quote, next + 1);
  6089. if (next === -1) {
  6090. unclosed('quote', quote);
  6091. }
  6092. escapePos = next;
  6093. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  6094. escapePos -= 1;
  6095. escaped = !escaped;
  6096. }
  6097. } while (escaped);
  6098. tokenType = t.str;
  6099. endLine = line;
  6100. endColumn = start - offset;
  6101. end = next + 1;
  6102. break;
  6103. default:
  6104. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  6105. next = css.indexOf('*/', start + 2) + 1;
  6106. if (next === 0) {
  6107. unclosed('comment', '*/');
  6108. }
  6109. content = css.slice(start, next + 1);
  6110. lines = content.split('\n');
  6111. last = lines.length - 1;
  6112. if (last > 0) {
  6113. nextLine = line + last;
  6114. nextOffset = next - lines[last].length;
  6115. } else {
  6116. nextLine = line;
  6117. nextOffset = offset;
  6118. }
  6119. tokenType = t.comment;
  6120. line = nextLine;
  6121. endLine = nextLine;
  6122. endColumn = next - nextOffset;
  6123. } else if (code === t.slash) {
  6124. next = start;
  6125. tokenType = code;
  6126. endLine = line;
  6127. endColumn = start - offset;
  6128. end = next + 1;
  6129. } else {
  6130. next = consumeWord(css, start);
  6131. tokenType = t.word;
  6132. endLine = line;
  6133. endColumn = next - offset;
  6134. }
  6135. end = next + 1;
  6136. break;
  6137. }
  6138. // Ensure that the token structure remains consistent
  6139. tokens.push([tokenType,
  6140. // [0] Token type
  6141. line,
  6142. // [1] Starting line
  6143. start - offset,
  6144. // [2] Starting column
  6145. endLine,
  6146. // [3] Ending line
  6147. endColumn,
  6148. // [4] Ending column
  6149. start,
  6150. // [5] Start position / Source index
  6151. end // [6] End position
  6152. ]);
  6153. // Reset offset for the next token
  6154. if (nextOffset) {
  6155. offset = nextOffset;
  6156. nextOffset = null;
  6157. }
  6158. start = end;
  6159. }
  6160. return tokens;
  6161. }
  6162. } (tokenize$1));
  6163. return tokenize$1;
  6164. }
  6165. var hasRequiredParser$2;
  6166. function requireParser$2 () {
  6167. if (hasRequiredParser$2) return parser$1.exports;
  6168. hasRequiredParser$2 = 1;
  6169. (function (module, exports$1) {
  6170. exports$1.__esModule = true;
  6171. exports$1["default"] = void 0;
  6172. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot$1());
  6173. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector$1());
  6174. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName$1());
  6175. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment$1());
  6176. var _id = _interopRequireDefault(/*@__PURE__*/ requireId$1());
  6177. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag$1());
  6178. var _string = _interopRequireDefault(/*@__PURE__*/ requireString$1());
  6179. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo$1());
  6180. var _attribute = _interopRequireWildcard(/*@__PURE__*/ requireAttribute$1());
  6181. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal$1());
  6182. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator$1());
  6183. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting$1());
  6184. var _sortAscending = _interopRequireDefault(/*@__PURE__*/ requireSortAscending$1());
  6185. var _tokenize = _interopRequireWildcard(/*@__PURE__*/ requireTokenize$1());
  6186. var tokens = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes$1());
  6187. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes$1());
  6188. var _util = /*@__PURE__*/ requireUtil$2();
  6189. var _WHITESPACE_TOKENS, _Object$assign;
  6190. 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); }
  6191. 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; }
  6192. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  6193. 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); } }
  6194. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  6195. 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);
  6196. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  6197. function tokenStart(token) {
  6198. return {
  6199. line: token[_tokenize.FIELDS.START_LINE],
  6200. column: token[_tokenize.FIELDS.START_COL]
  6201. };
  6202. }
  6203. function tokenEnd(token) {
  6204. return {
  6205. line: token[_tokenize.FIELDS.END_LINE],
  6206. column: token[_tokenize.FIELDS.END_COL]
  6207. };
  6208. }
  6209. function getSource(startLine, startColumn, endLine, endColumn) {
  6210. return {
  6211. start: {
  6212. line: startLine,
  6213. column: startColumn
  6214. },
  6215. end: {
  6216. line: endLine,
  6217. column: endColumn
  6218. }
  6219. };
  6220. }
  6221. function getTokenSource(token) {
  6222. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  6223. }
  6224. function getTokenSourceSpan(startToken, endToken) {
  6225. if (!startToken) {
  6226. return undefined;
  6227. }
  6228. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  6229. }
  6230. function unescapeProp(node, prop) {
  6231. var value = node[prop];
  6232. if (typeof value !== "string") {
  6233. return;
  6234. }
  6235. if (value.indexOf("\\") !== -1) {
  6236. (0, _util.ensureObject)(node, 'raws');
  6237. node[prop] = (0, _util.unesc)(value);
  6238. if (node.raws[prop] === undefined) {
  6239. node.raws[prop] = value;
  6240. }
  6241. }
  6242. return node;
  6243. }
  6244. function indexesOf(array, item) {
  6245. var i = -1;
  6246. var indexes = [];
  6247. while ((i = array.indexOf(item, i + 1)) !== -1) {
  6248. indexes.push(i);
  6249. }
  6250. return indexes;
  6251. }
  6252. function uniqs() {
  6253. var list = Array.prototype.concat.apply([], arguments);
  6254. return list.filter(function (item, i) {
  6255. return i === list.indexOf(item);
  6256. });
  6257. }
  6258. var Parser = /*#__PURE__*/function () {
  6259. function Parser(rule, options) {
  6260. if (options === void 0) {
  6261. options = {};
  6262. }
  6263. this.rule = rule;
  6264. this.options = Object.assign({
  6265. lossy: false,
  6266. safe: false
  6267. }, options);
  6268. this.position = 0;
  6269. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  6270. this.tokens = (0, _tokenize["default"])({
  6271. css: this.css,
  6272. error: this._errorGenerator(),
  6273. safe: this.options.safe
  6274. });
  6275. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  6276. this.root = new _root["default"]({
  6277. source: rootSource
  6278. });
  6279. this.root.errorGenerator = this._errorGenerator();
  6280. var selector = new _selector["default"]({
  6281. source: {
  6282. start: {
  6283. line: 1,
  6284. column: 1
  6285. }
  6286. },
  6287. sourceIndex: 0
  6288. });
  6289. this.root.append(selector);
  6290. this.current = selector;
  6291. this.loop();
  6292. }
  6293. var _proto = Parser.prototype;
  6294. _proto._errorGenerator = function _errorGenerator() {
  6295. var _this = this;
  6296. return function (message, errorOptions) {
  6297. if (typeof _this.rule === 'string') {
  6298. return new Error(message);
  6299. }
  6300. return _this.rule.error(message, errorOptions);
  6301. };
  6302. };
  6303. _proto.attribute = function attribute() {
  6304. var attr = [];
  6305. var startingToken = this.currToken;
  6306. this.position++;
  6307. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  6308. attr.push(this.currToken);
  6309. this.position++;
  6310. }
  6311. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  6312. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  6313. }
  6314. var len = attr.length;
  6315. var node = {
  6316. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  6317. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  6318. };
  6319. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  6320. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  6321. }
  6322. var pos = 0;
  6323. var spaceBefore = '';
  6324. var commentBefore = '';
  6325. var lastAdded = null;
  6326. var spaceAfterMeaningfulToken = false;
  6327. while (pos < len) {
  6328. var token = attr[pos];
  6329. var content = this.content(token);
  6330. var next = attr[pos + 1];
  6331. switch (token[_tokenize.FIELDS.TYPE]) {
  6332. case tokens.space:
  6333. // if (
  6334. // len === 1 ||
  6335. // pos === 0 && this.content(next) === '|'
  6336. // ) {
  6337. // return this.expected('attribute', token[TOKEN.START_POS], content);
  6338. // }
  6339. spaceAfterMeaningfulToken = true;
  6340. if (this.options.lossy) {
  6341. break;
  6342. }
  6343. if (lastAdded) {
  6344. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  6345. var prevContent = node.spaces[lastAdded].after || '';
  6346. node.spaces[lastAdded].after = prevContent + content;
  6347. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  6348. if (existingComment) {
  6349. node.raws.spaces[lastAdded].after = existingComment + content;
  6350. }
  6351. } else {
  6352. spaceBefore = spaceBefore + content;
  6353. commentBefore = commentBefore + content;
  6354. }
  6355. break;
  6356. case tokens.asterisk:
  6357. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6358. node.operator = content;
  6359. lastAdded = 'operator';
  6360. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  6361. if (spaceBefore) {
  6362. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  6363. node.spaces.attribute.before = spaceBefore;
  6364. spaceBefore = '';
  6365. }
  6366. if (commentBefore) {
  6367. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  6368. node.raws.spaces.attribute.before = spaceBefore;
  6369. commentBefore = '';
  6370. }
  6371. node.namespace = (node.namespace || "") + content;
  6372. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  6373. if (rawValue) {
  6374. node.raws.namespace += content;
  6375. }
  6376. lastAdded = 'namespace';
  6377. }
  6378. spaceAfterMeaningfulToken = false;
  6379. break;
  6380. case tokens.dollar:
  6381. if (lastAdded === "value") {
  6382. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  6383. node.value += "$";
  6384. if (oldRawValue) {
  6385. node.raws.value = oldRawValue + "$";
  6386. }
  6387. break;
  6388. }
  6389. // Falls through
  6390. case tokens.caret:
  6391. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6392. node.operator = content;
  6393. lastAdded = 'operator';
  6394. }
  6395. spaceAfterMeaningfulToken = false;
  6396. break;
  6397. case tokens.combinator:
  6398. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6399. node.operator = content;
  6400. lastAdded = 'operator';
  6401. }
  6402. if (content !== '|') {
  6403. spaceAfterMeaningfulToken = false;
  6404. break;
  6405. }
  6406. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6407. node.operator = content;
  6408. lastAdded = 'operator';
  6409. } else if (!node.namespace && !node.attribute) {
  6410. node.namespace = true;
  6411. }
  6412. spaceAfterMeaningfulToken = false;
  6413. break;
  6414. case tokens.word:
  6415. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
  6416. // this look-ahead probably fails with comment nodes involved.
  6417. !node.operator && !node.namespace) {
  6418. node.namespace = content;
  6419. lastAdded = 'namespace';
  6420. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  6421. if (spaceBefore) {
  6422. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  6423. node.spaces.attribute.before = spaceBefore;
  6424. spaceBefore = '';
  6425. }
  6426. if (commentBefore) {
  6427. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  6428. node.raws.spaces.attribute.before = commentBefore;
  6429. commentBefore = '';
  6430. }
  6431. node.attribute = (node.attribute || "") + content;
  6432. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  6433. if (_rawValue) {
  6434. node.raws.attribute += content;
  6435. }
  6436. lastAdded = 'attribute';
  6437. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  6438. var _unescaped = (0, _util.unesc)(content);
  6439. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  6440. var oldValue = node.value || '';
  6441. node.value = oldValue + _unescaped;
  6442. node.quoteMark = null;
  6443. if (_unescaped !== content || _oldRawValue) {
  6444. (0, _util.ensureObject)(node, 'raws');
  6445. node.raws.value = (_oldRawValue || oldValue) + content;
  6446. }
  6447. lastAdded = 'value';
  6448. } else {
  6449. var insensitive = content === 'i' || content === "I";
  6450. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  6451. node.insensitive = insensitive;
  6452. if (!insensitive || content === "I") {
  6453. (0, _util.ensureObject)(node, 'raws');
  6454. node.raws.insensitiveFlag = content;
  6455. }
  6456. lastAdded = 'insensitive';
  6457. if (spaceBefore) {
  6458. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  6459. node.spaces.insensitive.before = spaceBefore;
  6460. spaceBefore = '';
  6461. }
  6462. if (commentBefore) {
  6463. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  6464. node.raws.spaces.insensitive.before = commentBefore;
  6465. commentBefore = '';
  6466. }
  6467. } else if (node.value || node.value === '') {
  6468. lastAdded = 'value';
  6469. node.value += content;
  6470. if (node.raws.value) {
  6471. node.raws.value += content;
  6472. }
  6473. }
  6474. }
  6475. spaceAfterMeaningfulToken = false;
  6476. break;
  6477. case tokens.str:
  6478. if (!node.attribute || !node.operator) {
  6479. return this.error("Expected an attribute followed by an operator preceding the string.", {
  6480. index: token[_tokenize.FIELDS.START_POS]
  6481. });
  6482. }
  6483. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  6484. unescaped = _unescapeValue.unescaped,
  6485. quoteMark = _unescapeValue.quoteMark;
  6486. node.value = unescaped;
  6487. node.quoteMark = quoteMark;
  6488. lastAdded = 'value';
  6489. (0, _util.ensureObject)(node, 'raws');
  6490. node.raws.value = content;
  6491. spaceAfterMeaningfulToken = false;
  6492. break;
  6493. case tokens.equals:
  6494. if (!node.attribute) {
  6495. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  6496. }
  6497. if (node.value) {
  6498. return this.error('Unexpected "=" found; an operator was already defined.', {
  6499. index: token[_tokenize.FIELDS.START_POS]
  6500. });
  6501. }
  6502. node.operator = node.operator ? node.operator + content : content;
  6503. lastAdded = 'operator';
  6504. spaceAfterMeaningfulToken = false;
  6505. break;
  6506. case tokens.comment:
  6507. if (lastAdded) {
  6508. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  6509. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  6510. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  6511. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  6512. node.raws.spaces[lastAdded].after = rawLastComment + content;
  6513. } else {
  6514. var lastValue = node[lastAdded] || '';
  6515. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  6516. (0, _util.ensureObject)(node, 'raws');
  6517. node.raws[lastAdded] = rawLastValue + content;
  6518. }
  6519. } else {
  6520. commentBefore = commentBefore + content;
  6521. }
  6522. break;
  6523. default:
  6524. return this.error("Unexpected \"" + content + "\" found.", {
  6525. index: token[_tokenize.FIELDS.START_POS]
  6526. });
  6527. }
  6528. pos++;
  6529. }
  6530. unescapeProp(node, "attribute");
  6531. unescapeProp(node, "namespace");
  6532. this.newNode(new _attribute["default"](node));
  6533. this.position++;
  6534. }
  6535. /**
  6536. * return a node containing meaningless garbage up to (but not including) the specified token position.
  6537. * if the token position is negative, all remaining tokens are consumed.
  6538. *
  6539. * This returns an array containing a single string node if all whitespace,
  6540. * otherwise an array of comment nodes with space before and after.
  6541. *
  6542. * These tokens are not added to the current selector, the caller can add them or use them to amend
  6543. * a previous node's space metadata.
  6544. *
  6545. * In lossy mode, this returns only comments.
  6546. */;
  6547. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  6548. if (stopPosition < 0) {
  6549. stopPosition = this.tokens.length;
  6550. }
  6551. var startPosition = this.position;
  6552. var nodes = [];
  6553. var space = "";
  6554. var lastComment = undefined;
  6555. do {
  6556. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  6557. if (!this.options.lossy) {
  6558. space += this.content();
  6559. }
  6560. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  6561. var spaces = {};
  6562. if (space) {
  6563. spaces.before = space;
  6564. space = "";
  6565. }
  6566. lastComment = new _comment["default"]({
  6567. value: this.content(),
  6568. source: getTokenSource(this.currToken),
  6569. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  6570. spaces: spaces
  6571. });
  6572. nodes.push(lastComment);
  6573. }
  6574. } while (++this.position < stopPosition);
  6575. if (space) {
  6576. if (lastComment) {
  6577. lastComment.spaces.after = space;
  6578. } else if (!this.options.lossy) {
  6579. var firstToken = this.tokens[startPosition];
  6580. var lastToken = this.tokens[this.position - 1];
  6581. nodes.push(new _string["default"]({
  6582. value: '',
  6583. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  6584. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  6585. spaces: {
  6586. before: space,
  6587. after: ''
  6588. }
  6589. }));
  6590. }
  6591. }
  6592. return nodes;
  6593. }
  6594. /**
  6595. *
  6596. * @param {*} nodes
  6597. */;
  6598. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  6599. var _this2 = this;
  6600. if (requiredSpace === void 0) {
  6601. requiredSpace = false;
  6602. }
  6603. var space = "";
  6604. var rawSpace = "";
  6605. nodes.forEach(function (n) {
  6606. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  6607. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  6608. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  6609. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  6610. });
  6611. if (rawSpace === space) {
  6612. rawSpace = undefined;
  6613. }
  6614. var result = {
  6615. space: space,
  6616. rawSpace: rawSpace
  6617. };
  6618. return result;
  6619. };
  6620. _proto.isNamedCombinator = function isNamedCombinator(position) {
  6621. if (position === void 0) {
  6622. position = this.position;
  6623. }
  6624. 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;
  6625. };
  6626. _proto.namedCombinator = function namedCombinator() {
  6627. if (this.isNamedCombinator()) {
  6628. var nameRaw = this.content(this.tokens[this.position + 1]);
  6629. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  6630. var raws = {};
  6631. if (name !== nameRaw) {
  6632. raws.value = "/" + nameRaw + "/";
  6633. }
  6634. var node = new _combinator["default"]({
  6635. value: "/" + name + "/",
  6636. 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]),
  6637. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  6638. raws: raws
  6639. });
  6640. this.position = this.position + 3;
  6641. return node;
  6642. } else {
  6643. this.unexpected();
  6644. }
  6645. };
  6646. _proto.combinator = function combinator() {
  6647. var _this3 = this;
  6648. if (this.content() === '|') {
  6649. return this.namespace();
  6650. }
  6651. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  6652. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  6653. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6654. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  6655. if (nodes.length > 0) {
  6656. var last = this.current.last;
  6657. if (last) {
  6658. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  6659. space = _this$convertWhitespa.space,
  6660. rawSpace = _this$convertWhitespa.rawSpace;
  6661. if (rawSpace !== undefined) {
  6662. last.rawSpaceAfter += rawSpace;
  6663. }
  6664. last.spaces.after += space;
  6665. } else {
  6666. nodes.forEach(function (n) {
  6667. return _this3.newNode(n);
  6668. });
  6669. }
  6670. }
  6671. return;
  6672. }
  6673. var firstToken = this.currToken;
  6674. var spaceOrDescendantSelectorNodes = undefined;
  6675. if (nextSigTokenPos > this.position) {
  6676. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  6677. }
  6678. var node;
  6679. if (this.isNamedCombinator()) {
  6680. node = this.namedCombinator();
  6681. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  6682. node = new _combinator["default"]({
  6683. value: this.content(),
  6684. source: getTokenSource(this.currToken),
  6685. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  6686. });
  6687. this.position++;
  6688. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  6689. this.unexpected();
  6690. }
  6691. if (node) {
  6692. if (spaceOrDescendantSelectorNodes) {
  6693. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  6694. _space = _this$convertWhitespa2.space,
  6695. _rawSpace = _this$convertWhitespa2.rawSpace;
  6696. node.spaces.before = _space;
  6697. node.rawSpaceBefore = _rawSpace;
  6698. }
  6699. } else {
  6700. // descendant combinator
  6701. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  6702. _space2 = _this$convertWhitespa3.space,
  6703. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  6704. if (!_rawSpace2) {
  6705. _rawSpace2 = _space2;
  6706. }
  6707. var spaces = {};
  6708. var raws = {
  6709. spaces: {}
  6710. };
  6711. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  6712. spaces.before = _space2.slice(0, _space2.length - 1);
  6713. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  6714. } else if (_space2[0] === ' ' && _rawSpace2[0] === ' ') {
  6715. spaces.after = _space2.slice(1);
  6716. raws.spaces.after = _rawSpace2.slice(1);
  6717. } else {
  6718. raws.value = _rawSpace2;
  6719. }
  6720. node = new _combinator["default"]({
  6721. value: ' ',
  6722. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  6723. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  6724. spaces: spaces,
  6725. raws: raws
  6726. });
  6727. }
  6728. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  6729. node.spaces.after = this.optionalSpace(this.content());
  6730. this.position++;
  6731. }
  6732. return this.newNode(node);
  6733. };
  6734. _proto.comma = function comma() {
  6735. if (this.position === this.tokens.length - 1) {
  6736. this.root.trailingComma = true;
  6737. this.position++;
  6738. return;
  6739. }
  6740. this.current._inferEndPosition();
  6741. var selector = new _selector["default"]({
  6742. source: {
  6743. start: tokenStart(this.tokens[this.position + 1])
  6744. },
  6745. sourceIndex: this.tokens[this.position + 1][_tokenize.FIELDS.START_POS]
  6746. });
  6747. this.current.parent.append(selector);
  6748. this.current = selector;
  6749. this.position++;
  6750. };
  6751. _proto.comment = function comment() {
  6752. var current = this.currToken;
  6753. this.newNode(new _comment["default"]({
  6754. value: this.content(),
  6755. source: getTokenSource(current),
  6756. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6757. }));
  6758. this.position++;
  6759. };
  6760. _proto.error = function error(message, opts) {
  6761. throw this.root.error(message, opts);
  6762. };
  6763. _proto.missingBackslash = function missingBackslash() {
  6764. return this.error('Expected a backslash preceding the semicolon.', {
  6765. index: this.currToken[_tokenize.FIELDS.START_POS]
  6766. });
  6767. };
  6768. _proto.missingParenthesis = function missingParenthesis() {
  6769. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  6770. };
  6771. _proto.missingSquareBracket = function missingSquareBracket() {
  6772. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  6773. };
  6774. _proto.unexpected = function unexpected() {
  6775. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  6776. };
  6777. _proto.unexpectedPipe = function unexpectedPipe() {
  6778. return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  6779. };
  6780. _proto.namespace = function namespace() {
  6781. var before = this.prevToken && this.content(this.prevToken) || true;
  6782. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  6783. this.position++;
  6784. return this.word(before);
  6785. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  6786. this.position++;
  6787. return this.universal(before);
  6788. }
  6789. this.unexpectedPipe();
  6790. };
  6791. _proto.nesting = function nesting() {
  6792. if (this.nextToken) {
  6793. var nextContent = this.content(this.nextToken);
  6794. if (nextContent === "|") {
  6795. this.position++;
  6796. return;
  6797. }
  6798. }
  6799. var current = this.currToken;
  6800. this.newNode(new _nesting["default"]({
  6801. value: this.content(),
  6802. source: getTokenSource(current),
  6803. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6804. }));
  6805. this.position++;
  6806. };
  6807. _proto.parentheses = function parentheses() {
  6808. var last = this.current.last;
  6809. var unbalanced = 1;
  6810. this.position++;
  6811. if (last && last.type === types.PSEUDO) {
  6812. var selector = new _selector["default"]({
  6813. source: {
  6814. start: tokenStart(this.tokens[this.position])
  6815. },
  6816. sourceIndex: this.tokens[this.position][_tokenize.FIELDS.START_POS]
  6817. });
  6818. var cache = this.current;
  6819. last.append(selector);
  6820. this.current = selector;
  6821. while (this.position < this.tokens.length && unbalanced) {
  6822. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6823. unbalanced++;
  6824. }
  6825. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6826. unbalanced--;
  6827. }
  6828. if (unbalanced) {
  6829. this.parse();
  6830. } else {
  6831. this.current.source.end = tokenEnd(this.currToken);
  6832. this.current.parent.source.end = tokenEnd(this.currToken);
  6833. this.position++;
  6834. }
  6835. }
  6836. this.current = cache;
  6837. } else {
  6838. // I think this case should be an error. It's used to implement a basic parse of media queries
  6839. // but I don't think it's a good idea.
  6840. var parenStart = this.currToken;
  6841. var parenValue = "(";
  6842. var parenEnd;
  6843. while (this.position < this.tokens.length && unbalanced) {
  6844. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6845. unbalanced++;
  6846. }
  6847. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6848. unbalanced--;
  6849. }
  6850. parenEnd = this.currToken;
  6851. parenValue += this.parseParenthesisToken(this.currToken);
  6852. this.position++;
  6853. }
  6854. if (last) {
  6855. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  6856. } else {
  6857. this.newNode(new _string["default"]({
  6858. value: parenValue,
  6859. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  6860. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  6861. }));
  6862. }
  6863. }
  6864. if (unbalanced) {
  6865. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  6866. }
  6867. };
  6868. _proto.pseudo = function pseudo() {
  6869. var _this4 = this;
  6870. var pseudoStr = '';
  6871. var startingToken = this.currToken;
  6872. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  6873. pseudoStr += this.content();
  6874. this.position++;
  6875. }
  6876. if (!this.currToken) {
  6877. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  6878. }
  6879. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  6880. this.splitWord(false, function (first, length) {
  6881. pseudoStr += first;
  6882. _this4.newNode(new _pseudo["default"]({
  6883. value: pseudoStr,
  6884. source: getTokenSourceSpan(startingToken, _this4.currToken),
  6885. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  6886. }));
  6887. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6888. _this4.error('Misplaced parenthesis.', {
  6889. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  6890. });
  6891. }
  6892. });
  6893. } else {
  6894. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  6895. }
  6896. };
  6897. _proto.space = function space() {
  6898. var content = this.content();
  6899. // Handle space before and after the selector
  6900. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  6901. return node.type === 'comment';
  6902. })) {
  6903. this.spaces = this.optionalSpace(content);
  6904. this.position++;
  6905. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6906. this.current.last.spaces.after = this.optionalSpace(content);
  6907. this.position++;
  6908. } else {
  6909. this.combinator();
  6910. }
  6911. };
  6912. _proto.string = function string() {
  6913. var current = this.currToken;
  6914. this.newNode(new _string["default"]({
  6915. value: this.content(),
  6916. source: getTokenSource(current),
  6917. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6918. }));
  6919. this.position++;
  6920. };
  6921. _proto.universal = function universal(namespace) {
  6922. var nextToken = this.nextToken;
  6923. if (nextToken && this.content(nextToken) === '|') {
  6924. this.position++;
  6925. return this.namespace();
  6926. }
  6927. var current = this.currToken;
  6928. this.newNode(new _universal["default"]({
  6929. value: this.content(),
  6930. source: getTokenSource(current),
  6931. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6932. }), namespace);
  6933. this.position++;
  6934. };
  6935. _proto.splitWord = function splitWord(namespace, firstCallback) {
  6936. var _this5 = this;
  6937. var nextToken = this.nextToken;
  6938. var word = this.content();
  6939. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  6940. this.position++;
  6941. var current = this.content();
  6942. word += current;
  6943. if (current.lastIndexOf('\\') === current.length - 1) {
  6944. var next = this.nextToken;
  6945. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  6946. word += this.requiredSpace(this.content(next));
  6947. this.position++;
  6948. }
  6949. }
  6950. nextToken = this.nextToken;
  6951. }
  6952. var hasClass = indexesOf(word, '.').filter(function (i) {
  6953. // Allow escaped dot within class name
  6954. var escapedDot = word[i - 1] === '\\';
  6955. // Allow decimal numbers percent in @keyframes
  6956. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  6957. return !escapedDot && !isKeyframesPercent;
  6958. });
  6959. var hasId = indexesOf(word, '#').filter(function (i) {
  6960. return word[i - 1] !== '\\';
  6961. });
  6962. // Eliminate Sass interpolations from the list of id indexes
  6963. var interpolations = indexesOf(word, '#{');
  6964. if (interpolations.length) {
  6965. hasId = hasId.filter(function (hashIndex) {
  6966. return !~interpolations.indexOf(hashIndex);
  6967. });
  6968. }
  6969. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  6970. indices.forEach(function (ind, i) {
  6971. var index = indices[i + 1] || word.length;
  6972. var value = word.slice(ind, index);
  6973. if (i === 0 && firstCallback) {
  6974. return firstCallback.call(_this5, value, indices.length);
  6975. }
  6976. var node;
  6977. var current = _this5.currToken;
  6978. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  6979. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  6980. if (~hasClass.indexOf(ind)) {
  6981. var classNameOpts = {
  6982. value: value.slice(1),
  6983. source: source,
  6984. sourceIndex: sourceIndex
  6985. };
  6986. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  6987. } else if (~hasId.indexOf(ind)) {
  6988. var idOpts = {
  6989. value: value.slice(1),
  6990. source: source,
  6991. sourceIndex: sourceIndex
  6992. };
  6993. node = new _id["default"](unescapeProp(idOpts, "value"));
  6994. } else {
  6995. var tagOpts = {
  6996. value: value,
  6997. source: source,
  6998. sourceIndex: sourceIndex
  6999. };
  7000. unescapeProp(tagOpts, "value");
  7001. node = new _tag["default"](tagOpts);
  7002. }
  7003. _this5.newNode(node, namespace);
  7004. // Ensure that the namespace is used only once
  7005. namespace = null;
  7006. });
  7007. this.position++;
  7008. };
  7009. _proto.word = function word(namespace) {
  7010. var nextToken = this.nextToken;
  7011. if (nextToken && this.content(nextToken) === '|') {
  7012. this.position++;
  7013. return this.namespace();
  7014. }
  7015. return this.splitWord(namespace);
  7016. };
  7017. _proto.loop = function loop() {
  7018. while (this.position < this.tokens.length) {
  7019. this.parse(true);
  7020. }
  7021. this.current._inferEndPosition();
  7022. return this.root;
  7023. };
  7024. _proto.parse = function parse(throwOnParenthesis) {
  7025. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  7026. case tokens.space:
  7027. this.space();
  7028. break;
  7029. case tokens.comment:
  7030. this.comment();
  7031. break;
  7032. case tokens.openParenthesis:
  7033. this.parentheses();
  7034. break;
  7035. case tokens.closeParenthesis:
  7036. if (throwOnParenthesis) {
  7037. this.missingParenthesis();
  7038. }
  7039. break;
  7040. case tokens.openSquare:
  7041. this.attribute();
  7042. break;
  7043. case tokens.dollar:
  7044. case tokens.caret:
  7045. case tokens.equals:
  7046. case tokens.word:
  7047. this.word();
  7048. break;
  7049. case tokens.colon:
  7050. this.pseudo();
  7051. break;
  7052. case tokens.comma:
  7053. this.comma();
  7054. break;
  7055. case tokens.asterisk:
  7056. this.universal();
  7057. break;
  7058. case tokens.ampersand:
  7059. this.nesting();
  7060. break;
  7061. case tokens.slash:
  7062. case tokens.combinator:
  7063. this.combinator();
  7064. break;
  7065. case tokens.str:
  7066. this.string();
  7067. break;
  7068. // These cases throw; no break needed.
  7069. case tokens.closeSquare:
  7070. this.missingSquareBracket();
  7071. case tokens.semicolon:
  7072. this.missingBackslash();
  7073. default:
  7074. this.unexpected();
  7075. }
  7076. }
  7077. /**
  7078. * Helpers
  7079. */;
  7080. _proto.expected = function expected(description, index, found) {
  7081. if (Array.isArray(description)) {
  7082. var last = description.pop();
  7083. description = description.join(', ') + " or " + last;
  7084. }
  7085. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  7086. if (!found) {
  7087. return this.error("Expected " + an + " " + description + ".", {
  7088. index: index
  7089. });
  7090. }
  7091. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  7092. index: index
  7093. });
  7094. };
  7095. _proto.requiredSpace = function requiredSpace(space) {
  7096. return this.options.lossy ? ' ' : space;
  7097. };
  7098. _proto.optionalSpace = function optionalSpace(space) {
  7099. return this.options.lossy ? '' : space;
  7100. };
  7101. _proto.lossySpace = function lossySpace(space, required) {
  7102. if (this.options.lossy) {
  7103. return required ? ' ' : '';
  7104. } else {
  7105. return space;
  7106. }
  7107. };
  7108. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  7109. var content = this.content(token);
  7110. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  7111. return this.requiredSpace(content);
  7112. } else {
  7113. return content;
  7114. }
  7115. };
  7116. _proto.newNode = function newNode(node, namespace) {
  7117. if (namespace) {
  7118. if (/^ +$/.test(namespace)) {
  7119. if (!this.options.lossy) {
  7120. this.spaces = (this.spaces || '') + namespace;
  7121. }
  7122. namespace = true;
  7123. }
  7124. node.namespace = namespace;
  7125. unescapeProp(node, "namespace");
  7126. }
  7127. if (this.spaces) {
  7128. node.spaces.before = this.spaces;
  7129. this.spaces = '';
  7130. }
  7131. return this.current.append(node);
  7132. };
  7133. _proto.content = function content(token) {
  7134. if (token === void 0) {
  7135. token = this.currToken;
  7136. }
  7137. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  7138. };
  7139. /**
  7140. * returns the index of the next non-whitespace, non-comment token.
  7141. * returns -1 if no meaningful token is found.
  7142. */
  7143. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  7144. if (startPosition === void 0) {
  7145. startPosition = this.position + 1;
  7146. }
  7147. var searchPosition = startPosition;
  7148. while (searchPosition < this.tokens.length) {
  7149. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  7150. searchPosition++;
  7151. continue;
  7152. } else {
  7153. return searchPosition;
  7154. }
  7155. }
  7156. return -1;
  7157. };
  7158. _createClass(Parser, [{
  7159. key: "currToken",
  7160. get: function get() {
  7161. return this.tokens[this.position];
  7162. }
  7163. }, {
  7164. key: "nextToken",
  7165. get: function get() {
  7166. return this.tokens[this.position + 1];
  7167. }
  7168. }, {
  7169. key: "prevToken",
  7170. get: function get() {
  7171. return this.tokens[this.position - 1];
  7172. }
  7173. }]);
  7174. return Parser;
  7175. }();
  7176. exports$1["default"] = Parser;
  7177. module.exports = exports$1.default;
  7178. } (parser$1, parser$1.exports));
  7179. return parser$1.exports;
  7180. }
  7181. var hasRequiredProcessor$1;
  7182. function requireProcessor$1 () {
  7183. if (hasRequiredProcessor$1) return processor$1.exports;
  7184. hasRequiredProcessor$1 = 1;
  7185. (function (module, exports$1) {
  7186. exports$1.__esModule = true;
  7187. exports$1["default"] = void 0;
  7188. var _parser = _interopRequireDefault(/*@__PURE__*/ requireParser$2());
  7189. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7190. var Processor = /*#__PURE__*/function () {
  7191. function Processor(func, options) {
  7192. this.func = func || function noop() {};
  7193. this.funcRes = null;
  7194. this.options = options;
  7195. }
  7196. var _proto = Processor.prototype;
  7197. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  7198. if (options === void 0) {
  7199. options = {};
  7200. }
  7201. var merged = Object.assign({}, this.options, options);
  7202. if (merged.updateSelector === false) {
  7203. return false;
  7204. } else {
  7205. return typeof rule !== "string";
  7206. }
  7207. };
  7208. _proto._isLossy = function _isLossy(options) {
  7209. if (options === void 0) {
  7210. options = {};
  7211. }
  7212. var merged = Object.assign({}, this.options, options);
  7213. if (merged.lossless === false) {
  7214. return true;
  7215. } else {
  7216. return false;
  7217. }
  7218. };
  7219. _proto._root = function _root(rule, options) {
  7220. if (options === void 0) {
  7221. options = {};
  7222. }
  7223. var parser = new _parser["default"](rule, this._parseOptions(options));
  7224. return parser.root;
  7225. };
  7226. _proto._parseOptions = function _parseOptions(options) {
  7227. return {
  7228. lossy: this._isLossy(options)
  7229. };
  7230. };
  7231. _proto._run = function _run(rule, options) {
  7232. var _this = this;
  7233. if (options === void 0) {
  7234. options = {};
  7235. }
  7236. return new Promise(function (resolve, reject) {
  7237. try {
  7238. var root = _this._root(rule, options);
  7239. Promise.resolve(_this.func(root)).then(function (transform) {
  7240. var string = undefined;
  7241. if (_this._shouldUpdateSelector(rule, options)) {
  7242. string = root.toString();
  7243. rule.selector = string;
  7244. }
  7245. return {
  7246. transform: transform,
  7247. root: root,
  7248. string: string
  7249. };
  7250. }).then(resolve, reject);
  7251. } catch (e) {
  7252. reject(e);
  7253. return;
  7254. }
  7255. });
  7256. };
  7257. _proto._runSync = function _runSync(rule, options) {
  7258. if (options === void 0) {
  7259. options = {};
  7260. }
  7261. var root = this._root(rule, options);
  7262. var transform = this.func(root);
  7263. if (transform && typeof transform.then === "function") {
  7264. throw new Error("Selector processor returned a promise to a synchronous call.");
  7265. }
  7266. var string = undefined;
  7267. if (options.updateSelector && typeof rule !== "string") {
  7268. string = root.toString();
  7269. rule.selector = string;
  7270. }
  7271. return {
  7272. transform: transform,
  7273. root: root,
  7274. string: string
  7275. };
  7276. }
  7277. /**
  7278. * Process rule into a selector AST.
  7279. *
  7280. * @param rule {postcss.Rule | string} The css selector to be processed
  7281. * @param options The options for processing
  7282. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  7283. */;
  7284. _proto.ast = function ast(rule, options) {
  7285. return this._run(rule, options).then(function (result) {
  7286. return result.root;
  7287. });
  7288. }
  7289. /**
  7290. * Process rule into a selector AST synchronously.
  7291. *
  7292. * @param rule {postcss.Rule | string} The css selector to be processed
  7293. * @param options The options for processing
  7294. * @returns {parser.Root} The AST of the selector after processing it.
  7295. */;
  7296. _proto.astSync = function astSync(rule, options) {
  7297. return this._runSync(rule, options).root;
  7298. }
  7299. /**
  7300. * Process a selector into a transformed value asynchronously
  7301. *
  7302. * @param rule {postcss.Rule | string} The css selector to be processed
  7303. * @param options The options for processing
  7304. * @returns {Promise<any>} The value returned by the processor.
  7305. */;
  7306. _proto.transform = function transform(rule, options) {
  7307. return this._run(rule, options).then(function (result) {
  7308. return result.transform;
  7309. });
  7310. }
  7311. /**
  7312. * Process a selector into a transformed value synchronously.
  7313. *
  7314. * @param rule {postcss.Rule | string} The css selector to be processed
  7315. * @param options The options for processing
  7316. * @returns {any} The value returned by the processor.
  7317. */;
  7318. _proto.transformSync = function transformSync(rule, options) {
  7319. return this._runSync(rule, options).transform;
  7320. }
  7321. /**
  7322. * Process a selector into a new selector string asynchronously.
  7323. *
  7324. * @param rule {postcss.Rule | string} The css selector to be processed
  7325. * @param options The options for processing
  7326. * @returns {string} the selector after processing.
  7327. */;
  7328. _proto.process = function process(rule, options) {
  7329. return this._run(rule, options).then(function (result) {
  7330. return result.string || result.root.toString();
  7331. });
  7332. }
  7333. /**
  7334. * Process a selector into a new selector string synchronously.
  7335. *
  7336. * @param rule {postcss.Rule | string} The css selector to be processed
  7337. * @param options The options for processing
  7338. * @returns {string} the selector after processing.
  7339. */;
  7340. _proto.processSync = function processSync(rule, options) {
  7341. var result = this._runSync(rule, options);
  7342. return result.string || result.root.toString();
  7343. };
  7344. return Processor;
  7345. }();
  7346. exports$1["default"] = Processor;
  7347. module.exports = exports$1.default;
  7348. } (processor$1, processor$1.exports));
  7349. return processor$1.exports;
  7350. }
  7351. var selectors$1 = {};
  7352. var constructors$1 = {};
  7353. var hasRequiredConstructors$1;
  7354. function requireConstructors$1 () {
  7355. if (hasRequiredConstructors$1) return constructors$1;
  7356. hasRequiredConstructors$1 = 1;
  7357. constructors$1.__esModule = true;
  7358. 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;
  7359. var _attribute = _interopRequireDefault(/*@__PURE__*/ requireAttribute$1());
  7360. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName$1());
  7361. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator$1());
  7362. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment$1());
  7363. var _id = _interopRequireDefault(/*@__PURE__*/ requireId$1());
  7364. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting$1());
  7365. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo$1());
  7366. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot$1());
  7367. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector$1());
  7368. var _string = _interopRequireDefault(/*@__PURE__*/ requireString$1());
  7369. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag$1());
  7370. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal$1());
  7371. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7372. var attribute = function attribute(opts) {
  7373. return new _attribute["default"](opts);
  7374. };
  7375. constructors$1.attribute = attribute;
  7376. var className = function className(opts) {
  7377. return new _className["default"](opts);
  7378. };
  7379. constructors$1.className = className;
  7380. var combinator = function combinator(opts) {
  7381. return new _combinator["default"](opts);
  7382. };
  7383. constructors$1.combinator = combinator;
  7384. var comment = function comment(opts) {
  7385. return new _comment["default"](opts);
  7386. };
  7387. constructors$1.comment = comment;
  7388. var id = function id(opts) {
  7389. return new _id["default"](opts);
  7390. };
  7391. constructors$1.id = id;
  7392. var nesting = function nesting(opts) {
  7393. return new _nesting["default"](opts);
  7394. };
  7395. constructors$1.nesting = nesting;
  7396. var pseudo = function pseudo(opts) {
  7397. return new _pseudo["default"](opts);
  7398. };
  7399. constructors$1.pseudo = pseudo;
  7400. var root = function root(opts) {
  7401. return new _root["default"](opts);
  7402. };
  7403. constructors$1.root = root;
  7404. var selector = function selector(opts) {
  7405. return new _selector["default"](opts);
  7406. };
  7407. constructors$1.selector = selector;
  7408. var string = function string(opts) {
  7409. return new _string["default"](opts);
  7410. };
  7411. constructors$1.string = string;
  7412. var tag = function tag(opts) {
  7413. return new _tag["default"](opts);
  7414. };
  7415. constructors$1.tag = tag;
  7416. var universal = function universal(opts) {
  7417. return new _universal["default"](opts);
  7418. };
  7419. constructors$1.universal = universal;
  7420. return constructors$1;
  7421. }
  7422. var guards$1 = {};
  7423. var hasRequiredGuards$1;
  7424. function requireGuards$1 () {
  7425. if (hasRequiredGuards$1) return guards$1;
  7426. hasRequiredGuards$1 = 1;
  7427. guards$1.__esModule = true;
  7428. guards$1.isComment = guards$1.isCombinator = guards$1.isClassName = guards$1.isAttribute = void 0;
  7429. guards$1.isContainer = isContainer;
  7430. guards$1.isIdentifier = void 0;
  7431. guards$1.isNamespace = isNamespace;
  7432. guards$1.isNesting = void 0;
  7433. guards$1.isNode = isNode;
  7434. guards$1.isPseudo = void 0;
  7435. guards$1.isPseudoClass = isPseudoClass;
  7436. guards$1.isPseudoElement = isPseudoElement;
  7437. guards$1.isUniversal = guards$1.isTag = guards$1.isString = guards$1.isSelector = guards$1.isRoot = void 0;
  7438. var _types = /*@__PURE__*/ requireTypes$1();
  7439. var _IS_TYPE;
  7440. 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);
  7441. function isNode(node) {
  7442. return typeof node === "object" && IS_TYPE[node.type];
  7443. }
  7444. function isNodeType(type, node) {
  7445. return isNode(node) && node.type === type;
  7446. }
  7447. var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  7448. guards$1.isAttribute = isAttribute;
  7449. var isClassName = isNodeType.bind(null, _types.CLASS);
  7450. guards$1.isClassName = isClassName;
  7451. var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  7452. guards$1.isCombinator = isCombinator;
  7453. var isComment = isNodeType.bind(null, _types.COMMENT);
  7454. guards$1.isComment = isComment;
  7455. var isIdentifier = isNodeType.bind(null, _types.ID);
  7456. guards$1.isIdentifier = isIdentifier;
  7457. var isNesting = isNodeType.bind(null, _types.NESTING);
  7458. guards$1.isNesting = isNesting;
  7459. var isPseudo = isNodeType.bind(null, _types.PSEUDO);
  7460. guards$1.isPseudo = isPseudo;
  7461. var isRoot = isNodeType.bind(null, _types.ROOT);
  7462. guards$1.isRoot = isRoot;
  7463. var isSelector = isNodeType.bind(null, _types.SELECTOR);
  7464. guards$1.isSelector = isSelector;
  7465. var isString = isNodeType.bind(null, _types.STRING);
  7466. guards$1.isString = isString;
  7467. var isTag = isNodeType.bind(null, _types.TAG);
  7468. guards$1.isTag = isTag;
  7469. var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  7470. guards$1.isUniversal = isUniversal;
  7471. function isPseudoElement(node) {
  7472. 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");
  7473. }
  7474. function isPseudoClass(node) {
  7475. return isPseudo(node) && !isPseudoElement(node);
  7476. }
  7477. function isContainer(node) {
  7478. return !!(isNode(node) && node.walk);
  7479. }
  7480. function isNamespace(node) {
  7481. return isAttribute(node) || isTag(node);
  7482. }
  7483. return guards$1;
  7484. }
  7485. var hasRequiredSelectors$1;
  7486. function requireSelectors$1 () {
  7487. if (hasRequiredSelectors$1) return selectors$1;
  7488. hasRequiredSelectors$1 = 1;
  7489. (function (exports$1) {
  7490. exports$1.__esModule = true;
  7491. var _types = /*@__PURE__*/ requireTypes$1();
  7492. Object.keys(_types).forEach(function (key) {
  7493. if (key === "default" || key === "__esModule") return;
  7494. if (key in exports$1 && exports$1[key] === _types[key]) return;
  7495. exports$1[key] = _types[key];
  7496. });
  7497. var _constructors = /*@__PURE__*/ requireConstructors$1();
  7498. Object.keys(_constructors).forEach(function (key) {
  7499. if (key === "default" || key === "__esModule") return;
  7500. if (key in exports$1 && exports$1[key] === _constructors[key]) return;
  7501. exports$1[key] = _constructors[key];
  7502. });
  7503. var _guards = /*@__PURE__*/ requireGuards$1();
  7504. Object.keys(_guards).forEach(function (key) {
  7505. if (key === "default" || key === "__esModule") return;
  7506. if (key in exports$1 && exports$1[key] === _guards[key]) return;
  7507. exports$1[key] = _guards[key];
  7508. });
  7509. } (selectors$1));
  7510. return selectors$1;
  7511. }
  7512. var hasRequiredDist$1;
  7513. function requireDist$1 () {
  7514. if (hasRequiredDist$1) return dist$1.exports;
  7515. hasRequiredDist$1 = 1;
  7516. (function (module, exports$1) {
  7517. exports$1.__esModule = true;
  7518. exports$1["default"] = void 0;
  7519. var _processor = _interopRequireDefault(/*@__PURE__*/ requireProcessor$1());
  7520. var selectors = _interopRequireWildcard(/*@__PURE__*/ requireSelectors$1());
  7521. 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); }
  7522. 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; }
  7523. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7524. var parser = function parser(processor) {
  7525. return new _processor["default"](processor);
  7526. };
  7527. Object.assign(parser, selectors);
  7528. delete parser.__esModule;
  7529. var _default = parser;
  7530. exports$1["default"] = _default;
  7531. module.exports = exports$1.default;
  7532. } (dist$1, dist$1.exports));
  7533. return dist$1.exports;
  7534. }
  7535. var distExports = /*@__PURE__*/ requireDist$1();
  7536. var selectorParser = /*@__PURE__*/getDefaultExportFromCjs(distExports);
  7537. const animationNameRE = /^(?:-\w+-)?animation-name$/;
  7538. const animationRE = /^(?:-\w+-)?animation$/;
  7539. const keyframesRE = /^(?:-\w+-)?keyframes$/;
  7540. const scopedPlugin = (id = "") => {
  7541. const keyframes = /* @__PURE__ */ Object.create(null);
  7542. const shortId = id.replace(/^data-v-/, "");
  7543. return {
  7544. postcssPlugin: "vue-sfc-scoped",
  7545. Rule(rule) {
  7546. processRule(id, rule);
  7547. },
  7548. AtRule(node) {
  7549. if (keyframesRE.test(node.name) && !node.params.endsWith(`-${shortId}`)) {
  7550. keyframes[node.params] = node.params = node.params + "-" + shortId;
  7551. }
  7552. },
  7553. OnceExit(root) {
  7554. if (Object.keys(keyframes).length) {
  7555. root.walkDecls((decl) => {
  7556. if (animationNameRE.test(decl.prop)) {
  7557. decl.value = decl.value.split(",").map((v) => keyframes[v.trim()] || v.trim()).join(",");
  7558. }
  7559. if (animationRE.test(decl.prop)) {
  7560. decl.value = decl.value.split(",").map((v) => {
  7561. const vals = v.trim().split(/\s+/);
  7562. const i = vals.findIndex((val) => keyframes[val]);
  7563. if (i !== -1) {
  7564. vals.splice(i, 1, keyframes[vals[i]]);
  7565. return vals.join(" ");
  7566. } else {
  7567. return v;
  7568. }
  7569. }).join(",");
  7570. }
  7571. });
  7572. }
  7573. }
  7574. };
  7575. };
  7576. const processedRules = /* @__PURE__ */ new WeakSet();
  7577. function processRule(id, rule) {
  7578. if (processedRules.has(rule) || rule.parent && rule.parent.type === "atrule" && keyframesRE.test(rule.parent.name)) {
  7579. return;
  7580. }
  7581. processedRules.add(rule);
  7582. let deep = false;
  7583. let parent = rule.parent;
  7584. while (parent && parent.type !== "root") {
  7585. if (parent.__deep) {
  7586. deep = true;
  7587. break;
  7588. }
  7589. parent = parent.parent;
  7590. }
  7591. rule.selector = selectorParser((selectorRoot) => {
  7592. selectorRoot.each((selector) => {
  7593. rewriteSelector(id, rule, selector, selectorRoot, deep);
  7594. });
  7595. }).processSync(rule.selector);
  7596. }
  7597. function rewriteSelector(id, rule, selector, selectorRoot, deep, slotted = false) {
  7598. let node = null;
  7599. let shouldInject = !deep;
  7600. selector.each((n) => {
  7601. if (n.type === "combinator" && (n.value === ">>>" || n.value === "/deep/")) {
  7602. n.value = " ";
  7603. n.spaces.before = n.spaces.after = "";
  7604. warn(
  7605. `the >>> and /deep/ combinators have been deprecated. Use :deep() instead.`
  7606. );
  7607. return false;
  7608. }
  7609. if (n.type === "pseudo") {
  7610. const { value } = n;
  7611. if (value === ":deep" || value === "::v-deep") {
  7612. rule.__deep = true;
  7613. if (n.nodes.length) {
  7614. let last = n;
  7615. n.nodes[0].each((ss) => {
  7616. selector.insertAfter(last, ss);
  7617. last = ss;
  7618. });
  7619. const prev = selector.at(selector.index(n) - 1);
  7620. if (!prev || !isSpaceCombinator(prev)) {
  7621. selector.insertAfter(
  7622. n,
  7623. selectorParser.combinator({
  7624. value: " "
  7625. })
  7626. );
  7627. }
  7628. selector.removeChild(n);
  7629. } else {
  7630. warn(
  7631. `${value} usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead of ${value} <inner-selector>.`
  7632. );
  7633. const prev = selector.at(selector.index(n) - 1);
  7634. if (prev && isSpaceCombinator(prev)) {
  7635. selector.removeChild(prev);
  7636. }
  7637. selector.removeChild(n);
  7638. }
  7639. return false;
  7640. }
  7641. if (value === ":slotted" || value === "::v-slotted") {
  7642. rewriteSelector(
  7643. id,
  7644. rule,
  7645. n.nodes[0],
  7646. selectorRoot,
  7647. deep,
  7648. true
  7649. );
  7650. let last = n;
  7651. n.nodes[0].each((ss) => {
  7652. selector.insertAfter(last, ss);
  7653. last = ss;
  7654. });
  7655. selector.removeChild(n);
  7656. shouldInject = false;
  7657. return false;
  7658. }
  7659. if (value === ":global" || value === "::v-global") {
  7660. selector.replaceWith(n.nodes[0]);
  7661. return false;
  7662. }
  7663. }
  7664. if (n.type === "universal") {
  7665. const prev = selector.at(selector.index(n) - 1);
  7666. const next = selector.at(selector.index(n) + 1);
  7667. if (!prev) {
  7668. if (next) {
  7669. if (next.type === "combinator" && next.value === " ") {
  7670. selector.removeChild(next);
  7671. }
  7672. selector.removeChild(n);
  7673. return;
  7674. } else {
  7675. node = selectorParser.combinator({
  7676. value: ""
  7677. });
  7678. selector.insertBefore(n, node);
  7679. selector.removeChild(n);
  7680. return false;
  7681. }
  7682. }
  7683. if (node) return;
  7684. }
  7685. if (n.type !== "pseudo" && n.type !== "combinator" || n.type === "pseudo" && (n.value === ":is" || n.value === ":where") && !node) {
  7686. node = n;
  7687. }
  7688. });
  7689. if (rule.nodes.some((node2) => node2.type === "rule")) {
  7690. const deep2 = rule.__deep;
  7691. if (!deep2) {
  7692. extractAndWrapNodes(rule);
  7693. const atruleNodes = rule.nodes.filter((node2) => node2.type === "atrule");
  7694. for (const atnode of atruleNodes) {
  7695. extractAndWrapNodes(atnode);
  7696. }
  7697. }
  7698. shouldInject = deep2;
  7699. }
  7700. if (node) {
  7701. const { type, value } = node;
  7702. if (type === "pseudo" && (value === ":is" || value === ":where")) {
  7703. node.nodes.forEach(
  7704. (value2) => rewriteSelector(id, rule, value2, selectorRoot, deep, slotted)
  7705. );
  7706. shouldInject = false;
  7707. }
  7708. }
  7709. if (node) {
  7710. node.spaces.after = "";
  7711. } else {
  7712. selector.first.spaces.before = "";
  7713. }
  7714. if (shouldInject) {
  7715. const idToAdd = slotted ? id + "-s" : id;
  7716. selector.insertAfter(
  7717. // If node is null it means we need to inject [id] at the start
  7718. // insertAfter can handle `null` here
  7719. node,
  7720. selectorParser.attribute({
  7721. attribute: idToAdd,
  7722. value: idToAdd,
  7723. raws: {},
  7724. quoteMark: `"`
  7725. })
  7726. );
  7727. }
  7728. }
  7729. function isSpaceCombinator(node) {
  7730. return node.type === "combinator" && /^\s+$/.test(node.value);
  7731. }
  7732. function extractAndWrapNodes(parentNode) {
  7733. if (!parentNode.nodes) return;
  7734. const nodes = parentNode.nodes.filter(
  7735. (node) => node.type === "decl" || node.type === "comment"
  7736. );
  7737. if (nodes.length) {
  7738. for (const node of nodes) {
  7739. parentNode.removeChild(node);
  7740. }
  7741. const wrappedRule = new require$$0$1.Rule({
  7742. nodes,
  7743. selector: "&"
  7744. });
  7745. parentNode.prepend(wrappedRule);
  7746. }
  7747. }
  7748. scopedPlugin.postcss = true;
  7749. var sourceMap = {};
  7750. var sourceMapGenerator = {};
  7751. var base64Vlq = {};
  7752. var base64 = {};
  7753. /* -*- Mode: js; js-indent-level: 2; -*- */
  7754. var hasRequiredBase64;
  7755. function requireBase64 () {
  7756. if (hasRequiredBase64) return base64;
  7757. hasRequiredBase64 = 1;
  7758. /*
  7759. * Copyright 2011 Mozilla Foundation and contributors
  7760. * Licensed under the New BSD license. See LICENSE or:
  7761. * http://opensource.org/licenses/BSD-3-Clause
  7762. */
  7763. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  7764. /**
  7765. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  7766. */
  7767. base64.encode = function (number) {
  7768. if (0 <= number && number < intToCharMap.length) {
  7769. return intToCharMap[number];
  7770. }
  7771. throw new TypeError("Must be between 0 and 63: " + number);
  7772. };
  7773. /**
  7774. * Decode a single base 64 character code digit to an integer. Returns -1 on
  7775. * failure.
  7776. */
  7777. base64.decode = function (charCode) {
  7778. var bigA = 65; // 'A'
  7779. var bigZ = 90; // 'Z'
  7780. var littleA = 97; // 'a'
  7781. var littleZ = 122; // 'z'
  7782. var zero = 48; // '0'
  7783. var nine = 57; // '9'
  7784. var plus = 43; // '+'
  7785. var slash = 47; // '/'
  7786. var littleOffset = 26;
  7787. var numberOffset = 52;
  7788. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  7789. if (bigA <= charCode && charCode <= bigZ) {
  7790. return (charCode - bigA);
  7791. }
  7792. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  7793. if (littleA <= charCode && charCode <= littleZ) {
  7794. return (charCode - littleA + littleOffset);
  7795. }
  7796. // 52 - 61: 0123456789
  7797. if (zero <= charCode && charCode <= nine) {
  7798. return (charCode - zero + numberOffset);
  7799. }
  7800. // 62: +
  7801. if (charCode == plus) {
  7802. return 62;
  7803. }
  7804. // 63: /
  7805. if (charCode == slash) {
  7806. return 63;
  7807. }
  7808. // Invalid base64 digit.
  7809. return -1;
  7810. };
  7811. return base64;
  7812. }
  7813. /* -*- Mode: js; js-indent-level: 2; -*- */
  7814. var hasRequiredBase64Vlq;
  7815. function requireBase64Vlq () {
  7816. if (hasRequiredBase64Vlq) return base64Vlq;
  7817. hasRequiredBase64Vlq = 1;
  7818. /*
  7819. * Copyright 2011 Mozilla Foundation and contributors
  7820. * Licensed under the New BSD license. See LICENSE or:
  7821. * http://opensource.org/licenses/BSD-3-Clause
  7822. *
  7823. * Based on the Base 64 VLQ implementation in Closure Compiler:
  7824. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  7825. *
  7826. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  7827. * Redistribution and use in source and binary forms, with or without
  7828. * modification, are permitted provided that the following conditions are
  7829. * met:
  7830. *
  7831. * * Redistributions of source code must retain the above copyright
  7832. * notice, this list of conditions and the following disclaimer.
  7833. * * Redistributions in binary form must reproduce the above
  7834. * copyright notice, this list of conditions and the following
  7835. * disclaimer in the documentation and/or other materials provided
  7836. * with the distribution.
  7837. * * Neither the name of Google Inc. nor the names of its
  7838. * contributors may be used to endorse or promote products derived
  7839. * from this software without specific prior written permission.
  7840. *
  7841. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7842. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7843. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7844. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7845. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7846. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7847. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7848. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7849. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7850. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7851. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7852. */
  7853. var base64 = /*@__PURE__*/ requireBase64();
  7854. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  7855. // length quantities we use in the source map spec, the first bit is the sign,
  7856. // the next four bits are the actual value, and the 6th bit is the
  7857. // continuation bit. The continuation bit tells us whether there are more
  7858. // digits in this value following this digit.
  7859. //
  7860. // Continuation
  7861. // | Sign
  7862. // | |
  7863. // V V
  7864. // 101011
  7865. var VLQ_BASE_SHIFT = 5;
  7866. // binary: 100000
  7867. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  7868. // binary: 011111
  7869. var VLQ_BASE_MASK = VLQ_BASE - 1;
  7870. // binary: 100000
  7871. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  7872. /**
  7873. * Converts from a two-complement value to a value where the sign bit is
  7874. * placed in the least significant bit. For example, as decimals:
  7875. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  7876. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  7877. */
  7878. function toVLQSigned(aValue) {
  7879. return aValue < 0
  7880. ? ((-aValue) << 1) + 1
  7881. : (aValue << 1) + 0;
  7882. }
  7883. /**
  7884. * Converts to a two-complement value from a value where the sign bit is
  7885. * placed in the least significant bit. For example, as decimals:
  7886. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  7887. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  7888. */
  7889. function fromVLQSigned(aValue) {
  7890. var isNegative = (aValue & 1) === 1;
  7891. var shifted = aValue >> 1;
  7892. return isNegative
  7893. ? -shifted
  7894. : shifted;
  7895. }
  7896. /**
  7897. * Returns the base 64 VLQ encoded value.
  7898. */
  7899. base64Vlq.encode = function base64VLQ_encode(aValue) {
  7900. var encoded = "";
  7901. var digit;
  7902. var vlq = toVLQSigned(aValue);
  7903. do {
  7904. digit = vlq & VLQ_BASE_MASK;
  7905. vlq >>>= VLQ_BASE_SHIFT;
  7906. if (vlq > 0) {
  7907. // There are still more digits in this value, so we must make sure the
  7908. // continuation bit is marked.
  7909. digit |= VLQ_CONTINUATION_BIT;
  7910. }
  7911. encoded += base64.encode(digit);
  7912. } while (vlq > 0);
  7913. return encoded;
  7914. };
  7915. /**
  7916. * Decodes the next base 64 VLQ value from the given string and returns the
  7917. * value and the rest of the string via the out parameter.
  7918. */
  7919. base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  7920. var strLen = aStr.length;
  7921. var result = 0;
  7922. var shift = 0;
  7923. var continuation, digit;
  7924. do {
  7925. if (aIndex >= strLen) {
  7926. throw new Error("Expected more digits in base 64 VLQ value.");
  7927. }
  7928. digit = base64.decode(aStr.charCodeAt(aIndex++));
  7929. if (digit === -1) {
  7930. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  7931. }
  7932. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  7933. digit &= VLQ_BASE_MASK;
  7934. result = result + (digit << shift);
  7935. shift += VLQ_BASE_SHIFT;
  7936. } while (continuation);
  7937. aOutParam.value = fromVLQSigned(result);
  7938. aOutParam.rest = aIndex;
  7939. };
  7940. return base64Vlq;
  7941. }
  7942. var util$1 = {};
  7943. /* -*- Mode: js; js-indent-level: 2; -*- */
  7944. var hasRequiredUtil$1;
  7945. function requireUtil$1 () {
  7946. if (hasRequiredUtil$1) return util$1;
  7947. hasRequiredUtil$1 = 1;
  7948. (function (exports$1) {
  7949. /*
  7950. * Copyright 2011 Mozilla Foundation and contributors
  7951. * Licensed under the New BSD license. See LICENSE or:
  7952. * http://opensource.org/licenses/BSD-3-Clause
  7953. */
  7954. /**
  7955. * This is a helper function for getting values from parameter/options
  7956. * objects.
  7957. *
  7958. * @param args The object we are extracting values from
  7959. * @param name The name of the property we are getting.
  7960. * @param defaultValue An optional value to return if the property is missing
  7961. * from the object. If this is not specified and the property is missing, an
  7962. * error will be thrown.
  7963. */
  7964. function getArg(aArgs, aName, aDefaultValue) {
  7965. if (aName in aArgs) {
  7966. return aArgs[aName];
  7967. } else if (arguments.length === 3) {
  7968. return aDefaultValue;
  7969. } else {
  7970. throw new Error('"' + aName + '" is a required argument.');
  7971. }
  7972. }
  7973. exports$1.getArg = getArg;
  7974. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  7975. var dataUrlRegexp = /^data:.+\,.+$/;
  7976. function urlParse(aUrl) {
  7977. var match = aUrl.match(urlRegexp);
  7978. if (!match) {
  7979. return null;
  7980. }
  7981. return {
  7982. scheme: match[1],
  7983. auth: match[2],
  7984. host: match[3],
  7985. port: match[4],
  7986. path: match[5]
  7987. };
  7988. }
  7989. exports$1.urlParse = urlParse;
  7990. function urlGenerate(aParsedUrl) {
  7991. var url = '';
  7992. if (aParsedUrl.scheme) {
  7993. url += aParsedUrl.scheme + ':';
  7994. }
  7995. url += '//';
  7996. if (aParsedUrl.auth) {
  7997. url += aParsedUrl.auth + '@';
  7998. }
  7999. if (aParsedUrl.host) {
  8000. url += aParsedUrl.host;
  8001. }
  8002. if (aParsedUrl.port) {
  8003. url += ":" + aParsedUrl.port;
  8004. }
  8005. if (aParsedUrl.path) {
  8006. url += aParsedUrl.path;
  8007. }
  8008. return url;
  8009. }
  8010. exports$1.urlGenerate = urlGenerate;
  8011. /**
  8012. * Normalizes a path, or the path portion of a URL:
  8013. *
  8014. * - Replaces consecutive slashes with one slash.
  8015. * - Removes unnecessary '.' parts.
  8016. * - Removes unnecessary '<dir>/..' parts.
  8017. *
  8018. * Based on code in the Node.js 'path' core module.
  8019. *
  8020. * @param aPath The path or url to normalize.
  8021. */
  8022. function normalize(aPath) {
  8023. var path = aPath;
  8024. var url = urlParse(aPath);
  8025. if (url) {
  8026. if (!url.path) {
  8027. return aPath;
  8028. }
  8029. path = url.path;
  8030. }
  8031. var isAbsolute = exports$1.isAbsolute(path);
  8032. var parts = path.split(/\/+/);
  8033. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  8034. part = parts[i];
  8035. if (part === '.') {
  8036. parts.splice(i, 1);
  8037. } else if (part === '..') {
  8038. up++;
  8039. } else if (up > 0) {
  8040. if (part === '') {
  8041. // The first part is blank if the path is absolute. Trying to go
  8042. // above the root is a no-op. Therefore we can remove all '..' parts
  8043. // directly after the root.
  8044. parts.splice(i + 1, up);
  8045. up = 0;
  8046. } else {
  8047. parts.splice(i, 2);
  8048. up--;
  8049. }
  8050. }
  8051. }
  8052. path = parts.join('/');
  8053. if (path === '') {
  8054. path = isAbsolute ? '/' : '.';
  8055. }
  8056. if (url) {
  8057. url.path = path;
  8058. return urlGenerate(url);
  8059. }
  8060. return path;
  8061. }
  8062. exports$1.normalize = normalize;
  8063. /**
  8064. * Joins two paths/URLs.
  8065. *
  8066. * @param aRoot The root path or URL.
  8067. * @param aPath The path or URL to be joined with the root.
  8068. *
  8069. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  8070. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  8071. * first.
  8072. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  8073. * is updated with the result and aRoot is returned. Otherwise the result
  8074. * is returned.
  8075. * - If aPath is absolute, the result is aPath.
  8076. * - Otherwise the two paths are joined with a slash.
  8077. * - Joining for example 'http://' and 'www.example.com' is also supported.
  8078. */
  8079. function join(aRoot, aPath) {
  8080. if (aRoot === "") {
  8081. aRoot = ".";
  8082. }
  8083. if (aPath === "") {
  8084. aPath = ".";
  8085. }
  8086. var aPathUrl = urlParse(aPath);
  8087. var aRootUrl = urlParse(aRoot);
  8088. if (aRootUrl) {
  8089. aRoot = aRootUrl.path || '/';
  8090. }
  8091. // `join(foo, '//www.example.org')`
  8092. if (aPathUrl && !aPathUrl.scheme) {
  8093. if (aRootUrl) {
  8094. aPathUrl.scheme = aRootUrl.scheme;
  8095. }
  8096. return urlGenerate(aPathUrl);
  8097. }
  8098. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  8099. return aPath;
  8100. }
  8101. // `join('http://', 'www.example.com')`
  8102. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  8103. aRootUrl.host = aPath;
  8104. return urlGenerate(aRootUrl);
  8105. }
  8106. var joined = aPath.charAt(0) === '/'
  8107. ? aPath
  8108. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  8109. if (aRootUrl) {
  8110. aRootUrl.path = joined;
  8111. return urlGenerate(aRootUrl);
  8112. }
  8113. return joined;
  8114. }
  8115. exports$1.join = join;
  8116. exports$1.isAbsolute = function (aPath) {
  8117. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  8118. };
  8119. /**
  8120. * Make a path relative to a URL or another path.
  8121. *
  8122. * @param aRoot The root path or URL.
  8123. * @param aPath The path or URL to be made relative to aRoot.
  8124. */
  8125. function relative(aRoot, aPath) {
  8126. if (aRoot === "") {
  8127. aRoot = ".";
  8128. }
  8129. aRoot = aRoot.replace(/\/$/, '');
  8130. // It is possible for the path to be above the root. In this case, simply
  8131. // checking whether the root is a prefix of the path won't work. Instead, we
  8132. // need to remove components from the root one by one, until either we find
  8133. // a prefix that fits, or we run out of components to remove.
  8134. var level = 0;
  8135. while (aPath.indexOf(aRoot + '/') !== 0) {
  8136. var index = aRoot.lastIndexOf("/");
  8137. if (index < 0) {
  8138. return aPath;
  8139. }
  8140. // If the only part of the root that is left is the scheme (i.e. http://,
  8141. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  8142. // have exhausted all components, so the path is not relative to the root.
  8143. aRoot = aRoot.slice(0, index);
  8144. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  8145. return aPath;
  8146. }
  8147. ++level;
  8148. }
  8149. // Make sure we add a "../" for each component we removed from the root.
  8150. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  8151. }
  8152. exports$1.relative = relative;
  8153. var supportsNullProto = (function () {
  8154. var obj = Object.create(null);
  8155. return !('__proto__' in obj);
  8156. }());
  8157. function identity (s) {
  8158. return s;
  8159. }
  8160. /**
  8161. * Because behavior goes wacky when you set `__proto__` on objects, we
  8162. * have to prefix all the strings in our set with an arbitrary character.
  8163. *
  8164. * See https://github.com/mozilla/source-map/pull/31 and
  8165. * https://github.com/mozilla/source-map/issues/30
  8166. *
  8167. * @param String aStr
  8168. */
  8169. function toSetString(aStr) {
  8170. if (isProtoString(aStr)) {
  8171. return '$' + aStr;
  8172. }
  8173. return aStr;
  8174. }
  8175. exports$1.toSetString = supportsNullProto ? identity : toSetString;
  8176. function fromSetString(aStr) {
  8177. if (isProtoString(aStr)) {
  8178. return aStr.slice(1);
  8179. }
  8180. return aStr;
  8181. }
  8182. exports$1.fromSetString = supportsNullProto ? identity : fromSetString;
  8183. function isProtoString(s) {
  8184. if (!s) {
  8185. return false;
  8186. }
  8187. var length = s.length;
  8188. if (length < 9 /* "__proto__".length */) {
  8189. return false;
  8190. }
  8191. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  8192. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  8193. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  8194. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  8195. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  8196. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  8197. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  8198. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  8199. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  8200. return false;
  8201. }
  8202. for (var i = length - 10; i >= 0; i--) {
  8203. if (s.charCodeAt(i) !== 36 /* '$' */) {
  8204. return false;
  8205. }
  8206. }
  8207. return true;
  8208. }
  8209. /**
  8210. * Comparator between two mappings where the original positions are compared.
  8211. *
  8212. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  8213. * mappings with the same original source/line/column, but different generated
  8214. * line and column the same. Useful when searching for a mapping with a
  8215. * stubbed out mapping.
  8216. */
  8217. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  8218. var cmp = strcmp(mappingA.source, mappingB.source);
  8219. if (cmp !== 0) {
  8220. return cmp;
  8221. }
  8222. cmp = mappingA.originalLine - mappingB.originalLine;
  8223. if (cmp !== 0) {
  8224. return cmp;
  8225. }
  8226. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8227. if (cmp !== 0 || onlyCompareOriginal) {
  8228. return cmp;
  8229. }
  8230. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8231. if (cmp !== 0) {
  8232. return cmp;
  8233. }
  8234. cmp = mappingA.generatedLine - mappingB.generatedLine;
  8235. if (cmp !== 0) {
  8236. return cmp;
  8237. }
  8238. return strcmp(mappingA.name, mappingB.name);
  8239. }
  8240. exports$1.compareByOriginalPositions = compareByOriginalPositions;
  8241. /**
  8242. * Comparator between two mappings with deflated source and name indices where
  8243. * the generated positions are compared.
  8244. *
  8245. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  8246. * mappings with the same generated line and column, but different
  8247. * source/name/original line and column the same. Useful when searching for a
  8248. * mapping with a stubbed out mapping.
  8249. */
  8250. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  8251. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  8252. if (cmp !== 0) {
  8253. return cmp;
  8254. }
  8255. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8256. if (cmp !== 0 || onlyCompareGenerated) {
  8257. return cmp;
  8258. }
  8259. cmp = strcmp(mappingA.source, mappingB.source);
  8260. if (cmp !== 0) {
  8261. return cmp;
  8262. }
  8263. cmp = mappingA.originalLine - mappingB.originalLine;
  8264. if (cmp !== 0) {
  8265. return cmp;
  8266. }
  8267. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8268. if (cmp !== 0) {
  8269. return cmp;
  8270. }
  8271. return strcmp(mappingA.name, mappingB.name);
  8272. }
  8273. exports$1.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  8274. function strcmp(aStr1, aStr2) {
  8275. if (aStr1 === aStr2) {
  8276. return 0;
  8277. }
  8278. if (aStr1 === null) {
  8279. return 1; // aStr2 !== null
  8280. }
  8281. if (aStr2 === null) {
  8282. return -1; // aStr1 !== null
  8283. }
  8284. if (aStr1 > aStr2) {
  8285. return 1;
  8286. }
  8287. return -1;
  8288. }
  8289. /**
  8290. * Comparator between two mappings with inflated source and name strings where
  8291. * the generated positions are compared.
  8292. */
  8293. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  8294. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  8295. if (cmp !== 0) {
  8296. return cmp;
  8297. }
  8298. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8299. if (cmp !== 0) {
  8300. return cmp;
  8301. }
  8302. cmp = strcmp(mappingA.source, mappingB.source);
  8303. if (cmp !== 0) {
  8304. return cmp;
  8305. }
  8306. cmp = mappingA.originalLine - mappingB.originalLine;
  8307. if (cmp !== 0) {
  8308. return cmp;
  8309. }
  8310. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8311. if (cmp !== 0) {
  8312. return cmp;
  8313. }
  8314. return strcmp(mappingA.name, mappingB.name);
  8315. }
  8316. exports$1.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  8317. /**
  8318. * Strip any JSON XSSI avoidance prefix from the string (as documented
  8319. * in the source maps specification), and then parse the string as
  8320. * JSON.
  8321. */
  8322. function parseSourceMapInput(str) {
  8323. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  8324. }
  8325. exports$1.parseSourceMapInput = parseSourceMapInput;
  8326. /**
  8327. * Compute the URL of a source given the the source root, the source's
  8328. * URL, and the source map's URL.
  8329. */
  8330. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  8331. sourceURL = sourceURL || '';
  8332. if (sourceRoot) {
  8333. // This follows what Chrome does.
  8334. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  8335. sourceRoot += '/';
  8336. }
  8337. // The spec says:
  8338. // Line 4: An optional source root, useful for relocating source
  8339. // files on a server or removing repeated values in the
  8340. // “sources” entry. This value is prepended to the individual
  8341. // entries in the “source” field.
  8342. sourceURL = sourceRoot + sourceURL;
  8343. }
  8344. // Historically, SourceMapConsumer did not take the sourceMapURL as
  8345. // a parameter. This mode is still somewhat supported, which is why
  8346. // this code block is conditional. However, it's preferable to pass
  8347. // the source map URL to SourceMapConsumer, so that this function
  8348. // can implement the source URL resolution algorithm as outlined in
  8349. // the spec. This block is basically the equivalent of:
  8350. // new URL(sourceURL, sourceMapURL).toString()
  8351. // ... except it avoids using URL, which wasn't available in the
  8352. // older releases of node still supported by this library.
  8353. //
  8354. // The spec says:
  8355. // If the sources are not absolute URLs after prepending of the
  8356. // “sourceRoot”, the sources are resolved relative to the
  8357. // SourceMap (like resolving script src in a html document).
  8358. if (sourceMapURL) {
  8359. var parsed = urlParse(sourceMapURL);
  8360. if (!parsed) {
  8361. throw new Error("sourceMapURL could not be parsed");
  8362. }
  8363. if (parsed.path) {
  8364. // Strip the last path component, but keep the "/".
  8365. var index = parsed.path.lastIndexOf('/');
  8366. if (index >= 0) {
  8367. parsed.path = parsed.path.substring(0, index + 1);
  8368. }
  8369. }
  8370. sourceURL = join(urlGenerate(parsed), sourceURL);
  8371. }
  8372. return normalize(sourceURL);
  8373. }
  8374. exports$1.computeSourceURL = computeSourceURL;
  8375. } (util$1));
  8376. return util$1;
  8377. }
  8378. var arraySet = {};
  8379. /* -*- Mode: js; js-indent-level: 2; -*- */
  8380. var hasRequiredArraySet;
  8381. function requireArraySet () {
  8382. if (hasRequiredArraySet) return arraySet;
  8383. hasRequiredArraySet = 1;
  8384. /*
  8385. * Copyright 2011 Mozilla Foundation and contributors
  8386. * Licensed under the New BSD license. See LICENSE or:
  8387. * http://opensource.org/licenses/BSD-3-Clause
  8388. */
  8389. var util = /*@__PURE__*/ requireUtil$1();
  8390. var has = Object.prototype.hasOwnProperty;
  8391. var hasNativeMap = typeof Map !== "undefined";
  8392. /**
  8393. * A data structure which is a combination of an array and a set. Adding a new
  8394. * member is O(1), testing for membership is O(1), and finding the index of an
  8395. * element is O(1). Removing elements from the set is not supported. Only
  8396. * strings are supported for membership.
  8397. */
  8398. function ArraySet() {
  8399. this._array = [];
  8400. this._set = hasNativeMap ? new Map() : Object.create(null);
  8401. }
  8402. /**
  8403. * Static method for creating ArraySet instances from an existing array.
  8404. */
  8405. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  8406. var set = new ArraySet();
  8407. for (var i = 0, len = aArray.length; i < len; i++) {
  8408. set.add(aArray[i], aAllowDuplicates);
  8409. }
  8410. return set;
  8411. };
  8412. /**
  8413. * Return how many unique items are in this ArraySet. If duplicates have been
  8414. * added, than those do not count towards the size.
  8415. *
  8416. * @returns Number
  8417. */
  8418. ArraySet.prototype.size = function ArraySet_size() {
  8419. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  8420. };
  8421. /**
  8422. * Add the given string to this set.
  8423. *
  8424. * @param String aStr
  8425. */
  8426. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  8427. var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
  8428. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  8429. var idx = this._array.length;
  8430. if (!isDuplicate || aAllowDuplicates) {
  8431. this._array.push(aStr);
  8432. }
  8433. if (!isDuplicate) {
  8434. if (hasNativeMap) {
  8435. this._set.set(aStr, idx);
  8436. } else {
  8437. this._set[sStr] = idx;
  8438. }
  8439. }
  8440. };
  8441. /**
  8442. * Is the given string a member of this set?
  8443. *
  8444. * @param String aStr
  8445. */
  8446. ArraySet.prototype.has = function ArraySet_has(aStr) {
  8447. if (hasNativeMap) {
  8448. return this._set.has(aStr);
  8449. } else {
  8450. var sStr = util.toSetString(aStr);
  8451. return has.call(this._set, sStr);
  8452. }
  8453. };
  8454. /**
  8455. * What is the index of the given string in the array?
  8456. *
  8457. * @param String aStr
  8458. */
  8459. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  8460. if (hasNativeMap) {
  8461. var idx = this._set.get(aStr);
  8462. if (idx >= 0) {
  8463. return idx;
  8464. }
  8465. } else {
  8466. var sStr = util.toSetString(aStr);
  8467. if (has.call(this._set, sStr)) {
  8468. return this._set[sStr];
  8469. }
  8470. }
  8471. throw new Error('"' + aStr + '" is not in the set.');
  8472. };
  8473. /**
  8474. * What is the element at the given index?
  8475. *
  8476. * @param Number aIdx
  8477. */
  8478. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  8479. if (aIdx >= 0 && aIdx < this._array.length) {
  8480. return this._array[aIdx];
  8481. }
  8482. throw new Error('No element indexed by ' + aIdx);
  8483. };
  8484. /**
  8485. * Returns the array representation of this set (which has the proper indices
  8486. * indicated by indexOf). Note that this is a copy of the internal array used
  8487. * for storing the members so that no one can mess with internal state.
  8488. */
  8489. ArraySet.prototype.toArray = function ArraySet_toArray() {
  8490. return this._array.slice();
  8491. };
  8492. arraySet.ArraySet = ArraySet;
  8493. return arraySet;
  8494. }
  8495. var mappingList = {};
  8496. /* -*- Mode: js; js-indent-level: 2; -*- */
  8497. var hasRequiredMappingList;
  8498. function requireMappingList () {
  8499. if (hasRequiredMappingList) return mappingList;
  8500. hasRequiredMappingList = 1;
  8501. /*
  8502. * Copyright 2014 Mozilla Foundation and contributors
  8503. * Licensed under the New BSD license. See LICENSE or:
  8504. * http://opensource.org/licenses/BSD-3-Clause
  8505. */
  8506. var util = /*@__PURE__*/ requireUtil$1();
  8507. /**
  8508. * Determine whether mappingB is after mappingA with respect to generated
  8509. * position.
  8510. */
  8511. function generatedPositionAfter(mappingA, mappingB) {
  8512. // Optimized for most common case
  8513. var lineA = mappingA.generatedLine;
  8514. var lineB = mappingB.generatedLine;
  8515. var columnA = mappingA.generatedColumn;
  8516. var columnB = mappingB.generatedColumn;
  8517. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  8518. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  8519. }
  8520. /**
  8521. * A data structure to provide a sorted view of accumulated mappings in a
  8522. * performance conscious manner. It trades a neglibable overhead in general
  8523. * case for a large speedup in case of mappings being added in order.
  8524. */
  8525. function MappingList() {
  8526. this._array = [];
  8527. this._sorted = true;
  8528. // Serves as infimum
  8529. this._last = {generatedLine: -1, generatedColumn: 0};
  8530. }
  8531. /**
  8532. * Iterate through internal items. This method takes the same arguments that
  8533. * `Array.prototype.forEach` takes.
  8534. *
  8535. * NOTE: The order of the mappings is NOT guaranteed.
  8536. */
  8537. MappingList.prototype.unsortedForEach =
  8538. function MappingList_forEach(aCallback, aThisArg) {
  8539. this._array.forEach(aCallback, aThisArg);
  8540. };
  8541. /**
  8542. * Add the given source mapping.
  8543. *
  8544. * @param Object aMapping
  8545. */
  8546. MappingList.prototype.add = function MappingList_add(aMapping) {
  8547. if (generatedPositionAfter(this._last, aMapping)) {
  8548. this._last = aMapping;
  8549. this._array.push(aMapping);
  8550. } else {
  8551. this._sorted = false;
  8552. this._array.push(aMapping);
  8553. }
  8554. };
  8555. /**
  8556. * Returns the flat, sorted array of mappings. The mappings are sorted by
  8557. * generated position.
  8558. *
  8559. * WARNING: This method returns internal data without copying, for
  8560. * performance. The return value must NOT be mutated, and should be treated as
  8561. * an immutable borrow. If you want to take ownership, you must make your own
  8562. * copy.
  8563. */
  8564. MappingList.prototype.toArray = function MappingList_toArray() {
  8565. if (!this._sorted) {
  8566. this._array.sort(util.compareByGeneratedPositionsInflated);
  8567. this._sorted = true;
  8568. }
  8569. return this._array;
  8570. };
  8571. mappingList.MappingList = MappingList;
  8572. return mappingList;
  8573. }
  8574. /* -*- Mode: js; js-indent-level: 2; -*- */
  8575. var hasRequiredSourceMapGenerator;
  8576. function requireSourceMapGenerator () {
  8577. if (hasRequiredSourceMapGenerator) return sourceMapGenerator;
  8578. hasRequiredSourceMapGenerator = 1;
  8579. /*
  8580. * Copyright 2011 Mozilla Foundation and contributors
  8581. * Licensed under the New BSD license. See LICENSE or:
  8582. * http://opensource.org/licenses/BSD-3-Clause
  8583. */
  8584. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  8585. var util = /*@__PURE__*/ requireUtil$1();
  8586. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  8587. var MappingList = /*@__PURE__*/ requireMappingList().MappingList;
  8588. /**
  8589. * An instance of the SourceMapGenerator represents a source map which is
  8590. * being built incrementally. You may pass an object with the following
  8591. * properties:
  8592. *
  8593. * - file: The filename of the generated source.
  8594. * - sourceRoot: A root for all relative URLs in this source map.
  8595. */
  8596. function SourceMapGenerator(aArgs) {
  8597. if (!aArgs) {
  8598. aArgs = {};
  8599. }
  8600. this._file = util.getArg(aArgs, 'file', null);
  8601. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  8602. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  8603. this._sources = new ArraySet();
  8604. this._names = new ArraySet();
  8605. this._mappings = new MappingList();
  8606. this._sourcesContents = null;
  8607. }
  8608. SourceMapGenerator.prototype._version = 3;
  8609. /**
  8610. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  8611. *
  8612. * @param aSourceMapConsumer The SourceMap.
  8613. */
  8614. SourceMapGenerator.fromSourceMap =
  8615. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  8616. var sourceRoot = aSourceMapConsumer.sourceRoot;
  8617. var generator = new SourceMapGenerator({
  8618. file: aSourceMapConsumer.file,
  8619. sourceRoot: sourceRoot
  8620. });
  8621. aSourceMapConsumer.eachMapping(function (mapping) {
  8622. var newMapping = {
  8623. generated: {
  8624. line: mapping.generatedLine,
  8625. column: mapping.generatedColumn
  8626. }
  8627. };
  8628. if (mapping.source != null) {
  8629. newMapping.source = mapping.source;
  8630. if (sourceRoot != null) {
  8631. newMapping.source = util.relative(sourceRoot, newMapping.source);
  8632. }
  8633. newMapping.original = {
  8634. line: mapping.originalLine,
  8635. column: mapping.originalColumn
  8636. };
  8637. if (mapping.name != null) {
  8638. newMapping.name = mapping.name;
  8639. }
  8640. }
  8641. generator.addMapping(newMapping);
  8642. });
  8643. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8644. var sourceRelative = sourceFile;
  8645. if (sourceRoot !== null) {
  8646. sourceRelative = util.relative(sourceRoot, sourceFile);
  8647. }
  8648. if (!generator._sources.has(sourceRelative)) {
  8649. generator._sources.add(sourceRelative);
  8650. }
  8651. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8652. if (content != null) {
  8653. generator.setSourceContent(sourceFile, content);
  8654. }
  8655. });
  8656. return generator;
  8657. };
  8658. /**
  8659. * Add a single mapping from original source line and column to the generated
  8660. * source's line and column for this source map being created. The mapping
  8661. * object should have the following properties:
  8662. *
  8663. * - generated: An object with the generated line and column positions.
  8664. * - original: An object with the original line and column positions.
  8665. * - source: The original source file (relative to the sourceRoot).
  8666. * - name: An optional original token name for this mapping.
  8667. */
  8668. SourceMapGenerator.prototype.addMapping =
  8669. function SourceMapGenerator_addMapping(aArgs) {
  8670. var generated = util.getArg(aArgs, 'generated');
  8671. var original = util.getArg(aArgs, 'original', null);
  8672. var source = util.getArg(aArgs, 'source', null);
  8673. var name = util.getArg(aArgs, 'name', null);
  8674. if (!this._skipValidation) {
  8675. this._validateMapping(generated, original, source, name);
  8676. }
  8677. if (source != null) {
  8678. source = String(source);
  8679. if (!this._sources.has(source)) {
  8680. this._sources.add(source);
  8681. }
  8682. }
  8683. if (name != null) {
  8684. name = String(name);
  8685. if (!this._names.has(name)) {
  8686. this._names.add(name);
  8687. }
  8688. }
  8689. this._mappings.add({
  8690. generatedLine: generated.line,
  8691. generatedColumn: generated.column,
  8692. originalLine: original != null && original.line,
  8693. originalColumn: original != null && original.column,
  8694. source: source,
  8695. name: name
  8696. });
  8697. };
  8698. /**
  8699. * Set the source content for a source file.
  8700. */
  8701. SourceMapGenerator.prototype.setSourceContent =
  8702. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  8703. var source = aSourceFile;
  8704. if (this._sourceRoot != null) {
  8705. source = util.relative(this._sourceRoot, source);
  8706. }
  8707. if (aSourceContent != null) {
  8708. // Add the source content to the _sourcesContents map.
  8709. // Create a new _sourcesContents map if the property is null.
  8710. if (!this._sourcesContents) {
  8711. this._sourcesContents = Object.create(null);
  8712. }
  8713. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  8714. } else if (this._sourcesContents) {
  8715. // Remove the source file from the _sourcesContents map.
  8716. // If the _sourcesContents map is empty, set the property to null.
  8717. delete this._sourcesContents[util.toSetString(source)];
  8718. if (Object.keys(this._sourcesContents).length === 0) {
  8719. this._sourcesContents = null;
  8720. }
  8721. }
  8722. };
  8723. /**
  8724. * Applies the mappings of a sub-source-map for a specific source file to the
  8725. * source map being generated. Each mapping to the supplied source file is
  8726. * rewritten using the supplied source map. Note: The resolution for the
  8727. * resulting mappings is the minimium of this map and the supplied map.
  8728. *
  8729. * @param aSourceMapConsumer The source map to be applied.
  8730. * @param aSourceFile Optional. The filename of the source file.
  8731. * If omitted, SourceMapConsumer's file property will be used.
  8732. * @param aSourceMapPath Optional. The dirname of the path to the source map
  8733. * to be applied. If relative, it is relative to the SourceMapConsumer.
  8734. * This parameter is needed when the two source maps aren't in the same
  8735. * directory, and the source map to be applied contains relative source
  8736. * paths. If so, those relative source paths need to be rewritten
  8737. * relative to the SourceMapGenerator.
  8738. */
  8739. SourceMapGenerator.prototype.applySourceMap =
  8740. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  8741. var sourceFile = aSourceFile;
  8742. // If aSourceFile is omitted, we will use the file property of the SourceMap
  8743. if (aSourceFile == null) {
  8744. if (aSourceMapConsumer.file == null) {
  8745. throw new Error(
  8746. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  8747. 'or the source map\'s "file" property. Both were omitted.'
  8748. );
  8749. }
  8750. sourceFile = aSourceMapConsumer.file;
  8751. }
  8752. var sourceRoot = this._sourceRoot;
  8753. // Make "sourceFile" relative if an absolute Url is passed.
  8754. if (sourceRoot != null) {
  8755. sourceFile = util.relative(sourceRoot, sourceFile);
  8756. }
  8757. // Applying the SourceMap can add and remove items from the sources and
  8758. // the names array.
  8759. var newSources = new ArraySet();
  8760. var newNames = new ArraySet();
  8761. // Find mappings for the "sourceFile"
  8762. this._mappings.unsortedForEach(function (mapping) {
  8763. if (mapping.source === sourceFile && mapping.originalLine != null) {
  8764. // Check if it can be mapped by the source map, then update the mapping.
  8765. var original = aSourceMapConsumer.originalPositionFor({
  8766. line: mapping.originalLine,
  8767. column: mapping.originalColumn
  8768. });
  8769. if (original.source != null) {
  8770. // Copy mapping
  8771. mapping.source = original.source;
  8772. if (aSourceMapPath != null) {
  8773. mapping.source = util.join(aSourceMapPath, mapping.source);
  8774. }
  8775. if (sourceRoot != null) {
  8776. mapping.source = util.relative(sourceRoot, mapping.source);
  8777. }
  8778. mapping.originalLine = original.line;
  8779. mapping.originalColumn = original.column;
  8780. if (original.name != null) {
  8781. mapping.name = original.name;
  8782. }
  8783. }
  8784. }
  8785. var source = mapping.source;
  8786. if (source != null && !newSources.has(source)) {
  8787. newSources.add(source);
  8788. }
  8789. var name = mapping.name;
  8790. if (name != null && !newNames.has(name)) {
  8791. newNames.add(name);
  8792. }
  8793. }, this);
  8794. this._sources = newSources;
  8795. this._names = newNames;
  8796. // Copy sourcesContents of applied map.
  8797. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8798. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8799. if (content != null) {
  8800. if (aSourceMapPath != null) {
  8801. sourceFile = util.join(aSourceMapPath, sourceFile);
  8802. }
  8803. if (sourceRoot != null) {
  8804. sourceFile = util.relative(sourceRoot, sourceFile);
  8805. }
  8806. this.setSourceContent(sourceFile, content);
  8807. }
  8808. }, this);
  8809. };
  8810. /**
  8811. * A mapping can have one of the three levels of data:
  8812. *
  8813. * 1. Just the generated position.
  8814. * 2. The Generated position, original position, and original source.
  8815. * 3. Generated and original position, original source, as well as a name
  8816. * token.
  8817. *
  8818. * To maintain consistency, we validate that any new mapping being added falls
  8819. * in to one of these categories.
  8820. */
  8821. SourceMapGenerator.prototype._validateMapping =
  8822. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  8823. aName) {
  8824. // When aOriginal is truthy but has empty values for .line and .column,
  8825. // it is most likely a programmer error. In this case we throw a very
  8826. // specific error message to try to guide them the right way.
  8827. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  8828. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  8829. throw new Error(
  8830. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  8831. 'the original mapping entirely and only map the generated position. If so, pass ' +
  8832. 'null for the original mapping instead of an object with empty or null values.'
  8833. );
  8834. }
  8835. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8836. && aGenerated.line > 0 && aGenerated.column >= 0
  8837. && !aOriginal && !aSource && !aName) {
  8838. // Case 1.
  8839. return;
  8840. }
  8841. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8842. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  8843. && aGenerated.line > 0 && aGenerated.column >= 0
  8844. && aOriginal.line > 0 && aOriginal.column >= 0
  8845. && aSource) {
  8846. // Cases 2 and 3.
  8847. return;
  8848. }
  8849. else {
  8850. throw new Error('Invalid mapping: ' + JSON.stringify({
  8851. generated: aGenerated,
  8852. source: aSource,
  8853. original: aOriginal,
  8854. name: aName
  8855. }));
  8856. }
  8857. };
  8858. /**
  8859. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  8860. * specified by the source map format.
  8861. */
  8862. SourceMapGenerator.prototype._serializeMappings =
  8863. function SourceMapGenerator_serializeMappings() {
  8864. var previousGeneratedColumn = 0;
  8865. var previousGeneratedLine = 1;
  8866. var previousOriginalColumn = 0;
  8867. var previousOriginalLine = 0;
  8868. var previousName = 0;
  8869. var previousSource = 0;
  8870. var result = '';
  8871. var next;
  8872. var mapping;
  8873. var nameIdx;
  8874. var sourceIdx;
  8875. var mappings = this._mappings.toArray();
  8876. for (var i = 0, len = mappings.length; i < len; i++) {
  8877. mapping = mappings[i];
  8878. next = '';
  8879. if (mapping.generatedLine !== previousGeneratedLine) {
  8880. previousGeneratedColumn = 0;
  8881. while (mapping.generatedLine !== previousGeneratedLine) {
  8882. next += ';';
  8883. previousGeneratedLine++;
  8884. }
  8885. }
  8886. else {
  8887. if (i > 0) {
  8888. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  8889. continue;
  8890. }
  8891. next += ',';
  8892. }
  8893. }
  8894. next += base64VLQ.encode(mapping.generatedColumn
  8895. - previousGeneratedColumn);
  8896. previousGeneratedColumn = mapping.generatedColumn;
  8897. if (mapping.source != null) {
  8898. sourceIdx = this._sources.indexOf(mapping.source);
  8899. next += base64VLQ.encode(sourceIdx - previousSource);
  8900. previousSource = sourceIdx;
  8901. // lines are stored 0-based in SourceMap spec version 3
  8902. next += base64VLQ.encode(mapping.originalLine - 1
  8903. - previousOriginalLine);
  8904. previousOriginalLine = mapping.originalLine - 1;
  8905. next += base64VLQ.encode(mapping.originalColumn
  8906. - previousOriginalColumn);
  8907. previousOriginalColumn = mapping.originalColumn;
  8908. if (mapping.name != null) {
  8909. nameIdx = this._names.indexOf(mapping.name);
  8910. next += base64VLQ.encode(nameIdx - previousName);
  8911. previousName = nameIdx;
  8912. }
  8913. }
  8914. result += next;
  8915. }
  8916. return result;
  8917. };
  8918. SourceMapGenerator.prototype._generateSourcesContent =
  8919. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  8920. return aSources.map(function (source) {
  8921. if (!this._sourcesContents) {
  8922. return null;
  8923. }
  8924. if (aSourceRoot != null) {
  8925. source = util.relative(aSourceRoot, source);
  8926. }
  8927. var key = util.toSetString(source);
  8928. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  8929. ? this._sourcesContents[key]
  8930. : null;
  8931. }, this);
  8932. };
  8933. /**
  8934. * Externalize the source map.
  8935. */
  8936. SourceMapGenerator.prototype.toJSON =
  8937. function SourceMapGenerator_toJSON() {
  8938. var map = {
  8939. version: this._version,
  8940. sources: this._sources.toArray(),
  8941. names: this._names.toArray(),
  8942. mappings: this._serializeMappings()
  8943. };
  8944. if (this._file != null) {
  8945. map.file = this._file;
  8946. }
  8947. if (this._sourceRoot != null) {
  8948. map.sourceRoot = this._sourceRoot;
  8949. }
  8950. if (this._sourcesContents) {
  8951. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  8952. }
  8953. return map;
  8954. };
  8955. /**
  8956. * Render the source map being generated to a string.
  8957. */
  8958. SourceMapGenerator.prototype.toString =
  8959. function SourceMapGenerator_toString() {
  8960. return JSON.stringify(this.toJSON());
  8961. };
  8962. sourceMapGenerator.SourceMapGenerator = SourceMapGenerator;
  8963. return sourceMapGenerator;
  8964. }
  8965. var sourceMapConsumer = {};
  8966. var binarySearch = {};
  8967. /* -*- Mode: js; js-indent-level: 2; -*- */
  8968. var hasRequiredBinarySearch;
  8969. function requireBinarySearch () {
  8970. if (hasRequiredBinarySearch) return binarySearch;
  8971. hasRequiredBinarySearch = 1;
  8972. (function (exports$1) {
  8973. /*
  8974. * Copyright 2011 Mozilla Foundation and contributors
  8975. * Licensed under the New BSD license. See LICENSE or:
  8976. * http://opensource.org/licenses/BSD-3-Clause
  8977. */
  8978. exports$1.GREATEST_LOWER_BOUND = 1;
  8979. exports$1.LEAST_UPPER_BOUND = 2;
  8980. /**
  8981. * Recursive implementation of binary search.
  8982. *
  8983. * @param aLow Indices here and lower do not contain the needle.
  8984. * @param aHigh Indices here and higher do not contain the needle.
  8985. * @param aNeedle The element being searched for.
  8986. * @param aHaystack The non-empty array being searched.
  8987. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  8988. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  8989. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  8990. * closest element that is smaller than or greater than the one we are
  8991. * searching for, respectively, if the exact element cannot be found.
  8992. */
  8993. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  8994. // This function terminates when one of the following is true:
  8995. //
  8996. // 1. We find the exact element we are looking for.
  8997. //
  8998. // 2. We did not find the exact element, but we can return the index of
  8999. // the next-closest element.
  9000. //
  9001. // 3. We did not find the exact element, and there is no next-closest
  9002. // element than the one we are searching for, so we return -1.
  9003. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  9004. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  9005. if (cmp === 0) {
  9006. // Found the element we are looking for.
  9007. return mid;
  9008. }
  9009. else if (cmp > 0) {
  9010. // Our needle is greater than aHaystack[mid].
  9011. if (aHigh - mid > 1) {
  9012. // The element is in the upper half.
  9013. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  9014. }
  9015. // The exact needle element was not found in this haystack. Determine if
  9016. // we are in termination case (3) or (2) and return the appropriate thing.
  9017. if (aBias == exports$1.LEAST_UPPER_BOUND) {
  9018. return aHigh < aHaystack.length ? aHigh : -1;
  9019. } else {
  9020. return mid;
  9021. }
  9022. }
  9023. else {
  9024. // Our needle is less than aHaystack[mid].
  9025. if (mid - aLow > 1) {
  9026. // The element is in the lower half.
  9027. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  9028. }
  9029. // we are in termination case (3) or (2) and return the appropriate thing.
  9030. if (aBias == exports$1.LEAST_UPPER_BOUND) {
  9031. return mid;
  9032. } else {
  9033. return aLow < 0 ? -1 : aLow;
  9034. }
  9035. }
  9036. }
  9037. /**
  9038. * This is an implementation of binary search which will always try and return
  9039. * the index of the closest element if there is no exact hit. This is because
  9040. * mappings between original and generated line/col pairs are single points,
  9041. * and there is an implicit region between each of them, so a miss just means
  9042. * that you aren't on the very start of a region.
  9043. *
  9044. * @param aNeedle The element you are looking for.
  9045. * @param aHaystack The array that is being searched.
  9046. * @param aCompare A function which takes the needle and an element in the
  9047. * array and returns -1, 0, or 1 depending on whether the needle is less
  9048. * than, equal to, or greater than the element, respectively.
  9049. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  9050. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  9051. * closest element that is smaller than or greater than the one we are
  9052. * searching for, respectively, if the exact element cannot be found.
  9053. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  9054. */
  9055. exports$1.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  9056. if (aHaystack.length === 0) {
  9057. return -1;
  9058. }
  9059. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  9060. aCompare, aBias || exports$1.GREATEST_LOWER_BOUND);
  9061. if (index < 0) {
  9062. return -1;
  9063. }
  9064. // We have found either the exact element, or the next-closest element than
  9065. // the one we are searching for. However, there may be more than one such
  9066. // element. Make sure we always return the smallest of these.
  9067. while (index - 1 >= 0) {
  9068. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  9069. break;
  9070. }
  9071. --index;
  9072. }
  9073. return index;
  9074. };
  9075. } (binarySearch));
  9076. return binarySearch;
  9077. }
  9078. var quickSort = {};
  9079. /* -*- Mode: js; js-indent-level: 2; -*- */
  9080. var hasRequiredQuickSort;
  9081. function requireQuickSort () {
  9082. if (hasRequiredQuickSort) return quickSort;
  9083. hasRequiredQuickSort = 1;
  9084. /*
  9085. * Copyright 2011 Mozilla Foundation and contributors
  9086. * Licensed under the New BSD license. See LICENSE or:
  9087. * http://opensource.org/licenses/BSD-3-Clause
  9088. */
  9089. // It turns out that some (most?) JavaScript engines don't self-host
  9090. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  9091. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  9092. // custom comparator function, calling back and forth between the VM's C++ and
  9093. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  9094. // worse generated code for the comparator function than would be optimal. In
  9095. // fact, when sorting with a comparator, these costs outweigh the benefits of
  9096. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  9097. // a ~3500ms mean speed-up in `bench/bench.html`.
  9098. /**
  9099. * Swap the elements indexed by `x` and `y` in the array `ary`.
  9100. *
  9101. * @param {Array} ary
  9102. * The array.
  9103. * @param {Number} x
  9104. * The index of the first item.
  9105. * @param {Number} y
  9106. * The index of the second item.
  9107. */
  9108. function swap(ary, x, y) {
  9109. var temp = ary[x];
  9110. ary[x] = ary[y];
  9111. ary[y] = temp;
  9112. }
  9113. /**
  9114. * Returns a random integer within the range `low .. high` inclusive.
  9115. *
  9116. * @param {Number} low
  9117. * The lower bound on the range.
  9118. * @param {Number} high
  9119. * The upper bound on the range.
  9120. */
  9121. function randomIntInRange(low, high) {
  9122. return Math.round(low + (Math.random() * (high - low)));
  9123. }
  9124. /**
  9125. * The Quick Sort algorithm.
  9126. *
  9127. * @param {Array} ary
  9128. * An array to sort.
  9129. * @param {function} comparator
  9130. * Function to use to compare two items.
  9131. * @param {Number} p
  9132. * Start index of the array
  9133. * @param {Number} r
  9134. * End index of the array
  9135. */
  9136. function doQuickSort(ary, comparator, p, r) {
  9137. // If our lower bound is less than our upper bound, we (1) partition the
  9138. // array into two pieces and (2) recurse on each half. If it is not, this is
  9139. // the empty array and our base case.
  9140. if (p < r) {
  9141. // (1) Partitioning.
  9142. //
  9143. // The partitioning chooses a pivot between `p` and `r` and moves all
  9144. // elements that are less than or equal to the pivot to the before it, and
  9145. // all the elements that are greater than it after it. The effect is that
  9146. // once partition is done, the pivot is in the exact place it will be when
  9147. // the array is put in sorted order, and it will not need to be moved
  9148. // again. This runs in O(n) time.
  9149. // Always choose a random pivot so that an input array which is reverse
  9150. // sorted does not cause O(n^2) running time.
  9151. var pivotIndex = randomIntInRange(p, r);
  9152. var i = p - 1;
  9153. swap(ary, pivotIndex, r);
  9154. var pivot = ary[r];
  9155. // Immediately after `j` is incremented in this loop, the following hold
  9156. // true:
  9157. //
  9158. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  9159. //
  9160. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  9161. for (var j = p; j < r; j++) {
  9162. if (comparator(ary[j], pivot) <= 0) {
  9163. i += 1;
  9164. swap(ary, i, j);
  9165. }
  9166. }
  9167. swap(ary, i + 1, j);
  9168. var q = i + 1;
  9169. // (2) Recurse on each half.
  9170. doQuickSort(ary, comparator, p, q - 1);
  9171. doQuickSort(ary, comparator, q + 1, r);
  9172. }
  9173. }
  9174. /**
  9175. * Sort the given array in-place with the given comparator function.
  9176. *
  9177. * @param {Array} ary
  9178. * An array to sort.
  9179. * @param {function} comparator
  9180. * Function to use to compare two items.
  9181. */
  9182. quickSort.quickSort = function (ary, comparator) {
  9183. doQuickSort(ary, comparator, 0, ary.length - 1);
  9184. };
  9185. return quickSort;
  9186. }
  9187. /* -*- Mode: js; js-indent-level: 2; -*- */
  9188. var hasRequiredSourceMapConsumer;
  9189. function requireSourceMapConsumer () {
  9190. if (hasRequiredSourceMapConsumer) return sourceMapConsumer;
  9191. hasRequiredSourceMapConsumer = 1;
  9192. /*
  9193. * Copyright 2011 Mozilla Foundation and contributors
  9194. * Licensed under the New BSD license. See LICENSE or:
  9195. * http://opensource.org/licenses/BSD-3-Clause
  9196. */
  9197. var util = /*@__PURE__*/ requireUtil$1();
  9198. var binarySearch = /*@__PURE__*/ requireBinarySearch();
  9199. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  9200. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  9201. var quickSort = /*@__PURE__*/ requireQuickSort().quickSort;
  9202. function SourceMapConsumer(aSourceMap, aSourceMapURL) {
  9203. var sourceMap = aSourceMap;
  9204. if (typeof aSourceMap === 'string') {
  9205. sourceMap = util.parseSourceMapInput(aSourceMap);
  9206. }
  9207. return sourceMap.sections != null
  9208. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  9209. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  9210. }
  9211. SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  9212. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  9213. };
  9214. /**
  9215. * The version of the source mapping spec that we are consuming.
  9216. */
  9217. SourceMapConsumer.prototype._version = 3;
  9218. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  9219. // parsed mapping coordinates from the source map's "mappings" attribute. They
  9220. // are lazily instantiated, accessed via the `_generatedMappings` and
  9221. // `_originalMappings` getters respectively, and we only parse the mappings
  9222. // and create these arrays once queried for a source location. We jump through
  9223. // these hoops because there can be many thousands of mappings, and parsing
  9224. // them is expensive, so we only want to do it if we must.
  9225. //
  9226. // Each object in the arrays is of the form:
  9227. //
  9228. // {
  9229. // generatedLine: The line number in the generated code,
  9230. // generatedColumn: The column number in the generated code,
  9231. // source: The path to the original source file that generated this
  9232. // chunk of code,
  9233. // originalLine: The line number in the original source that
  9234. // corresponds to this chunk of generated code,
  9235. // originalColumn: The column number in the original source that
  9236. // corresponds to this chunk of generated code,
  9237. // name: The name of the original symbol which generated this chunk of
  9238. // code.
  9239. // }
  9240. //
  9241. // All properties except for `generatedLine` and `generatedColumn` can be
  9242. // `null`.
  9243. //
  9244. // `_generatedMappings` is ordered by the generated positions.
  9245. //
  9246. // `_originalMappings` is ordered by the original positions.
  9247. SourceMapConsumer.prototype.__generatedMappings = null;
  9248. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  9249. configurable: true,
  9250. enumerable: true,
  9251. get: function () {
  9252. if (!this.__generatedMappings) {
  9253. this._parseMappings(this._mappings, this.sourceRoot);
  9254. }
  9255. return this.__generatedMappings;
  9256. }
  9257. });
  9258. SourceMapConsumer.prototype.__originalMappings = null;
  9259. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  9260. configurable: true,
  9261. enumerable: true,
  9262. get: function () {
  9263. if (!this.__originalMappings) {
  9264. this._parseMappings(this._mappings, this.sourceRoot);
  9265. }
  9266. return this.__originalMappings;
  9267. }
  9268. });
  9269. SourceMapConsumer.prototype._charIsMappingSeparator =
  9270. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  9271. var c = aStr.charAt(index);
  9272. return c === ";" || c === ",";
  9273. };
  9274. /**
  9275. * Parse the mappings in a string in to a data structure which we can easily
  9276. * query (the ordered arrays in the `this.__generatedMappings` and
  9277. * `this.__originalMappings` properties).
  9278. */
  9279. SourceMapConsumer.prototype._parseMappings =
  9280. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9281. throw new Error("Subclasses must implement _parseMappings");
  9282. };
  9283. SourceMapConsumer.GENERATED_ORDER = 1;
  9284. SourceMapConsumer.ORIGINAL_ORDER = 2;
  9285. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  9286. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  9287. /**
  9288. * Iterate over each mapping between an original source/line/column and a
  9289. * generated line/column in this source map.
  9290. *
  9291. * @param Function aCallback
  9292. * The function that is called with each mapping.
  9293. * @param Object aContext
  9294. * Optional. If specified, this object will be the value of `this` every
  9295. * time that `aCallback` is called.
  9296. * @param aOrder
  9297. * Either `SourceMapConsumer.GENERATED_ORDER` or
  9298. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  9299. * iterate over the mappings sorted by the generated file's line/column
  9300. * order or the original's source/line/column order, respectively. Defaults to
  9301. * `SourceMapConsumer.GENERATED_ORDER`.
  9302. */
  9303. SourceMapConsumer.prototype.eachMapping =
  9304. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  9305. var context = aContext || null;
  9306. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  9307. var mappings;
  9308. switch (order) {
  9309. case SourceMapConsumer.GENERATED_ORDER:
  9310. mappings = this._generatedMappings;
  9311. break;
  9312. case SourceMapConsumer.ORIGINAL_ORDER:
  9313. mappings = this._originalMappings;
  9314. break;
  9315. default:
  9316. throw new Error("Unknown order of iteration.");
  9317. }
  9318. var sourceRoot = this.sourceRoot;
  9319. mappings.map(function (mapping) {
  9320. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  9321. source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  9322. return {
  9323. source: source,
  9324. generatedLine: mapping.generatedLine,
  9325. generatedColumn: mapping.generatedColumn,
  9326. originalLine: mapping.originalLine,
  9327. originalColumn: mapping.originalColumn,
  9328. name: mapping.name === null ? null : this._names.at(mapping.name)
  9329. };
  9330. }, this).forEach(aCallback, context);
  9331. };
  9332. /**
  9333. * Returns all generated line and column information for the original source,
  9334. * line, and column provided. If no column is provided, returns all mappings
  9335. * corresponding to a either the line we are searching for or the next
  9336. * closest line that has any mappings. Otherwise, returns all mappings
  9337. * corresponding to the given line and either the column we are searching for
  9338. * or the next closest column that has any offsets.
  9339. *
  9340. * The only argument is an object with the following properties:
  9341. *
  9342. * - source: The filename of the original source.
  9343. * - line: The line number in the original source. The line number is 1-based.
  9344. * - column: Optional. the column number in the original source.
  9345. * The column number is 0-based.
  9346. *
  9347. * and an array of objects is returned, each with the following properties:
  9348. *
  9349. * - line: The line number in the generated source, or null. The
  9350. * line number is 1-based.
  9351. * - column: The column number in the generated source, or null.
  9352. * The column number is 0-based.
  9353. */
  9354. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  9355. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  9356. var line = util.getArg(aArgs, 'line');
  9357. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  9358. // returns the index of the closest mapping less than the needle. By
  9359. // setting needle.originalColumn to 0, we thus find the last mapping for
  9360. // the given line, provided such a mapping exists.
  9361. var needle = {
  9362. source: util.getArg(aArgs, 'source'),
  9363. originalLine: line,
  9364. originalColumn: util.getArg(aArgs, 'column', 0)
  9365. };
  9366. needle.source = this._findSourceIndex(needle.source);
  9367. if (needle.source < 0) {
  9368. return [];
  9369. }
  9370. var mappings = [];
  9371. var index = this._findMapping(needle,
  9372. this._originalMappings,
  9373. "originalLine",
  9374. "originalColumn",
  9375. util.compareByOriginalPositions,
  9376. binarySearch.LEAST_UPPER_BOUND);
  9377. if (index >= 0) {
  9378. var mapping = this._originalMappings[index];
  9379. if (aArgs.column === undefined) {
  9380. var originalLine = mapping.originalLine;
  9381. // Iterate until either we run out of mappings, or we run into
  9382. // a mapping for a different line than the one we found. Since
  9383. // mappings are sorted, this is guaranteed to find all mappings for
  9384. // the line we found.
  9385. while (mapping && mapping.originalLine === originalLine) {
  9386. mappings.push({
  9387. line: util.getArg(mapping, 'generatedLine', null),
  9388. column: util.getArg(mapping, 'generatedColumn', null),
  9389. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9390. });
  9391. mapping = this._originalMappings[++index];
  9392. }
  9393. } else {
  9394. var originalColumn = mapping.originalColumn;
  9395. // Iterate until either we run out of mappings, or we run into
  9396. // a mapping for a different line than the one we were searching for.
  9397. // Since mappings are sorted, this is guaranteed to find all mappings for
  9398. // the line we are searching for.
  9399. while (mapping &&
  9400. mapping.originalLine === line &&
  9401. mapping.originalColumn == originalColumn) {
  9402. mappings.push({
  9403. line: util.getArg(mapping, 'generatedLine', null),
  9404. column: util.getArg(mapping, 'generatedColumn', null),
  9405. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9406. });
  9407. mapping = this._originalMappings[++index];
  9408. }
  9409. }
  9410. }
  9411. return mappings;
  9412. };
  9413. sourceMapConsumer.SourceMapConsumer = SourceMapConsumer;
  9414. /**
  9415. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  9416. * query for information about the original file positions by giving it a file
  9417. * position in the generated source.
  9418. *
  9419. * The first parameter is the raw source map (either as a JSON string, or
  9420. * already parsed to an object). According to the spec, source maps have the
  9421. * following attributes:
  9422. *
  9423. * - version: Which version of the source map spec this map is following.
  9424. * - sources: An array of URLs to the original source files.
  9425. * - names: An array of identifiers which can be referrenced by individual mappings.
  9426. * - sourceRoot: Optional. The URL root from which all sources are relative.
  9427. * - sourcesContent: Optional. An array of contents of the original source files.
  9428. * - mappings: A string of base64 VLQs which contain the actual mappings.
  9429. * - file: Optional. The generated file this source map is associated with.
  9430. *
  9431. * Here is an example source map, taken from the source map spec[0]:
  9432. *
  9433. * {
  9434. * version : 3,
  9435. * file: "out.js",
  9436. * sourceRoot : "",
  9437. * sources: ["foo.js", "bar.js"],
  9438. * names: ["src", "maps", "are", "fun"],
  9439. * mappings: "AA,AB;;ABCDE;"
  9440. * }
  9441. *
  9442. * The second parameter, if given, is a string whose value is the URL
  9443. * at which the source map was found. This URL is used to compute the
  9444. * sources array.
  9445. *
  9446. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  9447. */
  9448. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  9449. var sourceMap = aSourceMap;
  9450. if (typeof aSourceMap === 'string') {
  9451. sourceMap = util.parseSourceMapInput(aSourceMap);
  9452. }
  9453. var version = util.getArg(sourceMap, 'version');
  9454. var sources = util.getArg(sourceMap, 'sources');
  9455. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  9456. // requires the array) to play nice here.
  9457. var names = util.getArg(sourceMap, 'names', []);
  9458. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  9459. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  9460. var mappings = util.getArg(sourceMap, 'mappings');
  9461. var file = util.getArg(sourceMap, 'file', null);
  9462. // Once again, Sass deviates from the spec and supplies the version as a
  9463. // string rather than a number, so we use loose equality checking here.
  9464. if (version != this._version) {
  9465. throw new Error('Unsupported version: ' + version);
  9466. }
  9467. if (sourceRoot) {
  9468. sourceRoot = util.normalize(sourceRoot);
  9469. }
  9470. sources = sources
  9471. .map(String)
  9472. // Some source maps produce relative source paths like "./foo.js" instead of
  9473. // "foo.js". Normalize these first so that future comparisons will succeed.
  9474. // See bugzil.la/1090768.
  9475. .map(util.normalize)
  9476. // Always ensure that absolute sources are internally stored relative to
  9477. // the source root, if the source root is absolute. Not doing this would
  9478. // be particularly problematic when the source root is a prefix of the
  9479. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  9480. .map(function (source) {
  9481. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  9482. ? util.relative(sourceRoot, source)
  9483. : source;
  9484. });
  9485. // Pass `true` below to allow duplicate names and sources. While source maps
  9486. // are intended to be compressed and deduplicated, the TypeScript compiler
  9487. // sometimes generates source maps with duplicates in them. See Github issue
  9488. // #72 and bugzil.la/889492.
  9489. this._names = ArraySet.fromArray(names.map(String), true);
  9490. this._sources = ArraySet.fromArray(sources, true);
  9491. this._absoluteSources = this._sources.toArray().map(function (s) {
  9492. return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
  9493. });
  9494. this.sourceRoot = sourceRoot;
  9495. this.sourcesContent = sourcesContent;
  9496. this._mappings = mappings;
  9497. this._sourceMapURL = aSourceMapURL;
  9498. this.file = file;
  9499. }
  9500. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  9501. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  9502. /**
  9503. * Utility function to find the index of a source. Returns -1 if not
  9504. * found.
  9505. */
  9506. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  9507. var relativeSource = aSource;
  9508. if (this.sourceRoot != null) {
  9509. relativeSource = util.relative(this.sourceRoot, relativeSource);
  9510. }
  9511. if (this._sources.has(relativeSource)) {
  9512. return this._sources.indexOf(relativeSource);
  9513. }
  9514. // Maybe aSource is an absolute URL as returned by |sources|. In
  9515. // this case we can't simply undo the transform.
  9516. var i;
  9517. for (i = 0; i < this._absoluteSources.length; ++i) {
  9518. if (this._absoluteSources[i] == aSource) {
  9519. return i;
  9520. }
  9521. }
  9522. return -1;
  9523. };
  9524. /**
  9525. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  9526. *
  9527. * @param SourceMapGenerator aSourceMap
  9528. * The source map that will be consumed.
  9529. * @param String aSourceMapURL
  9530. * The URL at which the source map can be found (optional)
  9531. * @returns BasicSourceMapConsumer
  9532. */
  9533. BasicSourceMapConsumer.fromSourceMap =
  9534. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  9535. var smc = Object.create(BasicSourceMapConsumer.prototype);
  9536. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  9537. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  9538. smc.sourceRoot = aSourceMap._sourceRoot;
  9539. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  9540. smc.sourceRoot);
  9541. smc.file = aSourceMap._file;
  9542. smc._sourceMapURL = aSourceMapURL;
  9543. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  9544. return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  9545. });
  9546. // Because we are modifying the entries (by converting string sources and
  9547. // names to indices into the sources and names ArraySets), we have to make
  9548. // a copy of the entry or else bad things happen. Shared mutable state
  9549. // strikes again! See github issue #191.
  9550. var generatedMappings = aSourceMap._mappings.toArray().slice();
  9551. var destGeneratedMappings = smc.__generatedMappings = [];
  9552. var destOriginalMappings = smc.__originalMappings = [];
  9553. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  9554. var srcMapping = generatedMappings[i];
  9555. var destMapping = new Mapping;
  9556. destMapping.generatedLine = srcMapping.generatedLine;
  9557. destMapping.generatedColumn = srcMapping.generatedColumn;
  9558. if (srcMapping.source) {
  9559. destMapping.source = sources.indexOf(srcMapping.source);
  9560. destMapping.originalLine = srcMapping.originalLine;
  9561. destMapping.originalColumn = srcMapping.originalColumn;
  9562. if (srcMapping.name) {
  9563. destMapping.name = names.indexOf(srcMapping.name);
  9564. }
  9565. destOriginalMappings.push(destMapping);
  9566. }
  9567. destGeneratedMappings.push(destMapping);
  9568. }
  9569. quickSort(smc.__originalMappings, util.compareByOriginalPositions);
  9570. return smc;
  9571. };
  9572. /**
  9573. * The version of the source mapping spec that we are consuming.
  9574. */
  9575. BasicSourceMapConsumer.prototype._version = 3;
  9576. /**
  9577. * The list of original sources.
  9578. */
  9579. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  9580. get: function () {
  9581. return this._absoluteSources.slice();
  9582. }
  9583. });
  9584. /**
  9585. * Provide the JIT with a nice shape / hidden class.
  9586. */
  9587. function Mapping() {
  9588. this.generatedLine = 0;
  9589. this.generatedColumn = 0;
  9590. this.source = null;
  9591. this.originalLine = null;
  9592. this.originalColumn = null;
  9593. this.name = null;
  9594. }
  9595. /**
  9596. * Parse the mappings in a string in to a data structure which we can easily
  9597. * query (the ordered arrays in the `this.__generatedMappings` and
  9598. * `this.__originalMappings` properties).
  9599. */
  9600. BasicSourceMapConsumer.prototype._parseMappings =
  9601. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9602. var generatedLine = 1;
  9603. var previousGeneratedColumn = 0;
  9604. var previousOriginalLine = 0;
  9605. var previousOriginalColumn = 0;
  9606. var previousSource = 0;
  9607. var previousName = 0;
  9608. var length = aStr.length;
  9609. var index = 0;
  9610. var cachedSegments = {};
  9611. var temp = {};
  9612. var originalMappings = [];
  9613. var generatedMappings = [];
  9614. var mapping, str, segment, end, value;
  9615. while (index < length) {
  9616. if (aStr.charAt(index) === ';') {
  9617. generatedLine++;
  9618. index++;
  9619. previousGeneratedColumn = 0;
  9620. }
  9621. else if (aStr.charAt(index) === ',') {
  9622. index++;
  9623. }
  9624. else {
  9625. mapping = new Mapping();
  9626. mapping.generatedLine = generatedLine;
  9627. // Because each offset is encoded relative to the previous one,
  9628. // many segments often have the same encoding. We can exploit this
  9629. // fact by caching the parsed variable length fields of each segment,
  9630. // allowing us to avoid a second parse if we encounter the same
  9631. // segment again.
  9632. for (end = index; end < length; end++) {
  9633. if (this._charIsMappingSeparator(aStr, end)) {
  9634. break;
  9635. }
  9636. }
  9637. str = aStr.slice(index, end);
  9638. segment = cachedSegments[str];
  9639. if (segment) {
  9640. index += str.length;
  9641. } else {
  9642. segment = [];
  9643. while (index < end) {
  9644. base64VLQ.decode(aStr, index, temp);
  9645. value = temp.value;
  9646. index = temp.rest;
  9647. segment.push(value);
  9648. }
  9649. if (segment.length === 2) {
  9650. throw new Error('Found a source, but no line and column');
  9651. }
  9652. if (segment.length === 3) {
  9653. throw new Error('Found a source and line, but no column');
  9654. }
  9655. cachedSegments[str] = segment;
  9656. }
  9657. // Generated column.
  9658. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  9659. previousGeneratedColumn = mapping.generatedColumn;
  9660. if (segment.length > 1) {
  9661. // Original source.
  9662. mapping.source = previousSource + segment[1];
  9663. previousSource += segment[1];
  9664. // Original line.
  9665. mapping.originalLine = previousOriginalLine + segment[2];
  9666. previousOriginalLine = mapping.originalLine;
  9667. // Lines are stored 0-based
  9668. mapping.originalLine += 1;
  9669. // Original column.
  9670. mapping.originalColumn = previousOriginalColumn + segment[3];
  9671. previousOriginalColumn = mapping.originalColumn;
  9672. if (segment.length > 4) {
  9673. // Original name.
  9674. mapping.name = previousName + segment[4];
  9675. previousName += segment[4];
  9676. }
  9677. }
  9678. generatedMappings.push(mapping);
  9679. if (typeof mapping.originalLine === 'number') {
  9680. originalMappings.push(mapping);
  9681. }
  9682. }
  9683. }
  9684. quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
  9685. this.__generatedMappings = generatedMappings;
  9686. quickSort(originalMappings, util.compareByOriginalPositions);
  9687. this.__originalMappings = originalMappings;
  9688. };
  9689. /**
  9690. * Find the mapping that best matches the hypothetical "needle" mapping that
  9691. * we are searching for in the given "haystack" of mappings.
  9692. */
  9693. BasicSourceMapConsumer.prototype._findMapping =
  9694. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  9695. aColumnName, aComparator, aBias) {
  9696. // To return the position we are searching for, we must first find the
  9697. // mapping for the given position and then return the opposite position it
  9698. // points to. Because the mappings are sorted, we can use binary search to
  9699. // find the best mapping.
  9700. if (aNeedle[aLineName] <= 0) {
  9701. throw new TypeError('Line must be greater than or equal to 1, got '
  9702. + aNeedle[aLineName]);
  9703. }
  9704. if (aNeedle[aColumnName] < 0) {
  9705. throw new TypeError('Column must be greater than or equal to 0, got '
  9706. + aNeedle[aColumnName]);
  9707. }
  9708. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  9709. };
  9710. /**
  9711. * Compute the last column for each generated mapping. The last column is
  9712. * inclusive.
  9713. */
  9714. BasicSourceMapConsumer.prototype.computeColumnSpans =
  9715. function SourceMapConsumer_computeColumnSpans() {
  9716. for (var index = 0; index < this._generatedMappings.length; ++index) {
  9717. var mapping = this._generatedMappings[index];
  9718. // Mappings do not contain a field for the last generated columnt. We
  9719. // can come up with an optimistic estimate, however, by assuming that
  9720. // mappings are contiguous (i.e. given two consecutive mappings, the
  9721. // first mapping ends where the second one starts).
  9722. if (index + 1 < this._generatedMappings.length) {
  9723. var nextMapping = this._generatedMappings[index + 1];
  9724. if (mapping.generatedLine === nextMapping.generatedLine) {
  9725. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  9726. continue;
  9727. }
  9728. }
  9729. // The last mapping for each line spans the entire line.
  9730. mapping.lastGeneratedColumn = Infinity;
  9731. }
  9732. };
  9733. /**
  9734. * Returns the original source, line, and column information for the generated
  9735. * source's line and column positions provided. The only argument is an object
  9736. * with the following properties:
  9737. *
  9738. * - line: The line number in the generated source. The line number
  9739. * is 1-based.
  9740. * - column: The column number in the generated source. The column
  9741. * number is 0-based.
  9742. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  9743. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  9744. * closest element that is smaller than or greater than the one we are
  9745. * searching for, respectively, if the exact element cannot be found.
  9746. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  9747. *
  9748. * and an object is returned with the following properties:
  9749. *
  9750. * - source: The original source file, or null.
  9751. * - line: The line number in the original source, or null. The
  9752. * line number is 1-based.
  9753. * - column: The column number in the original source, or null. The
  9754. * column number is 0-based.
  9755. * - name: The original identifier, or null.
  9756. */
  9757. BasicSourceMapConsumer.prototype.originalPositionFor =
  9758. function SourceMapConsumer_originalPositionFor(aArgs) {
  9759. var needle = {
  9760. generatedLine: util.getArg(aArgs, 'line'),
  9761. generatedColumn: util.getArg(aArgs, 'column')
  9762. };
  9763. var index = this._findMapping(
  9764. needle,
  9765. this._generatedMappings,
  9766. "generatedLine",
  9767. "generatedColumn",
  9768. util.compareByGeneratedPositionsDeflated,
  9769. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  9770. );
  9771. if (index >= 0) {
  9772. var mapping = this._generatedMappings[index];
  9773. if (mapping.generatedLine === needle.generatedLine) {
  9774. var source = util.getArg(mapping, 'source', null);
  9775. if (source !== null) {
  9776. source = this._sources.at(source);
  9777. source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  9778. }
  9779. var name = util.getArg(mapping, 'name', null);
  9780. if (name !== null) {
  9781. name = this._names.at(name);
  9782. }
  9783. return {
  9784. source: source,
  9785. line: util.getArg(mapping, 'originalLine', null),
  9786. column: util.getArg(mapping, 'originalColumn', null),
  9787. name: name
  9788. };
  9789. }
  9790. }
  9791. return {
  9792. source: null,
  9793. line: null,
  9794. column: null,
  9795. name: null
  9796. };
  9797. };
  9798. /**
  9799. * Return true if we have the source content for every source in the source
  9800. * map, false otherwise.
  9801. */
  9802. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  9803. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  9804. if (!this.sourcesContent) {
  9805. return false;
  9806. }
  9807. return this.sourcesContent.length >= this._sources.size() &&
  9808. !this.sourcesContent.some(function (sc) { return sc == null; });
  9809. };
  9810. /**
  9811. * Returns the original source content. The only argument is the url of the
  9812. * original source file. Returns null if no original source content is
  9813. * available.
  9814. */
  9815. BasicSourceMapConsumer.prototype.sourceContentFor =
  9816. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  9817. if (!this.sourcesContent) {
  9818. return null;
  9819. }
  9820. var index = this._findSourceIndex(aSource);
  9821. if (index >= 0) {
  9822. return this.sourcesContent[index];
  9823. }
  9824. var relativeSource = aSource;
  9825. if (this.sourceRoot != null) {
  9826. relativeSource = util.relative(this.sourceRoot, relativeSource);
  9827. }
  9828. var url;
  9829. if (this.sourceRoot != null
  9830. && (url = util.urlParse(this.sourceRoot))) {
  9831. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  9832. // many users. We can help them out when they expect file:// URIs to
  9833. // behave like it would if they were running a local HTTP server. See
  9834. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  9835. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  9836. if (url.scheme == "file"
  9837. && this._sources.has(fileUriAbsPath)) {
  9838. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  9839. }
  9840. if ((!url.path || url.path == "/")
  9841. && this._sources.has("/" + relativeSource)) {
  9842. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  9843. }
  9844. }
  9845. // This function is used recursively from
  9846. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  9847. // don't want to throw if we can't find the source - we just want to
  9848. // return null, so we provide a flag to exit gracefully.
  9849. if (nullOnMissing) {
  9850. return null;
  9851. }
  9852. else {
  9853. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  9854. }
  9855. };
  9856. /**
  9857. * Returns the generated line and column information for the original source,
  9858. * line, and column positions provided. The only argument is an object with
  9859. * the following properties:
  9860. *
  9861. * - source: The filename of the original source.
  9862. * - line: The line number in the original source. The line number
  9863. * is 1-based.
  9864. * - column: The column number in the original source. The column
  9865. * number is 0-based.
  9866. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  9867. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  9868. * closest element that is smaller than or greater than the one we are
  9869. * searching for, respectively, if the exact element cannot be found.
  9870. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  9871. *
  9872. * and an object is returned with the following properties:
  9873. *
  9874. * - line: The line number in the generated source, or null. The
  9875. * line number is 1-based.
  9876. * - column: The column number in the generated source, or null.
  9877. * The column number is 0-based.
  9878. */
  9879. BasicSourceMapConsumer.prototype.generatedPositionFor =
  9880. function SourceMapConsumer_generatedPositionFor(aArgs) {
  9881. var source = util.getArg(aArgs, 'source');
  9882. source = this._findSourceIndex(source);
  9883. if (source < 0) {
  9884. return {
  9885. line: null,
  9886. column: null,
  9887. lastColumn: null
  9888. };
  9889. }
  9890. var needle = {
  9891. source: source,
  9892. originalLine: util.getArg(aArgs, 'line'),
  9893. originalColumn: util.getArg(aArgs, 'column')
  9894. };
  9895. var index = this._findMapping(
  9896. needle,
  9897. this._originalMappings,
  9898. "originalLine",
  9899. "originalColumn",
  9900. util.compareByOriginalPositions,
  9901. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  9902. );
  9903. if (index >= 0) {
  9904. var mapping = this._originalMappings[index];
  9905. if (mapping.source === needle.source) {
  9906. return {
  9907. line: util.getArg(mapping, 'generatedLine', null),
  9908. column: util.getArg(mapping, 'generatedColumn', null),
  9909. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9910. };
  9911. }
  9912. }
  9913. return {
  9914. line: null,
  9915. column: null,
  9916. lastColumn: null
  9917. };
  9918. };
  9919. sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer;
  9920. /**
  9921. * An IndexedSourceMapConsumer instance represents a parsed source map which
  9922. * we can query for information. It differs from BasicSourceMapConsumer in
  9923. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  9924. * input.
  9925. *
  9926. * The first parameter is a raw source map (either as a JSON string, or already
  9927. * parsed to an object). According to the spec for indexed source maps, they
  9928. * have the following attributes:
  9929. *
  9930. * - version: Which version of the source map spec this map is following.
  9931. * - file: Optional. The generated file this source map is associated with.
  9932. * - sections: A list of section definitions.
  9933. *
  9934. * Each value under the "sections" field has two fields:
  9935. * - offset: The offset into the original specified at which this section
  9936. * begins to apply, defined as an object with a "line" and "column"
  9937. * field.
  9938. * - map: A source map definition. This source map could also be indexed,
  9939. * but doesn't have to be.
  9940. *
  9941. * Instead of the "map" field, it's also possible to have a "url" field
  9942. * specifying a URL to retrieve a source map from, but that's currently
  9943. * unsupported.
  9944. *
  9945. * Here's an example source map, taken from the source map spec[0], but
  9946. * modified to omit a section which uses the "url" field.
  9947. *
  9948. * {
  9949. * version : 3,
  9950. * file: "app.js",
  9951. * sections: [{
  9952. * offset: {line:100, column:10},
  9953. * map: {
  9954. * version : 3,
  9955. * file: "section.js",
  9956. * sources: ["foo.js", "bar.js"],
  9957. * names: ["src", "maps", "are", "fun"],
  9958. * mappings: "AAAA,E;;ABCDE;"
  9959. * }
  9960. * }],
  9961. * }
  9962. *
  9963. * The second parameter, if given, is a string whose value is the URL
  9964. * at which the source map was found. This URL is used to compute the
  9965. * sources array.
  9966. *
  9967. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  9968. */
  9969. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  9970. var sourceMap = aSourceMap;
  9971. if (typeof aSourceMap === 'string') {
  9972. sourceMap = util.parseSourceMapInput(aSourceMap);
  9973. }
  9974. var version = util.getArg(sourceMap, 'version');
  9975. var sections = util.getArg(sourceMap, 'sections');
  9976. if (version != this._version) {
  9977. throw new Error('Unsupported version: ' + version);
  9978. }
  9979. this._sources = new ArraySet();
  9980. this._names = new ArraySet();
  9981. var lastOffset = {
  9982. line: -1,
  9983. column: 0
  9984. };
  9985. this._sections = sections.map(function (s) {
  9986. if (s.url) {
  9987. // The url field will require support for asynchronicity.
  9988. // See https://github.com/mozilla/source-map/issues/16
  9989. throw new Error('Support for url field in sections not implemented.');
  9990. }
  9991. var offset = util.getArg(s, 'offset');
  9992. var offsetLine = util.getArg(offset, 'line');
  9993. var offsetColumn = util.getArg(offset, 'column');
  9994. if (offsetLine < lastOffset.line ||
  9995. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  9996. throw new Error('Section offsets must be ordered and non-overlapping.');
  9997. }
  9998. lastOffset = offset;
  9999. return {
  10000. generatedOffset: {
  10001. // The offset fields are 0-based, but we use 1-based indices when
  10002. // encoding/decoding from VLQ.
  10003. generatedLine: offsetLine + 1,
  10004. generatedColumn: offsetColumn + 1
  10005. },
  10006. consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
  10007. }
  10008. });
  10009. }
  10010. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  10011. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  10012. /**
  10013. * The version of the source mapping spec that we are consuming.
  10014. */
  10015. IndexedSourceMapConsumer.prototype._version = 3;
  10016. /**
  10017. * The list of original sources.
  10018. */
  10019. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  10020. get: function () {
  10021. var sources = [];
  10022. for (var i = 0; i < this._sections.length; i++) {
  10023. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  10024. sources.push(this._sections[i].consumer.sources[j]);
  10025. }
  10026. }
  10027. return sources;
  10028. }
  10029. });
  10030. /**
  10031. * Returns the original source, line, and column information for the generated
  10032. * source's line and column positions provided. The only argument is an object
  10033. * with the following properties:
  10034. *
  10035. * - line: The line number in the generated source. The line number
  10036. * is 1-based.
  10037. * - column: The column number in the generated source. The column
  10038. * number is 0-based.
  10039. *
  10040. * and an object is returned with the following properties:
  10041. *
  10042. * - source: The original source file, or null.
  10043. * - line: The line number in the original source, or null. The
  10044. * line number is 1-based.
  10045. * - column: The column number in the original source, or null. The
  10046. * column number is 0-based.
  10047. * - name: The original identifier, or null.
  10048. */
  10049. IndexedSourceMapConsumer.prototype.originalPositionFor =
  10050. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  10051. var needle = {
  10052. generatedLine: util.getArg(aArgs, 'line'),
  10053. generatedColumn: util.getArg(aArgs, 'column')
  10054. };
  10055. // Find the section containing the generated position we're trying to map
  10056. // to an original position.
  10057. var sectionIndex = binarySearch.search(needle, this._sections,
  10058. function(needle, section) {
  10059. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  10060. if (cmp) {
  10061. return cmp;
  10062. }
  10063. return (needle.generatedColumn -
  10064. section.generatedOffset.generatedColumn);
  10065. });
  10066. var section = this._sections[sectionIndex];
  10067. if (!section) {
  10068. return {
  10069. source: null,
  10070. line: null,
  10071. column: null,
  10072. name: null
  10073. };
  10074. }
  10075. return section.consumer.originalPositionFor({
  10076. line: needle.generatedLine -
  10077. (section.generatedOffset.generatedLine - 1),
  10078. column: needle.generatedColumn -
  10079. (section.generatedOffset.generatedLine === needle.generatedLine
  10080. ? section.generatedOffset.generatedColumn - 1
  10081. : 0),
  10082. bias: aArgs.bias
  10083. });
  10084. };
  10085. /**
  10086. * Return true if we have the source content for every source in the source
  10087. * map, false otherwise.
  10088. */
  10089. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  10090. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  10091. return this._sections.every(function (s) {
  10092. return s.consumer.hasContentsOfAllSources();
  10093. });
  10094. };
  10095. /**
  10096. * Returns the original source content. The only argument is the url of the
  10097. * original source file. Returns null if no original source content is
  10098. * available.
  10099. */
  10100. IndexedSourceMapConsumer.prototype.sourceContentFor =
  10101. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  10102. for (var i = 0; i < this._sections.length; i++) {
  10103. var section = this._sections[i];
  10104. var content = section.consumer.sourceContentFor(aSource, true);
  10105. if (content) {
  10106. return content;
  10107. }
  10108. }
  10109. if (nullOnMissing) {
  10110. return null;
  10111. }
  10112. else {
  10113. throw new Error('"' + aSource + '" is not in the SourceMap.');
  10114. }
  10115. };
  10116. /**
  10117. * Returns the generated line and column information for the original source,
  10118. * line, and column positions provided. The only argument is an object with
  10119. * the following properties:
  10120. *
  10121. * - source: The filename of the original source.
  10122. * - line: The line number in the original source. The line number
  10123. * is 1-based.
  10124. * - column: The column number in the original source. The column
  10125. * number is 0-based.
  10126. *
  10127. * and an object is returned with the following properties:
  10128. *
  10129. * - line: The line number in the generated source, or null. The
  10130. * line number is 1-based.
  10131. * - column: The column number in the generated source, or null.
  10132. * The column number is 0-based.
  10133. */
  10134. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  10135. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  10136. for (var i = 0; i < this._sections.length; i++) {
  10137. var section = this._sections[i];
  10138. // Only consider this section if the requested source is in the list of
  10139. // sources of the consumer.
  10140. if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
  10141. continue;
  10142. }
  10143. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  10144. if (generatedPosition) {
  10145. var ret = {
  10146. line: generatedPosition.line +
  10147. (section.generatedOffset.generatedLine - 1),
  10148. column: generatedPosition.column +
  10149. (section.generatedOffset.generatedLine === generatedPosition.line
  10150. ? section.generatedOffset.generatedColumn - 1
  10151. : 0)
  10152. };
  10153. return ret;
  10154. }
  10155. }
  10156. return {
  10157. line: null,
  10158. column: null
  10159. };
  10160. };
  10161. /**
  10162. * Parse the mappings in a string in to a data structure which we can easily
  10163. * query (the ordered arrays in the `this.__generatedMappings` and
  10164. * `this.__originalMappings` properties).
  10165. */
  10166. IndexedSourceMapConsumer.prototype._parseMappings =
  10167. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  10168. this.__generatedMappings = [];
  10169. this.__originalMappings = [];
  10170. for (var i = 0; i < this._sections.length; i++) {
  10171. var section = this._sections[i];
  10172. var sectionMappings = section.consumer._generatedMappings;
  10173. for (var j = 0; j < sectionMappings.length; j++) {
  10174. var mapping = sectionMappings[j];
  10175. var source = section.consumer._sources.at(mapping.source);
  10176. source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  10177. this._sources.add(source);
  10178. source = this._sources.indexOf(source);
  10179. var name = null;
  10180. if (mapping.name) {
  10181. name = section.consumer._names.at(mapping.name);
  10182. this._names.add(name);
  10183. name = this._names.indexOf(name);
  10184. }
  10185. // The mappings coming from the consumer for the section have
  10186. // generated positions relative to the start of the section, so we
  10187. // need to offset them to be relative to the start of the concatenated
  10188. // generated file.
  10189. var adjustedMapping = {
  10190. source: source,
  10191. generatedLine: mapping.generatedLine +
  10192. (section.generatedOffset.generatedLine - 1),
  10193. generatedColumn: mapping.generatedColumn +
  10194. (section.generatedOffset.generatedLine === mapping.generatedLine
  10195. ? section.generatedOffset.generatedColumn - 1
  10196. : 0),
  10197. originalLine: mapping.originalLine,
  10198. originalColumn: mapping.originalColumn,
  10199. name: name
  10200. };
  10201. this.__generatedMappings.push(adjustedMapping);
  10202. if (typeof adjustedMapping.originalLine === 'number') {
  10203. this.__originalMappings.push(adjustedMapping);
  10204. }
  10205. }
  10206. }
  10207. quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  10208. quickSort(this.__originalMappings, util.compareByOriginalPositions);
  10209. };
  10210. sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  10211. return sourceMapConsumer;
  10212. }
  10213. var sourceNode = {};
  10214. /* -*- Mode: js; js-indent-level: 2; -*- */
  10215. var hasRequiredSourceNode;
  10216. function requireSourceNode () {
  10217. if (hasRequiredSourceNode) return sourceNode;
  10218. hasRequiredSourceNode = 1;
  10219. /*
  10220. * Copyright 2011 Mozilla Foundation and contributors
  10221. * Licensed under the New BSD license. See LICENSE or:
  10222. * http://opensource.org/licenses/BSD-3-Clause
  10223. */
  10224. var SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  10225. var util = /*@__PURE__*/ requireUtil$1();
  10226. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  10227. // operating systems these days (capturing the result).
  10228. var REGEX_NEWLINE = /(\r?\n)/;
  10229. // Newline character code for charCodeAt() comparisons
  10230. var NEWLINE_CODE = 10;
  10231. // Private symbol for identifying `SourceNode`s when multiple versions of
  10232. // the source-map library are loaded. This MUST NOT CHANGE across
  10233. // versions!
  10234. var isSourceNode = "$$$isSourceNode$$$";
  10235. /**
  10236. * SourceNodes provide a way to abstract over interpolating/concatenating
  10237. * snippets of generated JavaScript source code while maintaining the line and
  10238. * column information associated with the original source code.
  10239. *
  10240. * @param aLine The original line number.
  10241. * @param aColumn The original column number.
  10242. * @param aSource The original source's filename.
  10243. * @param aChunks Optional. An array of strings which are snippets of
  10244. * generated JS, or other SourceNodes.
  10245. * @param aName The original identifier.
  10246. */
  10247. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  10248. this.children = [];
  10249. this.sourceContents = {};
  10250. this.line = aLine == null ? null : aLine;
  10251. this.column = aColumn == null ? null : aColumn;
  10252. this.source = aSource == null ? null : aSource;
  10253. this.name = aName == null ? null : aName;
  10254. this[isSourceNode] = true;
  10255. if (aChunks != null) this.add(aChunks);
  10256. }
  10257. /**
  10258. * Creates a SourceNode from generated code and a SourceMapConsumer.
  10259. *
  10260. * @param aGeneratedCode The generated code
  10261. * @param aSourceMapConsumer The SourceMap for the generated code
  10262. * @param aRelativePath Optional. The path that relative sources in the
  10263. * SourceMapConsumer should be relative to.
  10264. */
  10265. SourceNode.fromStringWithSourceMap =
  10266. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  10267. // The SourceNode we want to fill with the generated code
  10268. // and the SourceMap
  10269. var node = new SourceNode();
  10270. // All even indices of this array are one line of the generated code,
  10271. // while all odd indices are the newlines between two adjacent lines
  10272. // (since `REGEX_NEWLINE` captures its match).
  10273. // Processed fragments are accessed by calling `shiftNextLine`.
  10274. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  10275. var remainingLinesIndex = 0;
  10276. var shiftNextLine = function() {
  10277. var lineContents = getNextLine();
  10278. // The last line of a file might not have a newline.
  10279. var newLine = getNextLine() || "";
  10280. return lineContents + newLine;
  10281. function getNextLine() {
  10282. return remainingLinesIndex < remainingLines.length ?
  10283. remainingLines[remainingLinesIndex++] : undefined;
  10284. }
  10285. };
  10286. // We need to remember the position of "remainingLines"
  10287. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  10288. // The generate SourceNodes we need a code range.
  10289. // To extract it current and last mapping is used.
  10290. // Here we store the last mapping.
  10291. var lastMapping = null;
  10292. aSourceMapConsumer.eachMapping(function (mapping) {
  10293. if (lastMapping !== null) {
  10294. // We add the code from "lastMapping" to "mapping":
  10295. // First check if there is a new line in between.
  10296. if (lastGeneratedLine < mapping.generatedLine) {
  10297. // Associate first line with "lastMapping"
  10298. addMappingWithCode(lastMapping, shiftNextLine());
  10299. lastGeneratedLine++;
  10300. lastGeneratedColumn = 0;
  10301. // The remaining code is added without mapping
  10302. } else {
  10303. // There is no new line in between.
  10304. // Associate the code between "lastGeneratedColumn" and
  10305. // "mapping.generatedColumn" with "lastMapping"
  10306. var nextLine = remainingLines[remainingLinesIndex] || '';
  10307. var code = nextLine.substr(0, mapping.generatedColumn -
  10308. lastGeneratedColumn);
  10309. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  10310. lastGeneratedColumn);
  10311. lastGeneratedColumn = mapping.generatedColumn;
  10312. addMappingWithCode(lastMapping, code);
  10313. // No more remaining code, continue
  10314. lastMapping = mapping;
  10315. return;
  10316. }
  10317. }
  10318. // We add the generated code until the first mapping
  10319. // to the SourceNode without any mapping.
  10320. // Each line is added as separate string.
  10321. while (lastGeneratedLine < mapping.generatedLine) {
  10322. node.add(shiftNextLine());
  10323. lastGeneratedLine++;
  10324. }
  10325. if (lastGeneratedColumn < mapping.generatedColumn) {
  10326. var nextLine = remainingLines[remainingLinesIndex] || '';
  10327. node.add(nextLine.substr(0, mapping.generatedColumn));
  10328. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  10329. lastGeneratedColumn = mapping.generatedColumn;
  10330. }
  10331. lastMapping = mapping;
  10332. }, this);
  10333. // We have processed all mappings.
  10334. if (remainingLinesIndex < remainingLines.length) {
  10335. if (lastMapping) {
  10336. // Associate the remaining code in the current line with "lastMapping"
  10337. addMappingWithCode(lastMapping, shiftNextLine());
  10338. }
  10339. // and add the remaining lines without any mapping
  10340. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  10341. }
  10342. // Copy sourcesContent into SourceNode
  10343. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  10344. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  10345. if (content != null) {
  10346. if (aRelativePath != null) {
  10347. sourceFile = util.join(aRelativePath, sourceFile);
  10348. }
  10349. node.setSourceContent(sourceFile, content);
  10350. }
  10351. });
  10352. return node;
  10353. function addMappingWithCode(mapping, code) {
  10354. if (mapping === null || mapping.source === undefined) {
  10355. node.add(code);
  10356. } else {
  10357. var source = aRelativePath
  10358. ? util.join(aRelativePath, mapping.source)
  10359. : mapping.source;
  10360. node.add(new SourceNode(mapping.originalLine,
  10361. mapping.originalColumn,
  10362. source,
  10363. code,
  10364. mapping.name));
  10365. }
  10366. }
  10367. };
  10368. /**
  10369. * Add a chunk of generated JS to this source node.
  10370. *
  10371. * @param aChunk A string snippet of generated JS code, another instance of
  10372. * SourceNode, or an array where each member is one of those things.
  10373. */
  10374. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  10375. if (Array.isArray(aChunk)) {
  10376. aChunk.forEach(function (chunk) {
  10377. this.add(chunk);
  10378. }, this);
  10379. }
  10380. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10381. if (aChunk) {
  10382. this.children.push(aChunk);
  10383. }
  10384. }
  10385. else {
  10386. throw new TypeError(
  10387. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10388. );
  10389. }
  10390. return this;
  10391. };
  10392. /**
  10393. * Add a chunk of generated JS to the beginning of this source node.
  10394. *
  10395. * @param aChunk A string snippet of generated JS code, another instance of
  10396. * SourceNode, or an array where each member is one of those things.
  10397. */
  10398. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  10399. if (Array.isArray(aChunk)) {
  10400. for (var i = aChunk.length-1; i >= 0; i--) {
  10401. this.prepend(aChunk[i]);
  10402. }
  10403. }
  10404. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10405. this.children.unshift(aChunk);
  10406. }
  10407. else {
  10408. throw new TypeError(
  10409. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10410. );
  10411. }
  10412. return this;
  10413. };
  10414. /**
  10415. * Walk over the tree of JS snippets in this node and its children. The
  10416. * walking function is called once for each snippet of JS and is passed that
  10417. * snippet and the its original associated source's line/column location.
  10418. *
  10419. * @param aFn The traversal function.
  10420. */
  10421. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  10422. var chunk;
  10423. for (var i = 0, len = this.children.length; i < len; i++) {
  10424. chunk = this.children[i];
  10425. if (chunk[isSourceNode]) {
  10426. chunk.walk(aFn);
  10427. }
  10428. else {
  10429. if (chunk !== '') {
  10430. aFn(chunk, { source: this.source,
  10431. line: this.line,
  10432. column: this.column,
  10433. name: this.name });
  10434. }
  10435. }
  10436. }
  10437. };
  10438. /**
  10439. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  10440. * each of `this.children`.
  10441. *
  10442. * @param aSep The separator.
  10443. */
  10444. SourceNode.prototype.join = function SourceNode_join(aSep) {
  10445. var newChildren;
  10446. var i;
  10447. var len = this.children.length;
  10448. if (len > 0) {
  10449. newChildren = [];
  10450. for (i = 0; i < len-1; i++) {
  10451. newChildren.push(this.children[i]);
  10452. newChildren.push(aSep);
  10453. }
  10454. newChildren.push(this.children[i]);
  10455. this.children = newChildren;
  10456. }
  10457. return this;
  10458. };
  10459. /**
  10460. * Call String.prototype.replace on the very right-most source snippet. Useful
  10461. * for trimming whitespace from the end of a source node, etc.
  10462. *
  10463. * @param aPattern The pattern to replace.
  10464. * @param aReplacement The thing to replace the pattern with.
  10465. */
  10466. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  10467. var lastChild = this.children[this.children.length - 1];
  10468. if (lastChild[isSourceNode]) {
  10469. lastChild.replaceRight(aPattern, aReplacement);
  10470. }
  10471. else if (typeof lastChild === 'string') {
  10472. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  10473. }
  10474. else {
  10475. this.children.push(''.replace(aPattern, aReplacement));
  10476. }
  10477. return this;
  10478. };
  10479. /**
  10480. * Set the source content for a source file. This will be added to the SourceMapGenerator
  10481. * in the sourcesContent field.
  10482. *
  10483. * @param aSourceFile The filename of the source file
  10484. * @param aSourceContent The content of the source file
  10485. */
  10486. SourceNode.prototype.setSourceContent =
  10487. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  10488. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  10489. };
  10490. /**
  10491. * Walk over the tree of SourceNodes. The walking function is called for each
  10492. * source file content and is passed the filename and source content.
  10493. *
  10494. * @param aFn The traversal function.
  10495. */
  10496. SourceNode.prototype.walkSourceContents =
  10497. function SourceNode_walkSourceContents(aFn) {
  10498. for (var i = 0, len = this.children.length; i < len; i++) {
  10499. if (this.children[i][isSourceNode]) {
  10500. this.children[i].walkSourceContents(aFn);
  10501. }
  10502. }
  10503. var sources = Object.keys(this.sourceContents);
  10504. for (var i = 0, len = sources.length; i < len; i++) {
  10505. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  10506. }
  10507. };
  10508. /**
  10509. * Return the string representation of this source node. Walks over the tree
  10510. * and concatenates all the various snippets together to one string.
  10511. */
  10512. SourceNode.prototype.toString = function SourceNode_toString() {
  10513. var str = "";
  10514. this.walk(function (chunk) {
  10515. str += chunk;
  10516. });
  10517. return str;
  10518. };
  10519. /**
  10520. * Returns the string representation of this source node along with a source
  10521. * map.
  10522. */
  10523. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  10524. var generated = {
  10525. code: "",
  10526. line: 1,
  10527. column: 0
  10528. };
  10529. var map = new SourceMapGenerator(aArgs);
  10530. var sourceMappingActive = false;
  10531. var lastOriginalSource = null;
  10532. var lastOriginalLine = null;
  10533. var lastOriginalColumn = null;
  10534. var lastOriginalName = null;
  10535. this.walk(function (chunk, original) {
  10536. generated.code += chunk;
  10537. if (original.source !== null
  10538. && original.line !== null
  10539. && original.column !== null) {
  10540. if(lastOriginalSource !== original.source
  10541. || lastOriginalLine !== original.line
  10542. || lastOriginalColumn !== original.column
  10543. || lastOriginalName !== original.name) {
  10544. map.addMapping({
  10545. source: original.source,
  10546. original: {
  10547. line: original.line,
  10548. column: original.column
  10549. },
  10550. generated: {
  10551. line: generated.line,
  10552. column: generated.column
  10553. },
  10554. name: original.name
  10555. });
  10556. }
  10557. lastOriginalSource = original.source;
  10558. lastOriginalLine = original.line;
  10559. lastOriginalColumn = original.column;
  10560. lastOriginalName = original.name;
  10561. sourceMappingActive = true;
  10562. } else if (sourceMappingActive) {
  10563. map.addMapping({
  10564. generated: {
  10565. line: generated.line,
  10566. column: generated.column
  10567. }
  10568. });
  10569. lastOriginalSource = null;
  10570. sourceMappingActive = false;
  10571. }
  10572. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  10573. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  10574. generated.line++;
  10575. generated.column = 0;
  10576. // Mappings end at eol
  10577. if (idx + 1 === length) {
  10578. lastOriginalSource = null;
  10579. sourceMappingActive = false;
  10580. } else if (sourceMappingActive) {
  10581. map.addMapping({
  10582. source: original.source,
  10583. original: {
  10584. line: original.line,
  10585. column: original.column
  10586. },
  10587. generated: {
  10588. line: generated.line,
  10589. column: generated.column
  10590. },
  10591. name: original.name
  10592. });
  10593. }
  10594. } else {
  10595. generated.column++;
  10596. }
  10597. }
  10598. });
  10599. this.walkSourceContents(function (sourceFile, sourceContent) {
  10600. map.setSourceContent(sourceFile, sourceContent);
  10601. });
  10602. return { code: generated.code, map: map };
  10603. };
  10604. sourceNode.SourceNode = SourceNode;
  10605. return sourceNode;
  10606. }
  10607. /*
  10608. * Copyright 2009-2011 Mozilla Foundation and contributors
  10609. * Licensed under the New BSD license. See LICENSE.txt or:
  10610. * http://opensource.org/licenses/BSD-3-Clause
  10611. */
  10612. var hasRequiredSourceMap;
  10613. function requireSourceMap () {
  10614. if (hasRequiredSourceMap) return sourceMap;
  10615. hasRequiredSourceMap = 1;
  10616. sourceMap.SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  10617. sourceMap.SourceMapConsumer = /*@__PURE__*/ requireSourceMapConsumer().SourceMapConsumer;
  10618. sourceMap.SourceNode = /*@__PURE__*/ requireSourceNode().SourceNode;
  10619. return sourceMap;
  10620. }
  10621. var mergeSourceMap;
  10622. var hasRequiredMergeSourceMap;
  10623. function requireMergeSourceMap () {
  10624. if (hasRequiredMergeSourceMap) return mergeSourceMap;
  10625. hasRequiredMergeSourceMap = 1;
  10626. var sourceMap = /*@__PURE__*/ requireSourceMap();
  10627. var SourceMapConsumer = sourceMap.SourceMapConsumer;
  10628. var SourceMapGenerator = sourceMap.SourceMapGenerator;
  10629. mergeSourceMap = merge;
  10630. /**
  10631. * Merge old source map and new source map and return merged.
  10632. * If old or new source map value is falsy, return another one as it is.
  10633. *
  10634. * @param {object|string} [oldMap] old source map object
  10635. * @param {object|string} [newmap] new source map object
  10636. * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
  10637. */
  10638. function merge(oldMap, newMap) {
  10639. if (!oldMap) return newMap
  10640. if (!newMap) return oldMap
  10641. var oldMapConsumer = new SourceMapConsumer(oldMap);
  10642. var newMapConsumer = new SourceMapConsumer(newMap);
  10643. var mergedMapGenerator = new SourceMapGenerator();
  10644. // iterate on new map and overwrite original position of new map with one of old map
  10645. newMapConsumer.eachMapping(function(m) {
  10646. // pass when `originalLine` is null.
  10647. // It occurs in case that the node does not have origin in original code.
  10648. if (m.originalLine == null) return
  10649. var origPosInOldMap = oldMapConsumer.originalPositionFor({
  10650. line: m.originalLine,
  10651. column: m.originalColumn
  10652. });
  10653. if (origPosInOldMap.source == null) return
  10654. mergedMapGenerator.addMapping({
  10655. original: {
  10656. line: origPosInOldMap.line,
  10657. column: origPosInOldMap.column
  10658. },
  10659. generated: {
  10660. line: m.generatedLine,
  10661. column: m.generatedColumn
  10662. },
  10663. source: origPosInOldMap.source,
  10664. name: origPosInOldMap.name
  10665. });
  10666. });
  10667. var consumers = [oldMapConsumer, newMapConsumer];
  10668. consumers.forEach(function(consumer) {
  10669. consumer.sources.forEach(function(sourceFile) {
  10670. mergedMapGenerator._sources.add(sourceFile);
  10671. var sourceContent = consumer.sourceContentFor(sourceFile);
  10672. if (sourceContent != null) {
  10673. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  10674. }
  10675. });
  10676. });
  10677. mergedMapGenerator._sourceRoot = oldMap.sourceRoot;
  10678. mergedMapGenerator._file = oldMap.file;
  10679. return JSON.parse(mergedMapGenerator.toString())
  10680. }
  10681. return mergeSourceMap;
  10682. }
  10683. var mergeSourceMapExports = /*@__PURE__*/ requireMergeSourceMap();
  10684. var merge = /*@__PURE__*/getDefaultExportFromCjs(mergeSourceMapExports);
  10685. const scss = (source, map, options, load = require) => {
  10686. const nodeSass = load("sass");
  10687. const { compileString, renderSync } = nodeSass;
  10688. const data = getSource(source, options.filename, options.additionalData);
  10689. let css;
  10690. let dependencies;
  10691. let sourceMap;
  10692. try {
  10693. if (compileString) {
  10694. const { pathToFileURL, fileURLToPath } = load("url");
  10695. const result = compileString(data, {
  10696. ...options,
  10697. url: pathToFileURL(options.filename),
  10698. sourceMap: !!map
  10699. });
  10700. css = result.css;
  10701. dependencies = result.loadedUrls.map((url) => fileURLToPath(url));
  10702. sourceMap = map ? result.sourceMap : void 0;
  10703. } else {
  10704. const result = renderSync({
  10705. ...options,
  10706. data,
  10707. file: options.filename,
  10708. outFile: options.filename,
  10709. sourceMap: !!map
  10710. });
  10711. css = result.css.toString();
  10712. dependencies = result.stats.includedFiles;
  10713. sourceMap = map ? JSON.parse(result.map.toString()) : void 0;
  10714. }
  10715. if (map) {
  10716. return {
  10717. code: css,
  10718. errors: [],
  10719. dependencies,
  10720. map: merge(map, sourceMap)
  10721. };
  10722. }
  10723. return { code: css, errors: [], dependencies };
  10724. } catch (e) {
  10725. return { code: "", errors: [e], dependencies: [] };
  10726. }
  10727. };
  10728. const sass = (source, map, options, load) => scss(
  10729. source,
  10730. map,
  10731. {
  10732. ...options,
  10733. indentedSyntax: true
  10734. },
  10735. load
  10736. );
  10737. const less = (source, map, options, load = require) => {
  10738. const nodeLess = load("less");
  10739. let result;
  10740. let error = null;
  10741. nodeLess.render(
  10742. getSource(source, options.filename, options.additionalData),
  10743. { ...options, syncImport: true },
  10744. (err, output) => {
  10745. error = err;
  10746. result = output;
  10747. }
  10748. );
  10749. if (error) return { code: "", errors: [error], dependencies: [] };
  10750. const dependencies = result.imports;
  10751. if (map) {
  10752. return {
  10753. code: result.css.toString(),
  10754. map: merge(map, result.map),
  10755. errors: [],
  10756. dependencies
  10757. };
  10758. }
  10759. return {
  10760. code: result.css.toString(),
  10761. errors: [],
  10762. dependencies
  10763. };
  10764. };
  10765. const styl = (source, map, options, load = require) => {
  10766. const nodeStylus = load("stylus");
  10767. try {
  10768. const ref = nodeStylus(source, options);
  10769. if (map) ref.set("sourcemap", { inline: false, comment: false });
  10770. const result = ref.render();
  10771. const dependencies = ref.deps();
  10772. if (map) {
  10773. return {
  10774. code: result,
  10775. map: merge(map, ref.sourcemap),
  10776. errors: [],
  10777. dependencies
  10778. };
  10779. }
  10780. return { code: result, errors: [], dependencies };
  10781. } catch (e) {
  10782. return { code: "", errors: [e], dependencies: [] };
  10783. }
  10784. };
  10785. function getSource(source, filename, additionalData) {
  10786. if (!additionalData) return source;
  10787. if (shared.isFunction(additionalData)) {
  10788. return additionalData(source, filename);
  10789. }
  10790. return additionalData + source;
  10791. }
  10792. const processors = {
  10793. less,
  10794. sass,
  10795. scss,
  10796. styl,
  10797. stylus: styl
  10798. };
  10799. var build = {exports: {}};
  10800. var fs = {};
  10801. var hasRequiredFs;
  10802. function requireFs () {
  10803. if (hasRequiredFs) return fs;
  10804. hasRequiredFs = 1;
  10805. Object.defineProperty(fs, "__esModule", {
  10806. value: true
  10807. });
  10808. fs.getFileSystem = getFileSystem;
  10809. fs.setFileSystem = setFileSystem;
  10810. let fileSystem = {
  10811. readFile: () => {
  10812. throw Error("readFile not implemented");
  10813. },
  10814. writeFile: () => {
  10815. throw Error("writeFile not implemented");
  10816. }
  10817. };
  10818. function setFileSystem(fs) {
  10819. fileSystem.readFile = fs.readFile;
  10820. fileSystem.writeFile = fs.writeFile;
  10821. }
  10822. function getFileSystem() {
  10823. return fileSystem;
  10824. }
  10825. return fs;
  10826. }
  10827. var pluginFactory = {};
  10828. var unquote = {};
  10829. var hasRequiredUnquote;
  10830. function requireUnquote () {
  10831. if (hasRequiredUnquote) return unquote;
  10832. hasRequiredUnquote = 1;
  10833. Object.defineProperty(unquote, "__esModule", {
  10834. value: true
  10835. });
  10836. unquote.default = unquote$1;
  10837. // copied from https://github.com/lakenen/node-unquote
  10838. const reg = /['"]/;
  10839. function unquote$1(str) {
  10840. if (!str) {
  10841. return "";
  10842. }
  10843. if (reg.test(str.charAt(0))) {
  10844. str = str.substr(1);
  10845. }
  10846. if (reg.test(str.charAt(str.length - 1))) {
  10847. str = str.substr(0, str.length - 1);
  10848. }
  10849. return str;
  10850. }
  10851. return unquote;
  10852. }
  10853. var Parser = {};
  10854. var replaceValueSymbols_1;
  10855. var hasRequiredReplaceValueSymbols;
  10856. function requireReplaceValueSymbols () {
  10857. if (hasRequiredReplaceValueSymbols) return replaceValueSymbols_1;
  10858. hasRequiredReplaceValueSymbols = 1;
  10859. const matchValueName = /[$]?[\w-]+/g;
  10860. const replaceValueSymbols = (value, replacements) => {
  10861. let matches;
  10862. while ((matches = matchValueName.exec(value))) {
  10863. const replacement = replacements[matches[0]];
  10864. if (replacement) {
  10865. value =
  10866. value.slice(0, matches.index) +
  10867. replacement +
  10868. value.slice(matchValueName.lastIndex);
  10869. matchValueName.lastIndex -= matches[0].length - replacement.length;
  10870. }
  10871. }
  10872. return value;
  10873. };
  10874. replaceValueSymbols_1 = replaceValueSymbols;
  10875. return replaceValueSymbols_1;
  10876. }
  10877. var replaceSymbols_1;
  10878. var hasRequiredReplaceSymbols;
  10879. function requireReplaceSymbols () {
  10880. if (hasRequiredReplaceSymbols) return replaceSymbols_1;
  10881. hasRequiredReplaceSymbols = 1;
  10882. const replaceValueSymbols = /*@__PURE__*/ requireReplaceValueSymbols();
  10883. const replaceSymbols = (css, replacements) => {
  10884. css.walk((node) => {
  10885. if (node.type === "decl" && node.value) {
  10886. node.value = replaceValueSymbols(node.value.toString(), replacements);
  10887. } else if (node.type === "rule" && node.selector) {
  10888. node.selector = replaceValueSymbols(
  10889. node.selector.toString(),
  10890. replacements
  10891. );
  10892. } else if (node.type === "atrule" && node.params) {
  10893. node.params = replaceValueSymbols(node.params.toString(), replacements);
  10894. }
  10895. });
  10896. };
  10897. replaceSymbols_1 = replaceSymbols;
  10898. return replaceSymbols_1;
  10899. }
  10900. var extractICSS_1;
  10901. var hasRequiredExtractICSS;
  10902. function requireExtractICSS () {
  10903. if (hasRequiredExtractICSS) return extractICSS_1;
  10904. hasRequiredExtractICSS = 1;
  10905. const importPattern = /^:import\(("[^"]*"|'[^']*'|[^"']+)\)$/;
  10906. const balancedQuotes = /^("[^"]*"|'[^']*'|[^"']+)$/;
  10907. const getDeclsObject = (rule) => {
  10908. const object = {};
  10909. rule.walkDecls((decl) => {
  10910. const before = decl.raws.before ? decl.raws.before.trim() : "";
  10911. object[before + decl.prop] = decl.value;
  10912. });
  10913. return object;
  10914. };
  10915. /**
  10916. *
  10917. * @param {string} css
  10918. * @param {boolean} removeRules
  10919. * @param {'auto' | 'rule' | 'at-rule'} mode
  10920. */
  10921. const extractICSS = (css, removeRules = true, mode = "auto") => {
  10922. const icssImports = {};
  10923. const icssExports = {};
  10924. function addImports(node, path) {
  10925. const unquoted = path.replace(/'|"/g, "");
  10926. icssImports[unquoted] = Object.assign(
  10927. icssImports[unquoted] || {},
  10928. getDeclsObject(node)
  10929. );
  10930. if (removeRules) {
  10931. node.remove();
  10932. }
  10933. }
  10934. function addExports(node) {
  10935. Object.assign(icssExports, getDeclsObject(node));
  10936. if (removeRules) {
  10937. node.remove();
  10938. }
  10939. }
  10940. css.each((node) => {
  10941. if (node.type === "rule" && mode !== "at-rule") {
  10942. if (node.selector.slice(0, 7) === ":import") {
  10943. const matches = importPattern.exec(node.selector);
  10944. if (matches) {
  10945. addImports(node, matches[1]);
  10946. }
  10947. }
  10948. if (node.selector === ":export") {
  10949. addExports(node);
  10950. }
  10951. }
  10952. if (node.type === "atrule" && mode !== "rule") {
  10953. if (node.name === "icss-import") {
  10954. const matches = balancedQuotes.exec(node.params);
  10955. if (matches) {
  10956. addImports(node, matches[1]);
  10957. }
  10958. }
  10959. if (node.name === "icss-export") {
  10960. addExports(node);
  10961. }
  10962. }
  10963. });
  10964. return { icssImports, icssExports };
  10965. };
  10966. extractICSS_1 = extractICSS;
  10967. return extractICSS_1;
  10968. }
  10969. var createICSSRules_1;
  10970. var hasRequiredCreateICSSRules;
  10971. function requireCreateICSSRules () {
  10972. if (hasRequiredCreateICSSRules) return createICSSRules_1;
  10973. hasRequiredCreateICSSRules = 1;
  10974. const createImports = (imports, postcss, mode = "rule") => {
  10975. return Object.keys(imports).map((path) => {
  10976. const aliases = imports[path];
  10977. const declarations = Object.keys(aliases).map((key) =>
  10978. postcss.decl({
  10979. prop: key,
  10980. value: aliases[key],
  10981. raws: { before: "\n " },
  10982. })
  10983. );
  10984. const hasDeclarations = declarations.length > 0;
  10985. const rule =
  10986. mode === "rule"
  10987. ? postcss.rule({
  10988. selector: `:import('${path}')`,
  10989. raws: { after: hasDeclarations ? "\n" : "" },
  10990. })
  10991. : postcss.atRule({
  10992. name: "icss-import",
  10993. params: `'${path}'`,
  10994. raws: { after: hasDeclarations ? "\n" : "" },
  10995. });
  10996. if (hasDeclarations) {
  10997. rule.append(declarations);
  10998. }
  10999. return rule;
  11000. });
  11001. };
  11002. const createExports = (exports$1, postcss, mode = "rule") => {
  11003. const declarations = Object.keys(exports$1).map((key) =>
  11004. postcss.decl({
  11005. prop: key,
  11006. value: exports$1[key],
  11007. raws: { before: "\n " },
  11008. })
  11009. );
  11010. if (declarations.length === 0) {
  11011. return [];
  11012. }
  11013. const rule =
  11014. mode === "rule"
  11015. ? postcss.rule({
  11016. selector: `:export`,
  11017. raws: { after: "\n" },
  11018. })
  11019. : postcss.atRule({
  11020. name: "icss-export",
  11021. raws: { after: "\n" },
  11022. });
  11023. rule.append(declarations);
  11024. return [rule];
  11025. };
  11026. const createICSSRules = (imports, exports$1, postcss, mode) => [
  11027. ...createImports(imports, postcss, mode),
  11028. ...createExports(exports$1, postcss, mode),
  11029. ];
  11030. createICSSRules_1 = createICSSRules;
  11031. return createICSSRules_1;
  11032. }
  11033. var src$4;
  11034. var hasRequiredSrc$4;
  11035. function requireSrc$4 () {
  11036. if (hasRequiredSrc$4) return src$4;
  11037. hasRequiredSrc$4 = 1;
  11038. const replaceValueSymbols = /*@__PURE__*/ requireReplaceValueSymbols();
  11039. const replaceSymbols = /*@__PURE__*/ requireReplaceSymbols();
  11040. const extractICSS = /*@__PURE__*/ requireExtractICSS();
  11041. const createICSSRules = /*@__PURE__*/ requireCreateICSSRules();
  11042. src$4 = {
  11043. replaceValueSymbols,
  11044. replaceSymbols,
  11045. extractICSS,
  11046. createICSSRules,
  11047. };
  11048. return src$4;
  11049. }
  11050. var hasRequiredParser$1;
  11051. function requireParser$1 () {
  11052. if (hasRequiredParser$1) return Parser;
  11053. hasRequiredParser$1 = 1;
  11054. Object.defineProperty(Parser, "__esModule", {
  11055. value: true
  11056. });
  11057. Parser.default = void 0;
  11058. var _icssUtils = /*@__PURE__*/ requireSrc$4();
  11059. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  11060. const importRegexp = /^:import\((.+)\)$/;
  11061. let Parser$1 = class Parser {
  11062. constructor(pathFetcher, trace) {
  11063. this.pathFetcher = pathFetcher;
  11064. this.plugin = this.plugin.bind(this);
  11065. this.exportTokens = {};
  11066. this.translations = {};
  11067. this.trace = trace;
  11068. }
  11069. plugin() {
  11070. const parser = this;
  11071. return {
  11072. postcssPlugin: "css-modules-parser",
  11073. async OnceExit(css) {
  11074. await Promise.all(parser.fetchAllImports(css));
  11075. parser.linkImportedSymbols(css);
  11076. return parser.extractExports(css);
  11077. }
  11078. };
  11079. }
  11080. fetchAllImports(css) {
  11081. let imports = [];
  11082. css.each(node => {
  11083. if (node.type == "rule" && node.selector.match(importRegexp)) {
  11084. imports.push(this.fetchImport(node, css.source.input.from, imports.length));
  11085. }
  11086. });
  11087. return imports;
  11088. }
  11089. linkImportedSymbols(css) {
  11090. (0, _icssUtils.replaceSymbols)(css, this.translations);
  11091. }
  11092. extractExports(css) {
  11093. css.each(node => {
  11094. if (node.type == "rule" && node.selector == ":export") this.handleExport(node);
  11095. });
  11096. }
  11097. handleExport(exportNode) {
  11098. exportNode.each(decl => {
  11099. if (decl.type == "decl") {
  11100. Object.keys(this.translations).forEach(translation => {
  11101. decl.value = decl.value.replace(translation, this.translations[translation]);
  11102. });
  11103. this.exportTokens[decl.prop] = decl.value;
  11104. }
  11105. });
  11106. exportNode.remove();
  11107. }
  11108. async fetchImport(importNode, relativeTo, depNr) {
  11109. const file = importNode.selector.match(importRegexp)[1];
  11110. const depTrace = this.trace + String.fromCharCode(depNr);
  11111. const exports$1 = await this.pathFetcher(file, relativeTo, depTrace);
  11112. try {
  11113. importNode.each(decl => {
  11114. if (decl.type == "decl") {
  11115. this.translations[decl.prop] = exports$1[decl.value];
  11116. }
  11117. });
  11118. importNode.remove();
  11119. } catch (err) {
  11120. console.log(err);
  11121. }
  11122. }
  11123. };
  11124. Parser.default = Parser$1;
  11125. return Parser;
  11126. }
  11127. var saveJSON = {};
  11128. var hasRequiredSaveJSON;
  11129. function requireSaveJSON () {
  11130. if (hasRequiredSaveJSON) return saveJSON;
  11131. hasRequiredSaveJSON = 1;
  11132. Object.defineProperty(saveJSON, "__esModule", {
  11133. value: true
  11134. });
  11135. saveJSON.default = saveJSON$1;
  11136. var _fs = /*@__PURE__*/ requireFs();
  11137. function saveJSON$1(cssFile, json) {
  11138. return new Promise((resolve, reject) => {
  11139. const {
  11140. writeFile
  11141. } = (0, _fs.getFileSystem)();
  11142. writeFile(`${cssFile}.json`, JSON.stringify(json), e => e ? reject(e) : resolve(json));
  11143. });
  11144. }
  11145. return saveJSON;
  11146. }
  11147. var localsConvention = {};
  11148. /**
  11149. * lodash (Custom Build) <https://lodash.com/>
  11150. * Build: `lodash modularize exports="npm" -o ./`
  11151. * Copyright jQuery Foundation and other contributors <https://jquery.org/>
  11152. * Released under MIT license <https://lodash.com/license>
  11153. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  11154. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11155. */
  11156. var lodash_camelcase;
  11157. var hasRequiredLodash_camelcase;
  11158. function requireLodash_camelcase () {
  11159. if (hasRequiredLodash_camelcase) return lodash_camelcase;
  11160. hasRequiredLodash_camelcase = 1;
  11161. /** `Object#toString` result references. */
  11162. var symbolTag = '[object Symbol]';
  11163. /** Used to match words composed of alphanumeric characters. */
  11164. var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
  11165. /** Used to match Latin Unicode letters (excluding mathematical operators). */
  11166. var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
  11167. /** Used to compose unicode character classes. */
  11168. var rsAstralRange = '\\ud800-\\udfff',
  11169. rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23',
  11170. rsComboSymbolsRange = '\\u20d0-\\u20f0',
  11171. rsDingbatRange = '\\u2700-\\u27bf',
  11172. rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
  11173. rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
  11174. rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
  11175. rsPunctuationRange = '\\u2000-\\u206f',
  11176. 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',
  11177. rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
  11178. rsVarRange = '\\ufe0e\\ufe0f',
  11179. rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
  11180. /** Used to compose unicode capture groups. */
  11181. var rsApos = "['\u2019]",
  11182. rsAstral = '[' + rsAstralRange + ']',
  11183. rsBreak = '[' + rsBreakRange + ']',
  11184. rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']',
  11185. rsDigits = '\\d+',
  11186. rsDingbat = '[' + rsDingbatRange + ']',
  11187. rsLower = '[' + rsLowerRange + ']',
  11188. rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
  11189. rsFitz = '\\ud83c[\\udffb-\\udfff]',
  11190. rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
  11191. rsNonAstral = '[^' + rsAstralRange + ']',
  11192. rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
  11193. rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
  11194. rsUpper = '[' + rsUpperRange + ']',
  11195. rsZWJ = '\\u200d';
  11196. /** Used to compose unicode regexes. */
  11197. var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')',
  11198. rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')',
  11199. rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
  11200. rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
  11201. reOptMod = rsModifier + '?',
  11202. rsOptVar = '[' + rsVarRange + ']?',
  11203. rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
  11204. rsSeq = rsOptVar + reOptMod + rsOptJoin,
  11205. rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
  11206. rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
  11207. /** Used to match apostrophes. */
  11208. var reApos = RegExp(rsApos, 'g');
  11209. /**
  11210. * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
  11211. * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
  11212. */
  11213. var reComboMark = RegExp(rsCombo, 'g');
  11214. /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
  11215. var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
  11216. /** Used to match complex or compound words. */
  11217. var reUnicodeWord = RegExp([
  11218. rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
  11219. rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')',
  11220. rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr,
  11221. rsUpper + '+' + rsOptUpperContr,
  11222. rsDigits,
  11223. rsEmoji
  11224. ].join('|'), 'g');
  11225. /** 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/). */
  11226. var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']');
  11227. /** Used to detect strings that need a more robust regexp to match words. */
  11228. 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 ]/;
  11229. /** Used to map Latin Unicode letters to basic Latin letters. */
  11230. var deburredLetters = {
  11231. // Latin-1 Supplement block.
  11232. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
  11233. '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
  11234. '\xc7': 'C', '\xe7': 'c',
  11235. '\xd0': 'D', '\xf0': 'd',
  11236. '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
  11237. '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
  11238. '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
  11239. '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
  11240. '\xd1': 'N', '\xf1': 'n',
  11241. '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
  11242. '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
  11243. '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
  11244. '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
  11245. '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
  11246. '\xc6': 'Ae', '\xe6': 'ae',
  11247. '\xde': 'Th', '\xfe': 'th',
  11248. '\xdf': 'ss',
  11249. // Latin Extended-A block.
  11250. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
  11251. '\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
  11252. '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
  11253. '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
  11254. '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
  11255. '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
  11256. '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
  11257. '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
  11258. '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
  11259. '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
  11260. '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
  11261. '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
  11262. '\u0134': 'J', '\u0135': 'j',
  11263. '\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
  11264. '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
  11265. '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
  11266. '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
  11267. '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
  11268. '\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
  11269. '\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
  11270. '\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
  11271. '\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
  11272. '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
  11273. '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
  11274. '\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
  11275. '\u0163': 't', '\u0165': 't', '\u0167': 't',
  11276. '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
  11277. '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
  11278. '\u0174': 'W', '\u0175': 'w',
  11279. '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
  11280. '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
  11281. '\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
  11282. '\u0132': 'IJ', '\u0133': 'ij',
  11283. '\u0152': 'Oe', '\u0153': 'oe',
  11284. '\u0149': "'n", '\u017f': 'ss'
  11285. };
  11286. /** Detect free variable `global` from Node.js. */
  11287. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
  11288. /** Detect free variable `self`. */
  11289. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  11290. /** Used as a reference to the global object. */
  11291. var root = freeGlobal || freeSelf || Function('return this')();
  11292. /**
  11293. * A specialized version of `_.reduce` for arrays without support for
  11294. * iteratee shorthands.
  11295. *
  11296. * @private
  11297. * @param {Array} [array] The array to iterate over.
  11298. * @param {Function} iteratee The function invoked per iteration.
  11299. * @param {*} [accumulator] The initial value.
  11300. * @param {boolean} [initAccum] Specify using the first element of `array` as
  11301. * the initial value.
  11302. * @returns {*} Returns the accumulated value.
  11303. */
  11304. function arrayReduce(array, iteratee, accumulator, initAccum) {
  11305. var index = -1,
  11306. length = array ? array.length : 0;
  11307. while (++index < length) {
  11308. accumulator = iteratee(accumulator, array[index], index, array);
  11309. }
  11310. return accumulator;
  11311. }
  11312. /**
  11313. * Converts an ASCII `string` to an array.
  11314. *
  11315. * @private
  11316. * @param {string} string The string to convert.
  11317. * @returns {Array} Returns the converted array.
  11318. */
  11319. function asciiToArray(string) {
  11320. return string.split('');
  11321. }
  11322. /**
  11323. * Splits an ASCII `string` into an array of its words.
  11324. *
  11325. * @private
  11326. * @param {string} The string to inspect.
  11327. * @returns {Array} Returns the words of `string`.
  11328. */
  11329. function asciiWords(string) {
  11330. return string.match(reAsciiWord) || [];
  11331. }
  11332. /**
  11333. * The base implementation of `_.propertyOf` without support for deep paths.
  11334. *
  11335. * @private
  11336. * @param {Object} object The object to query.
  11337. * @returns {Function} Returns the new accessor function.
  11338. */
  11339. function basePropertyOf(object) {
  11340. return function(key) {
  11341. return object == null ? undefined : object[key];
  11342. };
  11343. }
  11344. /**
  11345. * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
  11346. * letters to basic Latin letters.
  11347. *
  11348. * @private
  11349. * @param {string} letter The matched letter to deburr.
  11350. * @returns {string} Returns the deburred letter.
  11351. */
  11352. var deburrLetter = basePropertyOf(deburredLetters);
  11353. /**
  11354. * Checks if `string` contains Unicode symbols.
  11355. *
  11356. * @private
  11357. * @param {string} string The string to inspect.
  11358. * @returns {boolean} Returns `true` if a symbol is found, else `false`.
  11359. */
  11360. function hasUnicode(string) {
  11361. return reHasUnicode.test(string);
  11362. }
  11363. /**
  11364. * Checks if `string` contains a word composed of Unicode symbols.
  11365. *
  11366. * @private
  11367. * @param {string} string The string to inspect.
  11368. * @returns {boolean} Returns `true` if a word is found, else `false`.
  11369. */
  11370. function hasUnicodeWord(string) {
  11371. return reHasUnicodeWord.test(string);
  11372. }
  11373. /**
  11374. * Converts `string` to an array.
  11375. *
  11376. * @private
  11377. * @param {string} string The string to convert.
  11378. * @returns {Array} Returns the converted array.
  11379. */
  11380. function stringToArray(string) {
  11381. return hasUnicode(string)
  11382. ? unicodeToArray(string)
  11383. : asciiToArray(string);
  11384. }
  11385. /**
  11386. * Converts a Unicode `string` to an array.
  11387. *
  11388. * @private
  11389. * @param {string} string The string to convert.
  11390. * @returns {Array} Returns the converted array.
  11391. */
  11392. function unicodeToArray(string) {
  11393. return string.match(reUnicode) || [];
  11394. }
  11395. /**
  11396. * Splits a Unicode `string` into an array of its words.
  11397. *
  11398. * @private
  11399. * @param {string} The string to inspect.
  11400. * @returns {Array} Returns the words of `string`.
  11401. */
  11402. function unicodeWords(string) {
  11403. return string.match(reUnicodeWord) || [];
  11404. }
  11405. /** Used for built-in method references. */
  11406. var objectProto = Object.prototype;
  11407. /**
  11408. * Used to resolve the
  11409. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  11410. * of values.
  11411. */
  11412. var objectToString = objectProto.toString;
  11413. /** Built-in value references. */
  11414. var Symbol = root.Symbol;
  11415. /** Used to convert symbols to primitives and strings. */
  11416. var symbolProto = Symbol ? Symbol.prototype : undefined,
  11417. symbolToString = symbolProto ? symbolProto.toString : undefined;
  11418. /**
  11419. * The base implementation of `_.slice` without an iteratee call guard.
  11420. *
  11421. * @private
  11422. * @param {Array} array The array to slice.
  11423. * @param {number} [start=0] The start position.
  11424. * @param {number} [end=array.length] The end position.
  11425. * @returns {Array} Returns the slice of `array`.
  11426. */
  11427. function baseSlice(array, start, end) {
  11428. var index = -1,
  11429. length = array.length;
  11430. if (start < 0) {
  11431. start = -start > length ? 0 : (length + start);
  11432. }
  11433. end = end > length ? length : end;
  11434. if (end < 0) {
  11435. end += length;
  11436. }
  11437. length = start > end ? 0 : ((end - start) >>> 0);
  11438. start >>>= 0;
  11439. var result = Array(length);
  11440. while (++index < length) {
  11441. result[index] = array[index + start];
  11442. }
  11443. return result;
  11444. }
  11445. /**
  11446. * The base implementation of `_.toString` which doesn't convert nullish
  11447. * values to empty strings.
  11448. *
  11449. * @private
  11450. * @param {*} value The value to process.
  11451. * @returns {string} Returns the string.
  11452. */
  11453. function baseToString(value) {
  11454. // Exit early for strings to avoid a performance hit in some environments.
  11455. if (typeof value == 'string') {
  11456. return value;
  11457. }
  11458. if (isSymbol(value)) {
  11459. return symbolToString ? symbolToString.call(value) : '';
  11460. }
  11461. var result = (value + '');
  11462. return (result == '0' && (1 / value) == -Infinity) ? '-0' : result;
  11463. }
  11464. /**
  11465. * Casts `array` to a slice if it's needed.
  11466. *
  11467. * @private
  11468. * @param {Array} array The array to inspect.
  11469. * @param {number} start The start position.
  11470. * @param {number} [end=array.length] The end position.
  11471. * @returns {Array} Returns the cast slice.
  11472. */
  11473. function castSlice(array, start, end) {
  11474. var length = array.length;
  11475. end = end === undefined ? length : end;
  11476. return (!start && end >= length) ? array : baseSlice(array, start, end);
  11477. }
  11478. /**
  11479. * Creates a function like `_.lowerFirst`.
  11480. *
  11481. * @private
  11482. * @param {string} methodName The name of the `String` case method to use.
  11483. * @returns {Function} Returns the new case function.
  11484. */
  11485. function createCaseFirst(methodName) {
  11486. return function(string) {
  11487. string = toString(string);
  11488. var strSymbols = hasUnicode(string)
  11489. ? stringToArray(string)
  11490. : undefined;
  11491. var chr = strSymbols
  11492. ? strSymbols[0]
  11493. : string.charAt(0);
  11494. var trailing = strSymbols
  11495. ? castSlice(strSymbols, 1).join('')
  11496. : string.slice(1);
  11497. return chr[methodName]() + trailing;
  11498. };
  11499. }
  11500. /**
  11501. * Creates a function like `_.camelCase`.
  11502. *
  11503. * @private
  11504. * @param {Function} callback The function to combine each word.
  11505. * @returns {Function} Returns the new compounder function.
  11506. */
  11507. function createCompounder(callback) {
  11508. return function(string) {
  11509. return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
  11510. };
  11511. }
  11512. /**
  11513. * Checks if `value` is object-like. A value is object-like if it's not `null`
  11514. * and has a `typeof` result of "object".
  11515. *
  11516. * @static
  11517. * @memberOf _
  11518. * @since 4.0.0
  11519. * @category Lang
  11520. * @param {*} value The value to check.
  11521. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  11522. * @example
  11523. *
  11524. * _.isObjectLike({});
  11525. * // => true
  11526. *
  11527. * _.isObjectLike([1, 2, 3]);
  11528. * // => true
  11529. *
  11530. * _.isObjectLike(_.noop);
  11531. * // => false
  11532. *
  11533. * _.isObjectLike(null);
  11534. * // => false
  11535. */
  11536. function isObjectLike(value) {
  11537. return !!value && typeof value == 'object';
  11538. }
  11539. /**
  11540. * Checks if `value` is classified as a `Symbol` primitive or object.
  11541. *
  11542. * @static
  11543. * @memberOf _
  11544. * @since 4.0.0
  11545. * @category Lang
  11546. * @param {*} value The value to check.
  11547. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  11548. * @example
  11549. *
  11550. * _.isSymbol(Symbol.iterator);
  11551. * // => true
  11552. *
  11553. * _.isSymbol('abc');
  11554. * // => false
  11555. */
  11556. function isSymbol(value) {
  11557. return typeof value == 'symbol' ||
  11558. (isObjectLike(value) && objectToString.call(value) == symbolTag);
  11559. }
  11560. /**
  11561. * Converts `value` to a string. An empty string is returned for `null`
  11562. * and `undefined` values. The sign of `-0` is preserved.
  11563. *
  11564. * @static
  11565. * @memberOf _
  11566. * @since 4.0.0
  11567. * @category Lang
  11568. * @param {*} value The value to process.
  11569. * @returns {string} Returns the string.
  11570. * @example
  11571. *
  11572. * _.toString(null);
  11573. * // => ''
  11574. *
  11575. * _.toString(-0);
  11576. * // => '-0'
  11577. *
  11578. * _.toString([1, 2, 3]);
  11579. * // => '1,2,3'
  11580. */
  11581. function toString(value) {
  11582. return value == null ? '' : baseToString(value);
  11583. }
  11584. /**
  11585. * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
  11586. *
  11587. * @static
  11588. * @memberOf _
  11589. * @since 3.0.0
  11590. * @category String
  11591. * @param {string} [string=''] The string to convert.
  11592. * @returns {string} Returns the camel cased string.
  11593. * @example
  11594. *
  11595. * _.camelCase('Foo Bar');
  11596. * // => 'fooBar'
  11597. *
  11598. * _.camelCase('--foo-bar--');
  11599. * // => 'fooBar'
  11600. *
  11601. * _.camelCase('__FOO_BAR__');
  11602. * // => 'fooBar'
  11603. */
  11604. var camelCase = createCompounder(function(result, word, index) {
  11605. word = word.toLowerCase();
  11606. return result + (index ? capitalize(word) : word);
  11607. });
  11608. /**
  11609. * Converts the first character of `string` to upper case and the remaining
  11610. * to lower case.
  11611. *
  11612. * @static
  11613. * @memberOf _
  11614. * @since 3.0.0
  11615. * @category String
  11616. * @param {string} [string=''] The string to capitalize.
  11617. * @returns {string} Returns the capitalized string.
  11618. * @example
  11619. *
  11620. * _.capitalize('FRED');
  11621. * // => 'Fred'
  11622. */
  11623. function capitalize(string) {
  11624. return upperFirst(toString(string).toLowerCase());
  11625. }
  11626. /**
  11627. * Deburrs `string` by converting
  11628. * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
  11629. * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
  11630. * letters to basic Latin letters and removing
  11631. * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
  11632. *
  11633. * @static
  11634. * @memberOf _
  11635. * @since 3.0.0
  11636. * @category String
  11637. * @param {string} [string=''] The string to deburr.
  11638. * @returns {string} Returns the deburred string.
  11639. * @example
  11640. *
  11641. * _.deburr('déjà vu');
  11642. * // => 'deja vu'
  11643. */
  11644. function deburr(string) {
  11645. string = toString(string);
  11646. return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
  11647. }
  11648. /**
  11649. * Converts the first character of `string` to upper case.
  11650. *
  11651. * @static
  11652. * @memberOf _
  11653. * @since 4.0.0
  11654. * @category String
  11655. * @param {string} [string=''] The string to convert.
  11656. * @returns {string} Returns the converted string.
  11657. * @example
  11658. *
  11659. * _.upperFirst('fred');
  11660. * // => 'Fred'
  11661. *
  11662. * _.upperFirst('FRED');
  11663. * // => 'FRED'
  11664. */
  11665. var upperFirst = createCaseFirst('toUpperCase');
  11666. /**
  11667. * Splits `string` into an array of its words.
  11668. *
  11669. * @static
  11670. * @memberOf _
  11671. * @since 3.0.0
  11672. * @category String
  11673. * @param {string} [string=''] The string to inspect.
  11674. * @param {RegExp|string} [pattern] The pattern to match words.
  11675. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  11676. * @returns {Array} Returns the words of `string`.
  11677. * @example
  11678. *
  11679. * _.words('fred, barney, & pebbles');
  11680. * // => ['fred', 'barney', 'pebbles']
  11681. *
  11682. * _.words('fred, barney, & pebbles', /[^, ]+/g);
  11683. * // => ['fred', 'barney', '&', 'pebbles']
  11684. */
  11685. function words(string, pattern, guard) {
  11686. string = toString(string);
  11687. pattern = pattern;
  11688. if (pattern === undefined) {
  11689. return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
  11690. }
  11691. return string.match(pattern) || [];
  11692. }
  11693. lodash_camelcase = camelCase;
  11694. return lodash_camelcase;
  11695. }
  11696. var hasRequiredLocalsConvention;
  11697. function requireLocalsConvention () {
  11698. if (hasRequiredLocalsConvention) return localsConvention;
  11699. hasRequiredLocalsConvention = 1;
  11700. Object.defineProperty(localsConvention, "__esModule", {
  11701. value: true
  11702. });
  11703. localsConvention.makeLocalsConventionReducer = makeLocalsConventionReducer;
  11704. var _lodash = _interopRequireDefault(/*@__PURE__*/ requireLodash_camelcase());
  11705. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11706. function dashesCamelCase(string) {
  11707. return string.replace(/-+(\w)/g, (_, firstLetter) => firstLetter.toUpperCase());
  11708. }
  11709. function makeLocalsConventionReducer(localsConvention, inputFile) {
  11710. const isFunc = typeof localsConvention === "function";
  11711. return (tokens, [className, value]) => {
  11712. if (isFunc) {
  11713. const convention = localsConvention(className, value, inputFile);
  11714. tokens[convention] = value;
  11715. return tokens;
  11716. }
  11717. switch (localsConvention) {
  11718. case "camelCase":
  11719. tokens[className] = value;
  11720. tokens[(0, _lodash.default)(className)] = value;
  11721. break;
  11722. case "camelCaseOnly":
  11723. tokens[(0, _lodash.default)(className)] = value;
  11724. break;
  11725. case "dashes":
  11726. tokens[className] = value;
  11727. tokens[dashesCamelCase(className)] = value;
  11728. break;
  11729. case "dashesOnly":
  11730. tokens[dashesCamelCase(className)] = value;
  11731. break;
  11732. }
  11733. return tokens;
  11734. };
  11735. }
  11736. return localsConvention;
  11737. }
  11738. var FileSystemLoader = {};
  11739. var hasRequiredFileSystemLoader;
  11740. function requireFileSystemLoader () {
  11741. if (hasRequiredFileSystemLoader) return FileSystemLoader;
  11742. hasRequiredFileSystemLoader = 1;
  11743. Object.defineProperty(FileSystemLoader, "__esModule", {
  11744. value: true
  11745. });
  11746. FileSystemLoader.default = void 0;
  11747. var _postcss = _interopRequireDefault(require$$0$1);
  11748. var _path = _interopRequireDefault(path$1);
  11749. var _Parser = _interopRequireDefault(/*@__PURE__*/ requireParser$1());
  11750. var _fs = /*@__PURE__*/ requireFs();
  11751. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11752. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  11753. class Core {
  11754. constructor(plugins) {
  11755. this.plugins = plugins || Core.defaultPlugins;
  11756. }
  11757. async load(sourceString, sourcePath, trace, pathFetcher) {
  11758. const parser = new _Parser.default(pathFetcher, trace);
  11759. const plugins = this.plugins.concat([parser.plugin()]);
  11760. const result = await (0, _postcss.default)(plugins).process(sourceString, {
  11761. from: sourcePath
  11762. });
  11763. return {
  11764. injectableSource: result.css,
  11765. exportTokens: parser.exportTokens
  11766. };
  11767. }
  11768. } // Sorts dependencies in the following way:
  11769. // AAA comes before AA and A
  11770. // AB comes after AA and before A
  11771. // All Bs come after all As
  11772. // This ensures that the files are always returned in the following order:
  11773. // - In the order they were required, except
  11774. // - After all their dependencies
  11775. const traceKeySorter = (a, b) => {
  11776. if (a.length < b.length) {
  11777. return a < b.substring(0, a.length) ? -1 : 1;
  11778. }
  11779. if (a.length > b.length) {
  11780. return a.substring(0, b.length) <= b ? -1 : 1;
  11781. }
  11782. return a < b ? -1 : 1;
  11783. };
  11784. let FileSystemLoader$1 = class FileSystemLoader {
  11785. constructor(root, plugins, fileResolve) {
  11786. if (root === "/" && process.platform === "win32") {
  11787. const cwdDrive = process.cwd().slice(0, 3);
  11788. if (!/^[A-Za-z]:\\$/.test(cwdDrive)) {
  11789. throw new Error(`Failed to obtain root from "${process.cwd()}".`);
  11790. }
  11791. root = cwdDrive;
  11792. }
  11793. this.root = root;
  11794. this.fileResolve = fileResolve;
  11795. this.sources = {};
  11796. this.traces = {};
  11797. this.importNr = 0;
  11798. this.core = new Core(plugins);
  11799. this.tokensByFile = {};
  11800. this.fs = (0, _fs.getFileSystem)();
  11801. }
  11802. async fetch(_newPath, relativeTo, _trace) {
  11803. const newPath = _newPath.replace(/^["']|["']$/g, "");
  11804. const trace = _trace || String.fromCharCode(this.importNr++);
  11805. const useFileResolve = typeof this.fileResolve === "function";
  11806. const fileResolvedPath = useFileResolve ? await this.fileResolve(newPath, relativeTo) : await Promise.resolve();
  11807. if (fileResolvedPath && !_path.default.isAbsolute(fileResolvedPath)) {
  11808. throw new Error('The returned path from the "fileResolve" option must be absolute.');
  11809. }
  11810. const relativeDir = _path.default.dirname(relativeTo);
  11811. const rootRelativePath = fileResolvedPath || _path.default.resolve(relativeDir, newPath);
  11812. 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
  11813. if (!useFileResolve && newPath[0] !== "." && !_path.default.isAbsolute(newPath)) {
  11814. try {
  11815. fileRelativePath = require.resolve(newPath);
  11816. } catch (e) {// noop
  11817. }
  11818. }
  11819. const tokens = this.tokensByFile[fileRelativePath];
  11820. if (tokens) return tokens;
  11821. return new Promise((resolve, reject) => {
  11822. this.fs.readFile(fileRelativePath, "utf-8", async (err, source) => {
  11823. if (err) reject(err);
  11824. const {
  11825. injectableSource,
  11826. exportTokens
  11827. } = await this.core.load(source, rootRelativePath, trace, this.fetch.bind(this));
  11828. this.sources[fileRelativePath] = injectableSource;
  11829. this.traces[trace] = fileRelativePath;
  11830. this.tokensByFile[fileRelativePath] = exportTokens;
  11831. resolve(exportTokens);
  11832. });
  11833. });
  11834. }
  11835. get finalSource() {
  11836. const traces = this.traces;
  11837. const sources = this.sources;
  11838. let written = new Set();
  11839. return Object.keys(traces).sort(traceKeySorter).map(key => {
  11840. const filename = traces[key];
  11841. if (written.has(filename)) {
  11842. return null;
  11843. }
  11844. written.add(filename);
  11845. return sources[filename];
  11846. }).join("");
  11847. }
  11848. };
  11849. FileSystemLoader.default = FileSystemLoader$1;
  11850. return FileSystemLoader;
  11851. }
  11852. var scoping = {};
  11853. var src$3 = {exports: {}};
  11854. var topologicalSort_1;
  11855. var hasRequiredTopologicalSort;
  11856. function requireTopologicalSort () {
  11857. if (hasRequiredTopologicalSort) return topologicalSort_1;
  11858. hasRequiredTopologicalSort = 1;
  11859. const PERMANENT_MARKER = 2;
  11860. const TEMPORARY_MARKER = 1;
  11861. function createError(node, graph) {
  11862. const er = new Error("Nondeterministic import's order");
  11863. const related = graph[node];
  11864. const relatedNode = related.find(
  11865. (relatedNode) => graph[relatedNode].indexOf(node) > -1
  11866. );
  11867. er.nodes = [node, relatedNode];
  11868. return er;
  11869. }
  11870. function walkGraph(node, graph, state, result, strict) {
  11871. if (state[node] === PERMANENT_MARKER) {
  11872. return;
  11873. }
  11874. if (state[node] === TEMPORARY_MARKER) {
  11875. if (strict) {
  11876. return createError(node, graph);
  11877. }
  11878. return;
  11879. }
  11880. state[node] = TEMPORARY_MARKER;
  11881. const children = graph[node];
  11882. const length = children.length;
  11883. for (let i = 0; i < length; ++i) {
  11884. const error = walkGraph(children[i], graph, state, result, strict);
  11885. if (error instanceof Error) {
  11886. return error;
  11887. }
  11888. }
  11889. state[node] = PERMANENT_MARKER;
  11890. result.push(node);
  11891. }
  11892. function topologicalSort(graph, strict) {
  11893. const result = [];
  11894. const state = {};
  11895. const nodes = Object.keys(graph);
  11896. const length = nodes.length;
  11897. for (let i = 0; i < length; ++i) {
  11898. const er = walkGraph(nodes[i], graph, state, result, strict);
  11899. if (er instanceof Error) {
  11900. return er;
  11901. }
  11902. }
  11903. return result;
  11904. }
  11905. topologicalSort_1 = topologicalSort;
  11906. return topologicalSort_1;
  11907. }
  11908. var hasRequiredSrc$3;
  11909. function requireSrc$3 () {
  11910. if (hasRequiredSrc$3) return src$3.exports;
  11911. hasRequiredSrc$3 = 1;
  11912. const topologicalSort = /*@__PURE__*/ requireTopologicalSort();
  11913. const matchImports = /^(.+?)\s+from\s+(?:"([^"]+)"|'([^']+)'|(global))$/;
  11914. const icssImport = /^:import\((?:"([^"]+)"|'([^']+)')\)/;
  11915. const VISITED_MARKER = 1;
  11916. /**
  11917. * :import('G') {}
  11918. *
  11919. * Rule
  11920. * composes: ... from 'A'
  11921. * composes: ... from 'B'
  11922. * Rule
  11923. * composes: ... from 'A'
  11924. * composes: ... from 'A'
  11925. * composes: ... from 'C'
  11926. *
  11927. * Results in:
  11928. *
  11929. * graph: {
  11930. * G: [],
  11931. * A: [],
  11932. * B: ['A'],
  11933. * C: ['A'],
  11934. * }
  11935. */
  11936. function addImportToGraph(importId, parentId, graph, visited) {
  11937. const siblingsId = parentId + "_" + "siblings";
  11938. const visitedId = parentId + "_" + importId;
  11939. if (visited[visitedId] !== VISITED_MARKER) {
  11940. if (!Array.isArray(visited[siblingsId])) {
  11941. visited[siblingsId] = [];
  11942. }
  11943. const siblings = visited[siblingsId];
  11944. if (Array.isArray(graph[importId])) {
  11945. graph[importId] = graph[importId].concat(siblings);
  11946. } else {
  11947. graph[importId] = siblings.slice();
  11948. }
  11949. visited[visitedId] = VISITED_MARKER;
  11950. siblings.push(importId);
  11951. }
  11952. }
  11953. src$3.exports = (options = {}) => {
  11954. let importIndex = 0;
  11955. const createImportedName =
  11956. typeof options.createImportedName !== "function"
  11957. ? (importName /*, path*/) =>
  11958. `i__imported_${importName.replace(/\W/g, "_")}_${importIndex++}`
  11959. : options.createImportedName;
  11960. const failOnWrongOrder = options.failOnWrongOrder;
  11961. return {
  11962. postcssPlugin: "postcss-modules-extract-imports",
  11963. prepare() {
  11964. const graph = {};
  11965. const visited = {};
  11966. const existingImports = {};
  11967. const importDecls = {};
  11968. const imports = {};
  11969. return {
  11970. Once(root, postcss) {
  11971. // Check the existing imports order and save refs
  11972. root.walkRules((rule) => {
  11973. const matches = icssImport.exec(rule.selector);
  11974. if (matches) {
  11975. const [, /*match*/ doubleQuotePath, singleQuotePath] = matches;
  11976. const importPath = doubleQuotePath || singleQuotePath;
  11977. addImportToGraph(importPath, "root", graph, visited);
  11978. existingImports[importPath] = rule;
  11979. }
  11980. });
  11981. root.walkDecls(/^composes$/, (declaration) => {
  11982. const multiple = declaration.value.split(",");
  11983. const values = [];
  11984. multiple.forEach((value) => {
  11985. const matches = value.trim().match(matchImports);
  11986. if (!matches) {
  11987. values.push(value);
  11988. return;
  11989. }
  11990. let tmpSymbols;
  11991. let [
  11992. ,
  11993. /*match*/ symbols,
  11994. doubleQuotePath,
  11995. singleQuotePath,
  11996. global,
  11997. ] = matches;
  11998. if (global) {
  11999. // Composing globals simply means changing these classes to wrap them in global(name)
  12000. tmpSymbols = symbols.split(/\s+/).map((s) => `global(${s})`);
  12001. } else {
  12002. const importPath = doubleQuotePath || singleQuotePath;
  12003. let parent = declaration.parent;
  12004. let parentIndexes = "";
  12005. while (parent.type !== "root") {
  12006. parentIndexes =
  12007. parent.parent.index(parent) + "_" + parentIndexes;
  12008. parent = parent.parent;
  12009. }
  12010. const { selector } = declaration.parent;
  12011. const parentRule = `_${parentIndexes}${selector}`;
  12012. addImportToGraph(importPath, parentRule, graph, visited);
  12013. importDecls[importPath] = declaration;
  12014. imports[importPath] = imports[importPath] || {};
  12015. tmpSymbols = symbols.split(/\s+/).map((s) => {
  12016. if (!imports[importPath][s]) {
  12017. imports[importPath][s] = createImportedName(s, importPath);
  12018. }
  12019. return imports[importPath][s];
  12020. });
  12021. }
  12022. values.push(tmpSymbols.join(" "));
  12023. });
  12024. declaration.value = values.join(", ");
  12025. });
  12026. const importsOrder = topologicalSort(graph, failOnWrongOrder);
  12027. if (importsOrder instanceof Error) {
  12028. const importPath = importsOrder.nodes.find((importPath) =>
  12029. // eslint-disable-next-line no-prototype-builtins
  12030. importDecls.hasOwnProperty(importPath)
  12031. );
  12032. const decl = importDecls[importPath];
  12033. throw decl.error(
  12034. "Failed to resolve order of composed modules " +
  12035. importsOrder.nodes
  12036. .map((importPath) => "`" + importPath + "`")
  12037. .join(", ") +
  12038. ".",
  12039. {
  12040. plugin: "postcss-modules-extract-imports",
  12041. word: "composes",
  12042. }
  12043. );
  12044. }
  12045. let lastImportRule;
  12046. importsOrder.forEach((path) => {
  12047. const importedSymbols = imports[path];
  12048. let rule = existingImports[path];
  12049. if (!rule && importedSymbols) {
  12050. rule = postcss.rule({
  12051. selector: `:import("${path}")`,
  12052. raws: { after: "\n" },
  12053. });
  12054. if (lastImportRule) {
  12055. root.insertAfter(lastImportRule, rule);
  12056. } else {
  12057. root.prepend(rule);
  12058. }
  12059. }
  12060. lastImportRule = rule;
  12061. if (!importedSymbols) {
  12062. return;
  12063. }
  12064. Object.keys(importedSymbols).forEach((importedSymbol) => {
  12065. rule.append(
  12066. postcss.decl({
  12067. value: importedSymbol,
  12068. prop: importedSymbols[importedSymbol],
  12069. raws: { before: "\n " },
  12070. })
  12071. );
  12072. });
  12073. });
  12074. },
  12075. };
  12076. },
  12077. };
  12078. };
  12079. src$3.exports.postcss = true;
  12080. return src$3.exports;
  12081. }
  12082. var wasmHash = {exports: {}};
  12083. /*
  12084. MIT License http://www.opensource.org/licenses/mit-license.php
  12085. Author Tobias Koppers @sokra
  12086. */
  12087. var hasRequiredWasmHash;
  12088. function requireWasmHash () {
  12089. if (hasRequiredWasmHash) return wasmHash.exports;
  12090. hasRequiredWasmHash = 1;
  12091. // 65536 is the size of a wasm memory page
  12092. // 64 is the maximum chunk size for every possible wasm hash implementation
  12093. // 4 is the maximum number of bytes per char for string encoding (max is utf-8)
  12094. // ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64
  12095. const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & -4;
  12096. class WasmHash {
  12097. /**
  12098. * @param {WebAssembly.Instance} instance wasm instance
  12099. * @param {WebAssembly.Instance[]} instancesPool pool of instances
  12100. * @param {number} chunkSize size of data chunks passed to wasm
  12101. * @param {number} digestSize size of digest returned by wasm
  12102. */
  12103. constructor(instance, instancesPool, chunkSize, digestSize) {
  12104. const exports$1 = /** @type {any} */ (instance.exports);
  12105. exports$1.init();
  12106. this.exports = exports$1;
  12107. this.mem = Buffer.from(exports$1.memory.buffer, 0, 65536);
  12108. this.buffered = 0;
  12109. this.instancesPool = instancesPool;
  12110. this.chunkSize = chunkSize;
  12111. this.digestSize = digestSize;
  12112. }
  12113. reset() {
  12114. this.buffered = 0;
  12115. this.exports.init();
  12116. }
  12117. /**
  12118. * @param {Buffer | string} data data
  12119. * @param {BufferEncoding=} encoding encoding
  12120. * @returns {this} itself
  12121. */
  12122. update(data, encoding) {
  12123. if (typeof data === "string") {
  12124. while (data.length > MAX_SHORT_STRING) {
  12125. this._updateWithShortString(data.slice(0, MAX_SHORT_STRING), encoding);
  12126. data = data.slice(MAX_SHORT_STRING);
  12127. }
  12128. this._updateWithShortString(data, encoding);
  12129. return this;
  12130. }
  12131. this._updateWithBuffer(data);
  12132. return this;
  12133. }
  12134. /**
  12135. * @param {string} data data
  12136. * @param {BufferEncoding=} encoding encoding
  12137. * @returns {void}
  12138. */
  12139. _updateWithShortString(data, encoding) {
  12140. const { exports: exports$1, buffered, mem, chunkSize } = this;
  12141. let endPos;
  12142. if (data.length < 70) {
  12143. if (!encoding || encoding === "utf-8" || encoding === "utf8") {
  12144. endPos = buffered;
  12145. for (let i = 0; i < data.length; i++) {
  12146. const cc = data.charCodeAt(i);
  12147. if (cc < 0x80) {
  12148. mem[endPos++] = cc;
  12149. } else if (cc < 0x800) {
  12150. mem[endPos] = (cc >> 6) | 0xc0;
  12151. mem[endPos + 1] = (cc & 0x3f) | 0x80;
  12152. endPos += 2;
  12153. } else {
  12154. // bail-out for weird chars
  12155. endPos += mem.write(data.slice(i), endPos, encoding);
  12156. break;
  12157. }
  12158. }
  12159. } else if (encoding === "latin1") {
  12160. endPos = buffered;
  12161. for (let i = 0; i < data.length; i++) {
  12162. const cc = data.charCodeAt(i);
  12163. mem[endPos++] = cc;
  12164. }
  12165. } else {
  12166. endPos = buffered + mem.write(data, buffered, encoding);
  12167. }
  12168. } else {
  12169. endPos = buffered + mem.write(data, buffered, encoding);
  12170. }
  12171. if (endPos < chunkSize) {
  12172. this.buffered = endPos;
  12173. } else {
  12174. const l = endPos & ~(this.chunkSize - 1);
  12175. exports$1.update(l);
  12176. const newBuffered = endPos - l;
  12177. this.buffered = newBuffered;
  12178. if (newBuffered > 0) {
  12179. mem.copyWithin(0, l, endPos);
  12180. }
  12181. }
  12182. }
  12183. /**
  12184. * @param {Buffer} data data
  12185. * @returns {void}
  12186. */
  12187. _updateWithBuffer(data) {
  12188. const { exports: exports$1, buffered, mem } = this;
  12189. const length = data.length;
  12190. if (buffered + length < this.chunkSize) {
  12191. data.copy(mem, buffered, 0, length);
  12192. this.buffered += length;
  12193. } else {
  12194. const l = (buffered + length) & ~(this.chunkSize - 1);
  12195. if (l > 65536) {
  12196. let i = 65536 - buffered;
  12197. data.copy(mem, buffered, 0, i);
  12198. exports$1.update(65536);
  12199. const stop = l - buffered - 65536;
  12200. while (i < stop) {
  12201. data.copy(mem, 0, i, i + 65536);
  12202. exports$1.update(65536);
  12203. i += 65536;
  12204. }
  12205. data.copy(mem, 0, i, l - buffered);
  12206. exports$1.update(l - buffered - i);
  12207. } else {
  12208. data.copy(mem, buffered, 0, l - buffered);
  12209. exports$1.update(l);
  12210. }
  12211. const newBuffered = length + buffered - l;
  12212. this.buffered = newBuffered;
  12213. if (newBuffered > 0) {
  12214. data.copy(mem, 0, length - newBuffered, length);
  12215. }
  12216. }
  12217. }
  12218. digest(type) {
  12219. const { exports: exports$1, buffered, mem, digestSize } = this;
  12220. exports$1.final(buffered);
  12221. this.instancesPool.push(this);
  12222. const hex = mem.toString("latin1", 0, digestSize);
  12223. if (type === "hex") {
  12224. return hex;
  12225. }
  12226. if (type === "binary" || !type) {
  12227. return Buffer.from(hex, "hex");
  12228. }
  12229. return Buffer.from(hex, "hex").toString(type);
  12230. }
  12231. }
  12232. const create = (wasmModule, instancesPool, chunkSize, digestSize) => {
  12233. if (instancesPool.length > 0) {
  12234. const old = instancesPool.pop();
  12235. old.reset();
  12236. return old;
  12237. } else {
  12238. return new WasmHash(
  12239. new WebAssembly.Instance(wasmModule),
  12240. instancesPool,
  12241. chunkSize,
  12242. digestSize
  12243. );
  12244. }
  12245. };
  12246. wasmHash.exports = create;
  12247. wasmHash.exports.MAX_SHORT_STRING = MAX_SHORT_STRING;
  12248. return wasmHash.exports;
  12249. }
  12250. /*
  12251. MIT License http://www.opensource.org/licenses/mit-license.php
  12252. Author Tobias Koppers @sokra
  12253. */
  12254. var xxhash64_1;
  12255. var hasRequiredXxhash64;
  12256. function requireXxhash64 () {
  12257. if (hasRequiredXxhash64) return xxhash64_1;
  12258. hasRequiredXxhash64 = 1;
  12259. const create = /*@__PURE__*/ requireWasmHash();
  12260. //#region wasm code: xxhash64 (../../../assembly/hash/xxhash64.asm.ts) --initialMemory 1
  12261. const xxhash64 = new WebAssembly.Module(
  12262. Buffer.from(
  12263. // 1173 bytes
  12264. "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",
  12265. "base64"
  12266. )
  12267. );
  12268. //#endregion
  12269. xxhash64_1 = create.bind(null, xxhash64, [], 32, 16);
  12270. return xxhash64_1;
  12271. }
  12272. var BatchedHash_1;
  12273. var hasRequiredBatchedHash;
  12274. function requireBatchedHash () {
  12275. if (hasRequiredBatchedHash) return BatchedHash_1;
  12276. hasRequiredBatchedHash = 1;
  12277. const MAX_SHORT_STRING = /*@__PURE__*/ requireWasmHash().MAX_SHORT_STRING;
  12278. class BatchedHash {
  12279. constructor(hash) {
  12280. this.string = undefined;
  12281. this.encoding = undefined;
  12282. this.hash = hash;
  12283. }
  12284. /**
  12285. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  12286. * @param {string|Buffer} data data
  12287. * @param {string=} inputEncoding data encoding
  12288. * @returns {this} updated hash
  12289. */
  12290. update(data, inputEncoding) {
  12291. if (this.string !== undefined) {
  12292. if (
  12293. typeof data === "string" &&
  12294. inputEncoding === this.encoding &&
  12295. this.string.length + data.length < MAX_SHORT_STRING
  12296. ) {
  12297. this.string += data;
  12298. return this;
  12299. }
  12300. this.hash.update(this.string, this.encoding);
  12301. this.string = undefined;
  12302. }
  12303. if (typeof data === "string") {
  12304. if (
  12305. data.length < MAX_SHORT_STRING &&
  12306. // base64 encoding is not valid since it may contain padding chars
  12307. (!inputEncoding || !inputEncoding.startsWith("ba"))
  12308. ) {
  12309. this.string = data;
  12310. this.encoding = inputEncoding;
  12311. } else {
  12312. this.hash.update(data, inputEncoding);
  12313. }
  12314. } else {
  12315. this.hash.update(data);
  12316. }
  12317. return this;
  12318. }
  12319. /**
  12320. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  12321. * @param {string=} encoding encoding of the return value
  12322. * @returns {string|Buffer} digest
  12323. */
  12324. digest(encoding) {
  12325. if (this.string !== undefined) {
  12326. this.hash.update(this.string, this.encoding);
  12327. }
  12328. return this.hash.digest(encoding);
  12329. }
  12330. }
  12331. BatchedHash_1 = BatchedHash;
  12332. return BatchedHash_1;
  12333. }
  12334. /*
  12335. MIT License http://www.opensource.org/licenses/mit-license.php
  12336. Author Tobias Koppers @sokra
  12337. */
  12338. var md4_1;
  12339. var hasRequiredMd4;
  12340. function requireMd4 () {
  12341. if (hasRequiredMd4) return md4_1;
  12342. hasRequiredMd4 = 1;
  12343. const create = /*@__PURE__*/ requireWasmHash();
  12344. //#region wasm code: md4 (../../../assembly/hash/md4.asm.ts) --initialMemory 1
  12345. const md4 = new WebAssembly.Module(
  12346. Buffer.from(
  12347. // 2150 bytes
  12348. "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=",
  12349. "base64"
  12350. )
  12351. );
  12352. //#endregion
  12353. md4_1 = create.bind(null, md4, [], 64, 32);
  12354. return md4_1;
  12355. }
  12356. var BulkUpdateDecorator_1;
  12357. var hasRequiredBulkUpdateDecorator;
  12358. function requireBulkUpdateDecorator () {
  12359. if (hasRequiredBulkUpdateDecorator) return BulkUpdateDecorator_1;
  12360. hasRequiredBulkUpdateDecorator = 1;
  12361. const BULK_SIZE = 2000;
  12362. // We are using an object instead of a Map as this will stay static during the runtime
  12363. // so access to it can be optimized by v8
  12364. const digestCaches = {};
  12365. class BulkUpdateDecorator {
  12366. /**
  12367. * @param {Hash | function(): Hash} hashOrFactory function to create a hash
  12368. * @param {string=} hashKey key for caching
  12369. */
  12370. constructor(hashOrFactory, hashKey) {
  12371. this.hashKey = hashKey;
  12372. if (typeof hashOrFactory === "function") {
  12373. this.hashFactory = hashOrFactory;
  12374. this.hash = undefined;
  12375. } else {
  12376. this.hashFactory = undefined;
  12377. this.hash = hashOrFactory;
  12378. }
  12379. this.buffer = "";
  12380. }
  12381. /**
  12382. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  12383. * @param {string|Buffer} data data
  12384. * @param {string=} inputEncoding data encoding
  12385. * @returns {this} updated hash
  12386. */
  12387. update(data, inputEncoding) {
  12388. if (
  12389. inputEncoding !== undefined ||
  12390. typeof data !== "string" ||
  12391. data.length > BULK_SIZE
  12392. ) {
  12393. if (this.hash === undefined) {
  12394. this.hash = this.hashFactory();
  12395. }
  12396. if (this.buffer.length > 0) {
  12397. this.hash.update(this.buffer);
  12398. this.buffer = "";
  12399. }
  12400. this.hash.update(data, inputEncoding);
  12401. } else {
  12402. this.buffer += data;
  12403. if (this.buffer.length > BULK_SIZE) {
  12404. if (this.hash === undefined) {
  12405. this.hash = this.hashFactory();
  12406. }
  12407. this.hash.update(this.buffer);
  12408. this.buffer = "";
  12409. }
  12410. }
  12411. return this;
  12412. }
  12413. /**
  12414. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  12415. * @param {string=} encoding encoding of the return value
  12416. * @returns {string|Buffer} digest
  12417. */
  12418. digest(encoding) {
  12419. let digestCache;
  12420. const buffer = this.buffer;
  12421. if (this.hash === undefined) {
  12422. // short data for hash, we can use caching
  12423. const cacheKey = `${this.hashKey}-${encoding}`;
  12424. digestCache = digestCaches[cacheKey];
  12425. if (digestCache === undefined) {
  12426. digestCache = digestCaches[cacheKey] = new Map();
  12427. }
  12428. const cacheEntry = digestCache.get(buffer);
  12429. if (cacheEntry !== undefined) {
  12430. return cacheEntry;
  12431. }
  12432. this.hash = this.hashFactory();
  12433. }
  12434. if (buffer.length > 0) {
  12435. this.hash.update(buffer);
  12436. }
  12437. const digestResult = this.hash.digest(encoding);
  12438. if (digestCache !== undefined) {
  12439. digestCache.set(buffer, digestResult);
  12440. }
  12441. return digestResult;
  12442. }
  12443. }
  12444. BulkUpdateDecorator_1 = BulkUpdateDecorator;
  12445. return BulkUpdateDecorator_1;
  12446. }
  12447. var getHashDigest_1;
  12448. var hasRequiredGetHashDigest;
  12449. function requireGetHashDigest () {
  12450. if (hasRequiredGetHashDigest) return getHashDigest_1;
  12451. hasRequiredGetHashDigest = 1;
  12452. const baseEncodeTables = {
  12453. 26: "abcdefghijklmnopqrstuvwxyz",
  12454. 32: "123456789abcdefghjkmnpqrstuvwxyz", // no 0lio
  12455. 36: "0123456789abcdefghijklmnopqrstuvwxyz",
  12456. 49: "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no lIO
  12457. 52: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12458. 58: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no 0lIO
  12459. 62: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12460. 64: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_",
  12461. };
  12462. /**
  12463. * @param {Uint32Array} uint32Array Treated as a long base-0x100000000 number, little endian
  12464. * @param {number} divisor The divisor
  12465. * @return {number} Modulo (remainder) of the division
  12466. */
  12467. function divmod32(uint32Array, divisor) {
  12468. let carry = 0;
  12469. for (let i = uint32Array.length - 1; i >= 0; i--) {
  12470. const value = carry * 0x100000000 + uint32Array[i];
  12471. carry = value % divisor;
  12472. uint32Array[i] = Math.floor(value / divisor);
  12473. }
  12474. return carry;
  12475. }
  12476. function encodeBufferToBase(buffer, base, length) {
  12477. const encodeTable = baseEncodeTables[base];
  12478. if (!encodeTable) {
  12479. throw new Error("Unknown encoding base" + base);
  12480. }
  12481. // Input bits are only enough to generate this many characters
  12482. const limit = Math.ceil((buffer.length * 8) / Math.log2(base));
  12483. length = Math.min(length, limit);
  12484. // Most of the crypto digests (if not all) has length a multiple of 4 bytes.
  12485. // Fewer numbers in the array means faster math.
  12486. const uint32Array = new Uint32Array(Math.ceil(buffer.length / 4));
  12487. // Make sure the input buffer data is copied and is not mutated by reference.
  12488. // divmod32() would corrupt the BulkUpdateDecorator cache otherwise.
  12489. buffer.copy(Buffer.from(uint32Array.buffer));
  12490. let output = "";
  12491. for (let i = 0; i < length; i++) {
  12492. output = encodeTable[divmod32(uint32Array, base)] + output;
  12493. }
  12494. return output;
  12495. }
  12496. let crypto = undefined;
  12497. let createXXHash64 = undefined;
  12498. let createMd4 = undefined;
  12499. let BatchedHash = undefined;
  12500. let BulkUpdateDecorator = undefined;
  12501. function getHashDigest(buffer, algorithm, digestType, maxLength) {
  12502. algorithm = algorithm || "xxhash64";
  12503. maxLength = maxLength || 9999;
  12504. let hash;
  12505. if (algorithm === "xxhash64") {
  12506. if (createXXHash64 === undefined) {
  12507. createXXHash64 = /*@__PURE__*/ requireXxhash64();
  12508. if (BatchedHash === undefined) {
  12509. BatchedHash = /*@__PURE__*/ requireBatchedHash();
  12510. }
  12511. }
  12512. hash = new BatchedHash(createXXHash64());
  12513. } else if (algorithm === "md4") {
  12514. if (createMd4 === undefined) {
  12515. createMd4 = /*@__PURE__*/ requireMd4();
  12516. if (BatchedHash === undefined) {
  12517. BatchedHash = /*@__PURE__*/ requireBatchedHash();
  12518. }
  12519. }
  12520. hash = new BatchedHash(createMd4());
  12521. } else if (algorithm === "native-md4") {
  12522. if (typeof crypto === "undefined") {
  12523. crypto = require("crypto");
  12524. if (BulkUpdateDecorator === undefined) {
  12525. BulkUpdateDecorator = /*@__PURE__*/ requireBulkUpdateDecorator();
  12526. }
  12527. }
  12528. hash = new BulkUpdateDecorator(() => crypto.createHash("md4"), "md4");
  12529. } else {
  12530. if (typeof crypto === "undefined") {
  12531. crypto = require("crypto");
  12532. if (BulkUpdateDecorator === undefined) {
  12533. BulkUpdateDecorator = /*@__PURE__*/ requireBulkUpdateDecorator();
  12534. }
  12535. }
  12536. hash = new BulkUpdateDecorator(
  12537. () => crypto.createHash(algorithm),
  12538. algorithm
  12539. );
  12540. }
  12541. hash.update(buffer);
  12542. if (
  12543. digestType === "base26" ||
  12544. digestType === "base32" ||
  12545. digestType === "base36" ||
  12546. digestType === "base49" ||
  12547. digestType === "base52" ||
  12548. digestType === "base58" ||
  12549. digestType === "base62" ||
  12550. digestType === "base64safe"
  12551. ) {
  12552. return encodeBufferToBase(
  12553. hash.digest(),
  12554. digestType === "base64safe" ? 64 : digestType.substr(4),
  12555. maxLength
  12556. );
  12557. }
  12558. return hash.digest(digestType || "hex").substr(0, maxLength);
  12559. }
  12560. getHashDigest_1 = getHashDigest;
  12561. return getHashDigest_1;
  12562. }
  12563. var interpolateName_1;
  12564. var hasRequiredInterpolateName;
  12565. function requireInterpolateName () {
  12566. if (hasRequiredInterpolateName) return interpolateName_1;
  12567. hasRequiredInterpolateName = 1;
  12568. const path = path$1;
  12569. const getHashDigest = /*@__PURE__*/ requireGetHashDigest();
  12570. function interpolateName(loaderContext, name, options = {}) {
  12571. let filename;
  12572. const hasQuery =
  12573. loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1;
  12574. if (typeof name === "function") {
  12575. filename = name(
  12576. loaderContext.resourcePath,
  12577. hasQuery ? loaderContext.resourceQuery : undefined
  12578. );
  12579. } else {
  12580. filename = name || "[hash].[ext]";
  12581. }
  12582. const context = options.context;
  12583. const content = options.content;
  12584. const regExp = options.regExp;
  12585. let ext = "bin";
  12586. let basename = "file";
  12587. let directory = "";
  12588. let folder = "";
  12589. let query = "";
  12590. if (loaderContext.resourcePath) {
  12591. const parsed = path.parse(loaderContext.resourcePath);
  12592. let resourcePath = loaderContext.resourcePath;
  12593. if (parsed.ext) {
  12594. ext = parsed.ext.substr(1);
  12595. }
  12596. if (parsed.dir) {
  12597. basename = parsed.name;
  12598. resourcePath = parsed.dir + path.sep;
  12599. }
  12600. if (typeof context !== "undefined") {
  12601. directory = path
  12602. .relative(context, resourcePath + "_")
  12603. .replace(/\\/g, "/")
  12604. .replace(/\.\.(\/)?/g, "_$1");
  12605. directory = directory.substr(0, directory.length - 1);
  12606. } else {
  12607. directory = resourcePath.replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
  12608. }
  12609. if (directory.length <= 1) {
  12610. directory = "";
  12611. } else {
  12612. // directory.length > 1
  12613. folder = path.basename(directory);
  12614. }
  12615. }
  12616. if (loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1) {
  12617. query = loaderContext.resourceQuery;
  12618. const hashIdx = query.indexOf("#");
  12619. if (hashIdx >= 0) {
  12620. query = query.substr(0, hashIdx);
  12621. }
  12622. }
  12623. let url = filename;
  12624. if (content) {
  12625. // Match hash template
  12626. url = url
  12627. // `hash` and `contenthash` are same in `loader-utils` context
  12628. // let's keep `hash` for backward compatibility
  12629. .replace(
  12630. /\[(?:([^[:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*(?:safe)?))?(?::(\d+))?\]/gi,
  12631. (all, hashType, digestType, maxLength) =>
  12632. getHashDigest(content, hashType, digestType, parseInt(maxLength, 10))
  12633. );
  12634. }
  12635. url = url
  12636. .replace(/\[ext\]/gi, () => ext)
  12637. .replace(/\[name\]/gi, () => basename)
  12638. .replace(/\[path\]/gi, () => directory)
  12639. .replace(/\[folder\]/gi, () => folder)
  12640. .replace(/\[query\]/gi, () => query);
  12641. if (regExp && loaderContext.resourcePath) {
  12642. const match = loaderContext.resourcePath.match(new RegExp(regExp));
  12643. match &&
  12644. match.forEach((matched, i) => {
  12645. url = url.replace(new RegExp("\\[" + i + "\\]", "ig"), matched);
  12646. });
  12647. }
  12648. if (
  12649. typeof loaderContext.options === "object" &&
  12650. typeof loaderContext.options.customInterpolateName === "function"
  12651. ) {
  12652. url = loaderContext.options.customInterpolateName.call(
  12653. loaderContext,
  12654. url,
  12655. name,
  12656. options
  12657. );
  12658. }
  12659. return url;
  12660. }
  12661. interpolateName_1 = interpolateName;
  12662. return interpolateName_1;
  12663. }
  12664. var genericNames;
  12665. var hasRequiredGenericNames;
  12666. function requireGenericNames () {
  12667. if (hasRequiredGenericNames) return genericNames;
  12668. hasRequiredGenericNames = 1;
  12669. var interpolateName = /*@__PURE__*/ requireInterpolateName();
  12670. var path = path$1;
  12671. /**
  12672. * @param {string} pattern
  12673. * @param {object} options
  12674. * @param {string} options.context
  12675. * @param {string} options.hashPrefix
  12676. * @return {function}
  12677. */
  12678. genericNames = function createGenerator(pattern, options) {
  12679. options = options || {};
  12680. var context =
  12681. options && typeof options.context === "string"
  12682. ? options.context
  12683. : process.cwd();
  12684. var hashPrefix =
  12685. options && typeof options.hashPrefix === "string" ? options.hashPrefix : "";
  12686. /**
  12687. * @param {string} localName Usually a class name
  12688. * @param {string} filepath Absolute path
  12689. * @return {string}
  12690. */
  12691. return function generate(localName, filepath) {
  12692. var name = pattern.replace(/\[local\]/gi, localName);
  12693. var loaderContext = {
  12694. resourcePath: filepath,
  12695. };
  12696. var loaderOptions = {
  12697. content:
  12698. hashPrefix +
  12699. path.relative(context, filepath).replace(/\\/g, "/") +
  12700. "\x00" +
  12701. localName,
  12702. context: context,
  12703. };
  12704. var genericName = interpolateName(loaderContext, name, loaderOptions);
  12705. return genericName
  12706. .replace(new RegExp("[^a-zA-Z0-9\\-_\u00A0-\uFFFF]", "g"), "-")
  12707. .replace(/^((-?[0-9])|--)/, "_$1");
  12708. };
  12709. };
  12710. return genericNames;
  12711. }
  12712. var src$2 = {exports: {}};
  12713. var dist = {exports: {}};
  12714. var processor = {exports: {}};
  12715. var parser = {exports: {}};
  12716. var root = {exports: {}};
  12717. var container = {exports: {}};
  12718. var node = {exports: {}};
  12719. var util = {};
  12720. var unesc = {exports: {}};
  12721. var hasRequiredUnesc;
  12722. function requireUnesc () {
  12723. if (hasRequiredUnesc) return unesc.exports;
  12724. hasRequiredUnesc = 1;
  12725. (function (module, exports$1) {
  12726. exports$1.__esModule = true;
  12727. exports$1["default"] = unesc;
  12728. // Many thanks for this post which made this migration much easier.
  12729. // https://mathiasbynens.be/notes/css-escapes
  12730. /**
  12731. *
  12732. * @param {string} str
  12733. * @returns {[string, number]|undefined}
  12734. */
  12735. function gobbleHex(str) {
  12736. var lower = str.toLowerCase();
  12737. var hex = '';
  12738. var spaceTerminated = false;
  12739. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  12740. var code = lower.charCodeAt(i);
  12741. // check to see if we are dealing with a valid hex char [a-f|0-9]
  12742. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
  12743. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  12744. spaceTerminated = code === 32;
  12745. if (!valid) {
  12746. break;
  12747. }
  12748. hex += lower[i];
  12749. }
  12750. if (hex.length === 0) {
  12751. return undefined;
  12752. }
  12753. var codePoint = parseInt(hex, 16);
  12754. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
  12755. // Add special case for
  12756. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  12757. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  12758. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  12759. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  12760. }
  12761. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  12762. }
  12763. var CONTAINS_ESCAPE = /\\/;
  12764. function unesc(str) {
  12765. var needToProcess = CONTAINS_ESCAPE.test(str);
  12766. if (!needToProcess) {
  12767. return str;
  12768. }
  12769. var ret = "";
  12770. for (var i = 0; i < str.length; i++) {
  12771. if (str[i] === "\\") {
  12772. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  12773. if (gobbled !== undefined) {
  12774. ret += gobbled[0];
  12775. i += gobbled[1];
  12776. continue;
  12777. }
  12778. // Retain a pair of \\ if double escaped `\\\\`
  12779. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  12780. if (str[i + 1] === "\\") {
  12781. ret += "\\";
  12782. i++;
  12783. continue;
  12784. }
  12785. // if \\ is at the end of the string retain it
  12786. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  12787. if (str.length === i + 1) {
  12788. ret += str[i];
  12789. }
  12790. continue;
  12791. }
  12792. ret += str[i];
  12793. }
  12794. return ret;
  12795. }
  12796. module.exports = exports$1.default;
  12797. } (unesc, unesc.exports));
  12798. return unesc.exports;
  12799. }
  12800. var getProp = {exports: {}};
  12801. var hasRequiredGetProp;
  12802. function requireGetProp () {
  12803. if (hasRequiredGetProp) return getProp.exports;
  12804. hasRequiredGetProp = 1;
  12805. (function (module, exports$1) {
  12806. exports$1.__esModule = true;
  12807. exports$1["default"] = getProp;
  12808. function getProp(obj) {
  12809. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  12810. props[_key - 1] = arguments[_key];
  12811. }
  12812. while (props.length > 0) {
  12813. var prop = props.shift();
  12814. if (!obj[prop]) {
  12815. return undefined;
  12816. }
  12817. obj = obj[prop];
  12818. }
  12819. return obj;
  12820. }
  12821. module.exports = exports$1.default;
  12822. } (getProp, getProp.exports));
  12823. return getProp.exports;
  12824. }
  12825. var ensureObject = {exports: {}};
  12826. var hasRequiredEnsureObject;
  12827. function requireEnsureObject () {
  12828. if (hasRequiredEnsureObject) return ensureObject.exports;
  12829. hasRequiredEnsureObject = 1;
  12830. (function (module, exports$1) {
  12831. exports$1.__esModule = true;
  12832. exports$1["default"] = ensureObject;
  12833. function ensureObject(obj) {
  12834. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  12835. props[_key - 1] = arguments[_key];
  12836. }
  12837. while (props.length > 0) {
  12838. var prop = props.shift();
  12839. if (!obj[prop]) {
  12840. obj[prop] = {};
  12841. }
  12842. obj = obj[prop];
  12843. }
  12844. }
  12845. module.exports = exports$1.default;
  12846. } (ensureObject, ensureObject.exports));
  12847. return ensureObject.exports;
  12848. }
  12849. var stripComments = {exports: {}};
  12850. var hasRequiredStripComments;
  12851. function requireStripComments () {
  12852. if (hasRequiredStripComments) return stripComments.exports;
  12853. hasRequiredStripComments = 1;
  12854. (function (module, exports$1) {
  12855. exports$1.__esModule = true;
  12856. exports$1["default"] = stripComments;
  12857. function stripComments(str) {
  12858. var s = "";
  12859. var commentStart = str.indexOf("/*");
  12860. var lastEnd = 0;
  12861. while (commentStart >= 0) {
  12862. s = s + str.slice(lastEnd, commentStart);
  12863. var commentEnd = str.indexOf("*/", commentStart + 2);
  12864. if (commentEnd < 0) {
  12865. return s;
  12866. }
  12867. lastEnd = commentEnd + 2;
  12868. commentStart = str.indexOf("/*", lastEnd);
  12869. }
  12870. s = s + str.slice(lastEnd);
  12871. return s;
  12872. }
  12873. module.exports = exports$1.default;
  12874. } (stripComments, stripComments.exports));
  12875. return stripComments.exports;
  12876. }
  12877. var hasRequiredUtil;
  12878. function requireUtil () {
  12879. if (hasRequiredUtil) return util;
  12880. hasRequiredUtil = 1;
  12881. util.__esModule = true;
  12882. util.unesc = util.stripComments = util.getProp = util.ensureObject = void 0;
  12883. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc());
  12884. util.unesc = _unesc["default"];
  12885. var _getProp = _interopRequireDefault(/*@__PURE__*/ requireGetProp());
  12886. util.getProp = _getProp["default"];
  12887. var _ensureObject = _interopRequireDefault(/*@__PURE__*/ requireEnsureObject());
  12888. util.ensureObject = _ensureObject["default"];
  12889. var _stripComments = _interopRequireDefault(/*@__PURE__*/ requireStripComments());
  12890. util.stripComments = _stripComments["default"];
  12891. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  12892. return util;
  12893. }
  12894. var hasRequiredNode;
  12895. function requireNode () {
  12896. if (hasRequiredNode) return node.exports;
  12897. hasRequiredNode = 1;
  12898. (function (module, exports$1) {
  12899. exports$1.__esModule = true;
  12900. exports$1["default"] = void 0;
  12901. var _util = /*@__PURE__*/ requireUtil();
  12902. 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); } }
  12903. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  12904. var cloneNode = function cloneNode(obj, parent) {
  12905. if (typeof obj !== 'object' || obj === null) {
  12906. return obj;
  12907. }
  12908. var cloned = new obj.constructor();
  12909. for (var i in obj) {
  12910. if (!obj.hasOwnProperty(i)) {
  12911. continue;
  12912. }
  12913. var value = obj[i];
  12914. var type = typeof value;
  12915. if (i === 'parent' && type === 'object') {
  12916. if (parent) {
  12917. cloned[i] = parent;
  12918. }
  12919. } else if (value instanceof Array) {
  12920. cloned[i] = value.map(function (j) {
  12921. return cloneNode(j, cloned);
  12922. });
  12923. } else {
  12924. cloned[i] = cloneNode(value, cloned);
  12925. }
  12926. }
  12927. return cloned;
  12928. };
  12929. var Node = /*#__PURE__*/function () {
  12930. function Node(opts) {
  12931. if (opts === void 0) {
  12932. opts = {};
  12933. }
  12934. Object.assign(this, opts);
  12935. this.spaces = this.spaces || {};
  12936. this.spaces.before = this.spaces.before || '';
  12937. this.spaces.after = this.spaces.after || '';
  12938. }
  12939. var _proto = Node.prototype;
  12940. _proto.remove = function remove() {
  12941. if (this.parent) {
  12942. this.parent.removeChild(this);
  12943. }
  12944. this.parent = undefined;
  12945. return this;
  12946. };
  12947. _proto.replaceWith = function replaceWith() {
  12948. if (this.parent) {
  12949. for (var index in arguments) {
  12950. this.parent.insertBefore(this, arguments[index]);
  12951. }
  12952. this.remove();
  12953. }
  12954. return this;
  12955. };
  12956. _proto.next = function next() {
  12957. return this.parent.at(this.parent.index(this) + 1);
  12958. };
  12959. _proto.prev = function prev() {
  12960. return this.parent.at(this.parent.index(this) - 1);
  12961. };
  12962. _proto.clone = function clone(overrides) {
  12963. if (overrides === void 0) {
  12964. overrides = {};
  12965. }
  12966. var cloned = cloneNode(this);
  12967. for (var name in overrides) {
  12968. cloned[name] = overrides[name];
  12969. }
  12970. return cloned;
  12971. }
  12972. /**
  12973. * Some non-standard syntax doesn't follow normal escaping rules for css.
  12974. * This allows non standard syntax to be appended to an existing property
  12975. * by specifying the escaped value. By specifying the escaped value,
  12976. * illegal characters are allowed to be directly inserted into css output.
  12977. * @param {string} name the property to set
  12978. * @param {any} value the unescaped value of the property
  12979. * @param {string} valueEscaped optional. the escaped value of the property.
  12980. */;
  12981. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  12982. if (!this.raws) {
  12983. this.raws = {};
  12984. }
  12985. var originalValue = this[name];
  12986. var originalEscaped = this.raws[name];
  12987. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  12988. if (originalEscaped || valueEscaped !== value) {
  12989. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  12990. } else {
  12991. delete this.raws[name]; // delete any escaped value that was created by the setter.
  12992. }
  12993. }
  12994. /**
  12995. * Some non-standard syntax doesn't follow normal escaping rules for css.
  12996. * This allows the escaped value to be specified directly, allowing illegal
  12997. * characters to be directly inserted into css output.
  12998. * @param {string} name the property to set
  12999. * @param {any} value the unescaped value of the property
  13000. * @param {string} valueEscaped the escaped value of the property.
  13001. */;
  13002. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  13003. if (!this.raws) {
  13004. this.raws = {};
  13005. }
  13006. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  13007. this.raws[name] = valueEscaped;
  13008. }
  13009. /**
  13010. * When you want a value to passed through to CSS directly. This method
  13011. * deletes the corresponding raw value causing the stringifier to fallback
  13012. * to the unescaped value.
  13013. * @param {string} name the property to set.
  13014. * @param {any} value The value that is both escaped and unescaped.
  13015. */;
  13016. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  13017. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  13018. if (this.raws) {
  13019. delete this.raws[name];
  13020. }
  13021. }
  13022. /**
  13023. *
  13024. * @param {number} line The number (starting with 1)
  13025. * @param {number} column The column number (starting with 1)
  13026. */;
  13027. _proto.isAtPosition = function isAtPosition(line, column) {
  13028. if (this.source && this.source.start && this.source.end) {
  13029. if (this.source.start.line > line) {
  13030. return false;
  13031. }
  13032. if (this.source.end.line < line) {
  13033. return false;
  13034. }
  13035. if (this.source.start.line === line && this.source.start.column > column) {
  13036. return false;
  13037. }
  13038. if (this.source.end.line === line && this.source.end.column < column) {
  13039. return false;
  13040. }
  13041. return true;
  13042. }
  13043. return undefined;
  13044. };
  13045. _proto.stringifyProperty = function stringifyProperty(name) {
  13046. return this.raws && this.raws[name] || this[name];
  13047. };
  13048. _proto.valueToString = function valueToString() {
  13049. return String(this.stringifyProperty("value"));
  13050. };
  13051. _proto.toString = function toString() {
  13052. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  13053. };
  13054. _createClass(Node, [{
  13055. key: "rawSpaceBefore",
  13056. get: function get() {
  13057. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  13058. if (rawSpace === undefined) {
  13059. rawSpace = this.spaces && this.spaces.before;
  13060. }
  13061. return rawSpace || "";
  13062. },
  13063. set: function set(raw) {
  13064. (0, _util.ensureObject)(this, "raws", "spaces");
  13065. this.raws.spaces.before = raw;
  13066. }
  13067. }, {
  13068. key: "rawSpaceAfter",
  13069. get: function get() {
  13070. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  13071. if (rawSpace === undefined) {
  13072. rawSpace = this.spaces.after;
  13073. }
  13074. return rawSpace || "";
  13075. },
  13076. set: function set(raw) {
  13077. (0, _util.ensureObject)(this, "raws", "spaces");
  13078. this.raws.spaces.after = raw;
  13079. }
  13080. }]);
  13081. return Node;
  13082. }();
  13083. exports$1["default"] = Node;
  13084. module.exports = exports$1.default;
  13085. } (node, node.exports));
  13086. return node.exports;
  13087. }
  13088. var types$1 = {};
  13089. var hasRequiredTypes;
  13090. function requireTypes () {
  13091. if (hasRequiredTypes) return types$1;
  13092. hasRequiredTypes = 1;
  13093. types$1.__esModule = true;
  13094. 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;
  13095. var TAG = 'tag';
  13096. types$1.TAG = TAG;
  13097. var STRING = 'string';
  13098. types$1.STRING = STRING;
  13099. var SELECTOR = 'selector';
  13100. types$1.SELECTOR = SELECTOR;
  13101. var ROOT = 'root';
  13102. types$1.ROOT = ROOT;
  13103. var PSEUDO = 'pseudo';
  13104. types$1.PSEUDO = PSEUDO;
  13105. var NESTING = 'nesting';
  13106. types$1.NESTING = NESTING;
  13107. var ID = 'id';
  13108. types$1.ID = ID;
  13109. var COMMENT = 'comment';
  13110. types$1.COMMENT = COMMENT;
  13111. var COMBINATOR = 'combinator';
  13112. types$1.COMBINATOR = COMBINATOR;
  13113. var CLASS = 'class';
  13114. types$1.CLASS = CLASS;
  13115. var ATTRIBUTE = 'attribute';
  13116. types$1.ATTRIBUTE = ATTRIBUTE;
  13117. var UNIVERSAL = 'universal';
  13118. types$1.UNIVERSAL = UNIVERSAL;
  13119. return types$1;
  13120. }
  13121. var hasRequiredContainer;
  13122. function requireContainer () {
  13123. if (hasRequiredContainer) return container.exports;
  13124. hasRequiredContainer = 1;
  13125. (function (module, exports$1) {
  13126. exports$1.__esModule = true;
  13127. exports$1["default"] = void 0;
  13128. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13129. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes());
  13130. 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); }
  13131. 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; }
  13132. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13133. 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."); }
  13134. 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); }
  13135. 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; }
  13136. 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); } }
  13137. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13138. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13139. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13140. var Container = /*#__PURE__*/function (_Node) {
  13141. _inheritsLoose(Container, _Node);
  13142. function Container(opts) {
  13143. var _this;
  13144. _this = _Node.call(this, opts) || this;
  13145. if (!_this.nodes) {
  13146. _this.nodes = [];
  13147. }
  13148. return _this;
  13149. }
  13150. var _proto = Container.prototype;
  13151. _proto.append = function append(selector) {
  13152. selector.parent = this;
  13153. this.nodes.push(selector);
  13154. return this;
  13155. };
  13156. _proto.prepend = function prepend(selector) {
  13157. selector.parent = this;
  13158. this.nodes.unshift(selector);
  13159. return this;
  13160. };
  13161. _proto.at = function at(index) {
  13162. return this.nodes[index];
  13163. };
  13164. _proto.index = function index(child) {
  13165. if (typeof child === 'number') {
  13166. return child;
  13167. }
  13168. return this.nodes.indexOf(child);
  13169. };
  13170. _proto.removeChild = function removeChild(child) {
  13171. child = this.index(child);
  13172. this.at(child).parent = undefined;
  13173. this.nodes.splice(child, 1);
  13174. var index;
  13175. for (var id in this.indexes) {
  13176. index = this.indexes[id];
  13177. if (index >= child) {
  13178. this.indexes[id] = index - 1;
  13179. }
  13180. }
  13181. return this;
  13182. };
  13183. _proto.removeAll = function removeAll() {
  13184. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  13185. var node = _step.value;
  13186. node.parent = undefined;
  13187. }
  13188. this.nodes = [];
  13189. return this;
  13190. };
  13191. _proto.empty = function empty() {
  13192. return this.removeAll();
  13193. };
  13194. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  13195. newNode.parent = this;
  13196. var oldIndex = this.index(oldNode);
  13197. this.nodes.splice(oldIndex + 1, 0, newNode);
  13198. newNode.parent = this;
  13199. var index;
  13200. for (var id in this.indexes) {
  13201. index = this.indexes[id];
  13202. if (oldIndex <= index) {
  13203. this.indexes[id] = index + 1;
  13204. }
  13205. }
  13206. return this;
  13207. };
  13208. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  13209. newNode.parent = this;
  13210. var oldIndex = this.index(oldNode);
  13211. this.nodes.splice(oldIndex, 0, newNode);
  13212. newNode.parent = this;
  13213. var index;
  13214. for (var id in this.indexes) {
  13215. index = this.indexes[id];
  13216. if (index <= oldIndex) {
  13217. this.indexes[id] = index + 1;
  13218. }
  13219. }
  13220. return this;
  13221. };
  13222. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  13223. var found = undefined;
  13224. this.each(function (node) {
  13225. if (node.atPosition) {
  13226. var foundChild = node.atPosition(line, col);
  13227. if (foundChild) {
  13228. found = foundChild;
  13229. return false;
  13230. }
  13231. } else if (node.isAtPosition(line, col)) {
  13232. found = node;
  13233. return false;
  13234. }
  13235. });
  13236. return found;
  13237. }
  13238. /**
  13239. * Return the most specific node at the line and column number given.
  13240. * The source location is based on the original parsed location, locations aren't
  13241. * updated as selector nodes are mutated.
  13242. *
  13243. * Note that this location is relative to the location of the first character
  13244. * of the selector, and not the location of the selector in the overall document
  13245. * when used in conjunction with postcss.
  13246. *
  13247. * If not found, returns undefined.
  13248. * @param {number} line The line number of the node to find. (1-based index)
  13249. * @param {number} col The column number of the node to find. (1-based index)
  13250. */;
  13251. _proto.atPosition = function atPosition(line, col) {
  13252. if (this.isAtPosition(line, col)) {
  13253. return this._findChildAtPosition(line, col) || this;
  13254. } else {
  13255. return undefined;
  13256. }
  13257. };
  13258. _proto._inferEndPosition = function _inferEndPosition() {
  13259. if (this.last && this.last.source && this.last.source.end) {
  13260. this.source = this.source || {};
  13261. this.source.end = this.source.end || {};
  13262. Object.assign(this.source.end, this.last.source.end);
  13263. }
  13264. };
  13265. _proto.each = function each(callback) {
  13266. if (!this.lastEach) {
  13267. this.lastEach = 0;
  13268. }
  13269. if (!this.indexes) {
  13270. this.indexes = {};
  13271. }
  13272. this.lastEach++;
  13273. var id = this.lastEach;
  13274. this.indexes[id] = 0;
  13275. if (!this.length) {
  13276. return undefined;
  13277. }
  13278. var index, result;
  13279. while (this.indexes[id] < this.length) {
  13280. index = this.indexes[id];
  13281. result = callback(this.at(index), index);
  13282. if (result === false) {
  13283. break;
  13284. }
  13285. this.indexes[id] += 1;
  13286. }
  13287. delete this.indexes[id];
  13288. if (result === false) {
  13289. return false;
  13290. }
  13291. };
  13292. _proto.walk = function walk(callback) {
  13293. return this.each(function (node, i) {
  13294. var result = callback(node, i);
  13295. if (result !== false && node.length) {
  13296. result = node.walk(callback);
  13297. }
  13298. if (result === false) {
  13299. return false;
  13300. }
  13301. });
  13302. };
  13303. _proto.walkAttributes = function walkAttributes(callback) {
  13304. var _this2 = this;
  13305. return this.walk(function (selector) {
  13306. if (selector.type === types.ATTRIBUTE) {
  13307. return callback.call(_this2, selector);
  13308. }
  13309. });
  13310. };
  13311. _proto.walkClasses = function walkClasses(callback) {
  13312. var _this3 = this;
  13313. return this.walk(function (selector) {
  13314. if (selector.type === types.CLASS) {
  13315. return callback.call(_this3, selector);
  13316. }
  13317. });
  13318. };
  13319. _proto.walkCombinators = function walkCombinators(callback) {
  13320. var _this4 = this;
  13321. return this.walk(function (selector) {
  13322. if (selector.type === types.COMBINATOR) {
  13323. return callback.call(_this4, selector);
  13324. }
  13325. });
  13326. };
  13327. _proto.walkComments = function walkComments(callback) {
  13328. var _this5 = this;
  13329. return this.walk(function (selector) {
  13330. if (selector.type === types.COMMENT) {
  13331. return callback.call(_this5, selector);
  13332. }
  13333. });
  13334. };
  13335. _proto.walkIds = function walkIds(callback) {
  13336. var _this6 = this;
  13337. return this.walk(function (selector) {
  13338. if (selector.type === types.ID) {
  13339. return callback.call(_this6, selector);
  13340. }
  13341. });
  13342. };
  13343. _proto.walkNesting = function walkNesting(callback) {
  13344. var _this7 = this;
  13345. return this.walk(function (selector) {
  13346. if (selector.type === types.NESTING) {
  13347. return callback.call(_this7, selector);
  13348. }
  13349. });
  13350. };
  13351. _proto.walkPseudos = function walkPseudos(callback) {
  13352. var _this8 = this;
  13353. return this.walk(function (selector) {
  13354. if (selector.type === types.PSEUDO) {
  13355. return callback.call(_this8, selector);
  13356. }
  13357. });
  13358. };
  13359. _proto.walkTags = function walkTags(callback) {
  13360. var _this9 = this;
  13361. return this.walk(function (selector) {
  13362. if (selector.type === types.TAG) {
  13363. return callback.call(_this9, selector);
  13364. }
  13365. });
  13366. };
  13367. _proto.walkUniversals = function walkUniversals(callback) {
  13368. var _this10 = this;
  13369. return this.walk(function (selector) {
  13370. if (selector.type === types.UNIVERSAL) {
  13371. return callback.call(_this10, selector);
  13372. }
  13373. });
  13374. };
  13375. _proto.split = function split(callback) {
  13376. var _this11 = this;
  13377. var current = [];
  13378. return this.reduce(function (memo, node, index) {
  13379. var split = callback.call(_this11, node);
  13380. current.push(node);
  13381. if (split) {
  13382. memo.push(current);
  13383. current = [];
  13384. } else if (index === _this11.length - 1) {
  13385. memo.push(current);
  13386. }
  13387. return memo;
  13388. }, []);
  13389. };
  13390. _proto.map = function map(callback) {
  13391. return this.nodes.map(callback);
  13392. };
  13393. _proto.reduce = function reduce(callback, memo) {
  13394. return this.nodes.reduce(callback, memo);
  13395. };
  13396. _proto.every = function every(callback) {
  13397. return this.nodes.every(callback);
  13398. };
  13399. _proto.some = function some(callback) {
  13400. return this.nodes.some(callback);
  13401. };
  13402. _proto.filter = function filter(callback) {
  13403. return this.nodes.filter(callback);
  13404. };
  13405. _proto.sort = function sort(callback) {
  13406. return this.nodes.sort(callback);
  13407. };
  13408. _proto.toString = function toString() {
  13409. return this.map(String).join('');
  13410. };
  13411. _createClass(Container, [{
  13412. key: "first",
  13413. get: function get() {
  13414. return this.at(0);
  13415. }
  13416. }, {
  13417. key: "last",
  13418. get: function get() {
  13419. return this.at(this.length - 1);
  13420. }
  13421. }, {
  13422. key: "length",
  13423. get: function get() {
  13424. return this.nodes.length;
  13425. }
  13426. }]);
  13427. return Container;
  13428. }(_node["default"]);
  13429. exports$1["default"] = Container;
  13430. module.exports = exports$1.default;
  13431. } (container, container.exports));
  13432. return container.exports;
  13433. }
  13434. var hasRequiredRoot;
  13435. function requireRoot () {
  13436. if (hasRequiredRoot) return root.exports;
  13437. hasRequiredRoot = 1;
  13438. (function (module, exports$1) {
  13439. exports$1.__esModule = true;
  13440. exports$1["default"] = void 0;
  13441. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13442. var _types = /*@__PURE__*/ requireTypes();
  13443. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13444. 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); } }
  13445. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13446. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13447. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13448. var Root = /*#__PURE__*/function (_Container) {
  13449. _inheritsLoose(Root, _Container);
  13450. function Root(opts) {
  13451. var _this;
  13452. _this = _Container.call(this, opts) || this;
  13453. _this.type = _types.ROOT;
  13454. return _this;
  13455. }
  13456. var _proto = Root.prototype;
  13457. _proto.toString = function toString() {
  13458. var str = this.reduce(function (memo, selector) {
  13459. memo.push(String(selector));
  13460. return memo;
  13461. }, []).join(',');
  13462. return this.trailingComma ? str + ',' : str;
  13463. };
  13464. _proto.error = function error(message, options) {
  13465. if (this._error) {
  13466. return this._error(message, options);
  13467. } else {
  13468. return new Error(message);
  13469. }
  13470. };
  13471. _createClass(Root, [{
  13472. key: "errorGenerator",
  13473. set: function set(handler) {
  13474. this._error = handler;
  13475. }
  13476. }]);
  13477. return Root;
  13478. }(_container["default"]);
  13479. exports$1["default"] = Root;
  13480. module.exports = exports$1.default;
  13481. } (root, root.exports));
  13482. return root.exports;
  13483. }
  13484. var selector = {exports: {}};
  13485. var hasRequiredSelector;
  13486. function requireSelector () {
  13487. if (hasRequiredSelector) return selector.exports;
  13488. hasRequiredSelector = 1;
  13489. (function (module, exports$1) {
  13490. exports$1.__esModule = true;
  13491. exports$1["default"] = void 0;
  13492. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13493. var _types = /*@__PURE__*/ requireTypes();
  13494. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13495. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13496. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13497. var Selector = /*#__PURE__*/function (_Container) {
  13498. _inheritsLoose(Selector, _Container);
  13499. function Selector(opts) {
  13500. var _this;
  13501. _this = _Container.call(this, opts) || this;
  13502. _this.type = _types.SELECTOR;
  13503. return _this;
  13504. }
  13505. return Selector;
  13506. }(_container["default"]);
  13507. exports$1["default"] = Selector;
  13508. module.exports = exports$1.default;
  13509. } (selector, selector.exports));
  13510. return selector.exports;
  13511. }
  13512. var className = {exports: {}};
  13513. var hasRequiredClassName;
  13514. function requireClassName () {
  13515. if (hasRequiredClassName) return className.exports;
  13516. hasRequiredClassName = 1;
  13517. (function (module, exports$1) {
  13518. exports$1.__esModule = true;
  13519. exports$1["default"] = void 0;
  13520. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13521. var _util = /*@__PURE__*/ requireUtil();
  13522. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13523. var _types = /*@__PURE__*/ requireTypes();
  13524. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13525. 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); } }
  13526. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13527. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13528. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13529. var ClassName = /*#__PURE__*/function (_Node) {
  13530. _inheritsLoose(ClassName, _Node);
  13531. function ClassName(opts) {
  13532. var _this;
  13533. _this = _Node.call(this, opts) || this;
  13534. _this.type = _types.CLASS;
  13535. _this._constructed = true;
  13536. return _this;
  13537. }
  13538. var _proto = ClassName.prototype;
  13539. _proto.valueToString = function valueToString() {
  13540. return '.' + _Node.prototype.valueToString.call(this);
  13541. };
  13542. _createClass(ClassName, [{
  13543. key: "value",
  13544. get: function get() {
  13545. return this._value;
  13546. },
  13547. set: function set(v) {
  13548. if (this._constructed) {
  13549. var escaped = (0, _cssesc["default"])(v, {
  13550. isIdentifier: true
  13551. });
  13552. if (escaped !== v) {
  13553. (0, _util.ensureObject)(this, "raws");
  13554. this.raws.value = escaped;
  13555. } else if (this.raws) {
  13556. delete this.raws.value;
  13557. }
  13558. }
  13559. this._value = v;
  13560. }
  13561. }]);
  13562. return ClassName;
  13563. }(_node["default"]);
  13564. exports$1["default"] = ClassName;
  13565. module.exports = exports$1.default;
  13566. } (className, className.exports));
  13567. return className.exports;
  13568. }
  13569. var comment = {exports: {}};
  13570. var hasRequiredComment;
  13571. function requireComment () {
  13572. if (hasRequiredComment) return comment.exports;
  13573. hasRequiredComment = 1;
  13574. (function (module, exports$1) {
  13575. exports$1.__esModule = true;
  13576. exports$1["default"] = void 0;
  13577. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13578. var _types = /*@__PURE__*/ requireTypes();
  13579. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13580. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13581. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13582. var Comment = /*#__PURE__*/function (_Node) {
  13583. _inheritsLoose(Comment, _Node);
  13584. function Comment(opts) {
  13585. var _this;
  13586. _this = _Node.call(this, opts) || this;
  13587. _this.type = _types.COMMENT;
  13588. return _this;
  13589. }
  13590. return Comment;
  13591. }(_node["default"]);
  13592. exports$1["default"] = Comment;
  13593. module.exports = exports$1.default;
  13594. } (comment, comment.exports));
  13595. return comment.exports;
  13596. }
  13597. var id = {exports: {}};
  13598. var hasRequiredId;
  13599. function requireId () {
  13600. if (hasRequiredId) return id.exports;
  13601. hasRequiredId = 1;
  13602. (function (module, exports$1) {
  13603. exports$1.__esModule = true;
  13604. exports$1["default"] = void 0;
  13605. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13606. var _types = /*@__PURE__*/ requireTypes();
  13607. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13608. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13609. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13610. var ID = /*#__PURE__*/function (_Node) {
  13611. _inheritsLoose(ID, _Node);
  13612. function ID(opts) {
  13613. var _this;
  13614. _this = _Node.call(this, opts) || this;
  13615. _this.type = _types.ID;
  13616. return _this;
  13617. }
  13618. var _proto = ID.prototype;
  13619. _proto.valueToString = function valueToString() {
  13620. return '#' + _Node.prototype.valueToString.call(this);
  13621. };
  13622. return ID;
  13623. }(_node["default"]);
  13624. exports$1["default"] = ID;
  13625. module.exports = exports$1.default;
  13626. } (id, id.exports));
  13627. return id.exports;
  13628. }
  13629. var tag = {exports: {}};
  13630. var namespace = {exports: {}};
  13631. var hasRequiredNamespace;
  13632. function requireNamespace () {
  13633. if (hasRequiredNamespace) return namespace.exports;
  13634. hasRequiredNamespace = 1;
  13635. (function (module, exports$1) {
  13636. exports$1.__esModule = true;
  13637. exports$1["default"] = void 0;
  13638. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13639. var _util = /*@__PURE__*/ requireUtil();
  13640. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13641. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13642. 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); } }
  13643. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13644. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13645. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13646. var Namespace = /*#__PURE__*/function (_Node) {
  13647. _inheritsLoose(Namespace, _Node);
  13648. function Namespace() {
  13649. return _Node.apply(this, arguments) || this;
  13650. }
  13651. var _proto = Namespace.prototype;
  13652. _proto.qualifiedName = function qualifiedName(value) {
  13653. if (this.namespace) {
  13654. return this.namespaceString + "|" + value;
  13655. } else {
  13656. return value;
  13657. }
  13658. };
  13659. _proto.valueToString = function valueToString() {
  13660. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  13661. };
  13662. _createClass(Namespace, [{
  13663. key: "namespace",
  13664. get: function get() {
  13665. return this._namespace;
  13666. },
  13667. set: function set(namespace) {
  13668. if (namespace === true || namespace === "*" || namespace === "&") {
  13669. this._namespace = namespace;
  13670. if (this.raws) {
  13671. delete this.raws.namespace;
  13672. }
  13673. return;
  13674. }
  13675. var escaped = (0, _cssesc["default"])(namespace, {
  13676. isIdentifier: true
  13677. });
  13678. this._namespace = namespace;
  13679. if (escaped !== namespace) {
  13680. (0, _util.ensureObject)(this, "raws");
  13681. this.raws.namespace = escaped;
  13682. } else if (this.raws) {
  13683. delete this.raws.namespace;
  13684. }
  13685. }
  13686. }, {
  13687. key: "ns",
  13688. get: function get() {
  13689. return this._namespace;
  13690. },
  13691. set: function set(namespace) {
  13692. this.namespace = namespace;
  13693. }
  13694. }, {
  13695. key: "namespaceString",
  13696. get: function get() {
  13697. if (this.namespace) {
  13698. var ns = this.stringifyProperty("namespace");
  13699. if (ns === true) {
  13700. return '';
  13701. } else {
  13702. return ns;
  13703. }
  13704. } else {
  13705. return '';
  13706. }
  13707. }
  13708. }]);
  13709. return Namespace;
  13710. }(_node["default"]);
  13711. exports$1["default"] = Namespace;
  13712. module.exports = exports$1.default;
  13713. } (namespace, namespace.exports));
  13714. return namespace.exports;
  13715. }
  13716. var hasRequiredTag;
  13717. function requireTag () {
  13718. if (hasRequiredTag) return tag.exports;
  13719. hasRequiredTag = 1;
  13720. (function (module, exports$1) {
  13721. exports$1.__esModule = true;
  13722. exports$1["default"] = void 0;
  13723. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  13724. var _types = /*@__PURE__*/ requireTypes();
  13725. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13726. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13727. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13728. var Tag = /*#__PURE__*/function (_Namespace) {
  13729. _inheritsLoose(Tag, _Namespace);
  13730. function Tag(opts) {
  13731. var _this;
  13732. _this = _Namespace.call(this, opts) || this;
  13733. _this.type = _types.TAG;
  13734. return _this;
  13735. }
  13736. return Tag;
  13737. }(_namespace["default"]);
  13738. exports$1["default"] = Tag;
  13739. module.exports = exports$1.default;
  13740. } (tag, tag.exports));
  13741. return tag.exports;
  13742. }
  13743. var string = {exports: {}};
  13744. var hasRequiredString;
  13745. function requireString () {
  13746. if (hasRequiredString) return string.exports;
  13747. hasRequiredString = 1;
  13748. (function (module, exports$1) {
  13749. exports$1.__esModule = true;
  13750. exports$1["default"] = void 0;
  13751. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13752. var _types = /*@__PURE__*/ requireTypes();
  13753. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13754. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13755. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13756. var String = /*#__PURE__*/function (_Node) {
  13757. _inheritsLoose(String, _Node);
  13758. function String(opts) {
  13759. var _this;
  13760. _this = _Node.call(this, opts) || this;
  13761. _this.type = _types.STRING;
  13762. return _this;
  13763. }
  13764. return String;
  13765. }(_node["default"]);
  13766. exports$1["default"] = String;
  13767. module.exports = exports$1.default;
  13768. } (string, string.exports));
  13769. return string.exports;
  13770. }
  13771. var pseudo = {exports: {}};
  13772. var hasRequiredPseudo;
  13773. function requirePseudo () {
  13774. if (hasRequiredPseudo) return pseudo.exports;
  13775. hasRequiredPseudo = 1;
  13776. (function (module, exports$1) {
  13777. exports$1.__esModule = true;
  13778. exports$1["default"] = void 0;
  13779. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13780. var _types = /*@__PURE__*/ requireTypes();
  13781. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13782. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13783. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13784. var Pseudo = /*#__PURE__*/function (_Container) {
  13785. _inheritsLoose(Pseudo, _Container);
  13786. function Pseudo(opts) {
  13787. var _this;
  13788. _this = _Container.call(this, opts) || this;
  13789. _this.type = _types.PSEUDO;
  13790. return _this;
  13791. }
  13792. var _proto = Pseudo.prototype;
  13793. _proto.toString = function toString() {
  13794. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  13795. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  13796. };
  13797. return Pseudo;
  13798. }(_container["default"]);
  13799. exports$1["default"] = Pseudo;
  13800. module.exports = exports$1.default;
  13801. } (pseudo, pseudo.exports));
  13802. return pseudo.exports;
  13803. }
  13804. var attribute = {};
  13805. var hasRequiredAttribute;
  13806. function requireAttribute () {
  13807. if (hasRequiredAttribute) return attribute;
  13808. hasRequiredAttribute = 1;
  13809. (function (exports$1) {
  13810. exports$1.__esModule = true;
  13811. exports$1["default"] = void 0;
  13812. exports$1.unescapeValue = unescapeValue;
  13813. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13814. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc());
  13815. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  13816. var _types = /*@__PURE__*/ requireTypes();
  13817. var _CSSESC_QUOTE_OPTIONS;
  13818. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13819. 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); } }
  13820. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13821. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13822. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13823. var deprecate = /*@__PURE__*/ requireNode$1();
  13824. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  13825. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  13826. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  13827. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  13828. function unescapeValue(value) {
  13829. var deprecatedUsage = false;
  13830. var quoteMark = null;
  13831. var unescaped = value;
  13832. var m = unescaped.match(WRAPPED_IN_QUOTES);
  13833. if (m) {
  13834. quoteMark = m[1];
  13835. unescaped = m[2];
  13836. }
  13837. unescaped = (0, _unesc["default"])(unescaped);
  13838. if (unescaped !== value) {
  13839. deprecatedUsage = true;
  13840. }
  13841. return {
  13842. deprecatedUsage: deprecatedUsage,
  13843. unescaped: unescaped,
  13844. quoteMark: quoteMark
  13845. };
  13846. }
  13847. function handleDeprecatedContructorOpts(opts) {
  13848. if (opts.quoteMark !== undefined) {
  13849. return opts;
  13850. }
  13851. if (opts.value === undefined) {
  13852. return opts;
  13853. }
  13854. warnOfDeprecatedConstructor();
  13855. var _unescapeValue = unescapeValue(opts.value),
  13856. quoteMark = _unescapeValue.quoteMark,
  13857. unescaped = _unescapeValue.unescaped;
  13858. if (!opts.raws) {
  13859. opts.raws = {};
  13860. }
  13861. if (opts.raws.value === undefined) {
  13862. opts.raws.value = opts.value;
  13863. }
  13864. opts.value = unescaped;
  13865. opts.quoteMark = quoteMark;
  13866. return opts;
  13867. }
  13868. var Attribute = /*#__PURE__*/function (_Namespace) {
  13869. _inheritsLoose(Attribute, _Namespace);
  13870. function Attribute(opts) {
  13871. var _this;
  13872. if (opts === void 0) {
  13873. opts = {};
  13874. }
  13875. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  13876. _this.type = _types.ATTRIBUTE;
  13877. _this.raws = _this.raws || {};
  13878. Object.defineProperty(_this.raws, 'unquoted', {
  13879. get: deprecate(function () {
  13880. return _this.value;
  13881. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  13882. set: deprecate(function () {
  13883. return _this.value;
  13884. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  13885. });
  13886. _this._constructed = true;
  13887. return _this;
  13888. }
  13889. /**
  13890. * Returns the Attribute's value quoted such that it would be legal to use
  13891. * in the value of a css file. The original value's quotation setting
  13892. * used for stringification is left unchanged. See `setValue(value, options)`
  13893. * if you want to control the quote settings of a new value for the attribute.
  13894. *
  13895. * You can also change the quotation used for the current value by setting quoteMark.
  13896. *
  13897. * Options:
  13898. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  13899. * option is not set, the original value for quoteMark will be used. If
  13900. * indeterminate, a double quote is used. The legal values are:
  13901. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  13902. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  13903. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  13904. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  13905. * over the quoteMark option value.
  13906. * * smart {boolean} - if true, will select a quote mark based on the value
  13907. * and the other options specified here. See the `smartQuoteMark()`
  13908. * method.
  13909. **/
  13910. var _proto = Attribute.prototype;
  13911. _proto.getQuotedValue = function getQuotedValue(options) {
  13912. if (options === void 0) {
  13913. options = {};
  13914. }
  13915. var quoteMark = this._determineQuoteMark(options);
  13916. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  13917. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  13918. return escaped;
  13919. };
  13920. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  13921. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  13922. }
  13923. /**
  13924. * Set the unescaped value with the specified quotation options. The value
  13925. * provided must not include any wrapping quote marks -- those quotes will
  13926. * be interpreted as part of the value and escaped accordingly.
  13927. */;
  13928. _proto.setValue = function setValue(value, options) {
  13929. if (options === void 0) {
  13930. options = {};
  13931. }
  13932. this._value = value;
  13933. this._quoteMark = this._determineQuoteMark(options);
  13934. this._syncRawValue();
  13935. }
  13936. /**
  13937. * Intelligently select a quoteMark value based on the value's contents. If
  13938. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  13939. * mark will be picked that minimizes the number of escapes.
  13940. *
  13941. * If there's no clear winner, the quote mark from these options is used,
  13942. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  13943. * true). If the quoteMark is unspecified, a double quote is used.
  13944. *
  13945. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  13946. * from the quoteValue method.
  13947. */;
  13948. _proto.smartQuoteMark = function smartQuoteMark(options) {
  13949. var v = this.value;
  13950. var numSingleQuotes = v.replace(/[^']/g, '').length;
  13951. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  13952. if (numSingleQuotes + numDoubleQuotes === 0) {
  13953. var escaped = (0, _cssesc["default"])(v, {
  13954. isIdentifier: true
  13955. });
  13956. if (escaped === v) {
  13957. return Attribute.NO_QUOTE;
  13958. } else {
  13959. var pref = this.preferredQuoteMark(options);
  13960. if (pref === Attribute.NO_QUOTE) {
  13961. // pick a quote mark that isn't none and see if it's smaller
  13962. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  13963. var opts = CSSESC_QUOTE_OPTIONS[quote];
  13964. var quoteValue = (0, _cssesc["default"])(v, opts);
  13965. if (quoteValue.length < escaped.length) {
  13966. return quote;
  13967. }
  13968. }
  13969. return pref;
  13970. }
  13971. } else if (numDoubleQuotes === numSingleQuotes) {
  13972. return this.preferredQuoteMark(options);
  13973. } else if (numDoubleQuotes < numSingleQuotes) {
  13974. return Attribute.DOUBLE_QUOTE;
  13975. } else {
  13976. return Attribute.SINGLE_QUOTE;
  13977. }
  13978. }
  13979. /**
  13980. * Selects the preferred quote mark based on the options and the current quote mark value.
  13981. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  13982. * instead.
  13983. */;
  13984. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  13985. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  13986. if (quoteMark === undefined) {
  13987. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  13988. }
  13989. if (quoteMark === undefined) {
  13990. quoteMark = Attribute.DOUBLE_QUOTE;
  13991. }
  13992. return quoteMark;
  13993. };
  13994. _proto._syncRawValue = function _syncRawValue() {
  13995. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  13996. if (rawValue === this._value) {
  13997. if (this.raws) {
  13998. delete this.raws.value;
  13999. }
  14000. } else {
  14001. this.raws.value = rawValue;
  14002. }
  14003. };
  14004. _proto._handleEscapes = function _handleEscapes(prop, value) {
  14005. if (this._constructed) {
  14006. var escaped = (0, _cssesc["default"])(value, {
  14007. isIdentifier: true
  14008. });
  14009. if (escaped !== value) {
  14010. this.raws[prop] = escaped;
  14011. } else {
  14012. delete this.raws[prop];
  14013. }
  14014. }
  14015. };
  14016. _proto._spacesFor = function _spacesFor(name) {
  14017. var attrSpaces = {
  14018. before: '',
  14019. after: ''
  14020. };
  14021. var spaces = this.spaces[name] || {};
  14022. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  14023. return Object.assign(attrSpaces, spaces, rawSpaces);
  14024. };
  14025. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  14026. if (spaceName === void 0) {
  14027. spaceName = name;
  14028. }
  14029. if (concat === void 0) {
  14030. concat = defaultAttrConcat;
  14031. }
  14032. var attrSpaces = this._spacesFor(spaceName);
  14033. return concat(this.stringifyProperty(name), attrSpaces);
  14034. }
  14035. /**
  14036. * returns the offset of the attribute part specified relative to the
  14037. * start of the node of the output string.
  14038. *
  14039. * * "ns" - alias for "namespace"
  14040. * * "namespace" - the namespace if it exists.
  14041. * * "attribute" - the attribute name
  14042. * * "attributeNS" - the start of the attribute or its namespace
  14043. * * "operator" - the match operator of the attribute
  14044. * * "value" - The value (string or identifier)
  14045. * * "insensitive" - the case insensitivity flag;
  14046. * @param part One of the possible values inside an attribute.
  14047. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  14048. */;
  14049. _proto.offsetOf = function offsetOf(name) {
  14050. var count = 1;
  14051. var attributeSpaces = this._spacesFor("attribute");
  14052. count += attributeSpaces.before.length;
  14053. if (name === "namespace" || name === "ns") {
  14054. return this.namespace ? count : -1;
  14055. }
  14056. if (name === "attributeNS") {
  14057. return count;
  14058. }
  14059. count += this.namespaceString.length;
  14060. if (this.namespace) {
  14061. count += 1;
  14062. }
  14063. if (name === "attribute") {
  14064. return count;
  14065. }
  14066. count += this.stringifyProperty("attribute").length;
  14067. count += attributeSpaces.after.length;
  14068. var operatorSpaces = this._spacesFor("operator");
  14069. count += operatorSpaces.before.length;
  14070. var operator = this.stringifyProperty("operator");
  14071. if (name === "operator") {
  14072. return operator ? count : -1;
  14073. }
  14074. count += operator.length;
  14075. count += operatorSpaces.after.length;
  14076. var valueSpaces = this._spacesFor("value");
  14077. count += valueSpaces.before.length;
  14078. var value = this.stringifyProperty("value");
  14079. if (name === "value") {
  14080. return value ? count : -1;
  14081. }
  14082. count += value.length;
  14083. count += valueSpaces.after.length;
  14084. var insensitiveSpaces = this._spacesFor("insensitive");
  14085. count += insensitiveSpaces.before.length;
  14086. if (name === "insensitive") {
  14087. return this.insensitive ? count : -1;
  14088. }
  14089. return -1;
  14090. };
  14091. _proto.toString = function toString() {
  14092. var _this2 = this;
  14093. var selector = [this.rawSpaceBefore, '['];
  14094. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  14095. if (this.operator && (this.value || this.value === '')) {
  14096. selector.push(this._stringFor('operator'));
  14097. selector.push(this._stringFor('value'));
  14098. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  14099. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  14100. attrSpaces.before = " ";
  14101. }
  14102. return defaultAttrConcat(attrValue, attrSpaces);
  14103. }));
  14104. }
  14105. selector.push(']');
  14106. selector.push(this.rawSpaceAfter);
  14107. return selector.join('');
  14108. };
  14109. _createClass(Attribute, [{
  14110. key: "quoted",
  14111. get: function get() {
  14112. var qm = this.quoteMark;
  14113. return qm === "'" || qm === '"';
  14114. },
  14115. set: function set(value) {
  14116. warnOfDeprecatedQuotedAssignment();
  14117. }
  14118. /**
  14119. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  14120. * returns `null` if the value is not quoted.
  14121. * returns `undefined` if the quotation state is unknown (this can happen when
  14122. * the attribute is constructed without specifying a quote mark.)
  14123. */
  14124. }, {
  14125. key: "quoteMark",
  14126. get: function get() {
  14127. return this._quoteMark;
  14128. }
  14129. /**
  14130. * Set the quote mark to be used by this attribute's value.
  14131. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  14132. * value is updated accordingly.
  14133. *
  14134. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  14135. */,
  14136. set: function set(quoteMark) {
  14137. if (!this._constructed) {
  14138. this._quoteMark = quoteMark;
  14139. return;
  14140. }
  14141. if (this._quoteMark !== quoteMark) {
  14142. this._quoteMark = quoteMark;
  14143. this._syncRawValue();
  14144. }
  14145. }
  14146. }, {
  14147. key: "qualifiedAttribute",
  14148. get: function get() {
  14149. return this.qualifiedName(this.raws.attribute || this.attribute);
  14150. }
  14151. }, {
  14152. key: "insensitiveFlag",
  14153. get: function get() {
  14154. return this.insensitive ? 'i' : '';
  14155. }
  14156. }, {
  14157. key: "value",
  14158. get: function get() {
  14159. return this._value;
  14160. },
  14161. set:
  14162. /**
  14163. * Before 3.0, the value had to be set to an escaped value including any wrapped
  14164. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  14165. * is unescaped during parsing and any quote marks are removed.
  14166. *
  14167. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  14168. * a deprecation warning is raised when the new value contains any characters that would
  14169. * require escaping (including if it contains wrapped quotes).
  14170. *
  14171. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  14172. * how the new value is quoted.
  14173. */
  14174. function set(v) {
  14175. if (this._constructed) {
  14176. var _unescapeValue2 = unescapeValue(v),
  14177. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  14178. unescaped = _unescapeValue2.unescaped,
  14179. quoteMark = _unescapeValue2.quoteMark;
  14180. if (deprecatedUsage) {
  14181. warnOfDeprecatedValueAssignment();
  14182. }
  14183. if (unescaped === this._value && quoteMark === this._quoteMark) {
  14184. return;
  14185. }
  14186. this._value = unescaped;
  14187. this._quoteMark = quoteMark;
  14188. this._syncRawValue();
  14189. } else {
  14190. this._value = v;
  14191. }
  14192. }
  14193. }, {
  14194. key: "insensitive",
  14195. get: function get() {
  14196. return this._insensitive;
  14197. }
  14198. /**
  14199. * Set the case insensitive flag.
  14200. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  14201. * of the attribute is updated accordingly.
  14202. *
  14203. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  14204. */,
  14205. set: function set(insensitive) {
  14206. if (!insensitive) {
  14207. this._insensitive = false;
  14208. // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  14209. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  14210. if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
  14211. this.raws.insensitiveFlag = undefined;
  14212. }
  14213. }
  14214. this._insensitive = insensitive;
  14215. }
  14216. }, {
  14217. key: "attribute",
  14218. get: function get() {
  14219. return this._attribute;
  14220. },
  14221. set: function set(name) {
  14222. this._handleEscapes("attribute", name);
  14223. this._attribute = name;
  14224. }
  14225. }]);
  14226. return Attribute;
  14227. }(_namespace["default"]);
  14228. exports$1["default"] = Attribute;
  14229. Attribute.NO_QUOTE = null;
  14230. Attribute.SINGLE_QUOTE = "'";
  14231. Attribute.DOUBLE_QUOTE = '"';
  14232. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  14233. "'": {
  14234. quotes: 'single',
  14235. wrap: true
  14236. },
  14237. '"': {
  14238. quotes: 'double',
  14239. wrap: true
  14240. }
  14241. }, _CSSESC_QUOTE_OPTIONS[null] = {
  14242. isIdentifier: true
  14243. }, _CSSESC_QUOTE_OPTIONS);
  14244. function defaultAttrConcat(attrValue, attrSpaces) {
  14245. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  14246. }
  14247. } (attribute));
  14248. return attribute;
  14249. }
  14250. var universal = {exports: {}};
  14251. var hasRequiredUniversal;
  14252. function requireUniversal () {
  14253. if (hasRequiredUniversal) return universal.exports;
  14254. hasRequiredUniversal = 1;
  14255. (function (module, exports$1) {
  14256. exports$1.__esModule = true;
  14257. exports$1["default"] = void 0;
  14258. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  14259. var _types = /*@__PURE__*/ requireTypes();
  14260. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14261. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14262. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14263. var Universal = /*#__PURE__*/function (_Namespace) {
  14264. _inheritsLoose(Universal, _Namespace);
  14265. function Universal(opts) {
  14266. var _this;
  14267. _this = _Namespace.call(this, opts) || this;
  14268. _this.type = _types.UNIVERSAL;
  14269. _this.value = '*';
  14270. return _this;
  14271. }
  14272. return Universal;
  14273. }(_namespace["default"]);
  14274. exports$1["default"] = Universal;
  14275. module.exports = exports$1.default;
  14276. } (universal, universal.exports));
  14277. return universal.exports;
  14278. }
  14279. var combinator = {exports: {}};
  14280. var hasRequiredCombinator;
  14281. function requireCombinator () {
  14282. if (hasRequiredCombinator) return combinator.exports;
  14283. hasRequiredCombinator = 1;
  14284. (function (module, exports$1) {
  14285. exports$1.__esModule = true;
  14286. exports$1["default"] = void 0;
  14287. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  14288. var _types = /*@__PURE__*/ requireTypes();
  14289. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14290. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14291. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14292. var Combinator = /*#__PURE__*/function (_Node) {
  14293. _inheritsLoose(Combinator, _Node);
  14294. function Combinator(opts) {
  14295. var _this;
  14296. _this = _Node.call(this, opts) || this;
  14297. _this.type = _types.COMBINATOR;
  14298. return _this;
  14299. }
  14300. return Combinator;
  14301. }(_node["default"]);
  14302. exports$1["default"] = Combinator;
  14303. module.exports = exports$1.default;
  14304. } (combinator, combinator.exports));
  14305. return combinator.exports;
  14306. }
  14307. var nesting = {exports: {}};
  14308. var hasRequiredNesting;
  14309. function requireNesting () {
  14310. if (hasRequiredNesting) return nesting.exports;
  14311. hasRequiredNesting = 1;
  14312. (function (module, exports$1) {
  14313. exports$1.__esModule = true;
  14314. exports$1["default"] = void 0;
  14315. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  14316. var _types = /*@__PURE__*/ requireTypes();
  14317. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14318. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14319. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14320. var Nesting = /*#__PURE__*/function (_Node) {
  14321. _inheritsLoose(Nesting, _Node);
  14322. function Nesting(opts) {
  14323. var _this;
  14324. _this = _Node.call(this, opts) || this;
  14325. _this.type = _types.NESTING;
  14326. _this.value = '&';
  14327. return _this;
  14328. }
  14329. return Nesting;
  14330. }(_node["default"]);
  14331. exports$1["default"] = Nesting;
  14332. module.exports = exports$1.default;
  14333. } (nesting, nesting.exports));
  14334. return nesting.exports;
  14335. }
  14336. var sortAscending = {exports: {}};
  14337. var hasRequiredSortAscending;
  14338. function requireSortAscending () {
  14339. if (hasRequiredSortAscending) return sortAscending.exports;
  14340. hasRequiredSortAscending = 1;
  14341. (function (module, exports$1) {
  14342. exports$1.__esModule = true;
  14343. exports$1["default"] = sortAscending;
  14344. function sortAscending(list) {
  14345. return list.sort(function (a, b) {
  14346. return a - b;
  14347. });
  14348. }
  14349. module.exports = exports$1.default;
  14350. } (sortAscending, sortAscending.exports));
  14351. return sortAscending.exports;
  14352. }
  14353. var tokenize = {};
  14354. var tokenTypes = {};
  14355. var hasRequiredTokenTypes;
  14356. function requireTokenTypes () {
  14357. if (hasRequiredTokenTypes) return tokenTypes;
  14358. hasRequiredTokenTypes = 1;
  14359. tokenTypes.__esModule = true;
  14360. 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;
  14361. var ampersand = 38; // `&`.charCodeAt(0);
  14362. tokenTypes.ampersand = ampersand;
  14363. var asterisk = 42; // `*`.charCodeAt(0);
  14364. tokenTypes.asterisk = asterisk;
  14365. var at = 64; // `@`.charCodeAt(0);
  14366. tokenTypes.at = at;
  14367. var comma = 44; // `,`.charCodeAt(0);
  14368. tokenTypes.comma = comma;
  14369. var colon = 58; // `:`.charCodeAt(0);
  14370. tokenTypes.colon = colon;
  14371. var semicolon = 59; // `;`.charCodeAt(0);
  14372. tokenTypes.semicolon = semicolon;
  14373. var openParenthesis = 40; // `(`.charCodeAt(0);
  14374. tokenTypes.openParenthesis = openParenthesis;
  14375. var closeParenthesis = 41; // `)`.charCodeAt(0);
  14376. tokenTypes.closeParenthesis = closeParenthesis;
  14377. var openSquare = 91; // `[`.charCodeAt(0);
  14378. tokenTypes.openSquare = openSquare;
  14379. var closeSquare = 93; // `]`.charCodeAt(0);
  14380. tokenTypes.closeSquare = closeSquare;
  14381. var dollar = 36; // `$`.charCodeAt(0);
  14382. tokenTypes.dollar = dollar;
  14383. var tilde = 126; // `~`.charCodeAt(0);
  14384. tokenTypes.tilde = tilde;
  14385. var caret = 94; // `^`.charCodeAt(0);
  14386. tokenTypes.caret = caret;
  14387. var plus = 43; // `+`.charCodeAt(0);
  14388. tokenTypes.plus = plus;
  14389. var equals = 61; // `=`.charCodeAt(0);
  14390. tokenTypes.equals = equals;
  14391. var pipe = 124; // `|`.charCodeAt(0);
  14392. tokenTypes.pipe = pipe;
  14393. var greaterThan = 62; // `>`.charCodeAt(0);
  14394. tokenTypes.greaterThan = greaterThan;
  14395. var space = 32; // ` `.charCodeAt(0);
  14396. tokenTypes.space = space;
  14397. var singleQuote = 39; // `'`.charCodeAt(0);
  14398. tokenTypes.singleQuote = singleQuote;
  14399. var doubleQuote = 34; // `"`.charCodeAt(0);
  14400. tokenTypes.doubleQuote = doubleQuote;
  14401. var slash = 47; // `/`.charCodeAt(0);
  14402. tokenTypes.slash = slash;
  14403. var bang = 33; // `!`.charCodeAt(0);
  14404. tokenTypes.bang = bang;
  14405. var backslash = 92; // '\\'.charCodeAt(0);
  14406. tokenTypes.backslash = backslash;
  14407. var cr = 13; // '\r'.charCodeAt(0);
  14408. tokenTypes.cr = cr;
  14409. var feed = 12; // '\f'.charCodeAt(0);
  14410. tokenTypes.feed = feed;
  14411. var newline = 10; // '\n'.charCodeAt(0);
  14412. tokenTypes.newline = newline;
  14413. var tab = 9; // '\t'.charCodeAt(0);
  14414. // Expose aliases primarily for readability.
  14415. tokenTypes.tab = tab;
  14416. var str = singleQuote;
  14417. // No good single character representation!
  14418. tokenTypes.str = str;
  14419. var comment = -1;
  14420. tokenTypes.comment = comment;
  14421. var word = -2;
  14422. tokenTypes.word = word;
  14423. var combinator = -3;
  14424. tokenTypes.combinator = combinator;
  14425. return tokenTypes;
  14426. }
  14427. var hasRequiredTokenize;
  14428. function requireTokenize () {
  14429. if (hasRequiredTokenize) return tokenize;
  14430. hasRequiredTokenize = 1;
  14431. (function (exports$1) {
  14432. exports$1.__esModule = true;
  14433. exports$1.FIELDS = void 0;
  14434. exports$1["default"] = tokenize;
  14435. var t = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes());
  14436. var _unescapable, _wordDelimiters;
  14437. 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); }
  14438. 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; }
  14439. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  14440. 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);
  14441. var hex = {};
  14442. var hexChars = "0123456789abcdefABCDEF";
  14443. for (var i = 0; i < hexChars.length; i++) {
  14444. hex[hexChars.charCodeAt(i)] = true;
  14445. }
  14446. /**
  14447. * Returns the last index of the bar css word
  14448. * @param {string} css The string in which the word begins
  14449. * @param {number} start The index into the string where word's first letter occurs
  14450. */
  14451. function consumeWord(css, start) {
  14452. var next = start;
  14453. var code;
  14454. do {
  14455. code = css.charCodeAt(next);
  14456. if (wordDelimiters[code]) {
  14457. return next - 1;
  14458. } else if (code === t.backslash) {
  14459. next = consumeEscape(css, next) + 1;
  14460. } else {
  14461. // All other characters are part of the word
  14462. next++;
  14463. }
  14464. } while (next < css.length);
  14465. return next - 1;
  14466. }
  14467. /**
  14468. * Returns the last index of the escape sequence
  14469. * @param {string} css The string in which the sequence begins
  14470. * @param {number} start The index into the string where escape character (`\`) occurs.
  14471. */
  14472. function consumeEscape(css, start) {
  14473. var next = start;
  14474. var code = css.charCodeAt(next + 1);
  14475. if (unescapable[code]) ; else if (hex[code]) {
  14476. var hexDigits = 0;
  14477. // consume up to 6 hex chars
  14478. do {
  14479. next++;
  14480. hexDigits++;
  14481. code = css.charCodeAt(next + 1);
  14482. } while (hex[code] && hexDigits < 6);
  14483. // if fewer than 6 hex chars, a trailing space ends the escape
  14484. if (hexDigits < 6 && code === t.space) {
  14485. next++;
  14486. }
  14487. } else {
  14488. // the next char is part of the current word
  14489. next++;
  14490. }
  14491. return next;
  14492. }
  14493. var FIELDS = {
  14494. TYPE: 0,
  14495. START_LINE: 1,
  14496. START_COL: 2,
  14497. END_LINE: 3,
  14498. END_COL: 4,
  14499. START_POS: 5,
  14500. END_POS: 6
  14501. };
  14502. exports$1.FIELDS = FIELDS;
  14503. function tokenize(input) {
  14504. var tokens = [];
  14505. var css = input.css.valueOf();
  14506. var _css = css,
  14507. length = _css.length;
  14508. var offset = -1;
  14509. var line = 1;
  14510. var start = 0;
  14511. var end = 0;
  14512. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  14513. function unclosed(what, fix) {
  14514. if (input.safe) {
  14515. // fyi: this is never set to true.
  14516. css += fix;
  14517. next = css.length - 1;
  14518. } else {
  14519. throw input.error('Unclosed ' + what, line, start - offset, start);
  14520. }
  14521. }
  14522. while (start < length) {
  14523. code = css.charCodeAt(start);
  14524. if (code === t.newline) {
  14525. offset = start;
  14526. line += 1;
  14527. }
  14528. switch (code) {
  14529. case t.space:
  14530. case t.tab:
  14531. case t.newline:
  14532. case t.cr:
  14533. case t.feed:
  14534. next = start;
  14535. do {
  14536. next += 1;
  14537. code = css.charCodeAt(next);
  14538. if (code === t.newline) {
  14539. offset = next;
  14540. line += 1;
  14541. }
  14542. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  14543. tokenType = t.space;
  14544. endLine = line;
  14545. endColumn = next - offset - 1;
  14546. end = next;
  14547. break;
  14548. case t.plus:
  14549. case t.greaterThan:
  14550. case t.tilde:
  14551. case t.pipe:
  14552. next = start;
  14553. do {
  14554. next += 1;
  14555. code = css.charCodeAt(next);
  14556. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  14557. tokenType = t.combinator;
  14558. endLine = line;
  14559. endColumn = start - offset;
  14560. end = next;
  14561. break;
  14562. // Consume these characters as single tokens.
  14563. case t.asterisk:
  14564. case t.ampersand:
  14565. case t.bang:
  14566. case t.comma:
  14567. case t.equals:
  14568. case t.dollar:
  14569. case t.caret:
  14570. case t.openSquare:
  14571. case t.closeSquare:
  14572. case t.colon:
  14573. case t.semicolon:
  14574. case t.openParenthesis:
  14575. case t.closeParenthesis:
  14576. next = start;
  14577. tokenType = code;
  14578. endLine = line;
  14579. endColumn = start - offset;
  14580. end = next + 1;
  14581. break;
  14582. case t.singleQuote:
  14583. case t.doubleQuote:
  14584. quote = code === t.singleQuote ? "'" : '"';
  14585. next = start;
  14586. do {
  14587. escaped = false;
  14588. next = css.indexOf(quote, next + 1);
  14589. if (next === -1) {
  14590. unclosed('quote', quote);
  14591. }
  14592. escapePos = next;
  14593. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  14594. escapePos -= 1;
  14595. escaped = !escaped;
  14596. }
  14597. } while (escaped);
  14598. tokenType = t.str;
  14599. endLine = line;
  14600. endColumn = start - offset;
  14601. end = next + 1;
  14602. break;
  14603. default:
  14604. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  14605. next = css.indexOf('*/', start + 2) + 1;
  14606. if (next === 0) {
  14607. unclosed('comment', '*/');
  14608. }
  14609. content = css.slice(start, next + 1);
  14610. lines = content.split('\n');
  14611. last = lines.length - 1;
  14612. if (last > 0) {
  14613. nextLine = line + last;
  14614. nextOffset = next - lines[last].length;
  14615. } else {
  14616. nextLine = line;
  14617. nextOffset = offset;
  14618. }
  14619. tokenType = t.comment;
  14620. line = nextLine;
  14621. endLine = nextLine;
  14622. endColumn = next - nextOffset;
  14623. } else if (code === t.slash) {
  14624. next = start;
  14625. tokenType = code;
  14626. endLine = line;
  14627. endColumn = start - offset;
  14628. end = next + 1;
  14629. } else {
  14630. next = consumeWord(css, start);
  14631. tokenType = t.word;
  14632. endLine = line;
  14633. endColumn = next - offset;
  14634. }
  14635. end = next + 1;
  14636. break;
  14637. }
  14638. // Ensure that the token structure remains consistent
  14639. tokens.push([tokenType,
  14640. // [0] Token type
  14641. line,
  14642. // [1] Starting line
  14643. start - offset,
  14644. // [2] Starting column
  14645. endLine,
  14646. // [3] Ending line
  14647. endColumn,
  14648. // [4] Ending column
  14649. start,
  14650. // [5] Start position / Source index
  14651. end // [6] End position
  14652. ]);
  14653. // Reset offset for the next token
  14654. if (nextOffset) {
  14655. offset = nextOffset;
  14656. nextOffset = null;
  14657. }
  14658. start = end;
  14659. }
  14660. return tokens;
  14661. }
  14662. } (tokenize));
  14663. return tokenize;
  14664. }
  14665. var hasRequiredParser;
  14666. function requireParser () {
  14667. if (hasRequiredParser) return parser.exports;
  14668. hasRequiredParser = 1;
  14669. (function (module, exports$1) {
  14670. exports$1.__esModule = true;
  14671. exports$1["default"] = void 0;
  14672. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot());
  14673. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector());
  14674. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName());
  14675. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment());
  14676. var _id = _interopRequireDefault(/*@__PURE__*/ requireId());
  14677. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag());
  14678. var _string = _interopRequireDefault(/*@__PURE__*/ requireString());
  14679. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo());
  14680. var _attribute = _interopRequireWildcard(/*@__PURE__*/ requireAttribute());
  14681. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal());
  14682. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator());
  14683. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting());
  14684. var _sortAscending = _interopRequireDefault(/*@__PURE__*/ requireSortAscending());
  14685. var _tokenize = _interopRequireWildcard(/*@__PURE__*/ requireTokenize());
  14686. var tokens = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes());
  14687. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes());
  14688. var _util = /*@__PURE__*/ requireUtil();
  14689. var _WHITESPACE_TOKENS, _Object$assign;
  14690. 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); }
  14691. 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; }
  14692. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14693. 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); } }
  14694. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  14695. 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);
  14696. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  14697. function tokenStart(token) {
  14698. return {
  14699. line: token[_tokenize.FIELDS.START_LINE],
  14700. column: token[_tokenize.FIELDS.START_COL]
  14701. };
  14702. }
  14703. function tokenEnd(token) {
  14704. return {
  14705. line: token[_tokenize.FIELDS.END_LINE],
  14706. column: token[_tokenize.FIELDS.END_COL]
  14707. };
  14708. }
  14709. function getSource(startLine, startColumn, endLine, endColumn) {
  14710. return {
  14711. start: {
  14712. line: startLine,
  14713. column: startColumn
  14714. },
  14715. end: {
  14716. line: endLine,
  14717. column: endColumn
  14718. }
  14719. };
  14720. }
  14721. function getTokenSource(token) {
  14722. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  14723. }
  14724. function getTokenSourceSpan(startToken, endToken) {
  14725. if (!startToken) {
  14726. return undefined;
  14727. }
  14728. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  14729. }
  14730. function unescapeProp(node, prop) {
  14731. var value = node[prop];
  14732. if (typeof value !== "string") {
  14733. return;
  14734. }
  14735. if (value.indexOf("\\") !== -1) {
  14736. (0, _util.ensureObject)(node, 'raws');
  14737. node[prop] = (0, _util.unesc)(value);
  14738. if (node.raws[prop] === undefined) {
  14739. node.raws[prop] = value;
  14740. }
  14741. }
  14742. return node;
  14743. }
  14744. function indexesOf(array, item) {
  14745. var i = -1;
  14746. var indexes = [];
  14747. while ((i = array.indexOf(item, i + 1)) !== -1) {
  14748. indexes.push(i);
  14749. }
  14750. return indexes;
  14751. }
  14752. function uniqs() {
  14753. var list = Array.prototype.concat.apply([], arguments);
  14754. return list.filter(function (item, i) {
  14755. return i === list.indexOf(item);
  14756. });
  14757. }
  14758. var Parser = /*#__PURE__*/function () {
  14759. function Parser(rule, options) {
  14760. if (options === void 0) {
  14761. options = {};
  14762. }
  14763. this.rule = rule;
  14764. this.options = Object.assign({
  14765. lossy: false,
  14766. safe: false
  14767. }, options);
  14768. this.position = 0;
  14769. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  14770. this.tokens = (0, _tokenize["default"])({
  14771. css: this.css,
  14772. error: this._errorGenerator(),
  14773. safe: this.options.safe
  14774. });
  14775. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  14776. this.root = new _root["default"]({
  14777. source: rootSource
  14778. });
  14779. this.root.errorGenerator = this._errorGenerator();
  14780. var selector = new _selector["default"]({
  14781. source: {
  14782. start: {
  14783. line: 1,
  14784. column: 1
  14785. }
  14786. },
  14787. sourceIndex: 0
  14788. });
  14789. this.root.append(selector);
  14790. this.current = selector;
  14791. this.loop();
  14792. }
  14793. var _proto = Parser.prototype;
  14794. _proto._errorGenerator = function _errorGenerator() {
  14795. var _this = this;
  14796. return function (message, errorOptions) {
  14797. if (typeof _this.rule === 'string') {
  14798. return new Error(message);
  14799. }
  14800. return _this.rule.error(message, errorOptions);
  14801. };
  14802. };
  14803. _proto.attribute = function attribute() {
  14804. var attr = [];
  14805. var startingToken = this.currToken;
  14806. this.position++;
  14807. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  14808. attr.push(this.currToken);
  14809. this.position++;
  14810. }
  14811. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  14812. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  14813. }
  14814. var len = attr.length;
  14815. var node = {
  14816. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  14817. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  14818. };
  14819. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  14820. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  14821. }
  14822. var pos = 0;
  14823. var spaceBefore = '';
  14824. var commentBefore = '';
  14825. var lastAdded = null;
  14826. var spaceAfterMeaningfulToken = false;
  14827. while (pos < len) {
  14828. var token = attr[pos];
  14829. var content = this.content(token);
  14830. var next = attr[pos + 1];
  14831. switch (token[_tokenize.FIELDS.TYPE]) {
  14832. case tokens.space:
  14833. // if (
  14834. // len === 1 ||
  14835. // pos === 0 && this.content(next) === '|'
  14836. // ) {
  14837. // return this.expected('attribute', token[TOKEN.START_POS], content);
  14838. // }
  14839. spaceAfterMeaningfulToken = true;
  14840. if (this.options.lossy) {
  14841. break;
  14842. }
  14843. if (lastAdded) {
  14844. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  14845. var prevContent = node.spaces[lastAdded].after || '';
  14846. node.spaces[lastAdded].after = prevContent + content;
  14847. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  14848. if (existingComment) {
  14849. node.raws.spaces[lastAdded].after = existingComment + content;
  14850. }
  14851. } else {
  14852. spaceBefore = spaceBefore + content;
  14853. commentBefore = commentBefore + content;
  14854. }
  14855. break;
  14856. case tokens.asterisk:
  14857. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14858. node.operator = content;
  14859. lastAdded = 'operator';
  14860. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  14861. if (spaceBefore) {
  14862. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  14863. node.spaces.attribute.before = spaceBefore;
  14864. spaceBefore = '';
  14865. }
  14866. if (commentBefore) {
  14867. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  14868. node.raws.spaces.attribute.before = spaceBefore;
  14869. commentBefore = '';
  14870. }
  14871. node.namespace = (node.namespace || "") + content;
  14872. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  14873. if (rawValue) {
  14874. node.raws.namespace += content;
  14875. }
  14876. lastAdded = 'namespace';
  14877. }
  14878. spaceAfterMeaningfulToken = false;
  14879. break;
  14880. case tokens.dollar:
  14881. if (lastAdded === "value") {
  14882. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  14883. node.value += "$";
  14884. if (oldRawValue) {
  14885. node.raws.value = oldRawValue + "$";
  14886. }
  14887. break;
  14888. }
  14889. // Falls through
  14890. case tokens.caret:
  14891. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14892. node.operator = content;
  14893. lastAdded = 'operator';
  14894. }
  14895. spaceAfterMeaningfulToken = false;
  14896. break;
  14897. case tokens.combinator:
  14898. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14899. node.operator = content;
  14900. lastAdded = 'operator';
  14901. }
  14902. if (content !== '|') {
  14903. spaceAfterMeaningfulToken = false;
  14904. break;
  14905. }
  14906. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14907. node.operator = content;
  14908. lastAdded = 'operator';
  14909. } else if (!node.namespace && !node.attribute) {
  14910. node.namespace = true;
  14911. }
  14912. spaceAfterMeaningfulToken = false;
  14913. break;
  14914. case tokens.word:
  14915. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
  14916. // this look-ahead probably fails with comment nodes involved.
  14917. !node.operator && !node.namespace) {
  14918. node.namespace = content;
  14919. lastAdded = 'namespace';
  14920. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  14921. if (spaceBefore) {
  14922. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  14923. node.spaces.attribute.before = spaceBefore;
  14924. spaceBefore = '';
  14925. }
  14926. if (commentBefore) {
  14927. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  14928. node.raws.spaces.attribute.before = commentBefore;
  14929. commentBefore = '';
  14930. }
  14931. node.attribute = (node.attribute || "") + content;
  14932. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  14933. if (_rawValue) {
  14934. node.raws.attribute += content;
  14935. }
  14936. lastAdded = 'attribute';
  14937. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  14938. var _unescaped = (0, _util.unesc)(content);
  14939. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  14940. var oldValue = node.value || '';
  14941. node.value = oldValue + _unescaped;
  14942. node.quoteMark = null;
  14943. if (_unescaped !== content || _oldRawValue) {
  14944. (0, _util.ensureObject)(node, 'raws');
  14945. node.raws.value = (_oldRawValue || oldValue) + content;
  14946. }
  14947. lastAdded = 'value';
  14948. } else {
  14949. var insensitive = content === 'i' || content === "I";
  14950. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  14951. node.insensitive = insensitive;
  14952. if (!insensitive || content === "I") {
  14953. (0, _util.ensureObject)(node, 'raws');
  14954. node.raws.insensitiveFlag = content;
  14955. }
  14956. lastAdded = 'insensitive';
  14957. if (spaceBefore) {
  14958. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  14959. node.spaces.insensitive.before = spaceBefore;
  14960. spaceBefore = '';
  14961. }
  14962. if (commentBefore) {
  14963. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  14964. node.raws.spaces.insensitive.before = commentBefore;
  14965. commentBefore = '';
  14966. }
  14967. } else if (node.value || node.value === '') {
  14968. lastAdded = 'value';
  14969. node.value += content;
  14970. if (node.raws.value) {
  14971. node.raws.value += content;
  14972. }
  14973. }
  14974. }
  14975. spaceAfterMeaningfulToken = false;
  14976. break;
  14977. case tokens.str:
  14978. if (!node.attribute || !node.operator) {
  14979. return this.error("Expected an attribute followed by an operator preceding the string.", {
  14980. index: token[_tokenize.FIELDS.START_POS]
  14981. });
  14982. }
  14983. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  14984. unescaped = _unescapeValue.unescaped,
  14985. quoteMark = _unescapeValue.quoteMark;
  14986. node.value = unescaped;
  14987. node.quoteMark = quoteMark;
  14988. lastAdded = 'value';
  14989. (0, _util.ensureObject)(node, 'raws');
  14990. node.raws.value = content;
  14991. spaceAfterMeaningfulToken = false;
  14992. break;
  14993. case tokens.equals:
  14994. if (!node.attribute) {
  14995. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  14996. }
  14997. if (node.value) {
  14998. return this.error('Unexpected "=" found; an operator was already defined.', {
  14999. index: token[_tokenize.FIELDS.START_POS]
  15000. });
  15001. }
  15002. node.operator = node.operator ? node.operator + content : content;
  15003. lastAdded = 'operator';
  15004. spaceAfterMeaningfulToken = false;
  15005. break;
  15006. case tokens.comment:
  15007. if (lastAdded) {
  15008. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  15009. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  15010. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  15011. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  15012. node.raws.spaces[lastAdded].after = rawLastComment + content;
  15013. } else {
  15014. var lastValue = node[lastAdded] || '';
  15015. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  15016. (0, _util.ensureObject)(node, 'raws');
  15017. node.raws[lastAdded] = rawLastValue + content;
  15018. }
  15019. } else {
  15020. commentBefore = commentBefore + content;
  15021. }
  15022. break;
  15023. default:
  15024. return this.error("Unexpected \"" + content + "\" found.", {
  15025. index: token[_tokenize.FIELDS.START_POS]
  15026. });
  15027. }
  15028. pos++;
  15029. }
  15030. unescapeProp(node, "attribute");
  15031. unescapeProp(node, "namespace");
  15032. this.newNode(new _attribute["default"](node));
  15033. this.position++;
  15034. }
  15035. /**
  15036. * return a node containing meaningless garbage up to (but not including) the specified token position.
  15037. * if the token position is negative, all remaining tokens are consumed.
  15038. *
  15039. * This returns an array containing a single string node if all whitespace,
  15040. * otherwise an array of comment nodes with space before and after.
  15041. *
  15042. * These tokens are not added to the current selector, the caller can add them or use them to amend
  15043. * a previous node's space metadata.
  15044. *
  15045. * In lossy mode, this returns only comments.
  15046. */;
  15047. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  15048. if (stopPosition < 0) {
  15049. stopPosition = this.tokens.length;
  15050. }
  15051. var startPosition = this.position;
  15052. var nodes = [];
  15053. var space = "";
  15054. var lastComment = undefined;
  15055. do {
  15056. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  15057. if (!this.options.lossy) {
  15058. space += this.content();
  15059. }
  15060. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  15061. var spaces = {};
  15062. if (space) {
  15063. spaces.before = space;
  15064. space = "";
  15065. }
  15066. lastComment = new _comment["default"]({
  15067. value: this.content(),
  15068. source: getTokenSource(this.currToken),
  15069. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  15070. spaces: spaces
  15071. });
  15072. nodes.push(lastComment);
  15073. }
  15074. } while (++this.position < stopPosition);
  15075. if (space) {
  15076. if (lastComment) {
  15077. lastComment.spaces.after = space;
  15078. } else if (!this.options.lossy) {
  15079. var firstToken = this.tokens[startPosition];
  15080. var lastToken = this.tokens[this.position - 1];
  15081. nodes.push(new _string["default"]({
  15082. value: '',
  15083. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  15084. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  15085. spaces: {
  15086. before: space,
  15087. after: ''
  15088. }
  15089. }));
  15090. }
  15091. }
  15092. return nodes;
  15093. }
  15094. /**
  15095. *
  15096. * @param {*} nodes
  15097. */;
  15098. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  15099. var _this2 = this;
  15100. if (requiredSpace === void 0) {
  15101. requiredSpace = false;
  15102. }
  15103. var space = "";
  15104. var rawSpace = "";
  15105. nodes.forEach(function (n) {
  15106. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  15107. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  15108. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  15109. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  15110. });
  15111. if (rawSpace === space) {
  15112. rawSpace = undefined;
  15113. }
  15114. var result = {
  15115. space: space,
  15116. rawSpace: rawSpace
  15117. };
  15118. return result;
  15119. };
  15120. _proto.isNamedCombinator = function isNamedCombinator(position) {
  15121. if (position === void 0) {
  15122. position = this.position;
  15123. }
  15124. 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;
  15125. };
  15126. _proto.namedCombinator = function namedCombinator() {
  15127. if (this.isNamedCombinator()) {
  15128. var nameRaw = this.content(this.tokens[this.position + 1]);
  15129. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  15130. var raws = {};
  15131. if (name !== nameRaw) {
  15132. raws.value = "/" + nameRaw + "/";
  15133. }
  15134. var node = new _combinator["default"]({
  15135. value: "/" + name + "/",
  15136. 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]),
  15137. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  15138. raws: raws
  15139. });
  15140. this.position = this.position + 3;
  15141. return node;
  15142. } else {
  15143. this.unexpected();
  15144. }
  15145. };
  15146. _proto.combinator = function combinator() {
  15147. var _this3 = this;
  15148. if (this.content() === '|') {
  15149. return this.namespace();
  15150. }
  15151. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  15152. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  15153. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15154. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  15155. if (nodes.length > 0) {
  15156. var last = this.current.last;
  15157. if (last) {
  15158. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  15159. space = _this$convertWhitespa.space,
  15160. rawSpace = _this$convertWhitespa.rawSpace;
  15161. if (rawSpace !== undefined) {
  15162. last.rawSpaceAfter += rawSpace;
  15163. }
  15164. last.spaces.after += space;
  15165. } else {
  15166. nodes.forEach(function (n) {
  15167. return _this3.newNode(n);
  15168. });
  15169. }
  15170. }
  15171. return;
  15172. }
  15173. var firstToken = this.currToken;
  15174. var spaceOrDescendantSelectorNodes = undefined;
  15175. if (nextSigTokenPos > this.position) {
  15176. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  15177. }
  15178. var node;
  15179. if (this.isNamedCombinator()) {
  15180. node = this.namedCombinator();
  15181. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  15182. node = new _combinator["default"]({
  15183. value: this.content(),
  15184. source: getTokenSource(this.currToken),
  15185. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  15186. });
  15187. this.position++;
  15188. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  15189. this.unexpected();
  15190. }
  15191. if (node) {
  15192. if (spaceOrDescendantSelectorNodes) {
  15193. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  15194. _space = _this$convertWhitespa2.space,
  15195. _rawSpace = _this$convertWhitespa2.rawSpace;
  15196. node.spaces.before = _space;
  15197. node.rawSpaceBefore = _rawSpace;
  15198. }
  15199. } else {
  15200. // descendant combinator
  15201. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  15202. _space2 = _this$convertWhitespa3.space,
  15203. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  15204. if (!_rawSpace2) {
  15205. _rawSpace2 = _space2;
  15206. }
  15207. var spaces = {};
  15208. var raws = {
  15209. spaces: {}
  15210. };
  15211. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  15212. spaces.before = _space2.slice(0, _space2.length - 1);
  15213. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  15214. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  15215. spaces.after = _space2.slice(1);
  15216. raws.spaces.after = _rawSpace2.slice(1);
  15217. } else {
  15218. raws.value = _rawSpace2;
  15219. }
  15220. node = new _combinator["default"]({
  15221. value: ' ',
  15222. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  15223. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  15224. spaces: spaces,
  15225. raws: raws
  15226. });
  15227. }
  15228. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  15229. node.spaces.after = this.optionalSpace(this.content());
  15230. this.position++;
  15231. }
  15232. return this.newNode(node);
  15233. };
  15234. _proto.comma = function comma() {
  15235. if (this.position === this.tokens.length - 1) {
  15236. this.root.trailingComma = true;
  15237. this.position++;
  15238. return;
  15239. }
  15240. this.current._inferEndPosition();
  15241. var selector = new _selector["default"]({
  15242. source: {
  15243. start: tokenStart(this.tokens[this.position + 1])
  15244. },
  15245. sourceIndex: this.tokens[this.position + 1][_tokenize.FIELDS.START_POS]
  15246. });
  15247. this.current.parent.append(selector);
  15248. this.current = selector;
  15249. this.position++;
  15250. };
  15251. _proto.comment = function comment() {
  15252. var current = this.currToken;
  15253. this.newNode(new _comment["default"]({
  15254. value: this.content(),
  15255. source: getTokenSource(current),
  15256. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15257. }));
  15258. this.position++;
  15259. };
  15260. _proto.error = function error(message, opts) {
  15261. throw this.root.error(message, opts);
  15262. };
  15263. _proto.missingBackslash = function missingBackslash() {
  15264. return this.error('Expected a backslash preceding the semicolon.', {
  15265. index: this.currToken[_tokenize.FIELDS.START_POS]
  15266. });
  15267. };
  15268. _proto.missingParenthesis = function missingParenthesis() {
  15269. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  15270. };
  15271. _proto.missingSquareBracket = function missingSquareBracket() {
  15272. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  15273. };
  15274. _proto.unexpected = function unexpected() {
  15275. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  15276. };
  15277. _proto.unexpectedPipe = function unexpectedPipe() {
  15278. return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  15279. };
  15280. _proto.namespace = function namespace() {
  15281. var before = this.prevToken && this.content(this.prevToken) || true;
  15282. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  15283. this.position++;
  15284. return this.word(before);
  15285. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  15286. this.position++;
  15287. return this.universal(before);
  15288. }
  15289. this.unexpectedPipe();
  15290. };
  15291. _proto.nesting = function nesting() {
  15292. if (this.nextToken) {
  15293. var nextContent = this.content(this.nextToken);
  15294. if (nextContent === "|") {
  15295. this.position++;
  15296. return;
  15297. }
  15298. }
  15299. var current = this.currToken;
  15300. this.newNode(new _nesting["default"]({
  15301. value: this.content(),
  15302. source: getTokenSource(current),
  15303. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15304. }));
  15305. this.position++;
  15306. };
  15307. _proto.parentheses = function parentheses() {
  15308. var last = this.current.last;
  15309. var unbalanced = 1;
  15310. this.position++;
  15311. if (last && last.type === types.PSEUDO) {
  15312. var selector = new _selector["default"]({
  15313. source: {
  15314. start: tokenStart(this.tokens[this.position])
  15315. },
  15316. sourceIndex: this.tokens[this.position][_tokenize.FIELDS.START_POS]
  15317. });
  15318. var cache = this.current;
  15319. last.append(selector);
  15320. this.current = selector;
  15321. while (this.position < this.tokens.length && unbalanced) {
  15322. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15323. unbalanced++;
  15324. }
  15325. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15326. unbalanced--;
  15327. }
  15328. if (unbalanced) {
  15329. this.parse();
  15330. } else {
  15331. this.current.source.end = tokenEnd(this.currToken);
  15332. this.current.parent.source.end = tokenEnd(this.currToken);
  15333. this.position++;
  15334. }
  15335. }
  15336. this.current = cache;
  15337. } else {
  15338. // I think this case should be an error. It's used to implement a basic parse of media queries
  15339. // but I don't think it's a good idea.
  15340. var parenStart = this.currToken;
  15341. var parenValue = "(";
  15342. var parenEnd;
  15343. while (this.position < this.tokens.length && unbalanced) {
  15344. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15345. unbalanced++;
  15346. }
  15347. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15348. unbalanced--;
  15349. }
  15350. parenEnd = this.currToken;
  15351. parenValue += this.parseParenthesisToken(this.currToken);
  15352. this.position++;
  15353. }
  15354. if (last) {
  15355. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  15356. } else {
  15357. this.newNode(new _string["default"]({
  15358. value: parenValue,
  15359. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  15360. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  15361. }));
  15362. }
  15363. }
  15364. if (unbalanced) {
  15365. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  15366. }
  15367. };
  15368. _proto.pseudo = function pseudo() {
  15369. var _this4 = this;
  15370. var pseudoStr = '';
  15371. var startingToken = this.currToken;
  15372. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  15373. pseudoStr += this.content();
  15374. this.position++;
  15375. }
  15376. if (!this.currToken) {
  15377. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  15378. }
  15379. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  15380. this.splitWord(false, function (first, length) {
  15381. pseudoStr += first;
  15382. _this4.newNode(new _pseudo["default"]({
  15383. value: pseudoStr,
  15384. source: getTokenSourceSpan(startingToken, _this4.currToken),
  15385. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  15386. }));
  15387. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15388. _this4.error('Misplaced parenthesis.', {
  15389. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  15390. });
  15391. }
  15392. });
  15393. } else {
  15394. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  15395. }
  15396. };
  15397. _proto.space = function space() {
  15398. var content = this.content();
  15399. // Handle space before and after the selector
  15400. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  15401. return node.type === 'comment';
  15402. })) {
  15403. this.spaces = this.optionalSpace(content);
  15404. this.position++;
  15405. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15406. this.current.last.spaces.after = this.optionalSpace(content);
  15407. this.position++;
  15408. } else {
  15409. this.combinator();
  15410. }
  15411. };
  15412. _proto.string = function string() {
  15413. var current = this.currToken;
  15414. this.newNode(new _string["default"]({
  15415. value: this.content(),
  15416. source: getTokenSource(current),
  15417. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15418. }));
  15419. this.position++;
  15420. };
  15421. _proto.universal = function universal(namespace) {
  15422. var nextToken = this.nextToken;
  15423. if (nextToken && this.content(nextToken) === '|') {
  15424. this.position++;
  15425. return this.namespace();
  15426. }
  15427. var current = this.currToken;
  15428. this.newNode(new _universal["default"]({
  15429. value: this.content(),
  15430. source: getTokenSource(current),
  15431. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15432. }), namespace);
  15433. this.position++;
  15434. };
  15435. _proto.splitWord = function splitWord(namespace, firstCallback) {
  15436. var _this5 = this;
  15437. var nextToken = this.nextToken;
  15438. var word = this.content();
  15439. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  15440. this.position++;
  15441. var current = this.content();
  15442. word += current;
  15443. if (current.lastIndexOf('\\') === current.length - 1) {
  15444. var next = this.nextToken;
  15445. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  15446. word += this.requiredSpace(this.content(next));
  15447. this.position++;
  15448. }
  15449. }
  15450. nextToken = this.nextToken;
  15451. }
  15452. var hasClass = indexesOf(word, '.').filter(function (i) {
  15453. // Allow escaped dot within class name
  15454. var escapedDot = word[i - 1] === '\\';
  15455. // Allow decimal numbers percent in @keyframes
  15456. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  15457. return !escapedDot && !isKeyframesPercent;
  15458. });
  15459. var hasId = indexesOf(word, '#').filter(function (i) {
  15460. return word[i - 1] !== '\\';
  15461. });
  15462. // Eliminate Sass interpolations from the list of id indexes
  15463. var interpolations = indexesOf(word, '#{');
  15464. if (interpolations.length) {
  15465. hasId = hasId.filter(function (hashIndex) {
  15466. return !~interpolations.indexOf(hashIndex);
  15467. });
  15468. }
  15469. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  15470. indices.forEach(function (ind, i) {
  15471. var index = indices[i + 1] || word.length;
  15472. var value = word.slice(ind, index);
  15473. if (i === 0 && firstCallback) {
  15474. return firstCallback.call(_this5, value, indices.length);
  15475. }
  15476. var node;
  15477. var current = _this5.currToken;
  15478. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  15479. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  15480. if (~hasClass.indexOf(ind)) {
  15481. var classNameOpts = {
  15482. value: value.slice(1),
  15483. source: source,
  15484. sourceIndex: sourceIndex
  15485. };
  15486. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  15487. } else if (~hasId.indexOf(ind)) {
  15488. var idOpts = {
  15489. value: value.slice(1),
  15490. source: source,
  15491. sourceIndex: sourceIndex
  15492. };
  15493. node = new _id["default"](unescapeProp(idOpts, "value"));
  15494. } else {
  15495. var tagOpts = {
  15496. value: value,
  15497. source: source,
  15498. sourceIndex: sourceIndex
  15499. };
  15500. unescapeProp(tagOpts, "value");
  15501. node = new _tag["default"](tagOpts);
  15502. }
  15503. _this5.newNode(node, namespace);
  15504. // Ensure that the namespace is used only once
  15505. namespace = null;
  15506. });
  15507. this.position++;
  15508. };
  15509. _proto.word = function word(namespace) {
  15510. var nextToken = this.nextToken;
  15511. if (nextToken && this.content(nextToken) === '|') {
  15512. this.position++;
  15513. return this.namespace();
  15514. }
  15515. return this.splitWord(namespace);
  15516. };
  15517. _proto.loop = function loop() {
  15518. while (this.position < this.tokens.length) {
  15519. this.parse(true);
  15520. }
  15521. this.current._inferEndPosition();
  15522. return this.root;
  15523. };
  15524. _proto.parse = function parse(throwOnParenthesis) {
  15525. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  15526. case tokens.space:
  15527. this.space();
  15528. break;
  15529. case tokens.comment:
  15530. this.comment();
  15531. break;
  15532. case tokens.openParenthesis:
  15533. this.parentheses();
  15534. break;
  15535. case tokens.closeParenthesis:
  15536. if (throwOnParenthesis) {
  15537. this.missingParenthesis();
  15538. }
  15539. break;
  15540. case tokens.openSquare:
  15541. this.attribute();
  15542. break;
  15543. case tokens.dollar:
  15544. case tokens.caret:
  15545. case tokens.equals:
  15546. case tokens.word:
  15547. this.word();
  15548. break;
  15549. case tokens.colon:
  15550. this.pseudo();
  15551. break;
  15552. case tokens.comma:
  15553. this.comma();
  15554. break;
  15555. case tokens.asterisk:
  15556. this.universal();
  15557. break;
  15558. case tokens.ampersand:
  15559. this.nesting();
  15560. break;
  15561. case tokens.slash:
  15562. case tokens.combinator:
  15563. this.combinator();
  15564. break;
  15565. case tokens.str:
  15566. this.string();
  15567. break;
  15568. // These cases throw; no break needed.
  15569. case tokens.closeSquare:
  15570. this.missingSquareBracket();
  15571. case tokens.semicolon:
  15572. this.missingBackslash();
  15573. default:
  15574. this.unexpected();
  15575. }
  15576. }
  15577. /**
  15578. * Helpers
  15579. */;
  15580. _proto.expected = function expected(description, index, found) {
  15581. if (Array.isArray(description)) {
  15582. var last = description.pop();
  15583. description = description.join(', ') + " or " + last;
  15584. }
  15585. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  15586. if (!found) {
  15587. return this.error("Expected " + an + " " + description + ".", {
  15588. index: index
  15589. });
  15590. }
  15591. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  15592. index: index
  15593. });
  15594. };
  15595. _proto.requiredSpace = function requiredSpace(space) {
  15596. return this.options.lossy ? ' ' : space;
  15597. };
  15598. _proto.optionalSpace = function optionalSpace(space) {
  15599. return this.options.lossy ? '' : space;
  15600. };
  15601. _proto.lossySpace = function lossySpace(space, required) {
  15602. if (this.options.lossy) {
  15603. return required ? ' ' : '';
  15604. } else {
  15605. return space;
  15606. }
  15607. };
  15608. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  15609. var content = this.content(token);
  15610. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  15611. return this.requiredSpace(content);
  15612. } else {
  15613. return content;
  15614. }
  15615. };
  15616. _proto.newNode = function newNode(node, namespace) {
  15617. if (namespace) {
  15618. if (/^ +$/.test(namespace)) {
  15619. if (!this.options.lossy) {
  15620. this.spaces = (this.spaces || '') + namespace;
  15621. }
  15622. namespace = true;
  15623. }
  15624. node.namespace = namespace;
  15625. unescapeProp(node, "namespace");
  15626. }
  15627. if (this.spaces) {
  15628. node.spaces.before = this.spaces;
  15629. this.spaces = '';
  15630. }
  15631. return this.current.append(node);
  15632. };
  15633. _proto.content = function content(token) {
  15634. if (token === void 0) {
  15635. token = this.currToken;
  15636. }
  15637. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  15638. };
  15639. /**
  15640. * returns the index of the next non-whitespace, non-comment token.
  15641. * returns -1 if no meaningful token is found.
  15642. */
  15643. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  15644. if (startPosition === void 0) {
  15645. startPosition = this.position + 1;
  15646. }
  15647. var searchPosition = startPosition;
  15648. while (searchPosition < this.tokens.length) {
  15649. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  15650. searchPosition++;
  15651. continue;
  15652. } else {
  15653. return searchPosition;
  15654. }
  15655. }
  15656. return -1;
  15657. };
  15658. _createClass(Parser, [{
  15659. key: "currToken",
  15660. get: function get() {
  15661. return this.tokens[this.position];
  15662. }
  15663. }, {
  15664. key: "nextToken",
  15665. get: function get() {
  15666. return this.tokens[this.position + 1];
  15667. }
  15668. }, {
  15669. key: "prevToken",
  15670. get: function get() {
  15671. return this.tokens[this.position - 1];
  15672. }
  15673. }]);
  15674. return Parser;
  15675. }();
  15676. exports$1["default"] = Parser;
  15677. module.exports = exports$1.default;
  15678. } (parser, parser.exports));
  15679. return parser.exports;
  15680. }
  15681. var hasRequiredProcessor;
  15682. function requireProcessor () {
  15683. if (hasRequiredProcessor) return processor.exports;
  15684. hasRequiredProcessor = 1;
  15685. (function (module, exports$1) {
  15686. exports$1.__esModule = true;
  15687. exports$1["default"] = void 0;
  15688. var _parser = _interopRequireDefault(/*@__PURE__*/ requireParser());
  15689. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  15690. var Processor = /*#__PURE__*/function () {
  15691. function Processor(func, options) {
  15692. this.func = func || function noop() {};
  15693. this.funcRes = null;
  15694. this.options = options;
  15695. }
  15696. var _proto = Processor.prototype;
  15697. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  15698. if (options === void 0) {
  15699. options = {};
  15700. }
  15701. var merged = Object.assign({}, this.options, options);
  15702. if (merged.updateSelector === false) {
  15703. return false;
  15704. } else {
  15705. return typeof rule !== "string";
  15706. }
  15707. };
  15708. _proto._isLossy = function _isLossy(options) {
  15709. if (options === void 0) {
  15710. options = {};
  15711. }
  15712. var merged = Object.assign({}, this.options, options);
  15713. if (merged.lossless === false) {
  15714. return true;
  15715. } else {
  15716. return false;
  15717. }
  15718. };
  15719. _proto._root = function _root(rule, options) {
  15720. if (options === void 0) {
  15721. options = {};
  15722. }
  15723. var parser = new _parser["default"](rule, this._parseOptions(options));
  15724. return parser.root;
  15725. };
  15726. _proto._parseOptions = function _parseOptions(options) {
  15727. return {
  15728. lossy: this._isLossy(options)
  15729. };
  15730. };
  15731. _proto._run = function _run(rule, options) {
  15732. var _this = this;
  15733. if (options === void 0) {
  15734. options = {};
  15735. }
  15736. return new Promise(function (resolve, reject) {
  15737. try {
  15738. var root = _this._root(rule, options);
  15739. Promise.resolve(_this.func(root)).then(function (transform) {
  15740. var string = undefined;
  15741. if (_this._shouldUpdateSelector(rule, options)) {
  15742. string = root.toString();
  15743. rule.selector = string;
  15744. }
  15745. return {
  15746. transform: transform,
  15747. root: root,
  15748. string: string
  15749. };
  15750. }).then(resolve, reject);
  15751. } catch (e) {
  15752. reject(e);
  15753. return;
  15754. }
  15755. });
  15756. };
  15757. _proto._runSync = function _runSync(rule, options) {
  15758. if (options === void 0) {
  15759. options = {};
  15760. }
  15761. var root = this._root(rule, options);
  15762. var transform = this.func(root);
  15763. if (transform && typeof transform.then === "function") {
  15764. throw new Error("Selector processor returned a promise to a synchronous call.");
  15765. }
  15766. var string = undefined;
  15767. if (options.updateSelector && typeof rule !== "string") {
  15768. string = root.toString();
  15769. rule.selector = string;
  15770. }
  15771. return {
  15772. transform: transform,
  15773. root: root,
  15774. string: string
  15775. };
  15776. }
  15777. /**
  15778. * Process rule into a selector AST.
  15779. *
  15780. * @param rule {postcss.Rule | string} The css selector to be processed
  15781. * @param options The options for processing
  15782. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  15783. */;
  15784. _proto.ast = function ast(rule, options) {
  15785. return this._run(rule, options).then(function (result) {
  15786. return result.root;
  15787. });
  15788. }
  15789. /**
  15790. * Process rule into a selector AST synchronously.
  15791. *
  15792. * @param rule {postcss.Rule | string} The css selector to be processed
  15793. * @param options The options for processing
  15794. * @returns {parser.Root} The AST of the selector after processing it.
  15795. */;
  15796. _proto.astSync = function astSync(rule, options) {
  15797. return this._runSync(rule, options).root;
  15798. }
  15799. /**
  15800. * Process a selector into a transformed value asynchronously
  15801. *
  15802. * @param rule {postcss.Rule | string} The css selector to be processed
  15803. * @param options The options for processing
  15804. * @returns {Promise<any>} The value returned by the processor.
  15805. */;
  15806. _proto.transform = function transform(rule, options) {
  15807. return this._run(rule, options).then(function (result) {
  15808. return result.transform;
  15809. });
  15810. }
  15811. /**
  15812. * Process a selector into a transformed value synchronously.
  15813. *
  15814. * @param rule {postcss.Rule | string} The css selector to be processed
  15815. * @param options The options for processing
  15816. * @returns {any} The value returned by the processor.
  15817. */;
  15818. _proto.transformSync = function transformSync(rule, options) {
  15819. return this._runSync(rule, options).transform;
  15820. }
  15821. /**
  15822. * Process a selector into a new selector string asynchronously.
  15823. *
  15824. * @param rule {postcss.Rule | string} The css selector to be processed
  15825. * @param options The options for processing
  15826. * @returns {string} the selector after processing.
  15827. */;
  15828. _proto.process = function process(rule, options) {
  15829. return this._run(rule, options).then(function (result) {
  15830. return result.string || result.root.toString();
  15831. });
  15832. }
  15833. /**
  15834. * Process a selector into a new selector string synchronously.
  15835. *
  15836. * @param rule {postcss.Rule | string} The css selector to be processed
  15837. * @param options The options for processing
  15838. * @returns {string} the selector after processing.
  15839. */;
  15840. _proto.processSync = function processSync(rule, options) {
  15841. var result = this._runSync(rule, options);
  15842. return result.string || result.root.toString();
  15843. };
  15844. return Processor;
  15845. }();
  15846. exports$1["default"] = Processor;
  15847. module.exports = exports$1.default;
  15848. } (processor, processor.exports));
  15849. return processor.exports;
  15850. }
  15851. var selectors = {};
  15852. var constructors = {};
  15853. var hasRequiredConstructors;
  15854. function requireConstructors () {
  15855. if (hasRequiredConstructors) return constructors;
  15856. hasRequiredConstructors = 1;
  15857. constructors.__esModule = true;
  15858. 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;
  15859. var _attribute = _interopRequireDefault(/*@__PURE__*/ requireAttribute());
  15860. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName());
  15861. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator());
  15862. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment());
  15863. var _id = _interopRequireDefault(/*@__PURE__*/ requireId());
  15864. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting());
  15865. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo());
  15866. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot());
  15867. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector());
  15868. var _string = _interopRequireDefault(/*@__PURE__*/ requireString());
  15869. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag());
  15870. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal());
  15871. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  15872. var attribute = function attribute(opts) {
  15873. return new _attribute["default"](opts);
  15874. };
  15875. constructors.attribute = attribute;
  15876. var className = function className(opts) {
  15877. return new _className["default"](opts);
  15878. };
  15879. constructors.className = className;
  15880. var combinator = function combinator(opts) {
  15881. return new _combinator["default"](opts);
  15882. };
  15883. constructors.combinator = combinator;
  15884. var comment = function comment(opts) {
  15885. return new _comment["default"](opts);
  15886. };
  15887. constructors.comment = comment;
  15888. var id = function id(opts) {
  15889. return new _id["default"](opts);
  15890. };
  15891. constructors.id = id;
  15892. var nesting = function nesting(opts) {
  15893. return new _nesting["default"](opts);
  15894. };
  15895. constructors.nesting = nesting;
  15896. var pseudo = function pseudo(opts) {
  15897. return new _pseudo["default"](opts);
  15898. };
  15899. constructors.pseudo = pseudo;
  15900. var root = function root(opts) {
  15901. return new _root["default"](opts);
  15902. };
  15903. constructors.root = root;
  15904. var selector = function selector(opts) {
  15905. return new _selector["default"](opts);
  15906. };
  15907. constructors.selector = selector;
  15908. var string = function string(opts) {
  15909. return new _string["default"](opts);
  15910. };
  15911. constructors.string = string;
  15912. var tag = function tag(opts) {
  15913. return new _tag["default"](opts);
  15914. };
  15915. constructors.tag = tag;
  15916. var universal = function universal(opts) {
  15917. return new _universal["default"](opts);
  15918. };
  15919. constructors.universal = universal;
  15920. return constructors;
  15921. }
  15922. var guards = {};
  15923. var hasRequiredGuards;
  15924. function requireGuards () {
  15925. if (hasRequiredGuards) return guards;
  15926. hasRequiredGuards = 1;
  15927. guards.__esModule = true;
  15928. guards.isComment = guards.isCombinator = guards.isClassName = guards.isAttribute = void 0;
  15929. guards.isContainer = isContainer;
  15930. guards.isIdentifier = void 0;
  15931. guards.isNamespace = isNamespace;
  15932. guards.isNesting = void 0;
  15933. guards.isNode = isNode;
  15934. guards.isPseudo = void 0;
  15935. guards.isPseudoClass = isPseudoClass;
  15936. guards.isPseudoElement = isPseudoElement;
  15937. guards.isUniversal = guards.isTag = guards.isString = guards.isSelector = guards.isRoot = void 0;
  15938. var _types = /*@__PURE__*/ requireTypes();
  15939. var _IS_TYPE;
  15940. 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);
  15941. function isNode(node) {
  15942. return typeof node === "object" && IS_TYPE[node.type];
  15943. }
  15944. function isNodeType(type, node) {
  15945. return isNode(node) && node.type === type;
  15946. }
  15947. var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  15948. guards.isAttribute = isAttribute;
  15949. var isClassName = isNodeType.bind(null, _types.CLASS);
  15950. guards.isClassName = isClassName;
  15951. var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  15952. guards.isCombinator = isCombinator;
  15953. var isComment = isNodeType.bind(null, _types.COMMENT);
  15954. guards.isComment = isComment;
  15955. var isIdentifier = isNodeType.bind(null, _types.ID);
  15956. guards.isIdentifier = isIdentifier;
  15957. var isNesting = isNodeType.bind(null, _types.NESTING);
  15958. guards.isNesting = isNesting;
  15959. var isPseudo = isNodeType.bind(null, _types.PSEUDO);
  15960. guards.isPseudo = isPseudo;
  15961. var isRoot = isNodeType.bind(null, _types.ROOT);
  15962. guards.isRoot = isRoot;
  15963. var isSelector = isNodeType.bind(null, _types.SELECTOR);
  15964. guards.isSelector = isSelector;
  15965. var isString = isNodeType.bind(null, _types.STRING);
  15966. guards.isString = isString;
  15967. var isTag = isNodeType.bind(null, _types.TAG);
  15968. guards.isTag = isTag;
  15969. var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  15970. guards.isUniversal = isUniversal;
  15971. function isPseudoElement(node) {
  15972. 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");
  15973. }
  15974. function isPseudoClass(node) {
  15975. return isPseudo(node) && !isPseudoElement(node);
  15976. }
  15977. function isContainer(node) {
  15978. return !!(isNode(node) && node.walk);
  15979. }
  15980. function isNamespace(node) {
  15981. return isAttribute(node) || isTag(node);
  15982. }
  15983. return guards;
  15984. }
  15985. var hasRequiredSelectors;
  15986. function requireSelectors () {
  15987. if (hasRequiredSelectors) return selectors;
  15988. hasRequiredSelectors = 1;
  15989. (function (exports$1) {
  15990. exports$1.__esModule = true;
  15991. var _types = /*@__PURE__*/ requireTypes();
  15992. Object.keys(_types).forEach(function (key) {
  15993. if (key === "default" || key === "__esModule") return;
  15994. if (key in exports$1 && exports$1[key] === _types[key]) return;
  15995. exports$1[key] = _types[key];
  15996. });
  15997. var _constructors = /*@__PURE__*/ requireConstructors();
  15998. Object.keys(_constructors).forEach(function (key) {
  15999. if (key === "default" || key === "__esModule") return;
  16000. if (key in exports$1 && exports$1[key] === _constructors[key]) return;
  16001. exports$1[key] = _constructors[key];
  16002. });
  16003. var _guards = /*@__PURE__*/ requireGuards();
  16004. Object.keys(_guards).forEach(function (key) {
  16005. if (key === "default" || key === "__esModule") return;
  16006. if (key in exports$1 && exports$1[key] === _guards[key]) return;
  16007. exports$1[key] = _guards[key];
  16008. });
  16009. } (selectors));
  16010. return selectors;
  16011. }
  16012. var hasRequiredDist;
  16013. function requireDist () {
  16014. if (hasRequiredDist) return dist.exports;
  16015. hasRequiredDist = 1;
  16016. (function (module, exports$1) {
  16017. exports$1.__esModule = true;
  16018. exports$1["default"] = void 0;
  16019. var _processor = _interopRequireDefault(/*@__PURE__*/ requireProcessor());
  16020. var selectors = _interopRequireWildcard(/*@__PURE__*/ requireSelectors());
  16021. 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); }
  16022. 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; }
  16023. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  16024. var parser = function parser(processor) {
  16025. return new _processor["default"](processor);
  16026. };
  16027. Object.assign(parser, selectors);
  16028. delete parser.__esModule;
  16029. var _default = parser;
  16030. exports$1["default"] = _default;
  16031. module.exports = exports$1.default;
  16032. } (dist, dist.exports));
  16033. return dist.exports;
  16034. }
  16035. var parse;
  16036. var hasRequiredParse;
  16037. function requireParse () {
  16038. if (hasRequiredParse) return parse;
  16039. hasRequiredParse = 1;
  16040. var openParentheses = "(".charCodeAt(0);
  16041. var closeParentheses = ")".charCodeAt(0);
  16042. var singleQuote = "'".charCodeAt(0);
  16043. var doubleQuote = '"'.charCodeAt(0);
  16044. var backslash = "\\".charCodeAt(0);
  16045. var slash = "/".charCodeAt(0);
  16046. var comma = ",".charCodeAt(0);
  16047. var colon = ":".charCodeAt(0);
  16048. var star = "*".charCodeAt(0);
  16049. var uLower = "u".charCodeAt(0);
  16050. var uUpper = "U".charCodeAt(0);
  16051. var plus = "+".charCodeAt(0);
  16052. var isUnicodeRange = /^[a-f0-9?-]+$/i;
  16053. parse = function(input) {
  16054. var tokens = [];
  16055. var value = input;
  16056. var next,
  16057. quote,
  16058. prev,
  16059. token,
  16060. escape,
  16061. escapePos,
  16062. whitespacePos,
  16063. parenthesesOpenPos;
  16064. var pos = 0;
  16065. var code = value.charCodeAt(pos);
  16066. var max = value.length;
  16067. var stack = [{ nodes: tokens }];
  16068. var balanced = 0;
  16069. var parent;
  16070. var name = "";
  16071. var before = "";
  16072. var after = "";
  16073. while (pos < max) {
  16074. // Whitespaces
  16075. if (code <= 32) {
  16076. next = pos;
  16077. do {
  16078. next += 1;
  16079. code = value.charCodeAt(next);
  16080. } while (code <= 32);
  16081. token = value.slice(pos, next);
  16082. prev = tokens[tokens.length - 1];
  16083. if (code === closeParentheses && balanced) {
  16084. after = token;
  16085. } else if (prev && prev.type === "div") {
  16086. prev.after = token;
  16087. prev.sourceEndIndex += token.length;
  16088. } else if (
  16089. code === comma ||
  16090. code === colon ||
  16091. (code === slash &&
  16092. value.charCodeAt(next + 1) !== star &&
  16093. (!parent ||
  16094. (parent && parent.type === "function" && parent.value !== "calc")))
  16095. ) {
  16096. before = token;
  16097. } else {
  16098. tokens.push({
  16099. type: "space",
  16100. sourceIndex: pos,
  16101. sourceEndIndex: next,
  16102. value: token
  16103. });
  16104. }
  16105. pos = next;
  16106. // Quotes
  16107. } else if (code === singleQuote || code === doubleQuote) {
  16108. next = pos;
  16109. quote = code === singleQuote ? "'" : '"';
  16110. token = {
  16111. type: "string",
  16112. sourceIndex: pos,
  16113. quote: quote
  16114. };
  16115. do {
  16116. escape = false;
  16117. next = value.indexOf(quote, next + 1);
  16118. if (~next) {
  16119. escapePos = next;
  16120. while (value.charCodeAt(escapePos - 1) === backslash) {
  16121. escapePos -= 1;
  16122. escape = !escape;
  16123. }
  16124. } else {
  16125. value += quote;
  16126. next = value.length - 1;
  16127. token.unclosed = true;
  16128. }
  16129. } while (escape);
  16130. token.value = value.slice(pos + 1, next);
  16131. token.sourceEndIndex = token.unclosed ? next : next + 1;
  16132. tokens.push(token);
  16133. pos = next + 1;
  16134. code = value.charCodeAt(pos);
  16135. // Comments
  16136. } else if (code === slash && value.charCodeAt(pos + 1) === star) {
  16137. next = value.indexOf("*/", pos);
  16138. token = {
  16139. type: "comment",
  16140. sourceIndex: pos,
  16141. sourceEndIndex: next + 2
  16142. };
  16143. if (next === -1) {
  16144. token.unclosed = true;
  16145. next = value.length;
  16146. token.sourceEndIndex = next;
  16147. }
  16148. token.value = value.slice(pos + 2, next);
  16149. tokens.push(token);
  16150. pos = next + 2;
  16151. code = value.charCodeAt(pos);
  16152. // Operation within calc
  16153. } else if (
  16154. (code === slash || code === star) &&
  16155. parent &&
  16156. parent.type === "function" &&
  16157. parent.value === "calc"
  16158. ) {
  16159. token = value[pos];
  16160. tokens.push({
  16161. type: "word",
  16162. sourceIndex: pos - before.length,
  16163. sourceEndIndex: pos + token.length,
  16164. value: token
  16165. });
  16166. pos += 1;
  16167. code = value.charCodeAt(pos);
  16168. // Dividers
  16169. } else if (code === slash || code === comma || code === colon) {
  16170. token = value[pos];
  16171. tokens.push({
  16172. type: "div",
  16173. sourceIndex: pos - before.length,
  16174. sourceEndIndex: pos + token.length,
  16175. value: token,
  16176. before: before,
  16177. after: ""
  16178. });
  16179. before = "";
  16180. pos += 1;
  16181. code = value.charCodeAt(pos);
  16182. // Open parentheses
  16183. } else if (openParentheses === code) {
  16184. // Whitespaces after open parentheses
  16185. next = pos;
  16186. do {
  16187. next += 1;
  16188. code = value.charCodeAt(next);
  16189. } while (code <= 32);
  16190. parenthesesOpenPos = pos;
  16191. token = {
  16192. type: "function",
  16193. sourceIndex: pos - name.length,
  16194. value: name,
  16195. before: value.slice(parenthesesOpenPos + 1, next)
  16196. };
  16197. pos = next;
  16198. if (name === "url" && code !== singleQuote && code !== doubleQuote) {
  16199. next -= 1;
  16200. do {
  16201. escape = false;
  16202. next = value.indexOf(")", next + 1);
  16203. if (~next) {
  16204. escapePos = next;
  16205. while (value.charCodeAt(escapePos - 1) === backslash) {
  16206. escapePos -= 1;
  16207. escape = !escape;
  16208. }
  16209. } else {
  16210. value += ")";
  16211. next = value.length - 1;
  16212. token.unclosed = true;
  16213. }
  16214. } while (escape);
  16215. // Whitespaces before closed
  16216. whitespacePos = next;
  16217. do {
  16218. whitespacePos -= 1;
  16219. code = value.charCodeAt(whitespacePos);
  16220. } while (code <= 32);
  16221. if (parenthesesOpenPos < whitespacePos) {
  16222. if (pos !== whitespacePos + 1) {
  16223. token.nodes = [
  16224. {
  16225. type: "word",
  16226. sourceIndex: pos,
  16227. sourceEndIndex: whitespacePos + 1,
  16228. value: value.slice(pos, whitespacePos + 1)
  16229. }
  16230. ];
  16231. } else {
  16232. token.nodes = [];
  16233. }
  16234. if (token.unclosed && whitespacePos + 1 !== next) {
  16235. token.after = "";
  16236. token.nodes.push({
  16237. type: "space",
  16238. sourceIndex: whitespacePos + 1,
  16239. sourceEndIndex: next,
  16240. value: value.slice(whitespacePos + 1, next)
  16241. });
  16242. } else {
  16243. token.after = value.slice(whitespacePos + 1, next);
  16244. token.sourceEndIndex = next;
  16245. }
  16246. } else {
  16247. token.after = "";
  16248. token.nodes = [];
  16249. }
  16250. pos = next + 1;
  16251. token.sourceEndIndex = token.unclosed ? next : pos;
  16252. code = value.charCodeAt(pos);
  16253. tokens.push(token);
  16254. } else {
  16255. balanced += 1;
  16256. token.after = "";
  16257. token.sourceEndIndex = pos + 1;
  16258. tokens.push(token);
  16259. stack.push(token);
  16260. tokens = token.nodes = [];
  16261. parent = token;
  16262. }
  16263. name = "";
  16264. // Close parentheses
  16265. } else if (closeParentheses === code && balanced) {
  16266. pos += 1;
  16267. code = value.charCodeAt(pos);
  16268. parent.after = after;
  16269. parent.sourceEndIndex += after.length;
  16270. after = "";
  16271. balanced -= 1;
  16272. stack[stack.length - 1].sourceEndIndex = pos;
  16273. stack.pop();
  16274. parent = stack[balanced];
  16275. tokens = parent.nodes;
  16276. // Words
  16277. } else {
  16278. next = pos;
  16279. do {
  16280. if (code === backslash) {
  16281. next += 1;
  16282. }
  16283. next += 1;
  16284. code = value.charCodeAt(next);
  16285. } while (
  16286. next < max &&
  16287. !(
  16288. code <= 32 ||
  16289. code === singleQuote ||
  16290. code === doubleQuote ||
  16291. code === comma ||
  16292. code === colon ||
  16293. code === slash ||
  16294. code === openParentheses ||
  16295. (code === star &&
  16296. parent &&
  16297. parent.type === "function" &&
  16298. parent.value === "calc") ||
  16299. (code === slash &&
  16300. parent.type === "function" &&
  16301. parent.value === "calc") ||
  16302. (code === closeParentheses && balanced)
  16303. )
  16304. );
  16305. token = value.slice(pos, next);
  16306. if (openParentheses === code) {
  16307. name = token;
  16308. } else if (
  16309. (uLower === token.charCodeAt(0) || uUpper === token.charCodeAt(0)) &&
  16310. plus === token.charCodeAt(1) &&
  16311. isUnicodeRange.test(token.slice(2))
  16312. ) {
  16313. tokens.push({
  16314. type: "unicode-range",
  16315. sourceIndex: pos,
  16316. sourceEndIndex: next,
  16317. value: token
  16318. });
  16319. } else {
  16320. tokens.push({
  16321. type: "word",
  16322. sourceIndex: pos,
  16323. sourceEndIndex: next,
  16324. value: token
  16325. });
  16326. }
  16327. pos = next;
  16328. }
  16329. }
  16330. for (pos = stack.length - 1; pos; pos -= 1) {
  16331. stack[pos].unclosed = true;
  16332. stack[pos].sourceEndIndex = value.length;
  16333. }
  16334. return stack[0].nodes;
  16335. };
  16336. return parse;
  16337. }
  16338. var walk$1;
  16339. var hasRequiredWalk;
  16340. function requireWalk () {
  16341. if (hasRequiredWalk) return walk$1;
  16342. hasRequiredWalk = 1;
  16343. walk$1 = function walk(nodes, cb, bubble) {
  16344. var i, max, node, result;
  16345. for (i = 0, max = nodes.length; i < max; i += 1) {
  16346. node = nodes[i];
  16347. if (!bubble) {
  16348. result = cb(node, i, nodes);
  16349. }
  16350. if (
  16351. result !== false &&
  16352. node.type === "function" &&
  16353. Array.isArray(node.nodes)
  16354. ) {
  16355. walk(node.nodes, cb, bubble);
  16356. }
  16357. if (bubble) {
  16358. cb(node, i, nodes);
  16359. }
  16360. }
  16361. };
  16362. return walk$1;
  16363. }
  16364. var stringify_1;
  16365. var hasRequiredStringify;
  16366. function requireStringify () {
  16367. if (hasRequiredStringify) return stringify_1;
  16368. hasRequiredStringify = 1;
  16369. function stringifyNode(node, custom) {
  16370. var type = node.type;
  16371. var value = node.value;
  16372. var buf;
  16373. var customResult;
  16374. if (custom && (customResult = custom(node)) !== undefined) {
  16375. return customResult;
  16376. } else if (type === "word" || type === "space") {
  16377. return value;
  16378. } else if (type === "string") {
  16379. buf = node.quote || "";
  16380. return buf + value + (node.unclosed ? "" : buf);
  16381. } else if (type === "comment") {
  16382. return "/*" + value + (node.unclosed ? "" : "*/");
  16383. } else if (type === "div") {
  16384. return (node.before || "") + value + (node.after || "");
  16385. } else if (Array.isArray(node.nodes)) {
  16386. buf = stringify(node.nodes, custom);
  16387. if (type !== "function") {
  16388. return buf;
  16389. }
  16390. return (
  16391. value +
  16392. "(" +
  16393. (node.before || "") +
  16394. buf +
  16395. (node.after || "") +
  16396. (node.unclosed ? "" : ")")
  16397. );
  16398. }
  16399. return value;
  16400. }
  16401. function stringify(nodes, custom) {
  16402. var result, i;
  16403. if (Array.isArray(nodes)) {
  16404. result = "";
  16405. for (i = nodes.length - 1; ~i; i -= 1) {
  16406. result = stringifyNode(nodes[i], custom) + result;
  16407. }
  16408. return result;
  16409. }
  16410. return stringifyNode(nodes, custom);
  16411. }
  16412. stringify_1 = stringify;
  16413. return stringify_1;
  16414. }
  16415. var unit;
  16416. var hasRequiredUnit;
  16417. function requireUnit () {
  16418. if (hasRequiredUnit) return unit;
  16419. hasRequiredUnit = 1;
  16420. var minus = "-".charCodeAt(0);
  16421. var plus = "+".charCodeAt(0);
  16422. var dot = ".".charCodeAt(0);
  16423. var exp = "e".charCodeAt(0);
  16424. var EXP = "E".charCodeAt(0);
  16425. // Check if three code points would start a number
  16426. // https://www.w3.org/TR/css-syntax-3/#starts-with-a-number
  16427. function likeNumber(value) {
  16428. var code = value.charCodeAt(0);
  16429. var nextCode;
  16430. if (code === plus || code === minus) {
  16431. nextCode = value.charCodeAt(1);
  16432. if (nextCode >= 48 && nextCode <= 57) {
  16433. return true;
  16434. }
  16435. var nextNextCode = value.charCodeAt(2);
  16436. if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) {
  16437. return true;
  16438. }
  16439. return false;
  16440. }
  16441. if (code === dot) {
  16442. nextCode = value.charCodeAt(1);
  16443. if (nextCode >= 48 && nextCode <= 57) {
  16444. return true;
  16445. }
  16446. return false;
  16447. }
  16448. if (code >= 48 && code <= 57) {
  16449. return true;
  16450. }
  16451. return false;
  16452. }
  16453. // Consume a number
  16454. // https://www.w3.org/TR/css-syntax-3/#consume-number
  16455. unit = function(value) {
  16456. var pos = 0;
  16457. var length = value.length;
  16458. var code;
  16459. var nextCode;
  16460. var nextNextCode;
  16461. if (length === 0 || !likeNumber(value)) {
  16462. return false;
  16463. }
  16464. code = value.charCodeAt(pos);
  16465. if (code === plus || code === minus) {
  16466. pos++;
  16467. }
  16468. while (pos < length) {
  16469. code = value.charCodeAt(pos);
  16470. if (code < 48 || code > 57) {
  16471. break;
  16472. }
  16473. pos += 1;
  16474. }
  16475. code = value.charCodeAt(pos);
  16476. nextCode = value.charCodeAt(pos + 1);
  16477. if (code === dot && nextCode >= 48 && nextCode <= 57) {
  16478. pos += 2;
  16479. while (pos < length) {
  16480. code = value.charCodeAt(pos);
  16481. if (code < 48 || code > 57) {
  16482. break;
  16483. }
  16484. pos += 1;
  16485. }
  16486. }
  16487. code = value.charCodeAt(pos);
  16488. nextCode = value.charCodeAt(pos + 1);
  16489. nextNextCode = value.charCodeAt(pos + 2);
  16490. if (
  16491. (code === exp || code === EXP) &&
  16492. ((nextCode >= 48 && nextCode <= 57) ||
  16493. ((nextCode === plus || nextCode === minus) &&
  16494. nextNextCode >= 48 &&
  16495. nextNextCode <= 57))
  16496. ) {
  16497. pos += nextCode === plus || nextCode === minus ? 3 : 2;
  16498. while (pos < length) {
  16499. code = value.charCodeAt(pos);
  16500. if (code < 48 || code > 57) {
  16501. break;
  16502. }
  16503. pos += 1;
  16504. }
  16505. }
  16506. return {
  16507. number: value.slice(0, pos),
  16508. unit: value.slice(pos)
  16509. };
  16510. };
  16511. return unit;
  16512. }
  16513. var lib;
  16514. var hasRequiredLib;
  16515. function requireLib () {
  16516. if (hasRequiredLib) return lib;
  16517. hasRequiredLib = 1;
  16518. var parse = /*@__PURE__*/ requireParse();
  16519. var walk = /*@__PURE__*/ requireWalk();
  16520. var stringify = /*@__PURE__*/ requireStringify();
  16521. function ValueParser(value) {
  16522. if (this instanceof ValueParser) {
  16523. this.nodes = parse(value);
  16524. return this;
  16525. }
  16526. return new ValueParser(value);
  16527. }
  16528. ValueParser.prototype.toString = function() {
  16529. return Array.isArray(this.nodes) ? stringify(this.nodes) : "";
  16530. };
  16531. ValueParser.prototype.walk = function(cb, bubble) {
  16532. walk(this.nodes, cb, bubble);
  16533. return this;
  16534. };
  16535. ValueParser.unit = /*@__PURE__*/ requireUnit();
  16536. ValueParser.walk = walk;
  16537. ValueParser.stringify = stringify;
  16538. lib = ValueParser;
  16539. return lib;
  16540. }
  16541. var hasRequiredSrc$2;
  16542. function requireSrc$2 () {
  16543. if (hasRequiredSrc$2) return src$2.exports;
  16544. hasRequiredSrc$2 = 1;
  16545. const selectorParser = /*@__PURE__*/ requireDist();
  16546. const valueParser = /*@__PURE__*/ requireLib();
  16547. const { extractICSS } = /*@__PURE__*/ requireSrc$4();
  16548. const isSpacing = (node) => node.type === "combinator" && node.value === " ";
  16549. function normalizeNodeArray(nodes) {
  16550. const array = [];
  16551. nodes.forEach((x) => {
  16552. if (Array.isArray(x)) {
  16553. normalizeNodeArray(x).forEach((item) => {
  16554. array.push(item);
  16555. });
  16556. } else if (x) {
  16557. array.push(x);
  16558. }
  16559. });
  16560. if (array.length > 0 && isSpacing(array[array.length - 1])) {
  16561. array.pop();
  16562. }
  16563. return array;
  16564. }
  16565. function localizeNode(rule, mode, localAliasMap) {
  16566. const transform = (node, context) => {
  16567. if (context.ignoreNextSpacing && !isSpacing(node)) {
  16568. throw new Error("Missing whitespace after " + context.ignoreNextSpacing);
  16569. }
  16570. if (context.enforceNoSpacing && isSpacing(node)) {
  16571. throw new Error("Missing whitespace before " + context.enforceNoSpacing);
  16572. }
  16573. let newNodes;
  16574. switch (node.type) {
  16575. case "root": {
  16576. let resultingGlobal;
  16577. context.hasPureGlobals = false;
  16578. newNodes = node.nodes.map((n) => {
  16579. const nContext = {
  16580. global: context.global,
  16581. lastWasSpacing: true,
  16582. hasLocals: false,
  16583. explicit: false,
  16584. };
  16585. n = transform(n, nContext);
  16586. if (typeof resultingGlobal === "undefined") {
  16587. resultingGlobal = nContext.global;
  16588. } else if (resultingGlobal !== nContext.global) {
  16589. throw new Error(
  16590. 'Inconsistent rule global/local result in rule "' +
  16591. node +
  16592. '" (multiple selectors must result in the same mode for the rule)'
  16593. );
  16594. }
  16595. if (!nContext.hasLocals) {
  16596. context.hasPureGlobals = true;
  16597. }
  16598. return n;
  16599. });
  16600. context.global = resultingGlobal;
  16601. node.nodes = normalizeNodeArray(newNodes);
  16602. break;
  16603. }
  16604. case "selector": {
  16605. newNodes = node.map((childNode) => transform(childNode, context));
  16606. node = node.clone();
  16607. node.nodes = normalizeNodeArray(newNodes);
  16608. break;
  16609. }
  16610. case "combinator": {
  16611. if (isSpacing(node)) {
  16612. if (context.ignoreNextSpacing) {
  16613. context.ignoreNextSpacing = false;
  16614. context.lastWasSpacing = false;
  16615. context.enforceNoSpacing = false;
  16616. return null;
  16617. }
  16618. context.lastWasSpacing = true;
  16619. return node;
  16620. }
  16621. break;
  16622. }
  16623. case "pseudo": {
  16624. let childContext;
  16625. const isNested = !!node.length;
  16626. const isScoped = node.value === ":local" || node.value === ":global";
  16627. const isImportExport =
  16628. node.value === ":import" || node.value === ":export";
  16629. if (isImportExport) {
  16630. context.hasLocals = true;
  16631. // :local(.foo)
  16632. } else if (isNested) {
  16633. if (isScoped) {
  16634. if (node.nodes.length === 0) {
  16635. throw new Error(`${node.value}() can't be empty`);
  16636. }
  16637. if (context.inside) {
  16638. throw new Error(
  16639. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  16640. );
  16641. }
  16642. childContext = {
  16643. global: node.value === ":global",
  16644. inside: node.value,
  16645. hasLocals: false,
  16646. explicit: true,
  16647. };
  16648. newNodes = node
  16649. .map((childNode) => transform(childNode, childContext))
  16650. .reduce((acc, next) => acc.concat(next.nodes), []);
  16651. if (newNodes.length) {
  16652. const { before, after } = node.spaces;
  16653. const first = newNodes[0];
  16654. const last = newNodes[newNodes.length - 1];
  16655. first.spaces = { before, after: first.spaces.after };
  16656. last.spaces = { before: last.spaces.before, after };
  16657. }
  16658. node = newNodes;
  16659. break;
  16660. } else {
  16661. childContext = {
  16662. global: context.global,
  16663. inside: context.inside,
  16664. lastWasSpacing: true,
  16665. hasLocals: false,
  16666. explicit: context.explicit,
  16667. };
  16668. newNodes = node.map((childNode) => {
  16669. const newContext = {
  16670. ...childContext,
  16671. enforceNoSpacing: false,
  16672. };
  16673. const result = transform(childNode, newContext);
  16674. childContext.global = newContext.global;
  16675. childContext.hasLocals = newContext.hasLocals;
  16676. return result;
  16677. });
  16678. node = node.clone();
  16679. node.nodes = normalizeNodeArray(newNodes);
  16680. if (childContext.hasLocals) {
  16681. context.hasLocals = true;
  16682. }
  16683. }
  16684. break;
  16685. //:local .foo .bar
  16686. } else if (isScoped) {
  16687. if (context.inside) {
  16688. throw new Error(
  16689. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  16690. );
  16691. }
  16692. const addBackSpacing = !!node.spaces.before;
  16693. context.ignoreNextSpacing = context.lastWasSpacing
  16694. ? node.value
  16695. : false;
  16696. context.enforceNoSpacing = context.lastWasSpacing
  16697. ? false
  16698. : node.value;
  16699. context.global = node.value === ":global";
  16700. context.explicit = true;
  16701. // because this node has spacing that is lost when we remove it
  16702. // we make up for it by adding an extra combinator in since adding
  16703. // spacing on the parent selector doesn't work
  16704. return addBackSpacing
  16705. ? selectorParser.combinator({ value: " " })
  16706. : null;
  16707. }
  16708. break;
  16709. }
  16710. case "id":
  16711. case "class": {
  16712. if (!node.value) {
  16713. throw new Error("Invalid class or id selector syntax");
  16714. }
  16715. if (context.global) {
  16716. break;
  16717. }
  16718. const isImportedValue = localAliasMap.has(node.value);
  16719. const isImportedWithExplicitScope = isImportedValue && context.explicit;
  16720. if (!isImportedValue || isImportedWithExplicitScope) {
  16721. const innerNode = node.clone();
  16722. innerNode.spaces = { before: "", after: "" };
  16723. node = selectorParser.pseudo({
  16724. value: ":local",
  16725. nodes: [innerNode],
  16726. spaces: node.spaces,
  16727. });
  16728. context.hasLocals = true;
  16729. }
  16730. break;
  16731. }
  16732. case "nesting": {
  16733. if (node.value === "&") {
  16734. context.hasLocals = true;
  16735. }
  16736. }
  16737. }
  16738. context.lastWasSpacing = false;
  16739. context.ignoreNextSpacing = false;
  16740. context.enforceNoSpacing = false;
  16741. return node;
  16742. };
  16743. const rootContext = {
  16744. global: mode === "global",
  16745. hasPureGlobals: false,
  16746. };
  16747. rootContext.selector = selectorParser((root) => {
  16748. transform(root, rootContext);
  16749. }).processSync(rule, { updateSelector: false, lossless: true });
  16750. return rootContext;
  16751. }
  16752. function localizeDeclNode(node, context) {
  16753. switch (node.type) {
  16754. case "word":
  16755. if (context.localizeNextItem) {
  16756. if (!context.localAliasMap.has(node.value)) {
  16757. node.value = ":local(" + node.value + ")";
  16758. context.localizeNextItem = false;
  16759. }
  16760. }
  16761. break;
  16762. case "function":
  16763. if (
  16764. context.options &&
  16765. context.options.rewriteUrl &&
  16766. node.value.toLowerCase() === "url"
  16767. ) {
  16768. node.nodes.map((nestedNode) => {
  16769. if (nestedNode.type !== "string" && nestedNode.type !== "word") {
  16770. return;
  16771. }
  16772. let newUrl = context.options.rewriteUrl(
  16773. context.global,
  16774. nestedNode.value
  16775. );
  16776. switch (nestedNode.type) {
  16777. case "string":
  16778. if (nestedNode.quote === "'") {
  16779. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/'/g, "\\'");
  16780. }
  16781. if (nestedNode.quote === '"') {
  16782. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/"/g, '\\"');
  16783. }
  16784. break;
  16785. case "word":
  16786. newUrl = newUrl.replace(/("|'|\)|\\)/g, "\\$1");
  16787. break;
  16788. }
  16789. nestedNode.value = newUrl;
  16790. });
  16791. }
  16792. break;
  16793. }
  16794. return node;
  16795. }
  16796. // `none` is special value, other is global values
  16797. const specialKeywords = [
  16798. "none",
  16799. "inherit",
  16800. "initial",
  16801. "revert",
  16802. "revert-layer",
  16803. "unset",
  16804. ];
  16805. function localizeDeclarationValues(localize, declaration, context) {
  16806. const valueNodes = valueParser(declaration.value);
  16807. valueNodes.walk((node, index, nodes) => {
  16808. if (
  16809. node.type === "function" &&
  16810. (node.value.toLowerCase() === "var" || node.value.toLowerCase() === "env")
  16811. ) {
  16812. return false;
  16813. }
  16814. if (
  16815. node.type === "word" &&
  16816. specialKeywords.includes(node.value.toLowerCase())
  16817. ) {
  16818. return;
  16819. }
  16820. const subContext = {
  16821. options: context.options,
  16822. global: context.global,
  16823. localizeNextItem: localize && !context.global,
  16824. localAliasMap: context.localAliasMap,
  16825. };
  16826. nodes[index] = localizeDeclNode(node, subContext);
  16827. });
  16828. declaration.value = valueNodes.toString();
  16829. }
  16830. function localizeDeclaration(declaration, context) {
  16831. const isAnimation = /animation$/i.test(declaration.prop);
  16832. if (isAnimation) {
  16833. // letter
  16834. // An uppercase letter or a lowercase letter.
  16835. //
  16836. // ident-start code point
  16837. // A letter, a non-ASCII code point, or U+005F LOW LINE (_).
  16838. //
  16839. // ident code point
  16840. // An ident-start code point, a digit, or U+002D HYPHEN-MINUS (-).
  16841. // We don't validate `hex digits`, because we don't need it, it is work of linters.
  16842. const validIdent =
  16843. /^-?([a-z\u0080-\uFFFF_]|(\\[^\r\n\f])|-(?![0-9]))((\\[^\r\n\f])|[a-z\u0080-\uFFFF_0-9-])*$/i;
  16844. /*
  16845. The spec defines some keywords that you can use to describe properties such as the timing
  16846. function. These are still valid animation names, so as long as there is a property that accepts
  16847. a keyword, it is given priority. Only when all the properties that can take a keyword are
  16848. exhausted can the animation name be set to the keyword. I.e.
  16849. animation: infinite infinite;
  16850. The animation will repeat an infinite number of times from the first argument, and will have an
  16851. animation name of infinite from the second.
  16852. */
  16853. const animationKeywords = {
  16854. // animation-direction
  16855. $normal: 1,
  16856. $reverse: 1,
  16857. $alternate: 1,
  16858. "$alternate-reverse": 1,
  16859. // animation-fill-mode
  16860. $forwards: 1,
  16861. $backwards: 1,
  16862. $both: 1,
  16863. // animation-iteration-count
  16864. $infinite: 1,
  16865. // animation-play-state
  16866. $paused: 1,
  16867. $running: 1,
  16868. // animation-timing-function
  16869. $ease: 1,
  16870. "$ease-in": 1,
  16871. "$ease-out": 1,
  16872. "$ease-in-out": 1,
  16873. $linear: 1,
  16874. "$step-end": 1,
  16875. "$step-start": 1,
  16876. // Special
  16877. $none: Infinity, // No matter how many times you write none, it will never be an animation name
  16878. // Global values
  16879. $initial: Infinity,
  16880. $inherit: Infinity,
  16881. $unset: Infinity,
  16882. $revert: Infinity,
  16883. "$revert-layer": Infinity,
  16884. };
  16885. let parsedAnimationKeywords = {};
  16886. const valueNodes = valueParser(declaration.value).walk((node) => {
  16887. // If div-token appeared (represents as comma ','), a possibility of an animation-keywords should be reflesh.
  16888. if (node.type === "div") {
  16889. parsedAnimationKeywords = {};
  16890. return;
  16891. }
  16892. // Do not handle nested functions
  16893. else if (node.type === "function") {
  16894. return false;
  16895. }
  16896. // Ignore all except word
  16897. else if (node.type !== "word") {
  16898. return;
  16899. }
  16900. const value = node.type === "word" ? node.value.toLowerCase() : null;
  16901. let shouldParseAnimationName = false;
  16902. if (value && validIdent.test(value)) {
  16903. if ("$" + value in animationKeywords) {
  16904. parsedAnimationKeywords["$" + value] =
  16905. "$" + value in parsedAnimationKeywords
  16906. ? parsedAnimationKeywords["$" + value] + 1
  16907. : 0;
  16908. shouldParseAnimationName =
  16909. parsedAnimationKeywords["$" + value] >=
  16910. animationKeywords["$" + value];
  16911. } else {
  16912. shouldParseAnimationName = true;
  16913. }
  16914. }
  16915. const subContext = {
  16916. options: context.options,
  16917. global: context.global,
  16918. localizeNextItem: shouldParseAnimationName && !context.global,
  16919. localAliasMap: context.localAliasMap,
  16920. };
  16921. return localizeDeclNode(node, subContext);
  16922. });
  16923. declaration.value = valueNodes.toString();
  16924. return;
  16925. }
  16926. const isAnimationName = /animation(-name)?$/i.test(declaration.prop);
  16927. if (isAnimationName) {
  16928. return localizeDeclarationValues(true, declaration, context);
  16929. }
  16930. const hasUrl = /url\(/i.test(declaration.value);
  16931. if (hasUrl) {
  16932. return localizeDeclarationValues(false, declaration, context);
  16933. }
  16934. }
  16935. src$2.exports = (options = {}) => {
  16936. if (
  16937. options &&
  16938. options.mode &&
  16939. options.mode !== "global" &&
  16940. options.mode !== "local" &&
  16941. options.mode !== "pure"
  16942. ) {
  16943. throw new Error(
  16944. 'options.mode must be either "global", "local" or "pure" (default "local")'
  16945. );
  16946. }
  16947. const pureMode = options && options.mode === "pure";
  16948. const globalMode = options && options.mode === "global";
  16949. return {
  16950. postcssPlugin: "postcss-modules-local-by-default",
  16951. prepare() {
  16952. const localAliasMap = new Map();
  16953. return {
  16954. Once(root) {
  16955. const { icssImports } = extractICSS(root, false);
  16956. Object.keys(icssImports).forEach((key) => {
  16957. Object.keys(icssImports[key]).forEach((prop) => {
  16958. localAliasMap.set(prop, icssImports[key][prop]);
  16959. });
  16960. });
  16961. root.walkAtRules((atRule) => {
  16962. if (/keyframes$/i.test(atRule.name)) {
  16963. const globalMatch = /^\s*:global\s*\((.+)\)\s*$/.exec(
  16964. atRule.params
  16965. );
  16966. const localMatch = /^\s*:local\s*\((.+)\)\s*$/.exec(
  16967. atRule.params
  16968. );
  16969. let globalKeyframes = globalMode;
  16970. if (globalMatch) {
  16971. if (pureMode) {
  16972. throw atRule.error(
  16973. "@keyframes :global(...) is not allowed in pure mode"
  16974. );
  16975. }
  16976. atRule.params = globalMatch[1];
  16977. globalKeyframes = true;
  16978. } else if (localMatch) {
  16979. atRule.params = localMatch[0];
  16980. globalKeyframes = false;
  16981. } else if (
  16982. atRule.params &&
  16983. !globalMode &&
  16984. !localAliasMap.has(atRule.params)
  16985. ) {
  16986. atRule.params = ":local(" + atRule.params + ")";
  16987. }
  16988. atRule.walkDecls((declaration) => {
  16989. localizeDeclaration(declaration, {
  16990. localAliasMap,
  16991. options: options,
  16992. global: globalKeyframes,
  16993. });
  16994. });
  16995. } else if (/scope$/i.test(atRule.name)) {
  16996. if (atRule.params) {
  16997. atRule.params = atRule.params
  16998. .split("to")
  16999. .map((item) => {
  17000. const selector = item.trim().slice(1, -1).trim();
  17001. const context = localizeNode(
  17002. selector,
  17003. options.mode,
  17004. localAliasMap
  17005. );
  17006. context.options = options;
  17007. context.localAliasMap = localAliasMap;
  17008. if (pureMode && context.hasPureGlobals) {
  17009. throw atRule.error(
  17010. 'Selector in at-rule"' +
  17011. selector +
  17012. '" is not pure ' +
  17013. "(pure selectors must contain at least one local class or id)"
  17014. );
  17015. }
  17016. return `(${context.selector})`;
  17017. })
  17018. .join(" to ");
  17019. }
  17020. atRule.nodes.forEach((declaration) => {
  17021. if (declaration.type === "decl") {
  17022. localizeDeclaration(declaration, {
  17023. localAliasMap,
  17024. options: options,
  17025. global: globalMode,
  17026. });
  17027. }
  17028. });
  17029. } else if (atRule.nodes) {
  17030. atRule.nodes.forEach((declaration) => {
  17031. if (declaration.type === "decl") {
  17032. localizeDeclaration(declaration, {
  17033. localAliasMap,
  17034. options: options,
  17035. global: globalMode,
  17036. });
  17037. }
  17038. });
  17039. }
  17040. });
  17041. root.walkRules((rule) => {
  17042. if (
  17043. rule.parent &&
  17044. rule.parent.type === "atrule" &&
  17045. /keyframes$/i.test(rule.parent.name)
  17046. ) {
  17047. // ignore keyframe rules
  17048. return;
  17049. }
  17050. const context = localizeNode(rule, options.mode, localAliasMap);
  17051. context.options = options;
  17052. context.localAliasMap = localAliasMap;
  17053. if (pureMode && context.hasPureGlobals) {
  17054. throw rule.error(
  17055. 'Selector "' +
  17056. rule.selector +
  17057. '" is not pure ' +
  17058. "(pure selectors must contain at least one local class or id)"
  17059. );
  17060. }
  17061. rule.selector = context.selector;
  17062. // Less-syntax mixins parse as rules with no nodes
  17063. if (rule.nodes) {
  17064. rule.nodes.forEach((declaration) =>
  17065. localizeDeclaration(declaration, context)
  17066. );
  17067. }
  17068. });
  17069. },
  17070. };
  17071. },
  17072. };
  17073. };
  17074. src$2.exports.postcss = true;
  17075. return src$2.exports;
  17076. }
  17077. var src$1;
  17078. var hasRequiredSrc$1;
  17079. function requireSrc$1 () {
  17080. if (hasRequiredSrc$1) return src$1;
  17081. hasRequiredSrc$1 = 1;
  17082. const selectorParser = /*@__PURE__*/ requireDist();
  17083. const hasOwnProperty = Object.prototype.hasOwnProperty;
  17084. function isNestedRule(rule) {
  17085. if (!rule.parent || rule.parent.type === "root") {
  17086. return false;
  17087. }
  17088. if (rule.parent.type === "rule") {
  17089. return true;
  17090. }
  17091. return isNestedRule(rule.parent);
  17092. }
  17093. function getSingleLocalNamesForComposes(root, rule) {
  17094. if (isNestedRule(rule)) {
  17095. throw new Error(`composition is not allowed in nested rule \n\n${rule}`);
  17096. }
  17097. return root.nodes.map((node) => {
  17098. if (node.type !== "selector" || node.nodes.length !== 1) {
  17099. throw new Error(
  17100. `composition is only allowed when selector is single :local class name not in "${root}"`
  17101. );
  17102. }
  17103. node = node.nodes[0];
  17104. if (
  17105. node.type !== "pseudo" ||
  17106. node.value !== ":local" ||
  17107. node.nodes.length !== 1
  17108. ) {
  17109. throw new Error(
  17110. 'composition is only allowed when selector is single :local class name not in "' +
  17111. root +
  17112. '", "' +
  17113. node +
  17114. '" is weird'
  17115. );
  17116. }
  17117. node = node.first;
  17118. if (node.type !== "selector" || node.length !== 1) {
  17119. throw new Error(
  17120. 'composition is only allowed when selector is single :local class name not in "' +
  17121. root +
  17122. '", "' +
  17123. node +
  17124. '" is weird'
  17125. );
  17126. }
  17127. node = node.first;
  17128. if (node.type !== "class") {
  17129. // 'id' is not possible, because you can't compose ids
  17130. throw new Error(
  17131. 'composition is only allowed when selector is single :local class name not in "' +
  17132. root +
  17133. '", "' +
  17134. node +
  17135. '" is weird'
  17136. );
  17137. }
  17138. return node.value;
  17139. });
  17140. }
  17141. const whitespace = "[\\x20\\t\\r\\n\\f]";
  17142. const unescapeRegExp = new RegExp(
  17143. "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)",
  17144. "ig"
  17145. );
  17146. function unescape(str) {
  17147. return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => {
  17148. const high = "0x" + escaped - 0x10000;
  17149. // NaN means non-codepoint
  17150. // Workaround erroneous numeric interpretation of +"0x"
  17151. return high !== high || escapedWhitespace
  17152. ? escaped
  17153. : high < 0
  17154. ? // BMP codepoint
  17155. String.fromCharCode(high + 0x10000)
  17156. : // Supplemental Plane codepoint (surrogate pair)
  17157. String.fromCharCode((high >> 10) | 0xd800, (high & 0x3ff) | 0xdc00);
  17158. });
  17159. }
  17160. const plugin = (options = {}) => {
  17161. const generateScopedName =
  17162. (options && options.generateScopedName) || plugin.generateScopedName;
  17163. const generateExportEntry =
  17164. (options && options.generateExportEntry) || plugin.generateExportEntry;
  17165. const exportGlobals = options && options.exportGlobals;
  17166. return {
  17167. postcssPlugin: "postcss-modules-scope",
  17168. Once(root, { rule }) {
  17169. const exports$1 = Object.create(null);
  17170. function exportScopedName(name, rawName, node) {
  17171. const scopedName = generateScopedName(
  17172. rawName ? rawName : name,
  17173. root.source.input.from,
  17174. root.source.input.css,
  17175. node
  17176. );
  17177. const exportEntry = generateExportEntry(
  17178. rawName ? rawName : name,
  17179. scopedName,
  17180. root.source.input.from,
  17181. root.source.input.css,
  17182. node
  17183. );
  17184. const { key, value } = exportEntry;
  17185. exports$1[key] = exports$1[key] || [];
  17186. if (exports$1[key].indexOf(value) < 0) {
  17187. exports$1[key].push(value);
  17188. }
  17189. return scopedName;
  17190. }
  17191. function localizeNode(node) {
  17192. switch (node.type) {
  17193. case "selector":
  17194. node.nodes = node.map((item) => localizeNode(item));
  17195. return node;
  17196. case "class":
  17197. return selectorParser.className({
  17198. value: exportScopedName(
  17199. node.value,
  17200. node.raws && node.raws.value ? node.raws.value : null,
  17201. node
  17202. ),
  17203. });
  17204. case "id": {
  17205. return selectorParser.id({
  17206. value: exportScopedName(
  17207. node.value,
  17208. node.raws && node.raws.value ? node.raws.value : null,
  17209. node
  17210. ),
  17211. });
  17212. }
  17213. case "attribute": {
  17214. if (node.attribute === "class" && node.operator === "=") {
  17215. return selectorParser.attribute({
  17216. attribute: node.attribute,
  17217. operator: node.operator,
  17218. quoteMark: "'",
  17219. value: exportScopedName(node.value, null, null),
  17220. });
  17221. }
  17222. }
  17223. }
  17224. throw new Error(
  17225. `${node.type} ("${node}") is not allowed in a :local block`
  17226. );
  17227. }
  17228. function traverseNode(node) {
  17229. switch (node.type) {
  17230. case "pseudo":
  17231. if (node.value === ":local") {
  17232. if (node.nodes.length !== 1) {
  17233. throw new Error('Unexpected comma (",") in :local block');
  17234. }
  17235. const selector = localizeNode(node.first);
  17236. // move the spaces that were around the pseudo selector to the first
  17237. // non-container node
  17238. selector.first.spaces = node.spaces;
  17239. const nextNode = node.next();
  17240. if (
  17241. nextNode &&
  17242. nextNode.type === "combinator" &&
  17243. nextNode.value === " " &&
  17244. /\\[A-F0-9]{1,6}$/.test(selector.last.value)
  17245. ) {
  17246. selector.last.spaces.after = " ";
  17247. }
  17248. node.replaceWith(selector);
  17249. return;
  17250. }
  17251. /* falls through */
  17252. case "root":
  17253. case "selector": {
  17254. node.each((item) => traverseNode(item));
  17255. break;
  17256. }
  17257. case "id":
  17258. case "class":
  17259. if (exportGlobals) {
  17260. exports$1[node.value] = [node.value];
  17261. }
  17262. break;
  17263. }
  17264. return node;
  17265. }
  17266. // Find any :import and remember imported names
  17267. const importedNames = {};
  17268. root.walkRules(/^:import\(.+\)$/, (rule) => {
  17269. rule.walkDecls((decl) => {
  17270. importedNames[decl.prop] = true;
  17271. });
  17272. });
  17273. // Find any :local selectors
  17274. root.walkRules((rule) => {
  17275. let parsedSelector = selectorParser().astSync(rule);
  17276. rule.selector = traverseNode(parsedSelector.clone()).toString();
  17277. rule.walkDecls(/^(composes|compose-with)$/i, (decl) => {
  17278. const localNames = getSingleLocalNamesForComposes(
  17279. parsedSelector,
  17280. decl.parent
  17281. );
  17282. const multiple = decl.value.split(",");
  17283. multiple.forEach((value) => {
  17284. const classes = value.trim().split(/\s+/);
  17285. classes.forEach((className) => {
  17286. const global = /^global\(([^)]+)\)$/.exec(className);
  17287. if (global) {
  17288. localNames.forEach((exportedName) => {
  17289. exports$1[exportedName].push(global[1]);
  17290. });
  17291. } else if (hasOwnProperty.call(importedNames, className)) {
  17292. localNames.forEach((exportedName) => {
  17293. exports$1[exportedName].push(className);
  17294. });
  17295. } else if (hasOwnProperty.call(exports$1, className)) {
  17296. localNames.forEach((exportedName) => {
  17297. exports$1[className].forEach((item) => {
  17298. exports$1[exportedName].push(item);
  17299. });
  17300. });
  17301. } else {
  17302. throw decl.error(
  17303. `referenced class name "${className}" in ${decl.prop} not found`
  17304. );
  17305. }
  17306. });
  17307. });
  17308. decl.remove();
  17309. });
  17310. // Find any :local values
  17311. rule.walkDecls((decl) => {
  17312. if (!/:local\s*\((.+?)\)/.test(decl.value)) {
  17313. return;
  17314. }
  17315. let tokens = decl.value.split(/(,|'[^']*'|"[^"]*")/);
  17316. tokens = tokens.map((token, idx) => {
  17317. if (idx === 0 || tokens[idx - 1] === ",") {
  17318. let result = token;
  17319. const localMatch = /:local\s*\((.+?)\)/.exec(token);
  17320. if (localMatch) {
  17321. const input = localMatch.input;
  17322. const matchPattern = localMatch[0];
  17323. const matchVal = localMatch[1];
  17324. const newVal = exportScopedName(matchVal);
  17325. result = input.replace(matchPattern, newVal);
  17326. } else {
  17327. return token;
  17328. }
  17329. return result;
  17330. } else {
  17331. return token;
  17332. }
  17333. });
  17334. decl.value = tokens.join("");
  17335. });
  17336. });
  17337. // Find any :local keyframes
  17338. root.walkAtRules(/keyframes$/i, (atRule) => {
  17339. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(atRule.params);
  17340. if (!localMatch) {
  17341. return;
  17342. }
  17343. atRule.params = exportScopedName(localMatch[1]);
  17344. });
  17345. root.walkAtRules(/scope$/i, (atRule) => {
  17346. if (atRule.params) {
  17347. atRule.params = atRule.params
  17348. .split("to")
  17349. .map((item) => {
  17350. const selector = item.trim().slice(1, -1).trim();
  17351. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(selector);
  17352. if (!localMatch) {
  17353. return `(${selector})`;
  17354. }
  17355. let parsedSelector = selectorParser().astSync(selector);
  17356. return `(${traverseNode(parsedSelector).toString()})`;
  17357. })
  17358. .join(" to ");
  17359. }
  17360. });
  17361. // If we found any :locals, insert an :export rule
  17362. const exportedNames = Object.keys(exports$1);
  17363. if (exportedNames.length > 0) {
  17364. const exportRule = rule({ selector: ":export" });
  17365. exportedNames.forEach((exportedName) =>
  17366. exportRule.append({
  17367. prop: exportedName,
  17368. value: exports$1[exportedName].join(" "),
  17369. raws: { before: "\n " },
  17370. })
  17371. );
  17372. root.append(exportRule);
  17373. }
  17374. },
  17375. };
  17376. };
  17377. plugin.postcss = true;
  17378. plugin.generateScopedName = function (name, path) {
  17379. const sanitisedPath = path
  17380. .replace(/\.[^./\\]+$/, "")
  17381. .replace(/[\W_]+/g, "_")
  17382. .replace(/^_|_$/g, "");
  17383. return `_${sanitisedPath}__${name}`.trim();
  17384. };
  17385. plugin.generateExportEntry = function (name, scopedName) {
  17386. return {
  17387. key: unescape(name),
  17388. value: unescape(scopedName),
  17389. };
  17390. };
  17391. src$1 = plugin;
  17392. return src$1;
  17393. }
  17394. var stringHash;
  17395. var hasRequiredStringHash;
  17396. function requireStringHash () {
  17397. if (hasRequiredStringHash) return stringHash;
  17398. hasRequiredStringHash = 1;
  17399. function hash(str) {
  17400. var hash = 5381,
  17401. i = str.length;
  17402. while(i) {
  17403. hash = (hash * 33) ^ str.charCodeAt(--i);
  17404. }
  17405. /* JavaScript does bitwise operations (like XOR, above) on 32-bit signed
  17406. * integers. Since we want the results to be always positive, convert the
  17407. * signed int to an unsigned by doing an unsigned bitshift. */
  17408. return hash >>> 0;
  17409. }
  17410. stringHash = hash;
  17411. return stringHash;
  17412. }
  17413. var src = {exports: {}};
  17414. var hasRequiredSrc;
  17415. function requireSrc () {
  17416. if (hasRequiredSrc) return src.exports;
  17417. hasRequiredSrc = 1;
  17418. const ICSSUtils = /*@__PURE__*/ requireSrc$4();
  17419. const matchImports = /^(.+?|\([\s\S]+?\))\s+from\s+("[^"]*"|'[^']*'|[\w-]+)$/;
  17420. const matchValueDefinition = /(?:\s+|^)([\w-]+):?(.*?)$/;
  17421. const matchImport = /^([\w-]+)(?:\s+as\s+([\w-]+))?/;
  17422. src.exports = (options) => {
  17423. let importIndex = 0;
  17424. const createImportedName =
  17425. (options && options.createImportedName) ||
  17426. ((importName /*, path*/) =>
  17427. `i__const_${importName.replace(/\W/g, "_")}_${importIndex++}`);
  17428. return {
  17429. postcssPlugin: "postcss-modules-values",
  17430. prepare(result) {
  17431. const importAliases = [];
  17432. const definitions = {};
  17433. return {
  17434. Once(root, postcss) {
  17435. root.walkAtRules(/value/i, (atRule) => {
  17436. const matches = atRule.params.match(matchImports);
  17437. if (matches) {
  17438. let [, /*match*/ aliases, path] = matches;
  17439. // We can use constants for path names
  17440. if (definitions[path]) {
  17441. path = definitions[path];
  17442. }
  17443. const imports = aliases
  17444. .replace(/^\(\s*([\s\S]+)\s*\)$/, "$1")
  17445. .split(/\s*,\s*/)
  17446. .map((alias) => {
  17447. const tokens = matchImport.exec(alias);
  17448. if (tokens) {
  17449. const [, /*match*/ theirName, myName = theirName] = tokens;
  17450. const importedName = createImportedName(myName);
  17451. definitions[myName] = importedName;
  17452. return { theirName, importedName };
  17453. } else {
  17454. throw new Error(`@import statement "${alias}" is invalid!`);
  17455. }
  17456. });
  17457. importAliases.push({ path, imports });
  17458. atRule.remove();
  17459. return;
  17460. }
  17461. if (atRule.params.indexOf("@value") !== -1) {
  17462. result.warn("Invalid value definition: " + atRule.params);
  17463. }
  17464. let [, key, value] = `${atRule.params}${atRule.raws.between}`.match(
  17465. matchValueDefinition
  17466. );
  17467. const normalizedValue = value.replace(/\/\*((?!\*\/).*?)\*\//g, "");
  17468. if (normalizedValue.length === 0) {
  17469. result.warn("Invalid value definition: " + atRule.params);
  17470. atRule.remove();
  17471. return;
  17472. }
  17473. let isOnlySpace = /^\s+$/.test(normalizedValue);
  17474. if (!isOnlySpace) {
  17475. value = value.trim();
  17476. }
  17477. // Add to the definitions, knowing that values can refer to each other
  17478. definitions[key] = ICSSUtils.replaceValueSymbols(
  17479. value,
  17480. definitions
  17481. );
  17482. atRule.remove();
  17483. });
  17484. /* If we have no definitions, don't continue */
  17485. if (!Object.keys(definitions).length) {
  17486. return;
  17487. }
  17488. /* Perform replacements */
  17489. ICSSUtils.replaceSymbols(root, definitions);
  17490. /* 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 */
  17491. const exportDeclarations = Object.keys(definitions).map((key) =>
  17492. postcss.decl({
  17493. value: definitions[key],
  17494. prop: key,
  17495. raws: { before: "\n " },
  17496. })
  17497. );
  17498. /* Add export rules if any */
  17499. if (exportDeclarations.length > 0) {
  17500. const exportRule = postcss.rule({
  17501. selector: ":export",
  17502. raws: { after: "\n" },
  17503. });
  17504. exportRule.append(exportDeclarations);
  17505. root.prepend(exportRule);
  17506. }
  17507. /* Add import rules */
  17508. importAliases.reverse().forEach(({ path, imports }) => {
  17509. const importRule = postcss.rule({
  17510. selector: `:import(${path})`,
  17511. raws: { after: "\n" },
  17512. });
  17513. imports.forEach(({ theirName, importedName }) => {
  17514. importRule.append({
  17515. value: theirName,
  17516. prop: importedName,
  17517. raws: { before: "\n " },
  17518. });
  17519. });
  17520. root.prepend(importRule);
  17521. });
  17522. },
  17523. };
  17524. },
  17525. };
  17526. };
  17527. src.exports.postcss = true;
  17528. return src.exports;
  17529. }
  17530. var hasRequiredScoping;
  17531. function requireScoping () {
  17532. if (hasRequiredScoping) return scoping;
  17533. hasRequiredScoping = 1;
  17534. Object.defineProperty(scoping, "__esModule", {
  17535. value: true
  17536. });
  17537. scoping.behaviours = void 0;
  17538. scoping.getDefaultPlugins = getDefaultPlugins;
  17539. scoping.getDefaultScopeBehaviour = getDefaultScopeBehaviour;
  17540. scoping.getScopedNameGenerator = getScopedNameGenerator;
  17541. var _postcssModulesExtractImports = _interopRequireDefault(/*@__PURE__*/ requireSrc$3());
  17542. var _genericNames = _interopRequireDefault(/*@__PURE__*/ requireGenericNames());
  17543. var _postcssModulesLocalByDefault = _interopRequireDefault(/*@__PURE__*/ requireSrc$2());
  17544. var _postcssModulesScope = _interopRequireDefault(/*@__PURE__*/ requireSrc$1());
  17545. var _stringHash = _interopRequireDefault(/*@__PURE__*/ requireStringHash());
  17546. var _postcssModulesValues = _interopRequireDefault(/*@__PURE__*/ requireSrc());
  17547. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  17548. const behaviours = {
  17549. LOCAL: "local",
  17550. GLOBAL: "global"
  17551. };
  17552. scoping.behaviours = behaviours;
  17553. function getDefaultPlugins({
  17554. behaviour,
  17555. generateScopedName,
  17556. exportGlobals
  17557. }) {
  17558. const scope = (0, _postcssModulesScope.default)({
  17559. generateScopedName,
  17560. exportGlobals
  17561. });
  17562. const plugins = {
  17563. [behaviours.LOCAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  17564. mode: "local"
  17565. }), _postcssModulesExtractImports.default, scope],
  17566. [behaviours.GLOBAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  17567. mode: "global"
  17568. }), _postcssModulesExtractImports.default, scope]
  17569. };
  17570. return plugins[behaviour];
  17571. }
  17572. function isValidBehaviour(behaviour) {
  17573. return Object.keys(behaviours).map(key => behaviours[key]).indexOf(behaviour) > -1;
  17574. }
  17575. function getDefaultScopeBehaviour(scopeBehaviour) {
  17576. return scopeBehaviour && isValidBehaviour(scopeBehaviour) ? scopeBehaviour : behaviours.LOCAL;
  17577. }
  17578. function generateScopedNameDefault(name, filename, css) {
  17579. const i = css.indexOf(`.${name}`);
  17580. const lineNumber = css.substr(0, i).split(/[\r\n]/).length;
  17581. const hash = (0, _stringHash.default)(css).toString(36).substr(0, 5);
  17582. return `_${name}_${hash}_${lineNumber}`;
  17583. }
  17584. function getScopedNameGenerator(generateScopedName, hashPrefix) {
  17585. const scopedNameGenerator = generateScopedName || generateScopedNameDefault;
  17586. if (typeof scopedNameGenerator === "function") {
  17587. return scopedNameGenerator;
  17588. }
  17589. return (0, _genericNames.default)(scopedNameGenerator, {
  17590. context: process.cwd(),
  17591. hashPrefix: hashPrefix
  17592. });
  17593. }
  17594. return scoping;
  17595. }
  17596. var hasRequiredPluginFactory;
  17597. function requirePluginFactory () {
  17598. if (hasRequiredPluginFactory) return pluginFactory;
  17599. hasRequiredPluginFactory = 1;
  17600. Object.defineProperty(pluginFactory, "__esModule", {
  17601. value: true
  17602. });
  17603. pluginFactory.makePlugin = makePlugin;
  17604. var _postcss = _interopRequireDefault(require$$0$1);
  17605. var _unquote = _interopRequireDefault(/*@__PURE__*/ requireUnquote());
  17606. var _Parser = _interopRequireDefault(/*@__PURE__*/ requireParser$1());
  17607. var _saveJSON = _interopRequireDefault(/*@__PURE__*/ requireSaveJSON());
  17608. var _localsConvention = /*@__PURE__*/ requireLocalsConvention();
  17609. var _FileSystemLoader = _interopRequireDefault(/*@__PURE__*/ requireFileSystemLoader());
  17610. var _scoping = /*@__PURE__*/ requireScoping();
  17611. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  17612. const PLUGIN_NAME = "postcss-modules";
  17613. function isGlobalModule(globalModules, inputFile) {
  17614. return globalModules.some(regex => inputFile.match(regex));
  17615. }
  17616. function getDefaultPluginsList(opts, inputFile) {
  17617. const globalModulesList = opts.globalModulePaths || null;
  17618. const exportGlobals = opts.exportGlobals || false;
  17619. const defaultBehaviour = (0, _scoping.getDefaultScopeBehaviour)(opts.scopeBehaviour);
  17620. const generateScopedName = (0, _scoping.getScopedNameGenerator)(opts.generateScopedName, opts.hashPrefix);
  17621. if (globalModulesList && isGlobalModule(globalModulesList, inputFile)) {
  17622. return (0, _scoping.getDefaultPlugins)({
  17623. behaviour: _scoping.behaviours.GLOBAL,
  17624. generateScopedName,
  17625. exportGlobals
  17626. });
  17627. }
  17628. return (0, _scoping.getDefaultPlugins)({
  17629. behaviour: defaultBehaviour,
  17630. generateScopedName,
  17631. exportGlobals
  17632. });
  17633. }
  17634. function getLoader(opts, plugins) {
  17635. const root = typeof opts.root === "undefined" ? "/" : opts.root;
  17636. return typeof opts.Loader === "function" ? new opts.Loader(root, plugins, opts.resolve) : new _FileSystemLoader.default(root, plugins, opts.resolve);
  17637. }
  17638. function isOurPlugin(plugin) {
  17639. return plugin.postcssPlugin === PLUGIN_NAME;
  17640. }
  17641. function makePlugin(opts) {
  17642. return {
  17643. postcssPlugin: PLUGIN_NAME,
  17644. async OnceExit(css, {
  17645. result
  17646. }) {
  17647. const getJSON = opts.getJSON || _saveJSON.default;
  17648. const inputFile = css.source.input.file;
  17649. const pluginList = getDefaultPluginsList(opts, inputFile);
  17650. const resultPluginIndex = result.processor.plugins.findIndex(plugin => isOurPlugin(plugin));
  17651. if (resultPluginIndex === -1) {
  17652. throw new Error("Plugin missing from options.");
  17653. }
  17654. const earlierPlugins = result.processor.plugins.slice(0, resultPluginIndex);
  17655. const loaderPlugins = [...earlierPlugins, ...pluginList];
  17656. const loader = getLoader(opts, loaderPlugins);
  17657. const fetcher = async (file, relativeTo, depTrace) => {
  17658. const unquoteFile = (0, _unquote.default)(file);
  17659. return loader.fetch.call(loader, unquoteFile, relativeTo, depTrace);
  17660. };
  17661. const parser = new _Parser.default(fetcher);
  17662. await (0, _postcss.default)([...pluginList, parser.plugin()]).process(css, {
  17663. from: inputFile
  17664. });
  17665. const out = loader.finalSource;
  17666. if (out) css.prepend(out);
  17667. if (opts.localsConvention) {
  17668. const reducer = (0, _localsConvention.makeLocalsConventionReducer)(opts.localsConvention, inputFile);
  17669. parser.exportTokens = Object.entries(parser.exportTokens).reduce(reducer, {});
  17670. }
  17671. result.messages.push({
  17672. type: "export",
  17673. plugin: "postcss-modules",
  17674. exportTokens: parser.exportTokens
  17675. }); // getJSON may return a promise
  17676. return getJSON(css.source.input.file, parser.exportTokens, result.opts.to);
  17677. }
  17678. };
  17679. }
  17680. return pluginFactory;
  17681. }
  17682. var hasRequiredBuild;
  17683. function requireBuild () {
  17684. if (hasRequiredBuild) return build.exports;
  17685. hasRequiredBuild = 1;
  17686. var _fs = require$$0;
  17687. var _fs2 = /*@__PURE__*/ requireFs();
  17688. var _pluginFactory = /*@__PURE__*/ requirePluginFactory();
  17689. (0, _fs2.setFileSystem)({
  17690. readFile: _fs.readFile,
  17691. writeFile: _fs.writeFile
  17692. });
  17693. build.exports = (opts = {}) => (0, _pluginFactory.makePlugin)(opts);
  17694. build.exports.postcss = true;
  17695. return build.exports;
  17696. }
  17697. var buildExports = /*@__PURE__*/ requireBuild();
  17698. var postcssModules = /*@__PURE__*/getDefaultExportFromCjs(buildExports);
  17699. function compileStyle(options) {
  17700. return doCompileStyle({
  17701. ...options,
  17702. isAsync: false
  17703. });
  17704. }
  17705. function compileStyleAsync(options) {
  17706. return doCompileStyle({
  17707. ...options,
  17708. isAsync: true
  17709. });
  17710. }
  17711. function doCompileStyle(options) {
  17712. const {
  17713. filename,
  17714. id,
  17715. scoped = false,
  17716. trim = true,
  17717. isProd = false,
  17718. modules = false,
  17719. modulesOptions = {},
  17720. preprocessLang,
  17721. postcssOptions,
  17722. postcssPlugins
  17723. } = options;
  17724. const preprocessor = preprocessLang && processors[preprocessLang];
  17725. const preProcessedSource = preprocessor && preprocess(options, preprocessor);
  17726. const map = preProcessedSource ? preProcessedSource.map : options.inMap || options.map;
  17727. const source = preProcessedSource ? preProcessedSource.code : options.source;
  17728. const shortId = id.replace(/^data-v-/, "");
  17729. const longId = `data-v-${shortId}`;
  17730. const plugins = (postcssPlugins || []).slice();
  17731. plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
  17732. if (trim) {
  17733. plugins.push(trimPlugin());
  17734. }
  17735. if (scoped) {
  17736. plugins.push(scopedPlugin(longId));
  17737. }
  17738. let cssModules;
  17739. if (modules) {
  17740. if (!options.isAsync) {
  17741. throw new Error(
  17742. "[@vue/compiler-sfc] `modules` option can only be used with compileStyleAsync()."
  17743. );
  17744. }
  17745. plugins.push(
  17746. postcssModules({
  17747. ...modulesOptions,
  17748. getJSON: (_cssFileName, json) => {
  17749. cssModules = json;
  17750. }
  17751. })
  17752. );
  17753. }
  17754. const postCSSOptions = {
  17755. ...postcssOptions,
  17756. to: filename,
  17757. from: filename
  17758. };
  17759. if (map) {
  17760. postCSSOptions.map = {
  17761. inline: false,
  17762. annotation: false,
  17763. prev: map
  17764. };
  17765. }
  17766. let result;
  17767. let code;
  17768. let outMap;
  17769. const dependencies = new Set(
  17770. preProcessedSource ? preProcessedSource.dependencies : []
  17771. );
  17772. dependencies.delete(filename);
  17773. const errors = [];
  17774. if (preProcessedSource && preProcessedSource.errors.length) {
  17775. errors.push(...preProcessedSource.errors);
  17776. }
  17777. const recordPlainCssDependencies = (messages) => {
  17778. messages.forEach((msg) => {
  17779. if (msg.type === "dependency") {
  17780. dependencies.add(msg.file);
  17781. }
  17782. });
  17783. return dependencies;
  17784. };
  17785. try {
  17786. result = require$$0$1(plugins).process(source, postCSSOptions);
  17787. if (options.isAsync) {
  17788. return result.then((result2) => ({
  17789. code: result2.css || "",
  17790. map: result2.map && result2.map.toJSON(),
  17791. errors,
  17792. modules: cssModules,
  17793. rawResult: result2,
  17794. dependencies: recordPlainCssDependencies(result2.messages)
  17795. })).catch((error) => ({
  17796. code: "",
  17797. map: void 0,
  17798. errors: [...errors, error],
  17799. rawResult: void 0,
  17800. dependencies
  17801. }));
  17802. }
  17803. recordPlainCssDependencies(result.messages);
  17804. code = result.css;
  17805. outMap = result.map;
  17806. } catch (e) {
  17807. errors.push(e);
  17808. }
  17809. return {
  17810. code: code || ``,
  17811. map: outMap && outMap.toJSON(),
  17812. errors,
  17813. rawResult: result,
  17814. dependencies
  17815. };
  17816. }
  17817. function preprocess(options, preprocessor) {
  17818. return preprocessor(
  17819. options.source,
  17820. options.inMap || options.map,
  17821. {
  17822. filename: options.filename,
  17823. ...options.preprocessOptions
  17824. },
  17825. options.preprocessCustomRequire
  17826. );
  17827. }
  17828. const UNKNOWN_TYPE = "Unknown";
  17829. function resolveObjectKey(node, computed) {
  17830. switch (node.type) {
  17831. case "StringLiteral":
  17832. case "NumericLiteral":
  17833. return String(node.value);
  17834. case "Identifier":
  17835. if (!computed) return node.name;
  17836. }
  17837. return void 0;
  17838. }
  17839. function concatStrings(strs) {
  17840. return strs.filter((s) => !!s).join(", ");
  17841. }
  17842. function isLiteralNode(node) {
  17843. return node.type.endsWith("Literal");
  17844. }
  17845. function isCallOf(node, test) {
  17846. return !!(node && test && node.type === "CallExpression" && node.callee.type === "Identifier" && (typeof test === "string" ? node.callee.name === test : test(node.callee.name)));
  17847. }
  17848. function toRuntimeTypeString(types) {
  17849. return types.length > 1 ? `[${types.join(", ")}]` : types[0];
  17850. }
  17851. function getImportedName(specifier) {
  17852. if (specifier.type === "ImportSpecifier")
  17853. return specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
  17854. else if (specifier.type === "ImportNamespaceSpecifier") return "*";
  17855. return "default";
  17856. }
  17857. function getId(node) {
  17858. return node.type === "Identifier" ? node.name : node.type === "StringLiteral" ? node.value : null;
  17859. }
  17860. function getStringLiteralKey(node) {
  17861. 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;
  17862. }
  17863. const identity = (str) => str;
  17864. const fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
  17865. const toLowerCase = (str) => str.toLowerCase();
  17866. function toFileNameLowerCase(x) {
  17867. return fileNameLowerCaseRegExp.test(x) ? x.replace(fileNameLowerCaseRegExp, toLowerCase) : x;
  17868. }
  17869. function createGetCanonicalFileName(useCaseSensitiveFileNames) {
  17870. return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
  17871. }
  17872. const normalize = (path$1.posix || path$1).normalize;
  17873. const windowsSlashRE = /\\/g;
  17874. function normalizePath(p) {
  17875. return normalize(p.replace(windowsSlashRE, "/"));
  17876. }
  17877. const joinPaths = (path$1.posix || path$1).join;
  17878. const propNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~\-]/;
  17879. function getEscapedPropName(key) {
  17880. return propNameEscapeSymbolsRE.test(key) ? JSON.stringify(key) : key;
  17881. }
  17882. const isJS = (...langs) => langs.some((lang) => lang === "js" || lang === "jsx");
  17883. const isTS = (...langs) => langs.some((lang) => lang === "ts" || lang === "tsx");
  17884. function analyzeScriptBindings(ast) {
  17885. for (const node of ast) {
  17886. if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "ObjectExpression") {
  17887. return analyzeBindingsFromOptions(node.declaration);
  17888. }
  17889. }
  17890. return {};
  17891. }
  17892. function analyzeBindingsFromOptions(node) {
  17893. const bindings = {};
  17894. Object.defineProperty(bindings, "__isScriptSetup", {
  17895. enumerable: false,
  17896. value: false
  17897. });
  17898. for (const property of node.properties) {
  17899. if (property.type === "ObjectProperty" && !property.computed && property.key.type === "Identifier") {
  17900. if (property.key.name === "props") {
  17901. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  17902. bindings[key] = "props";
  17903. }
  17904. } else if (property.key.name === "inject") {
  17905. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  17906. bindings[key] = "options";
  17907. }
  17908. } else if (property.value.type === "ObjectExpression" && (property.key.name === "computed" || property.key.name === "methods")) {
  17909. for (const key of getObjectExpressionKeys(property.value)) {
  17910. bindings[key] = "options";
  17911. }
  17912. }
  17913. } else if (property.type === "ObjectMethod" && property.key.type === "Identifier" && (property.key.name === "setup" || property.key.name === "data")) {
  17914. for (const bodyItem of property.body.body) {
  17915. if (bodyItem.type === "ReturnStatement" && bodyItem.argument && bodyItem.argument.type === "ObjectExpression") {
  17916. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  17917. bindings[key] = property.key.name === "setup" ? "setup-maybe-ref" : "data";
  17918. }
  17919. }
  17920. }
  17921. }
  17922. }
  17923. return bindings;
  17924. }
  17925. function getObjectExpressionKeys(node) {
  17926. const keys = [];
  17927. for (const prop of node.properties) {
  17928. if (prop.type === "SpreadElement") continue;
  17929. const key = resolveObjectKey(prop.key, prop.computed);
  17930. if (key) keys.push(String(key));
  17931. }
  17932. return keys;
  17933. }
  17934. function getArrayExpressionKeys(node) {
  17935. const keys = [];
  17936. for (const element of node.elements) {
  17937. if (element && element.type === "StringLiteral") {
  17938. keys.push(element.value);
  17939. }
  17940. }
  17941. return keys;
  17942. }
  17943. function getObjectOrArrayExpressionKeys(value) {
  17944. if (value.type === "ArrayExpression") {
  17945. return getArrayExpressionKeys(value);
  17946. }
  17947. if (value.type === "ObjectExpression") {
  17948. return getObjectExpressionKeys(value);
  17949. }
  17950. return [];
  17951. }
  17952. var _a$1, _b;
  17953. class ScriptCompileContext {
  17954. constructor(descriptor, options) {
  17955. this.descriptor = descriptor;
  17956. this.options = options;
  17957. this.isCE = false;
  17958. this.source = this.descriptor.source;
  17959. this.filename = this.descriptor.filename;
  17960. this.s = new MagicString(this.source);
  17961. this.startOffset = (_a$1 = this.descriptor.scriptSetup) == null ? void 0 : _a$1.loc.start.offset;
  17962. this.endOffset = (_b = this.descriptor.scriptSetup) == null ? void 0 : _b.loc.end.offset;
  17963. this.userImports = /* @__PURE__ */ Object.create(null);
  17964. // macros presence check
  17965. this.hasDefinePropsCall = false;
  17966. this.hasDefineEmitCall = false;
  17967. this.hasDefineExposeCall = false;
  17968. this.hasDefaultExportName = false;
  17969. this.hasDefaultExportRender = false;
  17970. this.hasDefineOptionsCall = false;
  17971. this.hasDefineSlotsCall = false;
  17972. this.hasDefineModelCall = false;
  17973. this.propsDestructuredBindings = /* @__PURE__ */ Object.create(null);
  17974. // defineModel
  17975. this.modelDecls = /* @__PURE__ */ Object.create(null);
  17976. // codegen
  17977. this.bindingMetadata = {};
  17978. this.helperImports = /* @__PURE__ */ new Set();
  17979. const { script, scriptSetup } = descriptor;
  17980. const scriptLang = script && script.lang;
  17981. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  17982. this.isJS = isJS(scriptLang, scriptSetupLang);
  17983. this.isTS = isTS(scriptLang, scriptSetupLang);
  17984. const customElement = options.customElement;
  17985. const filename = this.descriptor.filename;
  17986. if (customElement) {
  17987. this.isCE = typeof customElement === "boolean" ? customElement : customElement(filename);
  17988. }
  17989. const plugins = resolveParserPlugins(
  17990. scriptLang || scriptSetupLang,
  17991. options.babelParserPlugins
  17992. );
  17993. function parse(input, offset) {
  17994. try {
  17995. return parser$2.parse(input, {
  17996. plugins,
  17997. sourceType: "module"
  17998. }).program;
  17999. } catch (e) {
  18000. e.message = `[vue/compiler-sfc] ${e.message}
  18001. ${descriptor.filename}
  18002. ${shared.generateCodeFrame(
  18003. descriptor.source,
  18004. e.pos + offset,
  18005. e.pos + offset + 1
  18006. )}`;
  18007. throw e;
  18008. }
  18009. }
  18010. this.scriptAst = descriptor.script && parse(descriptor.script.content, descriptor.script.loc.start.offset);
  18011. this.scriptSetupAst = descriptor.scriptSetup && parse(descriptor.scriptSetup.content, this.startOffset);
  18012. }
  18013. helper(key) {
  18014. this.helperImports.add(key);
  18015. return `_${key}`;
  18016. }
  18017. getString(node, scriptSetup = true) {
  18018. const block = scriptSetup ? this.descriptor.scriptSetup : this.descriptor.script;
  18019. return block.content.slice(node.start, node.end);
  18020. }
  18021. warn(msg, node, scope) {
  18022. warn(generateError(msg, node, this, scope));
  18023. }
  18024. error(msg, node, scope) {
  18025. throw new Error(
  18026. `[@vue/compiler-sfc] ${generateError(msg, node, this, scope)}`
  18027. );
  18028. }
  18029. }
  18030. function generateError(msg, node, ctx, scope) {
  18031. const offset = scope ? scope.offset : ctx.startOffset;
  18032. return `${msg}
  18033. ${(scope || ctx.descriptor).filename}
  18034. ${shared.generateCodeFrame(
  18035. (scope || ctx.descriptor).source,
  18036. node.start + offset,
  18037. node.end + offset
  18038. )}`;
  18039. }
  18040. function resolveParserPlugins(lang, userPlugins, dts = false) {
  18041. const plugins = [];
  18042. if (!userPlugins || !userPlugins.some(
  18043. (p) => p === "importAssertions" || p === "importAttributes" || shared.isArray(p) && p[0] === "importAttributes"
  18044. )) {
  18045. plugins.push("importAttributes");
  18046. }
  18047. if (lang === "jsx" || lang === "tsx" || lang === "mtsx") {
  18048. plugins.push("jsx");
  18049. } else if (userPlugins) {
  18050. userPlugins = userPlugins.filter((p) => p !== "jsx");
  18051. }
  18052. if (lang === "ts" || lang === "mts" || lang === "tsx" || lang === "cts" || lang === "mtsx") {
  18053. plugins.push(["typescript", { dts }], "explicitResourceManagement");
  18054. if (!userPlugins || !userPlugins.includes("decorators")) {
  18055. plugins.push("decorators-legacy");
  18056. }
  18057. }
  18058. if (userPlugins) {
  18059. plugins.push(...userPlugins);
  18060. }
  18061. return plugins;
  18062. }
  18063. function rewriteDefault(input, as, parserPlugins) {
  18064. const ast = parser$2.parse(input, {
  18065. sourceType: "module",
  18066. plugins: resolveParserPlugins("js", parserPlugins)
  18067. }).program.body;
  18068. const s = new MagicString(input);
  18069. rewriteDefaultAST(ast, s, as);
  18070. return s.toString();
  18071. }
  18072. function rewriteDefaultAST(ast, s, as) {
  18073. if (!hasDefaultExport(ast)) {
  18074. s.append(`
  18075. const ${as} = {}`);
  18076. return;
  18077. }
  18078. ast.forEach((node) => {
  18079. if (node.type === "ExportDefaultDeclaration") {
  18080. if (node.declaration.type === "ClassDeclaration" && node.declaration.id) {
  18081. const start = node.declaration.decorators && node.declaration.decorators.length > 0 ? node.declaration.decorators[node.declaration.decorators.length - 1].end : node.start;
  18082. s.overwrite(start, node.declaration.id.start, ` class `);
  18083. s.append(`
  18084. const ${as} = ${node.declaration.id.name}`);
  18085. } else {
  18086. s.overwrite(node.start, node.declaration.start, `const ${as} = `);
  18087. }
  18088. } else if (node.type === "ExportNamedDeclaration") {
  18089. for (const specifier of node.specifiers) {
  18090. if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier" && specifier.exported.name === "default") {
  18091. if (node.source) {
  18092. if (specifier.local.name === "default") {
  18093. s.prepend(
  18094. `import { default as __VUE_DEFAULT__ } from '${node.source.value}'
  18095. `
  18096. );
  18097. const end2 = specifierEnd(s, specifier.local.end, node.end);
  18098. s.remove(specifier.start, end2);
  18099. s.append(`
  18100. const ${as} = __VUE_DEFAULT__`);
  18101. continue;
  18102. } else {
  18103. s.prepend(
  18104. `import { ${s.slice(
  18105. specifier.local.start,
  18106. specifier.local.end
  18107. )} as __VUE_DEFAULT__ } from '${node.source.value}'
  18108. `
  18109. );
  18110. const end2 = specifierEnd(s, specifier.exported.end, node.end);
  18111. s.remove(specifier.start, end2);
  18112. s.append(`
  18113. const ${as} = __VUE_DEFAULT__`);
  18114. continue;
  18115. }
  18116. }
  18117. const end = specifierEnd(s, specifier.end, node.end);
  18118. s.remove(specifier.start, end);
  18119. s.append(`
  18120. const ${as} = ${specifier.local.name}`);
  18121. }
  18122. }
  18123. }
  18124. });
  18125. }
  18126. function hasDefaultExport(ast) {
  18127. for (const stmt of ast) {
  18128. if (stmt.type === "ExportDefaultDeclaration") {
  18129. return true;
  18130. } else if (stmt.type === "ExportNamedDeclaration" && stmt.specifiers.some(
  18131. (spec) => spec.exported.name === "default"
  18132. )) {
  18133. return true;
  18134. }
  18135. }
  18136. return false;
  18137. }
  18138. function specifierEnd(s, end, nodeEnd) {
  18139. let hasCommas = false;
  18140. let oldEnd = end;
  18141. while (end < nodeEnd) {
  18142. if (/\s/.test(s.slice(end, end + 1))) {
  18143. end++;
  18144. } else if (s.slice(end, end + 1) === ",") {
  18145. end++;
  18146. hasCommas = true;
  18147. break;
  18148. } else if (s.slice(end, end + 1) === "}") {
  18149. break;
  18150. }
  18151. }
  18152. return hasCommas ? end : oldEnd;
  18153. }
  18154. const normalScriptDefaultVar = `__default__`;
  18155. function processNormalScript(ctx, scopeId) {
  18156. var _a;
  18157. const script = ctx.descriptor.script;
  18158. try {
  18159. let content = script.content;
  18160. let map = script.map;
  18161. const scriptAst = ctx.scriptAst;
  18162. const bindings = analyzeScriptBindings(scriptAst.body);
  18163. const { cssVars } = ctx.descriptor;
  18164. const { genDefaultAs, isProd } = ctx.options;
  18165. if (cssVars.length || genDefaultAs) {
  18166. const defaultVar = genDefaultAs || normalScriptDefaultVar;
  18167. const s = new MagicString(content);
  18168. rewriteDefaultAST(scriptAst.body, s, defaultVar);
  18169. content = s.toString();
  18170. if (cssVars.length && !((_a = ctx.options.templateOptions) == null ? void 0 : _a.ssr)) {
  18171. content += genNormalScriptCssVarsCode(
  18172. cssVars,
  18173. bindings,
  18174. scopeId,
  18175. !!isProd,
  18176. defaultVar
  18177. );
  18178. }
  18179. if (!genDefaultAs) {
  18180. content += `
  18181. export default ${defaultVar}`;
  18182. }
  18183. }
  18184. return {
  18185. ...script,
  18186. content,
  18187. map,
  18188. bindings,
  18189. scriptAst: scriptAst.body
  18190. };
  18191. } catch (e) {
  18192. return script;
  18193. }
  18194. }
  18195. const balanced = (a, b, str) => {
  18196. const ma = a instanceof RegExp ? maybeMatch(a, str) : a;
  18197. const mb = b instanceof RegExp ? maybeMatch(b, str) : b;
  18198. const r = ma !== null && mb != null && range(ma, mb, str);
  18199. return (r && {
  18200. start: r[0],
  18201. end: r[1],
  18202. pre: str.slice(0, r[0]),
  18203. body: str.slice(r[0] + ma.length, r[1]),
  18204. post: str.slice(r[1] + mb.length),
  18205. });
  18206. };
  18207. const maybeMatch = (reg, str) => {
  18208. const m = str.match(reg);
  18209. return m ? m[0] : null;
  18210. };
  18211. const range = (a, b, str) => {
  18212. let begs, beg, left, right = undefined, result;
  18213. let ai = str.indexOf(a);
  18214. let bi = str.indexOf(b, ai + 1);
  18215. let i = ai;
  18216. if (ai >= 0 && bi > 0) {
  18217. if (a === b) {
  18218. return [ai, bi];
  18219. }
  18220. begs = [];
  18221. left = str.length;
  18222. while (i >= 0 && !result) {
  18223. if (i === ai) {
  18224. begs.push(i);
  18225. ai = str.indexOf(a, i + 1);
  18226. }
  18227. else if (begs.length === 1) {
  18228. const r = begs.pop();
  18229. if (r !== undefined)
  18230. result = [r, bi];
  18231. }
  18232. else {
  18233. beg = begs.pop();
  18234. if (beg !== undefined && beg < left) {
  18235. left = beg;
  18236. right = bi;
  18237. }
  18238. bi = str.indexOf(b, i + 1);
  18239. }
  18240. i = ai < bi && ai >= 0 ? ai : bi;
  18241. }
  18242. if (begs.length && right !== undefined) {
  18243. result = [left, right];
  18244. }
  18245. }
  18246. return result;
  18247. };
  18248. const escSlash = '\0SLASH' + Math.random() + '\0';
  18249. const escOpen = '\0OPEN' + Math.random() + '\0';
  18250. const escClose = '\0CLOSE' + Math.random() + '\0';
  18251. const escComma = '\0COMMA' + Math.random() + '\0';
  18252. const escPeriod = '\0PERIOD' + Math.random() + '\0';
  18253. const escSlashPattern = new RegExp(escSlash, 'g');
  18254. const escOpenPattern = new RegExp(escOpen, 'g');
  18255. const escClosePattern = new RegExp(escClose, 'g');
  18256. const escCommaPattern = new RegExp(escComma, 'g');
  18257. const escPeriodPattern = new RegExp(escPeriod, 'g');
  18258. const slashPattern = /\\\\/g;
  18259. const openPattern = /\\{/g;
  18260. const closePattern = /\\}/g;
  18261. const commaPattern = /\\,/g;
  18262. const periodPattern = /\\\./g;
  18263. const EXPANSION_MAX = 100_000;
  18264. function numeric(str) {
  18265. return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0);
  18266. }
  18267. function escapeBraces(str) {
  18268. return str
  18269. .replace(slashPattern, escSlash)
  18270. .replace(openPattern, escOpen)
  18271. .replace(closePattern, escClose)
  18272. .replace(commaPattern, escComma)
  18273. .replace(periodPattern, escPeriod);
  18274. }
  18275. function unescapeBraces(str) {
  18276. return str
  18277. .replace(escSlashPattern, '\\')
  18278. .replace(escOpenPattern, '{')
  18279. .replace(escClosePattern, '}')
  18280. .replace(escCommaPattern, ',')
  18281. .replace(escPeriodPattern, '.');
  18282. }
  18283. /**
  18284. * Basically just str.split(","), but handling cases
  18285. * where we have nested braced sections, which should be
  18286. * treated as individual members, like {a,{b,c},d}
  18287. */
  18288. function parseCommaParts(str) {
  18289. if (!str) {
  18290. return [''];
  18291. }
  18292. const parts = [];
  18293. const m = balanced('{', '}', str);
  18294. if (!m) {
  18295. return str.split(',');
  18296. }
  18297. const { pre, body, post } = m;
  18298. const p = pre.split(',');
  18299. p[p.length - 1] += '{' + body + '}';
  18300. const postParts = parseCommaParts(post);
  18301. if (post.length) {
  18302. p[p.length - 1] += postParts.shift();
  18303. p.push.apply(p, postParts);
  18304. }
  18305. parts.push.apply(parts, p);
  18306. return parts;
  18307. }
  18308. function expand(str, options = {}) {
  18309. if (!str) {
  18310. return [];
  18311. }
  18312. const { max = EXPANSION_MAX } = options;
  18313. // I don't know why Bash 4.3 does this, but it does.
  18314. // Anything starting with {} will have the first two bytes preserved
  18315. // but *only* at the top level, so {},a}b will not expand to anything,
  18316. // but a{},b}c will be expanded to [a}c,abc].
  18317. // One could argue that this is a bug in Bash, but since the goal of
  18318. // this module is to match Bash's rules, we escape a leading {}
  18319. if (str.slice(0, 2) === '{}') {
  18320. str = '\\{\\}' + str.slice(2);
  18321. }
  18322. return expand_(escapeBraces(str), max, true).map(unescapeBraces);
  18323. }
  18324. function embrace(str) {
  18325. return '{' + str + '}';
  18326. }
  18327. function isPadded(el) {
  18328. return /^-?0\d/.test(el);
  18329. }
  18330. function lte(i, y) {
  18331. return i <= y;
  18332. }
  18333. function gte(i, y) {
  18334. return i >= y;
  18335. }
  18336. function expand_(str, max, isTop) {
  18337. /** @type {string[]} */
  18338. const expansions = [];
  18339. const m = balanced('{', '}', str);
  18340. if (!m)
  18341. return [str];
  18342. // no need to expand pre, since it is guaranteed to be free of brace-sets
  18343. const pre = m.pre;
  18344. const post = m.post.length ? expand_(m.post, max, false) : [''];
  18345. if (/\$$/.test(m.pre)) {
  18346. for (let k = 0; k < post.length && k < max; k++) {
  18347. const expansion = pre + '{' + m.body + '}' + post[k];
  18348. expansions.push(expansion);
  18349. }
  18350. }
  18351. else {
  18352. const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  18353. const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  18354. const isSequence = isNumericSequence || isAlphaSequence;
  18355. const isOptions = m.body.indexOf(',') >= 0;
  18356. if (!isSequence && !isOptions) {
  18357. // {a},b}
  18358. if (m.post.match(/,(?!,).*\}/)) {
  18359. str = m.pre + '{' + m.body + escClose + m.post;
  18360. return expand_(str, max, true);
  18361. }
  18362. return [str];
  18363. }
  18364. let n;
  18365. if (isSequence) {
  18366. n = m.body.split(/\.\./);
  18367. }
  18368. else {
  18369. n = parseCommaParts(m.body);
  18370. if (n.length === 1 && n[0] !== undefined) {
  18371. // x{{a,b}}y ==> x{a}y x{b}y
  18372. n = expand_(n[0], max, false).map(embrace);
  18373. //XXX is this necessary? Can't seem to hit it in tests.
  18374. /* c8 ignore start */
  18375. if (n.length === 1) {
  18376. return post.map(p => m.pre + n[0] + p);
  18377. }
  18378. /* c8 ignore stop */
  18379. }
  18380. }
  18381. // at this point, n is the parts, and we know it's not a comma set
  18382. // with a single entry.
  18383. let N;
  18384. if (isSequence && n[0] !== undefined && n[1] !== undefined) {
  18385. const x = numeric(n[0]);
  18386. const y = numeric(n[1]);
  18387. const width = Math.max(n[0].length, n[1].length);
  18388. let incr = n.length === 3 && n[2] !== undefined ? Math.abs(numeric(n[2])) : 1;
  18389. let test = lte;
  18390. const reverse = y < x;
  18391. if (reverse) {
  18392. incr *= -1;
  18393. test = gte;
  18394. }
  18395. const pad = n.some(isPadded);
  18396. N = [];
  18397. for (let i = x; test(i, y); i += incr) {
  18398. let c;
  18399. if (isAlphaSequence) {
  18400. c = String.fromCharCode(i);
  18401. if (c === '\\') {
  18402. c = '';
  18403. }
  18404. }
  18405. else {
  18406. c = String(i);
  18407. if (pad) {
  18408. const need = width - c.length;
  18409. if (need > 0) {
  18410. const z = new Array(need + 1).join('0');
  18411. if (i < 0) {
  18412. c = '-' + z + c.slice(1);
  18413. }
  18414. else {
  18415. c = z + c;
  18416. }
  18417. }
  18418. }
  18419. }
  18420. N.push(c);
  18421. }
  18422. }
  18423. else {
  18424. N = [];
  18425. for (let j = 0; j < n.length; j++) {
  18426. N.push.apply(N, expand_(n[j], max, false));
  18427. }
  18428. }
  18429. for (let j = 0; j < N.length; j++) {
  18430. for (let k = 0; k < post.length && expansions.length < max; k++) {
  18431. const expansion = pre + N[j] + post[k];
  18432. if (!isTop || isSequence || expansion) {
  18433. expansions.push(expansion);
  18434. }
  18435. }
  18436. }
  18437. }
  18438. return expansions;
  18439. }
  18440. const MAX_PATTERN_LENGTH = 1024 * 64;
  18441. const assertValidPattern = (pattern) => {
  18442. if (typeof pattern !== 'string') {
  18443. throw new TypeError('invalid pattern');
  18444. }
  18445. if (pattern.length > MAX_PATTERN_LENGTH) {
  18446. throw new TypeError('pattern is too long');
  18447. }
  18448. };
  18449. // translate the various posix character classes into unicode properties
  18450. // this works across all unicode locales
  18451. // { <posix class>: [<translation>, /u flag required, negated]
  18452. const posixClasses = {
  18453. '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
  18454. '[:alpha:]': ['\\p{L}\\p{Nl}', true],
  18455. '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
  18456. '[:blank:]': ['\\p{Zs}\\t', true],
  18457. '[:cntrl:]': ['\\p{Cc}', true],
  18458. '[:digit:]': ['\\p{Nd}', true],
  18459. '[:graph:]': ['\\p{Z}\\p{C}', true, true],
  18460. '[:lower:]': ['\\p{Ll}', true],
  18461. '[:print:]': ['\\p{C}', true],
  18462. '[:punct:]': ['\\p{P}', true],
  18463. '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
  18464. '[:upper:]': ['\\p{Lu}', true],
  18465. '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
  18466. '[:xdigit:]': ['A-Fa-f0-9', false],
  18467. };
  18468. // only need to escape a few things inside of brace expressions
  18469. // escapes: [ \ ] -
  18470. const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
  18471. // escape all regexp magic characters
  18472. const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  18473. // everything has already been escaped, we just have to join
  18474. const rangesToString = (ranges) => ranges.join('');
  18475. // takes a glob string at a posix brace expression, and returns
  18476. // an equivalent regular expression source, and boolean indicating
  18477. // whether the /u flag needs to be applied, and the number of chars
  18478. // consumed to parse the character class.
  18479. // This also removes out of order ranges, and returns ($.) if the
  18480. // entire class just no good.
  18481. const parseClass = (glob, position) => {
  18482. const pos = position;
  18483. /* c8 ignore start */
  18484. if (glob.charAt(pos) !== '[') {
  18485. throw new Error('not in a brace expression');
  18486. }
  18487. /* c8 ignore stop */
  18488. const ranges = [];
  18489. const negs = [];
  18490. let i = pos + 1;
  18491. let sawStart = false;
  18492. let uflag = false;
  18493. let escaping = false;
  18494. let negate = false;
  18495. let endPos = pos;
  18496. let rangeStart = '';
  18497. WHILE: while (i < glob.length) {
  18498. const c = glob.charAt(i);
  18499. if ((c === '!' || c === '^') && i === pos + 1) {
  18500. negate = true;
  18501. i++;
  18502. continue;
  18503. }
  18504. if (c === ']' && sawStart && !escaping) {
  18505. endPos = i + 1;
  18506. break;
  18507. }
  18508. sawStart = true;
  18509. if (c === '\\') {
  18510. if (!escaping) {
  18511. escaping = true;
  18512. i++;
  18513. continue;
  18514. }
  18515. // escaped \ char, fall through and treat like normal char
  18516. }
  18517. if (c === '[' && !escaping) {
  18518. // either a posix class, a collation equivalent, or just a [
  18519. for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
  18520. if (glob.startsWith(cls, i)) {
  18521. // invalid, [a-[] is fine, but not [a-[:alpha]]
  18522. if (rangeStart) {
  18523. return ['$.', false, glob.length - pos, true];
  18524. }
  18525. i += cls.length;
  18526. if (neg)
  18527. negs.push(unip);
  18528. else
  18529. ranges.push(unip);
  18530. uflag = uflag || u;
  18531. continue WHILE;
  18532. }
  18533. }
  18534. }
  18535. // now it's just a normal character, effectively
  18536. escaping = false;
  18537. if (rangeStart) {
  18538. // throw this range away if it's not valid, but others
  18539. // can still match.
  18540. if (c > rangeStart) {
  18541. ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
  18542. }
  18543. else if (c === rangeStart) {
  18544. ranges.push(braceEscape(c));
  18545. }
  18546. rangeStart = '';
  18547. i++;
  18548. continue;
  18549. }
  18550. // now might be the start of a range.
  18551. // can be either c-d or c-] or c<more...>] or c] at this point
  18552. if (glob.startsWith('-]', i + 1)) {
  18553. ranges.push(braceEscape(c + '-'));
  18554. i += 2;
  18555. continue;
  18556. }
  18557. if (glob.startsWith('-', i + 1)) {
  18558. rangeStart = c;
  18559. i += 2;
  18560. continue;
  18561. }
  18562. // not the start of a range, just a single character
  18563. ranges.push(braceEscape(c));
  18564. i++;
  18565. }
  18566. if (endPos < i) {
  18567. // didn't see the end of the class, not a valid class,
  18568. // but might still be valid as a literal match.
  18569. return ['', false, 0, false];
  18570. }
  18571. // if we got no ranges and no negates, then we have a range that
  18572. // cannot possibly match anything, and that poisons the whole glob
  18573. if (!ranges.length && !negs.length) {
  18574. return ['$.', false, glob.length - pos, true];
  18575. }
  18576. // if we got one positive range, and it's a single character, then that's
  18577. // not actually a magic pattern, it's just that one literal character.
  18578. // we should not treat that as "magic", we should just return the literal
  18579. // character. [_] is a perfectly valid way to escape glob magic chars.
  18580. if (negs.length === 0 &&
  18581. ranges.length === 1 &&
  18582. /^\\?.$/.test(ranges[0]) &&
  18583. !negate) {
  18584. const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
  18585. return [regexpEscape(r), false, endPos - pos, false];
  18586. }
  18587. const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
  18588. const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
  18589. const comb = ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'
  18590. : ranges.length ? sranges
  18591. : snegs;
  18592. return [comb, uflag, endPos - pos, true];
  18593. };
  18594. /**
  18595. * Un-escape a string that has been escaped with {@link escape}.
  18596. *
  18597. * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then
  18598. * square-bracket escapes are removed, but not backslash escapes.
  18599. *
  18600. * For example, it will turn the string `'[*]'` into `*`, but it will not
  18601. * turn `'\\*'` into `'*'`, because `\` is a path separator in
  18602. * `windowsPathsNoEscape` mode.
  18603. *
  18604. * When `windowsPathsNoEscape` is not set, then both square-bracket escapes and
  18605. * backslash escapes are removed.
  18606. *
  18607. * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
  18608. * or unescaped.
  18609. *
  18610. * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be
  18611. * unescaped.
  18612. */
  18613. const unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true, } = {}) => {
  18614. if (magicalBraces) {
  18615. return windowsPathsNoEscape ?
  18616. s.replace(/\[([^\/\\])\]/g, '$1')
  18617. : s
  18618. .replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2')
  18619. .replace(/\\([^\/])/g, '$1');
  18620. }
  18621. return windowsPathsNoEscape ?
  18622. s.replace(/\[([^\/\\{}])\]/g, '$1')
  18623. : s
  18624. .replace(/((?!\\).|^)\[([^\/\\{}])\]/g, '$1$2')
  18625. .replace(/\\([^\/{}])/g, '$1');
  18626. };
  18627. // parse a single path portion
  18628. var _a;
  18629. const types = new Set(['!', '?', '+', '*', '@']);
  18630. const isExtglobType = (c) => types.has(c);
  18631. const isExtglobAST = (c) => isExtglobType(c.type);
  18632. // Map of which extglob types can adopt the children of a nested extglob
  18633. //
  18634. // anything but ! can adopt a matching type:
  18635. // +(a|+(b|c)|d) => +(a|b|c|d)
  18636. // *(a|*(b|c)|d) => *(a|b|c|d)
  18637. // @(a|@(b|c)|d) => @(a|b|c|d)
  18638. // ?(a|?(b|c)|d) => ?(a|b|c|d)
  18639. //
  18640. // * can adopt anything, because 0 or repetition is allowed
  18641. // *(a|?(b|c)|d) => *(a|b|c|d)
  18642. // *(a|+(b|c)|d) => *(a|b|c|d)
  18643. // *(a|@(b|c)|d) => *(a|b|c|d)
  18644. //
  18645. // + can adopt @, because 1 or repetition is allowed
  18646. // +(a|@(b|c)|d) => +(a|b|c|d)
  18647. //
  18648. // + and @ CANNOT adopt *, because 0 would be allowed
  18649. // +(a|*(b|c)|d) => would match "", on *(b|c)
  18650. // @(a|*(b|c)|d) => would match "", on *(b|c)
  18651. //
  18652. // + and @ CANNOT adopt ?, because 0 would be allowed
  18653. // +(a|?(b|c)|d) => would match "", on ?(b|c)
  18654. // @(a|?(b|c)|d) => would match "", on ?(b|c)
  18655. //
  18656. // ? can adopt @, because 0 or 1 is allowed
  18657. // ?(a|@(b|c)|d) => ?(a|b|c|d)
  18658. //
  18659. // ? and @ CANNOT adopt * or +, because >1 would be allowed
  18660. // ?(a|*(b|c)|d) => would match bbb on *(b|c)
  18661. // @(a|*(b|c)|d) => would match bbb on *(b|c)
  18662. // ?(a|+(b|c)|d) => would match bbb on +(b|c)
  18663. // @(a|+(b|c)|d) => would match bbb on +(b|c)
  18664. //
  18665. // ! CANNOT adopt ! (nothing else can either)
  18666. // !(a|!(b|c)|d) => !(a|b|c|d) would fail to match on b (not not b|c)
  18667. //
  18668. // ! can adopt @
  18669. // !(a|@(b|c)|d) => !(a|b|c|d)
  18670. //
  18671. // ! CANNOT adopt *
  18672. // !(a|*(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed
  18673. //
  18674. // ! CANNOT adopt +
  18675. // !(a|+(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed
  18676. //
  18677. // ! CANNOT adopt ?
  18678. // x!(a|?(b|c)|d) => x!(a|b|c|d) would fail to match "x"
  18679. const adoptionMap = new Map([
  18680. ['!', ['@']],
  18681. ['?', ['?', '@']],
  18682. ['@', ['@']],
  18683. ['*', ['*', '+', '?', '@']],
  18684. ['+', ['+', '@']],
  18685. ]);
  18686. // nested extglobs that can be adopted in, but with the addition of
  18687. // a blank '' element.
  18688. const adoptionWithSpaceMap = new Map([
  18689. ['!', ['?']],
  18690. ['@', ['?']],
  18691. ['+', ['?', '*']],
  18692. ]);
  18693. // union of the previous two maps
  18694. const adoptionAnyMap = new Map([
  18695. ['!', ['?', '@']],
  18696. ['?', ['?', '@']],
  18697. ['@', ['?', '@']],
  18698. ['*', ['*', '+', '?', '@']],
  18699. ['+', ['+', '@', '?', '*']],
  18700. ]);
  18701. // Extglobs that can take over their parent if they are the only child
  18702. // the key is parent, value maps child to resulting extglob parent type
  18703. // '@' is omitted because it's a special case. An `@` extglob with a single
  18704. // member can always be usurped by that subpattern.
  18705. const usurpMap = new Map([
  18706. ['!', new Map([['!', '@']])],
  18707. [
  18708. '?',
  18709. new Map([
  18710. ['*', '*'],
  18711. ['+', '*'],
  18712. ]),
  18713. ],
  18714. [
  18715. '@',
  18716. new Map([
  18717. ['!', '!'],
  18718. ['?', '?'],
  18719. ['@', '@'],
  18720. ['*', '*'],
  18721. ['+', '+'],
  18722. ]),
  18723. ],
  18724. [
  18725. '+',
  18726. new Map([
  18727. ['?', '*'],
  18728. ['*', '*'],
  18729. ]),
  18730. ],
  18731. ]);
  18732. // Patterns that get prepended to bind to the start of either the
  18733. // entire string, or just a single path portion, to prevent dots
  18734. // and/or traversal patterns, when needed.
  18735. // Exts don't need the ^ or / bit, because the root binds that already.
  18736. const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
  18737. const startNoDot = '(?!\\.)';
  18738. // characters that indicate a start of pattern needs the "no dots" bit,
  18739. // because a dot *might* be matched. ( is not in the list, because in
  18740. // the case of a child extglob, it will handle the prevention itself.
  18741. const addPatternStart = new Set(['[', '.']);
  18742. // cases where traversal is A-OK, no dot prevention needed
  18743. const justDots = new Set(['..', '.']);
  18744. const reSpecials = new Set('().*{}+?[]^$\\!');
  18745. const regExpEscape$1 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  18746. // any single thing other than /
  18747. const qmark$1 = '[^/]';
  18748. // * => any number of characters
  18749. const star$1 = qmark$1 + '*?';
  18750. // use + when we need to ensure that *something* matches, because the * is
  18751. // the only thing in the path portion.
  18752. const starNoEmpty = qmark$1 + '+?';
  18753. // remove the \ chars that we added if we end up doing a nonmagic compare
  18754. // const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
  18755. let ID = 0;
  18756. class AST {
  18757. type;
  18758. #root;
  18759. #hasMagic;
  18760. #uflag = false;
  18761. #parts = [];
  18762. #parent;
  18763. #parentIndex;
  18764. #negs;
  18765. #filledNegs = false;
  18766. #options;
  18767. #toString;
  18768. // set to true if it's an extglob with no children
  18769. // (which really means one child of '')
  18770. #emptyExt = false;
  18771. id = ++ID;
  18772. get depth() {
  18773. return (this.#parent?.depth ?? -1) + 1;
  18774. }
  18775. [Symbol.for('nodejs.util.inspect.custom')]() {
  18776. return {
  18777. '@@type': 'AST',
  18778. id: this.id,
  18779. type: this.type,
  18780. root: this.#root.id,
  18781. parent: this.#parent?.id,
  18782. depth: this.depth,
  18783. partsLength: this.#parts.length,
  18784. parts: this.#parts,
  18785. };
  18786. }
  18787. constructor(type, parent, options = {}) {
  18788. this.type = type;
  18789. // extglobs are inherently magical
  18790. if (type)
  18791. this.#hasMagic = true;
  18792. this.#parent = parent;
  18793. this.#root = this.#parent ? this.#parent.#root : this;
  18794. this.#options = this.#root === this ? options : this.#root.#options;
  18795. this.#negs = this.#root === this ? [] : this.#root.#negs;
  18796. if (type === '!' && !this.#root.#filledNegs)
  18797. this.#negs.push(this);
  18798. this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
  18799. }
  18800. get hasMagic() {
  18801. /* c8 ignore start */
  18802. if (this.#hasMagic !== undefined)
  18803. return this.#hasMagic;
  18804. /* c8 ignore stop */
  18805. for (const p of this.#parts) {
  18806. if (typeof p === 'string')
  18807. continue;
  18808. if (p.type || p.hasMagic)
  18809. return (this.#hasMagic = true);
  18810. }
  18811. // note: will be undefined until we generate the regexp src and find out
  18812. return this.#hasMagic;
  18813. }
  18814. // reconstructs the pattern
  18815. toString() {
  18816. if (this.#toString !== undefined)
  18817. return this.#toString;
  18818. if (!this.type) {
  18819. return (this.#toString = this.#parts.map(p => String(p)).join(''));
  18820. }
  18821. else {
  18822. return (this.#toString =
  18823. this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
  18824. }
  18825. }
  18826. #fillNegs() {
  18827. /* c8 ignore start */
  18828. if (this !== this.#root)
  18829. throw new Error('should only call on root');
  18830. if (this.#filledNegs)
  18831. return this;
  18832. /* c8 ignore stop */
  18833. // call toString() once to fill this out
  18834. this.toString();
  18835. this.#filledNegs = true;
  18836. let n;
  18837. while ((n = this.#negs.pop())) {
  18838. if (n.type !== '!')
  18839. continue;
  18840. // walk up the tree, appending everthing that comes AFTER parentIndex
  18841. let p = n;
  18842. let pp = p.#parent;
  18843. while (pp) {
  18844. for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
  18845. for (const part of n.#parts) {
  18846. /* c8 ignore start */
  18847. if (typeof part === 'string') {
  18848. throw new Error('string part in extglob AST??');
  18849. }
  18850. /* c8 ignore stop */
  18851. part.copyIn(pp.#parts[i]);
  18852. }
  18853. }
  18854. p = pp;
  18855. pp = p.#parent;
  18856. }
  18857. }
  18858. return this;
  18859. }
  18860. push(...parts) {
  18861. for (const p of parts) {
  18862. if (p === '')
  18863. continue;
  18864. /* c8 ignore start */
  18865. if (typeof p !== 'string' &&
  18866. !(p instanceof _a && p.#parent === this)) {
  18867. throw new Error('invalid part: ' + p);
  18868. }
  18869. /* c8 ignore stop */
  18870. this.#parts.push(p);
  18871. }
  18872. }
  18873. toJSON() {
  18874. const ret = this.type === null ?
  18875. this.#parts
  18876. .slice()
  18877. .map(p => (typeof p === 'string' ? p : p.toJSON()))
  18878. : [this.type, ...this.#parts.map(p => p.toJSON())];
  18879. if (this.isStart() && !this.type)
  18880. ret.unshift([]);
  18881. if (this.isEnd() &&
  18882. (this === this.#root ||
  18883. (this.#root.#filledNegs && this.#parent?.type === '!'))) {
  18884. ret.push({});
  18885. }
  18886. return ret;
  18887. }
  18888. isStart() {
  18889. if (this.#root === this)
  18890. return true;
  18891. // if (this.type) return !!this.#parent?.isStart()
  18892. if (!this.#parent?.isStart())
  18893. return false;
  18894. if (this.#parentIndex === 0)
  18895. return true;
  18896. // if everything AHEAD of this is a negation, then it's still the "start"
  18897. const p = this.#parent;
  18898. for (let i = 0; i < this.#parentIndex; i++) {
  18899. const pp = p.#parts[i];
  18900. if (!(pp instanceof _a && pp.type === '!')) {
  18901. return false;
  18902. }
  18903. }
  18904. return true;
  18905. }
  18906. isEnd() {
  18907. if (this.#root === this)
  18908. return true;
  18909. if (this.#parent?.type === '!')
  18910. return true;
  18911. if (!this.#parent?.isEnd())
  18912. return false;
  18913. if (!this.type)
  18914. return this.#parent?.isEnd();
  18915. // if not root, it'll always have a parent
  18916. /* c8 ignore start */
  18917. const pl = this.#parent ? this.#parent.#parts.length : 0;
  18918. /* c8 ignore stop */
  18919. return this.#parentIndex === pl - 1;
  18920. }
  18921. copyIn(part) {
  18922. if (typeof part === 'string')
  18923. this.push(part);
  18924. else
  18925. this.push(part.clone(this));
  18926. }
  18927. clone(parent) {
  18928. const c = new _a(this.type, parent);
  18929. for (const p of this.#parts) {
  18930. c.copyIn(p);
  18931. }
  18932. return c;
  18933. }
  18934. static #parseAST(str, ast, pos, opt, extDepth) {
  18935. const maxDepth = opt.maxExtglobRecursion ?? 2;
  18936. let escaping = false;
  18937. let inBrace = false;
  18938. let braceStart = -1;
  18939. let braceNeg = false;
  18940. if (ast.type === null) {
  18941. // outside of a extglob, append until we find a start
  18942. let i = pos;
  18943. let acc = '';
  18944. while (i < str.length) {
  18945. const c = str.charAt(i++);
  18946. // still accumulate escapes at this point, but we do ignore
  18947. // starts that are escaped
  18948. if (escaping || c === '\\') {
  18949. escaping = !escaping;
  18950. acc += c;
  18951. continue;
  18952. }
  18953. if (inBrace) {
  18954. if (i === braceStart + 1) {
  18955. if (c === '^' || c === '!') {
  18956. braceNeg = true;
  18957. }
  18958. }
  18959. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  18960. inBrace = false;
  18961. }
  18962. acc += c;
  18963. continue;
  18964. }
  18965. else if (c === '[') {
  18966. inBrace = true;
  18967. braceStart = i;
  18968. braceNeg = false;
  18969. acc += c;
  18970. continue;
  18971. }
  18972. // we don't have to check for adoption here, because that's
  18973. // done at the other recursion point.
  18974. const doRecurse = !opt.noext &&
  18975. isExtglobType(c) &&
  18976. str.charAt(i) === '(' &&
  18977. extDepth <= maxDepth;
  18978. if (doRecurse) {
  18979. ast.push(acc);
  18980. acc = '';
  18981. const ext = new _a(c, ast);
  18982. i = _a.#parseAST(str, ext, i, opt, extDepth + 1);
  18983. ast.push(ext);
  18984. continue;
  18985. }
  18986. acc += c;
  18987. }
  18988. ast.push(acc);
  18989. return i;
  18990. }
  18991. // some kind of extglob, pos is at the (
  18992. // find the next | or )
  18993. let i = pos + 1;
  18994. let part = new _a(null, ast);
  18995. const parts = [];
  18996. let acc = '';
  18997. while (i < str.length) {
  18998. const c = str.charAt(i++);
  18999. // still accumulate escapes at this point, but we do ignore
  19000. // starts that are escaped
  19001. if (escaping || c === '\\') {
  19002. escaping = !escaping;
  19003. acc += c;
  19004. continue;
  19005. }
  19006. if (inBrace) {
  19007. if (i === braceStart + 1) {
  19008. if (c === '^' || c === '!') {
  19009. braceNeg = true;
  19010. }
  19011. }
  19012. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  19013. inBrace = false;
  19014. }
  19015. acc += c;
  19016. continue;
  19017. }
  19018. else if (c === '[') {
  19019. inBrace = true;
  19020. braceStart = i;
  19021. braceNeg = false;
  19022. acc += c;
  19023. continue;
  19024. }
  19025. const doRecurse = !opt.noext &&
  19026. isExtglobType(c) &&
  19027. str.charAt(i) === '(' &&
  19028. /* c8 ignore start - the maxDepth is sufficient here */
  19029. (extDepth <= maxDepth || (ast && ast.#canAdoptType(c)));
  19030. /* c8 ignore stop */
  19031. if (doRecurse) {
  19032. const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1;
  19033. part.push(acc);
  19034. acc = '';
  19035. const ext = new _a(c, part);
  19036. part.push(ext);
  19037. i = _a.#parseAST(str, ext, i, opt, extDepth + depthAdd);
  19038. continue;
  19039. }
  19040. if (c === '|') {
  19041. part.push(acc);
  19042. acc = '';
  19043. parts.push(part);
  19044. part = new _a(null, ast);
  19045. continue;
  19046. }
  19047. if (c === ')') {
  19048. if (acc === '' && ast.#parts.length === 0) {
  19049. ast.#emptyExt = true;
  19050. }
  19051. part.push(acc);
  19052. acc = '';
  19053. ast.push(...parts, part);
  19054. return i;
  19055. }
  19056. acc += c;
  19057. }
  19058. // unfinished extglob
  19059. // if we got here, it was a malformed extglob! not an extglob, but
  19060. // maybe something else in there.
  19061. ast.type = null;
  19062. ast.#hasMagic = undefined;
  19063. ast.#parts = [str.substring(pos - 1)];
  19064. return i;
  19065. }
  19066. #canAdoptWithSpace(child) {
  19067. return this.#canAdopt(child, adoptionWithSpaceMap);
  19068. }
  19069. #canAdopt(child, map = adoptionMap) {
  19070. if (!child ||
  19071. typeof child !== 'object' ||
  19072. child.type !== null ||
  19073. child.#parts.length !== 1 ||
  19074. this.type === null) {
  19075. return false;
  19076. }
  19077. const gc = child.#parts[0];
  19078. if (!gc || typeof gc !== 'object' || gc.type === null) {
  19079. return false;
  19080. }
  19081. return this.#canAdoptType(gc.type, map);
  19082. }
  19083. #canAdoptType(c, map = adoptionAnyMap) {
  19084. return !!map.get(this.type)?.includes(c);
  19085. }
  19086. #adoptWithSpace(child, index) {
  19087. const gc = child.#parts[0];
  19088. const blank = new _a(null, gc, this.options);
  19089. blank.#parts.push('');
  19090. gc.push(blank);
  19091. this.#adopt(child, index);
  19092. }
  19093. #adopt(child, index) {
  19094. const gc = child.#parts[0];
  19095. this.#parts.splice(index, 1, ...gc.#parts);
  19096. for (const p of gc.#parts) {
  19097. if (typeof p === 'object')
  19098. p.#parent = this;
  19099. }
  19100. this.#toString = undefined;
  19101. }
  19102. #canUsurpType(c) {
  19103. const m = usurpMap.get(this.type);
  19104. return !!(m?.has(c));
  19105. }
  19106. #canUsurp(child) {
  19107. if (!child ||
  19108. typeof child !== 'object' ||
  19109. child.type !== null ||
  19110. child.#parts.length !== 1 ||
  19111. this.type === null ||
  19112. this.#parts.length !== 1) {
  19113. return false;
  19114. }
  19115. const gc = child.#parts[0];
  19116. if (!gc || typeof gc !== 'object' || gc.type === null) {
  19117. return false;
  19118. }
  19119. return this.#canUsurpType(gc.type);
  19120. }
  19121. #usurp(child) {
  19122. const m = usurpMap.get(this.type);
  19123. const gc = child.#parts[0];
  19124. const nt = m?.get(gc.type);
  19125. /* c8 ignore start - impossible */
  19126. if (!nt)
  19127. return false;
  19128. /* c8 ignore stop */
  19129. this.#parts = gc.#parts;
  19130. for (const p of this.#parts) {
  19131. if (typeof p === 'object') {
  19132. p.#parent = this;
  19133. }
  19134. }
  19135. this.type = nt;
  19136. this.#toString = undefined;
  19137. this.#emptyExt = false;
  19138. }
  19139. static fromGlob(pattern, options = {}) {
  19140. const ast = new _a(null, undefined, options);
  19141. _a.#parseAST(pattern, ast, 0, options, 0);
  19142. return ast;
  19143. }
  19144. // returns the regular expression if there's magic, or the unescaped
  19145. // string if not.
  19146. toMMPattern() {
  19147. // should only be called on root
  19148. /* c8 ignore start */
  19149. if (this !== this.#root)
  19150. return this.#root.toMMPattern();
  19151. /* c8 ignore stop */
  19152. const glob = this.toString();
  19153. const [re, body, hasMagic, uflag] = this.toRegExpSource();
  19154. // if we're in nocase mode, and not nocaseMagicOnly, then we do
  19155. // still need a regular expression if we have to case-insensitively
  19156. // match capital/lowercase characters.
  19157. const anyMagic = hasMagic ||
  19158. this.#hasMagic ||
  19159. (this.#options.nocase &&
  19160. !this.#options.nocaseMagicOnly &&
  19161. glob.toUpperCase() !== glob.toLowerCase());
  19162. if (!anyMagic) {
  19163. return body;
  19164. }
  19165. const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
  19166. return Object.assign(new RegExp(`^${re}$`, flags), {
  19167. _src: re,
  19168. _glob: glob,
  19169. });
  19170. }
  19171. get options() {
  19172. return this.#options;
  19173. }
  19174. // returns the string match, the regexp source, whether there's magic
  19175. // in the regexp (so a regular expression is required) and whether or
  19176. // not the uflag is needed for the regular expression (for posix classes)
  19177. // TODO: instead of injecting the start/end at this point, just return
  19178. // the BODY of the regexp, along with the start/end portions suitable
  19179. // for binding the start/end in either a joined full-path makeRe context
  19180. // (where we bind to (^|/), or a standalone matchPart context (where
  19181. // we bind to ^, and not /). Otherwise slashes get duped!
  19182. //
  19183. // In part-matching mode, the start is:
  19184. // - if not isStart: nothing
  19185. // - if traversal possible, but not allowed: ^(?!\.\.?$)
  19186. // - if dots allowed or not possible: ^
  19187. // - if dots possible and not allowed: ^(?!\.)
  19188. // end is:
  19189. // - if not isEnd(): nothing
  19190. // - else: $
  19191. //
  19192. // In full-path matching mode, we put the slash at the START of the
  19193. // pattern, so start is:
  19194. // - if first pattern: same as part-matching mode
  19195. // - if not isStart(): nothing
  19196. // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
  19197. // - if dots allowed or not possible: /
  19198. // - if dots possible and not allowed: /(?!\.)
  19199. // end is:
  19200. // - if last pattern, same as part-matching mode
  19201. // - else nothing
  19202. //
  19203. // Always put the (?:$|/) on negated tails, though, because that has to be
  19204. // there to bind the end of the negated pattern portion, and it's easier to
  19205. // just stick it in now rather than try to inject it later in the middle of
  19206. // the pattern.
  19207. //
  19208. // We can just always return the same end, and leave it up to the caller
  19209. // to know whether it's going to be used joined or in parts.
  19210. // And, if the start is adjusted slightly, can do the same there:
  19211. // - if not isStart: nothing
  19212. // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
  19213. // - if dots allowed or not possible: (?:/|^)
  19214. // - if dots possible and not allowed: (?:/|^)(?!\.)
  19215. //
  19216. // But it's better to have a simpler binding without a conditional, for
  19217. // performance, so probably better to return both start options.
  19218. //
  19219. // Then the caller just ignores the end if it's not the first pattern,
  19220. // and the start always gets applied.
  19221. //
  19222. // But that's always going to be $ if it's the ending pattern, or nothing,
  19223. // so the caller can just attach $ at the end of the pattern when building.
  19224. //
  19225. // So the todo is:
  19226. // - better detect what kind of start is needed
  19227. // - return both flavors of starting pattern
  19228. // - attach $ at the end of the pattern when creating the actual RegExp
  19229. //
  19230. // Ah, but wait, no, that all only applies to the root when the first pattern
  19231. // is not an extglob. If the first pattern IS an extglob, then we need all
  19232. // that dot prevention biz to live in the extglob portions, because eg
  19233. // +(*|.x*) can match .xy but not .yx.
  19234. //
  19235. // So, return the two flavors if it's #root and the first child is not an
  19236. // AST, otherwise leave it to the child AST to handle it, and there,
  19237. // use the (?:^|/) style of start binding.
  19238. //
  19239. // Even simplified further:
  19240. // - Since the start for a join is eg /(?!\.) and the start for a part
  19241. // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
  19242. // or start or whatever) and prepend ^ or / at the Regexp construction.
  19243. toRegExpSource(allowDot) {
  19244. const dot = allowDot ?? !!this.#options.dot;
  19245. if (this.#root === this) {
  19246. this.#flatten();
  19247. this.#fillNegs();
  19248. }
  19249. if (!isExtglobAST(this)) {
  19250. const noEmpty = this.isStart() &&
  19251. this.isEnd() &&
  19252. !this.#parts.some(s => typeof s !== 'string');
  19253. const src = this.#parts
  19254. .map(p => {
  19255. const [re, _, hasMagic, uflag] = typeof p === 'string' ?
  19256. _a.#parseGlob(p, this.#hasMagic, noEmpty)
  19257. : p.toRegExpSource(allowDot);
  19258. this.#hasMagic = this.#hasMagic || hasMagic;
  19259. this.#uflag = this.#uflag || uflag;
  19260. return re;
  19261. })
  19262. .join('');
  19263. let start = '';
  19264. if (this.isStart()) {
  19265. if (typeof this.#parts[0] === 'string') {
  19266. // this is the string that will match the start of the pattern,
  19267. // so we need to protect against dots and such.
  19268. // '.' and '..' cannot match unless the pattern is that exactly,
  19269. // even if it starts with . or dot:true is set.
  19270. const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
  19271. if (!dotTravAllowed) {
  19272. const aps = addPatternStart;
  19273. // check if we have a possibility of matching . or ..,
  19274. // and prevent that.
  19275. const needNoTrav =
  19276. // dots are allowed, and the pattern starts with [ or .
  19277. (dot && aps.has(src.charAt(0))) ||
  19278. // the pattern starts with \., and then [ or .
  19279. (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
  19280. // the pattern starts with \.\., and then [ or .
  19281. (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
  19282. // no need to prevent dots if it can't match a dot, or if a
  19283. // sub-pattern will be preventing it anyway.
  19284. const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
  19285. start =
  19286. needNoTrav ? startNoTraversal
  19287. : needNoDot ? startNoDot
  19288. : '';
  19289. }
  19290. }
  19291. }
  19292. // append the "end of path portion" pattern to negation tails
  19293. let end = '';
  19294. if (this.isEnd() &&
  19295. this.#root.#filledNegs &&
  19296. this.#parent?.type === '!') {
  19297. end = '(?:$|\\/)';
  19298. }
  19299. const final = start + src + end;
  19300. return [
  19301. final,
  19302. unescape(src),
  19303. (this.#hasMagic = !!this.#hasMagic),
  19304. this.#uflag,
  19305. ];
  19306. }
  19307. // We need to calculate the body *twice* if it's a repeat pattern
  19308. // at the start, once in nodot mode, then again in dot mode, so a
  19309. // pattern like *(?) can match 'x.y'
  19310. const repeated = this.type === '*' || this.type === '+';
  19311. // some kind of extglob
  19312. const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
  19313. let body = this.#partsToRegExp(dot);
  19314. if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
  19315. // invalid extglob, has to at least be *something* present, if it's
  19316. // the entire path portion.
  19317. const s = this.toString();
  19318. const me = this;
  19319. me.#parts = [s];
  19320. me.type = null;
  19321. me.#hasMagic = undefined;
  19322. return [s, unescape(this.toString()), false, false];
  19323. }
  19324. let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ?
  19325. ''
  19326. : this.#partsToRegExp(true);
  19327. if (bodyDotAllowed === body) {
  19328. bodyDotAllowed = '';
  19329. }
  19330. if (bodyDotAllowed) {
  19331. body = `(?:${body})(?:${bodyDotAllowed})*?`;
  19332. }
  19333. // an empty !() is exactly equivalent to a starNoEmpty
  19334. let final = '';
  19335. if (this.type === '!' && this.#emptyExt) {
  19336. final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
  19337. }
  19338. else {
  19339. const close = this.type === '!' ?
  19340. // !() must match something,but !(x) can match ''
  19341. '))' +
  19342. (this.isStart() && !dot && !allowDot ? startNoDot : '') +
  19343. star$1 +
  19344. ')'
  19345. : this.type === '@' ? ')'
  19346. : this.type === '?' ? ')?'
  19347. : this.type === '+' && bodyDotAllowed ? ')'
  19348. : this.type === '*' && bodyDotAllowed ? `)?`
  19349. : `)${this.type}`;
  19350. final = start + body + close;
  19351. }
  19352. return [
  19353. final,
  19354. unescape(body),
  19355. (this.#hasMagic = !!this.#hasMagic),
  19356. this.#uflag,
  19357. ];
  19358. }
  19359. #flatten() {
  19360. if (!isExtglobAST(this)) {
  19361. for (const p of this.#parts) {
  19362. if (typeof p === 'object') {
  19363. p.#flatten();
  19364. }
  19365. }
  19366. }
  19367. else {
  19368. // do up to 10 passes to flatten as much as possible
  19369. let iterations = 0;
  19370. let done = false;
  19371. do {
  19372. done = true;
  19373. for (let i = 0; i < this.#parts.length; i++) {
  19374. const c = this.#parts[i];
  19375. if (typeof c === 'object') {
  19376. c.#flatten();
  19377. if (this.#canAdopt(c)) {
  19378. done = false;
  19379. this.#adopt(c, i);
  19380. }
  19381. else if (this.#canAdoptWithSpace(c)) {
  19382. done = false;
  19383. this.#adoptWithSpace(c, i);
  19384. }
  19385. else if (this.#canUsurp(c)) {
  19386. done = false;
  19387. this.#usurp(c);
  19388. }
  19389. }
  19390. }
  19391. } while (!done && ++iterations < 10);
  19392. }
  19393. this.#toString = undefined;
  19394. }
  19395. #partsToRegExp(dot) {
  19396. return this.#parts
  19397. .map(p => {
  19398. // extglob ASTs should only contain parent ASTs
  19399. /* c8 ignore start */
  19400. if (typeof p === 'string') {
  19401. throw new Error('string type in extglob ast??');
  19402. }
  19403. /* c8 ignore stop */
  19404. // can ignore hasMagic, because extglobs are already always magic
  19405. const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
  19406. this.#uflag = this.#uflag || uflag;
  19407. return re;
  19408. })
  19409. .filter(p => !(this.isStart() && this.isEnd()) || !!p)
  19410. .join('|');
  19411. }
  19412. static #parseGlob(glob, hasMagic, noEmpty = false) {
  19413. let escaping = false;
  19414. let re = '';
  19415. let uflag = false;
  19416. // multiple stars that aren't globstars coalesce into one *
  19417. let inStar = false;
  19418. for (let i = 0; i < glob.length; i++) {
  19419. const c = glob.charAt(i);
  19420. if (escaping) {
  19421. escaping = false;
  19422. re += (reSpecials.has(c) ? '\\' : '') + c;
  19423. continue;
  19424. }
  19425. if (c === '*') {
  19426. if (inStar)
  19427. continue;
  19428. inStar = true;
  19429. re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star$1;
  19430. hasMagic = true;
  19431. continue;
  19432. }
  19433. else {
  19434. inStar = false;
  19435. }
  19436. if (c === '\\') {
  19437. if (i === glob.length - 1) {
  19438. re += '\\\\';
  19439. }
  19440. else {
  19441. escaping = true;
  19442. }
  19443. continue;
  19444. }
  19445. if (c === '[') {
  19446. const [src, needUflag, consumed, magic] = parseClass(glob, i);
  19447. if (consumed) {
  19448. re += src;
  19449. uflag = uflag || needUflag;
  19450. i += consumed - 1;
  19451. hasMagic = hasMagic || magic;
  19452. continue;
  19453. }
  19454. }
  19455. if (c === '?') {
  19456. re += qmark$1;
  19457. hasMagic = true;
  19458. continue;
  19459. }
  19460. re += regExpEscape$1(c);
  19461. }
  19462. return [re, unescape(glob), !!hasMagic, uflag];
  19463. }
  19464. }
  19465. _a = AST;
  19466. /**
  19467. * Escape all magic characters in a glob pattern.
  19468. *
  19469. * If the {@link MinimatchOptions.windowsPathsNoEscape}
  19470. * option is used, then characters are escaped by wrapping in `[]`, because
  19471. * a magic character wrapped in a character class can only be satisfied by
  19472. * that exact character. In this mode, `\` is _not_ escaped, because it is
  19473. * not interpreted as a magic character, but instead as a path separator.
  19474. *
  19475. * If the {@link MinimatchOptions.magicalBraces} option is used,
  19476. * then braces (`{` and `}`) will be escaped.
  19477. */
  19478. const escape = (s, { windowsPathsNoEscape = false, magicalBraces = false, } = {}) => {
  19479. // don't need to escape +@! because we escape the parens
  19480. // that make those magic, and escaping ! as [!] isn't valid,
  19481. // because [!]] is a valid glob class meaning not ']'.
  19482. if (magicalBraces) {
  19483. return windowsPathsNoEscape ?
  19484. s.replace(/[?*()[\]{}]/g, '[$&]')
  19485. : s.replace(/[?*()[\]\\{}]/g, '\\$&');
  19486. }
  19487. return windowsPathsNoEscape ?
  19488. s.replace(/[?*()[\]]/g, '[$&]')
  19489. : s.replace(/[?*()[\]\\]/g, '\\$&');
  19490. };
  19491. const minimatch = (p, pattern, options = {}) => {
  19492. assertValidPattern(pattern);
  19493. // shortcut: comments match nothing.
  19494. if (!options.nocomment && pattern.charAt(0) === '#') {
  19495. return false;
  19496. }
  19497. return new Minimatch(pattern, options).match(p);
  19498. };
  19499. // Optimized checking for the most common glob patterns.
  19500. const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
  19501. const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
  19502. const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
  19503. const starDotExtTestNocase = (ext) => {
  19504. ext = ext.toLowerCase();
  19505. return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
  19506. };
  19507. const starDotExtTestNocaseDot = (ext) => {
  19508. ext = ext.toLowerCase();
  19509. return (f) => f.toLowerCase().endsWith(ext);
  19510. };
  19511. const starDotStarRE = /^\*+\.\*+$/;
  19512. const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
  19513. const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
  19514. const dotStarRE = /^\.\*+$/;
  19515. const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
  19516. const starRE = /^\*+$/;
  19517. const starTest = (f) => f.length !== 0 && !f.startsWith('.');
  19518. const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
  19519. const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
  19520. const qmarksTestNocase = ([$0, ext = '']) => {
  19521. const noext = qmarksTestNoExt([$0]);
  19522. if (!ext)
  19523. return noext;
  19524. ext = ext.toLowerCase();
  19525. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  19526. };
  19527. const qmarksTestNocaseDot = ([$0, ext = '']) => {
  19528. const noext = qmarksTestNoExtDot([$0]);
  19529. if (!ext)
  19530. return noext;
  19531. ext = ext.toLowerCase();
  19532. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  19533. };
  19534. const qmarksTestDot = ([$0, ext = '']) => {
  19535. const noext = qmarksTestNoExtDot([$0]);
  19536. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  19537. };
  19538. const qmarksTest = ([$0, ext = '']) => {
  19539. const noext = qmarksTestNoExt([$0]);
  19540. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  19541. };
  19542. const qmarksTestNoExt = ([$0]) => {
  19543. const len = $0.length;
  19544. return (f) => f.length === len && !f.startsWith('.');
  19545. };
  19546. const qmarksTestNoExtDot = ([$0]) => {
  19547. const len = $0.length;
  19548. return (f) => f.length === len && f !== '.' && f !== '..';
  19549. };
  19550. /* c8 ignore start */
  19551. const defaultPlatform = (typeof process === 'object' && process ?
  19552. (typeof process.env === 'object' &&
  19553. process.env &&
  19554. process.env.__MINIMATCH_TESTING_PLATFORM__) ||
  19555. process.platform
  19556. : 'posix');
  19557. const path = {
  19558. win32: { sep: '\\' },
  19559. posix: { sep: '/' },
  19560. };
  19561. /* c8 ignore stop */
  19562. const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
  19563. minimatch.sep = sep;
  19564. const GLOBSTAR = Symbol('globstar **');
  19565. minimatch.GLOBSTAR = GLOBSTAR;
  19566. // any single thing other than /
  19567. // don't need to escape / when using new RegExp()
  19568. const qmark = '[^/]';
  19569. // * => any number of characters
  19570. const star = qmark + '*?';
  19571. // ** when dots are allowed. Anything goes, except .. and .
  19572. // not (^ or / followed by one or two dots followed by $ or /),
  19573. // followed by anything, any number of times.
  19574. const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
  19575. // not a ^ or / followed by a dot,
  19576. // followed by anything, any number of times.
  19577. const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
  19578. const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
  19579. minimatch.filter = filter;
  19580. const ext = (a, b = {}) => Object.assign({}, a, b);
  19581. const defaults = (def) => {
  19582. if (!def || typeof def !== 'object' || !Object.keys(def).length) {
  19583. return minimatch;
  19584. }
  19585. const orig = minimatch;
  19586. const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
  19587. return Object.assign(m, {
  19588. Minimatch: class Minimatch extends orig.Minimatch {
  19589. constructor(pattern, options = {}) {
  19590. super(pattern, ext(def, options));
  19591. }
  19592. static defaults(options) {
  19593. return orig.defaults(ext(def, options)).Minimatch;
  19594. }
  19595. },
  19596. AST: class AST extends orig.AST {
  19597. /* c8 ignore start */
  19598. constructor(type, parent, options = {}) {
  19599. super(type, parent, ext(def, options));
  19600. }
  19601. /* c8 ignore stop */
  19602. static fromGlob(pattern, options = {}) {
  19603. return orig.AST.fromGlob(pattern, ext(def, options));
  19604. }
  19605. },
  19606. unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
  19607. escape: (s, options = {}) => orig.escape(s, ext(def, options)),
  19608. filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
  19609. defaults: (options) => orig.defaults(ext(def, options)),
  19610. makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
  19611. braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
  19612. match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
  19613. sep: orig.sep,
  19614. GLOBSTAR: GLOBSTAR,
  19615. });
  19616. };
  19617. minimatch.defaults = defaults;
  19618. // Brace expansion:
  19619. // a{b,c}d -> abd acd
  19620. // a{b,}c -> abc ac
  19621. // a{0..3}d -> a0d a1d a2d a3d
  19622. // a{b,c{d,e}f}g -> abg acdfg acefg
  19623. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  19624. //
  19625. // Invalid sets are not expanded.
  19626. // a{2..}b -> a{2..}b
  19627. // a{b}c -> a{b}c
  19628. const braceExpand = (pattern, options = {}) => {
  19629. assertValidPattern(pattern);
  19630. // Thanks to Yeting Li <https://github.com/yetingli> for
  19631. // improving this regexp to avoid a ReDOS vulnerability.
  19632. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
  19633. // shortcut. no need to expand.
  19634. return [pattern];
  19635. }
  19636. return expand(pattern, { max: options.braceExpandMax });
  19637. };
  19638. minimatch.braceExpand = braceExpand;
  19639. // parse a component of the expanded set.
  19640. // At this point, no pattern may contain "/" in it
  19641. // so we're going to return a 2d array, where each entry is the full
  19642. // pattern, split on '/', and then turned into a regular expression.
  19643. // A regexp is made at the end which joins each array with an
  19644. // escaped /, and another full one which joins each regexp with |.
  19645. //
  19646. // Following the lead of Bash 4.1, note that "**" only has special meaning
  19647. // when it is the *only* thing in a path portion. Otherwise, any series
  19648. // of * is equivalent to a single *. Globstar behavior is enabled by
  19649. // default, and can be disabled by setting options.noglobstar.
  19650. const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
  19651. minimatch.makeRe = makeRe;
  19652. const match = (list, pattern, options = {}) => {
  19653. const mm = new Minimatch(pattern, options);
  19654. list = list.filter(f => mm.match(f));
  19655. if (mm.options.nonull && !list.length) {
  19656. list.push(pattern);
  19657. }
  19658. return list;
  19659. };
  19660. minimatch.match = match;
  19661. // replace stuff like \* with *
  19662. const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
  19663. const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  19664. class Minimatch {
  19665. options;
  19666. set;
  19667. pattern;
  19668. windowsPathsNoEscape;
  19669. nonegate;
  19670. negate;
  19671. comment;
  19672. empty;
  19673. preserveMultipleSlashes;
  19674. partial;
  19675. globSet;
  19676. globParts;
  19677. nocase;
  19678. isWindows;
  19679. platform;
  19680. windowsNoMagicRoot;
  19681. maxGlobstarRecursion;
  19682. regexp;
  19683. constructor(pattern, options = {}) {
  19684. assertValidPattern(pattern);
  19685. options = options || {};
  19686. this.options = options;
  19687. this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? 200;
  19688. this.pattern = pattern;
  19689. this.platform = options.platform || defaultPlatform;
  19690. this.isWindows = this.platform === 'win32';
  19691. // avoid the annoying deprecation flag lol
  19692. const awe = ('allowWindow' + 'sEscape');
  19693. this.windowsPathsNoEscape =
  19694. !!options.windowsPathsNoEscape || options[awe] === false;
  19695. if (this.windowsPathsNoEscape) {
  19696. this.pattern = this.pattern.replace(/\\/g, '/');
  19697. }
  19698. this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
  19699. this.regexp = null;
  19700. this.negate = false;
  19701. this.nonegate = !!options.nonegate;
  19702. this.comment = false;
  19703. this.empty = false;
  19704. this.partial = !!options.partial;
  19705. this.nocase = !!this.options.nocase;
  19706. this.windowsNoMagicRoot =
  19707. options.windowsNoMagicRoot !== undefined ?
  19708. options.windowsNoMagicRoot
  19709. : !!(this.isWindows && this.nocase);
  19710. this.globSet = [];
  19711. this.globParts = [];
  19712. this.set = [];
  19713. // make the set of regexps etc.
  19714. this.make();
  19715. }
  19716. hasMagic() {
  19717. if (this.options.magicalBraces && this.set.length > 1) {
  19718. return true;
  19719. }
  19720. for (const pattern of this.set) {
  19721. for (const part of pattern) {
  19722. if (typeof part !== 'string')
  19723. return true;
  19724. }
  19725. }
  19726. return false;
  19727. }
  19728. debug(..._) { }
  19729. make() {
  19730. const pattern = this.pattern;
  19731. const options = this.options;
  19732. // empty patterns and comments match nothing.
  19733. if (!options.nocomment && pattern.charAt(0) === '#') {
  19734. this.comment = true;
  19735. return;
  19736. }
  19737. if (!pattern) {
  19738. this.empty = true;
  19739. return;
  19740. }
  19741. // step 1: figure out negation, etc.
  19742. this.parseNegate();
  19743. // step 2: expand braces
  19744. this.globSet = [...new Set(this.braceExpand())];
  19745. if (options.debug) {
  19746. this.debug = (...args) => console.error(...args);
  19747. }
  19748. this.debug(this.pattern, this.globSet);
  19749. // step 3: now we have a set, so turn each one into a series of
  19750. // path-portion matching patterns.
  19751. // These will be regexps, except in the case of "**", which is
  19752. // set to the GLOBSTAR object for globstar behavior,
  19753. // and will not contain any / characters
  19754. //
  19755. // First, we preprocess to make the glob pattern sets a bit simpler
  19756. // and deduped. There are some perf-killing patterns that can cause
  19757. // problems with a glob walk, but we can simplify them down a bit.
  19758. const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
  19759. this.globParts = this.preprocess(rawGlobParts);
  19760. this.debug(this.pattern, this.globParts);
  19761. // glob --> regexps
  19762. let set = this.globParts.map((s, _, __) => {
  19763. if (this.isWindows && this.windowsNoMagicRoot) {
  19764. // check if it's a drive or unc path.
  19765. const isUNC = s[0] === '' &&
  19766. s[1] === '' &&
  19767. (s[2] === '?' || !globMagic.test(s[2])) &&
  19768. !globMagic.test(s[3]);
  19769. const isDrive = /^[a-z]:/i.test(s[0]);
  19770. if (isUNC) {
  19771. return [
  19772. ...s.slice(0, 4),
  19773. ...s.slice(4).map(ss => this.parse(ss)),
  19774. ];
  19775. }
  19776. else if (isDrive) {
  19777. return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
  19778. }
  19779. }
  19780. return s.map(ss => this.parse(ss));
  19781. });
  19782. this.debug(this.pattern, set);
  19783. // filter out everything that didn't compile properly.
  19784. this.set = set.filter(s => s.indexOf(false) === -1);
  19785. // do not treat the ? in UNC paths as magic
  19786. if (this.isWindows) {
  19787. for (let i = 0; i < this.set.length; i++) {
  19788. const p = this.set[i];
  19789. if (p[0] === '' &&
  19790. p[1] === '' &&
  19791. this.globParts[i][2] === '?' &&
  19792. typeof p[3] === 'string' &&
  19793. /^[a-z]:$/i.test(p[3])) {
  19794. p[2] = '?';
  19795. }
  19796. }
  19797. }
  19798. this.debug(this.pattern, this.set);
  19799. }
  19800. // various transforms to equivalent pattern sets that are
  19801. // faster to process in a filesystem walk. The goal is to
  19802. // eliminate what we can, and push all ** patterns as far
  19803. // to the right as possible, even if it increases the number
  19804. // of patterns that we have to process.
  19805. preprocess(globParts) {
  19806. // if we're not in globstar mode, then turn ** into *
  19807. if (this.options.noglobstar) {
  19808. for (let i = 0; i < globParts.length; i++) {
  19809. for (let j = 0; j < globParts[i].length; j++) {
  19810. if (globParts[i][j] === '**') {
  19811. globParts[i][j] = '*';
  19812. }
  19813. }
  19814. }
  19815. }
  19816. const { optimizationLevel = 1 } = this.options;
  19817. if (optimizationLevel >= 2) {
  19818. // aggressive optimization for the purpose of fs walking
  19819. globParts = this.firstPhasePreProcess(globParts);
  19820. globParts = this.secondPhasePreProcess(globParts);
  19821. }
  19822. else if (optimizationLevel >= 1) {
  19823. // just basic optimizations to remove some .. parts
  19824. globParts = this.levelOneOptimize(globParts);
  19825. }
  19826. else {
  19827. // just collapse multiple ** portions into one
  19828. globParts = this.adjascentGlobstarOptimize(globParts);
  19829. }
  19830. return globParts;
  19831. }
  19832. // just get rid of adjascent ** portions
  19833. adjascentGlobstarOptimize(globParts) {
  19834. return globParts.map(parts => {
  19835. let gs = -1;
  19836. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  19837. let i = gs;
  19838. while (parts[i + 1] === '**') {
  19839. i++;
  19840. }
  19841. if (i !== gs) {
  19842. parts.splice(gs, i - gs);
  19843. }
  19844. }
  19845. return parts;
  19846. });
  19847. }
  19848. // get rid of adjascent ** and resolve .. portions
  19849. levelOneOptimize(globParts) {
  19850. return globParts.map(parts => {
  19851. parts = parts.reduce((set, part) => {
  19852. const prev = set[set.length - 1];
  19853. if (part === '**' && prev === '**') {
  19854. return set;
  19855. }
  19856. if (part === '..') {
  19857. if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
  19858. set.pop();
  19859. return set;
  19860. }
  19861. }
  19862. set.push(part);
  19863. return set;
  19864. }, []);
  19865. return parts.length === 0 ? [''] : parts;
  19866. });
  19867. }
  19868. levelTwoFileOptimize(parts) {
  19869. if (!Array.isArray(parts)) {
  19870. parts = this.slashSplit(parts);
  19871. }
  19872. let didSomething = false;
  19873. do {
  19874. didSomething = false;
  19875. // <pre>/<e>/<rest> -> <pre>/<rest>
  19876. if (!this.preserveMultipleSlashes) {
  19877. for (let i = 1; i < parts.length - 1; i++) {
  19878. const p = parts[i];
  19879. // don't squeeze out UNC patterns
  19880. if (i === 1 && p === '' && parts[0] === '')
  19881. continue;
  19882. if (p === '.' || p === '') {
  19883. didSomething = true;
  19884. parts.splice(i, 1);
  19885. i--;
  19886. }
  19887. }
  19888. if (parts[0] === '.' &&
  19889. parts.length === 2 &&
  19890. (parts[1] === '.' || parts[1] === '')) {
  19891. didSomething = true;
  19892. parts.pop();
  19893. }
  19894. }
  19895. // <pre>/<p>/../<rest> -> <pre>/<rest>
  19896. let dd = 0;
  19897. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  19898. const p = parts[dd - 1];
  19899. if (p && p !== '.' && p !== '..' && p !== '**') {
  19900. didSomething = true;
  19901. parts.splice(dd - 1, 2);
  19902. dd -= 2;
  19903. }
  19904. }
  19905. } while (didSomething);
  19906. return parts.length === 0 ? [''] : parts;
  19907. }
  19908. // First phase: single-pattern processing
  19909. // <pre> is 1 or more portions
  19910. // <rest> is 1 or more portions
  19911. // <p> is any portion other than ., .., '', or **
  19912. // <e> is . or ''
  19913. //
  19914. // **/.. is *brutal* for filesystem walking performance, because
  19915. // it effectively resets the recursive walk each time it occurs,
  19916. // and ** cannot be reduced out by a .. pattern part like a regexp
  19917. // or most strings (other than .., ., and '') can be.
  19918. //
  19919. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  19920. // <pre>/<e>/<rest> -> <pre>/<rest>
  19921. // <pre>/<p>/../<rest> -> <pre>/<rest>
  19922. // **/**/<rest> -> **/<rest>
  19923. //
  19924. // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
  19925. // this WOULD be allowed if ** did follow symlinks, or * didn't
  19926. firstPhasePreProcess(globParts) {
  19927. let didSomething = false;
  19928. do {
  19929. didSomething = false;
  19930. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  19931. for (let parts of globParts) {
  19932. let gs = -1;
  19933. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  19934. let gss = gs;
  19935. while (parts[gss + 1] === '**') {
  19936. // <pre>/**/**/<rest> -> <pre>/**/<rest>
  19937. gss++;
  19938. }
  19939. // eg, if gs is 2 and gss is 4, that means we have 3 **
  19940. // parts, and can remove 2 of them.
  19941. if (gss > gs) {
  19942. parts.splice(gs + 1, gss - gs);
  19943. }
  19944. let next = parts[gs + 1];
  19945. const p = parts[gs + 2];
  19946. const p2 = parts[gs + 3];
  19947. if (next !== '..')
  19948. continue;
  19949. if (!p ||
  19950. p === '.' ||
  19951. p === '..' ||
  19952. !p2 ||
  19953. p2 === '.' ||
  19954. p2 === '..') {
  19955. continue;
  19956. }
  19957. didSomething = true;
  19958. // edit parts in place, and push the new one
  19959. parts.splice(gs, 1);
  19960. const other = parts.slice(0);
  19961. other[gs] = '**';
  19962. globParts.push(other);
  19963. gs--;
  19964. }
  19965. // <pre>/<e>/<rest> -> <pre>/<rest>
  19966. if (!this.preserveMultipleSlashes) {
  19967. for (let i = 1; i < parts.length - 1; i++) {
  19968. const p = parts[i];
  19969. // don't squeeze out UNC patterns
  19970. if (i === 1 && p === '' && parts[0] === '')
  19971. continue;
  19972. if (p === '.' || p === '') {
  19973. didSomething = true;
  19974. parts.splice(i, 1);
  19975. i--;
  19976. }
  19977. }
  19978. if (parts[0] === '.' &&
  19979. parts.length === 2 &&
  19980. (parts[1] === '.' || parts[1] === '')) {
  19981. didSomething = true;
  19982. parts.pop();
  19983. }
  19984. }
  19985. // <pre>/<p>/../<rest> -> <pre>/<rest>
  19986. let dd = 0;
  19987. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  19988. const p = parts[dd - 1];
  19989. if (p && p !== '.' && p !== '..' && p !== '**') {
  19990. didSomething = true;
  19991. const needDot = dd === 1 && parts[dd + 1] === '**';
  19992. const splin = needDot ? ['.'] : [];
  19993. parts.splice(dd - 1, 2, ...splin);
  19994. if (parts.length === 0)
  19995. parts.push('');
  19996. dd -= 2;
  19997. }
  19998. }
  19999. }
  20000. } while (didSomething);
  20001. return globParts;
  20002. }
  20003. // second phase: multi-pattern dedupes
  20004. // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
  20005. // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
  20006. // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
  20007. //
  20008. // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
  20009. // ^-- not valid because ** doens't follow symlinks
  20010. secondPhasePreProcess(globParts) {
  20011. for (let i = 0; i < globParts.length - 1; i++) {
  20012. for (let j = i + 1; j < globParts.length; j++) {
  20013. const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
  20014. if (matched) {
  20015. globParts[i] = [];
  20016. globParts[j] = matched;
  20017. break;
  20018. }
  20019. }
  20020. }
  20021. return globParts.filter(gs => gs.length);
  20022. }
  20023. partsMatch(a, b, emptyGSMatch = false) {
  20024. let ai = 0;
  20025. let bi = 0;
  20026. let result = [];
  20027. let which = '';
  20028. while (ai < a.length && bi < b.length) {
  20029. if (a[ai] === b[bi]) {
  20030. result.push(which === 'b' ? b[bi] : a[ai]);
  20031. ai++;
  20032. bi++;
  20033. }
  20034. else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
  20035. result.push(a[ai]);
  20036. ai++;
  20037. }
  20038. else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
  20039. result.push(b[bi]);
  20040. bi++;
  20041. }
  20042. else if (a[ai] === '*' &&
  20043. b[bi] &&
  20044. (this.options.dot || !b[bi].startsWith('.')) &&
  20045. b[bi] !== '**') {
  20046. if (which === 'b')
  20047. return false;
  20048. which = 'a';
  20049. result.push(a[ai]);
  20050. ai++;
  20051. bi++;
  20052. }
  20053. else if (b[bi] === '*' &&
  20054. a[ai] &&
  20055. (this.options.dot || !a[ai].startsWith('.')) &&
  20056. a[ai] !== '**') {
  20057. if (which === 'a')
  20058. return false;
  20059. which = 'b';
  20060. result.push(b[bi]);
  20061. ai++;
  20062. bi++;
  20063. }
  20064. else {
  20065. return false;
  20066. }
  20067. }
  20068. // if we fall out of the loop, it means they two are identical
  20069. // as long as their lengths match
  20070. return a.length === b.length && result;
  20071. }
  20072. parseNegate() {
  20073. if (this.nonegate)
  20074. return;
  20075. const pattern = this.pattern;
  20076. let negate = false;
  20077. let negateOffset = 0;
  20078. for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
  20079. negate = !negate;
  20080. negateOffset++;
  20081. }
  20082. if (negateOffset)
  20083. this.pattern = pattern.slice(negateOffset);
  20084. this.negate = negate;
  20085. }
  20086. // set partial to true to test if, for example,
  20087. // "/a/b" matches the start of "/*/b/*/d"
  20088. // Partial means, if you run out of file before you run
  20089. // out of pattern, then that's fine, as long as all
  20090. // the parts match.
  20091. matchOne(file, pattern, partial = false) {
  20092. let fileStartIndex = 0;
  20093. let patternStartIndex = 0;
  20094. // UNC paths like //?/X:/... can match X:/... and vice versa
  20095. // Drive letters in absolute drive or unc paths are always compared
  20096. // case-insensitively.
  20097. if (this.isWindows) {
  20098. const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
  20099. const fileUNC = !fileDrive &&
  20100. file[0] === '' &&
  20101. file[1] === '' &&
  20102. file[2] === '?' &&
  20103. /^[a-z]:$/i.test(file[3]);
  20104. const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
  20105. const patternUNC = !patternDrive &&
  20106. pattern[0] === '' &&
  20107. pattern[1] === '' &&
  20108. pattern[2] === '?' &&
  20109. typeof pattern[3] === 'string' &&
  20110. /^[a-z]:$/i.test(pattern[3]);
  20111. const fdi = fileUNC ? 3
  20112. : fileDrive ? 0
  20113. : undefined;
  20114. const pdi = patternUNC ? 3
  20115. : patternDrive ? 0
  20116. : undefined;
  20117. if (typeof fdi === 'number' && typeof pdi === 'number') {
  20118. const [fd, pd] = [
  20119. file[fdi],
  20120. pattern[pdi],
  20121. ];
  20122. // start matching at the drive letter index of each
  20123. if (fd.toLowerCase() === pd.toLowerCase()) {
  20124. pattern[pdi] = fd;
  20125. patternStartIndex = pdi;
  20126. fileStartIndex = fdi;
  20127. }
  20128. }
  20129. }
  20130. // resolve and reduce . and .. portions in the file as well.
  20131. // don't need to do the second phase, because it's only one string[]
  20132. const { optimizationLevel = 1 } = this.options;
  20133. if (optimizationLevel >= 2) {
  20134. file = this.levelTwoFileOptimize(file);
  20135. }
  20136. if (pattern.includes(GLOBSTAR)) {
  20137. return this.#matchGlobstar(file, pattern, partial, fileStartIndex, patternStartIndex);
  20138. }
  20139. return this.#matchOne(file, pattern, partial, fileStartIndex, patternStartIndex);
  20140. }
  20141. #matchGlobstar(file, pattern, partial, fileIndex, patternIndex) {
  20142. // split the pattern into head, tail, and middle of ** delimited parts
  20143. const firstgs = pattern.indexOf(GLOBSTAR, patternIndex);
  20144. const lastgs = pattern.lastIndexOf(GLOBSTAR);
  20145. // split the pattern up into globstar-delimited sections
  20146. // the tail has to be at the end, and the others just have
  20147. // to be found in order from the head.
  20148. const [head, body, tail] = partial ? [
  20149. pattern.slice(patternIndex, firstgs),
  20150. pattern.slice(firstgs + 1),
  20151. [],
  20152. ] : [
  20153. pattern.slice(patternIndex, firstgs),
  20154. pattern.slice(firstgs + 1, lastgs),
  20155. pattern.slice(lastgs + 1),
  20156. ];
  20157. // check the head, from the current file/pattern index.
  20158. if (head.length) {
  20159. const fileHead = file.slice(fileIndex, fileIndex + head.length);
  20160. if (!this.#matchOne(fileHead, head, partial, 0, 0)) {
  20161. return false;
  20162. }
  20163. fileIndex += head.length;
  20164. patternIndex += head.length;
  20165. }
  20166. // now we know the head matches!
  20167. // if the last portion is not empty, it MUST match the end
  20168. // check the tail
  20169. let fileTailMatch = 0;
  20170. if (tail.length) {
  20171. // if head + tail > file, then we cannot possibly match
  20172. if (tail.length + fileIndex > file.length)
  20173. return false;
  20174. // try to match the tail
  20175. let tailStart = file.length - tail.length;
  20176. if (this.#matchOne(file, tail, partial, tailStart, 0)) {
  20177. fileTailMatch = tail.length;
  20178. }
  20179. else {
  20180. // affordance for stuff like a/**/* matching a/b/
  20181. // if the last file portion is '', and there's more to the pattern
  20182. // then try without the '' bit.
  20183. if (file[file.length - 1] !== '' ||
  20184. fileIndex + tail.length === file.length) {
  20185. return false;
  20186. }
  20187. tailStart--;
  20188. if (!this.#matchOne(file, tail, partial, tailStart, 0)) {
  20189. return false;
  20190. }
  20191. fileTailMatch = tail.length + 1;
  20192. }
  20193. }
  20194. // now we know the tail matches!
  20195. // the middle is zero or more portions wrapped in **, possibly
  20196. // containing more ** sections.
  20197. // so a/**/b/**/c/**/d has become **/b/**/c/**
  20198. // if it's empty, it means a/**/b, just verify we have no bad dots
  20199. // if there's no tail, so it ends on /**, then we must have *something*
  20200. // after the head, or it's not a matc
  20201. if (!body.length) {
  20202. let sawSome = !!fileTailMatch;
  20203. for (let i = fileIndex; i < file.length - fileTailMatch; i++) {
  20204. const f = String(file[i]);
  20205. sawSome = true;
  20206. if (f === '.' ||
  20207. f === '..' ||
  20208. (!this.options.dot && f.startsWith('.'))) {
  20209. return false;
  20210. }
  20211. }
  20212. // in partial mode, we just need to get past all file parts
  20213. return partial || sawSome;
  20214. }
  20215. // now we know that there's one or more body sections, which can
  20216. // be matched anywhere from the 0 index (because the head was pruned)
  20217. // through to the length-fileTailMatch index.
  20218. // split the body up into sections, and note the minimum index it can
  20219. // be found at (start with the length of all previous segments)
  20220. // [section, before, after]
  20221. const bodySegments = [[[], 0]];
  20222. let currentBody = bodySegments[0];
  20223. let nonGsParts = 0;
  20224. const nonGsPartsSums = [0];
  20225. for (const b of body) {
  20226. if (b === GLOBSTAR) {
  20227. nonGsPartsSums.push(nonGsParts);
  20228. currentBody = [[], 0];
  20229. bodySegments.push(currentBody);
  20230. }
  20231. else {
  20232. currentBody[0].push(b);
  20233. nonGsParts++;
  20234. }
  20235. }
  20236. let i = bodySegments.length - 1;
  20237. const fileLength = file.length - fileTailMatch;
  20238. for (const b of bodySegments) {
  20239. b[1] = fileLength - (nonGsPartsSums[i--] + b[0].length);
  20240. }
  20241. return !!this.#matchGlobStarBodySections(file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch);
  20242. }
  20243. // return false for "nope, not matching"
  20244. // return null for "not matching, cannot keep trying"
  20245. #matchGlobStarBodySections(file,
  20246. // pattern section, last possible position for it
  20247. bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail) {
  20248. // take the first body segment, and walk from fileIndex to its "after"
  20249. // value at the end
  20250. // If it doesn't match at that position, we increment, until we hit
  20251. // that final possible position, and give up.
  20252. // If it does match, then advance and try to rest.
  20253. // If any of them fail we keep walking forward.
  20254. // this is still a bit recursively painful, but it's more constrained
  20255. // than previous implementations, because we never test something that
  20256. // can't possibly be a valid matching condition.
  20257. const bs = bodySegments[bodyIndex];
  20258. if (!bs) {
  20259. // just make sure that there's no bad dots
  20260. for (let i = fileIndex; i < file.length; i++) {
  20261. sawTail = true;
  20262. const f = file[i];
  20263. if (f === '.' ||
  20264. f === '..' ||
  20265. (!this.options.dot && f.startsWith('.'))) {
  20266. return false;
  20267. }
  20268. }
  20269. return sawTail;
  20270. }
  20271. // have a non-globstar body section to test
  20272. const [body, after] = bs;
  20273. while (fileIndex <= after) {
  20274. const m = this.#matchOne(file.slice(0, fileIndex + body.length), body, partial, fileIndex, 0);
  20275. // if limit exceeded, no match. intentional false negative,
  20276. // acceptable break in correctness for security.
  20277. if (m && globStarDepth < this.maxGlobstarRecursion) {
  20278. // match! see if the rest match. if so, we're done!
  20279. const sub = this.#matchGlobStarBodySections(file, bodySegments, fileIndex + body.length, bodyIndex + 1, partial, globStarDepth + 1, sawTail);
  20280. if (sub !== false) {
  20281. return sub;
  20282. }
  20283. }
  20284. const f = file[fileIndex];
  20285. if (f === '.' ||
  20286. f === '..' ||
  20287. (!this.options.dot && f.startsWith('.'))) {
  20288. return false;
  20289. }
  20290. fileIndex++;
  20291. }
  20292. // walked off. no point continuing
  20293. return partial || null;
  20294. }
  20295. #matchOne(file, pattern, partial, fileIndex, patternIndex) {
  20296. let fi;
  20297. let pi;
  20298. let pl;
  20299. let fl;
  20300. for (fi = fileIndex,
  20301. pi = patternIndex,
  20302. fl = file.length,
  20303. pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
  20304. this.debug('matchOne loop');
  20305. let p = pattern[pi];
  20306. let f = file[fi];
  20307. this.debug(pattern, p, f);
  20308. // should be impossible.
  20309. // some invalid regexp stuff in the set.
  20310. /* c8 ignore start */
  20311. if (p === false || p === GLOBSTAR) {
  20312. return false;
  20313. }
  20314. /* c8 ignore stop */
  20315. // something other than **
  20316. // non-magic patterns just have to match exactly
  20317. // patterns with magic have been turned into regexps.
  20318. let hit;
  20319. if (typeof p === 'string') {
  20320. hit = f === p;
  20321. this.debug('string match', p, f, hit);
  20322. }
  20323. else {
  20324. hit = p.test(f);
  20325. this.debug('pattern match', p, f, hit);
  20326. }
  20327. if (!hit)
  20328. return false;
  20329. }
  20330. // Note: ending in / means that we'll get a final ""
  20331. // at the end of the pattern. This can only match a
  20332. // corresponding "" at the end of the file.
  20333. // If the file ends in /, then it can only match a
  20334. // a pattern that ends in /, unless the pattern just
  20335. // doesn't have any more for it. But, a/b/ should *not*
  20336. // match "a/b/*", even though "" matches against the
  20337. // [^/]*? pattern, except in partial mode, where it might
  20338. // simply not be reached yet.
  20339. // However, a/b/ should still satisfy a/*
  20340. // now either we fell off the end of the pattern, or we're done.
  20341. if (fi === fl && pi === pl) {
  20342. // ran out of pattern and filename at the same time.
  20343. // an exact hit!
  20344. return true;
  20345. }
  20346. else if (fi === fl) {
  20347. // ran out of file, but still had pattern left.
  20348. // this is ok if we're doing the match as part of
  20349. // a glob fs traversal.
  20350. return partial;
  20351. }
  20352. else if (pi === pl) {
  20353. // ran out of pattern, still have file left.
  20354. // this is only acceptable if we're on the very last
  20355. // empty segment of a file with a trailing slash.
  20356. // a/* should match a/b/
  20357. return fi === fl - 1 && file[fi] === '';
  20358. /* c8 ignore start */
  20359. }
  20360. else {
  20361. // should be unreachable.
  20362. throw new Error('wtf?');
  20363. }
  20364. /* c8 ignore stop */
  20365. }
  20366. braceExpand() {
  20367. return braceExpand(this.pattern, this.options);
  20368. }
  20369. parse(pattern) {
  20370. assertValidPattern(pattern);
  20371. const options = this.options;
  20372. // shortcuts
  20373. if (pattern === '**')
  20374. return GLOBSTAR;
  20375. if (pattern === '')
  20376. return '';
  20377. // far and away, the most common glob pattern parts are
  20378. // *, *.*, and *.<ext> Add a fast check method for those.
  20379. let m;
  20380. let fastTest = null;
  20381. if ((m = pattern.match(starRE))) {
  20382. fastTest = options.dot ? starTestDot : starTest;
  20383. }
  20384. else if ((m = pattern.match(starDotExtRE))) {
  20385. fastTest = (options.nocase ?
  20386. options.dot ?
  20387. starDotExtTestNocaseDot
  20388. : starDotExtTestNocase
  20389. : options.dot ? starDotExtTestDot
  20390. : starDotExtTest)(m[1]);
  20391. }
  20392. else if ((m = pattern.match(qmarksRE))) {
  20393. fastTest = (options.nocase ?
  20394. options.dot ?
  20395. qmarksTestNocaseDot
  20396. : qmarksTestNocase
  20397. : options.dot ? qmarksTestDot
  20398. : qmarksTest)(m);
  20399. }
  20400. else if ((m = pattern.match(starDotStarRE))) {
  20401. fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
  20402. }
  20403. else if ((m = pattern.match(dotStarRE))) {
  20404. fastTest = dotStarTest;
  20405. }
  20406. const re = AST.fromGlob(pattern, this.options).toMMPattern();
  20407. if (fastTest && typeof re === 'object') {
  20408. // Avoids overriding in frozen environments
  20409. Reflect.defineProperty(re, 'test', { value: fastTest });
  20410. }
  20411. return re;
  20412. }
  20413. makeRe() {
  20414. if (this.regexp || this.regexp === false)
  20415. return this.regexp;
  20416. // at this point, this.set is a 2d array of partial
  20417. // pattern strings, or "**".
  20418. //
  20419. // It's better to use .match(). This function shouldn't
  20420. // be used, really, but it's pretty convenient sometimes,
  20421. // when you just want to work with a regex.
  20422. const set = this.set;
  20423. if (!set.length) {
  20424. this.regexp = false;
  20425. return this.regexp;
  20426. }
  20427. const options = this.options;
  20428. const twoStar = options.noglobstar ? star
  20429. : options.dot ? twoStarDot
  20430. : twoStarNoDot;
  20431. const flags = new Set(options.nocase ? ['i'] : []);
  20432. // regexpify non-globstar patterns
  20433. // if ** is only item, then we just do one twoStar
  20434. // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
  20435. // if ** is last, append (\/twoStar|) to previous
  20436. // if ** is in the middle, append (\/|\/twoStar\/) to previous
  20437. // then filter out GLOBSTAR symbols
  20438. let re = set
  20439. .map(pattern => {
  20440. const pp = pattern.map(p => {
  20441. if (p instanceof RegExp) {
  20442. for (const f of p.flags.split(''))
  20443. flags.add(f);
  20444. }
  20445. return (typeof p === 'string' ? regExpEscape(p)
  20446. : p === GLOBSTAR ? GLOBSTAR
  20447. : p._src);
  20448. });
  20449. pp.forEach((p, i) => {
  20450. const next = pp[i + 1];
  20451. const prev = pp[i - 1];
  20452. if (p !== GLOBSTAR || prev === GLOBSTAR) {
  20453. return;
  20454. }
  20455. if (prev === undefined) {
  20456. if (next !== undefined && next !== GLOBSTAR) {
  20457. pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
  20458. }
  20459. else {
  20460. pp[i] = twoStar;
  20461. }
  20462. }
  20463. else if (next === undefined) {
  20464. pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + ')?';
  20465. }
  20466. else if (next !== GLOBSTAR) {
  20467. pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
  20468. pp[i + 1] = GLOBSTAR;
  20469. }
  20470. });
  20471. const filtered = pp.filter(p => p !== GLOBSTAR);
  20472. // For partial matches, we need to make the pattern match
  20473. // any prefix of the full path. We do this by generating
  20474. // alternative patterns that match progressively longer prefixes.
  20475. if (this.partial && filtered.length >= 1) {
  20476. const prefixes = [];
  20477. for (let i = 1; i <= filtered.length; i++) {
  20478. prefixes.push(filtered.slice(0, i).join('/'));
  20479. }
  20480. return '(?:' + prefixes.join('|') + ')';
  20481. }
  20482. return filtered.join('/');
  20483. })
  20484. .join('|');
  20485. // need to wrap in parens if we had more than one thing with |,
  20486. // otherwise only the first will be anchored to ^ and the last to $
  20487. const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
  20488. // must match entire pattern
  20489. // ending in a * or ** will make it less strict.
  20490. re = '^' + open + re + close + '$';
  20491. // In partial mode, '/' should always match as it's a valid prefix for any pattern
  20492. if (this.partial) {
  20493. re = '^(?:\\/|' + open + re.slice(1, -1) + close + ')$';
  20494. }
  20495. // can match anything, as long as it's not this.
  20496. if (this.negate)
  20497. re = '^(?!' + re + ').+$';
  20498. try {
  20499. this.regexp = new RegExp(re, [...flags].join(''));
  20500. /* c8 ignore start */
  20501. }
  20502. catch (ex) {
  20503. // should be impossible
  20504. this.regexp = false;
  20505. }
  20506. /* c8 ignore stop */
  20507. return this.regexp;
  20508. }
  20509. slashSplit(p) {
  20510. // if p starts with // on windows, we preserve that
  20511. // so that UNC paths aren't broken. Otherwise, any number of
  20512. // / characters are coalesced into one, unless
  20513. // preserveMultipleSlashes is set to true.
  20514. if (this.preserveMultipleSlashes) {
  20515. return p.split('/');
  20516. }
  20517. else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
  20518. // add an extra '' for the one we lose
  20519. return ['', ...p.split(/\/+/)];
  20520. }
  20521. else {
  20522. return p.split(/\/+/);
  20523. }
  20524. }
  20525. match(f, partial = this.partial) {
  20526. this.debug('match', f, this.pattern);
  20527. // short-circuit in the case of busted things.
  20528. // comments, etc.
  20529. if (this.comment) {
  20530. return false;
  20531. }
  20532. if (this.empty) {
  20533. return f === '';
  20534. }
  20535. if (f === '/' && partial) {
  20536. return true;
  20537. }
  20538. const options = this.options;
  20539. // windows: need to use /, not \
  20540. if (this.isWindows) {
  20541. f = f.split('\\').join('/');
  20542. }
  20543. // treat the test path as a set of pathparts.
  20544. const ff = this.slashSplit(f);
  20545. this.debug(this.pattern, 'split', ff);
  20546. // just ONE of the pattern sets in this.set needs to match
  20547. // in order for it to be valid. If negating, then just one
  20548. // match means that we have failed.
  20549. // Either way, return on the first hit.
  20550. const set = this.set;
  20551. this.debug(this.pattern, 'set', set);
  20552. // Find the basename of the path by looking for the last non-empty segment
  20553. let filename = ff[ff.length - 1];
  20554. if (!filename) {
  20555. for (let i = ff.length - 2; !filename && i >= 0; i--) {
  20556. filename = ff[i];
  20557. }
  20558. }
  20559. for (let i = 0; i < set.length; i++) {
  20560. const pattern = set[i];
  20561. let file = ff;
  20562. if (options.matchBase && pattern.length === 1) {
  20563. file = [filename];
  20564. }
  20565. const hit = this.matchOne(file, pattern, partial);
  20566. if (hit) {
  20567. if (options.flipNegate) {
  20568. return true;
  20569. }
  20570. return !this.negate;
  20571. }
  20572. }
  20573. // didn't get any hits. this is success if it's a negative
  20574. // pattern, failure otherwise.
  20575. if (options.flipNegate) {
  20576. return false;
  20577. }
  20578. return this.negate;
  20579. }
  20580. static defaults(def) {
  20581. return minimatch.defaults(def).Minimatch;
  20582. }
  20583. }
  20584. /* c8 ignore stop */
  20585. minimatch.AST = AST;
  20586. minimatch.Minimatch = Minimatch;
  20587. minimatch.escape = escape;
  20588. minimatch.unescape = unescape;
  20589. class TypeScope {
  20590. constructor(filename, source, offset = 0, imports = /* @__PURE__ */ Object.create(null), types = /* @__PURE__ */ Object.create(null), declares = /* @__PURE__ */ Object.create(null)) {
  20591. this.filename = filename;
  20592. this.source = source;
  20593. this.offset = offset;
  20594. this.imports = imports;
  20595. this.types = types;
  20596. this.declares = declares;
  20597. this.isGenericScope = false;
  20598. this.resolvedImportSources = /* @__PURE__ */ Object.create(null);
  20599. this.exportedTypes = /* @__PURE__ */ Object.create(null);
  20600. this.exportedDeclares = /* @__PURE__ */ Object.create(null);
  20601. }
  20602. }
  20603. function resolveTypeElements(ctx, node, scope, typeParameters) {
  20604. const canCache = !typeParameters;
  20605. if (canCache && node._resolvedElements) {
  20606. return node._resolvedElements;
  20607. }
  20608. const resolved = innerResolveTypeElements(
  20609. ctx,
  20610. node,
  20611. node._ownerScope || scope || ctxToScope(ctx),
  20612. typeParameters
  20613. );
  20614. return canCache ? node._resolvedElements = resolved : resolved;
  20615. }
  20616. function innerResolveTypeElements(ctx, node, scope, typeParameters) {
  20617. var _a, _b;
  20618. if (node.leadingComments && node.leadingComments.some((c) => c.value.includes("@vue-ignore"))) {
  20619. return { props: {} };
  20620. }
  20621. switch (node.type) {
  20622. case "TSTypeLiteral":
  20623. return typeElementsToMap(ctx, node.members, scope, typeParameters);
  20624. case "TSInterfaceDeclaration":
  20625. return resolveInterfaceMembers(ctx, node, scope, typeParameters);
  20626. case "TSTypeAliasDeclaration":
  20627. case "TSTypeAnnotation":
  20628. case "TSParenthesizedType":
  20629. return resolveTypeElements(
  20630. ctx,
  20631. node.typeAnnotation,
  20632. scope,
  20633. typeParameters
  20634. );
  20635. case "TSFunctionType": {
  20636. return { props: {}, calls: [node] };
  20637. }
  20638. case "TSUnionType":
  20639. case "TSIntersectionType":
  20640. return mergeElements(
  20641. node.types.map((t) => resolveTypeElements(ctx, t, scope, typeParameters)),
  20642. node.type
  20643. );
  20644. case "TSMappedType":
  20645. return resolveMappedType(ctx, node, scope, typeParameters);
  20646. case "TSIndexedAccessType": {
  20647. const types = resolveIndexType(ctx, node, scope);
  20648. return mergeElements(
  20649. types.map((t) => resolveTypeElements(ctx, t, t._ownerScope)),
  20650. "TSUnionType"
  20651. );
  20652. }
  20653. case "TSExpressionWithTypeArguments":
  20654. // referenced by interface extends
  20655. case "TSTypeReference": {
  20656. const typeName = getReferenceName(node);
  20657. if ((typeName === "ExtractPropTypes" || typeName === "ExtractPublicPropTypes") && node.typeParameters && ((_a = scope.imports[typeName]) == null ? void 0 : _a.source) === "vue") {
  20658. return resolveExtractPropTypes(
  20659. resolveTypeElements(
  20660. ctx,
  20661. node.typeParameters.params[0],
  20662. scope,
  20663. typeParameters
  20664. ),
  20665. scope
  20666. );
  20667. }
  20668. const resolved = resolveTypeReference(ctx, node, scope);
  20669. if (resolved) {
  20670. let typeParams;
  20671. if ((resolved.type === "TSTypeAliasDeclaration" || resolved.type === "TSInterfaceDeclaration") && resolved.typeParameters && node.typeParameters) {
  20672. typeParams = /* @__PURE__ */ Object.create(null);
  20673. resolved.typeParameters.params.forEach((p, i) => {
  20674. let param = typeParameters && typeParameters[p.name];
  20675. if (!param) param = node.typeParameters.params[i];
  20676. typeParams[p.name] = param;
  20677. });
  20678. }
  20679. return resolveTypeElements(
  20680. ctx,
  20681. resolved,
  20682. resolved._ownerScope,
  20683. typeParams
  20684. );
  20685. } else {
  20686. if (typeof typeName === "string") {
  20687. if (typeParameters && typeParameters[typeName]) {
  20688. return resolveTypeElements(
  20689. ctx,
  20690. typeParameters[typeName],
  20691. scope,
  20692. typeParameters
  20693. );
  20694. }
  20695. if (
  20696. // @ts-expect-error
  20697. SupportedBuiltinsSet.has(typeName)
  20698. ) {
  20699. return resolveBuiltin(
  20700. ctx,
  20701. node,
  20702. typeName,
  20703. scope,
  20704. typeParameters
  20705. );
  20706. } else if (typeName === "ReturnType" && node.typeParameters) {
  20707. const ret = resolveReturnType(
  20708. ctx,
  20709. node.typeParameters.params[0],
  20710. scope
  20711. );
  20712. if (ret) {
  20713. return resolveTypeElements(ctx, ret, scope);
  20714. }
  20715. }
  20716. }
  20717. return ctx.error(
  20718. `Unresolvable type reference or unsupported built-in utility type`,
  20719. node,
  20720. scope
  20721. );
  20722. }
  20723. }
  20724. case "TSImportType": {
  20725. if (getId(node.argument) === "vue" && ((_b = node.qualifier) == null ? void 0 : _b.type) === "Identifier" && node.qualifier.name === "ExtractPropTypes" && node.typeParameters) {
  20726. return resolveExtractPropTypes(
  20727. resolveTypeElements(ctx, node.typeParameters.params[0], scope),
  20728. scope
  20729. );
  20730. }
  20731. const sourceScope = importSourceToScope(
  20732. ctx,
  20733. node.argument,
  20734. scope,
  20735. node.argument.value
  20736. );
  20737. const resolved = resolveTypeReference(ctx, node, sourceScope);
  20738. if (resolved) {
  20739. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  20740. }
  20741. break;
  20742. }
  20743. case "TSTypeQuery":
  20744. {
  20745. const resolved = resolveTypeReference(ctx, node, scope);
  20746. if (resolved) {
  20747. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  20748. }
  20749. }
  20750. break;
  20751. }
  20752. return ctx.error(`Unresolvable type: ${node.type}`, node, scope);
  20753. }
  20754. function typeElementsToMap(ctx, elements, scope = ctxToScope(ctx), typeParameters) {
  20755. const res = { props: {} };
  20756. for (const e of elements) {
  20757. if (e.type === "TSPropertySignature" || e.type === "TSMethodSignature") {
  20758. if (typeParameters) {
  20759. scope = createChildScope(scope);
  20760. scope.isGenericScope = true;
  20761. Object.assign(scope.types, typeParameters);
  20762. }
  20763. e._ownerScope = scope;
  20764. const name = getStringLiteralKey(e);
  20765. if (name !== null) {
  20766. res.props[name] = e;
  20767. } else {
  20768. ctx.error(
  20769. `Unsupported computed key in type referenced by a macro`,
  20770. e.key,
  20771. scope
  20772. );
  20773. }
  20774. } else if (e.type === "TSCallSignatureDeclaration") {
  20775. (res.calls || (res.calls = [])).push(e);
  20776. }
  20777. }
  20778. return res;
  20779. }
  20780. function mergeElements(maps, type) {
  20781. if (maps.length === 1) return maps[0];
  20782. const res = { props: {} };
  20783. const { props: baseProps } = res;
  20784. for (const { props, calls } of maps) {
  20785. for (const key in props) {
  20786. if (!shared.hasOwn(baseProps, key)) {
  20787. baseProps[key] = props[key];
  20788. } else {
  20789. baseProps[key] = createProperty(
  20790. baseProps[key].key,
  20791. {
  20792. type,
  20793. // @ts-expect-error
  20794. types: [baseProps[key], props[key]]
  20795. },
  20796. baseProps[key]._ownerScope,
  20797. baseProps[key].optional || props[key].optional
  20798. );
  20799. }
  20800. }
  20801. if (calls) {
  20802. (res.calls || (res.calls = [])).push(...calls);
  20803. }
  20804. }
  20805. return res;
  20806. }
  20807. function createProperty(key, typeAnnotation, scope, optional) {
  20808. return {
  20809. type: "TSPropertySignature",
  20810. key,
  20811. kind: "get",
  20812. optional,
  20813. typeAnnotation: {
  20814. type: "TSTypeAnnotation",
  20815. typeAnnotation
  20816. },
  20817. _ownerScope: scope
  20818. };
  20819. }
  20820. function resolveInterfaceMembers(ctx, node, scope, typeParameters) {
  20821. const base = typeElementsToMap(
  20822. ctx,
  20823. node.body.body,
  20824. node._ownerScope,
  20825. typeParameters
  20826. );
  20827. if (node.extends) {
  20828. for (const ext of node.extends) {
  20829. try {
  20830. const { props, calls } = resolveTypeElements(ctx, ext, scope);
  20831. for (const key in props) {
  20832. if (!shared.hasOwn(base.props, key)) {
  20833. base.props[key] = props[key];
  20834. }
  20835. }
  20836. if (calls) {
  20837. ;
  20838. (base.calls || (base.calls = [])).push(...calls);
  20839. }
  20840. } catch (e) {
  20841. if (!ctx.silentOnExtendsFailure) {
  20842. ctx.error(
  20843. `Failed to resolve extends base type.
  20844. If this previously worked in 3.2, you can instruct the compiler to ignore this extend by adding /* @vue-ignore */ before it, for example:
  20845. interface Props extends /* @vue-ignore */ Base {}
  20846. Note: both in 3.2 or with the ignore, the properties in the base type are treated as fallthrough attrs at runtime.`,
  20847. ext,
  20848. scope
  20849. );
  20850. }
  20851. }
  20852. }
  20853. }
  20854. return base;
  20855. }
  20856. function resolveMappedType(ctx, node, scope, typeParameters) {
  20857. const res = { props: {} };
  20858. let keys;
  20859. if (node.nameType) {
  20860. const { name, constraint } = node.typeParameter;
  20861. scope = createChildScope(scope);
  20862. Object.assign(scope.types, { ...typeParameters, [name]: constraint });
  20863. keys = resolveStringType(ctx, node.nameType, scope);
  20864. } else {
  20865. keys = resolveStringType(ctx, node.typeParameter.constraint, scope);
  20866. }
  20867. for (const key of keys) {
  20868. res.props[key] = createProperty(
  20869. {
  20870. type: "Identifier",
  20871. name: key
  20872. },
  20873. node.typeAnnotation,
  20874. scope,
  20875. !!node.optional
  20876. );
  20877. }
  20878. return res;
  20879. }
  20880. function resolveIndexType(ctx, node, scope) {
  20881. var _a, _b;
  20882. if (node.indexType.type === "TSNumberKeyword") {
  20883. return resolveArrayElementType(ctx, node.objectType, scope);
  20884. }
  20885. const { indexType, objectType } = node;
  20886. const types = [];
  20887. let keys;
  20888. let resolved;
  20889. if (indexType.type === "TSStringKeyword") {
  20890. resolved = resolveTypeElements(ctx, objectType, scope);
  20891. keys = Object.keys(resolved.props);
  20892. } else {
  20893. keys = resolveStringType(ctx, indexType, scope);
  20894. resolved = resolveTypeElements(ctx, objectType, scope);
  20895. }
  20896. for (const key of keys) {
  20897. const targetType = (_b = (_a = resolved.props[key]) == null ? void 0 : _a.typeAnnotation) == null ? void 0 : _b.typeAnnotation;
  20898. if (targetType) {
  20899. targetType._ownerScope = resolved.props[key]._ownerScope;
  20900. types.push(targetType);
  20901. }
  20902. }
  20903. return types;
  20904. }
  20905. function resolveArrayElementType(ctx, node, scope) {
  20906. if (node.type === "TSArrayType") {
  20907. return [node.elementType];
  20908. }
  20909. if (node.type === "TSTupleType") {
  20910. return node.elementTypes.map(
  20911. (t) => t.type === "TSNamedTupleMember" ? t.elementType : t
  20912. );
  20913. }
  20914. if (node.type === "TSTypeReference") {
  20915. if (getReferenceName(node) === "Array" && node.typeParameters) {
  20916. return node.typeParameters.params;
  20917. } else {
  20918. const resolved = resolveTypeReference(ctx, node, scope);
  20919. if (resolved) {
  20920. return resolveArrayElementType(ctx, resolved, scope);
  20921. }
  20922. }
  20923. }
  20924. return ctx.error(
  20925. "Failed to resolve element type from target type",
  20926. node,
  20927. scope
  20928. );
  20929. }
  20930. function resolveStringType(ctx, node, scope, typeParameters) {
  20931. switch (node.type) {
  20932. case "StringLiteral":
  20933. return [node.value];
  20934. case "TSLiteralType":
  20935. return resolveStringType(ctx, node.literal, scope, typeParameters);
  20936. case "TSUnionType":
  20937. return node.types.map((t) => resolveStringType(ctx, t, scope, typeParameters)).flat();
  20938. case "TemplateLiteral": {
  20939. return resolveTemplateKeys(ctx, node, scope);
  20940. }
  20941. case "TSTypeReference": {
  20942. const resolved = resolveTypeReference(ctx, node, scope);
  20943. if (resolved) {
  20944. return resolveStringType(ctx, resolved, scope, typeParameters);
  20945. }
  20946. if (node.typeName.type === "Identifier") {
  20947. const name = node.typeName.name;
  20948. if (typeParameters && typeParameters[name]) {
  20949. return resolveStringType(
  20950. ctx,
  20951. typeParameters[name],
  20952. scope,
  20953. typeParameters
  20954. );
  20955. }
  20956. const getParam = (index = 0) => resolveStringType(
  20957. ctx,
  20958. node.typeParameters.params[index],
  20959. scope,
  20960. typeParameters
  20961. );
  20962. switch (name) {
  20963. case "Extract":
  20964. return getParam(1);
  20965. case "Exclude": {
  20966. const excluded = getParam(1);
  20967. return getParam().filter((s) => !excluded.includes(s));
  20968. }
  20969. case "Uppercase":
  20970. return getParam().map((s) => s.toUpperCase());
  20971. case "Lowercase":
  20972. return getParam().map((s) => s.toLowerCase());
  20973. case "Capitalize":
  20974. return getParam().map(shared.capitalize);
  20975. case "Uncapitalize":
  20976. return getParam().map((s) => s[0].toLowerCase() + s.slice(1));
  20977. default:
  20978. ctx.error(
  20979. "Unsupported type when resolving index type",
  20980. node.typeName,
  20981. scope
  20982. );
  20983. }
  20984. }
  20985. }
  20986. }
  20987. return ctx.error("Failed to resolve index type into finite keys", node, scope);
  20988. }
  20989. function resolveTemplateKeys(ctx, node, scope) {
  20990. if (!node.expressions.length) {
  20991. return [node.quasis[0].value.raw];
  20992. }
  20993. const res = [];
  20994. const e = node.expressions[0];
  20995. const q = node.quasis[0];
  20996. const leading = q ? q.value.raw : ``;
  20997. const resolved = resolveStringType(ctx, e, scope);
  20998. const restResolved = resolveTemplateKeys(
  20999. ctx,
  21000. {
  21001. ...node,
  21002. expressions: node.expressions.slice(1),
  21003. quasis: q ? node.quasis.slice(1) : node.quasis
  21004. },
  21005. scope
  21006. );
  21007. for (const r of resolved) {
  21008. for (const rr of restResolved) {
  21009. res.push(leading + r + rr);
  21010. }
  21011. }
  21012. return res;
  21013. }
  21014. const SupportedBuiltinsSet = /* @__PURE__ */ new Set([
  21015. "Partial",
  21016. "Required",
  21017. "Readonly",
  21018. "Pick",
  21019. "Omit"
  21020. ]);
  21021. function resolveBuiltin(ctx, node, name, scope, typeParameters) {
  21022. const t = resolveTypeElements(
  21023. ctx,
  21024. node.typeParameters.params[0],
  21025. scope,
  21026. typeParameters
  21027. );
  21028. switch (name) {
  21029. case "Partial": {
  21030. const res2 = { props: {}, calls: t.calls };
  21031. Object.keys(t.props).forEach((key) => {
  21032. res2.props[key] = { ...t.props[key], optional: true };
  21033. });
  21034. return res2;
  21035. }
  21036. case "Required": {
  21037. const res2 = { props: {}, calls: t.calls };
  21038. Object.keys(t.props).forEach((key) => {
  21039. res2.props[key] = { ...t.props[key], optional: false };
  21040. });
  21041. return res2;
  21042. }
  21043. case "Readonly":
  21044. return t;
  21045. case "Pick": {
  21046. const picked = resolveStringType(
  21047. ctx,
  21048. node.typeParameters.params[1],
  21049. scope,
  21050. typeParameters
  21051. );
  21052. const res2 = { props: {}, calls: t.calls };
  21053. for (const key of picked) {
  21054. res2.props[key] = t.props[key];
  21055. }
  21056. return res2;
  21057. }
  21058. case "Omit":
  21059. const omitted = resolveStringType(
  21060. ctx,
  21061. node.typeParameters.params[1],
  21062. scope,
  21063. typeParameters
  21064. );
  21065. const res = { props: {}, calls: t.calls };
  21066. for (const key in t.props) {
  21067. if (!omitted.includes(key)) {
  21068. res.props[key] = t.props[key];
  21069. }
  21070. }
  21071. return res;
  21072. }
  21073. }
  21074. function resolveTypeReference(ctx, node, scope, name, onlyExported = false) {
  21075. const canCache = !(scope == null ? void 0 : scope.isGenericScope);
  21076. if (canCache && node._resolvedReference) {
  21077. return node._resolvedReference;
  21078. }
  21079. const resolved = innerResolveTypeReference(
  21080. ctx,
  21081. scope || ctxToScope(ctx),
  21082. name || getReferenceName(node),
  21083. node,
  21084. onlyExported
  21085. );
  21086. return canCache ? node._resolvedReference = resolved : resolved;
  21087. }
  21088. function innerResolveTypeReference(ctx, scope, name, node, onlyExported) {
  21089. if (typeof name === "string") {
  21090. if (scope.imports[name]) {
  21091. return resolveTypeFromImport(ctx, node, name, scope);
  21092. } else {
  21093. const lookupSource = node.type === "TSTypeQuery" ? onlyExported ? scope.exportedDeclares : scope.declares : onlyExported ? scope.exportedTypes : scope.types;
  21094. if (lookupSource[name]) {
  21095. return lookupSource[name];
  21096. } else {
  21097. const globalScopes = resolveGlobalScope(ctx);
  21098. if (globalScopes) {
  21099. for (const s of globalScopes) {
  21100. const src = node.type === "TSTypeQuery" ? s.declares : s.types;
  21101. if (src[name]) {
  21102. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(s.filename);
  21103. return src[name];
  21104. }
  21105. }
  21106. }
  21107. }
  21108. }
  21109. } else {
  21110. let ns = innerResolveTypeReference(ctx, scope, name[0], node, onlyExported);
  21111. if (ns) {
  21112. if (ns.type !== "TSModuleDeclaration") {
  21113. ns = ns._ns;
  21114. }
  21115. if (ns) {
  21116. const childScope = moduleDeclToScope(ctx, ns, ns._ownerScope || scope);
  21117. return innerResolveTypeReference(
  21118. ctx,
  21119. childScope,
  21120. name.length > 2 ? name.slice(1) : name[name.length - 1],
  21121. node,
  21122. !ns.declare
  21123. );
  21124. }
  21125. }
  21126. }
  21127. }
  21128. function getReferenceName(node) {
  21129. const ref = node.type === "TSTypeReference" ? node.typeName : node.type === "TSExpressionWithTypeArguments" ? node.expression : node.type === "TSImportType" ? node.qualifier : node.exprName;
  21130. if ((ref == null ? void 0 : ref.type) === "Identifier") {
  21131. return ref.name;
  21132. } else if ((ref == null ? void 0 : ref.type) === "TSQualifiedName") {
  21133. return qualifiedNameToPath(ref);
  21134. } else {
  21135. return "default";
  21136. }
  21137. }
  21138. function qualifiedNameToPath(node) {
  21139. if (node.type === "Identifier") {
  21140. return [node.name];
  21141. } else {
  21142. return [...qualifiedNameToPath(node.left), node.right.name];
  21143. }
  21144. }
  21145. function resolveGlobalScope(ctx) {
  21146. if (ctx.options.globalTypeFiles) {
  21147. const fs = resolveFS(ctx);
  21148. if (!fs) {
  21149. throw new Error("[vue/compiler-sfc] globalTypeFiles requires fs access.");
  21150. }
  21151. return ctx.options.globalTypeFiles.map(
  21152. (file) => fileToScope(ctx, normalizePath(file), true)
  21153. );
  21154. }
  21155. }
  21156. let ts;
  21157. let loadTS;
  21158. function registerTS(_loadTS) {
  21159. loadTS = () => {
  21160. try {
  21161. return _loadTS();
  21162. } catch (err) {
  21163. if (typeof err.message === "string" && err.message.includes("Cannot find module")) {
  21164. throw new Error(
  21165. 'Failed to load TypeScript, which is required for resolving imported types. Please make sure "TypeScript" is installed as a project dependency.'
  21166. );
  21167. } else {
  21168. throw new Error(
  21169. "Failed to load TypeScript for resolving imported types."
  21170. );
  21171. }
  21172. }
  21173. };
  21174. }
  21175. function resolveFS(ctx) {
  21176. if (ctx.fs) {
  21177. return ctx.fs;
  21178. }
  21179. if (!ts && loadTS) {
  21180. ts = loadTS();
  21181. }
  21182. const fs = ctx.options.fs || (ts == null ? void 0 : ts.sys);
  21183. if (!fs) {
  21184. return;
  21185. }
  21186. return ctx.fs = {
  21187. fileExists(file) {
  21188. if (file.endsWith(".vue.ts") && !file.endsWith(".d.vue.ts")) {
  21189. file = file.replace(/\.ts$/, "");
  21190. }
  21191. return fs.fileExists(file);
  21192. },
  21193. readFile(file) {
  21194. if (file.endsWith(".vue.ts") && !file.endsWith(".d.vue.ts")) {
  21195. file = file.replace(/\.ts$/, "");
  21196. }
  21197. return fs.readFile(file);
  21198. },
  21199. realpath: fs.realpath
  21200. };
  21201. }
  21202. function resolveTypeFromImport(ctx, node, name, scope) {
  21203. const { source, imported } = scope.imports[name];
  21204. const sourceScope = importSourceToScope(ctx, node, scope, source);
  21205. return resolveTypeReference(ctx, node, sourceScope, imported, true);
  21206. }
  21207. function importSourceToScope(ctx, node, scope, source) {
  21208. let fs;
  21209. try {
  21210. fs = resolveFS(ctx);
  21211. } catch (err) {
  21212. return ctx.error(err.message, node, scope);
  21213. }
  21214. if (!fs) {
  21215. return ctx.error(
  21216. `No fs option provided to \`compileScript\` in non-Node environment. File system access is required for resolving imported types.`,
  21217. node,
  21218. scope
  21219. );
  21220. }
  21221. let resolved = scope.resolvedImportSources[source];
  21222. if (!resolved) {
  21223. if (source.startsWith("..")) {
  21224. const osSpecificJoinFn = process__namespace.platform === "win32" ? path$1.join : joinPaths;
  21225. const filename = osSpecificJoinFn(path$1.dirname(scope.filename), source);
  21226. resolved = resolveExt(filename, fs);
  21227. } else if (source[0] === ".") {
  21228. const filename = joinPaths(path$1.dirname(scope.filename), source);
  21229. resolved = resolveExt(filename, fs);
  21230. } else {
  21231. if (!ts) {
  21232. if (loadTS) ts = loadTS();
  21233. if (!ts) {
  21234. return ctx.error(
  21235. `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.`,
  21236. node,
  21237. scope
  21238. );
  21239. }
  21240. }
  21241. resolved = resolveWithTS(scope.filename, source, ts, fs);
  21242. }
  21243. if (resolved) {
  21244. resolved = scope.resolvedImportSources[source] = normalizePath(resolved);
  21245. }
  21246. }
  21247. if (resolved) {
  21248. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(resolved);
  21249. return fileToScope(ctx, resolved);
  21250. } else {
  21251. return ctx.error(
  21252. `Failed to resolve import source ${JSON.stringify(source)}.`,
  21253. node,
  21254. scope
  21255. );
  21256. }
  21257. }
  21258. function resolveExt(filename, fs) {
  21259. let moduleType = "u";
  21260. if (filename.endsWith(".mjs")) {
  21261. moduleType = "m";
  21262. } else if (filename.endsWith(".cjs")) {
  21263. moduleType = "c";
  21264. }
  21265. filename = filename.replace(/\.[cm]?jsx?$/, "");
  21266. const tryResolve = (filename2) => {
  21267. if (fs.fileExists(filename2)) return filename2;
  21268. };
  21269. const resolveTs = () => tryResolve(filename + `.ts`) || tryResolve(filename + `.tsx`) || tryResolve(filename + `.d.ts`);
  21270. const resolveMts = () => tryResolve(filename + `.mts`) || tryResolve(filename + `.d.mts`);
  21271. const resolveCts = () => tryResolve(filename + `.cts`) || tryResolve(filename + `.d.cts`);
  21272. return tryResolve(filename) || // For explicit .mjs/.cjs imports, prefer .mts/.cts declarations first.
  21273. (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`));
  21274. }
  21275. const tsConfigCache = createCache();
  21276. const tsConfigRefMap = /* @__PURE__ */ new Map();
  21277. function resolveWithTS(containingFile, source, ts2, fs) {
  21278. var _a, _b;
  21279. const configPath = ts2.findConfigFile(containingFile, fs.fileExists);
  21280. let tsCompilerOptions;
  21281. let tsResolveCache;
  21282. if (configPath) {
  21283. let configs;
  21284. const normalizedConfigPath = normalizePath(configPath);
  21285. const cached = tsConfigCache.get(normalizedConfigPath);
  21286. if (!cached) {
  21287. configs = loadTSConfig(configPath, ts2, fs).map((config) => ({ config }));
  21288. tsConfigCache.set(normalizedConfigPath, configs);
  21289. } else {
  21290. configs = cached;
  21291. }
  21292. let matchedConfig;
  21293. if (configs.length === 1) {
  21294. matchedConfig = configs[0];
  21295. } else {
  21296. const [major, minor] = ts2.versionMajorMinor.split(".").map(Number);
  21297. const getPattern = (base, p) => {
  21298. const supportsConfigDir = major > 5 || major === 5 && minor >= 5;
  21299. return p.startsWith("${configDir}") && supportsConfigDir ? normalizePath(p.replace("${configDir}", path$1.dirname(configPath))) : joinPaths(base, p);
  21300. };
  21301. for (const c of configs) {
  21302. const base = normalizePath(
  21303. c.config.options.pathsBasePath || path$1.dirname(c.config.options.configFilePath)
  21304. );
  21305. const included = (_a = c.config.raw) == null ? void 0 : _a.include;
  21306. const excluded = (_b = c.config.raw) == null ? void 0 : _b.exclude;
  21307. if (!included && (!base || containingFile.startsWith(base)) || (included == null ? void 0 : included.some((p) => minimatch(containingFile, getPattern(base, p))))) {
  21308. if (excluded && excluded.some((p) => minimatch(containingFile, getPattern(base, p)))) {
  21309. continue;
  21310. }
  21311. matchedConfig = c;
  21312. break;
  21313. }
  21314. }
  21315. if (!matchedConfig) {
  21316. matchedConfig = configs[configs.length - 1];
  21317. }
  21318. }
  21319. tsCompilerOptions = matchedConfig.config.options;
  21320. tsResolveCache = matchedConfig.cache || (matchedConfig.cache = ts2.createModuleResolutionCache(
  21321. process__namespace.cwd(),
  21322. createGetCanonicalFileName(ts2.sys.useCaseSensitiveFileNames),
  21323. tsCompilerOptions
  21324. ));
  21325. } else {
  21326. tsCompilerOptions = {};
  21327. }
  21328. const res = ts2.resolveModuleName(
  21329. source,
  21330. containingFile,
  21331. tsCompilerOptions,
  21332. fs,
  21333. tsResolveCache
  21334. );
  21335. if (res.resolvedModule) {
  21336. let filename = res.resolvedModule.resolvedFileName;
  21337. if (filename.endsWith(".vue.ts") && !filename.endsWith(".d.vue.ts")) {
  21338. filename = filename.replace(/\.ts$/, "");
  21339. }
  21340. return fs.realpath ? fs.realpath(filename) : filename;
  21341. }
  21342. }
  21343. function loadTSConfig(configPath, ts2, fs, visited = /* @__PURE__ */ new Set()) {
  21344. const parseConfigHost = ts2.sys;
  21345. const config = ts2.parseJsonConfigFileContent(
  21346. ts2.readConfigFile(configPath, fs.readFile).config,
  21347. parseConfigHost,
  21348. path$1.dirname(configPath),
  21349. void 0,
  21350. configPath
  21351. );
  21352. const res = [config];
  21353. visited.add(configPath);
  21354. if (config.projectReferences) {
  21355. for (const ref of config.projectReferences) {
  21356. const refPath = ts2.resolveProjectReferencePath(ref);
  21357. if (visited.has(refPath) || !fs.fileExists(refPath)) {
  21358. continue;
  21359. }
  21360. tsConfigRefMap.set(refPath, configPath);
  21361. res.unshift(...loadTSConfig(refPath, ts2, fs, visited));
  21362. }
  21363. }
  21364. return res;
  21365. }
  21366. const fileToScopeCache = createCache();
  21367. function invalidateTypeCache(filename) {
  21368. filename = normalizePath(filename);
  21369. fileToScopeCache.delete(filename);
  21370. tsConfigCache.delete(filename);
  21371. const affectedConfig = tsConfigRefMap.get(filename);
  21372. if (affectedConfig) tsConfigCache.delete(affectedConfig);
  21373. }
  21374. function fileToScope(ctx, filename, asGlobal = false) {
  21375. const cached = fileToScopeCache.get(filename);
  21376. if (cached) {
  21377. return cached;
  21378. }
  21379. const fs = resolveFS(ctx);
  21380. const source = fs.readFile(filename) || "";
  21381. const body = parseFile(filename, source, fs, ctx.options.babelParserPlugins);
  21382. const scope = new TypeScope(filename, source, 0, recordImports(body));
  21383. recordTypes(ctx, body, scope, asGlobal);
  21384. fileToScopeCache.set(filename, scope);
  21385. return scope;
  21386. }
  21387. function parseFile(filename, content, fs, parserPlugins) {
  21388. const ext = path$1.extname(filename);
  21389. if (ext === ".ts" || ext === ".mts" || ext === ".tsx" || ext === ".cts" || ext === ".mtsx") {
  21390. return parser$2.parse(content, {
  21391. plugins: resolveParserPlugins(
  21392. ext.slice(1),
  21393. parserPlugins,
  21394. /\.d\.[cm]?ts$/.test(filename)
  21395. ),
  21396. sourceType: "module"
  21397. }).program.body;
  21398. }
  21399. const isUnknownTypeSource = !/\.[cm]?[tj]sx?$/.test(filename);
  21400. const arbitraryTypeSource = `${filename.slice(0, -ext.length)}.d${ext}.ts`;
  21401. const hasArbitraryTypeDeclaration = isUnknownTypeSource && fs.fileExists(arbitraryTypeSource);
  21402. if (hasArbitraryTypeDeclaration) {
  21403. return parser$2.parse(fs.readFile(arbitraryTypeSource), {
  21404. plugins: resolveParserPlugins("ts", parserPlugins, true),
  21405. sourceType: "module"
  21406. }).program.body;
  21407. }
  21408. if (ext === ".vue") {
  21409. const {
  21410. descriptor: { script, scriptSetup }
  21411. } = parse$1(content);
  21412. if (!script && !scriptSetup) {
  21413. return [];
  21414. }
  21415. const scriptOffset = script ? script.loc.start.offset : Infinity;
  21416. const scriptSetupOffset = scriptSetup ? scriptSetup.loc.start.offset : Infinity;
  21417. const firstBlock = scriptOffset < scriptSetupOffset ? script : scriptSetup;
  21418. const secondBlock = scriptOffset < scriptSetupOffset ? scriptSetup : script;
  21419. let scriptContent = " ".repeat(Math.min(scriptOffset, scriptSetupOffset)) + firstBlock.content;
  21420. if (secondBlock) {
  21421. scriptContent += " ".repeat(secondBlock.loc.start.offset - script.loc.end.offset) + secondBlock.content;
  21422. }
  21423. const lang = (script == null ? void 0 : script.lang) || (scriptSetup == null ? void 0 : scriptSetup.lang);
  21424. return parser$2.parse(scriptContent, {
  21425. plugins: resolveParserPlugins(lang, parserPlugins),
  21426. sourceType: "module"
  21427. }).program.body;
  21428. }
  21429. return [];
  21430. }
  21431. function ctxToScope(ctx) {
  21432. if (ctx.scope) {
  21433. return ctx.scope;
  21434. }
  21435. const body = "ast" in ctx ? ctx.ast : ctx.scriptAst ? [...ctx.scriptAst.body, ...ctx.scriptSetupAst.body] : ctx.scriptSetupAst.body;
  21436. const scope = new TypeScope(
  21437. ctx.filename,
  21438. ctx.source,
  21439. "startOffset" in ctx ? ctx.startOffset : 0,
  21440. "userImports" in ctx ? Object.create(ctx.userImports) : recordImports(body)
  21441. );
  21442. recordTypes(ctx, body, scope);
  21443. return ctx.scope = scope;
  21444. }
  21445. function moduleDeclToScope(ctx, node, parentScope) {
  21446. if (node._resolvedChildScope) {
  21447. return node._resolvedChildScope;
  21448. }
  21449. const scope = createChildScope(parentScope);
  21450. if (node.body.type === "TSModuleDeclaration") {
  21451. const decl = node.body;
  21452. decl._ownerScope = scope;
  21453. const id = getId(decl.id);
  21454. scope.types[id] = scope.exportedTypes[id] = decl;
  21455. } else {
  21456. recordTypes(ctx, node.body.body, scope);
  21457. }
  21458. return node._resolvedChildScope = scope;
  21459. }
  21460. function createChildScope(parentScope) {
  21461. return new TypeScope(
  21462. parentScope.filename,
  21463. parentScope.source,
  21464. parentScope.offset,
  21465. Object.create(parentScope.imports),
  21466. Object.create(parentScope.types),
  21467. Object.create(parentScope.declares)
  21468. );
  21469. }
  21470. const importExportRE = /^Import|^Export/;
  21471. function recordTypes(ctx, body, scope, asGlobal = false) {
  21472. const { types, declares, exportedTypes, exportedDeclares, imports } = scope;
  21473. const isAmbient = asGlobal ? !body.some((s) => importExportRE.test(s.type)) : false;
  21474. for (const stmt of body) {
  21475. if (asGlobal) {
  21476. if (isAmbient) {
  21477. if (stmt.declare) {
  21478. recordType(stmt, types, declares);
  21479. }
  21480. } else if (stmt.type === "TSModuleDeclaration" && stmt.global) {
  21481. for (const s of stmt.body.body) {
  21482. if (s.type === "ExportNamedDeclaration" && s.declaration) {
  21483. recordType(s.declaration, types, declares);
  21484. } else {
  21485. recordType(s, types, declares);
  21486. }
  21487. }
  21488. }
  21489. } else {
  21490. recordType(stmt, types, declares);
  21491. }
  21492. }
  21493. if (!asGlobal) {
  21494. for (const stmt of body) {
  21495. if (stmt.type === "ExportNamedDeclaration") {
  21496. if (stmt.declaration) {
  21497. recordType(stmt.declaration, types, declares);
  21498. recordType(stmt.declaration, exportedTypes, exportedDeclares);
  21499. } else {
  21500. for (const spec of stmt.specifiers) {
  21501. if (spec.type === "ExportSpecifier") {
  21502. const local = spec.local.name;
  21503. const exported = getId(spec.exported);
  21504. if (stmt.source) {
  21505. imports[exported] = {
  21506. source: stmt.source.value,
  21507. imported: local
  21508. };
  21509. exportedTypes[exported] = {
  21510. type: "TSTypeReference",
  21511. typeName: {
  21512. type: "Identifier",
  21513. name: local
  21514. },
  21515. _ownerScope: scope
  21516. };
  21517. } else if (types[local]) {
  21518. exportedTypes[exported] = types[local];
  21519. }
  21520. }
  21521. }
  21522. }
  21523. } else if (stmt.type === "ExportAllDeclaration") {
  21524. const sourceScope = importSourceToScope(
  21525. ctx,
  21526. stmt.source,
  21527. scope,
  21528. stmt.source.value
  21529. );
  21530. Object.assign(scope.exportedTypes, sourceScope.exportedTypes);
  21531. } else if (stmt.type === "ExportDefaultDeclaration" && stmt.declaration) {
  21532. if (stmt.declaration.type !== "Identifier") {
  21533. recordType(stmt.declaration, types, declares, "default");
  21534. recordType(
  21535. stmt.declaration,
  21536. exportedTypes,
  21537. exportedDeclares,
  21538. "default"
  21539. );
  21540. } else if (types[stmt.declaration.name]) {
  21541. exportedTypes["default"] = types[stmt.declaration.name];
  21542. }
  21543. }
  21544. }
  21545. }
  21546. for (const key of Object.keys(types)) {
  21547. const node = types[key];
  21548. node._ownerScope = scope;
  21549. if (node._ns) node._ns._ownerScope = scope;
  21550. }
  21551. for (const key of Object.keys(declares)) {
  21552. declares[key]._ownerScope = scope;
  21553. }
  21554. }
  21555. function recordType(node, types, declares, overwriteId) {
  21556. switch (node.type) {
  21557. case "TSInterfaceDeclaration":
  21558. case "TSEnumDeclaration":
  21559. case "TSModuleDeclaration": {
  21560. if (node.type === "TSModuleDeclaration" && node.global) {
  21561. const body = node.body;
  21562. for (const s of body.body) {
  21563. if (s.type === "ExportNamedDeclaration" && s.declaration) {
  21564. recordType(s.declaration, types, declares);
  21565. } else {
  21566. recordType(s, types, declares);
  21567. }
  21568. }
  21569. break;
  21570. }
  21571. const id = overwriteId || getId(node.id);
  21572. let existing = types[id];
  21573. if (existing) {
  21574. if (node.type === "TSModuleDeclaration") {
  21575. if (existing.type === "TSModuleDeclaration") {
  21576. mergeNamespaces(existing, node);
  21577. } else {
  21578. attachNamespace(existing, node);
  21579. }
  21580. break;
  21581. }
  21582. if (existing.type === "TSModuleDeclaration") {
  21583. types[id] = node;
  21584. attachNamespace(node, existing);
  21585. break;
  21586. }
  21587. if (existing.type !== node.type) {
  21588. break;
  21589. }
  21590. if (node.type === "TSInterfaceDeclaration") {
  21591. existing.body.body.push(...node.body.body);
  21592. } else {
  21593. existing.members.push(...node.members);
  21594. }
  21595. } else {
  21596. types[id] = node;
  21597. }
  21598. break;
  21599. }
  21600. case "ClassDeclaration":
  21601. if (overwriteId || node.id) types[overwriteId || getId(node.id)] = node;
  21602. break;
  21603. case "TSTypeAliasDeclaration":
  21604. types[node.id.name] = node.typeParameters ? node : node.typeAnnotation;
  21605. break;
  21606. case "TSDeclareFunction":
  21607. if (node.id) declares[node.id.name] = node;
  21608. break;
  21609. case "VariableDeclaration": {
  21610. if (node.declare) {
  21611. for (const decl of node.declarations) {
  21612. if (decl.id.type === "Identifier" && decl.id.typeAnnotation) {
  21613. declares[decl.id.name] = decl.id.typeAnnotation.typeAnnotation;
  21614. }
  21615. }
  21616. }
  21617. break;
  21618. }
  21619. }
  21620. }
  21621. function mergeNamespaces(to, from) {
  21622. const toBody = to.body;
  21623. const fromBody = from.body;
  21624. if (toBody.type === "TSModuleDeclaration") {
  21625. if (fromBody.type === "TSModuleDeclaration") {
  21626. mergeNamespaces(toBody, fromBody);
  21627. } else {
  21628. fromBody.body.push({
  21629. type: "ExportNamedDeclaration",
  21630. declaration: toBody,
  21631. exportKind: "type",
  21632. specifiers: []
  21633. });
  21634. }
  21635. } else if (fromBody.type === "TSModuleDeclaration") {
  21636. toBody.body.push({
  21637. type: "ExportNamedDeclaration",
  21638. declaration: fromBody,
  21639. exportKind: "type",
  21640. specifiers: []
  21641. });
  21642. } else {
  21643. toBody.body.push(...fromBody.body);
  21644. }
  21645. }
  21646. function attachNamespace(to, ns) {
  21647. if (!to._ns) {
  21648. to._ns = ns;
  21649. } else {
  21650. mergeNamespaces(to._ns, ns);
  21651. }
  21652. }
  21653. function recordImports(body) {
  21654. const imports = /* @__PURE__ */ Object.create(null);
  21655. for (const s of body) {
  21656. recordImport(s, imports);
  21657. }
  21658. return imports;
  21659. }
  21660. function recordImport(node, imports) {
  21661. if (node.type !== "ImportDeclaration") {
  21662. return;
  21663. }
  21664. for (const s of node.specifiers) {
  21665. imports[s.local.name] = {
  21666. imported: getImportedName(s),
  21667. source: node.source.value
  21668. };
  21669. }
  21670. }
  21671. function inferRuntimeType(ctx, node, scope = node._ownerScope || ctxToScope(ctx), isKeyOf = false, typeParameters) {
  21672. if (node.leadingComments && node.leadingComments.some((c) => c.value.includes("@vue-ignore"))) {
  21673. return [UNKNOWN_TYPE];
  21674. }
  21675. const prevSilent = ctx.silentOnExtendsFailure;
  21676. ctx.silentOnExtendsFailure = true;
  21677. try {
  21678. switch (node.type) {
  21679. case "TSStringKeyword":
  21680. return ["String"];
  21681. case "TSNumberKeyword":
  21682. return ["Number"];
  21683. case "TSBooleanKeyword":
  21684. return ["Boolean"];
  21685. case "TSObjectKeyword":
  21686. return ["Object"];
  21687. case "TSNullKeyword":
  21688. return ["null"];
  21689. case "TSTypeLiteral":
  21690. case "TSInterfaceDeclaration": {
  21691. const types = /* @__PURE__ */ new Set();
  21692. const members = node.type === "TSTypeLiteral" ? node.members : node.body.body;
  21693. for (const m of members) {
  21694. if (isKeyOf) {
  21695. if (m.type === "TSPropertySignature" && m.key.type === "NumericLiteral") {
  21696. types.add("Number");
  21697. } else if (m.type === "TSIndexSignature") {
  21698. const annotation = m.parameters[0].typeAnnotation;
  21699. if (annotation && annotation.type !== "Noop") {
  21700. const type = inferRuntimeType(
  21701. ctx,
  21702. annotation.typeAnnotation,
  21703. scope
  21704. )[0];
  21705. if (type === UNKNOWN_TYPE) return [UNKNOWN_TYPE];
  21706. types.add(type);
  21707. }
  21708. } else {
  21709. types.add("String");
  21710. }
  21711. } else if (m.type === "TSCallSignatureDeclaration" || m.type === "TSConstructSignatureDeclaration") {
  21712. types.add("Function");
  21713. } else {
  21714. types.add("Object");
  21715. }
  21716. }
  21717. return types.size ? Array.from(types) : [isKeyOf ? UNKNOWN_TYPE : "Object"];
  21718. }
  21719. case "TSPropertySignature":
  21720. if (node.typeAnnotation) {
  21721. return inferRuntimeType(
  21722. ctx,
  21723. node.typeAnnotation.typeAnnotation,
  21724. scope
  21725. );
  21726. }
  21727. break;
  21728. case "TSMethodSignature":
  21729. case "TSFunctionType":
  21730. return ["Function"];
  21731. case "TSArrayType":
  21732. case "TSTupleType":
  21733. return ["Array"];
  21734. case "TSLiteralType":
  21735. switch (node.literal.type) {
  21736. case "StringLiteral":
  21737. return ["String"];
  21738. case "BooleanLiteral":
  21739. return ["Boolean"];
  21740. case "NumericLiteral":
  21741. case "BigIntLiteral":
  21742. return ["Number"];
  21743. default:
  21744. return [UNKNOWN_TYPE];
  21745. }
  21746. case "TSTypeReference": {
  21747. const resolved = resolveTypeReference(ctx, node, scope);
  21748. if (resolved) {
  21749. if (resolved.type === "TSTypeAliasDeclaration") {
  21750. if (resolved.typeAnnotation.type === "TSFunctionType") {
  21751. return ["Function"];
  21752. }
  21753. if (node.typeParameters) {
  21754. const typeParams = /* @__PURE__ */ Object.create(null);
  21755. if (resolved.typeParameters) {
  21756. resolved.typeParameters.params.forEach((p, i) => {
  21757. typeParams[p.name] = node.typeParameters.params[i];
  21758. });
  21759. }
  21760. return inferRuntimeType(
  21761. ctx,
  21762. resolved.typeAnnotation,
  21763. resolved._ownerScope,
  21764. isKeyOf,
  21765. typeParams
  21766. );
  21767. }
  21768. }
  21769. return inferRuntimeType(ctx, resolved, resolved._ownerScope, isKeyOf);
  21770. }
  21771. if (node.typeName.type === "Identifier") {
  21772. if (typeParameters && typeParameters[node.typeName.name]) {
  21773. return inferRuntimeType(
  21774. ctx,
  21775. typeParameters[node.typeName.name],
  21776. scope,
  21777. isKeyOf,
  21778. typeParameters
  21779. );
  21780. }
  21781. if (isKeyOf) {
  21782. switch (node.typeName.name) {
  21783. case "String":
  21784. case "Array":
  21785. case "ArrayLike":
  21786. case "Parameters":
  21787. case "ConstructorParameters":
  21788. case "ReadonlyArray":
  21789. return ["String", "Number"];
  21790. // TS built-in utility types
  21791. case "Record":
  21792. case "Partial":
  21793. case "Required":
  21794. case "Readonly":
  21795. if (node.typeParameters && node.typeParameters.params[0]) {
  21796. return inferRuntimeType(
  21797. ctx,
  21798. node.typeParameters.params[0],
  21799. scope,
  21800. true
  21801. );
  21802. }
  21803. break;
  21804. case "Pick":
  21805. case "Extract":
  21806. if (node.typeParameters && node.typeParameters.params[1]) {
  21807. return inferRuntimeType(
  21808. ctx,
  21809. node.typeParameters.params[1],
  21810. scope
  21811. );
  21812. }
  21813. break;
  21814. case "Function":
  21815. case "Object":
  21816. case "Set":
  21817. case "Map":
  21818. case "WeakSet":
  21819. case "WeakMap":
  21820. case "Date":
  21821. case "Promise":
  21822. case "Error":
  21823. case "Uppercase":
  21824. case "Lowercase":
  21825. case "Capitalize":
  21826. case "Uncapitalize":
  21827. case "ReadonlyMap":
  21828. case "ReadonlySet":
  21829. return ["String"];
  21830. }
  21831. } else {
  21832. switch (node.typeName.name) {
  21833. case "Array":
  21834. case "Function":
  21835. case "Object":
  21836. case "Set":
  21837. case "Map":
  21838. case "WeakSet":
  21839. case "WeakMap":
  21840. case "Date":
  21841. case "Promise":
  21842. case "Error":
  21843. return [node.typeName.name];
  21844. // TS built-in utility types
  21845. // https://www.typescriptlang.org/docs/handbook/utility-types.html
  21846. case "Partial":
  21847. case "Required":
  21848. case "Readonly":
  21849. case "Record":
  21850. case "Pick":
  21851. case "Omit":
  21852. case "InstanceType":
  21853. return ["Object"];
  21854. case "Uppercase":
  21855. case "Lowercase":
  21856. case "Capitalize":
  21857. case "Uncapitalize":
  21858. return ["String"];
  21859. case "Parameters":
  21860. case "ConstructorParameters":
  21861. case "ReadonlyArray":
  21862. return ["Array"];
  21863. case "ReadonlyMap":
  21864. return ["Map"];
  21865. case "ReadonlySet":
  21866. return ["Set"];
  21867. case "NonNullable":
  21868. if (node.typeParameters && node.typeParameters.params[0]) {
  21869. return inferRuntimeType(
  21870. ctx,
  21871. node.typeParameters.params[0],
  21872. scope
  21873. ).filter((t) => t !== "null");
  21874. }
  21875. break;
  21876. case "Extract":
  21877. if (node.typeParameters && node.typeParameters.params[1]) {
  21878. return inferRuntimeType(
  21879. ctx,
  21880. node.typeParameters.params[1],
  21881. scope
  21882. );
  21883. }
  21884. break;
  21885. case "Exclude":
  21886. case "OmitThisParameter":
  21887. if (node.typeParameters && node.typeParameters.params[0]) {
  21888. return inferRuntimeType(
  21889. ctx,
  21890. node.typeParameters.params[0],
  21891. scope
  21892. );
  21893. }
  21894. break;
  21895. }
  21896. }
  21897. }
  21898. break;
  21899. }
  21900. case "TSParenthesizedType":
  21901. return inferRuntimeType(ctx, node.typeAnnotation, scope);
  21902. case "TSUnionType":
  21903. return flattenTypes(ctx, node.types, scope, isKeyOf, typeParameters);
  21904. case "TSIntersectionType": {
  21905. return flattenTypes(
  21906. ctx,
  21907. node.types,
  21908. scope,
  21909. isKeyOf,
  21910. typeParameters
  21911. ).filter((t) => t !== UNKNOWN_TYPE);
  21912. }
  21913. case "TSMappedType": {
  21914. const { typeAnnotation, typeParameter } = node;
  21915. if (typeAnnotation && typeAnnotation.type === "TSIndexedAccessType" && typeParameter && typeParameter.constraint && typeParameters) {
  21916. const constraint = typeParameter.constraint;
  21917. if (constraint.type === "TSTypeOperator" && constraint.operator === "keyof" && constraint.typeAnnotation && constraint.typeAnnotation.type === "TSTypeReference" && constraint.typeAnnotation.typeName.type === "Identifier") {
  21918. const typeName = constraint.typeAnnotation.typeName.name;
  21919. const index = typeAnnotation.indexType;
  21920. const obj = typeAnnotation.objectType;
  21921. 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) {
  21922. const targetType = typeParameters[typeName];
  21923. if (targetType) {
  21924. return inferRuntimeType(ctx, targetType, scope);
  21925. }
  21926. }
  21927. }
  21928. }
  21929. return [UNKNOWN_TYPE];
  21930. }
  21931. case "TSEnumDeclaration":
  21932. return inferEnumType(node);
  21933. case "TSSymbolKeyword":
  21934. return ["Symbol"];
  21935. case "TSIndexedAccessType": {
  21936. const types = resolveIndexType(ctx, node, scope);
  21937. return flattenTypes(ctx, types, scope, isKeyOf);
  21938. }
  21939. case "ClassDeclaration":
  21940. return ["Object"];
  21941. case "TSImportType": {
  21942. const sourceScope = importSourceToScope(
  21943. ctx,
  21944. node.argument,
  21945. scope,
  21946. node.argument.value
  21947. );
  21948. const resolved = resolveTypeReference(ctx, node, sourceScope);
  21949. if (resolved) {
  21950. return inferRuntimeType(ctx, resolved, resolved._ownerScope);
  21951. }
  21952. break;
  21953. }
  21954. case "TSTypeQuery": {
  21955. const id = node.exprName;
  21956. if (id.type === "Identifier") {
  21957. const matched = scope.declares[id.name];
  21958. if (matched) {
  21959. return inferRuntimeType(ctx, matched, matched._ownerScope, isKeyOf);
  21960. }
  21961. }
  21962. break;
  21963. }
  21964. // e.g. readonly
  21965. case "TSTypeOperator": {
  21966. return inferRuntimeType(
  21967. ctx,
  21968. node.typeAnnotation,
  21969. scope,
  21970. node.operator === "keyof"
  21971. );
  21972. }
  21973. case "TSAnyKeyword": {
  21974. if (isKeyOf) {
  21975. return ["String", "Number", "Symbol"];
  21976. }
  21977. break;
  21978. }
  21979. }
  21980. } catch (e) {
  21981. } finally {
  21982. ctx.silentOnExtendsFailure = prevSilent;
  21983. }
  21984. return [UNKNOWN_TYPE];
  21985. }
  21986. function flattenTypes(ctx, types, scope, isKeyOf = false, typeParameters = void 0) {
  21987. if (types.length === 1) {
  21988. return inferRuntimeType(
  21989. ctx,
  21990. types[0],
  21991. types[0]._ownerScope || scope,
  21992. isKeyOf,
  21993. typeParameters
  21994. );
  21995. }
  21996. return [
  21997. ...new Set(
  21998. [].concat(
  21999. ...types.map(
  22000. (t) => inferRuntimeType(
  22001. ctx,
  22002. t,
  22003. t._ownerScope || scope,
  22004. isKeyOf,
  22005. typeParameters
  22006. )
  22007. )
  22008. )
  22009. )
  22010. ];
  22011. }
  22012. function inferEnumType(node) {
  22013. const types = /* @__PURE__ */ new Set();
  22014. for (const m of node.members) {
  22015. if (m.initializer) {
  22016. switch (m.initializer.type) {
  22017. case "StringLiteral":
  22018. types.add("String");
  22019. break;
  22020. case "NumericLiteral":
  22021. types.add("Number");
  22022. break;
  22023. }
  22024. }
  22025. }
  22026. return types.size ? [...types] : ["Number"];
  22027. }
  22028. function resolveExtractPropTypes({ props }, scope) {
  22029. const res = { props: {} };
  22030. for (const key in props) {
  22031. const raw = props[key];
  22032. res.props[key] = reverseInferType(
  22033. raw.key,
  22034. raw.typeAnnotation.typeAnnotation,
  22035. scope
  22036. );
  22037. }
  22038. return res;
  22039. }
  22040. function reverseInferType(key, node, scope, optional = true, checkObjectSyntax = true) {
  22041. if (checkObjectSyntax && node.type === "TSTypeLiteral") {
  22042. const typeType = findStaticPropertyType(node, "type");
  22043. if (typeType) {
  22044. const requiredType = findStaticPropertyType(node, "required");
  22045. const optional2 = requiredType && requiredType.type === "TSLiteralType" && requiredType.literal.type === "BooleanLiteral" ? !requiredType.literal.value : true;
  22046. return reverseInferType(key, typeType, scope, optional2, false);
  22047. }
  22048. } else if (node.type === "TSTypeReference" && node.typeName.type === "Identifier") {
  22049. if (node.typeName.name.endsWith("Constructor")) {
  22050. return createProperty(
  22051. key,
  22052. ctorToType(node.typeName.name),
  22053. scope,
  22054. optional
  22055. );
  22056. } else if (node.typeName.name === "PropType" && node.typeParameters) {
  22057. return createProperty(key, node.typeParameters.params[0], scope, optional);
  22058. }
  22059. }
  22060. if ((node.type === "TSTypeReference" || node.type === "TSImportType") && node.typeParameters) {
  22061. for (const t of node.typeParameters.params) {
  22062. const inferred = reverseInferType(key, t, scope, optional);
  22063. if (inferred) return inferred;
  22064. }
  22065. }
  22066. return createProperty(key, { type: `TSNullKeyword` }, scope, optional);
  22067. }
  22068. function ctorToType(ctorType) {
  22069. const ctor = ctorType.slice(0, -11);
  22070. switch (ctor) {
  22071. case "String":
  22072. case "Number":
  22073. case "Boolean":
  22074. return { type: `TS${ctor}Keyword` };
  22075. case "Array":
  22076. case "Function":
  22077. case "Object":
  22078. case "Set":
  22079. case "Map":
  22080. case "WeakSet":
  22081. case "WeakMap":
  22082. case "Date":
  22083. case "Promise":
  22084. return {
  22085. type: "TSTypeReference",
  22086. typeName: { type: "Identifier", name: ctor }
  22087. };
  22088. }
  22089. return { type: `TSNullKeyword` };
  22090. }
  22091. function findStaticPropertyType(node, key) {
  22092. const prop = node.members.find(
  22093. (m) => m.type === "TSPropertySignature" && getStringLiteralKey(m) === key && m.typeAnnotation
  22094. );
  22095. return prop && prop.typeAnnotation.typeAnnotation;
  22096. }
  22097. function resolveReturnType(ctx, arg, scope) {
  22098. var _a;
  22099. let resolved = arg;
  22100. if (arg.type === "TSTypeReference" || arg.type === "TSTypeQuery" || arg.type === "TSImportType") {
  22101. resolved = resolveTypeReference(ctx, arg, scope);
  22102. }
  22103. if (!resolved) return;
  22104. if (resolved.type === "TSFunctionType") {
  22105. return (_a = resolved.typeAnnotation) == null ? void 0 : _a.typeAnnotation;
  22106. }
  22107. if (resolved.type === "TSDeclareFunction") {
  22108. return resolved.returnType;
  22109. }
  22110. }
  22111. function resolveUnionType(ctx, node, scope) {
  22112. if (node.type === "TSTypeReference") {
  22113. const resolved = resolveTypeReference(ctx, node, scope);
  22114. if (resolved) node = resolved;
  22115. }
  22116. let types;
  22117. if (node.type === "TSUnionType") {
  22118. types = node.types.flatMap((node2) => resolveUnionType(ctx, node2, scope));
  22119. } else {
  22120. types = [node];
  22121. }
  22122. return types;
  22123. }
  22124. const DEFINE_MODEL = "defineModel";
  22125. function processDefineModel(ctx, node, declId) {
  22126. if (!isCallOf(node, DEFINE_MODEL)) {
  22127. return false;
  22128. }
  22129. ctx.hasDefineModelCall = true;
  22130. const type = node.typeParameters && node.typeParameters.params[0] || void 0;
  22131. let modelName;
  22132. let options;
  22133. const arg0 = node.arguments[0] && CompilerDOM.unwrapTSNode(node.arguments[0]);
  22134. const hasName = arg0 && (arg0.type === "StringLiteral" || arg0.type === "TemplateLiteral" && arg0.expressions.length === 0);
  22135. if (hasName) {
  22136. modelName = arg0.type === "StringLiteral" ? arg0.value : arg0.quasis[0].value.cooked;
  22137. options = node.arguments[1];
  22138. } else {
  22139. modelName = "modelValue";
  22140. options = arg0;
  22141. }
  22142. if (ctx.modelDecls[modelName]) {
  22143. ctx.error(`duplicate model name ${JSON.stringify(modelName)}`, node);
  22144. }
  22145. let optionsString = options && ctx.getString(options);
  22146. let optionsRemoved = !options;
  22147. const runtimeOptionNodes = [];
  22148. if (options && options.type === "ObjectExpression" && !options.properties.some((p) => p.type === "SpreadElement" || p.computed)) {
  22149. let removed = 0;
  22150. for (let i = options.properties.length - 1; i >= 0; i--) {
  22151. const p = options.properties[i];
  22152. const next = options.properties[i + 1];
  22153. const start = p.start;
  22154. const end = next ? next.start : options.end - 1;
  22155. 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"))) {
  22156. optionsString = optionsString.slice(0, start - options.start) + optionsString.slice(end - options.start);
  22157. } else {
  22158. removed++;
  22159. ctx.s.remove(ctx.startOffset + start, ctx.startOffset + end);
  22160. runtimeOptionNodes.push(p);
  22161. }
  22162. }
  22163. if (removed === options.properties.length) {
  22164. optionsRemoved = true;
  22165. ctx.s.remove(
  22166. ctx.startOffset + (hasName ? arg0.end : options.start),
  22167. ctx.startOffset + options.end
  22168. );
  22169. }
  22170. }
  22171. ctx.modelDecls[modelName] = {
  22172. type,
  22173. options: optionsString,
  22174. runtimeOptionNodes,
  22175. identifier: declId && declId.type === "Identifier" ? declId.name : void 0
  22176. };
  22177. ctx.bindingMetadata[modelName] = "props";
  22178. ctx.s.overwrite(
  22179. ctx.startOffset + node.callee.start,
  22180. ctx.startOffset + node.callee.end,
  22181. ctx.helper("useModel")
  22182. );
  22183. ctx.s.appendLeft(
  22184. ctx.startOffset + (node.arguments.length ? node.arguments[0].start : node.end - 1),
  22185. `__props, ` + (hasName ? `` : `${JSON.stringify(modelName)}${optionsRemoved ? `` : `, `}`)
  22186. );
  22187. return true;
  22188. }
  22189. function genModelProps(ctx) {
  22190. if (!ctx.hasDefineModelCall) return;
  22191. const isProd = !!ctx.options.isProd;
  22192. let modelPropsDecl = "";
  22193. for (const [name, { type, options: runtimeOptions }] of Object.entries(
  22194. ctx.modelDecls
  22195. )) {
  22196. let skipCheck = false;
  22197. let codegenOptions = ``;
  22198. let runtimeTypes = type && inferRuntimeType(ctx, type);
  22199. if (runtimeTypes) {
  22200. const hasBoolean = runtimeTypes.includes("Boolean");
  22201. const hasFunction = runtimeTypes.includes("Function");
  22202. const hasUnknownType = runtimeTypes.includes(UNKNOWN_TYPE);
  22203. if (hasUnknownType) {
  22204. if (hasBoolean || hasFunction) {
  22205. runtimeTypes = runtimeTypes.filter((t) => t !== UNKNOWN_TYPE);
  22206. skipCheck = true;
  22207. } else {
  22208. runtimeTypes = ["null"];
  22209. }
  22210. }
  22211. if (!isProd) {
  22212. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}` + (skipCheck ? ", skipCheck: true" : "");
  22213. } else if (hasBoolean || runtimeOptions && hasFunction) {
  22214. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}`;
  22215. } else ;
  22216. }
  22217. let decl;
  22218. if (codegenOptions && runtimeOptions) {
  22219. decl = ctx.isTS ? `{ ${codegenOptions}, ...${runtimeOptions} }` : `Object.assign({ ${codegenOptions} }, ${runtimeOptions})`;
  22220. } else if (codegenOptions) {
  22221. decl = `{ ${codegenOptions} }`;
  22222. } else if (runtimeOptions) {
  22223. decl = runtimeOptions;
  22224. } else {
  22225. decl = `{}`;
  22226. }
  22227. modelPropsDecl += `
  22228. ${JSON.stringify(name)}: ${decl},`;
  22229. const modifierPropName = JSON.stringify(
  22230. name === "modelValue" ? `modelModifiers` : `${name}Modifiers`
  22231. );
  22232. modelPropsDecl += `
  22233. ${modifierPropName}: {},`;
  22234. }
  22235. return `{${modelPropsDecl}
  22236. }`;
  22237. }
  22238. const DEFINE_PROPS = "defineProps";
  22239. const WITH_DEFAULTS = "withDefaults";
  22240. function processDefineProps(ctx, node, declId, isWithDefaults = false) {
  22241. if (!isCallOf(node, DEFINE_PROPS)) {
  22242. return processWithDefaults(ctx, node, declId);
  22243. }
  22244. if (ctx.hasDefinePropsCall) {
  22245. ctx.error(`duplicate ${DEFINE_PROPS}() call`, node);
  22246. }
  22247. ctx.hasDefinePropsCall = true;
  22248. ctx.propsRuntimeDecl = node.arguments[0];
  22249. if (ctx.propsRuntimeDecl) {
  22250. for (const key of getObjectOrArrayExpressionKeys(ctx.propsRuntimeDecl)) {
  22251. if (!(key in ctx.bindingMetadata)) {
  22252. ctx.bindingMetadata[key] = "props";
  22253. }
  22254. }
  22255. }
  22256. if (node.typeParameters) {
  22257. if (ctx.propsRuntimeDecl) {
  22258. ctx.error(
  22259. `${DEFINE_PROPS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  22260. node
  22261. );
  22262. }
  22263. ctx.propsTypeDecl = node.typeParameters.params[0];
  22264. }
  22265. if (!isWithDefaults && declId && declId.type === "ObjectPattern") {
  22266. processPropsDestructure(ctx, declId);
  22267. }
  22268. ctx.propsCall = node;
  22269. ctx.propsDecl = declId;
  22270. return true;
  22271. }
  22272. function processWithDefaults(ctx, node, declId) {
  22273. if (!isCallOf(node, WITH_DEFAULTS)) {
  22274. return false;
  22275. }
  22276. if (!processDefineProps(
  22277. ctx,
  22278. node.arguments[0],
  22279. declId,
  22280. true
  22281. )) {
  22282. ctx.error(
  22283. `${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`,
  22284. node.arguments[0] || node
  22285. );
  22286. }
  22287. if (ctx.propsRuntimeDecl) {
  22288. ctx.error(
  22289. `${WITH_DEFAULTS} can only be used with type-based ${DEFINE_PROPS} declaration.`,
  22290. node
  22291. );
  22292. }
  22293. if (declId && declId.type === "ObjectPattern") {
  22294. ctx.warn(
  22295. `${WITH_DEFAULTS}() is unnecessary when using destructure with ${DEFINE_PROPS}().
  22296. Reactive destructure will be disabled when using withDefaults().
  22297. Prefer using destructure default values, e.g. const { foo = 1 } = defineProps(...). `,
  22298. node.callee
  22299. );
  22300. }
  22301. ctx.propsRuntimeDefaults = node.arguments[1];
  22302. if (!ctx.propsRuntimeDefaults) {
  22303. ctx.error(`The 2nd argument of ${WITH_DEFAULTS} is required.`, node);
  22304. }
  22305. ctx.propsCall = node;
  22306. return true;
  22307. }
  22308. function genRuntimeProps(ctx) {
  22309. let propsDecls;
  22310. if (ctx.propsRuntimeDecl) {
  22311. propsDecls = ctx.getString(ctx.propsRuntimeDecl).trim();
  22312. if (ctx.propsDestructureDecl) {
  22313. const defaults = [];
  22314. for (const key in ctx.propsDestructuredBindings) {
  22315. const d = genDestructuredDefaultValue(ctx, key);
  22316. const finalKey = getEscapedPropName(key);
  22317. if (d)
  22318. defaults.push(
  22319. `${finalKey}: ${d.valueString}${d.needSkipFactory ? `, __skip_${finalKey}: true` : ``}`
  22320. );
  22321. }
  22322. if (defaults.length) {
  22323. propsDecls = `/*@__PURE__*/${ctx.helper(
  22324. `mergeDefaults`
  22325. )}(${propsDecls}, {
  22326. ${defaults.join(",\n ")}
  22327. })`;
  22328. }
  22329. }
  22330. } else if (ctx.propsTypeDecl) {
  22331. propsDecls = extractRuntimeProps(ctx);
  22332. }
  22333. const modelsDecls = genModelProps(ctx);
  22334. if (propsDecls && modelsDecls) {
  22335. return `/*@__PURE__*/${ctx.helper(
  22336. "mergeModels"
  22337. )}(${propsDecls}, ${modelsDecls})`;
  22338. } else {
  22339. return modelsDecls || propsDecls;
  22340. }
  22341. }
  22342. function extractRuntimeProps(ctx) {
  22343. const props = resolveRuntimePropsFromType(ctx, ctx.propsTypeDecl);
  22344. if (!props.length) {
  22345. return;
  22346. }
  22347. const propStrings = [];
  22348. const hasStaticDefaults = hasStaticWithDefaults(ctx);
  22349. for (const prop of props) {
  22350. propStrings.push(genRuntimePropFromType(ctx, prop, hasStaticDefaults));
  22351. if ("bindingMetadata" in ctx && !(prop.key in ctx.bindingMetadata)) {
  22352. ctx.bindingMetadata[prop.key] = "props";
  22353. }
  22354. }
  22355. let propsDecls = `{
  22356. ${propStrings.join(",\n ")}
  22357. }`;
  22358. if (ctx.propsRuntimeDefaults && !hasStaticDefaults) {
  22359. propsDecls = `/*@__PURE__*/${ctx.helper(
  22360. "mergeDefaults"
  22361. )}(${propsDecls}, ${ctx.getString(ctx.propsRuntimeDefaults)})`;
  22362. }
  22363. return propsDecls;
  22364. }
  22365. function resolveRuntimePropsFromType(ctx, node) {
  22366. const props = [];
  22367. const elements = resolveTypeElements(ctx, node);
  22368. for (const key in elements.props) {
  22369. const e = elements.props[key];
  22370. let type = inferRuntimeType(ctx, e);
  22371. let skipCheck = false;
  22372. if (type.includes(UNKNOWN_TYPE)) {
  22373. if (type.includes("Boolean") || type.includes("Function")) {
  22374. type = type.filter((t) => t !== UNKNOWN_TYPE);
  22375. skipCheck = true;
  22376. } else {
  22377. type = ["null"];
  22378. }
  22379. }
  22380. props.push({
  22381. key,
  22382. required: !e.optional,
  22383. type: type || [`null`],
  22384. skipCheck
  22385. });
  22386. }
  22387. return props;
  22388. }
  22389. function genRuntimePropFromType(ctx, { key, required, type, skipCheck }, hasStaticDefaults) {
  22390. let defaultString;
  22391. const destructured = genDestructuredDefaultValue(ctx, key, type);
  22392. if (destructured) {
  22393. defaultString = `default: ${destructured.valueString}${destructured.needSkipFactory ? `, skipFactory: true` : ``}`;
  22394. } else if (hasStaticDefaults) {
  22395. const prop = ctx.propsRuntimeDefaults.properties.find(
  22396. (node) => {
  22397. if (node.type === "SpreadElement") return false;
  22398. return resolveObjectKey(node.key, node.computed) === key;
  22399. }
  22400. );
  22401. if (prop) {
  22402. if (prop.type === "ObjectProperty") {
  22403. defaultString = `default: ${ctx.getString(prop.value)}`;
  22404. } else {
  22405. let paramsString = "";
  22406. if (prop.params.length) {
  22407. const start = prop.params[0].start;
  22408. const end = prop.params[prop.params.length - 1].end;
  22409. paramsString = ctx.getString({ start, end });
  22410. }
  22411. defaultString = `${prop.async ? "async " : ""}${prop.kind !== "method" ? `${prop.kind} ` : ""}default(${paramsString}) ${ctx.getString(prop.body)}`;
  22412. }
  22413. }
  22414. }
  22415. const finalKey = getEscapedPropName(key);
  22416. if (!ctx.options.isProd) {
  22417. return `${finalKey}: { ${concatStrings([
  22418. `type: ${toRuntimeTypeString(type)}`,
  22419. `required: ${required}`,
  22420. skipCheck && "skipCheck: true",
  22421. defaultString
  22422. ])} }`;
  22423. } else if (type.some(
  22424. (el) => el === "Boolean" || (!hasStaticDefaults || defaultString) && el === "Function"
  22425. )) {
  22426. return `${finalKey}: { ${concatStrings([
  22427. `type: ${toRuntimeTypeString(type)}`,
  22428. defaultString
  22429. ])} }`;
  22430. } else {
  22431. if (ctx.isCE) {
  22432. if (defaultString) {
  22433. return `${finalKey}: ${`{ ${defaultString}, type: ${toRuntimeTypeString(
  22434. type
  22435. )} }`}`;
  22436. } else {
  22437. return `${finalKey}: {type: ${toRuntimeTypeString(type)}}`;
  22438. }
  22439. }
  22440. return `${finalKey}: ${defaultString ? `{ ${defaultString} }` : `{}`}`;
  22441. }
  22442. }
  22443. function hasStaticWithDefaults(ctx) {
  22444. return !!(ctx.propsRuntimeDefaults && ctx.propsRuntimeDefaults.type === "ObjectExpression" && ctx.propsRuntimeDefaults.properties.every(
  22445. (node) => node.type !== "SpreadElement" && (!node.computed || node.key.type.endsWith("Literal"))
  22446. ));
  22447. }
  22448. function genDestructuredDefaultValue(ctx, key, inferredType) {
  22449. const destructured = ctx.propsDestructuredBindings[key];
  22450. const defaultVal = destructured && destructured.default;
  22451. if (defaultVal) {
  22452. const value = ctx.getString(defaultVal);
  22453. const unwrapped = CompilerDOM.unwrapTSNode(defaultVal);
  22454. if (inferredType && inferredType.length && !inferredType.includes("null")) {
  22455. const valueType = inferValueType(unwrapped);
  22456. if (valueType && !inferredType.includes(valueType)) {
  22457. ctx.error(
  22458. `Default value of prop "${key}" does not match declared type.`,
  22459. unwrapped
  22460. );
  22461. }
  22462. }
  22463. const needSkipFactory = !inferredType && (CompilerDOM.isFunctionType(unwrapped) || unwrapped.type === "Identifier");
  22464. const needFactoryWrap = !needSkipFactory && !isLiteralNode(unwrapped) && !(inferredType == null ? void 0 : inferredType.includes("Function"));
  22465. return {
  22466. valueString: needFactoryWrap ? `() => (${value})` : value,
  22467. needSkipFactory
  22468. };
  22469. }
  22470. }
  22471. function inferValueType(node) {
  22472. switch (node.type) {
  22473. case "StringLiteral":
  22474. return "String";
  22475. case "NumericLiteral":
  22476. return "Number";
  22477. case "BooleanLiteral":
  22478. return "Boolean";
  22479. case "ObjectExpression":
  22480. return "Object";
  22481. case "ArrayExpression":
  22482. return "Array";
  22483. case "FunctionExpression":
  22484. case "ArrowFunctionExpression":
  22485. return "Function";
  22486. }
  22487. }
  22488. function processPropsDestructure(ctx, declId) {
  22489. if (ctx.options.propsDestructure === "error") {
  22490. ctx.error(`Props destructure is explicitly prohibited via config.`, declId);
  22491. } else if (ctx.options.propsDestructure === false) {
  22492. return;
  22493. }
  22494. ctx.propsDestructureDecl = declId;
  22495. const registerBinding = (key, local, defaultValue) => {
  22496. ctx.propsDestructuredBindings[key] = { local, default: defaultValue };
  22497. if (local !== key) {
  22498. ctx.bindingMetadata[local] = "props-aliased";
  22499. (ctx.bindingMetadata.__propsAliases || (ctx.bindingMetadata.__propsAliases = {}))[local] = key;
  22500. }
  22501. };
  22502. for (const prop of declId.properties) {
  22503. if (prop.type === "ObjectProperty") {
  22504. const propKey = resolveObjectKey(prop.key, prop.computed);
  22505. if (!propKey) {
  22506. ctx.error(
  22507. `${DEFINE_PROPS}() destructure cannot use computed key.`,
  22508. prop.key
  22509. );
  22510. }
  22511. if (prop.value.type === "AssignmentPattern") {
  22512. const { left, right } = prop.value;
  22513. if (left.type !== "Identifier") {
  22514. ctx.error(
  22515. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  22516. left
  22517. );
  22518. }
  22519. registerBinding(propKey, left.name, right);
  22520. } else if (prop.value.type === "Identifier") {
  22521. registerBinding(propKey, prop.value.name);
  22522. } else {
  22523. ctx.error(
  22524. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  22525. prop.value
  22526. );
  22527. }
  22528. } else {
  22529. ctx.propsDestructureRestId = prop.argument.name;
  22530. ctx.bindingMetadata[ctx.propsDestructureRestId] = "setup-reactive-const";
  22531. }
  22532. }
  22533. }
  22534. function transformDestructuredProps(ctx, vueImportAliases) {
  22535. if (ctx.options.propsDestructure === false) {
  22536. return;
  22537. }
  22538. const rootScope = /* @__PURE__ */ Object.create(null);
  22539. const scopeStack = [rootScope];
  22540. let currentScope = rootScope;
  22541. const excludedIds = /* @__PURE__ */ new WeakSet();
  22542. const parentStack = [];
  22543. const propsLocalToPublicMap = /* @__PURE__ */ Object.create(null);
  22544. for (const key in ctx.propsDestructuredBindings) {
  22545. const { local } = ctx.propsDestructuredBindings[key];
  22546. rootScope[local] = true;
  22547. propsLocalToPublicMap[local] = key;
  22548. }
  22549. function pushScope() {
  22550. scopeStack.push(currentScope = Object.create(currentScope));
  22551. }
  22552. function popScope() {
  22553. scopeStack.pop();
  22554. currentScope = scopeStack[scopeStack.length - 1] || null;
  22555. }
  22556. function registerLocalBinding(id) {
  22557. excludedIds.add(id);
  22558. if (currentScope) {
  22559. currentScope[id.name] = false;
  22560. } else {
  22561. ctx.error(
  22562. "registerBinding called without active scope, something is wrong.",
  22563. id
  22564. );
  22565. }
  22566. }
  22567. function walkScope(node, isRoot = false) {
  22568. for (const stmt of node.body) {
  22569. if (stmt.type === "VariableDeclaration") {
  22570. walkVariableDeclaration(stmt, isRoot);
  22571. } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
  22572. if (stmt.declare || !stmt.id) continue;
  22573. registerLocalBinding(stmt.id);
  22574. } else if (stmt.type === "ExportNamedDeclaration" && stmt.declaration && stmt.declaration.type === "VariableDeclaration") {
  22575. walkVariableDeclaration(stmt.declaration, isRoot);
  22576. } else if (stmt.type === "LabeledStatement" && stmt.body.type === "VariableDeclaration") {
  22577. walkVariableDeclaration(stmt.body, isRoot);
  22578. }
  22579. }
  22580. }
  22581. function walkVariableDeclaration(stmt, isRoot = false) {
  22582. if (stmt.declare) {
  22583. return;
  22584. }
  22585. for (const decl of stmt.declarations) {
  22586. const isDefineProps = isRoot && decl.init && isCallOf(CompilerDOM.unwrapTSNode(decl.init), "defineProps");
  22587. for (const id of CompilerDOM.extractIdentifiers(decl.id)) {
  22588. if (isDefineProps) {
  22589. excludedIds.add(id);
  22590. } else {
  22591. registerLocalBinding(id);
  22592. }
  22593. }
  22594. }
  22595. }
  22596. function rewriteId(id, parent, parentStack2) {
  22597. if (parent.type === "AssignmentExpression" && id === parent.left || parent.type === "UpdateExpression") {
  22598. ctx.error(`Cannot assign to destructured props as they are readonly.`, id);
  22599. }
  22600. if (CompilerDOM.isStaticProperty(parent) && parent.shorthand) {
  22601. if (!parent.inPattern || CompilerDOM.isInDestructureAssignment(parent, parentStack2)) {
  22602. ctx.s.appendLeft(
  22603. id.end + ctx.startOffset,
  22604. `: ${shared.genPropsAccessExp(propsLocalToPublicMap[id.name])}`
  22605. );
  22606. }
  22607. } else {
  22608. ctx.s.overwrite(
  22609. id.start + ctx.startOffset,
  22610. id.end + ctx.startOffset,
  22611. shared.genPropsAccessExp(propsLocalToPublicMap[id.name])
  22612. );
  22613. }
  22614. }
  22615. function checkUsage(node, method, alias = method) {
  22616. if (isCallOf(node, alias)) {
  22617. const arg = CompilerDOM.unwrapTSNode(node.arguments[0]);
  22618. if (arg.type === "Identifier" && currentScope[arg.name]) {
  22619. ctx.error(
  22620. `"${arg.name}" is a destructured prop and should not be passed directly to ${method}(). Pass a getter () => ${arg.name} instead.`,
  22621. arg
  22622. );
  22623. }
  22624. }
  22625. }
  22626. const ast = ctx.scriptSetupAst;
  22627. walkScope(ast, true);
  22628. estreeWalker.walk(ast, {
  22629. enter(node, parent) {
  22630. parent && parentStack.push(parent);
  22631. if (parent && parent.type.startsWith("TS") && !CompilerDOM.TS_NODE_TYPES.includes(parent.type)) {
  22632. return this.skip();
  22633. }
  22634. checkUsage(node, "watch", vueImportAliases.watch);
  22635. checkUsage(node, "toRef", vueImportAliases.toRef);
  22636. if (CompilerDOM.isFunctionType(node)) {
  22637. pushScope();
  22638. CompilerDOM.walkFunctionParams(node, registerLocalBinding);
  22639. if (node.body.type === "BlockStatement") {
  22640. walkScope(node.body);
  22641. }
  22642. return;
  22643. }
  22644. if (node.type === "CatchClause") {
  22645. pushScope();
  22646. if (node.param && node.param.type === "Identifier") {
  22647. registerLocalBinding(node.param);
  22648. }
  22649. walkScope(node.body);
  22650. return;
  22651. }
  22652. if (node.type === "ForOfStatement" || node.type === "ForInStatement" || node.type === "ForStatement") {
  22653. pushScope();
  22654. const varDecl = node.type === "ForStatement" ? node.init : node.left;
  22655. if (varDecl && varDecl.type === "VariableDeclaration") {
  22656. walkVariableDeclaration(varDecl);
  22657. }
  22658. if (node.body.type === "BlockStatement") {
  22659. walkScope(node.body);
  22660. }
  22661. return;
  22662. }
  22663. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent)) {
  22664. pushScope();
  22665. walkScope(node);
  22666. return;
  22667. }
  22668. if (node.type === "Identifier") {
  22669. if (CompilerDOM.isReferencedIdentifier(node, parent, parentStack) && !excludedIds.has(node)) {
  22670. if (currentScope[node.name]) {
  22671. rewriteId(node, parent, parentStack);
  22672. }
  22673. }
  22674. }
  22675. },
  22676. leave(node, parent) {
  22677. parent && parentStack.pop();
  22678. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent) || CompilerDOM.isFunctionType(node) || node.type === "CatchClause" || node.type === "ForOfStatement" || node.type === "ForInStatement" || node.type === "ForStatement") {
  22679. popScope();
  22680. }
  22681. }
  22682. });
  22683. }
  22684. const DEFINE_EMITS = "defineEmits";
  22685. function processDefineEmits(ctx, node, declId) {
  22686. if (!isCallOf(node, DEFINE_EMITS)) {
  22687. return false;
  22688. }
  22689. if (ctx.hasDefineEmitCall) {
  22690. ctx.error(`duplicate ${DEFINE_EMITS}() call`, node);
  22691. }
  22692. ctx.hasDefineEmitCall = true;
  22693. ctx.emitsRuntimeDecl = node.arguments[0];
  22694. if (node.typeParameters) {
  22695. if (ctx.emitsRuntimeDecl) {
  22696. ctx.error(
  22697. `${DEFINE_EMITS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  22698. node
  22699. );
  22700. }
  22701. ctx.emitsTypeDecl = node.typeParameters.params[0];
  22702. }
  22703. ctx.emitDecl = declId;
  22704. return true;
  22705. }
  22706. function genRuntimeEmits(ctx) {
  22707. let emitsDecl = "";
  22708. if (ctx.emitsRuntimeDecl) {
  22709. emitsDecl = ctx.getString(ctx.emitsRuntimeDecl).trim();
  22710. } else if (ctx.emitsTypeDecl) {
  22711. const typeDeclaredEmits = extractRuntimeEmits(ctx);
  22712. emitsDecl = typeDeclaredEmits.size ? `[${Array.from(typeDeclaredEmits).map((k) => JSON.stringify(k)).join(", ")}]` : ``;
  22713. }
  22714. if (ctx.hasDefineModelCall) {
  22715. let modelEmitsDecl = `[${Object.keys(ctx.modelDecls).map((n) => JSON.stringify(`update:${n}`)).join(", ")}]`;
  22716. emitsDecl = emitsDecl ? `/*@__PURE__*/${ctx.helper(
  22717. "mergeModels"
  22718. )}(${emitsDecl}, ${modelEmitsDecl})` : modelEmitsDecl;
  22719. }
  22720. return emitsDecl;
  22721. }
  22722. function extractRuntimeEmits(ctx) {
  22723. const emits = /* @__PURE__ */ new Set();
  22724. const node = ctx.emitsTypeDecl;
  22725. if (node.type === "TSFunctionType") {
  22726. extractEventNames(ctx, node.parameters[0], emits);
  22727. return emits;
  22728. }
  22729. const { props, calls } = resolveTypeElements(ctx, node);
  22730. let hasProperty = false;
  22731. for (const key in props) {
  22732. emits.add(key);
  22733. hasProperty = true;
  22734. }
  22735. if (calls) {
  22736. if (hasProperty) {
  22737. ctx.error(
  22738. `defineEmits() type cannot mixed call signature and property syntax.`,
  22739. node
  22740. );
  22741. }
  22742. for (const call of calls) {
  22743. extractEventNames(ctx, call.parameters[0], emits);
  22744. }
  22745. }
  22746. return emits;
  22747. }
  22748. function extractEventNames(ctx, eventName, emits) {
  22749. if (eventName.type === "Identifier" && eventName.typeAnnotation && eventName.typeAnnotation.type === "TSTypeAnnotation") {
  22750. const types = resolveUnionType(ctx, eventName.typeAnnotation.typeAnnotation);
  22751. for (const type of types) {
  22752. if (type.type === "TSLiteralType") {
  22753. if (type.literal.type !== "UnaryExpression" && type.literal.type !== "TemplateLiteral") {
  22754. emits.add(String(type.literal.value));
  22755. }
  22756. }
  22757. }
  22758. }
  22759. }
  22760. const DEFINE_EXPOSE = "defineExpose";
  22761. function processDefineExpose(ctx, node) {
  22762. if (isCallOf(node, DEFINE_EXPOSE)) {
  22763. if (ctx.hasDefineExposeCall) {
  22764. ctx.error(`duplicate ${DEFINE_EXPOSE}() call`, node);
  22765. }
  22766. ctx.hasDefineExposeCall = true;
  22767. return true;
  22768. }
  22769. return false;
  22770. }
  22771. const DEFINE_SLOTS = "defineSlots";
  22772. function processDefineSlots(ctx, node, declId) {
  22773. if (!isCallOf(node, DEFINE_SLOTS)) {
  22774. return false;
  22775. }
  22776. if (ctx.hasDefineSlotsCall) {
  22777. ctx.error(`duplicate ${DEFINE_SLOTS}() call`, node);
  22778. }
  22779. ctx.hasDefineSlotsCall = true;
  22780. if (node.arguments.length > 0) {
  22781. ctx.error(`${DEFINE_SLOTS}() cannot accept arguments`, node);
  22782. }
  22783. if (declId) {
  22784. ctx.s.overwrite(
  22785. ctx.startOffset + node.start,
  22786. ctx.startOffset + node.end,
  22787. `${ctx.helper("useSlots")}()`
  22788. );
  22789. }
  22790. return true;
  22791. }
  22792. const DEFINE_OPTIONS = "defineOptions";
  22793. function processDefineOptions(ctx, node) {
  22794. if (!isCallOf(node, DEFINE_OPTIONS)) {
  22795. return false;
  22796. }
  22797. if (ctx.hasDefineOptionsCall) {
  22798. ctx.error(`duplicate ${DEFINE_OPTIONS}() call`, node);
  22799. }
  22800. if (node.typeParameters) {
  22801. ctx.error(`${DEFINE_OPTIONS}() cannot accept type arguments`, node);
  22802. }
  22803. if (!node.arguments[0]) return true;
  22804. ctx.hasDefineOptionsCall = true;
  22805. ctx.optionsRuntimeDecl = CompilerDOM.unwrapTSNode(node.arguments[0]);
  22806. let propsOption = void 0;
  22807. let emitsOption = void 0;
  22808. let exposeOption = void 0;
  22809. let slotsOption = void 0;
  22810. if (ctx.optionsRuntimeDecl.type === "ObjectExpression") {
  22811. for (const prop of ctx.optionsRuntimeDecl.properties) {
  22812. if ((prop.type === "ObjectProperty" || prop.type === "ObjectMethod") && prop.key.type === "Identifier") {
  22813. switch (prop.key.name) {
  22814. case "props":
  22815. propsOption = prop;
  22816. break;
  22817. case "emits":
  22818. emitsOption = prop;
  22819. break;
  22820. case "expose":
  22821. exposeOption = prop;
  22822. break;
  22823. case "slots":
  22824. slotsOption = prop;
  22825. break;
  22826. }
  22827. }
  22828. }
  22829. }
  22830. if (propsOption) {
  22831. ctx.error(
  22832. `${DEFINE_OPTIONS}() cannot be used to declare props. Use ${DEFINE_PROPS}() instead.`,
  22833. propsOption
  22834. );
  22835. }
  22836. if (emitsOption) {
  22837. ctx.error(
  22838. `${DEFINE_OPTIONS}() cannot be used to declare emits. Use ${DEFINE_EMITS}() instead.`,
  22839. emitsOption
  22840. );
  22841. }
  22842. if (exposeOption) {
  22843. ctx.error(
  22844. `${DEFINE_OPTIONS}() cannot be used to declare expose. Use ${DEFINE_EXPOSE}() instead.`,
  22845. exposeOption
  22846. );
  22847. }
  22848. if (slotsOption) {
  22849. ctx.error(
  22850. `${DEFINE_OPTIONS}() cannot be used to declare slots. Use ${DEFINE_SLOTS}() instead.`,
  22851. slotsOption
  22852. );
  22853. }
  22854. return true;
  22855. }
  22856. function processAwait(ctx, node, needSemi, isStatement) {
  22857. const argumentStart = node.argument.extra && node.argument.extra.parenthesized ? node.argument.extra.parenStart : node.argument.start;
  22858. const startOffset = ctx.startOffset;
  22859. const argumentStr = ctx.descriptor.source.slice(
  22860. argumentStart + startOffset,
  22861. node.argument.end + startOffset
  22862. );
  22863. const containsNestedAwait = /\bawait\b/.test(argumentStr);
  22864. ctx.s.overwrite(
  22865. node.start + startOffset,
  22866. argumentStart + startOffset,
  22867. `${needSemi ? `;` : ``}(
  22868. ([__temp,__restore] = ${ctx.helper(
  22869. `withAsyncContext`
  22870. )}(${containsNestedAwait ? `async ` : ``}() => `
  22871. );
  22872. ctx.s.appendLeft(
  22873. node.end + startOffset,
  22874. `)),
  22875. ${isStatement ? `` : `__temp = `}await __temp,
  22876. __restore()${isStatement ? `` : `,
  22877. __temp`}
  22878. )`
  22879. );
  22880. }
  22881. const MACROS = [
  22882. DEFINE_PROPS,
  22883. DEFINE_EMITS,
  22884. DEFINE_EXPOSE,
  22885. DEFINE_OPTIONS,
  22886. DEFINE_SLOTS,
  22887. DEFINE_MODEL,
  22888. WITH_DEFAULTS
  22889. ];
  22890. function compileScript(sfc, options) {
  22891. var _a, _b, _c;
  22892. if (!options.id) {
  22893. warnOnce(
  22894. `compileScript now requires passing the \`id\` option.
  22895. Upgrade your vite or vue-loader version for compatibility with the latest experimental proposals.`
  22896. );
  22897. }
  22898. const { script, scriptSetup, source, filename } = sfc;
  22899. const hoistStatic = options.hoistStatic !== false && !script;
  22900. const scopeId = options.id ? options.id.replace(/^data-v-/, "") : "";
  22901. const scriptLang = script && script.lang;
  22902. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  22903. const isJSOrTS = isJS(scriptLang, scriptSetupLang) || isTS(scriptLang, scriptSetupLang);
  22904. if (script && scriptSetup && scriptLang !== scriptSetupLang) {
  22905. throw new Error(
  22906. `[@vue/compiler-sfc] <script> and <script setup> must have the same language type.`
  22907. );
  22908. }
  22909. if (!scriptSetup) {
  22910. if (!script) {
  22911. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
  22912. }
  22913. if (script.lang && !isJSOrTS) {
  22914. return script;
  22915. }
  22916. const ctx2 = new ScriptCompileContext(sfc, options);
  22917. return processNormalScript(ctx2, scopeId);
  22918. }
  22919. if (scriptSetupLang && !isJSOrTS) {
  22920. return scriptSetup;
  22921. }
  22922. const ctx = new ScriptCompileContext(sfc, options);
  22923. const scriptBindings = /* @__PURE__ */ Object.create(null);
  22924. const setupBindings = /* @__PURE__ */ Object.create(null);
  22925. let defaultExport;
  22926. let hasAwait = false;
  22927. let hasInlinedSsrRenderFn = false;
  22928. const startOffset = ctx.startOffset;
  22929. const endOffset = ctx.endOffset;
  22930. const scriptStartOffset = script && script.loc.start.offset;
  22931. const scriptEndOffset = script && script.loc.end.offset;
  22932. function hoistNode(node) {
  22933. const start = node.start + startOffset;
  22934. let end = node.end + startOffset;
  22935. if (node.trailingComments && node.trailingComments.length > 0) {
  22936. const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
  22937. end = lastCommentNode.end + startOffset;
  22938. }
  22939. while (end <= source.length) {
  22940. if (!/\s/.test(source.charAt(end))) {
  22941. break;
  22942. }
  22943. end++;
  22944. }
  22945. ctx.s.move(start, end, 0);
  22946. }
  22947. function registerUserImport(source2, local, imported, isType, isFromSetup, needTemplateUsageCheck) {
  22948. let isUsedInTemplate = needTemplateUsageCheck;
  22949. if (needTemplateUsageCheck && ctx.isTS && sfc.template && !sfc.template.src && !sfc.template.lang) {
  22950. isUsedInTemplate = isImportUsed(local, sfc);
  22951. }
  22952. ctx.userImports[local] = {
  22953. isType,
  22954. imported,
  22955. local,
  22956. source: source2,
  22957. isFromSetup,
  22958. isUsedInTemplate
  22959. };
  22960. }
  22961. function checkInvalidScopeReference(node, method) {
  22962. if (!node) return;
  22963. CompilerDOM.walkIdentifiers(node, (id) => {
  22964. const binding = setupBindings[id.name];
  22965. if (binding && binding !== "literal-const") {
  22966. ctx.error(
  22967. `\`${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.`,
  22968. id
  22969. );
  22970. }
  22971. });
  22972. }
  22973. const scriptAst = ctx.scriptAst;
  22974. const scriptSetupAst = ctx.scriptSetupAst;
  22975. if (scriptAst) {
  22976. for (const node of scriptAst.body) {
  22977. if (node.type === "ImportDeclaration") {
  22978. for (const specifier of node.specifiers) {
  22979. const imported = getImportedName(specifier);
  22980. registerUserImport(
  22981. node.source.value,
  22982. specifier.local.name,
  22983. imported,
  22984. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  22985. false,
  22986. !options.inlineTemplate
  22987. );
  22988. }
  22989. }
  22990. }
  22991. }
  22992. for (const node of scriptSetupAst.body) {
  22993. if (node.type === "ImportDeclaration") {
  22994. hoistNode(node);
  22995. let removed = 0;
  22996. const removeSpecifier = (i) => {
  22997. const removeLeft = i > removed;
  22998. removed++;
  22999. const current = node.specifiers[i];
  23000. const next = node.specifiers[i + 1];
  23001. ctx.s.remove(
  23002. removeLeft ? node.specifiers[i - 1].end + startOffset : current.start + startOffset,
  23003. next && !removeLeft ? next.start + startOffset : current.end + startOffset
  23004. );
  23005. };
  23006. for (let i = 0; i < node.specifiers.length; i++) {
  23007. const specifier = node.specifiers[i];
  23008. const local = specifier.local.name;
  23009. const imported = getImportedName(specifier);
  23010. const source2 = node.source.value;
  23011. const existing = ctx.userImports[local];
  23012. if (source2 === "vue" && MACROS.includes(imported)) {
  23013. if (local === imported) {
  23014. warnOnce(
  23015. `\`${imported}\` is a compiler macro and no longer needs to be imported.`
  23016. );
  23017. } else {
  23018. ctx.error(
  23019. `\`${imported}\` is a compiler macro and cannot be aliased to a different name.`,
  23020. specifier
  23021. );
  23022. }
  23023. removeSpecifier(i);
  23024. } else if (existing) {
  23025. if (existing.source === source2 && existing.imported === imported) {
  23026. removeSpecifier(i);
  23027. } else {
  23028. ctx.error(
  23029. `different imports aliased to same local name.`,
  23030. specifier
  23031. );
  23032. }
  23033. } else {
  23034. registerUserImport(
  23035. source2,
  23036. local,
  23037. imported,
  23038. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  23039. true,
  23040. !options.inlineTemplate
  23041. );
  23042. }
  23043. }
  23044. if (node.specifiers.length && removed === node.specifiers.length) {
  23045. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  23046. }
  23047. }
  23048. }
  23049. const vueImportAliases = {};
  23050. for (const key in ctx.userImports) {
  23051. const { source: source2, imported, local } = ctx.userImports[key];
  23052. if (source2 === "vue") vueImportAliases[imported] = local;
  23053. }
  23054. if (script && scriptAst) {
  23055. for (const node of scriptAst.body) {
  23056. if (node.type === "ExportDefaultDeclaration") {
  23057. defaultExport = node;
  23058. let optionProperties;
  23059. if (defaultExport.declaration.type === "ObjectExpression") {
  23060. optionProperties = defaultExport.declaration.properties;
  23061. } else if (defaultExport.declaration.type === "CallExpression" && defaultExport.declaration.arguments[0] && defaultExport.declaration.arguments[0].type === "ObjectExpression") {
  23062. optionProperties = defaultExport.declaration.arguments[0].properties;
  23063. }
  23064. if (optionProperties) {
  23065. for (const p of optionProperties) {
  23066. if (p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name") {
  23067. ctx.hasDefaultExportName = true;
  23068. }
  23069. if ((p.type === "ObjectMethod" || p.type === "ObjectProperty") && p.key.type === "Identifier" && p.key.name === "render") {
  23070. ctx.hasDefaultExportRender = true;
  23071. }
  23072. }
  23073. }
  23074. const start = node.start + scriptStartOffset;
  23075. const end = node.declaration.start + scriptStartOffset;
  23076. ctx.s.overwrite(start, end, `const ${normalScriptDefaultVar} = `);
  23077. } else if (node.type === "ExportNamedDeclaration") {
  23078. const defaultSpecifier = node.specifiers.find(
  23079. (s) => s.exported.type === "Identifier" && s.exported.name === "default"
  23080. );
  23081. if (defaultSpecifier) {
  23082. defaultExport = node;
  23083. if (node.specifiers.length > 1) {
  23084. ctx.s.remove(
  23085. defaultSpecifier.start + scriptStartOffset,
  23086. defaultSpecifier.end + scriptStartOffset
  23087. );
  23088. } else {
  23089. ctx.s.remove(
  23090. node.start + scriptStartOffset,
  23091. node.end + scriptStartOffset
  23092. );
  23093. }
  23094. if (node.source) {
  23095. ctx.s.prepend(
  23096. `import { ${defaultSpecifier.local.name} as ${normalScriptDefaultVar} } from '${node.source.value}'
  23097. `
  23098. );
  23099. } else {
  23100. ctx.s.appendLeft(
  23101. scriptEndOffset,
  23102. `
  23103. const ${normalScriptDefaultVar} = ${defaultSpecifier.local.name}
  23104. `
  23105. );
  23106. }
  23107. }
  23108. if (node.declaration) {
  23109. walkDeclaration(
  23110. "script",
  23111. node.declaration,
  23112. scriptBindings,
  23113. vueImportAliases,
  23114. hoistStatic
  23115. );
  23116. }
  23117. } else if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  23118. walkDeclaration(
  23119. "script",
  23120. node,
  23121. scriptBindings,
  23122. vueImportAliases,
  23123. hoistStatic
  23124. );
  23125. }
  23126. }
  23127. if (scriptStartOffset > startOffset) {
  23128. if (!/\n$/.test(script.content.trim())) {
  23129. ctx.s.appendLeft(scriptEndOffset, `
  23130. `);
  23131. }
  23132. ctx.s.move(scriptStartOffset, scriptEndOffset, 0);
  23133. }
  23134. }
  23135. for (const node of scriptSetupAst.body) {
  23136. if (node.type === "ExpressionStatement") {
  23137. const expr = CompilerDOM.unwrapTSNode(node.expression);
  23138. if (processDefineProps(ctx, expr) || processDefineEmits(ctx, expr) || processDefineOptions(ctx, expr) || processDefineSlots(ctx, expr)) {
  23139. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  23140. } else if (processDefineExpose(ctx, expr)) {
  23141. const callee = expr.callee;
  23142. ctx.s.overwrite(
  23143. callee.start + startOffset,
  23144. callee.end + startOffset,
  23145. "__expose"
  23146. );
  23147. } else {
  23148. processDefineModel(ctx, expr);
  23149. }
  23150. }
  23151. if (node.type === "VariableDeclaration" && !node.declare) {
  23152. const total = node.declarations.length;
  23153. let left = total;
  23154. let lastNonRemoved;
  23155. for (let i = 0; i < total; i++) {
  23156. const decl = node.declarations[i];
  23157. const init = decl.init && CompilerDOM.unwrapTSNode(decl.init);
  23158. if (init) {
  23159. if (processDefineOptions(ctx, init)) {
  23160. ctx.error(
  23161. `${DEFINE_OPTIONS}() has no returning value, it cannot be assigned.`,
  23162. node
  23163. );
  23164. }
  23165. const isDefineProps = processDefineProps(ctx, init, decl.id);
  23166. if (ctx.propsDestructureRestId) {
  23167. setupBindings[ctx.propsDestructureRestId] = "setup-reactive-const";
  23168. }
  23169. const isDefineEmits = !isDefineProps && processDefineEmits(ctx, init, decl.id);
  23170. !isDefineEmits && (processDefineSlots(ctx, init, decl.id) || processDefineModel(ctx, init, decl.id));
  23171. if (isDefineProps && !ctx.propsDestructureRestId && ctx.propsDestructureDecl) {
  23172. if (left === 1) {
  23173. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  23174. } else {
  23175. let start = decl.start + startOffset;
  23176. let end = decl.end + startOffset;
  23177. if (i === total - 1) {
  23178. start = node.declarations[lastNonRemoved].end + startOffset;
  23179. } else {
  23180. end = node.declarations[i + 1].start + startOffset;
  23181. }
  23182. ctx.s.remove(start, end);
  23183. left--;
  23184. }
  23185. } else if (isDefineEmits) {
  23186. ctx.s.overwrite(
  23187. startOffset + init.start,
  23188. startOffset + init.end,
  23189. "__emit"
  23190. );
  23191. } else {
  23192. lastNonRemoved = i;
  23193. }
  23194. }
  23195. }
  23196. }
  23197. let isAllLiteral = false;
  23198. if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  23199. isAllLiteral = walkDeclaration(
  23200. "scriptSetup",
  23201. node,
  23202. setupBindings,
  23203. vueImportAliases,
  23204. hoistStatic,
  23205. !!ctx.propsDestructureDecl
  23206. );
  23207. }
  23208. if (hoistStatic && isAllLiteral) {
  23209. hoistNode(node);
  23210. }
  23211. if (node.type === "VariableDeclaration" && !node.declare || node.type.endsWith("Statement")) {
  23212. const scope = [scriptSetupAst.body];
  23213. estreeWalker.walk(node, {
  23214. enter(child, parent) {
  23215. if (CompilerDOM.isFunctionType(child)) {
  23216. this.skip();
  23217. }
  23218. if (child.type === "BlockStatement") {
  23219. scope.push(child.body);
  23220. }
  23221. if (child.type === "AwaitExpression") {
  23222. hasAwait = true;
  23223. const currentScope = scope[scope.length - 1];
  23224. const needsSemi = currentScope.some((n, i) => {
  23225. return (scope.length === 1 || i > 0) && n.type === "ExpressionStatement" && n.start === child.start;
  23226. });
  23227. processAwait(
  23228. ctx,
  23229. child,
  23230. needsSemi,
  23231. parent.type === "ExpressionStatement"
  23232. );
  23233. }
  23234. },
  23235. exit(node2) {
  23236. if (node2.type === "BlockStatement") scope.pop();
  23237. }
  23238. });
  23239. }
  23240. if (node.type === "ExportNamedDeclaration" && node.exportKind !== "type" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration") {
  23241. ctx.error(
  23242. `<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.`,
  23243. node
  23244. );
  23245. }
  23246. if (ctx.isTS) {
  23247. if (node.type.startsWith("TS") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "VariableDeclaration" && node.declare) {
  23248. if (node.type !== "TSEnumDeclaration") {
  23249. hoistNode(node);
  23250. }
  23251. }
  23252. }
  23253. }
  23254. if (ctx.propsDestructureDecl) {
  23255. transformDestructuredProps(ctx, vueImportAliases);
  23256. }
  23257. checkInvalidScopeReference(ctx.propsRuntimeDecl, DEFINE_PROPS);
  23258. checkInvalidScopeReference(ctx.propsRuntimeDefaults, DEFINE_PROPS);
  23259. checkInvalidScopeReference(ctx.propsDestructureDecl, DEFINE_PROPS);
  23260. checkInvalidScopeReference(ctx.emitsRuntimeDecl, DEFINE_EMITS);
  23261. checkInvalidScopeReference(ctx.optionsRuntimeDecl, DEFINE_OPTIONS);
  23262. for (const { runtimeOptionNodes } of Object.values(ctx.modelDecls)) {
  23263. for (const node of runtimeOptionNodes) {
  23264. checkInvalidScopeReference(node, DEFINE_MODEL);
  23265. }
  23266. }
  23267. if (script) {
  23268. if (startOffset < scriptStartOffset) {
  23269. ctx.s.remove(0, startOffset);
  23270. ctx.s.remove(endOffset, scriptStartOffset);
  23271. ctx.s.remove(scriptEndOffset, source.length);
  23272. } else {
  23273. ctx.s.remove(0, scriptStartOffset);
  23274. ctx.s.remove(scriptEndOffset, startOffset);
  23275. ctx.s.remove(endOffset, source.length);
  23276. }
  23277. } else {
  23278. ctx.s.remove(0, startOffset);
  23279. ctx.s.remove(endOffset, source.length);
  23280. }
  23281. if (scriptAst) {
  23282. Object.assign(ctx.bindingMetadata, analyzeScriptBindings(scriptAst.body));
  23283. }
  23284. for (const [key, { isType, imported, source: source2 }] of Object.entries(
  23285. ctx.userImports
  23286. )) {
  23287. if (isType) continue;
  23288. ctx.bindingMetadata[key] = imported === "*" || imported === "default" && source2.endsWith(".vue") || source2 === "vue" ? "setup-const" : "setup-maybe-ref";
  23289. }
  23290. for (const key in scriptBindings) {
  23291. ctx.bindingMetadata[key] = scriptBindings[key];
  23292. }
  23293. for (const key in setupBindings) {
  23294. ctx.bindingMetadata[key] = setupBindings[key];
  23295. }
  23296. if (sfc.template && !sfc.template.src && sfc.template.ast) {
  23297. const vModelIds = resolveTemplateVModelIdentifiers(sfc);
  23298. if (vModelIds.size) {
  23299. const toDemote = /* @__PURE__ */ new Set();
  23300. for (const id of vModelIds) {
  23301. if (setupBindings[id] === "setup-reactive-const") {
  23302. toDemote.add(id);
  23303. }
  23304. }
  23305. if (toDemote.size) {
  23306. for (const node of scriptSetupAst.body) {
  23307. if (node.type === "VariableDeclaration" && node.kind === "const" && !node.declare) {
  23308. const demotedInDecl = [];
  23309. for (const decl of node.declarations) {
  23310. if (decl.id.type === "Identifier" && toDemote.has(decl.id.name)) {
  23311. demotedInDecl.push(decl.id.name);
  23312. }
  23313. }
  23314. if (demotedInDecl.length) {
  23315. ctx.s.overwrite(
  23316. node.start + startOffset,
  23317. node.start + startOffset + "const".length,
  23318. "let"
  23319. );
  23320. for (const id of demotedInDecl) {
  23321. setupBindings[id] = "setup-let";
  23322. ctx.bindingMetadata[id] = "setup-let";
  23323. warnOnce(
  23324. `\`v-model\` cannot update a \`const\` reactive binding \`${id}\`. The compiler has transformed it to \`let\` to make the update work.`
  23325. );
  23326. }
  23327. }
  23328. }
  23329. }
  23330. }
  23331. }
  23332. }
  23333. if (sfc.cssVars.length && // no need to do this when targeting SSR
  23334. !((_a = options.templateOptions) == null ? void 0 : _a.ssr)) {
  23335. ctx.helperImports.add(CSS_VARS_HELPER);
  23336. ctx.helperImports.add("unref");
  23337. ctx.s.prependLeft(
  23338. startOffset,
  23339. `
  23340. ${genCssVarsCode(
  23341. sfc.cssVars,
  23342. ctx.bindingMetadata,
  23343. scopeId,
  23344. !!options.isProd
  23345. )}
  23346. `
  23347. );
  23348. }
  23349. let args = `__props`;
  23350. if (ctx.propsTypeDecl) {
  23351. args += `: any`;
  23352. }
  23353. if (ctx.propsDecl) {
  23354. if (ctx.propsDestructureRestId) {
  23355. ctx.s.overwrite(
  23356. startOffset + ctx.propsCall.start,
  23357. startOffset + ctx.propsCall.end,
  23358. `${ctx.helper(`createPropsRestProxy`)}(__props, ${JSON.stringify(
  23359. Object.keys(ctx.propsDestructuredBindings)
  23360. )})`
  23361. );
  23362. ctx.s.overwrite(
  23363. startOffset + ctx.propsDestructureDecl.start,
  23364. startOffset + ctx.propsDestructureDecl.end,
  23365. ctx.propsDestructureRestId
  23366. );
  23367. } else if (!ctx.propsDestructureDecl) {
  23368. ctx.s.overwrite(
  23369. startOffset + ctx.propsCall.start,
  23370. startOffset + ctx.propsCall.end,
  23371. "__props"
  23372. );
  23373. }
  23374. }
  23375. if (hasAwait) {
  23376. const any = ctx.isTS ? `: any` : ``;
  23377. ctx.s.prependLeft(startOffset, `
  23378. let __temp${any}, __restore${any}
  23379. `);
  23380. }
  23381. const destructureElements = ctx.hasDefineExposeCall || !options.inlineTemplate ? [`expose: __expose`] : [];
  23382. if (ctx.emitDecl) {
  23383. destructureElements.push(`emit: __emit`);
  23384. }
  23385. if (destructureElements.length) {
  23386. args += `, { ${destructureElements.join(", ")} }`;
  23387. }
  23388. let templateMap;
  23389. let returned;
  23390. const propsDecl = genRuntimeProps(ctx);
  23391. if (!options.inlineTemplate || !sfc.template && ctx.hasDefaultExportRender) {
  23392. const allBindings = {
  23393. ...scriptBindings,
  23394. ...setupBindings
  23395. };
  23396. for (const key in ctx.userImports) {
  23397. if (!ctx.userImports[key].isType && ctx.userImports[key].isUsedInTemplate) {
  23398. allBindings[key] = true;
  23399. }
  23400. }
  23401. returned = `{ `;
  23402. for (const key in allBindings) {
  23403. if (allBindings[key] === true && ctx.userImports[key].source !== "vue" && !ctx.userImports[key].source.endsWith(".vue")) {
  23404. returned += `get ${key}() { return ${key} }, `;
  23405. } else if (ctx.bindingMetadata[key] === "setup-let") {
  23406. const setArg = key === "v" ? `_v` : `v`;
  23407. returned += `get ${key}() { return ${key} }, set ${key}(${setArg}) { ${key} = ${setArg} }, `;
  23408. } else {
  23409. returned += `${key}, `;
  23410. }
  23411. }
  23412. returned = returned.replace(/, $/, "") + ` }`;
  23413. } else {
  23414. if (sfc.template && !sfc.template.src) {
  23415. if (options.templateOptions && options.templateOptions.ssr) {
  23416. hasInlinedSsrRenderFn = true;
  23417. }
  23418. const { code, ast, preamble, tips, errors, map: map2 } = compileTemplate({
  23419. filename,
  23420. ast: sfc.template.ast,
  23421. source: sfc.template.content,
  23422. inMap: sfc.template.map,
  23423. ...options.templateOptions,
  23424. id: scopeId,
  23425. scoped: sfc.styles.some((s) => s.scoped),
  23426. isProd: options.isProd,
  23427. ssrCssVars: sfc.cssVars,
  23428. compilerOptions: {
  23429. ...options.templateOptions && options.templateOptions.compilerOptions,
  23430. inline: true,
  23431. isTS: ctx.isTS,
  23432. bindingMetadata: ctx.bindingMetadata
  23433. }
  23434. });
  23435. templateMap = map2;
  23436. if (tips.length) {
  23437. tips.forEach(warnOnce);
  23438. }
  23439. const err = errors[0];
  23440. if (typeof err === "string") {
  23441. throw new Error(err);
  23442. } else if (err) {
  23443. if (err.loc) {
  23444. err.message += `
  23445. ` + sfc.filename + "\n" + shared.generateCodeFrame(
  23446. source,
  23447. err.loc.start.offset,
  23448. err.loc.end.offset
  23449. ) + `
  23450. `;
  23451. }
  23452. throw err;
  23453. }
  23454. if (preamble) {
  23455. ctx.s.prepend(preamble);
  23456. }
  23457. if (ast && ast.helpers.has(CompilerDOM.UNREF)) {
  23458. ctx.helperImports.delete("unref");
  23459. }
  23460. returned = code;
  23461. } else {
  23462. returned = `() => {}`;
  23463. }
  23464. }
  23465. if (!options.inlineTemplate && true) {
  23466. ctx.s.appendRight(
  23467. endOffset,
  23468. `
  23469. const __returned__ = ${returned}
  23470. Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })
  23471. return __returned__
  23472. }
  23473. `
  23474. );
  23475. } else {
  23476. ctx.s.appendRight(endOffset, `
  23477. return ${returned}
  23478. }
  23479. `);
  23480. }
  23481. const genDefaultAs = options.genDefaultAs ? `const ${options.genDefaultAs} =` : `export default`;
  23482. let runtimeOptions = ``;
  23483. if (!ctx.hasDefaultExportName && filename && filename !== DEFAULT_FILENAME) {
  23484. const match = filename.match(/([^/\\]+)\.\w+$/);
  23485. if (match) {
  23486. runtimeOptions += `
  23487. __name: '${match[1]}',`;
  23488. }
  23489. }
  23490. if (hasInlinedSsrRenderFn) {
  23491. runtimeOptions += `
  23492. __ssrInlineRender: true,`;
  23493. }
  23494. if (propsDecl) runtimeOptions += `
  23495. props: ${propsDecl},`;
  23496. const emitsDecl = genRuntimeEmits(ctx);
  23497. if (emitsDecl) runtimeOptions += `
  23498. emits: ${emitsDecl},`;
  23499. let definedOptions = "";
  23500. if (ctx.optionsRuntimeDecl) {
  23501. definedOptions = scriptSetup.content.slice(ctx.optionsRuntimeDecl.start, ctx.optionsRuntimeDecl.end).trim();
  23502. }
  23503. const exposeCall = ctx.hasDefineExposeCall || options.inlineTemplate ? `` : ` __expose();
  23504. `;
  23505. if (ctx.isTS) {
  23506. const def = (defaultExport ? `
  23507. ...${normalScriptDefaultVar},` : ``) + (definedOptions ? `
  23508. ...${definedOptions},` : "");
  23509. ctx.s.prependLeft(
  23510. startOffset,
  23511. `
  23512. ${genDefaultAs} /*@__PURE__*/${ctx.helper(
  23513. `defineComponent`
  23514. )}({${def}${runtimeOptions}
  23515. ${hasAwait ? `async ` : ``}setup(${args}) {
  23516. ${exposeCall}`
  23517. );
  23518. ctx.s.appendRight(endOffset, `})`);
  23519. } else {
  23520. if (defaultExport || definedOptions) {
  23521. ctx.s.prependLeft(
  23522. startOffset,
  23523. `
  23524. ${genDefaultAs} /*@__PURE__*/Object.assign(${defaultExport ? `${normalScriptDefaultVar}, ` : ""}${definedOptions ? `${definedOptions}, ` : ""}{${runtimeOptions}
  23525. ${hasAwait ? `async ` : ``}setup(${args}) {
  23526. ${exposeCall}`
  23527. );
  23528. ctx.s.appendRight(endOffset, `})`);
  23529. } else {
  23530. ctx.s.prependLeft(
  23531. startOffset,
  23532. `
  23533. ${genDefaultAs} {${runtimeOptions}
  23534. ${hasAwait ? `async ` : ``}setup(${args}) {
  23535. ${exposeCall}`
  23536. );
  23537. ctx.s.appendRight(endOffset, `}`);
  23538. }
  23539. }
  23540. if (ctx.helperImports.size > 0) {
  23541. const runtimeModuleName = (_c = (_b = options.templateOptions) == null ? void 0 : _b.compilerOptions) == null ? void 0 : _c.runtimeModuleName;
  23542. const importSrc = runtimeModuleName ? JSON.stringify(runtimeModuleName) : `'vue'`;
  23543. ctx.s.prepend(
  23544. `import { ${[...ctx.helperImports].map((h) => `${h} as _${h}`).join(", ")} } from ${importSrc}
  23545. `
  23546. );
  23547. }
  23548. const content = ctx.s.toString();
  23549. let map = options.sourceMap !== false ? ctx.s.generateMap({
  23550. source: filename,
  23551. hires: true,
  23552. includeContent: true
  23553. }) : void 0;
  23554. if (templateMap && map) {
  23555. const offset = content.indexOf(returned);
  23556. const templateLineOffset = content.slice(0, offset).split(/\r?\n/).length - 1;
  23557. map = mergeSourceMaps(map, templateMap, templateLineOffset);
  23558. }
  23559. return {
  23560. ...scriptSetup,
  23561. bindings: ctx.bindingMetadata,
  23562. imports: ctx.userImports,
  23563. content,
  23564. map,
  23565. scriptAst: scriptAst == null ? void 0 : scriptAst.body,
  23566. scriptSetupAst: scriptSetupAst == null ? void 0 : scriptSetupAst.body,
  23567. deps: ctx.deps ? [...ctx.deps] : void 0
  23568. };
  23569. }
  23570. function registerBinding(bindings, node, type) {
  23571. bindings[node.name] = type;
  23572. }
  23573. function walkDeclaration(from, node, bindings, userImportAliases, hoistStatic, isPropsDestructureEnabled = false) {
  23574. let isAllLiteral = false;
  23575. if (node.type === "VariableDeclaration") {
  23576. const isConst = node.kind === "const";
  23577. isAllLiteral = isConst && node.declarations.every(
  23578. (decl) => decl.id.type === "Identifier" && isStaticNode(decl.init)
  23579. );
  23580. for (const { id, init: _init } of node.declarations) {
  23581. const init = _init && CompilerDOM.unwrapTSNode(_init);
  23582. const isConstMacroCall = isConst && isCallOf(
  23583. init,
  23584. (c) => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS || c === DEFINE_SLOTS
  23585. );
  23586. if (id.type === "Identifier") {
  23587. let bindingType;
  23588. const userReactiveBinding = userImportAliases["reactive"];
  23589. if ((hoistStatic || from === "script") && (isAllLiteral || isConst && isStaticNode(init))) {
  23590. bindingType = "literal-const";
  23591. } else if (isCallOf(init, userReactiveBinding)) {
  23592. bindingType = isConst ? "setup-reactive-const" : "setup-let";
  23593. } else if (
  23594. // if a declaration is a const literal, we can mark it so that
  23595. // the generated render fn code doesn't need to unref() it
  23596. isConstMacroCall || isConst && canNeverBeRef(init, userReactiveBinding)
  23597. ) {
  23598. bindingType = isCallOf(init, DEFINE_PROPS) ? "setup-reactive-const" : "setup-const";
  23599. } else if (isConst) {
  23600. if (isCallOf(
  23601. init,
  23602. (m) => m === userImportAliases["ref"] || m === userImportAliases["computed"] || m === userImportAliases["shallowRef"] || m === userImportAliases["customRef"] || m === userImportAliases["toRef"] || m === userImportAliases["useTemplateRef"] || m === DEFINE_MODEL
  23603. )) {
  23604. bindingType = "setup-ref";
  23605. } else {
  23606. bindingType = "setup-maybe-ref";
  23607. }
  23608. } else {
  23609. bindingType = "setup-let";
  23610. }
  23611. registerBinding(bindings, id, bindingType);
  23612. } else {
  23613. if (isCallOf(init, DEFINE_PROPS) && isPropsDestructureEnabled) {
  23614. continue;
  23615. }
  23616. if (id.type === "ObjectPattern") {
  23617. walkObjectPattern(id, bindings, isConst, isConstMacroCall);
  23618. } else if (id.type === "ArrayPattern") {
  23619. walkArrayPattern(id, bindings, isConst, isConstMacroCall);
  23620. }
  23621. }
  23622. }
  23623. } else if (node.type === "TSEnumDeclaration") {
  23624. isAllLiteral = node.members.every(
  23625. (member) => !member.initializer || isStaticNode(member.initializer)
  23626. );
  23627. bindings[node.id.name] = isAllLiteral ? "literal-const" : "setup-const";
  23628. } else if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
  23629. bindings[node.id.name] = "setup-const";
  23630. }
  23631. return isAllLiteral;
  23632. }
  23633. function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
  23634. for (const p of node.properties) {
  23635. if (p.type === "ObjectProperty") {
  23636. if (p.key.type === "Identifier" && p.key === p.value) {
  23637. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  23638. registerBinding(bindings, p.key, type);
  23639. } else {
  23640. walkPattern(p.value, bindings, isConst, isDefineCall);
  23641. }
  23642. } else {
  23643. const type = isConst ? "setup-const" : "setup-let";
  23644. registerBinding(bindings, p.argument, type);
  23645. }
  23646. }
  23647. }
  23648. function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
  23649. for (const e of node.elements) {
  23650. e && walkPattern(e, bindings, isConst, isDefineCall);
  23651. }
  23652. }
  23653. function walkPattern(node, bindings, isConst, isDefineCall = false) {
  23654. if (node.type === "Identifier") {
  23655. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  23656. registerBinding(bindings, node, type);
  23657. } else if (node.type === "RestElement") {
  23658. const type = isConst ? "setup-const" : "setup-let";
  23659. registerBinding(bindings, node.argument, type);
  23660. } else if (node.type === "ObjectPattern") {
  23661. walkObjectPattern(node, bindings, isConst);
  23662. } else if (node.type === "ArrayPattern") {
  23663. walkArrayPattern(node, bindings, isConst);
  23664. } else if (node.type === "AssignmentPattern") {
  23665. if (node.left.type === "Identifier") {
  23666. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  23667. registerBinding(bindings, node.left, type);
  23668. } else {
  23669. walkPattern(node.left, bindings, isConst);
  23670. }
  23671. }
  23672. }
  23673. function canNeverBeRef(node, userReactiveImport) {
  23674. if (isCallOf(node, userReactiveImport)) {
  23675. return true;
  23676. }
  23677. switch (node.type) {
  23678. case "UnaryExpression":
  23679. case "BinaryExpression":
  23680. case "ArrayExpression":
  23681. case "ObjectExpression":
  23682. case "FunctionExpression":
  23683. case "ArrowFunctionExpression":
  23684. case "UpdateExpression":
  23685. case "ClassExpression":
  23686. case "TaggedTemplateExpression":
  23687. return true;
  23688. case "SequenceExpression":
  23689. return canNeverBeRef(
  23690. node.expressions[node.expressions.length - 1],
  23691. userReactiveImport
  23692. );
  23693. default:
  23694. if (isLiteralNode(node)) {
  23695. return true;
  23696. }
  23697. return false;
  23698. }
  23699. }
  23700. function isStaticNode(node) {
  23701. node = CompilerDOM.unwrapTSNode(node);
  23702. switch (node.type) {
  23703. case "UnaryExpression":
  23704. return isStaticNode(node.argument);
  23705. case "LogicalExpression":
  23706. // 1 > 2
  23707. case "BinaryExpression":
  23708. return isStaticNode(node.left) && isStaticNode(node.right);
  23709. case "ConditionalExpression": {
  23710. return isStaticNode(node.test) && isStaticNode(node.consequent) && isStaticNode(node.alternate);
  23711. }
  23712. case "SequenceExpression":
  23713. // (1, 2)
  23714. case "TemplateLiteral":
  23715. return node.expressions.every((expr) => isStaticNode(expr));
  23716. case "ParenthesizedExpression":
  23717. return isStaticNode(node.expression);
  23718. case "StringLiteral":
  23719. case "NumericLiteral":
  23720. case "BooleanLiteral":
  23721. case "NullLiteral":
  23722. case "BigIntLiteral":
  23723. return true;
  23724. }
  23725. return false;
  23726. }
  23727. function mergeSourceMaps(scriptMap, templateMap, templateLineOffset) {
  23728. const generator = new sourceMapJs.SourceMapGenerator();
  23729. const addMapping = (map, lineOffset = 0) => {
  23730. const consumer = new sourceMapJs.SourceMapConsumer(map);
  23731. consumer.sources.forEach((sourceFile) => {
  23732. generator._sources.add(sourceFile);
  23733. const sourceContent = consumer.sourceContentFor(sourceFile);
  23734. if (sourceContent != null) {
  23735. generator.setSourceContent(sourceFile, sourceContent);
  23736. }
  23737. });
  23738. consumer.eachMapping((m) => {
  23739. if (m.originalLine == null) return;
  23740. generator.addMapping({
  23741. generated: {
  23742. line: m.generatedLine + lineOffset,
  23743. column: m.generatedColumn
  23744. },
  23745. original: {
  23746. line: m.originalLine,
  23747. column: m.originalColumn
  23748. },
  23749. source: m.source,
  23750. name: m.name
  23751. });
  23752. });
  23753. };
  23754. addMapping(scriptMap);
  23755. addMapping(templateMap, templateLineOffset);
  23756. generator._sourceRoot = scriptMap.sourceRoot;
  23757. generator._file = scriptMap.file;
  23758. return generator.toJSON();
  23759. }
  23760. const version = "3.5.32";
  23761. const parseCache = parseCache$1;
  23762. const errorMessages = {
  23763. ...CompilerDOM.errorMessages,
  23764. ...CompilerDOM.DOMErrorMessages
  23765. };
  23766. const walk = estreeWalker.walk;
  23767. const shouldTransformRef = () => false;
  23768. exports.extractIdentifiers = compilerCore.extractIdentifiers;
  23769. exports.generateCodeFrame = compilerCore.generateCodeFrame;
  23770. exports.isInDestructureAssignment = compilerCore.isInDestructureAssignment;
  23771. exports.isStaticProperty = compilerCore.isStaticProperty;
  23772. exports.walkIdentifiers = compilerCore.walkIdentifiers;
  23773. exports.MagicString = MagicString;
  23774. exports.babelParse = parser$2.parse;
  23775. exports.compileScript = compileScript;
  23776. exports.compileStyle = compileStyle;
  23777. exports.compileStyleAsync = compileStyleAsync;
  23778. exports.compileTemplate = compileTemplate;
  23779. exports.errorMessages = errorMessages;
  23780. exports.extractRuntimeEmits = extractRuntimeEmits;
  23781. exports.extractRuntimeProps = extractRuntimeProps;
  23782. exports.inferRuntimeType = inferRuntimeType;
  23783. exports.invalidateTypeCache = invalidateTypeCache;
  23784. exports.parse = parse$1;
  23785. exports.parseCache = parseCache;
  23786. exports.registerTS = registerTS;
  23787. exports.resolveTypeElements = resolveTypeElements;
  23788. exports.rewriteDefault = rewriteDefault;
  23789. exports.rewriteDefaultAST = rewriteDefaultAST;
  23790. exports.shouldTransformRef = shouldTransformRef;
  23791. exports.version = version;
  23792. exports.walk = walk;