compiler-sfc.cjs.js 844 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706
  1. /**
  2. * @vue/compiler-sfc v3.5.33
  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. let hasNestedDeep = false;
  7601. let splitForNestedDeep = false;
  7602. selector.each((n) => {
  7603. if (n.type === "combinator" && (n.value === ">>>" || n.value === "/deep/")) {
  7604. n.value = " ";
  7605. n.spaces.before = n.spaces.after = "";
  7606. warn(
  7607. `the >>> and /deep/ combinators have been deprecated. Use :deep() instead.`
  7608. );
  7609. return false;
  7610. }
  7611. if (n.type === "pseudo") {
  7612. const { value } = n;
  7613. if (isDeepContainerPseudo(n)) {
  7614. const hasDeepSelectors = n.nodes.some(
  7615. (selector2) => selector2.some(isDeepSelector)
  7616. );
  7617. if (hasDeepSelectors) {
  7618. const hasScopeAnchor = !!node;
  7619. const hasMixedSelectors = n.nodes.some(
  7620. (selector2) => !selector2.some(isDeepSelector)
  7621. );
  7622. const hasTrailingNodes = selector.index(n) < selector.length - 1;
  7623. if (canSplitDeepContainerPseudo(n) && !deep && !hasScopeAnchor && hasMixedSelectors && hasTrailingNodes) {
  7624. splitSelectorForNestedDeep(
  7625. id,
  7626. rule,
  7627. selector,
  7628. selectorRoot,
  7629. n,
  7630. deep,
  7631. slotted
  7632. );
  7633. splitForNestedDeep = true;
  7634. return false;
  7635. }
  7636. if (value === ":not" && !deep && !hasScopeAnchor && hasMixedSelectors && hasTrailingNodes) {
  7637. return;
  7638. }
  7639. n.nodes.forEach(
  7640. (selector2) => rewriteSelector(
  7641. id,
  7642. rule,
  7643. selector2,
  7644. selectorRoot,
  7645. deep || hasScopeAnchor,
  7646. slotted
  7647. )
  7648. );
  7649. if (!hasScopeAnchor) {
  7650. node = n;
  7651. shouldInject = false;
  7652. }
  7653. hasNestedDeep = true;
  7654. }
  7655. }
  7656. if (value === ":deep" || value === "::v-deep") {
  7657. rule.__deep = true;
  7658. if (n.nodes.length) {
  7659. let last = n;
  7660. n.nodes[0].each((ss) => {
  7661. selector.insertAfter(last, ss);
  7662. last = ss;
  7663. });
  7664. const prev = selector.at(selector.index(n) - 1);
  7665. if (!prev || !isSpaceCombinator(prev)) {
  7666. selector.insertAfter(
  7667. n,
  7668. selectorParser.combinator({
  7669. value: " "
  7670. })
  7671. );
  7672. }
  7673. selector.removeChild(n);
  7674. } else {
  7675. warn(
  7676. `${value} usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead of ${value} <inner-selector>.`
  7677. );
  7678. const prev = selector.at(selector.index(n) - 1);
  7679. if (prev && isSpaceCombinator(prev)) {
  7680. selector.removeChild(prev);
  7681. }
  7682. selector.removeChild(n);
  7683. }
  7684. return false;
  7685. }
  7686. if (value === ":slotted" || value === "::v-slotted") {
  7687. rewriteSelector(
  7688. id,
  7689. rule,
  7690. n.nodes[0],
  7691. selectorRoot,
  7692. deep,
  7693. true
  7694. );
  7695. let last = n;
  7696. n.nodes[0].each((ss) => {
  7697. selector.insertAfter(last, ss);
  7698. last = ss;
  7699. });
  7700. selector.removeChild(n);
  7701. shouldInject = false;
  7702. return false;
  7703. }
  7704. if (value === ":global" || value === "::v-global") {
  7705. selector.replaceWith(n.nodes[0]);
  7706. return false;
  7707. }
  7708. }
  7709. if (n.type === "universal") {
  7710. const prev = selector.at(selector.index(n) - 1);
  7711. const next = selector.at(selector.index(n) + 1);
  7712. if (!prev) {
  7713. if (next) {
  7714. if (next.type === "combinator" && next.value === " ") {
  7715. selector.removeChild(next);
  7716. }
  7717. selector.removeChild(n);
  7718. return;
  7719. } else {
  7720. node = selectorParser.combinator({
  7721. value: ""
  7722. });
  7723. selector.insertBefore(n, node);
  7724. selector.removeChild(n);
  7725. return false;
  7726. }
  7727. }
  7728. if (node) return;
  7729. }
  7730. if (!hasNestedDeep && (n.type !== "pseudo" && n.type !== "combinator" || n.type === "pseudo" && (n.value === ":is" || n.value === ":where") && !node)) {
  7731. node = n;
  7732. }
  7733. });
  7734. if (splitForNestedDeep) {
  7735. return;
  7736. }
  7737. if (rule.nodes.some((node2) => node2.type === "rule")) {
  7738. const deep2 = rule.__deep;
  7739. if (!deep2) {
  7740. extractAndWrapNodes(rule);
  7741. const atruleNodes = rule.nodes.filter((node2) => node2.type === "atrule");
  7742. for (const atnode of atruleNodes) {
  7743. extractAndWrapNodes(atnode);
  7744. }
  7745. }
  7746. shouldInject = deep2;
  7747. }
  7748. if (node && !hasNestedDeep) {
  7749. const { type, value } = node;
  7750. if (type === "pseudo" && (value === ":is" || value === ":where")) {
  7751. node.nodes.forEach(
  7752. (value2) => rewriteSelector(id, rule, value2, selectorRoot, deep, slotted)
  7753. );
  7754. shouldInject = false;
  7755. }
  7756. }
  7757. if (node) {
  7758. node.spaces.after = "";
  7759. } else {
  7760. selector.first.spaces.before = "";
  7761. }
  7762. if (shouldInject) {
  7763. const idToAdd = slotted ? id + "-s" : id;
  7764. selector.insertAfter(
  7765. // If node is null it means we need to inject [id] at the start
  7766. // insertAfter can handle `null` here
  7767. node,
  7768. selectorParser.attribute({
  7769. attribute: idToAdd,
  7770. value: idToAdd,
  7771. raws: {},
  7772. quoteMark: `"`
  7773. })
  7774. );
  7775. }
  7776. }
  7777. function isSpaceCombinator(node) {
  7778. return node.type === "combinator" && /^\s+$/.test(node.value);
  7779. }
  7780. function isDeepSelector(node) {
  7781. var _a;
  7782. if (node.type === "pseudo" && (node.value === ":deep" || node.value === "::v-deep")) {
  7783. return true;
  7784. }
  7785. return !!((_a = node.nodes) == null ? void 0 : _a.some((child) => isDeepSelector(child)));
  7786. }
  7787. function isDeepContainerPseudo(node) {
  7788. return node.type === "pseudo" && (node.value === ":is" || node.value === ":where" || node.value === ":has" || node.value === ":not");
  7789. }
  7790. function canSplitDeepContainerPseudo(node) {
  7791. return node.value === ":is" || node.value === ":where" || node.value === ":has";
  7792. }
  7793. function splitSelectorForNestedDeep(id, rule, selector, selectorRoot, pseudo, deep, slotted) {
  7794. const pseudoIndex = selector.index(pseudo);
  7795. const selectors = pseudo.nodes.map((branch, index) => {
  7796. const branchSelector = selector.clone();
  7797. if (branchSelector.first) {
  7798. branchSelector.first.spaces.before = index === 0 ? selector.first.spaces.before : " ";
  7799. }
  7800. const branchPseudo = branchSelector.at(pseudoIndex);
  7801. const branchClone = branch.clone();
  7802. if (branchClone.first) {
  7803. branchClone.first.spaces.before = "";
  7804. }
  7805. branchPseudo.removeAll();
  7806. branchPseudo.append(branchClone);
  7807. rewriteSelector(id, rule, branchSelector, selectorRoot, deep, slotted);
  7808. return branchSelector;
  7809. });
  7810. selector.replaceWith(...selectors);
  7811. }
  7812. function extractAndWrapNodes(parentNode) {
  7813. if (!parentNode.nodes) return;
  7814. const nodes = parentNode.nodes.filter(
  7815. (node) => node.type === "decl" || node.type === "comment"
  7816. );
  7817. if (nodes.length) {
  7818. for (const node of nodes) {
  7819. parentNode.removeChild(node);
  7820. }
  7821. const wrappedRule = new require$$0$1.Rule({
  7822. nodes,
  7823. selector: "&"
  7824. });
  7825. parentNode.prepend(wrappedRule);
  7826. }
  7827. }
  7828. scopedPlugin.postcss = true;
  7829. var sourceMap = {};
  7830. var sourceMapGenerator = {};
  7831. var base64Vlq = {};
  7832. var base64 = {};
  7833. /* -*- Mode: js; js-indent-level: 2; -*- */
  7834. var hasRequiredBase64;
  7835. function requireBase64 () {
  7836. if (hasRequiredBase64) return base64;
  7837. hasRequiredBase64 = 1;
  7838. /*
  7839. * Copyright 2011 Mozilla Foundation and contributors
  7840. * Licensed under the New BSD license. See LICENSE or:
  7841. * http://opensource.org/licenses/BSD-3-Clause
  7842. */
  7843. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  7844. /**
  7845. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  7846. */
  7847. base64.encode = function (number) {
  7848. if (0 <= number && number < intToCharMap.length) {
  7849. return intToCharMap[number];
  7850. }
  7851. throw new TypeError("Must be between 0 and 63: " + number);
  7852. };
  7853. /**
  7854. * Decode a single base 64 character code digit to an integer. Returns -1 on
  7855. * failure.
  7856. */
  7857. base64.decode = function (charCode) {
  7858. var bigA = 65; // 'A'
  7859. var bigZ = 90; // 'Z'
  7860. var littleA = 97; // 'a'
  7861. var littleZ = 122; // 'z'
  7862. var zero = 48; // '0'
  7863. var nine = 57; // '9'
  7864. var plus = 43; // '+'
  7865. var slash = 47; // '/'
  7866. var littleOffset = 26;
  7867. var numberOffset = 52;
  7868. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  7869. if (bigA <= charCode && charCode <= bigZ) {
  7870. return (charCode - bigA);
  7871. }
  7872. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  7873. if (littleA <= charCode && charCode <= littleZ) {
  7874. return (charCode - littleA + littleOffset);
  7875. }
  7876. // 52 - 61: 0123456789
  7877. if (zero <= charCode && charCode <= nine) {
  7878. return (charCode - zero + numberOffset);
  7879. }
  7880. // 62: +
  7881. if (charCode == plus) {
  7882. return 62;
  7883. }
  7884. // 63: /
  7885. if (charCode == slash) {
  7886. return 63;
  7887. }
  7888. // Invalid base64 digit.
  7889. return -1;
  7890. };
  7891. return base64;
  7892. }
  7893. /* -*- Mode: js; js-indent-level: 2; -*- */
  7894. var hasRequiredBase64Vlq;
  7895. function requireBase64Vlq () {
  7896. if (hasRequiredBase64Vlq) return base64Vlq;
  7897. hasRequiredBase64Vlq = 1;
  7898. /*
  7899. * Copyright 2011 Mozilla Foundation and contributors
  7900. * Licensed under the New BSD license. See LICENSE or:
  7901. * http://opensource.org/licenses/BSD-3-Clause
  7902. *
  7903. * Based on the Base 64 VLQ implementation in Closure Compiler:
  7904. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  7905. *
  7906. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  7907. * Redistribution and use in source and binary forms, with or without
  7908. * modification, are permitted provided that the following conditions are
  7909. * met:
  7910. *
  7911. * * Redistributions of source code must retain the above copyright
  7912. * notice, this list of conditions and the following disclaimer.
  7913. * * Redistributions in binary form must reproduce the above
  7914. * copyright notice, this list of conditions and the following
  7915. * disclaimer in the documentation and/or other materials provided
  7916. * with the distribution.
  7917. * * Neither the name of Google Inc. nor the names of its
  7918. * contributors may be used to endorse or promote products derived
  7919. * from this software without specific prior written permission.
  7920. *
  7921. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7922. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7923. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7924. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7925. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7926. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7927. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7928. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7929. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7930. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7931. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7932. */
  7933. var base64 = /*@__PURE__*/ requireBase64();
  7934. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  7935. // length quantities we use in the source map spec, the first bit is the sign,
  7936. // the next four bits are the actual value, and the 6th bit is the
  7937. // continuation bit. The continuation bit tells us whether there are more
  7938. // digits in this value following this digit.
  7939. //
  7940. // Continuation
  7941. // | Sign
  7942. // | |
  7943. // V V
  7944. // 101011
  7945. var VLQ_BASE_SHIFT = 5;
  7946. // binary: 100000
  7947. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  7948. // binary: 011111
  7949. var VLQ_BASE_MASK = VLQ_BASE - 1;
  7950. // binary: 100000
  7951. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  7952. /**
  7953. * Converts from a two-complement value to a value where the sign bit is
  7954. * placed in the least significant bit. For example, as decimals:
  7955. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  7956. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  7957. */
  7958. function toVLQSigned(aValue) {
  7959. return aValue < 0
  7960. ? ((-aValue) << 1) + 1
  7961. : (aValue << 1) + 0;
  7962. }
  7963. /**
  7964. * Converts to a two-complement value from a value where the sign bit is
  7965. * placed in the least significant bit. For example, as decimals:
  7966. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  7967. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  7968. */
  7969. function fromVLQSigned(aValue) {
  7970. var isNegative = (aValue & 1) === 1;
  7971. var shifted = aValue >> 1;
  7972. return isNegative
  7973. ? -shifted
  7974. : shifted;
  7975. }
  7976. /**
  7977. * Returns the base 64 VLQ encoded value.
  7978. */
  7979. base64Vlq.encode = function base64VLQ_encode(aValue) {
  7980. var encoded = "";
  7981. var digit;
  7982. var vlq = toVLQSigned(aValue);
  7983. do {
  7984. digit = vlq & VLQ_BASE_MASK;
  7985. vlq >>>= VLQ_BASE_SHIFT;
  7986. if (vlq > 0) {
  7987. // There are still more digits in this value, so we must make sure the
  7988. // continuation bit is marked.
  7989. digit |= VLQ_CONTINUATION_BIT;
  7990. }
  7991. encoded += base64.encode(digit);
  7992. } while (vlq > 0);
  7993. return encoded;
  7994. };
  7995. /**
  7996. * Decodes the next base 64 VLQ value from the given string and returns the
  7997. * value and the rest of the string via the out parameter.
  7998. */
  7999. base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  8000. var strLen = aStr.length;
  8001. var result = 0;
  8002. var shift = 0;
  8003. var continuation, digit;
  8004. do {
  8005. if (aIndex >= strLen) {
  8006. throw new Error("Expected more digits in base 64 VLQ value.");
  8007. }
  8008. digit = base64.decode(aStr.charCodeAt(aIndex++));
  8009. if (digit === -1) {
  8010. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  8011. }
  8012. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  8013. digit &= VLQ_BASE_MASK;
  8014. result = result + (digit << shift);
  8015. shift += VLQ_BASE_SHIFT;
  8016. } while (continuation);
  8017. aOutParam.value = fromVLQSigned(result);
  8018. aOutParam.rest = aIndex;
  8019. };
  8020. return base64Vlq;
  8021. }
  8022. var util$1 = {};
  8023. /* -*- Mode: js; js-indent-level: 2; -*- */
  8024. var hasRequiredUtil$1;
  8025. function requireUtil$1 () {
  8026. if (hasRequiredUtil$1) return util$1;
  8027. hasRequiredUtil$1 = 1;
  8028. (function (exports$1) {
  8029. /*
  8030. * Copyright 2011 Mozilla Foundation and contributors
  8031. * Licensed under the New BSD license. See LICENSE or:
  8032. * http://opensource.org/licenses/BSD-3-Clause
  8033. */
  8034. /**
  8035. * This is a helper function for getting values from parameter/options
  8036. * objects.
  8037. *
  8038. * @param args The object we are extracting values from
  8039. * @param name The name of the property we are getting.
  8040. * @param defaultValue An optional value to return if the property is missing
  8041. * from the object. If this is not specified and the property is missing, an
  8042. * error will be thrown.
  8043. */
  8044. function getArg(aArgs, aName, aDefaultValue) {
  8045. if (aName in aArgs) {
  8046. return aArgs[aName];
  8047. } else if (arguments.length === 3) {
  8048. return aDefaultValue;
  8049. } else {
  8050. throw new Error('"' + aName + '" is a required argument.');
  8051. }
  8052. }
  8053. exports$1.getArg = getArg;
  8054. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  8055. var dataUrlRegexp = /^data:.+\,.+$/;
  8056. function urlParse(aUrl) {
  8057. var match = aUrl.match(urlRegexp);
  8058. if (!match) {
  8059. return null;
  8060. }
  8061. return {
  8062. scheme: match[1],
  8063. auth: match[2],
  8064. host: match[3],
  8065. port: match[4],
  8066. path: match[5]
  8067. };
  8068. }
  8069. exports$1.urlParse = urlParse;
  8070. function urlGenerate(aParsedUrl) {
  8071. var url = '';
  8072. if (aParsedUrl.scheme) {
  8073. url += aParsedUrl.scheme + ':';
  8074. }
  8075. url += '//';
  8076. if (aParsedUrl.auth) {
  8077. url += aParsedUrl.auth + '@';
  8078. }
  8079. if (aParsedUrl.host) {
  8080. url += aParsedUrl.host;
  8081. }
  8082. if (aParsedUrl.port) {
  8083. url += ":" + aParsedUrl.port;
  8084. }
  8085. if (aParsedUrl.path) {
  8086. url += aParsedUrl.path;
  8087. }
  8088. return url;
  8089. }
  8090. exports$1.urlGenerate = urlGenerate;
  8091. /**
  8092. * Normalizes a path, or the path portion of a URL:
  8093. *
  8094. * - Replaces consecutive slashes with one slash.
  8095. * - Removes unnecessary '.' parts.
  8096. * - Removes unnecessary '<dir>/..' parts.
  8097. *
  8098. * Based on code in the Node.js 'path' core module.
  8099. *
  8100. * @param aPath The path or url to normalize.
  8101. */
  8102. function normalize(aPath) {
  8103. var path = aPath;
  8104. var url = urlParse(aPath);
  8105. if (url) {
  8106. if (!url.path) {
  8107. return aPath;
  8108. }
  8109. path = url.path;
  8110. }
  8111. var isAbsolute = exports$1.isAbsolute(path);
  8112. var parts = path.split(/\/+/);
  8113. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  8114. part = parts[i];
  8115. if (part === '.') {
  8116. parts.splice(i, 1);
  8117. } else if (part === '..') {
  8118. up++;
  8119. } else if (up > 0) {
  8120. if (part === '') {
  8121. // The first part is blank if the path is absolute. Trying to go
  8122. // above the root is a no-op. Therefore we can remove all '..' parts
  8123. // directly after the root.
  8124. parts.splice(i + 1, up);
  8125. up = 0;
  8126. } else {
  8127. parts.splice(i, 2);
  8128. up--;
  8129. }
  8130. }
  8131. }
  8132. path = parts.join('/');
  8133. if (path === '') {
  8134. path = isAbsolute ? '/' : '.';
  8135. }
  8136. if (url) {
  8137. url.path = path;
  8138. return urlGenerate(url);
  8139. }
  8140. return path;
  8141. }
  8142. exports$1.normalize = normalize;
  8143. /**
  8144. * Joins two paths/URLs.
  8145. *
  8146. * @param aRoot The root path or URL.
  8147. * @param aPath The path or URL to be joined with the root.
  8148. *
  8149. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  8150. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  8151. * first.
  8152. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  8153. * is updated with the result and aRoot is returned. Otherwise the result
  8154. * is returned.
  8155. * - If aPath is absolute, the result is aPath.
  8156. * - Otherwise the two paths are joined with a slash.
  8157. * - Joining for example 'http://' and 'www.example.com' is also supported.
  8158. */
  8159. function join(aRoot, aPath) {
  8160. if (aRoot === "") {
  8161. aRoot = ".";
  8162. }
  8163. if (aPath === "") {
  8164. aPath = ".";
  8165. }
  8166. var aPathUrl = urlParse(aPath);
  8167. var aRootUrl = urlParse(aRoot);
  8168. if (aRootUrl) {
  8169. aRoot = aRootUrl.path || '/';
  8170. }
  8171. // `join(foo, '//www.example.org')`
  8172. if (aPathUrl && !aPathUrl.scheme) {
  8173. if (aRootUrl) {
  8174. aPathUrl.scheme = aRootUrl.scheme;
  8175. }
  8176. return urlGenerate(aPathUrl);
  8177. }
  8178. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  8179. return aPath;
  8180. }
  8181. // `join('http://', 'www.example.com')`
  8182. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  8183. aRootUrl.host = aPath;
  8184. return urlGenerate(aRootUrl);
  8185. }
  8186. var joined = aPath.charAt(0) === '/'
  8187. ? aPath
  8188. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  8189. if (aRootUrl) {
  8190. aRootUrl.path = joined;
  8191. return urlGenerate(aRootUrl);
  8192. }
  8193. return joined;
  8194. }
  8195. exports$1.join = join;
  8196. exports$1.isAbsolute = function (aPath) {
  8197. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  8198. };
  8199. /**
  8200. * Make a path relative to a URL or another path.
  8201. *
  8202. * @param aRoot The root path or URL.
  8203. * @param aPath The path or URL to be made relative to aRoot.
  8204. */
  8205. function relative(aRoot, aPath) {
  8206. if (aRoot === "") {
  8207. aRoot = ".";
  8208. }
  8209. aRoot = aRoot.replace(/\/$/, '');
  8210. // It is possible for the path to be above the root. In this case, simply
  8211. // checking whether the root is a prefix of the path won't work. Instead, we
  8212. // need to remove components from the root one by one, until either we find
  8213. // a prefix that fits, or we run out of components to remove.
  8214. var level = 0;
  8215. while (aPath.indexOf(aRoot + '/') !== 0) {
  8216. var index = aRoot.lastIndexOf("/");
  8217. if (index < 0) {
  8218. return aPath;
  8219. }
  8220. // If the only part of the root that is left is the scheme (i.e. http://,
  8221. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  8222. // have exhausted all components, so the path is not relative to the root.
  8223. aRoot = aRoot.slice(0, index);
  8224. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  8225. return aPath;
  8226. }
  8227. ++level;
  8228. }
  8229. // Make sure we add a "../" for each component we removed from the root.
  8230. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  8231. }
  8232. exports$1.relative = relative;
  8233. var supportsNullProto = (function () {
  8234. var obj = Object.create(null);
  8235. return !('__proto__' in obj);
  8236. }());
  8237. function identity (s) {
  8238. return s;
  8239. }
  8240. /**
  8241. * Because behavior goes wacky when you set `__proto__` on objects, we
  8242. * have to prefix all the strings in our set with an arbitrary character.
  8243. *
  8244. * See https://github.com/mozilla/source-map/pull/31 and
  8245. * https://github.com/mozilla/source-map/issues/30
  8246. *
  8247. * @param String aStr
  8248. */
  8249. function toSetString(aStr) {
  8250. if (isProtoString(aStr)) {
  8251. return '$' + aStr;
  8252. }
  8253. return aStr;
  8254. }
  8255. exports$1.toSetString = supportsNullProto ? identity : toSetString;
  8256. function fromSetString(aStr) {
  8257. if (isProtoString(aStr)) {
  8258. return aStr.slice(1);
  8259. }
  8260. return aStr;
  8261. }
  8262. exports$1.fromSetString = supportsNullProto ? identity : fromSetString;
  8263. function isProtoString(s) {
  8264. if (!s) {
  8265. return false;
  8266. }
  8267. var length = s.length;
  8268. if (length < 9 /* "__proto__".length */) {
  8269. return false;
  8270. }
  8271. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  8272. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  8273. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  8274. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  8275. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  8276. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  8277. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  8278. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  8279. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  8280. return false;
  8281. }
  8282. for (var i = length - 10; i >= 0; i--) {
  8283. if (s.charCodeAt(i) !== 36 /* '$' */) {
  8284. return false;
  8285. }
  8286. }
  8287. return true;
  8288. }
  8289. /**
  8290. * Comparator between two mappings where the original positions are compared.
  8291. *
  8292. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  8293. * mappings with the same original source/line/column, but different generated
  8294. * line and column the same. Useful when searching for a mapping with a
  8295. * stubbed out mapping.
  8296. */
  8297. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  8298. var cmp = strcmp(mappingA.source, mappingB.source);
  8299. if (cmp !== 0) {
  8300. return cmp;
  8301. }
  8302. cmp = mappingA.originalLine - mappingB.originalLine;
  8303. if (cmp !== 0) {
  8304. return cmp;
  8305. }
  8306. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8307. if (cmp !== 0 || onlyCompareOriginal) {
  8308. return cmp;
  8309. }
  8310. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8311. if (cmp !== 0) {
  8312. return cmp;
  8313. }
  8314. cmp = mappingA.generatedLine - mappingB.generatedLine;
  8315. if (cmp !== 0) {
  8316. return cmp;
  8317. }
  8318. return strcmp(mappingA.name, mappingB.name);
  8319. }
  8320. exports$1.compareByOriginalPositions = compareByOriginalPositions;
  8321. /**
  8322. * Comparator between two mappings with deflated source and name indices where
  8323. * the generated positions are compared.
  8324. *
  8325. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  8326. * mappings with the same generated line and column, but different
  8327. * source/name/original line and column the same. Useful when searching for a
  8328. * mapping with a stubbed out mapping.
  8329. */
  8330. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  8331. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  8332. if (cmp !== 0) {
  8333. return cmp;
  8334. }
  8335. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8336. if (cmp !== 0 || onlyCompareGenerated) {
  8337. return cmp;
  8338. }
  8339. cmp = strcmp(mappingA.source, mappingB.source);
  8340. if (cmp !== 0) {
  8341. return cmp;
  8342. }
  8343. cmp = mappingA.originalLine - mappingB.originalLine;
  8344. if (cmp !== 0) {
  8345. return cmp;
  8346. }
  8347. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8348. if (cmp !== 0) {
  8349. return cmp;
  8350. }
  8351. return strcmp(mappingA.name, mappingB.name);
  8352. }
  8353. exports$1.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  8354. function strcmp(aStr1, aStr2) {
  8355. if (aStr1 === aStr2) {
  8356. return 0;
  8357. }
  8358. if (aStr1 === null) {
  8359. return 1; // aStr2 !== null
  8360. }
  8361. if (aStr2 === null) {
  8362. return -1; // aStr1 !== null
  8363. }
  8364. if (aStr1 > aStr2) {
  8365. return 1;
  8366. }
  8367. return -1;
  8368. }
  8369. /**
  8370. * Comparator between two mappings with inflated source and name strings where
  8371. * the generated positions are compared.
  8372. */
  8373. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  8374. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  8375. if (cmp !== 0) {
  8376. return cmp;
  8377. }
  8378. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8379. if (cmp !== 0) {
  8380. return cmp;
  8381. }
  8382. cmp = strcmp(mappingA.source, mappingB.source);
  8383. if (cmp !== 0) {
  8384. return cmp;
  8385. }
  8386. cmp = mappingA.originalLine - mappingB.originalLine;
  8387. if (cmp !== 0) {
  8388. return cmp;
  8389. }
  8390. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8391. if (cmp !== 0) {
  8392. return cmp;
  8393. }
  8394. return strcmp(mappingA.name, mappingB.name);
  8395. }
  8396. exports$1.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  8397. /**
  8398. * Strip any JSON XSSI avoidance prefix from the string (as documented
  8399. * in the source maps specification), and then parse the string as
  8400. * JSON.
  8401. */
  8402. function parseSourceMapInput(str) {
  8403. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  8404. }
  8405. exports$1.parseSourceMapInput = parseSourceMapInput;
  8406. /**
  8407. * Compute the URL of a source given the the source root, the source's
  8408. * URL, and the source map's URL.
  8409. */
  8410. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  8411. sourceURL = sourceURL || '';
  8412. if (sourceRoot) {
  8413. // This follows what Chrome does.
  8414. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  8415. sourceRoot += '/';
  8416. }
  8417. // The spec says:
  8418. // Line 4: An optional source root, useful for relocating source
  8419. // files on a server or removing repeated values in the
  8420. // “sources” entry. This value is prepended to the individual
  8421. // entries in the “source” field.
  8422. sourceURL = sourceRoot + sourceURL;
  8423. }
  8424. // Historically, SourceMapConsumer did not take the sourceMapURL as
  8425. // a parameter. This mode is still somewhat supported, which is why
  8426. // this code block is conditional. However, it's preferable to pass
  8427. // the source map URL to SourceMapConsumer, so that this function
  8428. // can implement the source URL resolution algorithm as outlined in
  8429. // the spec. This block is basically the equivalent of:
  8430. // new URL(sourceURL, sourceMapURL).toString()
  8431. // ... except it avoids using URL, which wasn't available in the
  8432. // older releases of node still supported by this library.
  8433. //
  8434. // The spec says:
  8435. // If the sources are not absolute URLs after prepending of the
  8436. // “sourceRoot”, the sources are resolved relative to the
  8437. // SourceMap (like resolving script src in a html document).
  8438. if (sourceMapURL) {
  8439. var parsed = urlParse(sourceMapURL);
  8440. if (!parsed) {
  8441. throw new Error("sourceMapURL could not be parsed");
  8442. }
  8443. if (parsed.path) {
  8444. // Strip the last path component, but keep the "/".
  8445. var index = parsed.path.lastIndexOf('/');
  8446. if (index >= 0) {
  8447. parsed.path = parsed.path.substring(0, index + 1);
  8448. }
  8449. }
  8450. sourceURL = join(urlGenerate(parsed), sourceURL);
  8451. }
  8452. return normalize(sourceURL);
  8453. }
  8454. exports$1.computeSourceURL = computeSourceURL;
  8455. } (util$1));
  8456. return util$1;
  8457. }
  8458. var arraySet = {};
  8459. /* -*- Mode: js; js-indent-level: 2; -*- */
  8460. var hasRequiredArraySet;
  8461. function requireArraySet () {
  8462. if (hasRequiredArraySet) return arraySet;
  8463. hasRequiredArraySet = 1;
  8464. /*
  8465. * Copyright 2011 Mozilla Foundation and contributors
  8466. * Licensed under the New BSD license. See LICENSE or:
  8467. * http://opensource.org/licenses/BSD-3-Clause
  8468. */
  8469. var util = /*@__PURE__*/ requireUtil$1();
  8470. var has = Object.prototype.hasOwnProperty;
  8471. var hasNativeMap = typeof Map !== "undefined";
  8472. /**
  8473. * A data structure which is a combination of an array and a set. Adding a new
  8474. * member is O(1), testing for membership is O(1), and finding the index of an
  8475. * element is O(1). Removing elements from the set is not supported. Only
  8476. * strings are supported for membership.
  8477. */
  8478. function ArraySet() {
  8479. this._array = [];
  8480. this._set = hasNativeMap ? new Map() : Object.create(null);
  8481. }
  8482. /**
  8483. * Static method for creating ArraySet instances from an existing array.
  8484. */
  8485. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  8486. var set = new ArraySet();
  8487. for (var i = 0, len = aArray.length; i < len; i++) {
  8488. set.add(aArray[i], aAllowDuplicates);
  8489. }
  8490. return set;
  8491. };
  8492. /**
  8493. * Return how many unique items are in this ArraySet. If duplicates have been
  8494. * added, than those do not count towards the size.
  8495. *
  8496. * @returns Number
  8497. */
  8498. ArraySet.prototype.size = function ArraySet_size() {
  8499. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  8500. };
  8501. /**
  8502. * Add the given string to this set.
  8503. *
  8504. * @param String aStr
  8505. */
  8506. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  8507. var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
  8508. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  8509. var idx = this._array.length;
  8510. if (!isDuplicate || aAllowDuplicates) {
  8511. this._array.push(aStr);
  8512. }
  8513. if (!isDuplicate) {
  8514. if (hasNativeMap) {
  8515. this._set.set(aStr, idx);
  8516. } else {
  8517. this._set[sStr] = idx;
  8518. }
  8519. }
  8520. };
  8521. /**
  8522. * Is the given string a member of this set?
  8523. *
  8524. * @param String aStr
  8525. */
  8526. ArraySet.prototype.has = function ArraySet_has(aStr) {
  8527. if (hasNativeMap) {
  8528. return this._set.has(aStr);
  8529. } else {
  8530. var sStr = util.toSetString(aStr);
  8531. return has.call(this._set, sStr);
  8532. }
  8533. };
  8534. /**
  8535. * What is the index of the given string in the array?
  8536. *
  8537. * @param String aStr
  8538. */
  8539. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  8540. if (hasNativeMap) {
  8541. var idx = this._set.get(aStr);
  8542. if (idx >= 0) {
  8543. return idx;
  8544. }
  8545. } else {
  8546. var sStr = util.toSetString(aStr);
  8547. if (has.call(this._set, sStr)) {
  8548. return this._set[sStr];
  8549. }
  8550. }
  8551. throw new Error('"' + aStr + '" is not in the set.');
  8552. };
  8553. /**
  8554. * What is the element at the given index?
  8555. *
  8556. * @param Number aIdx
  8557. */
  8558. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  8559. if (aIdx >= 0 && aIdx < this._array.length) {
  8560. return this._array[aIdx];
  8561. }
  8562. throw new Error('No element indexed by ' + aIdx);
  8563. };
  8564. /**
  8565. * Returns the array representation of this set (which has the proper indices
  8566. * indicated by indexOf). Note that this is a copy of the internal array used
  8567. * for storing the members so that no one can mess with internal state.
  8568. */
  8569. ArraySet.prototype.toArray = function ArraySet_toArray() {
  8570. return this._array.slice();
  8571. };
  8572. arraySet.ArraySet = ArraySet;
  8573. return arraySet;
  8574. }
  8575. var mappingList = {};
  8576. /* -*- Mode: js; js-indent-level: 2; -*- */
  8577. var hasRequiredMappingList;
  8578. function requireMappingList () {
  8579. if (hasRequiredMappingList) return mappingList;
  8580. hasRequiredMappingList = 1;
  8581. /*
  8582. * Copyright 2014 Mozilla Foundation and contributors
  8583. * Licensed under the New BSD license. See LICENSE or:
  8584. * http://opensource.org/licenses/BSD-3-Clause
  8585. */
  8586. var util = /*@__PURE__*/ requireUtil$1();
  8587. /**
  8588. * Determine whether mappingB is after mappingA with respect to generated
  8589. * position.
  8590. */
  8591. function generatedPositionAfter(mappingA, mappingB) {
  8592. // Optimized for most common case
  8593. var lineA = mappingA.generatedLine;
  8594. var lineB = mappingB.generatedLine;
  8595. var columnA = mappingA.generatedColumn;
  8596. var columnB = mappingB.generatedColumn;
  8597. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  8598. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  8599. }
  8600. /**
  8601. * A data structure to provide a sorted view of accumulated mappings in a
  8602. * performance conscious manner. It trades a neglibable overhead in general
  8603. * case for a large speedup in case of mappings being added in order.
  8604. */
  8605. function MappingList() {
  8606. this._array = [];
  8607. this._sorted = true;
  8608. // Serves as infimum
  8609. this._last = {generatedLine: -1, generatedColumn: 0};
  8610. }
  8611. /**
  8612. * Iterate through internal items. This method takes the same arguments that
  8613. * `Array.prototype.forEach` takes.
  8614. *
  8615. * NOTE: The order of the mappings is NOT guaranteed.
  8616. */
  8617. MappingList.prototype.unsortedForEach =
  8618. function MappingList_forEach(aCallback, aThisArg) {
  8619. this._array.forEach(aCallback, aThisArg);
  8620. };
  8621. /**
  8622. * Add the given source mapping.
  8623. *
  8624. * @param Object aMapping
  8625. */
  8626. MappingList.prototype.add = function MappingList_add(aMapping) {
  8627. if (generatedPositionAfter(this._last, aMapping)) {
  8628. this._last = aMapping;
  8629. this._array.push(aMapping);
  8630. } else {
  8631. this._sorted = false;
  8632. this._array.push(aMapping);
  8633. }
  8634. };
  8635. /**
  8636. * Returns the flat, sorted array of mappings. The mappings are sorted by
  8637. * generated position.
  8638. *
  8639. * WARNING: This method returns internal data without copying, for
  8640. * performance. The return value must NOT be mutated, and should be treated as
  8641. * an immutable borrow. If you want to take ownership, you must make your own
  8642. * copy.
  8643. */
  8644. MappingList.prototype.toArray = function MappingList_toArray() {
  8645. if (!this._sorted) {
  8646. this._array.sort(util.compareByGeneratedPositionsInflated);
  8647. this._sorted = true;
  8648. }
  8649. return this._array;
  8650. };
  8651. mappingList.MappingList = MappingList;
  8652. return mappingList;
  8653. }
  8654. /* -*- Mode: js; js-indent-level: 2; -*- */
  8655. var hasRequiredSourceMapGenerator;
  8656. function requireSourceMapGenerator () {
  8657. if (hasRequiredSourceMapGenerator) return sourceMapGenerator;
  8658. hasRequiredSourceMapGenerator = 1;
  8659. /*
  8660. * Copyright 2011 Mozilla Foundation and contributors
  8661. * Licensed under the New BSD license. See LICENSE or:
  8662. * http://opensource.org/licenses/BSD-3-Clause
  8663. */
  8664. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  8665. var util = /*@__PURE__*/ requireUtil$1();
  8666. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  8667. var MappingList = /*@__PURE__*/ requireMappingList().MappingList;
  8668. /**
  8669. * An instance of the SourceMapGenerator represents a source map which is
  8670. * being built incrementally. You may pass an object with the following
  8671. * properties:
  8672. *
  8673. * - file: The filename of the generated source.
  8674. * - sourceRoot: A root for all relative URLs in this source map.
  8675. */
  8676. function SourceMapGenerator(aArgs) {
  8677. if (!aArgs) {
  8678. aArgs = {};
  8679. }
  8680. this._file = util.getArg(aArgs, 'file', null);
  8681. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  8682. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  8683. this._sources = new ArraySet();
  8684. this._names = new ArraySet();
  8685. this._mappings = new MappingList();
  8686. this._sourcesContents = null;
  8687. }
  8688. SourceMapGenerator.prototype._version = 3;
  8689. /**
  8690. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  8691. *
  8692. * @param aSourceMapConsumer The SourceMap.
  8693. */
  8694. SourceMapGenerator.fromSourceMap =
  8695. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  8696. var sourceRoot = aSourceMapConsumer.sourceRoot;
  8697. var generator = new SourceMapGenerator({
  8698. file: aSourceMapConsumer.file,
  8699. sourceRoot: sourceRoot
  8700. });
  8701. aSourceMapConsumer.eachMapping(function (mapping) {
  8702. var newMapping = {
  8703. generated: {
  8704. line: mapping.generatedLine,
  8705. column: mapping.generatedColumn
  8706. }
  8707. };
  8708. if (mapping.source != null) {
  8709. newMapping.source = mapping.source;
  8710. if (sourceRoot != null) {
  8711. newMapping.source = util.relative(sourceRoot, newMapping.source);
  8712. }
  8713. newMapping.original = {
  8714. line: mapping.originalLine,
  8715. column: mapping.originalColumn
  8716. };
  8717. if (mapping.name != null) {
  8718. newMapping.name = mapping.name;
  8719. }
  8720. }
  8721. generator.addMapping(newMapping);
  8722. });
  8723. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8724. var sourceRelative = sourceFile;
  8725. if (sourceRoot !== null) {
  8726. sourceRelative = util.relative(sourceRoot, sourceFile);
  8727. }
  8728. if (!generator._sources.has(sourceRelative)) {
  8729. generator._sources.add(sourceRelative);
  8730. }
  8731. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8732. if (content != null) {
  8733. generator.setSourceContent(sourceFile, content);
  8734. }
  8735. });
  8736. return generator;
  8737. };
  8738. /**
  8739. * Add a single mapping from original source line and column to the generated
  8740. * source's line and column for this source map being created. The mapping
  8741. * object should have the following properties:
  8742. *
  8743. * - generated: An object with the generated line and column positions.
  8744. * - original: An object with the original line and column positions.
  8745. * - source: The original source file (relative to the sourceRoot).
  8746. * - name: An optional original token name for this mapping.
  8747. */
  8748. SourceMapGenerator.prototype.addMapping =
  8749. function SourceMapGenerator_addMapping(aArgs) {
  8750. var generated = util.getArg(aArgs, 'generated');
  8751. var original = util.getArg(aArgs, 'original', null);
  8752. var source = util.getArg(aArgs, 'source', null);
  8753. var name = util.getArg(aArgs, 'name', null);
  8754. if (!this._skipValidation) {
  8755. this._validateMapping(generated, original, source, name);
  8756. }
  8757. if (source != null) {
  8758. source = String(source);
  8759. if (!this._sources.has(source)) {
  8760. this._sources.add(source);
  8761. }
  8762. }
  8763. if (name != null) {
  8764. name = String(name);
  8765. if (!this._names.has(name)) {
  8766. this._names.add(name);
  8767. }
  8768. }
  8769. this._mappings.add({
  8770. generatedLine: generated.line,
  8771. generatedColumn: generated.column,
  8772. originalLine: original != null && original.line,
  8773. originalColumn: original != null && original.column,
  8774. source: source,
  8775. name: name
  8776. });
  8777. };
  8778. /**
  8779. * Set the source content for a source file.
  8780. */
  8781. SourceMapGenerator.prototype.setSourceContent =
  8782. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  8783. var source = aSourceFile;
  8784. if (this._sourceRoot != null) {
  8785. source = util.relative(this._sourceRoot, source);
  8786. }
  8787. if (aSourceContent != null) {
  8788. // Add the source content to the _sourcesContents map.
  8789. // Create a new _sourcesContents map if the property is null.
  8790. if (!this._sourcesContents) {
  8791. this._sourcesContents = Object.create(null);
  8792. }
  8793. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  8794. } else if (this._sourcesContents) {
  8795. // Remove the source file from the _sourcesContents map.
  8796. // If the _sourcesContents map is empty, set the property to null.
  8797. delete this._sourcesContents[util.toSetString(source)];
  8798. if (Object.keys(this._sourcesContents).length === 0) {
  8799. this._sourcesContents = null;
  8800. }
  8801. }
  8802. };
  8803. /**
  8804. * Applies the mappings of a sub-source-map for a specific source file to the
  8805. * source map being generated. Each mapping to the supplied source file is
  8806. * rewritten using the supplied source map. Note: The resolution for the
  8807. * resulting mappings is the minimium of this map and the supplied map.
  8808. *
  8809. * @param aSourceMapConsumer The source map to be applied.
  8810. * @param aSourceFile Optional. The filename of the source file.
  8811. * If omitted, SourceMapConsumer's file property will be used.
  8812. * @param aSourceMapPath Optional. The dirname of the path to the source map
  8813. * to be applied. If relative, it is relative to the SourceMapConsumer.
  8814. * This parameter is needed when the two source maps aren't in the same
  8815. * directory, and the source map to be applied contains relative source
  8816. * paths. If so, those relative source paths need to be rewritten
  8817. * relative to the SourceMapGenerator.
  8818. */
  8819. SourceMapGenerator.prototype.applySourceMap =
  8820. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  8821. var sourceFile = aSourceFile;
  8822. // If aSourceFile is omitted, we will use the file property of the SourceMap
  8823. if (aSourceFile == null) {
  8824. if (aSourceMapConsumer.file == null) {
  8825. throw new Error(
  8826. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  8827. 'or the source map\'s "file" property. Both were omitted.'
  8828. );
  8829. }
  8830. sourceFile = aSourceMapConsumer.file;
  8831. }
  8832. var sourceRoot = this._sourceRoot;
  8833. // Make "sourceFile" relative if an absolute Url is passed.
  8834. if (sourceRoot != null) {
  8835. sourceFile = util.relative(sourceRoot, sourceFile);
  8836. }
  8837. // Applying the SourceMap can add and remove items from the sources and
  8838. // the names array.
  8839. var newSources = new ArraySet();
  8840. var newNames = new ArraySet();
  8841. // Find mappings for the "sourceFile"
  8842. this._mappings.unsortedForEach(function (mapping) {
  8843. if (mapping.source === sourceFile && mapping.originalLine != null) {
  8844. // Check if it can be mapped by the source map, then update the mapping.
  8845. var original = aSourceMapConsumer.originalPositionFor({
  8846. line: mapping.originalLine,
  8847. column: mapping.originalColumn
  8848. });
  8849. if (original.source != null) {
  8850. // Copy mapping
  8851. mapping.source = original.source;
  8852. if (aSourceMapPath != null) {
  8853. mapping.source = util.join(aSourceMapPath, mapping.source);
  8854. }
  8855. if (sourceRoot != null) {
  8856. mapping.source = util.relative(sourceRoot, mapping.source);
  8857. }
  8858. mapping.originalLine = original.line;
  8859. mapping.originalColumn = original.column;
  8860. if (original.name != null) {
  8861. mapping.name = original.name;
  8862. }
  8863. }
  8864. }
  8865. var source = mapping.source;
  8866. if (source != null && !newSources.has(source)) {
  8867. newSources.add(source);
  8868. }
  8869. var name = mapping.name;
  8870. if (name != null && !newNames.has(name)) {
  8871. newNames.add(name);
  8872. }
  8873. }, this);
  8874. this._sources = newSources;
  8875. this._names = newNames;
  8876. // Copy sourcesContents of applied map.
  8877. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8878. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8879. if (content != null) {
  8880. if (aSourceMapPath != null) {
  8881. sourceFile = util.join(aSourceMapPath, sourceFile);
  8882. }
  8883. if (sourceRoot != null) {
  8884. sourceFile = util.relative(sourceRoot, sourceFile);
  8885. }
  8886. this.setSourceContent(sourceFile, content);
  8887. }
  8888. }, this);
  8889. };
  8890. /**
  8891. * A mapping can have one of the three levels of data:
  8892. *
  8893. * 1. Just the generated position.
  8894. * 2. The Generated position, original position, and original source.
  8895. * 3. Generated and original position, original source, as well as a name
  8896. * token.
  8897. *
  8898. * To maintain consistency, we validate that any new mapping being added falls
  8899. * in to one of these categories.
  8900. */
  8901. SourceMapGenerator.prototype._validateMapping =
  8902. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  8903. aName) {
  8904. // When aOriginal is truthy but has empty values for .line and .column,
  8905. // it is most likely a programmer error. In this case we throw a very
  8906. // specific error message to try to guide them the right way.
  8907. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  8908. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  8909. throw new Error(
  8910. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  8911. 'the original mapping entirely and only map the generated position. If so, pass ' +
  8912. 'null for the original mapping instead of an object with empty or null values.'
  8913. );
  8914. }
  8915. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8916. && aGenerated.line > 0 && aGenerated.column >= 0
  8917. && !aOriginal && !aSource && !aName) {
  8918. // Case 1.
  8919. return;
  8920. }
  8921. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8922. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  8923. && aGenerated.line > 0 && aGenerated.column >= 0
  8924. && aOriginal.line > 0 && aOriginal.column >= 0
  8925. && aSource) {
  8926. // Cases 2 and 3.
  8927. return;
  8928. }
  8929. else {
  8930. throw new Error('Invalid mapping: ' + JSON.stringify({
  8931. generated: aGenerated,
  8932. source: aSource,
  8933. original: aOriginal,
  8934. name: aName
  8935. }));
  8936. }
  8937. };
  8938. /**
  8939. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  8940. * specified by the source map format.
  8941. */
  8942. SourceMapGenerator.prototype._serializeMappings =
  8943. function SourceMapGenerator_serializeMappings() {
  8944. var previousGeneratedColumn = 0;
  8945. var previousGeneratedLine = 1;
  8946. var previousOriginalColumn = 0;
  8947. var previousOriginalLine = 0;
  8948. var previousName = 0;
  8949. var previousSource = 0;
  8950. var result = '';
  8951. var next;
  8952. var mapping;
  8953. var nameIdx;
  8954. var sourceIdx;
  8955. var mappings = this._mappings.toArray();
  8956. for (var i = 0, len = mappings.length; i < len; i++) {
  8957. mapping = mappings[i];
  8958. next = '';
  8959. if (mapping.generatedLine !== previousGeneratedLine) {
  8960. previousGeneratedColumn = 0;
  8961. while (mapping.generatedLine !== previousGeneratedLine) {
  8962. next += ';';
  8963. previousGeneratedLine++;
  8964. }
  8965. }
  8966. else {
  8967. if (i > 0) {
  8968. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  8969. continue;
  8970. }
  8971. next += ',';
  8972. }
  8973. }
  8974. next += base64VLQ.encode(mapping.generatedColumn
  8975. - previousGeneratedColumn);
  8976. previousGeneratedColumn = mapping.generatedColumn;
  8977. if (mapping.source != null) {
  8978. sourceIdx = this._sources.indexOf(mapping.source);
  8979. next += base64VLQ.encode(sourceIdx - previousSource);
  8980. previousSource = sourceIdx;
  8981. // lines are stored 0-based in SourceMap spec version 3
  8982. next += base64VLQ.encode(mapping.originalLine - 1
  8983. - previousOriginalLine);
  8984. previousOriginalLine = mapping.originalLine - 1;
  8985. next += base64VLQ.encode(mapping.originalColumn
  8986. - previousOriginalColumn);
  8987. previousOriginalColumn = mapping.originalColumn;
  8988. if (mapping.name != null) {
  8989. nameIdx = this._names.indexOf(mapping.name);
  8990. next += base64VLQ.encode(nameIdx - previousName);
  8991. previousName = nameIdx;
  8992. }
  8993. }
  8994. result += next;
  8995. }
  8996. return result;
  8997. };
  8998. SourceMapGenerator.prototype._generateSourcesContent =
  8999. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  9000. return aSources.map(function (source) {
  9001. if (!this._sourcesContents) {
  9002. return null;
  9003. }
  9004. if (aSourceRoot != null) {
  9005. source = util.relative(aSourceRoot, source);
  9006. }
  9007. var key = util.toSetString(source);
  9008. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  9009. ? this._sourcesContents[key]
  9010. : null;
  9011. }, this);
  9012. };
  9013. /**
  9014. * Externalize the source map.
  9015. */
  9016. SourceMapGenerator.prototype.toJSON =
  9017. function SourceMapGenerator_toJSON() {
  9018. var map = {
  9019. version: this._version,
  9020. sources: this._sources.toArray(),
  9021. names: this._names.toArray(),
  9022. mappings: this._serializeMappings()
  9023. };
  9024. if (this._file != null) {
  9025. map.file = this._file;
  9026. }
  9027. if (this._sourceRoot != null) {
  9028. map.sourceRoot = this._sourceRoot;
  9029. }
  9030. if (this._sourcesContents) {
  9031. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  9032. }
  9033. return map;
  9034. };
  9035. /**
  9036. * Render the source map being generated to a string.
  9037. */
  9038. SourceMapGenerator.prototype.toString =
  9039. function SourceMapGenerator_toString() {
  9040. return JSON.stringify(this.toJSON());
  9041. };
  9042. sourceMapGenerator.SourceMapGenerator = SourceMapGenerator;
  9043. return sourceMapGenerator;
  9044. }
  9045. var sourceMapConsumer = {};
  9046. var binarySearch = {};
  9047. /* -*- Mode: js; js-indent-level: 2; -*- */
  9048. var hasRequiredBinarySearch;
  9049. function requireBinarySearch () {
  9050. if (hasRequiredBinarySearch) return binarySearch;
  9051. hasRequiredBinarySearch = 1;
  9052. (function (exports$1) {
  9053. /*
  9054. * Copyright 2011 Mozilla Foundation and contributors
  9055. * Licensed under the New BSD license. See LICENSE or:
  9056. * http://opensource.org/licenses/BSD-3-Clause
  9057. */
  9058. exports$1.GREATEST_LOWER_BOUND = 1;
  9059. exports$1.LEAST_UPPER_BOUND = 2;
  9060. /**
  9061. * Recursive implementation of binary search.
  9062. *
  9063. * @param aLow Indices here and lower do not contain the needle.
  9064. * @param aHigh Indices here and higher do not contain the needle.
  9065. * @param aNeedle The element being searched for.
  9066. * @param aHaystack The non-empty array being searched.
  9067. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  9068. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  9069. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  9070. * closest element that is smaller than or greater than the one we are
  9071. * searching for, respectively, if the exact element cannot be found.
  9072. */
  9073. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  9074. // This function terminates when one of the following is true:
  9075. //
  9076. // 1. We find the exact element we are looking for.
  9077. //
  9078. // 2. We did not find the exact element, but we can return the index of
  9079. // the next-closest element.
  9080. //
  9081. // 3. We did not find the exact element, and there is no next-closest
  9082. // element than the one we are searching for, so we return -1.
  9083. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  9084. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  9085. if (cmp === 0) {
  9086. // Found the element we are looking for.
  9087. return mid;
  9088. }
  9089. else if (cmp > 0) {
  9090. // Our needle is greater than aHaystack[mid].
  9091. if (aHigh - mid > 1) {
  9092. // The element is in the upper half.
  9093. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  9094. }
  9095. // The exact needle element was not found in this haystack. Determine if
  9096. // we are in termination case (3) or (2) and return the appropriate thing.
  9097. if (aBias == exports$1.LEAST_UPPER_BOUND) {
  9098. return aHigh < aHaystack.length ? aHigh : -1;
  9099. } else {
  9100. return mid;
  9101. }
  9102. }
  9103. else {
  9104. // Our needle is less than aHaystack[mid].
  9105. if (mid - aLow > 1) {
  9106. // The element is in the lower half.
  9107. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  9108. }
  9109. // we are in termination case (3) or (2) and return the appropriate thing.
  9110. if (aBias == exports$1.LEAST_UPPER_BOUND) {
  9111. return mid;
  9112. } else {
  9113. return aLow < 0 ? -1 : aLow;
  9114. }
  9115. }
  9116. }
  9117. /**
  9118. * This is an implementation of binary search which will always try and return
  9119. * the index of the closest element if there is no exact hit. This is because
  9120. * mappings between original and generated line/col pairs are single points,
  9121. * and there is an implicit region between each of them, so a miss just means
  9122. * that you aren't on the very start of a region.
  9123. *
  9124. * @param aNeedle The element you are looking for.
  9125. * @param aHaystack The array that is being searched.
  9126. * @param aCompare A function which takes the needle and an element in the
  9127. * array and returns -1, 0, or 1 depending on whether the needle is less
  9128. * than, equal to, or greater than the element, respectively.
  9129. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  9130. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  9131. * closest element that is smaller than or greater than the one we are
  9132. * searching for, respectively, if the exact element cannot be found.
  9133. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  9134. */
  9135. exports$1.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  9136. if (aHaystack.length === 0) {
  9137. return -1;
  9138. }
  9139. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  9140. aCompare, aBias || exports$1.GREATEST_LOWER_BOUND);
  9141. if (index < 0) {
  9142. return -1;
  9143. }
  9144. // We have found either the exact element, or the next-closest element than
  9145. // the one we are searching for. However, there may be more than one such
  9146. // element. Make sure we always return the smallest of these.
  9147. while (index - 1 >= 0) {
  9148. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  9149. break;
  9150. }
  9151. --index;
  9152. }
  9153. return index;
  9154. };
  9155. } (binarySearch));
  9156. return binarySearch;
  9157. }
  9158. var quickSort = {};
  9159. /* -*- Mode: js; js-indent-level: 2; -*- */
  9160. var hasRequiredQuickSort;
  9161. function requireQuickSort () {
  9162. if (hasRequiredQuickSort) return quickSort;
  9163. hasRequiredQuickSort = 1;
  9164. /*
  9165. * Copyright 2011 Mozilla Foundation and contributors
  9166. * Licensed under the New BSD license. See LICENSE or:
  9167. * http://opensource.org/licenses/BSD-3-Clause
  9168. */
  9169. // It turns out that some (most?) JavaScript engines don't self-host
  9170. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  9171. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  9172. // custom comparator function, calling back and forth between the VM's C++ and
  9173. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  9174. // worse generated code for the comparator function than would be optimal. In
  9175. // fact, when sorting with a comparator, these costs outweigh the benefits of
  9176. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  9177. // a ~3500ms mean speed-up in `bench/bench.html`.
  9178. /**
  9179. * Swap the elements indexed by `x` and `y` in the array `ary`.
  9180. *
  9181. * @param {Array} ary
  9182. * The array.
  9183. * @param {Number} x
  9184. * The index of the first item.
  9185. * @param {Number} y
  9186. * The index of the second item.
  9187. */
  9188. function swap(ary, x, y) {
  9189. var temp = ary[x];
  9190. ary[x] = ary[y];
  9191. ary[y] = temp;
  9192. }
  9193. /**
  9194. * Returns a random integer within the range `low .. high` inclusive.
  9195. *
  9196. * @param {Number} low
  9197. * The lower bound on the range.
  9198. * @param {Number} high
  9199. * The upper bound on the range.
  9200. */
  9201. function randomIntInRange(low, high) {
  9202. return Math.round(low + (Math.random() * (high - low)));
  9203. }
  9204. /**
  9205. * The Quick Sort algorithm.
  9206. *
  9207. * @param {Array} ary
  9208. * An array to sort.
  9209. * @param {function} comparator
  9210. * Function to use to compare two items.
  9211. * @param {Number} p
  9212. * Start index of the array
  9213. * @param {Number} r
  9214. * End index of the array
  9215. */
  9216. function doQuickSort(ary, comparator, p, r) {
  9217. // If our lower bound is less than our upper bound, we (1) partition the
  9218. // array into two pieces and (2) recurse on each half. If it is not, this is
  9219. // the empty array and our base case.
  9220. if (p < r) {
  9221. // (1) Partitioning.
  9222. //
  9223. // The partitioning chooses a pivot between `p` and `r` and moves all
  9224. // elements that are less than or equal to the pivot to the before it, and
  9225. // all the elements that are greater than it after it. The effect is that
  9226. // once partition is done, the pivot is in the exact place it will be when
  9227. // the array is put in sorted order, and it will not need to be moved
  9228. // again. This runs in O(n) time.
  9229. // Always choose a random pivot so that an input array which is reverse
  9230. // sorted does not cause O(n^2) running time.
  9231. var pivotIndex = randomIntInRange(p, r);
  9232. var i = p - 1;
  9233. swap(ary, pivotIndex, r);
  9234. var pivot = ary[r];
  9235. // Immediately after `j` is incremented in this loop, the following hold
  9236. // true:
  9237. //
  9238. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  9239. //
  9240. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  9241. for (var j = p; j < r; j++) {
  9242. if (comparator(ary[j], pivot) <= 0) {
  9243. i += 1;
  9244. swap(ary, i, j);
  9245. }
  9246. }
  9247. swap(ary, i + 1, j);
  9248. var q = i + 1;
  9249. // (2) Recurse on each half.
  9250. doQuickSort(ary, comparator, p, q - 1);
  9251. doQuickSort(ary, comparator, q + 1, r);
  9252. }
  9253. }
  9254. /**
  9255. * Sort the given array in-place with the given comparator function.
  9256. *
  9257. * @param {Array} ary
  9258. * An array to sort.
  9259. * @param {function} comparator
  9260. * Function to use to compare two items.
  9261. */
  9262. quickSort.quickSort = function (ary, comparator) {
  9263. doQuickSort(ary, comparator, 0, ary.length - 1);
  9264. };
  9265. return quickSort;
  9266. }
  9267. /* -*- Mode: js; js-indent-level: 2; -*- */
  9268. var hasRequiredSourceMapConsumer;
  9269. function requireSourceMapConsumer () {
  9270. if (hasRequiredSourceMapConsumer) return sourceMapConsumer;
  9271. hasRequiredSourceMapConsumer = 1;
  9272. /*
  9273. * Copyright 2011 Mozilla Foundation and contributors
  9274. * Licensed under the New BSD license. See LICENSE or:
  9275. * http://opensource.org/licenses/BSD-3-Clause
  9276. */
  9277. var util = /*@__PURE__*/ requireUtil$1();
  9278. var binarySearch = /*@__PURE__*/ requireBinarySearch();
  9279. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  9280. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  9281. var quickSort = /*@__PURE__*/ requireQuickSort().quickSort;
  9282. function SourceMapConsumer(aSourceMap, aSourceMapURL) {
  9283. var sourceMap = aSourceMap;
  9284. if (typeof aSourceMap === 'string') {
  9285. sourceMap = util.parseSourceMapInput(aSourceMap);
  9286. }
  9287. return sourceMap.sections != null
  9288. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  9289. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  9290. }
  9291. SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  9292. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  9293. };
  9294. /**
  9295. * The version of the source mapping spec that we are consuming.
  9296. */
  9297. SourceMapConsumer.prototype._version = 3;
  9298. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  9299. // parsed mapping coordinates from the source map's "mappings" attribute. They
  9300. // are lazily instantiated, accessed via the `_generatedMappings` and
  9301. // `_originalMappings` getters respectively, and we only parse the mappings
  9302. // and create these arrays once queried for a source location. We jump through
  9303. // these hoops because there can be many thousands of mappings, and parsing
  9304. // them is expensive, so we only want to do it if we must.
  9305. //
  9306. // Each object in the arrays is of the form:
  9307. //
  9308. // {
  9309. // generatedLine: The line number in the generated code,
  9310. // generatedColumn: The column number in the generated code,
  9311. // source: The path to the original source file that generated this
  9312. // chunk of code,
  9313. // originalLine: The line number in the original source that
  9314. // corresponds to this chunk of generated code,
  9315. // originalColumn: The column number in the original source that
  9316. // corresponds to this chunk of generated code,
  9317. // name: The name of the original symbol which generated this chunk of
  9318. // code.
  9319. // }
  9320. //
  9321. // All properties except for `generatedLine` and `generatedColumn` can be
  9322. // `null`.
  9323. //
  9324. // `_generatedMappings` is ordered by the generated positions.
  9325. //
  9326. // `_originalMappings` is ordered by the original positions.
  9327. SourceMapConsumer.prototype.__generatedMappings = null;
  9328. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  9329. configurable: true,
  9330. enumerable: true,
  9331. get: function () {
  9332. if (!this.__generatedMappings) {
  9333. this._parseMappings(this._mappings, this.sourceRoot);
  9334. }
  9335. return this.__generatedMappings;
  9336. }
  9337. });
  9338. SourceMapConsumer.prototype.__originalMappings = null;
  9339. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  9340. configurable: true,
  9341. enumerable: true,
  9342. get: function () {
  9343. if (!this.__originalMappings) {
  9344. this._parseMappings(this._mappings, this.sourceRoot);
  9345. }
  9346. return this.__originalMappings;
  9347. }
  9348. });
  9349. SourceMapConsumer.prototype._charIsMappingSeparator =
  9350. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  9351. var c = aStr.charAt(index);
  9352. return c === ";" || c === ",";
  9353. };
  9354. /**
  9355. * Parse the mappings in a string in to a data structure which we can easily
  9356. * query (the ordered arrays in the `this.__generatedMappings` and
  9357. * `this.__originalMappings` properties).
  9358. */
  9359. SourceMapConsumer.prototype._parseMappings =
  9360. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9361. throw new Error("Subclasses must implement _parseMappings");
  9362. };
  9363. SourceMapConsumer.GENERATED_ORDER = 1;
  9364. SourceMapConsumer.ORIGINAL_ORDER = 2;
  9365. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  9366. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  9367. /**
  9368. * Iterate over each mapping between an original source/line/column and a
  9369. * generated line/column in this source map.
  9370. *
  9371. * @param Function aCallback
  9372. * The function that is called with each mapping.
  9373. * @param Object aContext
  9374. * Optional. If specified, this object will be the value of `this` every
  9375. * time that `aCallback` is called.
  9376. * @param aOrder
  9377. * Either `SourceMapConsumer.GENERATED_ORDER` or
  9378. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  9379. * iterate over the mappings sorted by the generated file's line/column
  9380. * order or the original's source/line/column order, respectively. Defaults to
  9381. * `SourceMapConsumer.GENERATED_ORDER`.
  9382. */
  9383. SourceMapConsumer.prototype.eachMapping =
  9384. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  9385. var context = aContext || null;
  9386. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  9387. var mappings;
  9388. switch (order) {
  9389. case SourceMapConsumer.GENERATED_ORDER:
  9390. mappings = this._generatedMappings;
  9391. break;
  9392. case SourceMapConsumer.ORIGINAL_ORDER:
  9393. mappings = this._originalMappings;
  9394. break;
  9395. default:
  9396. throw new Error("Unknown order of iteration.");
  9397. }
  9398. var sourceRoot = this.sourceRoot;
  9399. mappings.map(function (mapping) {
  9400. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  9401. source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  9402. return {
  9403. source: source,
  9404. generatedLine: mapping.generatedLine,
  9405. generatedColumn: mapping.generatedColumn,
  9406. originalLine: mapping.originalLine,
  9407. originalColumn: mapping.originalColumn,
  9408. name: mapping.name === null ? null : this._names.at(mapping.name)
  9409. };
  9410. }, this).forEach(aCallback, context);
  9411. };
  9412. /**
  9413. * Returns all generated line and column information for the original source,
  9414. * line, and column provided. If no column is provided, returns all mappings
  9415. * corresponding to a either the line we are searching for or the next
  9416. * closest line that has any mappings. Otherwise, returns all mappings
  9417. * corresponding to the given line and either the column we are searching for
  9418. * or the next closest column that has any offsets.
  9419. *
  9420. * The only argument is an object with the following properties:
  9421. *
  9422. * - source: The filename of the original source.
  9423. * - line: The line number in the original source. The line number is 1-based.
  9424. * - column: Optional. the column number in the original source.
  9425. * The column number is 0-based.
  9426. *
  9427. * and an array of objects is returned, each with the following properties:
  9428. *
  9429. * - line: The line number in the generated source, or null. The
  9430. * line number is 1-based.
  9431. * - column: The column number in the generated source, or null.
  9432. * The column number is 0-based.
  9433. */
  9434. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  9435. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  9436. var line = util.getArg(aArgs, 'line');
  9437. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  9438. // returns the index of the closest mapping less than the needle. By
  9439. // setting needle.originalColumn to 0, we thus find the last mapping for
  9440. // the given line, provided such a mapping exists.
  9441. var needle = {
  9442. source: util.getArg(aArgs, 'source'),
  9443. originalLine: line,
  9444. originalColumn: util.getArg(aArgs, 'column', 0)
  9445. };
  9446. needle.source = this._findSourceIndex(needle.source);
  9447. if (needle.source < 0) {
  9448. return [];
  9449. }
  9450. var mappings = [];
  9451. var index = this._findMapping(needle,
  9452. this._originalMappings,
  9453. "originalLine",
  9454. "originalColumn",
  9455. util.compareByOriginalPositions,
  9456. binarySearch.LEAST_UPPER_BOUND);
  9457. if (index >= 0) {
  9458. var mapping = this._originalMappings[index];
  9459. if (aArgs.column === undefined) {
  9460. var originalLine = mapping.originalLine;
  9461. // Iterate until either we run out of mappings, or we run into
  9462. // a mapping for a different line than the one we found. Since
  9463. // mappings are sorted, this is guaranteed to find all mappings for
  9464. // the line we found.
  9465. while (mapping && mapping.originalLine === originalLine) {
  9466. mappings.push({
  9467. line: util.getArg(mapping, 'generatedLine', null),
  9468. column: util.getArg(mapping, 'generatedColumn', null),
  9469. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9470. });
  9471. mapping = this._originalMappings[++index];
  9472. }
  9473. } else {
  9474. var originalColumn = mapping.originalColumn;
  9475. // Iterate until either we run out of mappings, or we run into
  9476. // a mapping for a different line than the one we were searching for.
  9477. // Since mappings are sorted, this is guaranteed to find all mappings for
  9478. // the line we are searching for.
  9479. while (mapping &&
  9480. mapping.originalLine === line &&
  9481. mapping.originalColumn == originalColumn) {
  9482. mappings.push({
  9483. line: util.getArg(mapping, 'generatedLine', null),
  9484. column: util.getArg(mapping, 'generatedColumn', null),
  9485. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9486. });
  9487. mapping = this._originalMappings[++index];
  9488. }
  9489. }
  9490. }
  9491. return mappings;
  9492. };
  9493. sourceMapConsumer.SourceMapConsumer = SourceMapConsumer;
  9494. /**
  9495. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  9496. * query for information about the original file positions by giving it a file
  9497. * position in the generated source.
  9498. *
  9499. * The first parameter is the raw source map (either as a JSON string, or
  9500. * already parsed to an object). According to the spec, source maps have the
  9501. * following attributes:
  9502. *
  9503. * - version: Which version of the source map spec this map is following.
  9504. * - sources: An array of URLs to the original source files.
  9505. * - names: An array of identifiers which can be referrenced by individual mappings.
  9506. * - sourceRoot: Optional. The URL root from which all sources are relative.
  9507. * - sourcesContent: Optional. An array of contents of the original source files.
  9508. * - mappings: A string of base64 VLQs which contain the actual mappings.
  9509. * - file: Optional. The generated file this source map is associated with.
  9510. *
  9511. * Here is an example source map, taken from the source map spec[0]:
  9512. *
  9513. * {
  9514. * version : 3,
  9515. * file: "out.js",
  9516. * sourceRoot : "",
  9517. * sources: ["foo.js", "bar.js"],
  9518. * names: ["src", "maps", "are", "fun"],
  9519. * mappings: "AA,AB;;ABCDE;"
  9520. * }
  9521. *
  9522. * The second parameter, if given, is a string whose value is the URL
  9523. * at which the source map was found. This URL is used to compute the
  9524. * sources array.
  9525. *
  9526. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  9527. */
  9528. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  9529. var sourceMap = aSourceMap;
  9530. if (typeof aSourceMap === 'string') {
  9531. sourceMap = util.parseSourceMapInput(aSourceMap);
  9532. }
  9533. var version = util.getArg(sourceMap, 'version');
  9534. var sources = util.getArg(sourceMap, 'sources');
  9535. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  9536. // requires the array) to play nice here.
  9537. var names = util.getArg(sourceMap, 'names', []);
  9538. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  9539. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  9540. var mappings = util.getArg(sourceMap, 'mappings');
  9541. var file = util.getArg(sourceMap, 'file', null);
  9542. // Once again, Sass deviates from the spec and supplies the version as a
  9543. // string rather than a number, so we use loose equality checking here.
  9544. if (version != this._version) {
  9545. throw new Error('Unsupported version: ' + version);
  9546. }
  9547. if (sourceRoot) {
  9548. sourceRoot = util.normalize(sourceRoot);
  9549. }
  9550. sources = sources
  9551. .map(String)
  9552. // Some source maps produce relative source paths like "./foo.js" instead of
  9553. // "foo.js". Normalize these first so that future comparisons will succeed.
  9554. // See bugzil.la/1090768.
  9555. .map(util.normalize)
  9556. // Always ensure that absolute sources are internally stored relative to
  9557. // the source root, if the source root is absolute. Not doing this would
  9558. // be particularly problematic when the source root is a prefix of the
  9559. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  9560. .map(function (source) {
  9561. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  9562. ? util.relative(sourceRoot, source)
  9563. : source;
  9564. });
  9565. // Pass `true` below to allow duplicate names and sources. While source maps
  9566. // are intended to be compressed and deduplicated, the TypeScript compiler
  9567. // sometimes generates source maps with duplicates in them. See Github issue
  9568. // #72 and bugzil.la/889492.
  9569. this._names = ArraySet.fromArray(names.map(String), true);
  9570. this._sources = ArraySet.fromArray(sources, true);
  9571. this._absoluteSources = this._sources.toArray().map(function (s) {
  9572. return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
  9573. });
  9574. this.sourceRoot = sourceRoot;
  9575. this.sourcesContent = sourcesContent;
  9576. this._mappings = mappings;
  9577. this._sourceMapURL = aSourceMapURL;
  9578. this.file = file;
  9579. }
  9580. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  9581. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  9582. /**
  9583. * Utility function to find the index of a source. Returns -1 if not
  9584. * found.
  9585. */
  9586. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  9587. var relativeSource = aSource;
  9588. if (this.sourceRoot != null) {
  9589. relativeSource = util.relative(this.sourceRoot, relativeSource);
  9590. }
  9591. if (this._sources.has(relativeSource)) {
  9592. return this._sources.indexOf(relativeSource);
  9593. }
  9594. // Maybe aSource is an absolute URL as returned by |sources|. In
  9595. // this case we can't simply undo the transform.
  9596. var i;
  9597. for (i = 0; i < this._absoluteSources.length; ++i) {
  9598. if (this._absoluteSources[i] == aSource) {
  9599. return i;
  9600. }
  9601. }
  9602. return -1;
  9603. };
  9604. /**
  9605. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  9606. *
  9607. * @param SourceMapGenerator aSourceMap
  9608. * The source map that will be consumed.
  9609. * @param String aSourceMapURL
  9610. * The URL at which the source map can be found (optional)
  9611. * @returns BasicSourceMapConsumer
  9612. */
  9613. BasicSourceMapConsumer.fromSourceMap =
  9614. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  9615. var smc = Object.create(BasicSourceMapConsumer.prototype);
  9616. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  9617. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  9618. smc.sourceRoot = aSourceMap._sourceRoot;
  9619. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  9620. smc.sourceRoot);
  9621. smc.file = aSourceMap._file;
  9622. smc._sourceMapURL = aSourceMapURL;
  9623. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  9624. return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  9625. });
  9626. // Because we are modifying the entries (by converting string sources and
  9627. // names to indices into the sources and names ArraySets), we have to make
  9628. // a copy of the entry or else bad things happen. Shared mutable state
  9629. // strikes again! See github issue #191.
  9630. var generatedMappings = aSourceMap._mappings.toArray().slice();
  9631. var destGeneratedMappings = smc.__generatedMappings = [];
  9632. var destOriginalMappings = smc.__originalMappings = [];
  9633. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  9634. var srcMapping = generatedMappings[i];
  9635. var destMapping = new Mapping;
  9636. destMapping.generatedLine = srcMapping.generatedLine;
  9637. destMapping.generatedColumn = srcMapping.generatedColumn;
  9638. if (srcMapping.source) {
  9639. destMapping.source = sources.indexOf(srcMapping.source);
  9640. destMapping.originalLine = srcMapping.originalLine;
  9641. destMapping.originalColumn = srcMapping.originalColumn;
  9642. if (srcMapping.name) {
  9643. destMapping.name = names.indexOf(srcMapping.name);
  9644. }
  9645. destOriginalMappings.push(destMapping);
  9646. }
  9647. destGeneratedMappings.push(destMapping);
  9648. }
  9649. quickSort(smc.__originalMappings, util.compareByOriginalPositions);
  9650. return smc;
  9651. };
  9652. /**
  9653. * The version of the source mapping spec that we are consuming.
  9654. */
  9655. BasicSourceMapConsumer.prototype._version = 3;
  9656. /**
  9657. * The list of original sources.
  9658. */
  9659. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  9660. get: function () {
  9661. return this._absoluteSources.slice();
  9662. }
  9663. });
  9664. /**
  9665. * Provide the JIT with a nice shape / hidden class.
  9666. */
  9667. function Mapping() {
  9668. this.generatedLine = 0;
  9669. this.generatedColumn = 0;
  9670. this.source = null;
  9671. this.originalLine = null;
  9672. this.originalColumn = null;
  9673. this.name = null;
  9674. }
  9675. /**
  9676. * Parse the mappings in a string in to a data structure which we can easily
  9677. * query (the ordered arrays in the `this.__generatedMappings` and
  9678. * `this.__originalMappings` properties).
  9679. */
  9680. BasicSourceMapConsumer.prototype._parseMappings =
  9681. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9682. var generatedLine = 1;
  9683. var previousGeneratedColumn = 0;
  9684. var previousOriginalLine = 0;
  9685. var previousOriginalColumn = 0;
  9686. var previousSource = 0;
  9687. var previousName = 0;
  9688. var length = aStr.length;
  9689. var index = 0;
  9690. var cachedSegments = {};
  9691. var temp = {};
  9692. var originalMappings = [];
  9693. var generatedMappings = [];
  9694. var mapping, str, segment, end, value;
  9695. while (index < length) {
  9696. if (aStr.charAt(index) === ';') {
  9697. generatedLine++;
  9698. index++;
  9699. previousGeneratedColumn = 0;
  9700. }
  9701. else if (aStr.charAt(index) === ',') {
  9702. index++;
  9703. }
  9704. else {
  9705. mapping = new Mapping();
  9706. mapping.generatedLine = generatedLine;
  9707. // Because each offset is encoded relative to the previous one,
  9708. // many segments often have the same encoding. We can exploit this
  9709. // fact by caching the parsed variable length fields of each segment,
  9710. // allowing us to avoid a second parse if we encounter the same
  9711. // segment again.
  9712. for (end = index; end < length; end++) {
  9713. if (this._charIsMappingSeparator(aStr, end)) {
  9714. break;
  9715. }
  9716. }
  9717. str = aStr.slice(index, end);
  9718. segment = cachedSegments[str];
  9719. if (segment) {
  9720. index += str.length;
  9721. } else {
  9722. segment = [];
  9723. while (index < end) {
  9724. base64VLQ.decode(aStr, index, temp);
  9725. value = temp.value;
  9726. index = temp.rest;
  9727. segment.push(value);
  9728. }
  9729. if (segment.length === 2) {
  9730. throw new Error('Found a source, but no line and column');
  9731. }
  9732. if (segment.length === 3) {
  9733. throw new Error('Found a source and line, but no column');
  9734. }
  9735. cachedSegments[str] = segment;
  9736. }
  9737. // Generated column.
  9738. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  9739. previousGeneratedColumn = mapping.generatedColumn;
  9740. if (segment.length > 1) {
  9741. // Original source.
  9742. mapping.source = previousSource + segment[1];
  9743. previousSource += segment[1];
  9744. // Original line.
  9745. mapping.originalLine = previousOriginalLine + segment[2];
  9746. previousOriginalLine = mapping.originalLine;
  9747. // Lines are stored 0-based
  9748. mapping.originalLine += 1;
  9749. // Original column.
  9750. mapping.originalColumn = previousOriginalColumn + segment[3];
  9751. previousOriginalColumn = mapping.originalColumn;
  9752. if (segment.length > 4) {
  9753. // Original name.
  9754. mapping.name = previousName + segment[4];
  9755. previousName += segment[4];
  9756. }
  9757. }
  9758. generatedMappings.push(mapping);
  9759. if (typeof mapping.originalLine === 'number') {
  9760. originalMappings.push(mapping);
  9761. }
  9762. }
  9763. }
  9764. quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
  9765. this.__generatedMappings = generatedMappings;
  9766. quickSort(originalMappings, util.compareByOriginalPositions);
  9767. this.__originalMappings = originalMappings;
  9768. };
  9769. /**
  9770. * Find the mapping that best matches the hypothetical "needle" mapping that
  9771. * we are searching for in the given "haystack" of mappings.
  9772. */
  9773. BasicSourceMapConsumer.prototype._findMapping =
  9774. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  9775. aColumnName, aComparator, aBias) {
  9776. // To return the position we are searching for, we must first find the
  9777. // mapping for the given position and then return the opposite position it
  9778. // points to. Because the mappings are sorted, we can use binary search to
  9779. // find the best mapping.
  9780. if (aNeedle[aLineName] <= 0) {
  9781. throw new TypeError('Line must be greater than or equal to 1, got '
  9782. + aNeedle[aLineName]);
  9783. }
  9784. if (aNeedle[aColumnName] < 0) {
  9785. throw new TypeError('Column must be greater than or equal to 0, got '
  9786. + aNeedle[aColumnName]);
  9787. }
  9788. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  9789. };
  9790. /**
  9791. * Compute the last column for each generated mapping. The last column is
  9792. * inclusive.
  9793. */
  9794. BasicSourceMapConsumer.prototype.computeColumnSpans =
  9795. function SourceMapConsumer_computeColumnSpans() {
  9796. for (var index = 0; index < this._generatedMappings.length; ++index) {
  9797. var mapping = this._generatedMappings[index];
  9798. // Mappings do not contain a field for the last generated columnt. We
  9799. // can come up with an optimistic estimate, however, by assuming that
  9800. // mappings are contiguous (i.e. given two consecutive mappings, the
  9801. // first mapping ends where the second one starts).
  9802. if (index + 1 < this._generatedMappings.length) {
  9803. var nextMapping = this._generatedMappings[index + 1];
  9804. if (mapping.generatedLine === nextMapping.generatedLine) {
  9805. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  9806. continue;
  9807. }
  9808. }
  9809. // The last mapping for each line spans the entire line.
  9810. mapping.lastGeneratedColumn = Infinity;
  9811. }
  9812. };
  9813. /**
  9814. * Returns the original source, line, and column information for the generated
  9815. * source's line and column positions provided. The only argument is an object
  9816. * with the following properties:
  9817. *
  9818. * - line: The line number in the generated source. The line number
  9819. * is 1-based.
  9820. * - column: The column number in the generated source. The column
  9821. * number is 0-based.
  9822. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  9823. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  9824. * closest element that is smaller than or greater than the one we are
  9825. * searching for, respectively, if the exact element cannot be found.
  9826. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  9827. *
  9828. * and an object is returned with the following properties:
  9829. *
  9830. * - source: The original source file, or null.
  9831. * - line: The line number in the original source, or null. The
  9832. * line number is 1-based.
  9833. * - column: The column number in the original source, or null. The
  9834. * column number is 0-based.
  9835. * - name: The original identifier, or null.
  9836. */
  9837. BasicSourceMapConsumer.prototype.originalPositionFor =
  9838. function SourceMapConsumer_originalPositionFor(aArgs) {
  9839. var needle = {
  9840. generatedLine: util.getArg(aArgs, 'line'),
  9841. generatedColumn: util.getArg(aArgs, 'column')
  9842. };
  9843. var index = this._findMapping(
  9844. needle,
  9845. this._generatedMappings,
  9846. "generatedLine",
  9847. "generatedColumn",
  9848. util.compareByGeneratedPositionsDeflated,
  9849. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  9850. );
  9851. if (index >= 0) {
  9852. var mapping = this._generatedMappings[index];
  9853. if (mapping.generatedLine === needle.generatedLine) {
  9854. var source = util.getArg(mapping, 'source', null);
  9855. if (source !== null) {
  9856. source = this._sources.at(source);
  9857. source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  9858. }
  9859. var name = util.getArg(mapping, 'name', null);
  9860. if (name !== null) {
  9861. name = this._names.at(name);
  9862. }
  9863. return {
  9864. source: source,
  9865. line: util.getArg(mapping, 'originalLine', null),
  9866. column: util.getArg(mapping, 'originalColumn', null),
  9867. name: name
  9868. };
  9869. }
  9870. }
  9871. return {
  9872. source: null,
  9873. line: null,
  9874. column: null,
  9875. name: null
  9876. };
  9877. };
  9878. /**
  9879. * Return true if we have the source content for every source in the source
  9880. * map, false otherwise.
  9881. */
  9882. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  9883. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  9884. if (!this.sourcesContent) {
  9885. return false;
  9886. }
  9887. return this.sourcesContent.length >= this._sources.size() &&
  9888. !this.sourcesContent.some(function (sc) { return sc == null; });
  9889. };
  9890. /**
  9891. * Returns the original source content. The only argument is the url of the
  9892. * original source file. Returns null if no original source content is
  9893. * available.
  9894. */
  9895. BasicSourceMapConsumer.prototype.sourceContentFor =
  9896. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  9897. if (!this.sourcesContent) {
  9898. return null;
  9899. }
  9900. var index = this._findSourceIndex(aSource);
  9901. if (index >= 0) {
  9902. return this.sourcesContent[index];
  9903. }
  9904. var relativeSource = aSource;
  9905. if (this.sourceRoot != null) {
  9906. relativeSource = util.relative(this.sourceRoot, relativeSource);
  9907. }
  9908. var url;
  9909. if (this.sourceRoot != null
  9910. && (url = util.urlParse(this.sourceRoot))) {
  9911. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  9912. // many users. We can help them out when they expect file:// URIs to
  9913. // behave like it would if they were running a local HTTP server. See
  9914. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  9915. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  9916. if (url.scheme == "file"
  9917. && this._sources.has(fileUriAbsPath)) {
  9918. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  9919. }
  9920. if ((!url.path || url.path == "/")
  9921. && this._sources.has("/" + relativeSource)) {
  9922. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  9923. }
  9924. }
  9925. // This function is used recursively from
  9926. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  9927. // don't want to throw if we can't find the source - we just want to
  9928. // return null, so we provide a flag to exit gracefully.
  9929. if (nullOnMissing) {
  9930. return null;
  9931. }
  9932. else {
  9933. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  9934. }
  9935. };
  9936. /**
  9937. * Returns the generated line and column information for the original source,
  9938. * line, and column positions provided. The only argument is an object with
  9939. * the following properties:
  9940. *
  9941. * - source: The filename of the original source.
  9942. * - line: The line number in the original source. The line number
  9943. * is 1-based.
  9944. * - column: The column number in the original source. The column
  9945. * number is 0-based.
  9946. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  9947. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  9948. * closest element that is smaller than or greater than the one we are
  9949. * searching for, respectively, if the exact element cannot be found.
  9950. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  9951. *
  9952. * and an object is returned with the following properties:
  9953. *
  9954. * - line: The line number in the generated source, or null. The
  9955. * line number is 1-based.
  9956. * - column: The column number in the generated source, or null.
  9957. * The column number is 0-based.
  9958. */
  9959. BasicSourceMapConsumer.prototype.generatedPositionFor =
  9960. function SourceMapConsumer_generatedPositionFor(aArgs) {
  9961. var source = util.getArg(aArgs, 'source');
  9962. source = this._findSourceIndex(source);
  9963. if (source < 0) {
  9964. return {
  9965. line: null,
  9966. column: null,
  9967. lastColumn: null
  9968. };
  9969. }
  9970. var needle = {
  9971. source: source,
  9972. originalLine: util.getArg(aArgs, 'line'),
  9973. originalColumn: util.getArg(aArgs, 'column')
  9974. };
  9975. var index = this._findMapping(
  9976. needle,
  9977. this._originalMappings,
  9978. "originalLine",
  9979. "originalColumn",
  9980. util.compareByOriginalPositions,
  9981. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  9982. );
  9983. if (index >= 0) {
  9984. var mapping = this._originalMappings[index];
  9985. if (mapping.source === needle.source) {
  9986. return {
  9987. line: util.getArg(mapping, 'generatedLine', null),
  9988. column: util.getArg(mapping, 'generatedColumn', null),
  9989. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9990. };
  9991. }
  9992. }
  9993. return {
  9994. line: null,
  9995. column: null,
  9996. lastColumn: null
  9997. };
  9998. };
  9999. sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer;
  10000. /**
  10001. * An IndexedSourceMapConsumer instance represents a parsed source map which
  10002. * we can query for information. It differs from BasicSourceMapConsumer in
  10003. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  10004. * input.
  10005. *
  10006. * The first parameter is a raw source map (either as a JSON string, or already
  10007. * parsed to an object). According to the spec for indexed source maps, they
  10008. * have the following attributes:
  10009. *
  10010. * - version: Which version of the source map spec this map is following.
  10011. * - file: Optional. The generated file this source map is associated with.
  10012. * - sections: A list of section definitions.
  10013. *
  10014. * Each value under the "sections" field has two fields:
  10015. * - offset: The offset into the original specified at which this section
  10016. * begins to apply, defined as an object with a "line" and "column"
  10017. * field.
  10018. * - map: A source map definition. This source map could also be indexed,
  10019. * but doesn't have to be.
  10020. *
  10021. * Instead of the "map" field, it's also possible to have a "url" field
  10022. * specifying a URL to retrieve a source map from, but that's currently
  10023. * unsupported.
  10024. *
  10025. * Here's an example source map, taken from the source map spec[0], but
  10026. * modified to omit a section which uses the "url" field.
  10027. *
  10028. * {
  10029. * version : 3,
  10030. * file: "app.js",
  10031. * sections: [{
  10032. * offset: {line:100, column:10},
  10033. * map: {
  10034. * version : 3,
  10035. * file: "section.js",
  10036. * sources: ["foo.js", "bar.js"],
  10037. * names: ["src", "maps", "are", "fun"],
  10038. * mappings: "AAAA,E;;ABCDE;"
  10039. * }
  10040. * }],
  10041. * }
  10042. *
  10043. * The second parameter, if given, is a string whose value is the URL
  10044. * at which the source map was found. This URL is used to compute the
  10045. * sources array.
  10046. *
  10047. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  10048. */
  10049. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  10050. var sourceMap = aSourceMap;
  10051. if (typeof aSourceMap === 'string') {
  10052. sourceMap = util.parseSourceMapInput(aSourceMap);
  10053. }
  10054. var version = util.getArg(sourceMap, 'version');
  10055. var sections = util.getArg(sourceMap, 'sections');
  10056. if (version != this._version) {
  10057. throw new Error('Unsupported version: ' + version);
  10058. }
  10059. this._sources = new ArraySet();
  10060. this._names = new ArraySet();
  10061. var lastOffset = {
  10062. line: -1,
  10063. column: 0
  10064. };
  10065. this._sections = sections.map(function (s) {
  10066. if (s.url) {
  10067. // The url field will require support for asynchronicity.
  10068. // See https://github.com/mozilla/source-map/issues/16
  10069. throw new Error('Support for url field in sections not implemented.');
  10070. }
  10071. var offset = util.getArg(s, 'offset');
  10072. var offsetLine = util.getArg(offset, 'line');
  10073. var offsetColumn = util.getArg(offset, 'column');
  10074. if (offsetLine < lastOffset.line ||
  10075. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  10076. throw new Error('Section offsets must be ordered and non-overlapping.');
  10077. }
  10078. lastOffset = offset;
  10079. return {
  10080. generatedOffset: {
  10081. // The offset fields are 0-based, but we use 1-based indices when
  10082. // encoding/decoding from VLQ.
  10083. generatedLine: offsetLine + 1,
  10084. generatedColumn: offsetColumn + 1
  10085. },
  10086. consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
  10087. }
  10088. });
  10089. }
  10090. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  10091. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  10092. /**
  10093. * The version of the source mapping spec that we are consuming.
  10094. */
  10095. IndexedSourceMapConsumer.prototype._version = 3;
  10096. /**
  10097. * The list of original sources.
  10098. */
  10099. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  10100. get: function () {
  10101. var sources = [];
  10102. for (var i = 0; i < this._sections.length; i++) {
  10103. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  10104. sources.push(this._sections[i].consumer.sources[j]);
  10105. }
  10106. }
  10107. return sources;
  10108. }
  10109. });
  10110. /**
  10111. * Returns the original source, line, and column information for the generated
  10112. * source's line and column positions provided. The only argument is an object
  10113. * with the following properties:
  10114. *
  10115. * - line: The line number in the generated source. The line number
  10116. * is 1-based.
  10117. * - column: The column number in the generated source. The column
  10118. * number is 0-based.
  10119. *
  10120. * and an object is returned with the following properties:
  10121. *
  10122. * - source: The original source file, or null.
  10123. * - line: The line number in the original source, or null. The
  10124. * line number is 1-based.
  10125. * - column: The column number in the original source, or null. The
  10126. * column number is 0-based.
  10127. * - name: The original identifier, or null.
  10128. */
  10129. IndexedSourceMapConsumer.prototype.originalPositionFor =
  10130. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  10131. var needle = {
  10132. generatedLine: util.getArg(aArgs, 'line'),
  10133. generatedColumn: util.getArg(aArgs, 'column')
  10134. };
  10135. // Find the section containing the generated position we're trying to map
  10136. // to an original position.
  10137. var sectionIndex = binarySearch.search(needle, this._sections,
  10138. function(needle, section) {
  10139. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  10140. if (cmp) {
  10141. return cmp;
  10142. }
  10143. return (needle.generatedColumn -
  10144. section.generatedOffset.generatedColumn);
  10145. });
  10146. var section = this._sections[sectionIndex];
  10147. if (!section) {
  10148. return {
  10149. source: null,
  10150. line: null,
  10151. column: null,
  10152. name: null
  10153. };
  10154. }
  10155. return section.consumer.originalPositionFor({
  10156. line: needle.generatedLine -
  10157. (section.generatedOffset.generatedLine - 1),
  10158. column: needle.generatedColumn -
  10159. (section.generatedOffset.generatedLine === needle.generatedLine
  10160. ? section.generatedOffset.generatedColumn - 1
  10161. : 0),
  10162. bias: aArgs.bias
  10163. });
  10164. };
  10165. /**
  10166. * Return true if we have the source content for every source in the source
  10167. * map, false otherwise.
  10168. */
  10169. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  10170. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  10171. return this._sections.every(function (s) {
  10172. return s.consumer.hasContentsOfAllSources();
  10173. });
  10174. };
  10175. /**
  10176. * Returns the original source content. The only argument is the url of the
  10177. * original source file. Returns null if no original source content is
  10178. * available.
  10179. */
  10180. IndexedSourceMapConsumer.prototype.sourceContentFor =
  10181. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  10182. for (var i = 0; i < this._sections.length; i++) {
  10183. var section = this._sections[i];
  10184. var content = section.consumer.sourceContentFor(aSource, true);
  10185. if (content) {
  10186. return content;
  10187. }
  10188. }
  10189. if (nullOnMissing) {
  10190. return null;
  10191. }
  10192. else {
  10193. throw new Error('"' + aSource + '" is not in the SourceMap.');
  10194. }
  10195. };
  10196. /**
  10197. * Returns the generated line and column information for the original source,
  10198. * line, and column positions provided. The only argument is an object with
  10199. * the following properties:
  10200. *
  10201. * - source: The filename of the original source.
  10202. * - line: The line number in the original source. The line number
  10203. * is 1-based.
  10204. * - column: The column number in the original source. The column
  10205. * number is 0-based.
  10206. *
  10207. * and an object is returned with the following properties:
  10208. *
  10209. * - line: The line number in the generated source, or null. The
  10210. * line number is 1-based.
  10211. * - column: The column number in the generated source, or null.
  10212. * The column number is 0-based.
  10213. */
  10214. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  10215. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  10216. for (var i = 0; i < this._sections.length; i++) {
  10217. var section = this._sections[i];
  10218. // Only consider this section if the requested source is in the list of
  10219. // sources of the consumer.
  10220. if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
  10221. continue;
  10222. }
  10223. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  10224. if (generatedPosition) {
  10225. var ret = {
  10226. line: generatedPosition.line +
  10227. (section.generatedOffset.generatedLine - 1),
  10228. column: generatedPosition.column +
  10229. (section.generatedOffset.generatedLine === generatedPosition.line
  10230. ? section.generatedOffset.generatedColumn - 1
  10231. : 0)
  10232. };
  10233. return ret;
  10234. }
  10235. }
  10236. return {
  10237. line: null,
  10238. column: null
  10239. };
  10240. };
  10241. /**
  10242. * Parse the mappings in a string in to a data structure which we can easily
  10243. * query (the ordered arrays in the `this.__generatedMappings` and
  10244. * `this.__originalMappings` properties).
  10245. */
  10246. IndexedSourceMapConsumer.prototype._parseMappings =
  10247. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  10248. this.__generatedMappings = [];
  10249. this.__originalMappings = [];
  10250. for (var i = 0; i < this._sections.length; i++) {
  10251. var section = this._sections[i];
  10252. var sectionMappings = section.consumer._generatedMappings;
  10253. for (var j = 0; j < sectionMappings.length; j++) {
  10254. var mapping = sectionMappings[j];
  10255. var source = section.consumer._sources.at(mapping.source);
  10256. source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  10257. this._sources.add(source);
  10258. source = this._sources.indexOf(source);
  10259. var name = null;
  10260. if (mapping.name) {
  10261. name = section.consumer._names.at(mapping.name);
  10262. this._names.add(name);
  10263. name = this._names.indexOf(name);
  10264. }
  10265. // The mappings coming from the consumer for the section have
  10266. // generated positions relative to the start of the section, so we
  10267. // need to offset them to be relative to the start of the concatenated
  10268. // generated file.
  10269. var adjustedMapping = {
  10270. source: source,
  10271. generatedLine: mapping.generatedLine +
  10272. (section.generatedOffset.generatedLine - 1),
  10273. generatedColumn: mapping.generatedColumn +
  10274. (section.generatedOffset.generatedLine === mapping.generatedLine
  10275. ? section.generatedOffset.generatedColumn - 1
  10276. : 0),
  10277. originalLine: mapping.originalLine,
  10278. originalColumn: mapping.originalColumn,
  10279. name: name
  10280. };
  10281. this.__generatedMappings.push(adjustedMapping);
  10282. if (typeof adjustedMapping.originalLine === 'number') {
  10283. this.__originalMappings.push(adjustedMapping);
  10284. }
  10285. }
  10286. }
  10287. quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  10288. quickSort(this.__originalMappings, util.compareByOriginalPositions);
  10289. };
  10290. sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  10291. return sourceMapConsumer;
  10292. }
  10293. var sourceNode = {};
  10294. /* -*- Mode: js; js-indent-level: 2; -*- */
  10295. var hasRequiredSourceNode;
  10296. function requireSourceNode () {
  10297. if (hasRequiredSourceNode) return sourceNode;
  10298. hasRequiredSourceNode = 1;
  10299. /*
  10300. * Copyright 2011 Mozilla Foundation and contributors
  10301. * Licensed under the New BSD license. See LICENSE or:
  10302. * http://opensource.org/licenses/BSD-3-Clause
  10303. */
  10304. var SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  10305. var util = /*@__PURE__*/ requireUtil$1();
  10306. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  10307. // operating systems these days (capturing the result).
  10308. var REGEX_NEWLINE = /(\r?\n)/;
  10309. // Newline character code for charCodeAt() comparisons
  10310. var NEWLINE_CODE = 10;
  10311. // Private symbol for identifying `SourceNode`s when multiple versions of
  10312. // the source-map library are loaded. This MUST NOT CHANGE across
  10313. // versions!
  10314. var isSourceNode = "$$$isSourceNode$$$";
  10315. /**
  10316. * SourceNodes provide a way to abstract over interpolating/concatenating
  10317. * snippets of generated JavaScript source code while maintaining the line and
  10318. * column information associated with the original source code.
  10319. *
  10320. * @param aLine The original line number.
  10321. * @param aColumn The original column number.
  10322. * @param aSource The original source's filename.
  10323. * @param aChunks Optional. An array of strings which are snippets of
  10324. * generated JS, or other SourceNodes.
  10325. * @param aName The original identifier.
  10326. */
  10327. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  10328. this.children = [];
  10329. this.sourceContents = {};
  10330. this.line = aLine == null ? null : aLine;
  10331. this.column = aColumn == null ? null : aColumn;
  10332. this.source = aSource == null ? null : aSource;
  10333. this.name = aName == null ? null : aName;
  10334. this[isSourceNode] = true;
  10335. if (aChunks != null) this.add(aChunks);
  10336. }
  10337. /**
  10338. * Creates a SourceNode from generated code and a SourceMapConsumer.
  10339. *
  10340. * @param aGeneratedCode The generated code
  10341. * @param aSourceMapConsumer The SourceMap for the generated code
  10342. * @param aRelativePath Optional. The path that relative sources in the
  10343. * SourceMapConsumer should be relative to.
  10344. */
  10345. SourceNode.fromStringWithSourceMap =
  10346. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  10347. // The SourceNode we want to fill with the generated code
  10348. // and the SourceMap
  10349. var node = new SourceNode();
  10350. // All even indices of this array are one line of the generated code,
  10351. // while all odd indices are the newlines between two adjacent lines
  10352. // (since `REGEX_NEWLINE` captures its match).
  10353. // Processed fragments are accessed by calling `shiftNextLine`.
  10354. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  10355. var remainingLinesIndex = 0;
  10356. var shiftNextLine = function() {
  10357. var lineContents = getNextLine();
  10358. // The last line of a file might not have a newline.
  10359. var newLine = getNextLine() || "";
  10360. return lineContents + newLine;
  10361. function getNextLine() {
  10362. return remainingLinesIndex < remainingLines.length ?
  10363. remainingLines[remainingLinesIndex++] : undefined;
  10364. }
  10365. };
  10366. // We need to remember the position of "remainingLines"
  10367. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  10368. // The generate SourceNodes we need a code range.
  10369. // To extract it current and last mapping is used.
  10370. // Here we store the last mapping.
  10371. var lastMapping = null;
  10372. aSourceMapConsumer.eachMapping(function (mapping) {
  10373. if (lastMapping !== null) {
  10374. // We add the code from "lastMapping" to "mapping":
  10375. // First check if there is a new line in between.
  10376. if (lastGeneratedLine < mapping.generatedLine) {
  10377. // Associate first line with "lastMapping"
  10378. addMappingWithCode(lastMapping, shiftNextLine());
  10379. lastGeneratedLine++;
  10380. lastGeneratedColumn = 0;
  10381. // The remaining code is added without mapping
  10382. } else {
  10383. // There is no new line in between.
  10384. // Associate the code between "lastGeneratedColumn" and
  10385. // "mapping.generatedColumn" with "lastMapping"
  10386. var nextLine = remainingLines[remainingLinesIndex] || '';
  10387. var code = nextLine.substr(0, mapping.generatedColumn -
  10388. lastGeneratedColumn);
  10389. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  10390. lastGeneratedColumn);
  10391. lastGeneratedColumn = mapping.generatedColumn;
  10392. addMappingWithCode(lastMapping, code);
  10393. // No more remaining code, continue
  10394. lastMapping = mapping;
  10395. return;
  10396. }
  10397. }
  10398. // We add the generated code until the first mapping
  10399. // to the SourceNode without any mapping.
  10400. // Each line is added as separate string.
  10401. while (lastGeneratedLine < mapping.generatedLine) {
  10402. node.add(shiftNextLine());
  10403. lastGeneratedLine++;
  10404. }
  10405. if (lastGeneratedColumn < mapping.generatedColumn) {
  10406. var nextLine = remainingLines[remainingLinesIndex] || '';
  10407. node.add(nextLine.substr(0, mapping.generatedColumn));
  10408. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  10409. lastGeneratedColumn = mapping.generatedColumn;
  10410. }
  10411. lastMapping = mapping;
  10412. }, this);
  10413. // We have processed all mappings.
  10414. if (remainingLinesIndex < remainingLines.length) {
  10415. if (lastMapping) {
  10416. // Associate the remaining code in the current line with "lastMapping"
  10417. addMappingWithCode(lastMapping, shiftNextLine());
  10418. }
  10419. // and add the remaining lines without any mapping
  10420. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  10421. }
  10422. // Copy sourcesContent into SourceNode
  10423. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  10424. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  10425. if (content != null) {
  10426. if (aRelativePath != null) {
  10427. sourceFile = util.join(aRelativePath, sourceFile);
  10428. }
  10429. node.setSourceContent(sourceFile, content);
  10430. }
  10431. });
  10432. return node;
  10433. function addMappingWithCode(mapping, code) {
  10434. if (mapping === null || mapping.source === undefined) {
  10435. node.add(code);
  10436. } else {
  10437. var source = aRelativePath
  10438. ? util.join(aRelativePath, mapping.source)
  10439. : mapping.source;
  10440. node.add(new SourceNode(mapping.originalLine,
  10441. mapping.originalColumn,
  10442. source,
  10443. code,
  10444. mapping.name));
  10445. }
  10446. }
  10447. };
  10448. /**
  10449. * Add a chunk of generated JS to this source node.
  10450. *
  10451. * @param aChunk A string snippet of generated JS code, another instance of
  10452. * SourceNode, or an array where each member is one of those things.
  10453. */
  10454. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  10455. if (Array.isArray(aChunk)) {
  10456. aChunk.forEach(function (chunk) {
  10457. this.add(chunk);
  10458. }, this);
  10459. }
  10460. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10461. if (aChunk) {
  10462. this.children.push(aChunk);
  10463. }
  10464. }
  10465. else {
  10466. throw new TypeError(
  10467. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10468. );
  10469. }
  10470. return this;
  10471. };
  10472. /**
  10473. * Add a chunk of generated JS to the beginning of this source node.
  10474. *
  10475. * @param aChunk A string snippet of generated JS code, another instance of
  10476. * SourceNode, or an array where each member is one of those things.
  10477. */
  10478. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  10479. if (Array.isArray(aChunk)) {
  10480. for (var i = aChunk.length-1; i >= 0; i--) {
  10481. this.prepend(aChunk[i]);
  10482. }
  10483. }
  10484. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10485. this.children.unshift(aChunk);
  10486. }
  10487. else {
  10488. throw new TypeError(
  10489. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10490. );
  10491. }
  10492. return this;
  10493. };
  10494. /**
  10495. * Walk over the tree of JS snippets in this node and its children. The
  10496. * walking function is called once for each snippet of JS and is passed that
  10497. * snippet and the its original associated source's line/column location.
  10498. *
  10499. * @param aFn The traversal function.
  10500. */
  10501. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  10502. var chunk;
  10503. for (var i = 0, len = this.children.length; i < len; i++) {
  10504. chunk = this.children[i];
  10505. if (chunk[isSourceNode]) {
  10506. chunk.walk(aFn);
  10507. }
  10508. else {
  10509. if (chunk !== '') {
  10510. aFn(chunk, { source: this.source,
  10511. line: this.line,
  10512. column: this.column,
  10513. name: this.name });
  10514. }
  10515. }
  10516. }
  10517. };
  10518. /**
  10519. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  10520. * each of `this.children`.
  10521. *
  10522. * @param aSep The separator.
  10523. */
  10524. SourceNode.prototype.join = function SourceNode_join(aSep) {
  10525. var newChildren;
  10526. var i;
  10527. var len = this.children.length;
  10528. if (len > 0) {
  10529. newChildren = [];
  10530. for (i = 0; i < len-1; i++) {
  10531. newChildren.push(this.children[i]);
  10532. newChildren.push(aSep);
  10533. }
  10534. newChildren.push(this.children[i]);
  10535. this.children = newChildren;
  10536. }
  10537. return this;
  10538. };
  10539. /**
  10540. * Call String.prototype.replace on the very right-most source snippet. Useful
  10541. * for trimming whitespace from the end of a source node, etc.
  10542. *
  10543. * @param aPattern The pattern to replace.
  10544. * @param aReplacement The thing to replace the pattern with.
  10545. */
  10546. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  10547. var lastChild = this.children[this.children.length - 1];
  10548. if (lastChild[isSourceNode]) {
  10549. lastChild.replaceRight(aPattern, aReplacement);
  10550. }
  10551. else if (typeof lastChild === 'string') {
  10552. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  10553. }
  10554. else {
  10555. this.children.push(''.replace(aPattern, aReplacement));
  10556. }
  10557. return this;
  10558. };
  10559. /**
  10560. * Set the source content for a source file. This will be added to the SourceMapGenerator
  10561. * in the sourcesContent field.
  10562. *
  10563. * @param aSourceFile The filename of the source file
  10564. * @param aSourceContent The content of the source file
  10565. */
  10566. SourceNode.prototype.setSourceContent =
  10567. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  10568. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  10569. };
  10570. /**
  10571. * Walk over the tree of SourceNodes. The walking function is called for each
  10572. * source file content and is passed the filename and source content.
  10573. *
  10574. * @param aFn The traversal function.
  10575. */
  10576. SourceNode.prototype.walkSourceContents =
  10577. function SourceNode_walkSourceContents(aFn) {
  10578. for (var i = 0, len = this.children.length; i < len; i++) {
  10579. if (this.children[i][isSourceNode]) {
  10580. this.children[i].walkSourceContents(aFn);
  10581. }
  10582. }
  10583. var sources = Object.keys(this.sourceContents);
  10584. for (var i = 0, len = sources.length; i < len; i++) {
  10585. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  10586. }
  10587. };
  10588. /**
  10589. * Return the string representation of this source node. Walks over the tree
  10590. * and concatenates all the various snippets together to one string.
  10591. */
  10592. SourceNode.prototype.toString = function SourceNode_toString() {
  10593. var str = "";
  10594. this.walk(function (chunk) {
  10595. str += chunk;
  10596. });
  10597. return str;
  10598. };
  10599. /**
  10600. * Returns the string representation of this source node along with a source
  10601. * map.
  10602. */
  10603. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  10604. var generated = {
  10605. code: "",
  10606. line: 1,
  10607. column: 0
  10608. };
  10609. var map = new SourceMapGenerator(aArgs);
  10610. var sourceMappingActive = false;
  10611. var lastOriginalSource = null;
  10612. var lastOriginalLine = null;
  10613. var lastOriginalColumn = null;
  10614. var lastOriginalName = null;
  10615. this.walk(function (chunk, original) {
  10616. generated.code += chunk;
  10617. if (original.source !== null
  10618. && original.line !== null
  10619. && original.column !== null) {
  10620. if(lastOriginalSource !== original.source
  10621. || lastOriginalLine !== original.line
  10622. || lastOriginalColumn !== original.column
  10623. || lastOriginalName !== original.name) {
  10624. map.addMapping({
  10625. source: original.source,
  10626. original: {
  10627. line: original.line,
  10628. column: original.column
  10629. },
  10630. generated: {
  10631. line: generated.line,
  10632. column: generated.column
  10633. },
  10634. name: original.name
  10635. });
  10636. }
  10637. lastOriginalSource = original.source;
  10638. lastOriginalLine = original.line;
  10639. lastOriginalColumn = original.column;
  10640. lastOriginalName = original.name;
  10641. sourceMappingActive = true;
  10642. } else if (sourceMappingActive) {
  10643. map.addMapping({
  10644. generated: {
  10645. line: generated.line,
  10646. column: generated.column
  10647. }
  10648. });
  10649. lastOriginalSource = null;
  10650. sourceMappingActive = false;
  10651. }
  10652. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  10653. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  10654. generated.line++;
  10655. generated.column = 0;
  10656. // Mappings end at eol
  10657. if (idx + 1 === length) {
  10658. lastOriginalSource = null;
  10659. sourceMappingActive = false;
  10660. } else if (sourceMappingActive) {
  10661. map.addMapping({
  10662. source: original.source,
  10663. original: {
  10664. line: original.line,
  10665. column: original.column
  10666. },
  10667. generated: {
  10668. line: generated.line,
  10669. column: generated.column
  10670. },
  10671. name: original.name
  10672. });
  10673. }
  10674. } else {
  10675. generated.column++;
  10676. }
  10677. }
  10678. });
  10679. this.walkSourceContents(function (sourceFile, sourceContent) {
  10680. map.setSourceContent(sourceFile, sourceContent);
  10681. });
  10682. return { code: generated.code, map: map };
  10683. };
  10684. sourceNode.SourceNode = SourceNode;
  10685. return sourceNode;
  10686. }
  10687. /*
  10688. * Copyright 2009-2011 Mozilla Foundation and contributors
  10689. * Licensed under the New BSD license. See LICENSE.txt or:
  10690. * http://opensource.org/licenses/BSD-3-Clause
  10691. */
  10692. var hasRequiredSourceMap;
  10693. function requireSourceMap () {
  10694. if (hasRequiredSourceMap) return sourceMap;
  10695. hasRequiredSourceMap = 1;
  10696. sourceMap.SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  10697. sourceMap.SourceMapConsumer = /*@__PURE__*/ requireSourceMapConsumer().SourceMapConsumer;
  10698. sourceMap.SourceNode = /*@__PURE__*/ requireSourceNode().SourceNode;
  10699. return sourceMap;
  10700. }
  10701. var mergeSourceMap;
  10702. var hasRequiredMergeSourceMap;
  10703. function requireMergeSourceMap () {
  10704. if (hasRequiredMergeSourceMap) return mergeSourceMap;
  10705. hasRequiredMergeSourceMap = 1;
  10706. var sourceMap = /*@__PURE__*/ requireSourceMap();
  10707. var SourceMapConsumer = sourceMap.SourceMapConsumer;
  10708. var SourceMapGenerator = sourceMap.SourceMapGenerator;
  10709. mergeSourceMap = merge;
  10710. /**
  10711. * Merge old source map and new source map and return merged.
  10712. * If old or new source map value is falsy, return another one as it is.
  10713. *
  10714. * @param {object|string} [oldMap] old source map object
  10715. * @param {object|string} [newmap] new source map object
  10716. * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
  10717. */
  10718. function merge(oldMap, newMap) {
  10719. if (!oldMap) return newMap
  10720. if (!newMap) return oldMap
  10721. var oldMapConsumer = new SourceMapConsumer(oldMap);
  10722. var newMapConsumer = new SourceMapConsumer(newMap);
  10723. var mergedMapGenerator = new SourceMapGenerator();
  10724. // iterate on new map and overwrite original position of new map with one of old map
  10725. newMapConsumer.eachMapping(function(m) {
  10726. // pass when `originalLine` is null.
  10727. // It occurs in case that the node does not have origin in original code.
  10728. if (m.originalLine == null) return
  10729. var origPosInOldMap = oldMapConsumer.originalPositionFor({
  10730. line: m.originalLine,
  10731. column: m.originalColumn
  10732. });
  10733. if (origPosInOldMap.source == null) return
  10734. mergedMapGenerator.addMapping({
  10735. original: {
  10736. line: origPosInOldMap.line,
  10737. column: origPosInOldMap.column
  10738. },
  10739. generated: {
  10740. line: m.generatedLine,
  10741. column: m.generatedColumn
  10742. },
  10743. source: origPosInOldMap.source,
  10744. name: origPosInOldMap.name
  10745. });
  10746. });
  10747. var consumers = [oldMapConsumer, newMapConsumer];
  10748. consumers.forEach(function(consumer) {
  10749. consumer.sources.forEach(function(sourceFile) {
  10750. mergedMapGenerator._sources.add(sourceFile);
  10751. var sourceContent = consumer.sourceContentFor(sourceFile);
  10752. if (sourceContent != null) {
  10753. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  10754. }
  10755. });
  10756. });
  10757. mergedMapGenerator._sourceRoot = oldMap.sourceRoot;
  10758. mergedMapGenerator._file = oldMap.file;
  10759. return JSON.parse(mergedMapGenerator.toString())
  10760. }
  10761. return mergeSourceMap;
  10762. }
  10763. var mergeSourceMapExports = /*@__PURE__*/ requireMergeSourceMap();
  10764. var merge = /*@__PURE__*/getDefaultExportFromCjs(mergeSourceMapExports);
  10765. const scss = (source, map, options, load = require) => {
  10766. const nodeSass = load("sass");
  10767. const { compileString, renderSync } = nodeSass;
  10768. const data = getSource(source, options.filename, options.additionalData);
  10769. let css;
  10770. let dependencies;
  10771. let sourceMap;
  10772. try {
  10773. if (compileString) {
  10774. const { pathToFileURL, fileURLToPath } = load("url");
  10775. const result = compileString(data, {
  10776. ...options,
  10777. url: pathToFileURL(options.filename),
  10778. sourceMap: !!map
  10779. });
  10780. css = result.css;
  10781. dependencies = result.loadedUrls.map((url) => fileURLToPath(url));
  10782. sourceMap = map ? result.sourceMap : void 0;
  10783. } else {
  10784. const result = renderSync({
  10785. ...options,
  10786. data,
  10787. file: options.filename,
  10788. outFile: options.filename,
  10789. sourceMap: !!map
  10790. });
  10791. css = result.css.toString();
  10792. dependencies = result.stats.includedFiles;
  10793. sourceMap = map ? JSON.parse(result.map.toString()) : void 0;
  10794. }
  10795. if (map) {
  10796. return {
  10797. code: css,
  10798. errors: [],
  10799. dependencies,
  10800. map: merge(map, sourceMap)
  10801. };
  10802. }
  10803. return { code: css, errors: [], dependencies };
  10804. } catch (e) {
  10805. return { code: "", errors: [e], dependencies: [] };
  10806. }
  10807. };
  10808. const sass = (source, map, options, load) => scss(
  10809. source,
  10810. map,
  10811. {
  10812. ...options,
  10813. indentedSyntax: true
  10814. },
  10815. load
  10816. );
  10817. const less = (source, map, options, load = require) => {
  10818. const nodeLess = load("less");
  10819. let result;
  10820. let error = null;
  10821. nodeLess.render(
  10822. getSource(source, options.filename, options.additionalData),
  10823. { ...options, syncImport: true },
  10824. (err, output) => {
  10825. error = err;
  10826. result = output;
  10827. }
  10828. );
  10829. if (error) return { code: "", errors: [error], dependencies: [] };
  10830. const dependencies = result.imports;
  10831. if (map) {
  10832. return {
  10833. code: result.css.toString(),
  10834. map: merge(map, result.map),
  10835. errors: [],
  10836. dependencies
  10837. };
  10838. }
  10839. return {
  10840. code: result.css.toString(),
  10841. errors: [],
  10842. dependencies
  10843. };
  10844. };
  10845. const styl = (source, map, options, load = require) => {
  10846. const nodeStylus = load("stylus");
  10847. try {
  10848. const ref = nodeStylus(source, options);
  10849. if (map) ref.set("sourcemap", { inline: false, comment: false });
  10850. const result = ref.render();
  10851. const dependencies = ref.deps();
  10852. if (map) {
  10853. return {
  10854. code: result,
  10855. map: merge(map, ref.sourcemap),
  10856. errors: [],
  10857. dependencies
  10858. };
  10859. }
  10860. return { code: result, errors: [], dependencies };
  10861. } catch (e) {
  10862. return { code: "", errors: [e], dependencies: [] };
  10863. }
  10864. };
  10865. function getSource(source, filename, additionalData) {
  10866. if (!additionalData) return source;
  10867. if (shared.isFunction(additionalData)) {
  10868. return additionalData(source, filename);
  10869. }
  10870. return additionalData + source;
  10871. }
  10872. const processors = {
  10873. less,
  10874. sass,
  10875. scss,
  10876. styl,
  10877. stylus: styl
  10878. };
  10879. var build = {exports: {}};
  10880. var fs = {};
  10881. var hasRequiredFs;
  10882. function requireFs () {
  10883. if (hasRequiredFs) return fs;
  10884. hasRequiredFs = 1;
  10885. Object.defineProperty(fs, "__esModule", {
  10886. value: true
  10887. });
  10888. fs.getFileSystem = getFileSystem;
  10889. fs.setFileSystem = setFileSystem;
  10890. let fileSystem = {
  10891. readFile: () => {
  10892. throw Error("readFile not implemented");
  10893. },
  10894. writeFile: () => {
  10895. throw Error("writeFile not implemented");
  10896. }
  10897. };
  10898. function setFileSystem(fs) {
  10899. fileSystem.readFile = fs.readFile;
  10900. fileSystem.writeFile = fs.writeFile;
  10901. }
  10902. function getFileSystem() {
  10903. return fileSystem;
  10904. }
  10905. return fs;
  10906. }
  10907. var pluginFactory = {};
  10908. var unquote = {};
  10909. var hasRequiredUnquote;
  10910. function requireUnquote () {
  10911. if (hasRequiredUnquote) return unquote;
  10912. hasRequiredUnquote = 1;
  10913. Object.defineProperty(unquote, "__esModule", {
  10914. value: true
  10915. });
  10916. unquote.default = unquote$1;
  10917. // copied from https://github.com/lakenen/node-unquote
  10918. const reg = /['"]/;
  10919. function unquote$1(str) {
  10920. if (!str) {
  10921. return "";
  10922. }
  10923. if (reg.test(str.charAt(0))) {
  10924. str = str.substr(1);
  10925. }
  10926. if (reg.test(str.charAt(str.length - 1))) {
  10927. str = str.substr(0, str.length - 1);
  10928. }
  10929. return str;
  10930. }
  10931. return unquote;
  10932. }
  10933. var Parser = {};
  10934. var replaceValueSymbols_1;
  10935. var hasRequiredReplaceValueSymbols;
  10936. function requireReplaceValueSymbols () {
  10937. if (hasRequiredReplaceValueSymbols) return replaceValueSymbols_1;
  10938. hasRequiredReplaceValueSymbols = 1;
  10939. const matchValueName = /[$]?[\w-]+/g;
  10940. const replaceValueSymbols = (value, replacements) => {
  10941. let matches;
  10942. while ((matches = matchValueName.exec(value))) {
  10943. const replacement = replacements[matches[0]];
  10944. if (replacement) {
  10945. value =
  10946. value.slice(0, matches.index) +
  10947. replacement +
  10948. value.slice(matchValueName.lastIndex);
  10949. matchValueName.lastIndex -= matches[0].length - replacement.length;
  10950. }
  10951. }
  10952. return value;
  10953. };
  10954. replaceValueSymbols_1 = replaceValueSymbols;
  10955. return replaceValueSymbols_1;
  10956. }
  10957. var replaceSymbols_1;
  10958. var hasRequiredReplaceSymbols;
  10959. function requireReplaceSymbols () {
  10960. if (hasRequiredReplaceSymbols) return replaceSymbols_1;
  10961. hasRequiredReplaceSymbols = 1;
  10962. const replaceValueSymbols = /*@__PURE__*/ requireReplaceValueSymbols();
  10963. const replaceSymbols = (css, replacements) => {
  10964. css.walk((node) => {
  10965. if (node.type === "decl" && node.value) {
  10966. node.value = replaceValueSymbols(node.value.toString(), replacements);
  10967. } else if (node.type === "rule" && node.selector) {
  10968. node.selector = replaceValueSymbols(
  10969. node.selector.toString(),
  10970. replacements
  10971. );
  10972. } else if (node.type === "atrule" && node.params) {
  10973. node.params = replaceValueSymbols(node.params.toString(), replacements);
  10974. }
  10975. });
  10976. };
  10977. replaceSymbols_1 = replaceSymbols;
  10978. return replaceSymbols_1;
  10979. }
  10980. var extractICSS_1;
  10981. var hasRequiredExtractICSS;
  10982. function requireExtractICSS () {
  10983. if (hasRequiredExtractICSS) return extractICSS_1;
  10984. hasRequiredExtractICSS = 1;
  10985. const importPattern = /^:import\(("[^"]*"|'[^']*'|[^"']+)\)$/;
  10986. const balancedQuotes = /^("[^"]*"|'[^']*'|[^"']+)$/;
  10987. const getDeclsObject = (rule) => {
  10988. const object = {};
  10989. rule.walkDecls((decl) => {
  10990. const before = decl.raws.before ? decl.raws.before.trim() : "";
  10991. object[before + decl.prop] = decl.value;
  10992. });
  10993. return object;
  10994. };
  10995. /**
  10996. *
  10997. * @param {string} css
  10998. * @param {boolean} removeRules
  10999. * @param {'auto' | 'rule' | 'at-rule'} mode
  11000. */
  11001. const extractICSS = (css, removeRules = true, mode = "auto") => {
  11002. const icssImports = {};
  11003. const icssExports = {};
  11004. function addImports(node, path) {
  11005. const unquoted = path.replace(/'|"/g, "");
  11006. icssImports[unquoted] = Object.assign(
  11007. icssImports[unquoted] || {},
  11008. getDeclsObject(node)
  11009. );
  11010. if (removeRules) {
  11011. node.remove();
  11012. }
  11013. }
  11014. function addExports(node) {
  11015. Object.assign(icssExports, getDeclsObject(node));
  11016. if (removeRules) {
  11017. node.remove();
  11018. }
  11019. }
  11020. css.each((node) => {
  11021. if (node.type === "rule" && mode !== "at-rule") {
  11022. if (node.selector.slice(0, 7) === ":import") {
  11023. const matches = importPattern.exec(node.selector);
  11024. if (matches) {
  11025. addImports(node, matches[1]);
  11026. }
  11027. }
  11028. if (node.selector === ":export") {
  11029. addExports(node);
  11030. }
  11031. }
  11032. if (node.type === "atrule" && mode !== "rule") {
  11033. if (node.name === "icss-import") {
  11034. const matches = balancedQuotes.exec(node.params);
  11035. if (matches) {
  11036. addImports(node, matches[1]);
  11037. }
  11038. }
  11039. if (node.name === "icss-export") {
  11040. addExports(node);
  11041. }
  11042. }
  11043. });
  11044. return { icssImports, icssExports };
  11045. };
  11046. extractICSS_1 = extractICSS;
  11047. return extractICSS_1;
  11048. }
  11049. var createICSSRules_1;
  11050. var hasRequiredCreateICSSRules;
  11051. function requireCreateICSSRules () {
  11052. if (hasRequiredCreateICSSRules) return createICSSRules_1;
  11053. hasRequiredCreateICSSRules = 1;
  11054. const createImports = (imports, postcss, mode = "rule") => {
  11055. return Object.keys(imports).map((path) => {
  11056. const aliases = imports[path];
  11057. const declarations = Object.keys(aliases).map((key) =>
  11058. postcss.decl({
  11059. prop: key,
  11060. value: aliases[key],
  11061. raws: { before: "\n " },
  11062. })
  11063. );
  11064. const hasDeclarations = declarations.length > 0;
  11065. const rule =
  11066. mode === "rule"
  11067. ? postcss.rule({
  11068. selector: `:import('${path}')`,
  11069. raws: { after: hasDeclarations ? "\n" : "" },
  11070. })
  11071. : postcss.atRule({
  11072. name: "icss-import",
  11073. params: `'${path}'`,
  11074. raws: { after: hasDeclarations ? "\n" : "" },
  11075. });
  11076. if (hasDeclarations) {
  11077. rule.append(declarations);
  11078. }
  11079. return rule;
  11080. });
  11081. };
  11082. const createExports = (exports$1, postcss, mode = "rule") => {
  11083. const declarations = Object.keys(exports$1).map((key) =>
  11084. postcss.decl({
  11085. prop: key,
  11086. value: exports$1[key],
  11087. raws: { before: "\n " },
  11088. })
  11089. );
  11090. if (declarations.length === 0) {
  11091. return [];
  11092. }
  11093. const rule =
  11094. mode === "rule"
  11095. ? postcss.rule({
  11096. selector: `:export`,
  11097. raws: { after: "\n" },
  11098. })
  11099. : postcss.atRule({
  11100. name: "icss-export",
  11101. raws: { after: "\n" },
  11102. });
  11103. rule.append(declarations);
  11104. return [rule];
  11105. };
  11106. const createICSSRules = (imports, exports$1, postcss, mode) => [
  11107. ...createImports(imports, postcss, mode),
  11108. ...createExports(exports$1, postcss, mode),
  11109. ];
  11110. createICSSRules_1 = createICSSRules;
  11111. return createICSSRules_1;
  11112. }
  11113. var src$4;
  11114. var hasRequiredSrc$4;
  11115. function requireSrc$4 () {
  11116. if (hasRequiredSrc$4) return src$4;
  11117. hasRequiredSrc$4 = 1;
  11118. const replaceValueSymbols = /*@__PURE__*/ requireReplaceValueSymbols();
  11119. const replaceSymbols = /*@__PURE__*/ requireReplaceSymbols();
  11120. const extractICSS = /*@__PURE__*/ requireExtractICSS();
  11121. const createICSSRules = /*@__PURE__*/ requireCreateICSSRules();
  11122. src$4 = {
  11123. replaceValueSymbols,
  11124. replaceSymbols,
  11125. extractICSS,
  11126. createICSSRules,
  11127. };
  11128. return src$4;
  11129. }
  11130. var hasRequiredParser$1;
  11131. function requireParser$1 () {
  11132. if (hasRequiredParser$1) return Parser;
  11133. hasRequiredParser$1 = 1;
  11134. Object.defineProperty(Parser, "__esModule", {
  11135. value: true
  11136. });
  11137. Parser.default = void 0;
  11138. var _icssUtils = /*@__PURE__*/ requireSrc$4();
  11139. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  11140. const importRegexp = /^:import\((.+)\)$/;
  11141. let Parser$1 = class Parser {
  11142. constructor(pathFetcher, trace) {
  11143. this.pathFetcher = pathFetcher;
  11144. this.plugin = this.plugin.bind(this);
  11145. this.exportTokens = {};
  11146. this.translations = {};
  11147. this.trace = trace;
  11148. }
  11149. plugin() {
  11150. const parser = this;
  11151. return {
  11152. postcssPlugin: "css-modules-parser",
  11153. async OnceExit(css) {
  11154. await Promise.all(parser.fetchAllImports(css));
  11155. parser.linkImportedSymbols(css);
  11156. return parser.extractExports(css);
  11157. }
  11158. };
  11159. }
  11160. fetchAllImports(css) {
  11161. let imports = [];
  11162. css.each(node => {
  11163. if (node.type == "rule" && node.selector.match(importRegexp)) {
  11164. imports.push(this.fetchImport(node, css.source.input.from, imports.length));
  11165. }
  11166. });
  11167. return imports;
  11168. }
  11169. linkImportedSymbols(css) {
  11170. (0, _icssUtils.replaceSymbols)(css, this.translations);
  11171. }
  11172. extractExports(css) {
  11173. css.each(node => {
  11174. if (node.type == "rule" && node.selector == ":export") this.handleExport(node);
  11175. });
  11176. }
  11177. handleExport(exportNode) {
  11178. exportNode.each(decl => {
  11179. if (decl.type == "decl") {
  11180. Object.keys(this.translations).forEach(translation => {
  11181. decl.value = decl.value.replace(translation, this.translations[translation]);
  11182. });
  11183. this.exportTokens[decl.prop] = decl.value;
  11184. }
  11185. });
  11186. exportNode.remove();
  11187. }
  11188. async fetchImport(importNode, relativeTo, depNr) {
  11189. const file = importNode.selector.match(importRegexp)[1];
  11190. const depTrace = this.trace + String.fromCharCode(depNr);
  11191. const exports$1 = await this.pathFetcher(file, relativeTo, depTrace);
  11192. try {
  11193. importNode.each(decl => {
  11194. if (decl.type == "decl") {
  11195. this.translations[decl.prop] = exports$1[decl.value];
  11196. }
  11197. });
  11198. importNode.remove();
  11199. } catch (err) {
  11200. console.log(err);
  11201. }
  11202. }
  11203. };
  11204. Parser.default = Parser$1;
  11205. return Parser;
  11206. }
  11207. var saveJSON = {};
  11208. var hasRequiredSaveJSON;
  11209. function requireSaveJSON () {
  11210. if (hasRequiredSaveJSON) return saveJSON;
  11211. hasRequiredSaveJSON = 1;
  11212. Object.defineProperty(saveJSON, "__esModule", {
  11213. value: true
  11214. });
  11215. saveJSON.default = saveJSON$1;
  11216. var _fs = /*@__PURE__*/ requireFs();
  11217. function saveJSON$1(cssFile, json) {
  11218. return new Promise((resolve, reject) => {
  11219. const {
  11220. writeFile
  11221. } = (0, _fs.getFileSystem)();
  11222. writeFile(`${cssFile}.json`, JSON.stringify(json), e => e ? reject(e) : resolve(json));
  11223. });
  11224. }
  11225. return saveJSON;
  11226. }
  11227. var localsConvention = {};
  11228. /**
  11229. * lodash (Custom Build) <https://lodash.com/>
  11230. * Build: `lodash modularize exports="npm" -o ./`
  11231. * Copyright jQuery Foundation and other contributors <https://jquery.org/>
  11232. * Released under MIT license <https://lodash.com/license>
  11233. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  11234. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11235. */
  11236. var lodash_camelcase;
  11237. var hasRequiredLodash_camelcase;
  11238. function requireLodash_camelcase () {
  11239. if (hasRequiredLodash_camelcase) return lodash_camelcase;
  11240. hasRequiredLodash_camelcase = 1;
  11241. /** `Object#toString` result references. */
  11242. var symbolTag = '[object Symbol]';
  11243. /** Used to match words composed of alphanumeric characters. */
  11244. var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
  11245. /** Used to match Latin Unicode letters (excluding mathematical operators). */
  11246. var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
  11247. /** Used to compose unicode character classes. */
  11248. var rsAstralRange = '\\ud800-\\udfff',
  11249. rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23',
  11250. rsComboSymbolsRange = '\\u20d0-\\u20f0',
  11251. rsDingbatRange = '\\u2700-\\u27bf',
  11252. rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
  11253. rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
  11254. rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
  11255. rsPunctuationRange = '\\u2000-\\u206f',
  11256. 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',
  11257. rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
  11258. rsVarRange = '\\ufe0e\\ufe0f',
  11259. rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
  11260. /** Used to compose unicode capture groups. */
  11261. var rsApos = "['\u2019]",
  11262. rsAstral = '[' + rsAstralRange + ']',
  11263. rsBreak = '[' + rsBreakRange + ']',
  11264. rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']',
  11265. rsDigits = '\\d+',
  11266. rsDingbat = '[' + rsDingbatRange + ']',
  11267. rsLower = '[' + rsLowerRange + ']',
  11268. rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
  11269. rsFitz = '\\ud83c[\\udffb-\\udfff]',
  11270. rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
  11271. rsNonAstral = '[^' + rsAstralRange + ']',
  11272. rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
  11273. rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
  11274. rsUpper = '[' + rsUpperRange + ']',
  11275. rsZWJ = '\\u200d';
  11276. /** Used to compose unicode regexes. */
  11277. var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')',
  11278. rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')',
  11279. rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
  11280. rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
  11281. reOptMod = rsModifier + '?',
  11282. rsOptVar = '[' + rsVarRange + ']?',
  11283. rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
  11284. rsSeq = rsOptVar + reOptMod + rsOptJoin,
  11285. rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
  11286. rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
  11287. /** Used to match apostrophes. */
  11288. var reApos = RegExp(rsApos, 'g');
  11289. /**
  11290. * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
  11291. * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
  11292. */
  11293. var reComboMark = RegExp(rsCombo, 'g');
  11294. /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
  11295. var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
  11296. /** Used to match complex or compound words. */
  11297. var reUnicodeWord = RegExp([
  11298. rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
  11299. rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')',
  11300. rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr,
  11301. rsUpper + '+' + rsOptUpperContr,
  11302. rsDigits,
  11303. rsEmoji
  11304. ].join('|'), 'g');
  11305. /** 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/). */
  11306. var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']');
  11307. /** Used to detect strings that need a more robust regexp to match words. */
  11308. 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 ]/;
  11309. /** Used to map Latin Unicode letters to basic Latin letters. */
  11310. var deburredLetters = {
  11311. // Latin-1 Supplement block.
  11312. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
  11313. '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
  11314. '\xc7': 'C', '\xe7': 'c',
  11315. '\xd0': 'D', '\xf0': 'd',
  11316. '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
  11317. '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
  11318. '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
  11319. '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
  11320. '\xd1': 'N', '\xf1': 'n',
  11321. '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
  11322. '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
  11323. '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
  11324. '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
  11325. '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
  11326. '\xc6': 'Ae', '\xe6': 'ae',
  11327. '\xde': 'Th', '\xfe': 'th',
  11328. '\xdf': 'ss',
  11329. // Latin Extended-A block.
  11330. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
  11331. '\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
  11332. '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
  11333. '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
  11334. '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
  11335. '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
  11336. '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
  11337. '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
  11338. '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
  11339. '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
  11340. '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
  11341. '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
  11342. '\u0134': 'J', '\u0135': 'j',
  11343. '\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
  11344. '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
  11345. '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
  11346. '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
  11347. '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
  11348. '\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
  11349. '\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
  11350. '\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
  11351. '\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
  11352. '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
  11353. '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
  11354. '\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
  11355. '\u0163': 't', '\u0165': 't', '\u0167': 't',
  11356. '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
  11357. '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
  11358. '\u0174': 'W', '\u0175': 'w',
  11359. '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
  11360. '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
  11361. '\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
  11362. '\u0132': 'IJ', '\u0133': 'ij',
  11363. '\u0152': 'Oe', '\u0153': 'oe',
  11364. '\u0149': "'n", '\u017f': 'ss'
  11365. };
  11366. /** Detect free variable `global` from Node.js. */
  11367. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
  11368. /** Detect free variable `self`. */
  11369. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  11370. /** Used as a reference to the global object. */
  11371. var root = freeGlobal || freeSelf || Function('return this')();
  11372. /**
  11373. * A specialized version of `_.reduce` for arrays without support for
  11374. * iteratee shorthands.
  11375. *
  11376. * @private
  11377. * @param {Array} [array] The array to iterate over.
  11378. * @param {Function} iteratee The function invoked per iteration.
  11379. * @param {*} [accumulator] The initial value.
  11380. * @param {boolean} [initAccum] Specify using the first element of `array` as
  11381. * the initial value.
  11382. * @returns {*} Returns the accumulated value.
  11383. */
  11384. function arrayReduce(array, iteratee, accumulator, initAccum) {
  11385. var index = -1,
  11386. length = array ? array.length : 0;
  11387. while (++index < length) {
  11388. accumulator = iteratee(accumulator, array[index], index, array);
  11389. }
  11390. return accumulator;
  11391. }
  11392. /**
  11393. * Converts an ASCII `string` to an array.
  11394. *
  11395. * @private
  11396. * @param {string} string The string to convert.
  11397. * @returns {Array} Returns the converted array.
  11398. */
  11399. function asciiToArray(string) {
  11400. return string.split('');
  11401. }
  11402. /**
  11403. * Splits an ASCII `string` into an array of its words.
  11404. *
  11405. * @private
  11406. * @param {string} The string to inspect.
  11407. * @returns {Array} Returns the words of `string`.
  11408. */
  11409. function asciiWords(string) {
  11410. return string.match(reAsciiWord) || [];
  11411. }
  11412. /**
  11413. * The base implementation of `_.propertyOf` without support for deep paths.
  11414. *
  11415. * @private
  11416. * @param {Object} object The object to query.
  11417. * @returns {Function} Returns the new accessor function.
  11418. */
  11419. function basePropertyOf(object) {
  11420. return function(key) {
  11421. return object == null ? undefined : object[key];
  11422. };
  11423. }
  11424. /**
  11425. * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
  11426. * letters to basic Latin letters.
  11427. *
  11428. * @private
  11429. * @param {string} letter The matched letter to deburr.
  11430. * @returns {string} Returns the deburred letter.
  11431. */
  11432. var deburrLetter = basePropertyOf(deburredLetters);
  11433. /**
  11434. * Checks if `string` contains Unicode symbols.
  11435. *
  11436. * @private
  11437. * @param {string} string The string to inspect.
  11438. * @returns {boolean} Returns `true` if a symbol is found, else `false`.
  11439. */
  11440. function hasUnicode(string) {
  11441. return reHasUnicode.test(string);
  11442. }
  11443. /**
  11444. * Checks if `string` contains a word composed of Unicode symbols.
  11445. *
  11446. * @private
  11447. * @param {string} string The string to inspect.
  11448. * @returns {boolean} Returns `true` if a word is found, else `false`.
  11449. */
  11450. function hasUnicodeWord(string) {
  11451. return reHasUnicodeWord.test(string);
  11452. }
  11453. /**
  11454. * Converts `string` to an array.
  11455. *
  11456. * @private
  11457. * @param {string} string The string to convert.
  11458. * @returns {Array} Returns the converted array.
  11459. */
  11460. function stringToArray(string) {
  11461. return hasUnicode(string)
  11462. ? unicodeToArray(string)
  11463. : asciiToArray(string);
  11464. }
  11465. /**
  11466. * Converts a Unicode `string` to an array.
  11467. *
  11468. * @private
  11469. * @param {string} string The string to convert.
  11470. * @returns {Array} Returns the converted array.
  11471. */
  11472. function unicodeToArray(string) {
  11473. return string.match(reUnicode) || [];
  11474. }
  11475. /**
  11476. * Splits a Unicode `string` into an array of its words.
  11477. *
  11478. * @private
  11479. * @param {string} The string to inspect.
  11480. * @returns {Array} Returns the words of `string`.
  11481. */
  11482. function unicodeWords(string) {
  11483. return string.match(reUnicodeWord) || [];
  11484. }
  11485. /** Used for built-in method references. */
  11486. var objectProto = Object.prototype;
  11487. /**
  11488. * Used to resolve the
  11489. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  11490. * of values.
  11491. */
  11492. var objectToString = objectProto.toString;
  11493. /** Built-in value references. */
  11494. var Symbol = root.Symbol;
  11495. /** Used to convert symbols to primitives and strings. */
  11496. var symbolProto = Symbol ? Symbol.prototype : undefined,
  11497. symbolToString = symbolProto ? symbolProto.toString : undefined;
  11498. /**
  11499. * The base implementation of `_.slice` without an iteratee call guard.
  11500. *
  11501. * @private
  11502. * @param {Array} array The array to slice.
  11503. * @param {number} [start=0] The start position.
  11504. * @param {number} [end=array.length] The end position.
  11505. * @returns {Array} Returns the slice of `array`.
  11506. */
  11507. function baseSlice(array, start, end) {
  11508. var index = -1,
  11509. length = array.length;
  11510. if (start < 0) {
  11511. start = -start > length ? 0 : (length + start);
  11512. }
  11513. end = end > length ? length : end;
  11514. if (end < 0) {
  11515. end += length;
  11516. }
  11517. length = start > end ? 0 : ((end - start) >>> 0);
  11518. start >>>= 0;
  11519. var result = Array(length);
  11520. while (++index < length) {
  11521. result[index] = array[index + start];
  11522. }
  11523. return result;
  11524. }
  11525. /**
  11526. * The base implementation of `_.toString` which doesn't convert nullish
  11527. * values to empty strings.
  11528. *
  11529. * @private
  11530. * @param {*} value The value to process.
  11531. * @returns {string} Returns the string.
  11532. */
  11533. function baseToString(value) {
  11534. // Exit early for strings to avoid a performance hit in some environments.
  11535. if (typeof value == 'string') {
  11536. return value;
  11537. }
  11538. if (isSymbol(value)) {
  11539. return symbolToString ? symbolToString.call(value) : '';
  11540. }
  11541. var result = (value + '');
  11542. return (result == '0' && (1 / value) == -Infinity) ? '-0' : result;
  11543. }
  11544. /**
  11545. * Casts `array` to a slice if it's needed.
  11546. *
  11547. * @private
  11548. * @param {Array} array The array to inspect.
  11549. * @param {number} start The start position.
  11550. * @param {number} [end=array.length] The end position.
  11551. * @returns {Array} Returns the cast slice.
  11552. */
  11553. function castSlice(array, start, end) {
  11554. var length = array.length;
  11555. end = end === undefined ? length : end;
  11556. return (!start && end >= length) ? array : baseSlice(array, start, end);
  11557. }
  11558. /**
  11559. * Creates a function like `_.lowerFirst`.
  11560. *
  11561. * @private
  11562. * @param {string} methodName The name of the `String` case method to use.
  11563. * @returns {Function} Returns the new case function.
  11564. */
  11565. function createCaseFirst(methodName) {
  11566. return function(string) {
  11567. string = toString(string);
  11568. var strSymbols = hasUnicode(string)
  11569. ? stringToArray(string)
  11570. : undefined;
  11571. var chr = strSymbols
  11572. ? strSymbols[0]
  11573. : string.charAt(0);
  11574. var trailing = strSymbols
  11575. ? castSlice(strSymbols, 1).join('')
  11576. : string.slice(1);
  11577. return chr[methodName]() + trailing;
  11578. };
  11579. }
  11580. /**
  11581. * Creates a function like `_.camelCase`.
  11582. *
  11583. * @private
  11584. * @param {Function} callback The function to combine each word.
  11585. * @returns {Function} Returns the new compounder function.
  11586. */
  11587. function createCompounder(callback) {
  11588. return function(string) {
  11589. return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
  11590. };
  11591. }
  11592. /**
  11593. * Checks if `value` is object-like. A value is object-like if it's not `null`
  11594. * and has a `typeof` result of "object".
  11595. *
  11596. * @static
  11597. * @memberOf _
  11598. * @since 4.0.0
  11599. * @category Lang
  11600. * @param {*} value The value to check.
  11601. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  11602. * @example
  11603. *
  11604. * _.isObjectLike({});
  11605. * // => true
  11606. *
  11607. * _.isObjectLike([1, 2, 3]);
  11608. * // => true
  11609. *
  11610. * _.isObjectLike(_.noop);
  11611. * // => false
  11612. *
  11613. * _.isObjectLike(null);
  11614. * // => false
  11615. */
  11616. function isObjectLike(value) {
  11617. return !!value && typeof value == 'object';
  11618. }
  11619. /**
  11620. * Checks if `value` is classified as a `Symbol` primitive or object.
  11621. *
  11622. * @static
  11623. * @memberOf _
  11624. * @since 4.0.0
  11625. * @category Lang
  11626. * @param {*} value The value to check.
  11627. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  11628. * @example
  11629. *
  11630. * _.isSymbol(Symbol.iterator);
  11631. * // => true
  11632. *
  11633. * _.isSymbol('abc');
  11634. * // => false
  11635. */
  11636. function isSymbol(value) {
  11637. return typeof value == 'symbol' ||
  11638. (isObjectLike(value) && objectToString.call(value) == symbolTag);
  11639. }
  11640. /**
  11641. * Converts `value` to a string. An empty string is returned for `null`
  11642. * and `undefined` values. The sign of `-0` is preserved.
  11643. *
  11644. * @static
  11645. * @memberOf _
  11646. * @since 4.0.0
  11647. * @category Lang
  11648. * @param {*} value The value to process.
  11649. * @returns {string} Returns the string.
  11650. * @example
  11651. *
  11652. * _.toString(null);
  11653. * // => ''
  11654. *
  11655. * _.toString(-0);
  11656. * // => '-0'
  11657. *
  11658. * _.toString([1, 2, 3]);
  11659. * // => '1,2,3'
  11660. */
  11661. function toString(value) {
  11662. return value == null ? '' : baseToString(value);
  11663. }
  11664. /**
  11665. * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
  11666. *
  11667. * @static
  11668. * @memberOf _
  11669. * @since 3.0.0
  11670. * @category String
  11671. * @param {string} [string=''] The string to convert.
  11672. * @returns {string} Returns the camel cased string.
  11673. * @example
  11674. *
  11675. * _.camelCase('Foo Bar');
  11676. * // => 'fooBar'
  11677. *
  11678. * _.camelCase('--foo-bar--');
  11679. * // => 'fooBar'
  11680. *
  11681. * _.camelCase('__FOO_BAR__');
  11682. * // => 'fooBar'
  11683. */
  11684. var camelCase = createCompounder(function(result, word, index) {
  11685. word = word.toLowerCase();
  11686. return result + (index ? capitalize(word) : word);
  11687. });
  11688. /**
  11689. * Converts the first character of `string` to upper case and the remaining
  11690. * to lower case.
  11691. *
  11692. * @static
  11693. * @memberOf _
  11694. * @since 3.0.0
  11695. * @category String
  11696. * @param {string} [string=''] The string to capitalize.
  11697. * @returns {string} Returns the capitalized string.
  11698. * @example
  11699. *
  11700. * _.capitalize('FRED');
  11701. * // => 'Fred'
  11702. */
  11703. function capitalize(string) {
  11704. return upperFirst(toString(string).toLowerCase());
  11705. }
  11706. /**
  11707. * Deburrs `string` by converting
  11708. * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
  11709. * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
  11710. * letters to basic Latin letters and removing
  11711. * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
  11712. *
  11713. * @static
  11714. * @memberOf _
  11715. * @since 3.0.0
  11716. * @category String
  11717. * @param {string} [string=''] The string to deburr.
  11718. * @returns {string} Returns the deburred string.
  11719. * @example
  11720. *
  11721. * _.deburr('déjà vu');
  11722. * // => 'deja vu'
  11723. */
  11724. function deburr(string) {
  11725. string = toString(string);
  11726. return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
  11727. }
  11728. /**
  11729. * Converts the first character of `string` to upper case.
  11730. *
  11731. * @static
  11732. * @memberOf _
  11733. * @since 4.0.0
  11734. * @category String
  11735. * @param {string} [string=''] The string to convert.
  11736. * @returns {string} Returns the converted string.
  11737. * @example
  11738. *
  11739. * _.upperFirst('fred');
  11740. * // => 'Fred'
  11741. *
  11742. * _.upperFirst('FRED');
  11743. * // => 'FRED'
  11744. */
  11745. var upperFirst = createCaseFirst('toUpperCase');
  11746. /**
  11747. * Splits `string` into an array of its words.
  11748. *
  11749. * @static
  11750. * @memberOf _
  11751. * @since 3.0.0
  11752. * @category String
  11753. * @param {string} [string=''] The string to inspect.
  11754. * @param {RegExp|string} [pattern] The pattern to match words.
  11755. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  11756. * @returns {Array} Returns the words of `string`.
  11757. * @example
  11758. *
  11759. * _.words('fred, barney, & pebbles');
  11760. * // => ['fred', 'barney', 'pebbles']
  11761. *
  11762. * _.words('fred, barney, & pebbles', /[^, ]+/g);
  11763. * // => ['fred', 'barney', '&', 'pebbles']
  11764. */
  11765. function words(string, pattern, guard) {
  11766. string = toString(string);
  11767. pattern = pattern;
  11768. if (pattern === undefined) {
  11769. return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
  11770. }
  11771. return string.match(pattern) || [];
  11772. }
  11773. lodash_camelcase = camelCase;
  11774. return lodash_camelcase;
  11775. }
  11776. var hasRequiredLocalsConvention;
  11777. function requireLocalsConvention () {
  11778. if (hasRequiredLocalsConvention) return localsConvention;
  11779. hasRequiredLocalsConvention = 1;
  11780. Object.defineProperty(localsConvention, "__esModule", {
  11781. value: true
  11782. });
  11783. localsConvention.makeLocalsConventionReducer = makeLocalsConventionReducer;
  11784. var _lodash = _interopRequireDefault(/*@__PURE__*/ requireLodash_camelcase());
  11785. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11786. function dashesCamelCase(string) {
  11787. return string.replace(/-+(\w)/g, (_, firstLetter) => firstLetter.toUpperCase());
  11788. }
  11789. function makeLocalsConventionReducer(localsConvention, inputFile) {
  11790. const isFunc = typeof localsConvention === "function";
  11791. return (tokens, [className, value]) => {
  11792. if (isFunc) {
  11793. const convention = localsConvention(className, value, inputFile);
  11794. tokens[convention] = value;
  11795. return tokens;
  11796. }
  11797. switch (localsConvention) {
  11798. case "camelCase":
  11799. tokens[className] = value;
  11800. tokens[(0, _lodash.default)(className)] = value;
  11801. break;
  11802. case "camelCaseOnly":
  11803. tokens[(0, _lodash.default)(className)] = value;
  11804. break;
  11805. case "dashes":
  11806. tokens[className] = value;
  11807. tokens[dashesCamelCase(className)] = value;
  11808. break;
  11809. case "dashesOnly":
  11810. tokens[dashesCamelCase(className)] = value;
  11811. break;
  11812. }
  11813. return tokens;
  11814. };
  11815. }
  11816. return localsConvention;
  11817. }
  11818. var FileSystemLoader = {};
  11819. var hasRequiredFileSystemLoader;
  11820. function requireFileSystemLoader () {
  11821. if (hasRequiredFileSystemLoader) return FileSystemLoader;
  11822. hasRequiredFileSystemLoader = 1;
  11823. Object.defineProperty(FileSystemLoader, "__esModule", {
  11824. value: true
  11825. });
  11826. FileSystemLoader.default = void 0;
  11827. var _postcss = _interopRequireDefault(require$$0$1);
  11828. var _path = _interopRequireDefault(path$1);
  11829. var _Parser = _interopRequireDefault(/*@__PURE__*/ requireParser$1());
  11830. var _fs = /*@__PURE__*/ requireFs();
  11831. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11832. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  11833. class Core {
  11834. constructor(plugins) {
  11835. this.plugins = plugins || Core.defaultPlugins;
  11836. }
  11837. async load(sourceString, sourcePath, trace, pathFetcher) {
  11838. const parser = new _Parser.default(pathFetcher, trace);
  11839. const plugins = this.plugins.concat([parser.plugin()]);
  11840. const result = await (0, _postcss.default)(plugins).process(sourceString, {
  11841. from: sourcePath
  11842. });
  11843. return {
  11844. injectableSource: result.css,
  11845. exportTokens: parser.exportTokens
  11846. };
  11847. }
  11848. } // Sorts dependencies in the following way:
  11849. // AAA comes before AA and A
  11850. // AB comes after AA and before A
  11851. // All Bs come after all As
  11852. // This ensures that the files are always returned in the following order:
  11853. // - In the order they were required, except
  11854. // - After all their dependencies
  11855. const traceKeySorter = (a, b) => {
  11856. if (a.length < b.length) {
  11857. return a < b.substring(0, a.length) ? -1 : 1;
  11858. }
  11859. if (a.length > b.length) {
  11860. return a.substring(0, b.length) <= b ? -1 : 1;
  11861. }
  11862. return a < b ? -1 : 1;
  11863. };
  11864. let FileSystemLoader$1 = class FileSystemLoader {
  11865. constructor(root, plugins, fileResolve) {
  11866. if (root === "/" && process.platform === "win32") {
  11867. const cwdDrive = process.cwd().slice(0, 3);
  11868. if (!/^[A-Za-z]:\\$/.test(cwdDrive)) {
  11869. throw new Error(`Failed to obtain root from "${process.cwd()}".`);
  11870. }
  11871. root = cwdDrive;
  11872. }
  11873. this.root = root;
  11874. this.fileResolve = fileResolve;
  11875. this.sources = {};
  11876. this.traces = {};
  11877. this.importNr = 0;
  11878. this.core = new Core(plugins);
  11879. this.tokensByFile = {};
  11880. this.fs = (0, _fs.getFileSystem)();
  11881. }
  11882. async fetch(_newPath, relativeTo, _trace) {
  11883. const newPath = _newPath.replace(/^["']|["']$/g, "");
  11884. const trace = _trace || String.fromCharCode(this.importNr++);
  11885. const useFileResolve = typeof this.fileResolve === "function";
  11886. const fileResolvedPath = useFileResolve ? await this.fileResolve(newPath, relativeTo) : await Promise.resolve();
  11887. if (fileResolvedPath && !_path.default.isAbsolute(fileResolvedPath)) {
  11888. throw new Error('The returned path from the "fileResolve" option must be absolute.');
  11889. }
  11890. const relativeDir = _path.default.dirname(relativeTo);
  11891. const rootRelativePath = fileResolvedPath || _path.default.resolve(relativeDir, newPath);
  11892. 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
  11893. if (!useFileResolve && newPath[0] !== "." && !_path.default.isAbsolute(newPath)) {
  11894. try {
  11895. fileRelativePath = require.resolve(newPath);
  11896. } catch (e) {// noop
  11897. }
  11898. }
  11899. const tokens = this.tokensByFile[fileRelativePath];
  11900. if (tokens) return tokens;
  11901. return new Promise((resolve, reject) => {
  11902. this.fs.readFile(fileRelativePath, "utf-8", async (err, source) => {
  11903. if (err) reject(err);
  11904. const {
  11905. injectableSource,
  11906. exportTokens
  11907. } = await this.core.load(source, rootRelativePath, trace, this.fetch.bind(this));
  11908. this.sources[fileRelativePath] = injectableSource;
  11909. this.traces[trace] = fileRelativePath;
  11910. this.tokensByFile[fileRelativePath] = exportTokens;
  11911. resolve(exportTokens);
  11912. });
  11913. });
  11914. }
  11915. get finalSource() {
  11916. const traces = this.traces;
  11917. const sources = this.sources;
  11918. let written = new Set();
  11919. return Object.keys(traces).sort(traceKeySorter).map(key => {
  11920. const filename = traces[key];
  11921. if (written.has(filename)) {
  11922. return null;
  11923. }
  11924. written.add(filename);
  11925. return sources[filename];
  11926. }).join("");
  11927. }
  11928. };
  11929. FileSystemLoader.default = FileSystemLoader$1;
  11930. return FileSystemLoader;
  11931. }
  11932. var scoping = {};
  11933. var src$3 = {exports: {}};
  11934. var topologicalSort_1;
  11935. var hasRequiredTopologicalSort;
  11936. function requireTopologicalSort () {
  11937. if (hasRequiredTopologicalSort) return topologicalSort_1;
  11938. hasRequiredTopologicalSort = 1;
  11939. const PERMANENT_MARKER = 2;
  11940. const TEMPORARY_MARKER = 1;
  11941. function createError(node, graph) {
  11942. const er = new Error("Nondeterministic import's order");
  11943. const related = graph[node];
  11944. const relatedNode = related.find(
  11945. (relatedNode) => graph[relatedNode].indexOf(node) > -1
  11946. );
  11947. er.nodes = [node, relatedNode];
  11948. return er;
  11949. }
  11950. function walkGraph(node, graph, state, result, strict) {
  11951. if (state[node] === PERMANENT_MARKER) {
  11952. return;
  11953. }
  11954. if (state[node] === TEMPORARY_MARKER) {
  11955. if (strict) {
  11956. return createError(node, graph);
  11957. }
  11958. return;
  11959. }
  11960. state[node] = TEMPORARY_MARKER;
  11961. const children = graph[node];
  11962. const length = children.length;
  11963. for (let i = 0; i < length; ++i) {
  11964. const error = walkGraph(children[i], graph, state, result, strict);
  11965. if (error instanceof Error) {
  11966. return error;
  11967. }
  11968. }
  11969. state[node] = PERMANENT_MARKER;
  11970. result.push(node);
  11971. }
  11972. function topologicalSort(graph, strict) {
  11973. const result = [];
  11974. const state = {};
  11975. const nodes = Object.keys(graph);
  11976. const length = nodes.length;
  11977. for (let i = 0; i < length; ++i) {
  11978. const er = walkGraph(nodes[i], graph, state, result, strict);
  11979. if (er instanceof Error) {
  11980. return er;
  11981. }
  11982. }
  11983. return result;
  11984. }
  11985. topologicalSort_1 = topologicalSort;
  11986. return topologicalSort_1;
  11987. }
  11988. var hasRequiredSrc$3;
  11989. function requireSrc$3 () {
  11990. if (hasRequiredSrc$3) return src$3.exports;
  11991. hasRequiredSrc$3 = 1;
  11992. const topologicalSort = /*@__PURE__*/ requireTopologicalSort();
  11993. const matchImports = /^(.+?)\s+from\s+(?:"([^"]+)"|'([^']+)'|(global))$/;
  11994. const icssImport = /^:import\((?:"([^"]+)"|'([^']+)')\)/;
  11995. const VISITED_MARKER = 1;
  11996. /**
  11997. * :import('G') {}
  11998. *
  11999. * Rule
  12000. * composes: ... from 'A'
  12001. * composes: ... from 'B'
  12002. * Rule
  12003. * composes: ... from 'A'
  12004. * composes: ... from 'A'
  12005. * composes: ... from 'C'
  12006. *
  12007. * Results in:
  12008. *
  12009. * graph: {
  12010. * G: [],
  12011. * A: [],
  12012. * B: ['A'],
  12013. * C: ['A'],
  12014. * }
  12015. */
  12016. function addImportToGraph(importId, parentId, graph, visited) {
  12017. const siblingsId = parentId + "_" + "siblings";
  12018. const visitedId = parentId + "_" + importId;
  12019. if (visited[visitedId] !== VISITED_MARKER) {
  12020. if (!Array.isArray(visited[siblingsId])) {
  12021. visited[siblingsId] = [];
  12022. }
  12023. const siblings = visited[siblingsId];
  12024. if (Array.isArray(graph[importId])) {
  12025. graph[importId] = graph[importId].concat(siblings);
  12026. } else {
  12027. graph[importId] = siblings.slice();
  12028. }
  12029. visited[visitedId] = VISITED_MARKER;
  12030. siblings.push(importId);
  12031. }
  12032. }
  12033. src$3.exports = (options = {}) => {
  12034. let importIndex = 0;
  12035. const createImportedName =
  12036. typeof options.createImportedName !== "function"
  12037. ? (importName /*, path*/) =>
  12038. `i__imported_${importName.replace(/\W/g, "_")}_${importIndex++}`
  12039. : options.createImportedName;
  12040. const failOnWrongOrder = options.failOnWrongOrder;
  12041. return {
  12042. postcssPlugin: "postcss-modules-extract-imports",
  12043. prepare() {
  12044. const graph = {};
  12045. const visited = {};
  12046. const existingImports = {};
  12047. const importDecls = {};
  12048. const imports = {};
  12049. return {
  12050. Once(root, postcss) {
  12051. // Check the existing imports order and save refs
  12052. root.walkRules((rule) => {
  12053. const matches = icssImport.exec(rule.selector);
  12054. if (matches) {
  12055. const [, /*match*/ doubleQuotePath, singleQuotePath] = matches;
  12056. const importPath = doubleQuotePath || singleQuotePath;
  12057. addImportToGraph(importPath, "root", graph, visited);
  12058. existingImports[importPath] = rule;
  12059. }
  12060. });
  12061. root.walkDecls(/^composes$/, (declaration) => {
  12062. const multiple = declaration.value.split(",");
  12063. const values = [];
  12064. multiple.forEach((value) => {
  12065. const matches = value.trim().match(matchImports);
  12066. if (!matches) {
  12067. values.push(value);
  12068. return;
  12069. }
  12070. let tmpSymbols;
  12071. let [
  12072. ,
  12073. /*match*/ symbols,
  12074. doubleQuotePath,
  12075. singleQuotePath,
  12076. global,
  12077. ] = matches;
  12078. if (global) {
  12079. // Composing globals simply means changing these classes to wrap them in global(name)
  12080. tmpSymbols = symbols.split(/\s+/).map((s) => `global(${s})`);
  12081. } else {
  12082. const importPath = doubleQuotePath || singleQuotePath;
  12083. let parent = declaration.parent;
  12084. let parentIndexes = "";
  12085. while (parent.type !== "root") {
  12086. parentIndexes =
  12087. parent.parent.index(parent) + "_" + parentIndexes;
  12088. parent = parent.parent;
  12089. }
  12090. const { selector } = declaration.parent;
  12091. const parentRule = `_${parentIndexes}${selector}`;
  12092. addImportToGraph(importPath, parentRule, graph, visited);
  12093. importDecls[importPath] = declaration;
  12094. imports[importPath] = imports[importPath] || {};
  12095. tmpSymbols = symbols.split(/\s+/).map((s) => {
  12096. if (!imports[importPath][s]) {
  12097. imports[importPath][s] = createImportedName(s, importPath);
  12098. }
  12099. return imports[importPath][s];
  12100. });
  12101. }
  12102. values.push(tmpSymbols.join(" "));
  12103. });
  12104. declaration.value = values.join(", ");
  12105. });
  12106. const importsOrder = topologicalSort(graph, failOnWrongOrder);
  12107. if (importsOrder instanceof Error) {
  12108. const importPath = importsOrder.nodes.find((importPath) =>
  12109. // eslint-disable-next-line no-prototype-builtins
  12110. importDecls.hasOwnProperty(importPath)
  12111. );
  12112. const decl = importDecls[importPath];
  12113. throw decl.error(
  12114. "Failed to resolve order of composed modules " +
  12115. importsOrder.nodes
  12116. .map((importPath) => "`" + importPath + "`")
  12117. .join(", ") +
  12118. ".",
  12119. {
  12120. plugin: "postcss-modules-extract-imports",
  12121. word: "composes",
  12122. }
  12123. );
  12124. }
  12125. let lastImportRule;
  12126. importsOrder.forEach((path) => {
  12127. const importedSymbols = imports[path];
  12128. let rule = existingImports[path];
  12129. if (!rule && importedSymbols) {
  12130. rule = postcss.rule({
  12131. selector: `:import("${path}")`,
  12132. raws: { after: "\n" },
  12133. });
  12134. if (lastImportRule) {
  12135. root.insertAfter(lastImportRule, rule);
  12136. } else {
  12137. root.prepend(rule);
  12138. }
  12139. }
  12140. lastImportRule = rule;
  12141. if (!importedSymbols) {
  12142. return;
  12143. }
  12144. Object.keys(importedSymbols).forEach((importedSymbol) => {
  12145. rule.append(
  12146. postcss.decl({
  12147. value: importedSymbol,
  12148. prop: importedSymbols[importedSymbol],
  12149. raws: { before: "\n " },
  12150. })
  12151. );
  12152. });
  12153. });
  12154. },
  12155. };
  12156. },
  12157. };
  12158. };
  12159. src$3.exports.postcss = true;
  12160. return src$3.exports;
  12161. }
  12162. var wasmHash = {exports: {}};
  12163. /*
  12164. MIT License http://www.opensource.org/licenses/mit-license.php
  12165. Author Tobias Koppers @sokra
  12166. */
  12167. var hasRequiredWasmHash;
  12168. function requireWasmHash () {
  12169. if (hasRequiredWasmHash) return wasmHash.exports;
  12170. hasRequiredWasmHash = 1;
  12171. // 65536 is the size of a wasm memory page
  12172. // 64 is the maximum chunk size for every possible wasm hash implementation
  12173. // 4 is the maximum number of bytes per char for string encoding (max is utf-8)
  12174. // ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64
  12175. const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & -4;
  12176. class WasmHash {
  12177. /**
  12178. * @param {WebAssembly.Instance} instance wasm instance
  12179. * @param {WebAssembly.Instance[]} instancesPool pool of instances
  12180. * @param {number} chunkSize size of data chunks passed to wasm
  12181. * @param {number} digestSize size of digest returned by wasm
  12182. */
  12183. constructor(instance, instancesPool, chunkSize, digestSize) {
  12184. const exports$1 = /** @type {any} */ (instance.exports);
  12185. exports$1.init();
  12186. this.exports = exports$1;
  12187. this.mem = Buffer.from(exports$1.memory.buffer, 0, 65536);
  12188. this.buffered = 0;
  12189. this.instancesPool = instancesPool;
  12190. this.chunkSize = chunkSize;
  12191. this.digestSize = digestSize;
  12192. }
  12193. reset() {
  12194. this.buffered = 0;
  12195. this.exports.init();
  12196. }
  12197. /**
  12198. * @param {Buffer | string} data data
  12199. * @param {BufferEncoding=} encoding encoding
  12200. * @returns {this} itself
  12201. */
  12202. update(data, encoding) {
  12203. if (typeof data === "string") {
  12204. while (data.length > MAX_SHORT_STRING) {
  12205. this._updateWithShortString(data.slice(0, MAX_SHORT_STRING), encoding);
  12206. data = data.slice(MAX_SHORT_STRING);
  12207. }
  12208. this._updateWithShortString(data, encoding);
  12209. return this;
  12210. }
  12211. this._updateWithBuffer(data);
  12212. return this;
  12213. }
  12214. /**
  12215. * @param {string} data data
  12216. * @param {BufferEncoding=} encoding encoding
  12217. * @returns {void}
  12218. */
  12219. _updateWithShortString(data, encoding) {
  12220. const { exports: exports$1, buffered, mem, chunkSize } = this;
  12221. let endPos;
  12222. if (data.length < 70) {
  12223. if (!encoding || encoding === "utf-8" || encoding === "utf8") {
  12224. endPos = buffered;
  12225. for (let i = 0; i < data.length; i++) {
  12226. const cc = data.charCodeAt(i);
  12227. if (cc < 0x80) {
  12228. mem[endPos++] = cc;
  12229. } else if (cc < 0x800) {
  12230. mem[endPos] = (cc >> 6) | 0xc0;
  12231. mem[endPos + 1] = (cc & 0x3f) | 0x80;
  12232. endPos += 2;
  12233. } else {
  12234. // bail-out for weird chars
  12235. endPos += mem.write(data.slice(i), endPos, encoding);
  12236. break;
  12237. }
  12238. }
  12239. } else if (encoding === "latin1") {
  12240. endPos = buffered;
  12241. for (let i = 0; i < data.length; i++) {
  12242. const cc = data.charCodeAt(i);
  12243. mem[endPos++] = cc;
  12244. }
  12245. } else {
  12246. endPos = buffered + mem.write(data, buffered, encoding);
  12247. }
  12248. } else {
  12249. endPos = buffered + mem.write(data, buffered, encoding);
  12250. }
  12251. if (endPos < chunkSize) {
  12252. this.buffered = endPos;
  12253. } else {
  12254. const l = endPos & ~(this.chunkSize - 1);
  12255. exports$1.update(l);
  12256. const newBuffered = endPos - l;
  12257. this.buffered = newBuffered;
  12258. if (newBuffered > 0) {
  12259. mem.copyWithin(0, l, endPos);
  12260. }
  12261. }
  12262. }
  12263. /**
  12264. * @param {Buffer} data data
  12265. * @returns {void}
  12266. */
  12267. _updateWithBuffer(data) {
  12268. const { exports: exports$1, buffered, mem } = this;
  12269. const length = data.length;
  12270. if (buffered + length < this.chunkSize) {
  12271. data.copy(mem, buffered, 0, length);
  12272. this.buffered += length;
  12273. } else {
  12274. const l = (buffered + length) & ~(this.chunkSize - 1);
  12275. if (l > 65536) {
  12276. let i = 65536 - buffered;
  12277. data.copy(mem, buffered, 0, i);
  12278. exports$1.update(65536);
  12279. const stop = l - buffered - 65536;
  12280. while (i < stop) {
  12281. data.copy(mem, 0, i, i + 65536);
  12282. exports$1.update(65536);
  12283. i += 65536;
  12284. }
  12285. data.copy(mem, 0, i, l - buffered);
  12286. exports$1.update(l - buffered - i);
  12287. } else {
  12288. data.copy(mem, buffered, 0, l - buffered);
  12289. exports$1.update(l);
  12290. }
  12291. const newBuffered = length + buffered - l;
  12292. this.buffered = newBuffered;
  12293. if (newBuffered > 0) {
  12294. data.copy(mem, 0, length - newBuffered, length);
  12295. }
  12296. }
  12297. }
  12298. digest(type) {
  12299. const { exports: exports$1, buffered, mem, digestSize } = this;
  12300. exports$1.final(buffered);
  12301. this.instancesPool.push(this);
  12302. const hex = mem.toString("latin1", 0, digestSize);
  12303. if (type === "hex") {
  12304. return hex;
  12305. }
  12306. if (type === "binary" || !type) {
  12307. return Buffer.from(hex, "hex");
  12308. }
  12309. return Buffer.from(hex, "hex").toString(type);
  12310. }
  12311. }
  12312. const create = (wasmModule, instancesPool, chunkSize, digestSize) => {
  12313. if (instancesPool.length > 0) {
  12314. const old = instancesPool.pop();
  12315. old.reset();
  12316. return old;
  12317. } else {
  12318. return new WasmHash(
  12319. new WebAssembly.Instance(wasmModule),
  12320. instancesPool,
  12321. chunkSize,
  12322. digestSize
  12323. );
  12324. }
  12325. };
  12326. wasmHash.exports = create;
  12327. wasmHash.exports.MAX_SHORT_STRING = MAX_SHORT_STRING;
  12328. return wasmHash.exports;
  12329. }
  12330. /*
  12331. MIT License http://www.opensource.org/licenses/mit-license.php
  12332. Author Tobias Koppers @sokra
  12333. */
  12334. var xxhash64_1;
  12335. var hasRequiredXxhash64;
  12336. function requireXxhash64 () {
  12337. if (hasRequiredXxhash64) return xxhash64_1;
  12338. hasRequiredXxhash64 = 1;
  12339. const create = /*@__PURE__*/ requireWasmHash();
  12340. //#region wasm code: xxhash64 (../../../assembly/hash/xxhash64.asm.ts) --initialMemory 1
  12341. const xxhash64 = new WebAssembly.Module(
  12342. Buffer.from(
  12343. // 1173 bytes
  12344. "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",
  12345. "base64"
  12346. )
  12347. );
  12348. //#endregion
  12349. xxhash64_1 = create.bind(null, xxhash64, [], 32, 16);
  12350. return xxhash64_1;
  12351. }
  12352. var BatchedHash_1;
  12353. var hasRequiredBatchedHash;
  12354. function requireBatchedHash () {
  12355. if (hasRequiredBatchedHash) return BatchedHash_1;
  12356. hasRequiredBatchedHash = 1;
  12357. const MAX_SHORT_STRING = /*@__PURE__*/ requireWasmHash().MAX_SHORT_STRING;
  12358. class BatchedHash {
  12359. constructor(hash) {
  12360. this.string = undefined;
  12361. this.encoding = undefined;
  12362. this.hash = hash;
  12363. }
  12364. /**
  12365. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  12366. * @param {string|Buffer} data data
  12367. * @param {string=} inputEncoding data encoding
  12368. * @returns {this} updated hash
  12369. */
  12370. update(data, inputEncoding) {
  12371. if (this.string !== undefined) {
  12372. if (
  12373. typeof data === "string" &&
  12374. inputEncoding === this.encoding &&
  12375. this.string.length + data.length < MAX_SHORT_STRING
  12376. ) {
  12377. this.string += data;
  12378. return this;
  12379. }
  12380. this.hash.update(this.string, this.encoding);
  12381. this.string = undefined;
  12382. }
  12383. if (typeof data === "string") {
  12384. if (
  12385. data.length < MAX_SHORT_STRING &&
  12386. // base64 encoding is not valid since it may contain padding chars
  12387. (!inputEncoding || !inputEncoding.startsWith("ba"))
  12388. ) {
  12389. this.string = data;
  12390. this.encoding = inputEncoding;
  12391. } else {
  12392. this.hash.update(data, inputEncoding);
  12393. }
  12394. } else {
  12395. this.hash.update(data);
  12396. }
  12397. return this;
  12398. }
  12399. /**
  12400. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  12401. * @param {string=} encoding encoding of the return value
  12402. * @returns {string|Buffer} digest
  12403. */
  12404. digest(encoding) {
  12405. if (this.string !== undefined) {
  12406. this.hash.update(this.string, this.encoding);
  12407. }
  12408. return this.hash.digest(encoding);
  12409. }
  12410. }
  12411. BatchedHash_1 = BatchedHash;
  12412. return BatchedHash_1;
  12413. }
  12414. /*
  12415. MIT License http://www.opensource.org/licenses/mit-license.php
  12416. Author Tobias Koppers @sokra
  12417. */
  12418. var md4_1;
  12419. var hasRequiredMd4;
  12420. function requireMd4 () {
  12421. if (hasRequiredMd4) return md4_1;
  12422. hasRequiredMd4 = 1;
  12423. const create = /*@__PURE__*/ requireWasmHash();
  12424. //#region wasm code: md4 (../../../assembly/hash/md4.asm.ts) --initialMemory 1
  12425. const md4 = new WebAssembly.Module(
  12426. Buffer.from(
  12427. // 2150 bytes
  12428. "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=",
  12429. "base64"
  12430. )
  12431. );
  12432. //#endregion
  12433. md4_1 = create.bind(null, md4, [], 64, 32);
  12434. return md4_1;
  12435. }
  12436. var BulkUpdateDecorator_1;
  12437. var hasRequiredBulkUpdateDecorator;
  12438. function requireBulkUpdateDecorator () {
  12439. if (hasRequiredBulkUpdateDecorator) return BulkUpdateDecorator_1;
  12440. hasRequiredBulkUpdateDecorator = 1;
  12441. const BULK_SIZE = 2000;
  12442. // We are using an object instead of a Map as this will stay static during the runtime
  12443. // so access to it can be optimized by v8
  12444. const digestCaches = {};
  12445. class BulkUpdateDecorator {
  12446. /**
  12447. * @param {Hash | function(): Hash} hashOrFactory function to create a hash
  12448. * @param {string=} hashKey key for caching
  12449. */
  12450. constructor(hashOrFactory, hashKey) {
  12451. this.hashKey = hashKey;
  12452. if (typeof hashOrFactory === "function") {
  12453. this.hashFactory = hashOrFactory;
  12454. this.hash = undefined;
  12455. } else {
  12456. this.hashFactory = undefined;
  12457. this.hash = hashOrFactory;
  12458. }
  12459. this.buffer = "";
  12460. }
  12461. /**
  12462. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  12463. * @param {string|Buffer} data data
  12464. * @param {string=} inputEncoding data encoding
  12465. * @returns {this} updated hash
  12466. */
  12467. update(data, inputEncoding) {
  12468. if (
  12469. inputEncoding !== undefined ||
  12470. typeof data !== "string" ||
  12471. data.length > BULK_SIZE
  12472. ) {
  12473. if (this.hash === undefined) {
  12474. this.hash = this.hashFactory();
  12475. }
  12476. if (this.buffer.length > 0) {
  12477. this.hash.update(this.buffer);
  12478. this.buffer = "";
  12479. }
  12480. this.hash.update(data, inputEncoding);
  12481. } else {
  12482. this.buffer += data;
  12483. if (this.buffer.length > BULK_SIZE) {
  12484. if (this.hash === undefined) {
  12485. this.hash = this.hashFactory();
  12486. }
  12487. this.hash.update(this.buffer);
  12488. this.buffer = "";
  12489. }
  12490. }
  12491. return this;
  12492. }
  12493. /**
  12494. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  12495. * @param {string=} encoding encoding of the return value
  12496. * @returns {string|Buffer} digest
  12497. */
  12498. digest(encoding) {
  12499. let digestCache;
  12500. const buffer = this.buffer;
  12501. if (this.hash === undefined) {
  12502. // short data for hash, we can use caching
  12503. const cacheKey = `${this.hashKey}-${encoding}`;
  12504. digestCache = digestCaches[cacheKey];
  12505. if (digestCache === undefined) {
  12506. digestCache = digestCaches[cacheKey] = new Map();
  12507. }
  12508. const cacheEntry = digestCache.get(buffer);
  12509. if (cacheEntry !== undefined) {
  12510. return cacheEntry;
  12511. }
  12512. this.hash = this.hashFactory();
  12513. }
  12514. if (buffer.length > 0) {
  12515. this.hash.update(buffer);
  12516. }
  12517. const digestResult = this.hash.digest(encoding);
  12518. if (digestCache !== undefined) {
  12519. digestCache.set(buffer, digestResult);
  12520. }
  12521. return digestResult;
  12522. }
  12523. }
  12524. BulkUpdateDecorator_1 = BulkUpdateDecorator;
  12525. return BulkUpdateDecorator_1;
  12526. }
  12527. var getHashDigest_1;
  12528. var hasRequiredGetHashDigest;
  12529. function requireGetHashDigest () {
  12530. if (hasRequiredGetHashDigest) return getHashDigest_1;
  12531. hasRequiredGetHashDigest = 1;
  12532. const baseEncodeTables = {
  12533. 26: "abcdefghijklmnopqrstuvwxyz",
  12534. 32: "123456789abcdefghjkmnpqrstuvwxyz", // no 0lio
  12535. 36: "0123456789abcdefghijklmnopqrstuvwxyz",
  12536. 49: "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no lIO
  12537. 52: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12538. 58: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no 0lIO
  12539. 62: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12540. 64: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_",
  12541. };
  12542. /**
  12543. * @param {Uint32Array} uint32Array Treated as a long base-0x100000000 number, little endian
  12544. * @param {number} divisor The divisor
  12545. * @return {number} Modulo (remainder) of the division
  12546. */
  12547. function divmod32(uint32Array, divisor) {
  12548. let carry = 0;
  12549. for (let i = uint32Array.length - 1; i >= 0; i--) {
  12550. const value = carry * 0x100000000 + uint32Array[i];
  12551. carry = value % divisor;
  12552. uint32Array[i] = Math.floor(value / divisor);
  12553. }
  12554. return carry;
  12555. }
  12556. function encodeBufferToBase(buffer, base, length) {
  12557. const encodeTable = baseEncodeTables[base];
  12558. if (!encodeTable) {
  12559. throw new Error("Unknown encoding base" + base);
  12560. }
  12561. // Input bits are only enough to generate this many characters
  12562. const limit = Math.ceil((buffer.length * 8) / Math.log2(base));
  12563. length = Math.min(length, limit);
  12564. // Most of the crypto digests (if not all) has length a multiple of 4 bytes.
  12565. // Fewer numbers in the array means faster math.
  12566. const uint32Array = new Uint32Array(Math.ceil(buffer.length / 4));
  12567. // Make sure the input buffer data is copied and is not mutated by reference.
  12568. // divmod32() would corrupt the BulkUpdateDecorator cache otherwise.
  12569. buffer.copy(Buffer.from(uint32Array.buffer));
  12570. let output = "";
  12571. for (let i = 0; i < length; i++) {
  12572. output = encodeTable[divmod32(uint32Array, base)] + output;
  12573. }
  12574. return output;
  12575. }
  12576. let crypto = undefined;
  12577. let createXXHash64 = undefined;
  12578. let createMd4 = undefined;
  12579. let BatchedHash = undefined;
  12580. let BulkUpdateDecorator = undefined;
  12581. function getHashDigest(buffer, algorithm, digestType, maxLength) {
  12582. algorithm = algorithm || "xxhash64";
  12583. maxLength = maxLength || 9999;
  12584. let hash;
  12585. if (algorithm === "xxhash64") {
  12586. if (createXXHash64 === undefined) {
  12587. createXXHash64 = /*@__PURE__*/ requireXxhash64();
  12588. if (BatchedHash === undefined) {
  12589. BatchedHash = /*@__PURE__*/ requireBatchedHash();
  12590. }
  12591. }
  12592. hash = new BatchedHash(createXXHash64());
  12593. } else if (algorithm === "md4") {
  12594. if (createMd4 === undefined) {
  12595. createMd4 = /*@__PURE__*/ requireMd4();
  12596. if (BatchedHash === undefined) {
  12597. BatchedHash = /*@__PURE__*/ requireBatchedHash();
  12598. }
  12599. }
  12600. hash = new BatchedHash(createMd4());
  12601. } else if (algorithm === "native-md4") {
  12602. if (typeof crypto === "undefined") {
  12603. crypto = require("crypto");
  12604. if (BulkUpdateDecorator === undefined) {
  12605. BulkUpdateDecorator = /*@__PURE__*/ requireBulkUpdateDecorator();
  12606. }
  12607. }
  12608. hash = new BulkUpdateDecorator(() => crypto.createHash("md4"), "md4");
  12609. } else {
  12610. if (typeof crypto === "undefined") {
  12611. crypto = require("crypto");
  12612. if (BulkUpdateDecorator === undefined) {
  12613. BulkUpdateDecorator = /*@__PURE__*/ requireBulkUpdateDecorator();
  12614. }
  12615. }
  12616. hash = new BulkUpdateDecorator(
  12617. () => crypto.createHash(algorithm),
  12618. algorithm
  12619. );
  12620. }
  12621. hash.update(buffer);
  12622. if (
  12623. digestType === "base26" ||
  12624. digestType === "base32" ||
  12625. digestType === "base36" ||
  12626. digestType === "base49" ||
  12627. digestType === "base52" ||
  12628. digestType === "base58" ||
  12629. digestType === "base62" ||
  12630. digestType === "base64safe"
  12631. ) {
  12632. return encodeBufferToBase(
  12633. hash.digest(),
  12634. digestType === "base64safe" ? 64 : digestType.substr(4),
  12635. maxLength
  12636. );
  12637. }
  12638. return hash.digest(digestType || "hex").substr(0, maxLength);
  12639. }
  12640. getHashDigest_1 = getHashDigest;
  12641. return getHashDigest_1;
  12642. }
  12643. var interpolateName_1;
  12644. var hasRequiredInterpolateName;
  12645. function requireInterpolateName () {
  12646. if (hasRequiredInterpolateName) return interpolateName_1;
  12647. hasRequiredInterpolateName = 1;
  12648. const path = path$1;
  12649. const getHashDigest = /*@__PURE__*/ requireGetHashDigest();
  12650. function interpolateName(loaderContext, name, options = {}) {
  12651. let filename;
  12652. const hasQuery =
  12653. loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1;
  12654. if (typeof name === "function") {
  12655. filename = name(
  12656. loaderContext.resourcePath,
  12657. hasQuery ? loaderContext.resourceQuery : undefined
  12658. );
  12659. } else {
  12660. filename = name || "[hash].[ext]";
  12661. }
  12662. const context = options.context;
  12663. const content = options.content;
  12664. const regExp = options.regExp;
  12665. let ext = "bin";
  12666. let basename = "file";
  12667. let directory = "";
  12668. let folder = "";
  12669. let query = "";
  12670. if (loaderContext.resourcePath) {
  12671. const parsed = path.parse(loaderContext.resourcePath);
  12672. let resourcePath = loaderContext.resourcePath;
  12673. if (parsed.ext) {
  12674. ext = parsed.ext.substr(1);
  12675. }
  12676. if (parsed.dir) {
  12677. basename = parsed.name;
  12678. resourcePath = parsed.dir + path.sep;
  12679. }
  12680. if (typeof context !== "undefined") {
  12681. directory = path
  12682. .relative(context, resourcePath + "_")
  12683. .replace(/\\/g, "/")
  12684. .replace(/\.\.(\/)?/g, "_$1");
  12685. directory = directory.substr(0, directory.length - 1);
  12686. } else {
  12687. directory = resourcePath.replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
  12688. }
  12689. if (directory.length <= 1) {
  12690. directory = "";
  12691. } else {
  12692. // directory.length > 1
  12693. folder = path.basename(directory);
  12694. }
  12695. }
  12696. if (loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1) {
  12697. query = loaderContext.resourceQuery;
  12698. const hashIdx = query.indexOf("#");
  12699. if (hashIdx >= 0) {
  12700. query = query.substr(0, hashIdx);
  12701. }
  12702. }
  12703. let url = filename;
  12704. if (content) {
  12705. // Match hash template
  12706. url = url
  12707. // `hash` and `contenthash` are same in `loader-utils` context
  12708. // let's keep `hash` for backward compatibility
  12709. .replace(
  12710. /\[(?:([^[:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*(?:safe)?))?(?::(\d+))?\]/gi,
  12711. (all, hashType, digestType, maxLength) =>
  12712. getHashDigest(content, hashType, digestType, parseInt(maxLength, 10))
  12713. );
  12714. }
  12715. url = url
  12716. .replace(/\[ext\]/gi, () => ext)
  12717. .replace(/\[name\]/gi, () => basename)
  12718. .replace(/\[path\]/gi, () => directory)
  12719. .replace(/\[folder\]/gi, () => folder)
  12720. .replace(/\[query\]/gi, () => query);
  12721. if (regExp && loaderContext.resourcePath) {
  12722. const match = loaderContext.resourcePath.match(new RegExp(regExp));
  12723. match &&
  12724. match.forEach((matched, i) => {
  12725. url = url.replace(new RegExp("\\[" + i + "\\]", "ig"), matched);
  12726. });
  12727. }
  12728. if (
  12729. typeof loaderContext.options === "object" &&
  12730. typeof loaderContext.options.customInterpolateName === "function"
  12731. ) {
  12732. url = loaderContext.options.customInterpolateName.call(
  12733. loaderContext,
  12734. url,
  12735. name,
  12736. options
  12737. );
  12738. }
  12739. return url;
  12740. }
  12741. interpolateName_1 = interpolateName;
  12742. return interpolateName_1;
  12743. }
  12744. var genericNames;
  12745. var hasRequiredGenericNames;
  12746. function requireGenericNames () {
  12747. if (hasRequiredGenericNames) return genericNames;
  12748. hasRequiredGenericNames = 1;
  12749. var interpolateName = /*@__PURE__*/ requireInterpolateName();
  12750. var path = path$1;
  12751. /**
  12752. * @param {string} pattern
  12753. * @param {object} options
  12754. * @param {string} options.context
  12755. * @param {string} options.hashPrefix
  12756. * @return {function}
  12757. */
  12758. genericNames = function createGenerator(pattern, options) {
  12759. options = options || {};
  12760. var context =
  12761. options && typeof options.context === "string"
  12762. ? options.context
  12763. : process.cwd();
  12764. var hashPrefix =
  12765. options && typeof options.hashPrefix === "string" ? options.hashPrefix : "";
  12766. /**
  12767. * @param {string} localName Usually a class name
  12768. * @param {string} filepath Absolute path
  12769. * @return {string}
  12770. */
  12771. return function generate(localName, filepath) {
  12772. var name = pattern.replace(/\[local\]/gi, localName);
  12773. var loaderContext = {
  12774. resourcePath: filepath,
  12775. };
  12776. var loaderOptions = {
  12777. content:
  12778. hashPrefix +
  12779. path.relative(context, filepath).replace(/\\/g, "/") +
  12780. "\x00" +
  12781. localName,
  12782. context: context,
  12783. };
  12784. var genericName = interpolateName(loaderContext, name, loaderOptions);
  12785. return genericName
  12786. .replace(new RegExp("[^a-zA-Z0-9\\-_\u00A0-\uFFFF]", "g"), "-")
  12787. .replace(/^((-?[0-9])|--)/, "_$1");
  12788. };
  12789. };
  12790. return genericNames;
  12791. }
  12792. var src$2 = {exports: {}};
  12793. var dist = {exports: {}};
  12794. var processor = {exports: {}};
  12795. var parser = {exports: {}};
  12796. var root = {exports: {}};
  12797. var container = {exports: {}};
  12798. var node = {exports: {}};
  12799. var util = {};
  12800. var unesc = {exports: {}};
  12801. var hasRequiredUnesc;
  12802. function requireUnesc () {
  12803. if (hasRequiredUnesc) return unesc.exports;
  12804. hasRequiredUnesc = 1;
  12805. (function (module, exports$1) {
  12806. exports$1.__esModule = true;
  12807. exports$1["default"] = unesc;
  12808. // Many thanks for this post which made this migration much easier.
  12809. // https://mathiasbynens.be/notes/css-escapes
  12810. /**
  12811. *
  12812. * @param {string} str
  12813. * @returns {[string, number]|undefined}
  12814. */
  12815. function gobbleHex(str) {
  12816. var lower = str.toLowerCase();
  12817. var hex = '';
  12818. var spaceTerminated = false;
  12819. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  12820. var code = lower.charCodeAt(i);
  12821. // check to see if we are dealing with a valid hex char [a-f|0-9]
  12822. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
  12823. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  12824. spaceTerminated = code === 32;
  12825. if (!valid) {
  12826. break;
  12827. }
  12828. hex += lower[i];
  12829. }
  12830. if (hex.length === 0) {
  12831. return undefined;
  12832. }
  12833. var codePoint = parseInt(hex, 16);
  12834. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
  12835. // Add special case for
  12836. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  12837. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  12838. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  12839. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  12840. }
  12841. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  12842. }
  12843. var CONTAINS_ESCAPE = /\\/;
  12844. function unesc(str) {
  12845. var needToProcess = CONTAINS_ESCAPE.test(str);
  12846. if (!needToProcess) {
  12847. return str;
  12848. }
  12849. var ret = "";
  12850. for (var i = 0; i < str.length; i++) {
  12851. if (str[i] === "\\") {
  12852. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  12853. if (gobbled !== undefined) {
  12854. ret += gobbled[0];
  12855. i += gobbled[1];
  12856. continue;
  12857. }
  12858. // Retain a pair of \\ if double escaped `\\\\`
  12859. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  12860. if (str[i + 1] === "\\") {
  12861. ret += "\\";
  12862. i++;
  12863. continue;
  12864. }
  12865. // if \\ is at the end of the string retain it
  12866. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  12867. if (str.length === i + 1) {
  12868. ret += str[i];
  12869. }
  12870. continue;
  12871. }
  12872. ret += str[i];
  12873. }
  12874. return ret;
  12875. }
  12876. module.exports = exports$1.default;
  12877. } (unesc, unesc.exports));
  12878. return unesc.exports;
  12879. }
  12880. var getProp = {exports: {}};
  12881. var hasRequiredGetProp;
  12882. function requireGetProp () {
  12883. if (hasRequiredGetProp) return getProp.exports;
  12884. hasRequiredGetProp = 1;
  12885. (function (module, exports$1) {
  12886. exports$1.__esModule = true;
  12887. exports$1["default"] = getProp;
  12888. function getProp(obj) {
  12889. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  12890. props[_key - 1] = arguments[_key];
  12891. }
  12892. while (props.length > 0) {
  12893. var prop = props.shift();
  12894. if (!obj[prop]) {
  12895. return undefined;
  12896. }
  12897. obj = obj[prop];
  12898. }
  12899. return obj;
  12900. }
  12901. module.exports = exports$1.default;
  12902. } (getProp, getProp.exports));
  12903. return getProp.exports;
  12904. }
  12905. var ensureObject = {exports: {}};
  12906. var hasRequiredEnsureObject;
  12907. function requireEnsureObject () {
  12908. if (hasRequiredEnsureObject) return ensureObject.exports;
  12909. hasRequiredEnsureObject = 1;
  12910. (function (module, exports$1) {
  12911. exports$1.__esModule = true;
  12912. exports$1["default"] = ensureObject;
  12913. function ensureObject(obj) {
  12914. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  12915. props[_key - 1] = arguments[_key];
  12916. }
  12917. while (props.length > 0) {
  12918. var prop = props.shift();
  12919. if (!obj[prop]) {
  12920. obj[prop] = {};
  12921. }
  12922. obj = obj[prop];
  12923. }
  12924. }
  12925. module.exports = exports$1.default;
  12926. } (ensureObject, ensureObject.exports));
  12927. return ensureObject.exports;
  12928. }
  12929. var stripComments = {exports: {}};
  12930. var hasRequiredStripComments;
  12931. function requireStripComments () {
  12932. if (hasRequiredStripComments) return stripComments.exports;
  12933. hasRequiredStripComments = 1;
  12934. (function (module, exports$1) {
  12935. exports$1.__esModule = true;
  12936. exports$1["default"] = stripComments;
  12937. function stripComments(str) {
  12938. var s = "";
  12939. var commentStart = str.indexOf("/*");
  12940. var lastEnd = 0;
  12941. while (commentStart >= 0) {
  12942. s = s + str.slice(lastEnd, commentStart);
  12943. var commentEnd = str.indexOf("*/", commentStart + 2);
  12944. if (commentEnd < 0) {
  12945. return s;
  12946. }
  12947. lastEnd = commentEnd + 2;
  12948. commentStart = str.indexOf("/*", lastEnd);
  12949. }
  12950. s = s + str.slice(lastEnd);
  12951. return s;
  12952. }
  12953. module.exports = exports$1.default;
  12954. } (stripComments, stripComments.exports));
  12955. return stripComments.exports;
  12956. }
  12957. var hasRequiredUtil;
  12958. function requireUtil () {
  12959. if (hasRequiredUtil) return util;
  12960. hasRequiredUtil = 1;
  12961. util.__esModule = true;
  12962. util.unesc = util.stripComments = util.getProp = util.ensureObject = void 0;
  12963. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc());
  12964. util.unesc = _unesc["default"];
  12965. var _getProp = _interopRequireDefault(/*@__PURE__*/ requireGetProp());
  12966. util.getProp = _getProp["default"];
  12967. var _ensureObject = _interopRequireDefault(/*@__PURE__*/ requireEnsureObject());
  12968. util.ensureObject = _ensureObject["default"];
  12969. var _stripComments = _interopRequireDefault(/*@__PURE__*/ requireStripComments());
  12970. util.stripComments = _stripComments["default"];
  12971. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  12972. return util;
  12973. }
  12974. var hasRequiredNode;
  12975. function requireNode () {
  12976. if (hasRequiredNode) return node.exports;
  12977. hasRequiredNode = 1;
  12978. (function (module, exports$1) {
  12979. exports$1.__esModule = true;
  12980. exports$1["default"] = void 0;
  12981. var _util = /*@__PURE__*/ requireUtil();
  12982. 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); } }
  12983. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  12984. var cloneNode = function cloneNode(obj, parent) {
  12985. if (typeof obj !== 'object' || obj === null) {
  12986. return obj;
  12987. }
  12988. var cloned = new obj.constructor();
  12989. for (var i in obj) {
  12990. if (!obj.hasOwnProperty(i)) {
  12991. continue;
  12992. }
  12993. var value = obj[i];
  12994. var type = typeof value;
  12995. if (i === 'parent' && type === 'object') {
  12996. if (parent) {
  12997. cloned[i] = parent;
  12998. }
  12999. } else if (value instanceof Array) {
  13000. cloned[i] = value.map(function (j) {
  13001. return cloneNode(j, cloned);
  13002. });
  13003. } else {
  13004. cloned[i] = cloneNode(value, cloned);
  13005. }
  13006. }
  13007. return cloned;
  13008. };
  13009. var Node = /*#__PURE__*/function () {
  13010. function Node(opts) {
  13011. if (opts === void 0) {
  13012. opts = {};
  13013. }
  13014. Object.assign(this, opts);
  13015. this.spaces = this.spaces || {};
  13016. this.spaces.before = this.spaces.before || '';
  13017. this.spaces.after = this.spaces.after || '';
  13018. }
  13019. var _proto = Node.prototype;
  13020. _proto.remove = function remove() {
  13021. if (this.parent) {
  13022. this.parent.removeChild(this);
  13023. }
  13024. this.parent = undefined;
  13025. return this;
  13026. };
  13027. _proto.replaceWith = function replaceWith() {
  13028. if (this.parent) {
  13029. for (var index in arguments) {
  13030. this.parent.insertBefore(this, arguments[index]);
  13031. }
  13032. this.remove();
  13033. }
  13034. return this;
  13035. };
  13036. _proto.next = function next() {
  13037. return this.parent.at(this.parent.index(this) + 1);
  13038. };
  13039. _proto.prev = function prev() {
  13040. return this.parent.at(this.parent.index(this) - 1);
  13041. };
  13042. _proto.clone = function clone(overrides) {
  13043. if (overrides === void 0) {
  13044. overrides = {};
  13045. }
  13046. var cloned = cloneNode(this);
  13047. for (var name in overrides) {
  13048. cloned[name] = overrides[name];
  13049. }
  13050. return cloned;
  13051. }
  13052. /**
  13053. * Some non-standard syntax doesn't follow normal escaping rules for css.
  13054. * This allows non standard syntax to be appended to an existing property
  13055. * by specifying the escaped value. By specifying the escaped value,
  13056. * illegal characters are allowed to be directly inserted into css output.
  13057. * @param {string} name the property to set
  13058. * @param {any} value the unescaped value of the property
  13059. * @param {string} valueEscaped optional. the escaped value of the property.
  13060. */;
  13061. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  13062. if (!this.raws) {
  13063. this.raws = {};
  13064. }
  13065. var originalValue = this[name];
  13066. var originalEscaped = this.raws[name];
  13067. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  13068. if (originalEscaped || valueEscaped !== value) {
  13069. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  13070. } else {
  13071. delete this.raws[name]; // delete any escaped value that was created by the setter.
  13072. }
  13073. }
  13074. /**
  13075. * Some non-standard syntax doesn't follow normal escaping rules for css.
  13076. * This allows the escaped value to be specified directly, allowing illegal
  13077. * characters to be directly inserted into css output.
  13078. * @param {string} name the property to set
  13079. * @param {any} value the unescaped value of the property
  13080. * @param {string} valueEscaped the escaped value of the property.
  13081. */;
  13082. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  13083. if (!this.raws) {
  13084. this.raws = {};
  13085. }
  13086. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  13087. this.raws[name] = valueEscaped;
  13088. }
  13089. /**
  13090. * When you want a value to passed through to CSS directly. This method
  13091. * deletes the corresponding raw value causing the stringifier to fallback
  13092. * to the unescaped value.
  13093. * @param {string} name the property to set.
  13094. * @param {any} value The value that is both escaped and unescaped.
  13095. */;
  13096. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  13097. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  13098. if (this.raws) {
  13099. delete this.raws[name];
  13100. }
  13101. }
  13102. /**
  13103. *
  13104. * @param {number} line The number (starting with 1)
  13105. * @param {number} column The column number (starting with 1)
  13106. */;
  13107. _proto.isAtPosition = function isAtPosition(line, column) {
  13108. if (this.source && this.source.start && this.source.end) {
  13109. if (this.source.start.line > line) {
  13110. return false;
  13111. }
  13112. if (this.source.end.line < line) {
  13113. return false;
  13114. }
  13115. if (this.source.start.line === line && this.source.start.column > column) {
  13116. return false;
  13117. }
  13118. if (this.source.end.line === line && this.source.end.column < column) {
  13119. return false;
  13120. }
  13121. return true;
  13122. }
  13123. return undefined;
  13124. };
  13125. _proto.stringifyProperty = function stringifyProperty(name) {
  13126. return this.raws && this.raws[name] || this[name];
  13127. };
  13128. _proto.valueToString = function valueToString() {
  13129. return String(this.stringifyProperty("value"));
  13130. };
  13131. _proto.toString = function toString() {
  13132. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  13133. };
  13134. _createClass(Node, [{
  13135. key: "rawSpaceBefore",
  13136. get: function get() {
  13137. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  13138. if (rawSpace === undefined) {
  13139. rawSpace = this.spaces && this.spaces.before;
  13140. }
  13141. return rawSpace || "";
  13142. },
  13143. set: function set(raw) {
  13144. (0, _util.ensureObject)(this, "raws", "spaces");
  13145. this.raws.spaces.before = raw;
  13146. }
  13147. }, {
  13148. key: "rawSpaceAfter",
  13149. get: function get() {
  13150. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  13151. if (rawSpace === undefined) {
  13152. rawSpace = this.spaces.after;
  13153. }
  13154. return rawSpace || "";
  13155. },
  13156. set: function set(raw) {
  13157. (0, _util.ensureObject)(this, "raws", "spaces");
  13158. this.raws.spaces.after = raw;
  13159. }
  13160. }]);
  13161. return Node;
  13162. }();
  13163. exports$1["default"] = Node;
  13164. module.exports = exports$1.default;
  13165. } (node, node.exports));
  13166. return node.exports;
  13167. }
  13168. var types$1 = {};
  13169. var hasRequiredTypes;
  13170. function requireTypes () {
  13171. if (hasRequiredTypes) return types$1;
  13172. hasRequiredTypes = 1;
  13173. types$1.__esModule = true;
  13174. 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;
  13175. var TAG = 'tag';
  13176. types$1.TAG = TAG;
  13177. var STRING = 'string';
  13178. types$1.STRING = STRING;
  13179. var SELECTOR = 'selector';
  13180. types$1.SELECTOR = SELECTOR;
  13181. var ROOT = 'root';
  13182. types$1.ROOT = ROOT;
  13183. var PSEUDO = 'pseudo';
  13184. types$1.PSEUDO = PSEUDO;
  13185. var NESTING = 'nesting';
  13186. types$1.NESTING = NESTING;
  13187. var ID = 'id';
  13188. types$1.ID = ID;
  13189. var COMMENT = 'comment';
  13190. types$1.COMMENT = COMMENT;
  13191. var COMBINATOR = 'combinator';
  13192. types$1.COMBINATOR = COMBINATOR;
  13193. var CLASS = 'class';
  13194. types$1.CLASS = CLASS;
  13195. var ATTRIBUTE = 'attribute';
  13196. types$1.ATTRIBUTE = ATTRIBUTE;
  13197. var UNIVERSAL = 'universal';
  13198. types$1.UNIVERSAL = UNIVERSAL;
  13199. return types$1;
  13200. }
  13201. var hasRequiredContainer;
  13202. function requireContainer () {
  13203. if (hasRequiredContainer) return container.exports;
  13204. hasRequiredContainer = 1;
  13205. (function (module, exports$1) {
  13206. exports$1.__esModule = true;
  13207. exports$1["default"] = void 0;
  13208. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13209. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes());
  13210. 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); }
  13211. 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; }
  13212. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13213. 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."); }
  13214. 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); }
  13215. 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; }
  13216. 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); } }
  13217. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13218. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13219. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13220. var Container = /*#__PURE__*/function (_Node) {
  13221. _inheritsLoose(Container, _Node);
  13222. function Container(opts) {
  13223. var _this;
  13224. _this = _Node.call(this, opts) || this;
  13225. if (!_this.nodes) {
  13226. _this.nodes = [];
  13227. }
  13228. return _this;
  13229. }
  13230. var _proto = Container.prototype;
  13231. _proto.append = function append(selector) {
  13232. selector.parent = this;
  13233. this.nodes.push(selector);
  13234. return this;
  13235. };
  13236. _proto.prepend = function prepend(selector) {
  13237. selector.parent = this;
  13238. this.nodes.unshift(selector);
  13239. return this;
  13240. };
  13241. _proto.at = function at(index) {
  13242. return this.nodes[index];
  13243. };
  13244. _proto.index = function index(child) {
  13245. if (typeof child === 'number') {
  13246. return child;
  13247. }
  13248. return this.nodes.indexOf(child);
  13249. };
  13250. _proto.removeChild = function removeChild(child) {
  13251. child = this.index(child);
  13252. this.at(child).parent = undefined;
  13253. this.nodes.splice(child, 1);
  13254. var index;
  13255. for (var id in this.indexes) {
  13256. index = this.indexes[id];
  13257. if (index >= child) {
  13258. this.indexes[id] = index - 1;
  13259. }
  13260. }
  13261. return this;
  13262. };
  13263. _proto.removeAll = function removeAll() {
  13264. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  13265. var node = _step.value;
  13266. node.parent = undefined;
  13267. }
  13268. this.nodes = [];
  13269. return this;
  13270. };
  13271. _proto.empty = function empty() {
  13272. return this.removeAll();
  13273. };
  13274. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  13275. newNode.parent = this;
  13276. var oldIndex = this.index(oldNode);
  13277. this.nodes.splice(oldIndex + 1, 0, newNode);
  13278. newNode.parent = this;
  13279. var index;
  13280. for (var id in this.indexes) {
  13281. index = this.indexes[id];
  13282. if (oldIndex <= index) {
  13283. this.indexes[id] = index + 1;
  13284. }
  13285. }
  13286. return this;
  13287. };
  13288. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  13289. newNode.parent = this;
  13290. var oldIndex = this.index(oldNode);
  13291. this.nodes.splice(oldIndex, 0, newNode);
  13292. newNode.parent = this;
  13293. var index;
  13294. for (var id in this.indexes) {
  13295. index = this.indexes[id];
  13296. if (index <= oldIndex) {
  13297. this.indexes[id] = index + 1;
  13298. }
  13299. }
  13300. return this;
  13301. };
  13302. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  13303. var found = undefined;
  13304. this.each(function (node) {
  13305. if (node.atPosition) {
  13306. var foundChild = node.atPosition(line, col);
  13307. if (foundChild) {
  13308. found = foundChild;
  13309. return false;
  13310. }
  13311. } else if (node.isAtPosition(line, col)) {
  13312. found = node;
  13313. return false;
  13314. }
  13315. });
  13316. return found;
  13317. }
  13318. /**
  13319. * Return the most specific node at the line and column number given.
  13320. * The source location is based on the original parsed location, locations aren't
  13321. * updated as selector nodes are mutated.
  13322. *
  13323. * Note that this location is relative to the location of the first character
  13324. * of the selector, and not the location of the selector in the overall document
  13325. * when used in conjunction with postcss.
  13326. *
  13327. * If not found, returns undefined.
  13328. * @param {number} line The line number of the node to find. (1-based index)
  13329. * @param {number} col The column number of the node to find. (1-based index)
  13330. */;
  13331. _proto.atPosition = function atPosition(line, col) {
  13332. if (this.isAtPosition(line, col)) {
  13333. return this._findChildAtPosition(line, col) || this;
  13334. } else {
  13335. return undefined;
  13336. }
  13337. };
  13338. _proto._inferEndPosition = function _inferEndPosition() {
  13339. if (this.last && this.last.source && this.last.source.end) {
  13340. this.source = this.source || {};
  13341. this.source.end = this.source.end || {};
  13342. Object.assign(this.source.end, this.last.source.end);
  13343. }
  13344. };
  13345. _proto.each = function each(callback) {
  13346. if (!this.lastEach) {
  13347. this.lastEach = 0;
  13348. }
  13349. if (!this.indexes) {
  13350. this.indexes = {};
  13351. }
  13352. this.lastEach++;
  13353. var id = this.lastEach;
  13354. this.indexes[id] = 0;
  13355. if (!this.length) {
  13356. return undefined;
  13357. }
  13358. var index, result;
  13359. while (this.indexes[id] < this.length) {
  13360. index = this.indexes[id];
  13361. result = callback(this.at(index), index);
  13362. if (result === false) {
  13363. break;
  13364. }
  13365. this.indexes[id] += 1;
  13366. }
  13367. delete this.indexes[id];
  13368. if (result === false) {
  13369. return false;
  13370. }
  13371. };
  13372. _proto.walk = function walk(callback) {
  13373. return this.each(function (node, i) {
  13374. var result = callback(node, i);
  13375. if (result !== false && node.length) {
  13376. result = node.walk(callback);
  13377. }
  13378. if (result === false) {
  13379. return false;
  13380. }
  13381. });
  13382. };
  13383. _proto.walkAttributes = function walkAttributes(callback) {
  13384. var _this2 = this;
  13385. return this.walk(function (selector) {
  13386. if (selector.type === types.ATTRIBUTE) {
  13387. return callback.call(_this2, selector);
  13388. }
  13389. });
  13390. };
  13391. _proto.walkClasses = function walkClasses(callback) {
  13392. var _this3 = this;
  13393. return this.walk(function (selector) {
  13394. if (selector.type === types.CLASS) {
  13395. return callback.call(_this3, selector);
  13396. }
  13397. });
  13398. };
  13399. _proto.walkCombinators = function walkCombinators(callback) {
  13400. var _this4 = this;
  13401. return this.walk(function (selector) {
  13402. if (selector.type === types.COMBINATOR) {
  13403. return callback.call(_this4, selector);
  13404. }
  13405. });
  13406. };
  13407. _proto.walkComments = function walkComments(callback) {
  13408. var _this5 = this;
  13409. return this.walk(function (selector) {
  13410. if (selector.type === types.COMMENT) {
  13411. return callback.call(_this5, selector);
  13412. }
  13413. });
  13414. };
  13415. _proto.walkIds = function walkIds(callback) {
  13416. var _this6 = this;
  13417. return this.walk(function (selector) {
  13418. if (selector.type === types.ID) {
  13419. return callback.call(_this6, selector);
  13420. }
  13421. });
  13422. };
  13423. _proto.walkNesting = function walkNesting(callback) {
  13424. var _this7 = this;
  13425. return this.walk(function (selector) {
  13426. if (selector.type === types.NESTING) {
  13427. return callback.call(_this7, selector);
  13428. }
  13429. });
  13430. };
  13431. _proto.walkPseudos = function walkPseudos(callback) {
  13432. var _this8 = this;
  13433. return this.walk(function (selector) {
  13434. if (selector.type === types.PSEUDO) {
  13435. return callback.call(_this8, selector);
  13436. }
  13437. });
  13438. };
  13439. _proto.walkTags = function walkTags(callback) {
  13440. var _this9 = this;
  13441. return this.walk(function (selector) {
  13442. if (selector.type === types.TAG) {
  13443. return callback.call(_this9, selector);
  13444. }
  13445. });
  13446. };
  13447. _proto.walkUniversals = function walkUniversals(callback) {
  13448. var _this10 = this;
  13449. return this.walk(function (selector) {
  13450. if (selector.type === types.UNIVERSAL) {
  13451. return callback.call(_this10, selector);
  13452. }
  13453. });
  13454. };
  13455. _proto.split = function split(callback) {
  13456. var _this11 = this;
  13457. var current = [];
  13458. return this.reduce(function (memo, node, index) {
  13459. var split = callback.call(_this11, node);
  13460. current.push(node);
  13461. if (split) {
  13462. memo.push(current);
  13463. current = [];
  13464. } else if (index === _this11.length - 1) {
  13465. memo.push(current);
  13466. }
  13467. return memo;
  13468. }, []);
  13469. };
  13470. _proto.map = function map(callback) {
  13471. return this.nodes.map(callback);
  13472. };
  13473. _proto.reduce = function reduce(callback, memo) {
  13474. return this.nodes.reduce(callback, memo);
  13475. };
  13476. _proto.every = function every(callback) {
  13477. return this.nodes.every(callback);
  13478. };
  13479. _proto.some = function some(callback) {
  13480. return this.nodes.some(callback);
  13481. };
  13482. _proto.filter = function filter(callback) {
  13483. return this.nodes.filter(callback);
  13484. };
  13485. _proto.sort = function sort(callback) {
  13486. return this.nodes.sort(callback);
  13487. };
  13488. _proto.toString = function toString() {
  13489. return this.map(String).join('');
  13490. };
  13491. _createClass(Container, [{
  13492. key: "first",
  13493. get: function get() {
  13494. return this.at(0);
  13495. }
  13496. }, {
  13497. key: "last",
  13498. get: function get() {
  13499. return this.at(this.length - 1);
  13500. }
  13501. }, {
  13502. key: "length",
  13503. get: function get() {
  13504. return this.nodes.length;
  13505. }
  13506. }]);
  13507. return Container;
  13508. }(_node["default"]);
  13509. exports$1["default"] = Container;
  13510. module.exports = exports$1.default;
  13511. } (container, container.exports));
  13512. return container.exports;
  13513. }
  13514. var hasRequiredRoot;
  13515. function requireRoot () {
  13516. if (hasRequiredRoot) return root.exports;
  13517. hasRequiredRoot = 1;
  13518. (function (module, exports$1) {
  13519. exports$1.__esModule = true;
  13520. exports$1["default"] = void 0;
  13521. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13522. var _types = /*@__PURE__*/ requireTypes();
  13523. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13524. 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); } }
  13525. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13526. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13527. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13528. var Root = /*#__PURE__*/function (_Container) {
  13529. _inheritsLoose(Root, _Container);
  13530. function Root(opts) {
  13531. var _this;
  13532. _this = _Container.call(this, opts) || this;
  13533. _this.type = _types.ROOT;
  13534. return _this;
  13535. }
  13536. var _proto = Root.prototype;
  13537. _proto.toString = function toString() {
  13538. var str = this.reduce(function (memo, selector) {
  13539. memo.push(String(selector));
  13540. return memo;
  13541. }, []).join(',');
  13542. return this.trailingComma ? str + ',' : str;
  13543. };
  13544. _proto.error = function error(message, options) {
  13545. if (this._error) {
  13546. return this._error(message, options);
  13547. } else {
  13548. return new Error(message);
  13549. }
  13550. };
  13551. _createClass(Root, [{
  13552. key: "errorGenerator",
  13553. set: function set(handler) {
  13554. this._error = handler;
  13555. }
  13556. }]);
  13557. return Root;
  13558. }(_container["default"]);
  13559. exports$1["default"] = Root;
  13560. module.exports = exports$1.default;
  13561. } (root, root.exports));
  13562. return root.exports;
  13563. }
  13564. var selector = {exports: {}};
  13565. var hasRequiredSelector;
  13566. function requireSelector () {
  13567. if (hasRequiredSelector) return selector.exports;
  13568. hasRequiredSelector = 1;
  13569. (function (module, exports$1) {
  13570. exports$1.__esModule = true;
  13571. exports$1["default"] = void 0;
  13572. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13573. var _types = /*@__PURE__*/ requireTypes();
  13574. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13575. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13576. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13577. var Selector = /*#__PURE__*/function (_Container) {
  13578. _inheritsLoose(Selector, _Container);
  13579. function Selector(opts) {
  13580. var _this;
  13581. _this = _Container.call(this, opts) || this;
  13582. _this.type = _types.SELECTOR;
  13583. return _this;
  13584. }
  13585. return Selector;
  13586. }(_container["default"]);
  13587. exports$1["default"] = Selector;
  13588. module.exports = exports$1.default;
  13589. } (selector, selector.exports));
  13590. return selector.exports;
  13591. }
  13592. var className = {exports: {}};
  13593. var hasRequiredClassName;
  13594. function requireClassName () {
  13595. if (hasRequiredClassName) return className.exports;
  13596. hasRequiredClassName = 1;
  13597. (function (module, exports$1) {
  13598. exports$1.__esModule = true;
  13599. exports$1["default"] = void 0;
  13600. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13601. var _util = /*@__PURE__*/ requireUtil();
  13602. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13603. var _types = /*@__PURE__*/ requireTypes();
  13604. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13605. 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); } }
  13606. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13607. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13608. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13609. var ClassName = /*#__PURE__*/function (_Node) {
  13610. _inheritsLoose(ClassName, _Node);
  13611. function ClassName(opts) {
  13612. var _this;
  13613. _this = _Node.call(this, opts) || this;
  13614. _this.type = _types.CLASS;
  13615. _this._constructed = true;
  13616. return _this;
  13617. }
  13618. var _proto = ClassName.prototype;
  13619. _proto.valueToString = function valueToString() {
  13620. return '.' + _Node.prototype.valueToString.call(this);
  13621. };
  13622. _createClass(ClassName, [{
  13623. key: "value",
  13624. get: function get() {
  13625. return this._value;
  13626. },
  13627. set: function set(v) {
  13628. if (this._constructed) {
  13629. var escaped = (0, _cssesc["default"])(v, {
  13630. isIdentifier: true
  13631. });
  13632. if (escaped !== v) {
  13633. (0, _util.ensureObject)(this, "raws");
  13634. this.raws.value = escaped;
  13635. } else if (this.raws) {
  13636. delete this.raws.value;
  13637. }
  13638. }
  13639. this._value = v;
  13640. }
  13641. }]);
  13642. return ClassName;
  13643. }(_node["default"]);
  13644. exports$1["default"] = ClassName;
  13645. module.exports = exports$1.default;
  13646. } (className, className.exports));
  13647. return className.exports;
  13648. }
  13649. var comment = {exports: {}};
  13650. var hasRequiredComment;
  13651. function requireComment () {
  13652. if (hasRequiredComment) return comment.exports;
  13653. hasRequiredComment = 1;
  13654. (function (module, exports$1) {
  13655. exports$1.__esModule = true;
  13656. exports$1["default"] = void 0;
  13657. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13658. var _types = /*@__PURE__*/ requireTypes();
  13659. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13660. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13661. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13662. var Comment = /*#__PURE__*/function (_Node) {
  13663. _inheritsLoose(Comment, _Node);
  13664. function Comment(opts) {
  13665. var _this;
  13666. _this = _Node.call(this, opts) || this;
  13667. _this.type = _types.COMMENT;
  13668. return _this;
  13669. }
  13670. return Comment;
  13671. }(_node["default"]);
  13672. exports$1["default"] = Comment;
  13673. module.exports = exports$1.default;
  13674. } (comment, comment.exports));
  13675. return comment.exports;
  13676. }
  13677. var id = {exports: {}};
  13678. var hasRequiredId;
  13679. function requireId () {
  13680. if (hasRequiredId) return id.exports;
  13681. hasRequiredId = 1;
  13682. (function (module, exports$1) {
  13683. exports$1.__esModule = true;
  13684. exports$1["default"] = void 0;
  13685. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13686. var _types = /*@__PURE__*/ requireTypes();
  13687. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13688. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13689. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13690. var ID = /*#__PURE__*/function (_Node) {
  13691. _inheritsLoose(ID, _Node);
  13692. function ID(opts) {
  13693. var _this;
  13694. _this = _Node.call(this, opts) || this;
  13695. _this.type = _types.ID;
  13696. return _this;
  13697. }
  13698. var _proto = ID.prototype;
  13699. _proto.valueToString = function valueToString() {
  13700. return '#' + _Node.prototype.valueToString.call(this);
  13701. };
  13702. return ID;
  13703. }(_node["default"]);
  13704. exports$1["default"] = ID;
  13705. module.exports = exports$1.default;
  13706. } (id, id.exports));
  13707. return id.exports;
  13708. }
  13709. var tag = {exports: {}};
  13710. var namespace = {exports: {}};
  13711. var hasRequiredNamespace;
  13712. function requireNamespace () {
  13713. if (hasRequiredNamespace) return namespace.exports;
  13714. hasRequiredNamespace = 1;
  13715. (function (module, exports$1) {
  13716. exports$1.__esModule = true;
  13717. exports$1["default"] = void 0;
  13718. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13719. var _util = /*@__PURE__*/ requireUtil();
  13720. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13721. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13722. 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); } }
  13723. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13724. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13725. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13726. var Namespace = /*#__PURE__*/function (_Node) {
  13727. _inheritsLoose(Namespace, _Node);
  13728. function Namespace() {
  13729. return _Node.apply(this, arguments) || this;
  13730. }
  13731. var _proto = Namespace.prototype;
  13732. _proto.qualifiedName = function qualifiedName(value) {
  13733. if (this.namespace) {
  13734. return this.namespaceString + "|" + value;
  13735. } else {
  13736. return value;
  13737. }
  13738. };
  13739. _proto.valueToString = function valueToString() {
  13740. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  13741. };
  13742. _createClass(Namespace, [{
  13743. key: "namespace",
  13744. get: function get() {
  13745. return this._namespace;
  13746. },
  13747. set: function set(namespace) {
  13748. if (namespace === true || namespace === "*" || namespace === "&") {
  13749. this._namespace = namespace;
  13750. if (this.raws) {
  13751. delete this.raws.namespace;
  13752. }
  13753. return;
  13754. }
  13755. var escaped = (0, _cssesc["default"])(namespace, {
  13756. isIdentifier: true
  13757. });
  13758. this._namespace = namespace;
  13759. if (escaped !== namespace) {
  13760. (0, _util.ensureObject)(this, "raws");
  13761. this.raws.namespace = escaped;
  13762. } else if (this.raws) {
  13763. delete this.raws.namespace;
  13764. }
  13765. }
  13766. }, {
  13767. key: "ns",
  13768. get: function get() {
  13769. return this._namespace;
  13770. },
  13771. set: function set(namespace) {
  13772. this.namespace = namespace;
  13773. }
  13774. }, {
  13775. key: "namespaceString",
  13776. get: function get() {
  13777. if (this.namespace) {
  13778. var ns = this.stringifyProperty("namespace");
  13779. if (ns === true) {
  13780. return '';
  13781. } else {
  13782. return ns;
  13783. }
  13784. } else {
  13785. return '';
  13786. }
  13787. }
  13788. }]);
  13789. return Namespace;
  13790. }(_node["default"]);
  13791. exports$1["default"] = Namespace;
  13792. module.exports = exports$1.default;
  13793. } (namespace, namespace.exports));
  13794. return namespace.exports;
  13795. }
  13796. var hasRequiredTag;
  13797. function requireTag () {
  13798. if (hasRequiredTag) return tag.exports;
  13799. hasRequiredTag = 1;
  13800. (function (module, exports$1) {
  13801. exports$1.__esModule = true;
  13802. exports$1["default"] = void 0;
  13803. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  13804. var _types = /*@__PURE__*/ requireTypes();
  13805. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13806. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13807. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13808. var Tag = /*#__PURE__*/function (_Namespace) {
  13809. _inheritsLoose(Tag, _Namespace);
  13810. function Tag(opts) {
  13811. var _this;
  13812. _this = _Namespace.call(this, opts) || this;
  13813. _this.type = _types.TAG;
  13814. return _this;
  13815. }
  13816. return Tag;
  13817. }(_namespace["default"]);
  13818. exports$1["default"] = Tag;
  13819. module.exports = exports$1.default;
  13820. } (tag, tag.exports));
  13821. return tag.exports;
  13822. }
  13823. var string = {exports: {}};
  13824. var hasRequiredString;
  13825. function requireString () {
  13826. if (hasRequiredString) return string.exports;
  13827. hasRequiredString = 1;
  13828. (function (module, exports$1) {
  13829. exports$1.__esModule = true;
  13830. exports$1["default"] = void 0;
  13831. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13832. var _types = /*@__PURE__*/ requireTypes();
  13833. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13834. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13835. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13836. var String = /*#__PURE__*/function (_Node) {
  13837. _inheritsLoose(String, _Node);
  13838. function String(opts) {
  13839. var _this;
  13840. _this = _Node.call(this, opts) || this;
  13841. _this.type = _types.STRING;
  13842. return _this;
  13843. }
  13844. return String;
  13845. }(_node["default"]);
  13846. exports$1["default"] = String;
  13847. module.exports = exports$1.default;
  13848. } (string, string.exports));
  13849. return string.exports;
  13850. }
  13851. var pseudo = {exports: {}};
  13852. var hasRequiredPseudo;
  13853. function requirePseudo () {
  13854. if (hasRequiredPseudo) return pseudo.exports;
  13855. hasRequiredPseudo = 1;
  13856. (function (module, exports$1) {
  13857. exports$1.__esModule = true;
  13858. exports$1["default"] = void 0;
  13859. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13860. var _types = /*@__PURE__*/ requireTypes();
  13861. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13862. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13863. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13864. var Pseudo = /*#__PURE__*/function (_Container) {
  13865. _inheritsLoose(Pseudo, _Container);
  13866. function Pseudo(opts) {
  13867. var _this;
  13868. _this = _Container.call(this, opts) || this;
  13869. _this.type = _types.PSEUDO;
  13870. return _this;
  13871. }
  13872. var _proto = Pseudo.prototype;
  13873. _proto.toString = function toString() {
  13874. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  13875. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  13876. };
  13877. return Pseudo;
  13878. }(_container["default"]);
  13879. exports$1["default"] = Pseudo;
  13880. module.exports = exports$1.default;
  13881. } (pseudo, pseudo.exports));
  13882. return pseudo.exports;
  13883. }
  13884. var attribute = {};
  13885. var hasRequiredAttribute;
  13886. function requireAttribute () {
  13887. if (hasRequiredAttribute) return attribute;
  13888. hasRequiredAttribute = 1;
  13889. (function (exports$1) {
  13890. exports$1.__esModule = true;
  13891. exports$1["default"] = void 0;
  13892. exports$1.unescapeValue = unescapeValue;
  13893. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13894. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc());
  13895. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  13896. var _types = /*@__PURE__*/ requireTypes();
  13897. var _CSSESC_QUOTE_OPTIONS;
  13898. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13899. 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); } }
  13900. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13901. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13902. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13903. var deprecate = /*@__PURE__*/ requireNode$1();
  13904. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  13905. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  13906. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  13907. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  13908. function unescapeValue(value) {
  13909. var deprecatedUsage = false;
  13910. var quoteMark = null;
  13911. var unescaped = value;
  13912. var m = unescaped.match(WRAPPED_IN_QUOTES);
  13913. if (m) {
  13914. quoteMark = m[1];
  13915. unescaped = m[2];
  13916. }
  13917. unescaped = (0, _unesc["default"])(unescaped);
  13918. if (unescaped !== value) {
  13919. deprecatedUsage = true;
  13920. }
  13921. return {
  13922. deprecatedUsage: deprecatedUsage,
  13923. unescaped: unescaped,
  13924. quoteMark: quoteMark
  13925. };
  13926. }
  13927. function handleDeprecatedContructorOpts(opts) {
  13928. if (opts.quoteMark !== undefined) {
  13929. return opts;
  13930. }
  13931. if (opts.value === undefined) {
  13932. return opts;
  13933. }
  13934. warnOfDeprecatedConstructor();
  13935. var _unescapeValue = unescapeValue(opts.value),
  13936. quoteMark = _unescapeValue.quoteMark,
  13937. unescaped = _unescapeValue.unescaped;
  13938. if (!opts.raws) {
  13939. opts.raws = {};
  13940. }
  13941. if (opts.raws.value === undefined) {
  13942. opts.raws.value = opts.value;
  13943. }
  13944. opts.value = unescaped;
  13945. opts.quoteMark = quoteMark;
  13946. return opts;
  13947. }
  13948. var Attribute = /*#__PURE__*/function (_Namespace) {
  13949. _inheritsLoose(Attribute, _Namespace);
  13950. function Attribute(opts) {
  13951. var _this;
  13952. if (opts === void 0) {
  13953. opts = {};
  13954. }
  13955. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  13956. _this.type = _types.ATTRIBUTE;
  13957. _this.raws = _this.raws || {};
  13958. Object.defineProperty(_this.raws, 'unquoted', {
  13959. get: deprecate(function () {
  13960. return _this.value;
  13961. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  13962. set: deprecate(function () {
  13963. return _this.value;
  13964. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  13965. });
  13966. _this._constructed = true;
  13967. return _this;
  13968. }
  13969. /**
  13970. * Returns the Attribute's value quoted such that it would be legal to use
  13971. * in the value of a css file. The original value's quotation setting
  13972. * used for stringification is left unchanged. See `setValue(value, options)`
  13973. * if you want to control the quote settings of a new value for the attribute.
  13974. *
  13975. * You can also change the quotation used for the current value by setting quoteMark.
  13976. *
  13977. * Options:
  13978. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  13979. * option is not set, the original value for quoteMark will be used. If
  13980. * indeterminate, a double quote is used. The legal values are:
  13981. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  13982. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  13983. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  13984. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  13985. * over the quoteMark option value.
  13986. * * smart {boolean} - if true, will select a quote mark based on the value
  13987. * and the other options specified here. See the `smartQuoteMark()`
  13988. * method.
  13989. **/
  13990. var _proto = Attribute.prototype;
  13991. _proto.getQuotedValue = function getQuotedValue(options) {
  13992. if (options === void 0) {
  13993. options = {};
  13994. }
  13995. var quoteMark = this._determineQuoteMark(options);
  13996. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  13997. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  13998. return escaped;
  13999. };
  14000. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  14001. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  14002. }
  14003. /**
  14004. * Set the unescaped value with the specified quotation options. The value
  14005. * provided must not include any wrapping quote marks -- those quotes will
  14006. * be interpreted as part of the value and escaped accordingly.
  14007. */;
  14008. _proto.setValue = function setValue(value, options) {
  14009. if (options === void 0) {
  14010. options = {};
  14011. }
  14012. this._value = value;
  14013. this._quoteMark = this._determineQuoteMark(options);
  14014. this._syncRawValue();
  14015. }
  14016. /**
  14017. * Intelligently select a quoteMark value based on the value's contents. If
  14018. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  14019. * mark will be picked that minimizes the number of escapes.
  14020. *
  14021. * If there's no clear winner, the quote mark from these options is used,
  14022. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  14023. * true). If the quoteMark is unspecified, a double quote is used.
  14024. *
  14025. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  14026. * from the quoteValue method.
  14027. */;
  14028. _proto.smartQuoteMark = function smartQuoteMark(options) {
  14029. var v = this.value;
  14030. var numSingleQuotes = v.replace(/[^']/g, '').length;
  14031. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  14032. if (numSingleQuotes + numDoubleQuotes === 0) {
  14033. var escaped = (0, _cssesc["default"])(v, {
  14034. isIdentifier: true
  14035. });
  14036. if (escaped === v) {
  14037. return Attribute.NO_QUOTE;
  14038. } else {
  14039. var pref = this.preferredQuoteMark(options);
  14040. if (pref === Attribute.NO_QUOTE) {
  14041. // pick a quote mark that isn't none and see if it's smaller
  14042. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  14043. var opts = CSSESC_QUOTE_OPTIONS[quote];
  14044. var quoteValue = (0, _cssesc["default"])(v, opts);
  14045. if (quoteValue.length < escaped.length) {
  14046. return quote;
  14047. }
  14048. }
  14049. return pref;
  14050. }
  14051. } else if (numDoubleQuotes === numSingleQuotes) {
  14052. return this.preferredQuoteMark(options);
  14053. } else if (numDoubleQuotes < numSingleQuotes) {
  14054. return Attribute.DOUBLE_QUOTE;
  14055. } else {
  14056. return Attribute.SINGLE_QUOTE;
  14057. }
  14058. }
  14059. /**
  14060. * Selects the preferred quote mark based on the options and the current quote mark value.
  14061. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  14062. * instead.
  14063. */;
  14064. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  14065. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  14066. if (quoteMark === undefined) {
  14067. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  14068. }
  14069. if (quoteMark === undefined) {
  14070. quoteMark = Attribute.DOUBLE_QUOTE;
  14071. }
  14072. return quoteMark;
  14073. };
  14074. _proto._syncRawValue = function _syncRawValue() {
  14075. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  14076. if (rawValue === this._value) {
  14077. if (this.raws) {
  14078. delete this.raws.value;
  14079. }
  14080. } else {
  14081. this.raws.value = rawValue;
  14082. }
  14083. };
  14084. _proto._handleEscapes = function _handleEscapes(prop, value) {
  14085. if (this._constructed) {
  14086. var escaped = (0, _cssesc["default"])(value, {
  14087. isIdentifier: true
  14088. });
  14089. if (escaped !== value) {
  14090. this.raws[prop] = escaped;
  14091. } else {
  14092. delete this.raws[prop];
  14093. }
  14094. }
  14095. };
  14096. _proto._spacesFor = function _spacesFor(name) {
  14097. var attrSpaces = {
  14098. before: '',
  14099. after: ''
  14100. };
  14101. var spaces = this.spaces[name] || {};
  14102. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  14103. return Object.assign(attrSpaces, spaces, rawSpaces);
  14104. };
  14105. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  14106. if (spaceName === void 0) {
  14107. spaceName = name;
  14108. }
  14109. if (concat === void 0) {
  14110. concat = defaultAttrConcat;
  14111. }
  14112. var attrSpaces = this._spacesFor(spaceName);
  14113. return concat(this.stringifyProperty(name), attrSpaces);
  14114. }
  14115. /**
  14116. * returns the offset of the attribute part specified relative to the
  14117. * start of the node of the output string.
  14118. *
  14119. * * "ns" - alias for "namespace"
  14120. * * "namespace" - the namespace if it exists.
  14121. * * "attribute" - the attribute name
  14122. * * "attributeNS" - the start of the attribute or its namespace
  14123. * * "operator" - the match operator of the attribute
  14124. * * "value" - The value (string or identifier)
  14125. * * "insensitive" - the case insensitivity flag;
  14126. * @param part One of the possible values inside an attribute.
  14127. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  14128. */;
  14129. _proto.offsetOf = function offsetOf(name) {
  14130. var count = 1;
  14131. var attributeSpaces = this._spacesFor("attribute");
  14132. count += attributeSpaces.before.length;
  14133. if (name === "namespace" || name === "ns") {
  14134. return this.namespace ? count : -1;
  14135. }
  14136. if (name === "attributeNS") {
  14137. return count;
  14138. }
  14139. count += this.namespaceString.length;
  14140. if (this.namespace) {
  14141. count += 1;
  14142. }
  14143. if (name === "attribute") {
  14144. return count;
  14145. }
  14146. count += this.stringifyProperty("attribute").length;
  14147. count += attributeSpaces.after.length;
  14148. var operatorSpaces = this._spacesFor("operator");
  14149. count += operatorSpaces.before.length;
  14150. var operator = this.stringifyProperty("operator");
  14151. if (name === "operator") {
  14152. return operator ? count : -1;
  14153. }
  14154. count += operator.length;
  14155. count += operatorSpaces.after.length;
  14156. var valueSpaces = this._spacesFor("value");
  14157. count += valueSpaces.before.length;
  14158. var value = this.stringifyProperty("value");
  14159. if (name === "value") {
  14160. return value ? count : -1;
  14161. }
  14162. count += value.length;
  14163. count += valueSpaces.after.length;
  14164. var insensitiveSpaces = this._spacesFor("insensitive");
  14165. count += insensitiveSpaces.before.length;
  14166. if (name === "insensitive") {
  14167. return this.insensitive ? count : -1;
  14168. }
  14169. return -1;
  14170. };
  14171. _proto.toString = function toString() {
  14172. var _this2 = this;
  14173. var selector = [this.rawSpaceBefore, '['];
  14174. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  14175. if (this.operator && (this.value || this.value === '')) {
  14176. selector.push(this._stringFor('operator'));
  14177. selector.push(this._stringFor('value'));
  14178. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  14179. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  14180. attrSpaces.before = " ";
  14181. }
  14182. return defaultAttrConcat(attrValue, attrSpaces);
  14183. }));
  14184. }
  14185. selector.push(']');
  14186. selector.push(this.rawSpaceAfter);
  14187. return selector.join('');
  14188. };
  14189. _createClass(Attribute, [{
  14190. key: "quoted",
  14191. get: function get() {
  14192. var qm = this.quoteMark;
  14193. return qm === "'" || qm === '"';
  14194. },
  14195. set: function set(value) {
  14196. warnOfDeprecatedQuotedAssignment();
  14197. }
  14198. /**
  14199. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  14200. * returns `null` if the value is not quoted.
  14201. * returns `undefined` if the quotation state is unknown (this can happen when
  14202. * the attribute is constructed without specifying a quote mark.)
  14203. */
  14204. }, {
  14205. key: "quoteMark",
  14206. get: function get() {
  14207. return this._quoteMark;
  14208. }
  14209. /**
  14210. * Set the quote mark to be used by this attribute's value.
  14211. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  14212. * value is updated accordingly.
  14213. *
  14214. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  14215. */,
  14216. set: function set(quoteMark) {
  14217. if (!this._constructed) {
  14218. this._quoteMark = quoteMark;
  14219. return;
  14220. }
  14221. if (this._quoteMark !== quoteMark) {
  14222. this._quoteMark = quoteMark;
  14223. this._syncRawValue();
  14224. }
  14225. }
  14226. }, {
  14227. key: "qualifiedAttribute",
  14228. get: function get() {
  14229. return this.qualifiedName(this.raws.attribute || this.attribute);
  14230. }
  14231. }, {
  14232. key: "insensitiveFlag",
  14233. get: function get() {
  14234. return this.insensitive ? 'i' : '';
  14235. }
  14236. }, {
  14237. key: "value",
  14238. get: function get() {
  14239. return this._value;
  14240. },
  14241. set:
  14242. /**
  14243. * Before 3.0, the value had to be set to an escaped value including any wrapped
  14244. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  14245. * is unescaped during parsing and any quote marks are removed.
  14246. *
  14247. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  14248. * a deprecation warning is raised when the new value contains any characters that would
  14249. * require escaping (including if it contains wrapped quotes).
  14250. *
  14251. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  14252. * how the new value is quoted.
  14253. */
  14254. function set(v) {
  14255. if (this._constructed) {
  14256. var _unescapeValue2 = unescapeValue(v),
  14257. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  14258. unescaped = _unescapeValue2.unescaped,
  14259. quoteMark = _unescapeValue2.quoteMark;
  14260. if (deprecatedUsage) {
  14261. warnOfDeprecatedValueAssignment();
  14262. }
  14263. if (unescaped === this._value && quoteMark === this._quoteMark) {
  14264. return;
  14265. }
  14266. this._value = unescaped;
  14267. this._quoteMark = quoteMark;
  14268. this._syncRawValue();
  14269. } else {
  14270. this._value = v;
  14271. }
  14272. }
  14273. }, {
  14274. key: "insensitive",
  14275. get: function get() {
  14276. return this._insensitive;
  14277. }
  14278. /**
  14279. * Set the case insensitive flag.
  14280. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  14281. * of the attribute is updated accordingly.
  14282. *
  14283. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  14284. */,
  14285. set: function set(insensitive) {
  14286. if (!insensitive) {
  14287. this._insensitive = false;
  14288. // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  14289. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  14290. if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
  14291. this.raws.insensitiveFlag = undefined;
  14292. }
  14293. }
  14294. this._insensitive = insensitive;
  14295. }
  14296. }, {
  14297. key: "attribute",
  14298. get: function get() {
  14299. return this._attribute;
  14300. },
  14301. set: function set(name) {
  14302. this._handleEscapes("attribute", name);
  14303. this._attribute = name;
  14304. }
  14305. }]);
  14306. return Attribute;
  14307. }(_namespace["default"]);
  14308. exports$1["default"] = Attribute;
  14309. Attribute.NO_QUOTE = null;
  14310. Attribute.SINGLE_QUOTE = "'";
  14311. Attribute.DOUBLE_QUOTE = '"';
  14312. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  14313. "'": {
  14314. quotes: 'single',
  14315. wrap: true
  14316. },
  14317. '"': {
  14318. quotes: 'double',
  14319. wrap: true
  14320. }
  14321. }, _CSSESC_QUOTE_OPTIONS[null] = {
  14322. isIdentifier: true
  14323. }, _CSSESC_QUOTE_OPTIONS);
  14324. function defaultAttrConcat(attrValue, attrSpaces) {
  14325. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  14326. }
  14327. } (attribute));
  14328. return attribute;
  14329. }
  14330. var universal = {exports: {}};
  14331. var hasRequiredUniversal;
  14332. function requireUniversal () {
  14333. if (hasRequiredUniversal) return universal.exports;
  14334. hasRequiredUniversal = 1;
  14335. (function (module, exports$1) {
  14336. exports$1.__esModule = true;
  14337. exports$1["default"] = void 0;
  14338. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  14339. var _types = /*@__PURE__*/ requireTypes();
  14340. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14341. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14342. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14343. var Universal = /*#__PURE__*/function (_Namespace) {
  14344. _inheritsLoose(Universal, _Namespace);
  14345. function Universal(opts) {
  14346. var _this;
  14347. _this = _Namespace.call(this, opts) || this;
  14348. _this.type = _types.UNIVERSAL;
  14349. _this.value = '*';
  14350. return _this;
  14351. }
  14352. return Universal;
  14353. }(_namespace["default"]);
  14354. exports$1["default"] = Universal;
  14355. module.exports = exports$1.default;
  14356. } (universal, universal.exports));
  14357. return universal.exports;
  14358. }
  14359. var combinator = {exports: {}};
  14360. var hasRequiredCombinator;
  14361. function requireCombinator () {
  14362. if (hasRequiredCombinator) return combinator.exports;
  14363. hasRequiredCombinator = 1;
  14364. (function (module, exports$1) {
  14365. exports$1.__esModule = true;
  14366. exports$1["default"] = void 0;
  14367. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  14368. var _types = /*@__PURE__*/ requireTypes();
  14369. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14370. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14371. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14372. var Combinator = /*#__PURE__*/function (_Node) {
  14373. _inheritsLoose(Combinator, _Node);
  14374. function Combinator(opts) {
  14375. var _this;
  14376. _this = _Node.call(this, opts) || this;
  14377. _this.type = _types.COMBINATOR;
  14378. return _this;
  14379. }
  14380. return Combinator;
  14381. }(_node["default"]);
  14382. exports$1["default"] = Combinator;
  14383. module.exports = exports$1.default;
  14384. } (combinator, combinator.exports));
  14385. return combinator.exports;
  14386. }
  14387. var nesting = {exports: {}};
  14388. var hasRequiredNesting;
  14389. function requireNesting () {
  14390. if (hasRequiredNesting) return nesting.exports;
  14391. hasRequiredNesting = 1;
  14392. (function (module, exports$1) {
  14393. exports$1.__esModule = true;
  14394. exports$1["default"] = void 0;
  14395. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  14396. var _types = /*@__PURE__*/ requireTypes();
  14397. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14398. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14399. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14400. var Nesting = /*#__PURE__*/function (_Node) {
  14401. _inheritsLoose(Nesting, _Node);
  14402. function Nesting(opts) {
  14403. var _this;
  14404. _this = _Node.call(this, opts) || this;
  14405. _this.type = _types.NESTING;
  14406. _this.value = '&';
  14407. return _this;
  14408. }
  14409. return Nesting;
  14410. }(_node["default"]);
  14411. exports$1["default"] = Nesting;
  14412. module.exports = exports$1.default;
  14413. } (nesting, nesting.exports));
  14414. return nesting.exports;
  14415. }
  14416. var sortAscending = {exports: {}};
  14417. var hasRequiredSortAscending;
  14418. function requireSortAscending () {
  14419. if (hasRequiredSortAscending) return sortAscending.exports;
  14420. hasRequiredSortAscending = 1;
  14421. (function (module, exports$1) {
  14422. exports$1.__esModule = true;
  14423. exports$1["default"] = sortAscending;
  14424. function sortAscending(list) {
  14425. return list.sort(function (a, b) {
  14426. return a - b;
  14427. });
  14428. }
  14429. module.exports = exports$1.default;
  14430. } (sortAscending, sortAscending.exports));
  14431. return sortAscending.exports;
  14432. }
  14433. var tokenize = {};
  14434. var tokenTypes = {};
  14435. var hasRequiredTokenTypes;
  14436. function requireTokenTypes () {
  14437. if (hasRequiredTokenTypes) return tokenTypes;
  14438. hasRequiredTokenTypes = 1;
  14439. tokenTypes.__esModule = true;
  14440. 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;
  14441. var ampersand = 38; // `&`.charCodeAt(0);
  14442. tokenTypes.ampersand = ampersand;
  14443. var asterisk = 42; // `*`.charCodeAt(0);
  14444. tokenTypes.asterisk = asterisk;
  14445. var at = 64; // `@`.charCodeAt(0);
  14446. tokenTypes.at = at;
  14447. var comma = 44; // `,`.charCodeAt(0);
  14448. tokenTypes.comma = comma;
  14449. var colon = 58; // `:`.charCodeAt(0);
  14450. tokenTypes.colon = colon;
  14451. var semicolon = 59; // `;`.charCodeAt(0);
  14452. tokenTypes.semicolon = semicolon;
  14453. var openParenthesis = 40; // `(`.charCodeAt(0);
  14454. tokenTypes.openParenthesis = openParenthesis;
  14455. var closeParenthesis = 41; // `)`.charCodeAt(0);
  14456. tokenTypes.closeParenthesis = closeParenthesis;
  14457. var openSquare = 91; // `[`.charCodeAt(0);
  14458. tokenTypes.openSquare = openSquare;
  14459. var closeSquare = 93; // `]`.charCodeAt(0);
  14460. tokenTypes.closeSquare = closeSquare;
  14461. var dollar = 36; // `$`.charCodeAt(0);
  14462. tokenTypes.dollar = dollar;
  14463. var tilde = 126; // `~`.charCodeAt(0);
  14464. tokenTypes.tilde = tilde;
  14465. var caret = 94; // `^`.charCodeAt(0);
  14466. tokenTypes.caret = caret;
  14467. var plus = 43; // `+`.charCodeAt(0);
  14468. tokenTypes.plus = plus;
  14469. var equals = 61; // `=`.charCodeAt(0);
  14470. tokenTypes.equals = equals;
  14471. var pipe = 124; // `|`.charCodeAt(0);
  14472. tokenTypes.pipe = pipe;
  14473. var greaterThan = 62; // `>`.charCodeAt(0);
  14474. tokenTypes.greaterThan = greaterThan;
  14475. var space = 32; // ` `.charCodeAt(0);
  14476. tokenTypes.space = space;
  14477. var singleQuote = 39; // `'`.charCodeAt(0);
  14478. tokenTypes.singleQuote = singleQuote;
  14479. var doubleQuote = 34; // `"`.charCodeAt(0);
  14480. tokenTypes.doubleQuote = doubleQuote;
  14481. var slash = 47; // `/`.charCodeAt(0);
  14482. tokenTypes.slash = slash;
  14483. var bang = 33; // `!`.charCodeAt(0);
  14484. tokenTypes.bang = bang;
  14485. var backslash = 92; // '\\'.charCodeAt(0);
  14486. tokenTypes.backslash = backslash;
  14487. var cr = 13; // '\r'.charCodeAt(0);
  14488. tokenTypes.cr = cr;
  14489. var feed = 12; // '\f'.charCodeAt(0);
  14490. tokenTypes.feed = feed;
  14491. var newline = 10; // '\n'.charCodeAt(0);
  14492. tokenTypes.newline = newline;
  14493. var tab = 9; // '\t'.charCodeAt(0);
  14494. // Expose aliases primarily for readability.
  14495. tokenTypes.tab = tab;
  14496. var str = singleQuote;
  14497. // No good single character representation!
  14498. tokenTypes.str = str;
  14499. var comment = -1;
  14500. tokenTypes.comment = comment;
  14501. var word = -2;
  14502. tokenTypes.word = word;
  14503. var combinator = -3;
  14504. tokenTypes.combinator = combinator;
  14505. return tokenTypes;
  14506. }
  14507. var hasRequiredTokenize;
  14508. function requireTokenize () {
  14509. if (hasRequiredTokenize) return tokenize;
  14510. hasRequiredTokenize = 1;
  14511. (function (exports$1) {
  14512. exports$1.__esModule = true;
  14513. exports$1.FIELDS = void 0;
  14514. exports$1["default"] = tokenize;
  14515. var t = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes());
  14516. var _unescapable, _wordDelimiters;
  14517. 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); }
  14518. 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; }
  14519. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  14520. 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);
  14521. var hex = {};
  14522. var hexChars = "0123456789abcdefABCDEF";
  14523. for (var i = 0; i < hexChars.length; i++) {
  14524. hex[hexChars.charCodeAt(i)] = true;
  14525. }
  14526. /**
  14527. * Returns the last index of the bar css word
  14528. * @param {string} css The string in which the word begins
  14529. * @param {number} start The index into the string where word's first letter occurs
  14530. */
  14531. function consumeWord(css, start) {
  14532. var next = start;
  14533. var code;
  14534. do {
  14535. code = css.charCodeAt(next);
  14536. if (wordDelimiters[code]) {
  14537. return next - 1;
  14538. } else if (code === t.backslash) {
  14539. next = consumeEscape(css, next) + 1;
  14540. } else {
  14541. // All other characters are part of the word
  14542. next++;
  14543. }
  14544. } while (next < css.length);
  14545. return next - 1;
  14546. }
  14547. /**
  14548. * Returns the last index of the escape sequence
  14549. * @param {string} css The string in which the sequence begins
  14550. * @param {number} start The index into the string where escape character (`\`) occurs.
  14551. */
  14552. function consumeEscape(css, start) {
  14553. var next = start;
  14554. var code = css.charCodeAt(next + 1);
  14555. if (unescapable[code]) ; else if (hex[code]) {
  14556. var hexDigits = 0;
  14557. // consume up to 6 hex chars
  14558. do {
  14559. next++;
  14560. hexDigits++;
  14561. code = css.charCodeAt(next + 1);
  14562. } while (hex[code] && hexDigits < 6);
  14563. // if fewer than 6 hex chars, a trailing space ends the escape
  14564. if (hexDigits < 6 && code === t.space) {
  14565. next++;
  14566. }
  14567. } else {
  14568. // the next char is part of the current word
  14569. next++;
  14570. }
  14571. return next;
  14572. }
  14573. var FIELDS = {
  14574. TYPE: 0,
  14575. START_LINE: 1,
  14576. START_COL: 2,
  14577. END_LINE: 3,
  14578. END_COL: 4,
  14579. START_POS: 5,
  14580. END_POS: 6
  14581. };
  14582. exports$1.FIELDS = FIELDS;
  14583. function tokenize(input) {
  14584. var tokens = [];
  14585. var css = input.css.valueOf();
  14586. var _css = css,
  14587. length = _css.length;
  14588. var offset = -1;
  14589. var line = 1;
  14590. var start = 0;
  14591. var end = 0;
  14592. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  14593. function unclosed(what, fix) {
  14594. if (input.safe) {
  14595. // fyi: this is never set to true.
  14596. css += fix;
  14597. next = css.length - 1;
  14598. } else {
  14599. throw input.error('Unclosed ' + what, line, start - offset, start);
  14600. }
  14601. }
  14602. while (start < length) {
  14603. code = css.charCodeAt(start);
  14604. if (code === t.newline) {
  14605. offset = start;
  14606. line += 1;
  14607. }
  14608. switch (code) {
  14609. case t.space:
  14610. case t.tab:
  14611. case t.newline:
  14612. case t.cr:
  14613. case t.feed:
  14614. next = start;
  14615. do {
  14616. next += 1;
  14617. code = css.charCodeAt(next);
  14618. if (code === t.newline) {
  14619. offset = next;
  14620. line += 1;
  14621. }
  14622. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  14623. tokenType = t.space;
  14624. endLine = line;
  14625. endColumn = next - offset - 1;
  14626. end = next;
  14627. break;
  14628. case t.plus:
  14629. case t.greaterThan:
  14630. case t.tilde:
  14631. case t.pipe:
  14632. next = start;
  14633. do {
  14634. next += 1;
  14635. code = css.charCodeAt(next);
  14636. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  14637. tokenType = t.combinator;
  14638. endLine = line;
  14639. endColumn = start - offset;
  14640. end = next;
  14641. break;
  14642. // Consume these characters as single tokens.
  14643. case t.asterisk:
  14644. case t.ampersand:
  14645. case t.bang:
  14646. case t.comma:
  14647. case t.equals:
  14648. case t.dollar:
  14649. case t.caret:
  14650. case t.openSquare:
  14651. case t.closeSquare:
  14652. case t.colon:
  14653. case t.semicolon:
  14654. case t.openParenthesis:
  14655. case t.closeParenthesis:
  14656. next = start;
  14657. tokenType = code;
  14658. endLine = line;
  14659. endColumn = start - offset;
  14660. end = next + 1;
  14661. break;
  14662. case t.singleQuote:
  14663. case t.doubleQuote:
  14664. quote = code === t.singleQuote ? "'" : '"';
  14665. next = start;
  14666. do {
  14667. escaped = false;
  14668. next = css.indexOf(quote, next + 1);
  14669. if (next === -1) {
  14670. unclosed('quote', quote);
  14671. }
  14672. escapePos = next;
  14673. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  14674. escapePos -= 1;
  14675. escaped = !escaped;
  14676. }
  14677. } while (escaped);
  14678. tokenType = t.str;
  14679. endLine = line;
  14680. endColumn = start - offset;
  14681. end = next + 1;
  14682. break;
  14683. default:
  14684. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  14685. next = css.indexOf('*/', start + 2) + 1;
  14686. if (next === 0) {
  14687. unclosed('comment', '*/');
  14688. }
  14689. content = css.slice(start, next + 1);
  14690. lines = content.split('\n');
  14691. last = lines.length - 1;
  14692. if (last > 0) {
  14693. nextLine = line + last;
  14694. nextOffset = next - lines[last].length;
  14695. } else {
  14696. nextLine = line;
  14697. nextOffset = offset;
  14698. }
  14699. tokenType = t.comment;
  14700. line = nextLine;
  14701. endLine = nextLine;
  14702. endColumn = next - nextOffset;
  14703. } else if (code === t.slash) {
  14704. next = start;
  14705. tokenType = code;
  14706. endLine = line;
  14707. endColumn = start - offset;
  14708. end = next + 1;
  14709. } else {
  14710. next = consumeWord(css, start);
  14711. tokenType = t.word;
  14712. endLine = line;
  14713. endColumn = next - offset;
  14714. }
  14715. end = next + 1;
  14716. break;
  14717. }
  14718. // Ensure that the token structure remains consistent
  14719. tokens.push([tokenType,
  14720. // [0] Token type
  14721. line,
  14722. // [1] Starting line
  14723. start - offset,
  14724. // [2] Starting column
  14725. endLine,
  14726. // [3] Ending line
  14727. endColumn,
  14728. // [4] Ending column
  14729. start,
  14730. // [5] Start position / Source index
  14731. end // [6] End position
  14732. ]);
  14733. // Reset offset for the next token
  14734. if (nextOffset) {
  14735. offset = nextOffset;
  14736. nextOffset = null;
  14737. }
  14738. start = end;
  14739. }
  14740. return tokens;
  14741. }
  14742. } (tokenize));
  14743. return tokenize;
  14744. }
  14745. var hasRequiredParser;
  14746. function requireParser () {
  14747. if (hasRequiredParser) return parser.exports;
  14748. hasRequiredParser = 1;
  14749. (function (module, exports$1) {
  14750. exports$1.__esModule = true;
  14751. exports$1["default"] = void 0;
  14752. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot());
  14753. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector());
  14754. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName());
  14755. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment());
  14756. var _id = _interopRequireDefault(/*@__PURE__*/ requireId());
  14757. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag());
  14758. var _string = _interopRequireDefault(/*@__PURE__*/ requireString());
  14759. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo());
  14760. var _attribute = _interopRequireWildcard(/*@__PURE__*/ requireAttribute());
  14761. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal());
  14762. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator());
  14763. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting());
  14764. var _sortAscending = _interopRequireDefault(/*@__PURE__*/ requireSortAscending());
  14765. var _tokenize = _interopRequireWildcard(/*@__PURE__*/ requireTokenize());
  14766. var tokens = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes());
  14767. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes());
  14768. var _util = /*@__PURE__*/ requireUtil();
  14769. var _WHITESPACE_TOKENS, _Object$assign;
  14770. 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); }
  14771. 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; }
  14772. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14773. 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); } }
  14774. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  14775. 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);
  14776. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  14777. function tokenStart(token) {
  14778. return {
  14779. line: token[_tokenize.FIELDS.START_LINE],
  14780. column: token[_tokenize.FIELDS.START_COL]
  14781. };
  14782. }
  14783. function tokenEnd(token) {
  14784. return {
  14785. line: token[_tokenize.FIELDS.END_LINE],
  14786. column: token[_tokenize.FIELDS.END_COL]
  14787. };
  14788. }
  14789. function getSource(startLine, startColumn, endLine, endColumn) {
  14790. return {
  14791. start: {
  14792. line: startLine,
  14793. column: startColumn
  14794. },
  14795. end: {
  14796. line: endLine,
  14797. column: endColumn
  14798. }
  14799. };
  14800. }
  14801. function getTokenSource(token) {
  14802. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  14803. }
  14804. function getTokenSourceSpan(startToken, endToken) {
  14805. if (!startToken) {
  14806. return undefined;
  14807. }
  14808. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  14809. }
  14810. function unescapeProp(node, prop) {
  14811. var value = node[prop];
  14812. if (typeof value !== "string") {
  14813. return;
  14814. }
  14815. if (value.indexOf("\\") !== -1) {
  14816. (0, _util.ensureObject)(node, 'raws');
  14817. node[prop] = (0, _util.unesc)(value);
  14818. if (node.raws[prop] === undefined) {
  14819. node.raws[prop] = value;
  14820. }
  14821. }
  14822. return node;
  14823. }
  14824. function indexesOf(array, item) {
  14825. var i = -1;
  14826. var indexes = [];
  14827. while ((i = array.indexOf(item, i + 1)) !== -1) {
  14828. indexes.push(i);
  14829. }
  14830. return indexes;
  14831. }
  14832. function uniqs() {
  14833. var list = Array.prototype.concat.apply([], arguments);
  14834. return list.filter(function (item, i) {
  14835. return i === list.indexOf(item);
  14836. });
  14837. }
  14838. var Parser = /*#__PURE__*/function () {
  14839. function Parser(rule, options) {
  14840. if (options === void 0) {
  14841. options = {};
  14842. }
  14843. this.rule = rule;
  14844. this.options = Object.assign({
  14845. lossy: false,
  14846. safe: false
  14847. }, options);
  14848. this.position = 0;
  14849. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  14850. this.tokens = (0, _tokenize["default"])({
  14851. css: this.css,
  14852. error: this._errorGenerator(),
  14853. safe: this.options.safe
  14854. });
  14855. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  14856. this.root = new _root["default"]({
  14857. source: rootSource
  14858. });
  14859. this.root.errorGenerator = this._errorGenerator();
  14860. var selector = new _selector["default"]({
  14861. source: {
  14862. start: {
  14863. line: 1,
  14864. column: 1
  14865. }
  14866. },
  14867. sourceIndex: 0
  14868. });
  14869. this.root.append(selector);
  14870. this.current = selector;
  14871. this.loop();
  14872. }
  14873. var _proto = Parser.prototype;
  14874. _proto._errorGenerator = function _errorGenerator() {
  14875. var _this = this;
  14876. return function (message, errorOptions) {
  14877. if (typeof _this.rule === 'string') {
  14878. return new Error(message);
  14879. }
  14880. return _this.rule.error(message, errorOptions);
  14881. };
  14882. };
  14883. _proto.attribute = function attribute() {
  14884. var attr = [];
  14885. var startingToken = this.currToken;
  14886. this.position++;
  14887. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  14888. attr.push(this.currToken);
  14889. this.position++;
  14890. }
  14891. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  14892. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  14893. }
  14894. var len = attr.length;
  14895. var node = {
  14896. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  14897. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  14898. };
  14899. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  14900. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  14901. }
  14902. var pos = 0;
  14903. var spaceBefore = '';
  14904. var commentBefore = '';
  14905. var lastAdded = null;
  14906. var spaceAfterMeaningfulToken = false;
  14907. while (pos < len) {
  14908. var token = attr[pos];
  14909. var content = this.content(token);
  14910. var next = attr[pos + 1];
  14911. switch (token[_tokenize.FIELDS.TYPE]) {
  14912. case tokens.space:
  14913. // if (
  14914. // len === 1 ||
  14915. // pos === 0 && this.content(next) === '|'
  14916. // ) {
  14917. // return this.expected('attribute', token[TOKEN.START_POS], content);
  14918. // }
  14919. spaceAfterMeaningfulToken = true;
  14920. if (this.options.lossy) {
  14921. break;
  14922. }
  14923. if (lastAdded) {
  14924. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  14925. var prevContent = node.spaces[lastAdded].after || '';
  14926. node.spaces[lastAdded].after = prevContent + content;
  14927. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  14928. if (existingComment) {
  14929. node.raws.spaces[lastAdded].after = existingComment + content;
  14930. }
  14931. } else {
  14932. spaceBefore = spaceBefore + content;
  14933. commentBefore = commentBefore + content;
  14934. }
  14935. break;
  14936. case tokens.asterisk:
  14937. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14938. node.operator = content;
  14939. lastAdded = 'operator';
  14940. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  14941. if (spaceBefore) {
  14942. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  14943. node.spaces.attribute.before = spaceBefore;
  14944. spaceBefore = '';
  14945. }
  14946. if (commentBefore) {
  14947. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  14948. node.raws.spaces.attribute.before = spaceBefore;
  14949. commentBefore = '';
  14950. }
  14951. node.namespace = (node.namespace || "") + content;
  14952. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  14953. if (rawValue) {
  14954. node.raws.namespace += content;
  14955. }
  14956. lastAdded = 'namespace';
  14957. }
  14958. spaceAfterMeaningfulToken = false;
  14959. break;
  14960. case tokens.dollar:
  14961. if (lastAdded === "value") {
  14962. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  14963. node.value += "$";
  14964. if (oldRawValue) {
  14965. node.raws.value = oldRawValue + "$";
  14966. }
  14967. break;
  14968. }
  14969. // Falls through
  14970. case tokens.caret:
  14971. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14972. node.operator = content;
  14973. lastAdded = 'operator';
  14974. }
  14975. spaceAfterMeaningfulToken = false;
  14976. break;
  14977. case tokens.combinator:
  14978. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14979. node.operator = content;
  14980. lastAdded = 'operator';
  14981. }
  14982. if (content !== '|') {
  14983. spaceAfterMeaningfulToken = false;
  14984. break;
  14985. }
  14986. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14987. node.operator = content;
  14988. lastAdded = 'operator';
  14989. } else if (!node.namespace && !node.attribute) {
  14990. node.namespace = true;
  14991. }
  14992. spaceAfterMeaningfulToken = false;
  14993. break;
  14994. case tokens.word:
  14995. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
  14996. // this look-ahead probably fails with comment nodes involved.
  14997. !node.operator && !node.namespace) {
  14998. node.namespace = content;
  14999. lastAdded = 'namespace';
  15000. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  15001. if (spaceBefore) {
  15002. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  15003. node.spaces.attribute.before = spaceBefore;
  15004. spaceBefore = '';
  15005. }
  15006. if (commentBefore) {
  15007. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  15008. node.raws.spaces.attribute.before = commentBefore;
  15009. commentBefore = '';
  15010. }
  15011. node.attribute = (node.attribute || "") + content;
  15012. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  15013. if (_rawValue) {
  15014. node.raws.attribute += content;
  15015. }
  15016. lastAdded = 'attribute';
  15017. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  15018. var _unescaped = (0, _util.unesc)(content);
  15019. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  15020. var oldValue = node.value || '';
  15021. node.value = oldValue + _unescaped;
  15022. node.quoteMark = null;
  15023. if (_unescaped !== content || _oldRawValue) {
  15024. (0, _util.ensureObject)(node, 'raws');
  15025. node.raws.value = (_oldRawValue || oldValue) + content;
  15026. }
  15027. lastAdded = 'value';
  15028. } else {
  15029. var insensitive = content === 'i' || content === "I";
  15030. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  15031. node.insensitive = insensitive;
  15032. if (!insensitive || content === "I") {
  15033. (0, _util.ensureObject)(node, 'raws');
  15034. node.raws.insensitiveFlag = content;
  15035. }
  15036. lastAdded = 'insensitive';
  15037. if (spaceBefore) {
  15038. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  15039. node.spaces.insensitive.before = spaceBefore;
  15040. spaceBefore = '';
  15041. }
  15042. if (commentBefore) {
  15043. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  15044. node.raws.spaces.insensitive.before = commentBefore;
  15045. commentBefore = '';
  15046. }
  15047. } else if (node.value || node.value === '') {
  15048. lastAdded = 'value';
  15049. node.value += content;
  15050. if (node.raws.value) {
  15051. node.raws.value += content;
  15052. }
  15053. }
  15054. }
  15055. spaceAfterMeaningfulToken = false;
  15056. break;
  15057. case tokens.str:
  15058. if (!node.attribute || !node.operator) {
  15059. return this.error("Expected an attribute followed by an operator preceding the string.", {
  15060. index: token[_tokenize.FIELDS.START_POS]
  15061. });
  15062. }
  15063. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  15064. unescaped = _unescapeValue.unescaped,
  15065. quoteMark = _unescapeValue.quoteMark;
  15066. node.value = unescaped;
  15067. node.quoteMark = quoteMark;
  15068. lastAdded = 'value';
  15069. (0, _util.ensureObject)(node, 'raws');
  15070. node.raws.value = content;
  15071. spaceAfterMeaningfulToken = false;
  15072. break;
  15073. case tokens.equals:
  15074. if (!node.attribute) {
  15075. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  15076. }
  15077. if (node.value) {
  15078. return this.error('Unexpected "=" found; an operator was already defined.', {
  15079. index: token[_tokenize.FIELDS.START_POS]
  15080. });
  15081. }
  15082. node.operator = node.operator ? node.operator + content : content;
  15083. lastAdded = 'operator';
  15084. spaceAfterMeaningfulToken = false;
  15085. break;
  15086. case tokens.comment:
  15087. if (lastAdded) {
  15088. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  15089. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  15090. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  15091. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  15092. node.raws.spaces[lastAdded].after = rawLastComment + content;
  15093. } else {
  15094. var lastValue = node[lastAdded] || '';
  15095. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  15096. (0, _util.ensureObject)(node, 'raws');
  15097. node.raws[lastAdded] = rawLastValue + content;
  15098. }
  15099. } else {
  15100. commentBefore = commentBefore + content;
  15101. }
  15102. break;
  15103. default:
  15104. return this.error("Unexpected \"" + content + "\" found.", {
  15105. index: token[_tokenize.FIELDS.START_POS]
  15106. });
  15107. }
  15108. pos++;
  15109. }
  15110. unescapeProp(node, "attribute");
  15111. unescapeProp(node, "namespace");
  15112. this.newNode(new _attribute["default"](node));
  15113. this.position++;
  15114. }
  15115. /**
  15116. * return a node containing meaningless garbage up to (but not including) the specified token position.
  15117. * if the token position is negative, all remaining tokens are consumed.
  15118. *
  15119. * This returns an array containing a single string node if all whitespace,
  15120. * otherwise an array of comment nodes with space before and after.
  15121. *
  15122. * These tokens are not added to the current selector, the caller can add them or use them to amend
  15123. * a previous node's space metadata.
  15124. *
  15125. * In lossy mode, this returns only comments.
  15126. */;
  15127. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  15128. if (stopPosition < 0) {
  15129. stopPosition = this.tokens.length;
  15130. }
  15131. var startPosition = this.position;
  15132. var nodes = [];
  15133. var space = "";
  15134. var lastComment = undefined;
  15135. do {
  15136. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  15137. if (!this.options.lossy) {
  15138. space += this.content();
  15139. }
  15140. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  15141. var spaces = {};
  15142. if (space) {
  15143. spaces.before = space;
  15144. space = "";
  15145. }
  15146. lastComment = new _comment["default"]({
  15147. value: this.content(),
  15148. source: getTokenSource(this.currToken),
  15149. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  15150. spaces: spaces
  15151. });
  15152. nodes.push(lastComment);
  15153. }
  15154. } while (++this.position < stopPosition);
  15155. if (space) {
  15156. if (lastComment) {
  15157. lastComment.spaces.after = space;
  15158. } else if (!this.options.lossy) {
  15159. var firstToken = this.tokens[startPosition];
  15160. var lastToken = this.tokens[this.position - 1];
  15161. nodes.push(new _string["default"]({
  15162. value: '',
  15163. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  15164. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  15165. spaces: {
  15166. before: space,
  15167. after: ''
  15168. }
  15169. }));
  15170. }
  15171. }
  15172. return nodes;
  15173. }
  15174. /**
  15175. *
  15176. * @param {*} nodes
  15177. */;
  15178. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  15179. var _this2 = this;
  15180. if (requiredSpace === void 0) {
  15181. requiredSpace = false;
  15182. }
  15183. var space = "";
  15184. var rawSpace = "";
  15185. nodes.forEach(function (n) {
  15186. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  15187. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  15188. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  15189. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  15190. });
  15191. if (rawSpace === space) {
  15192. rawSpace = undefined;
  15193. }
  15194. var result = {
  15195. space: space,
  15196. rawSpace: rawSpace
  15197. };
  15198. return result;
  15199. };
  15200. _proto.isNamedCombinator = function isNamedCombinator(position) {
  15201. if (position === void 0) {
  15202. position = this.position;
  15203. }
  15204. 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;
  15205. };
  15206. _proto.namedCombinator = function namedCombinator() {
  15207. if (this.isNamedCombinator()) {
  15208. var nameRaw = this.content(this.tokens[this.position + 1]);
  15209. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  15210. var raws = {};
  15211. if (name !== nameRaw) {
  15212. raws.value = "/" + nameRaw + "/";
  15213. }
  15214. var node = new _combinator["default"]({
  15215. value: "/" + name + "/",
  15216. 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]),
  15217. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  15218. raws: raws
  15219. });
  15220. this.position = this.position + 3;
  15221. return node;
  15222. } else {
  15223. this.unexpected();
  15224. }
  15225. };
  15226. _proto.combinator = function combinator() {
  15227. var _this3 = this;
  15228. if (this.content() === '|') {
  15229. return this.namespace();
  15230. }
  15231. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  15232. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  15233. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15234. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  15235. if (nodes.length > 0) {
  15236. var last = this.current.last;
  15237. if (last) {
  15238. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  15239. space = _this$convertWhitespa.space,
  15240. rawSpace = _this$convertWhitespa.rawSpace;
  15241. if (rawSpace !== undefined) {
  15242. last.rawSpaceAfter += rawSpace;
  15243. }
  15244. last.spaces.after += space;
  15245. } else {
  15246. nodes.forEach(function (n) {
  15247. return _this3.newNode(n);
  15248. });
  15249. }
  15250. }
  15251. return;
  15252. }
  15253. var firstToken = this.currToken;
  15254. var spaceOrDescendantSelectorNodes = undefined;
  15255. if (nextSigTokenPos > this.position) {
  15256. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  15257. }
  15258. var node;
  15259. if (this.isNamedCombinator()) {
  15260. node = this.namedCombinator();
  15261. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  15262. node = new _combinator["default"]({
  15263. value: this.content(),
  15264. source: getTokenSource(this.currToken),
  15265. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  15266. });
  15267. this.position++;
  15268. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  15269. this.unexpected();
  15270. }
  15271. if (node) {
  15272. if (spaceOrDescendantSelectorNodes) {
  15273. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  15274. _space = _this$convertWhitespa2.space,
  15275. _rawSpace = _this$convertWhitespa2.rawSpace;
  15276. node.spaces.before = _space;
  15277. node.rawSpaceBefore = _rawSpace;
  15278. }
  15279. } else {
  15280. // descendant combinator
  15281. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  15282. _space2 = _this$convertWhitespa3.space,
  15283. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  15284. if (!_rawSpace2) {
  15285. _rawSpace2 = _space2;
  15286. }
  15287. var spaces = {};
  15288. var raws = {
  15289. spaces: {}
  15290. };
  15291. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  15292. spaces.before = _space2.slice(0, _space2.length - 1);
  15293. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  15294. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  15295. spaces.after = _space2.slice(1);
  15296. raws.spaces.after = _rawSpace2.slice(1);
  15297. } else {
  15298. raws.value = _rawSpace2;
  15299. }
  15300. node = new _combinator["default"]({
  15301. value: ' ',
  15302. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  15303. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  15304. spaces: spaces,
  15305. raws: raws
  15306. });
  15307. }
  15308. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  15309. node.spaces.after = this.optionalSpace(this.content());
  15310. this.position++;
  15311. }
  15312. return this.newNode(node);
  15313. };
  15314. _proto.comma = function comma() {
  15315. if (this.position === this.tokens.length - 1) {
  15316. this.root.trailingComma = true;
  15317. this.position++;
  15318. return;
  15319. }
  15320. this.current._inferEndPosition();
  15321. var selector = new _selector["default"]({
  15322. source: {
  15323. start: tokenStart(this.tokens[this.position + 1])
  15324. },
  15325. sourceIndex: this.tokens[this.position + 1][_tokenize.FIELDS.START_POS]
  15326. });
  15327. this.current.parent.append(selector);
  15328. this.current = selector;
  15329. this.position++;
  15330. };
  15331. _proto.comment = function comment() {
  15332. var current = this.currToken;
  15333. this.newNode(new _comment["default"]({
  15334. value: this.content(),
  15335. source: getTokenSource(current),
  15336. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15337. }));
  15338. this.position++;
  15339. };
  15340. _proto.error = function error(message, opts) {
  15341. throw this.root.error(message, opts);
  15342. };
  15343. _proto.missingBackslash = function missingBackslash() {
  15344. return this.error('Expected a backslash preceding the semicolon.', {
  15345. index: this.currToken[_tokenize.FIELDS.START_POS]
  15346. });
  15347. };
  15348. _proto.missingParenthesis = function missingParenthesis() {
  15349. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  15350. };
  15351. _proto.missingSquareBracket = function missingSquareBracket() {
  15352. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  15353. };
  15354. _proto.unexpected = function unexpected() {
  15355. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  15356. };
  15357. _proto.unexpectedPipe = function unexpectedPipe() {
  15358. return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  15359. };
  15360. _proto.namespace = function namespace() {
  15361. var before = this.prevToken && this.content(this.prevToken) || true;
  15362. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  15363. this.position++;
  15364. return this.word(before);
  15365. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  15366. this.position++;
  15367. return this.universal(before);
  15368. }
  15369. this.unexpectedPipe();
  15370. };
  15371. _proto.nesting = function nesting() {
  15372. if (this.nextToken) {
  15373. var nextContent = this.content(this.nextToken);
  15374. if (nextContent === "|") {
  15375. this.position++;
  15376. return;
  15377. }
  15378. }
  15379. var current = this.currToken;
  15380. this.newNode(new _nesting["default"]({
  15381. value: this.content(),
  15382. source: getTokenSource(current),
  15383. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15384. }));
  15385. this.position++;
  15386. };
  15387. _proto.parentheses = function parentheses() {
  15388. var last = this.current.last;
  15389. var unbalanced = 1;
  15390. this.position++;
  15391. if (last && last.type === types.PSEUDO) {
  15392. var selector = new _selector["default"]({
  15393. source: {
  15394. start: tokenStart(this.tokens[this.position])
  15395. },
  15396. sourceIndex: this.tokens[this.position][_tokenize.FIELDS.START_POS]
  15397. });
  15398. var cache = this.current;
  15399. last.append(selector);
  15400. this.current = selector;
  15401. while (this.position < this.tokens.length && unbalanced) {
  15402. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15403. unbalanced++;
  15404. }
  15405. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15406. unbalanced--;
  15407. }
  15408. if (unbalanced) {
  15409. this.parse();
  15410. } else {
  15411. this.current.source.end = tokenEnd(this.currToken);
  15412. this.current.parent.source.end = tokenEnd(this.currToken);
  15413. this.position++;
  15414. }
  15415. }
  15416. this.current = cache;
  15417. } else {
  15418. // I think this case should be an error. It's used to implement a basic parse of media queries
  15419. // but I don't think it's a good idea.
  15420. var parenStart = this.currToken;
  15421. var parenValue = "(";
  15422. var parenEnd;
  15423. while (this.position < this.tokens.length && unbalanced) {
  15424. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15425. unbalanced++;
  15426. }
  15427. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15428. unbalanced--;
  15429. }
  15430. parenEnd = this.currToken;
  15431. parenValue += this.parseParenthesisToken(this.currToken);
  15432. this.position++;
  15433. }
  15434. if (last) {
  15435. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  15436. } else {
  15437. this.newNode(new _string["default"]({
  15438. value: parenValue,
  15439. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  15440. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  15441. }));
  15442. }
  15443. }
  15444. if (unbalanced) {
  15445. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  15446. }
  15447. };
  15448. _proto.pseudo = function pseudo() {
  15449. var _this4 = this;
  15450. var pseudoStr = '';
  15451. var startingToken = this.currToken;
  15452. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  15453. pseudoStr += this.content();
  15454. this.position++;
  15455. }
  15456. if (!this.currToken) {
  15457. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  15458. }
  15459. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  15460. this.splitWord(false, function (first, length) {
  15461. pseudoStr += first;
  15462. _this4.newNode(new _pseudo["default"]({
  15463. value: pseudoStr,
  15464. source: getTokenSourceSpan(startingToken, _this4.currToken),
  15465. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  15466. }));
  15467. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15468. _this4.error('Misplaced parenthesis.', {
  15469. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  15470. });
  15471. }
  15472. });
  15473. } else {
  15474. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  15475. }
  15476. };
  15477. _proto.space = function space() {
  15478. var content = this.content();
  15479. // Handle space before and after the selector
  15480. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  15481. return node.type === 'comment';
  15482. })) {
  15483. this.spaces = this.optionalSpace(content);
  15484. this.position++;
  15485. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15486. this.current.last.spaces.after = this.optionalSpace(content);
  15487. this.position++;
  15488. } else {
  15489. this.combinator();
  15490. }
  15491. };
  15492. _proto.string = function string() {
  15493. var current = this.currToken;
  15494. this.newNode(new _string["default"]({
  15495. value: this.content(),
  15496. source: getTokenSource(current),
  15497. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15498. }));
  15499. this.position++;
  15500. };
  15501. _proto.universal = function universal(namespace) {
  15502. var nextToken = this.nextToken;
  15503. if (nextToken && this.content(nextToken) === '|') {
  15504. this.position++;
  15505. return this.namespace();
  15506. }
  15507. var current = this.currToken;
  15508. this.newNode(new _universal["default"]({
  15509. value: this.content(),
  15510. source: getTokenSource(current),
  15511. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15512. }), namespace);
  15513. this.position++;
  15514. };
  15515. _proto.splitWord = function splitWord(namespace, firstCallback) {
  15516. var _this5 = this;
  15517. var nextToken = this.nextToken;
  15518. var word = this.content();
  15519. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  15520. this.position++;
  15521. var current = this.content();
  15522. word += current;
  15523. if (current.lastIndexOf('\\') === current.length - 1) {
  15524. var next = this.nextToken;
  15525. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  15526. word += this.requiredSpace(this.content(next));
  15527. this.position++;
  15528. }
  15529. }
  15530. nextToken = this.nextToken;
  15531. }
  15532. var hasClass = indexesOf(word, '.').filter(function (i) {
  15533. // Allow escaped dot within class name
  15534. var escapedDot = word[i - 1] === '\\';
  15535. // Allow decimal numbers percent in @keyframes
  15536. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  15537. return !escapedDot && !isKeyframesPercent;
  15538. });
  15539. var hasId = indexesOf(word, '#').filter(function (i) {
  15540. return word[i - 1] !== '\\';
  15541. });
  15542. // Eliminate Sass interpolations from the list of id indexes
  15543. var interpolations = indexesOf(word, '#{');
  15544. if (interpolations.length) {
  15545. hasId = hasId.filter(function (hashIndex) {
  15546. return !~interpolations.indexOf(hashIndex);
  15547. });
  15548. }
  15549. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  15550. indices.forEach(function (ind, i) {
  15551. var index = indices[i + 1] || word.length;
  15552. var value = word.slice(ind, index);
  15553. if (i === 0 && firstCallback) {
  15554. return firstCallback.call(_this5, value, indices.length);
  15555. }
  15556. var node;
  15557. var current = _this5.currToken;
  15558. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  15559. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  15560. if (~hasClass.indexOf(ind)) {
  15561. var classNameOpts = {
  15562. value: value.slice(1),
  15563. source: source,
  15564. sourceIndex: sourceIndex
  15565. };
  15566. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  15567. } else if (~hasId.indexOf(ind)) {
  15568. var idOpts = {
  15569. value: value.slice(1),
  15570. source: source,
  15571. sourceIndex: sourceIndex
  15572. };
  15573. node = new _id["default"](unescapeProp(idOpts, "value"));
  15574. } else {
  15575. var tagOpts = {
  15576. value: value,
  15577. source: source,
  15578. sourceIndex: sourceIndex
  15579. };
  15580. unescapeProp(tagOpts, "value");
  15581. node = new _tag["default"](tagOpts);
  15582. }
  15583. _this5.newNode(node, namespace);
  15584. // Ensure that the namespace is used only once
  15585. namespace = null;
  15586. });
  15587. this.position++;
  15588. };
  15589. _proto.word = function word(namespace) {
  15590. var nextToken = this.nextToken;
  15591. if (nextToken && this.content(nextToken) === '|') {
  15592. this.position++;
  15593. return this.namespace();
  15594. }
  15595. return this.splitWord(namespace);
  15596. };
  15597. _proto.loop = function loop() {
  15598. while (this.position < this.tokens.length) {
  15599. this.parse(true);
  15600. }
  15601. this.current._inferEndPosition();
  15602. return this.root;
  15603. };
  15604. _proto.parse = function parse(throwOnParenthesis) {
  15605. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  15606. case tokens.space:
  15607. this.space();
  15608. break;
  15609. case tokens.comment:
  15610. this.comment();
  15611. break;
  15612. case tokens.openParenthesis:
  15613. this.parentheses();
  15614. break;
  15615. case tokens.closeParenthesis:
  15616. if (throwOnParenthesis) {
  15617. this.missingParenthesis();
  15618. }
  15619. break;
  15620. case tokens.openSquare:
  15621. this.attribute();
  15622. break;
  15623. case tokens.dollar:
  15624. case tokens.caret:
  15625. case tokens.equals:
  15626. case tokens.word:
  15627. this.word();
  15628. break;
  15629. case tokens.colon:
  15630. this.pseudo();
  15631. break;
  15632. case tokens.comma:
  15633. this.comma();
  15634. break;
  15635. case tokens.asterisk:
  15636. this.universal();
  15637. break;
  15638. case tokens.ampersand:
  15639. this.nesting();
  15640. break;
  15641. case tokens.slash:
  15642. case tokens.combinator:
  15643. this.combinator();
  15644. break;
  15645. case tokens.str:
  15646. this.string();
  15647. break;
  15648. // These cases throw; no break needed.
  15649. case tokens.closeSquare:
  15650. this.missingSquareBracket();
  15651. case tokens.semicolon:
  15652. this.missingBackslash();
  15653. default:
  15654. this.unexpected();
  15655. }
  15656. }
  15657. /**
  15658. * Helpers
  15659. */;
  15660. _proto.expected = function expected(description, index, found) {
  15661. if (Array.isArray(description)) {
  15662. var last = description.pop();
  15663. description = description.join(', ') + " or " + last;
  15664. }
  15665. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  15666. if (!found) {
  15667. return this.error("Expected " + an + " " + description + ".", {
  15668. index: index
  15669. });
  15670. }
  15671. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  15672. index: index
  15673. });
  15674. };
  15675. _proto.requiredSpace = function requiredSpace(space) {
  15676. return this.options.lossy ? ' ' : space;
  15677. };
  15678. _proto.optionalSpace = function optionalSpace(space) {
  15679. return this.options.lossy ? '' : space;
  15680. };
  15681. _proto.lossySpace = function lossySpace(space, required) {
  15682. if (this.options.lossy) {
  15683. return required ? ' ' : '';
  15684. } else {
  15685. return space;
  15686. }
  15687. };
  15688. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  15689. var content = this.content(token);
  15690. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  15691. return this.requiredSpace(content);
  15692. } else {
  15693. return content;
  15694. }
  15695. };
  15696. _proto.newNode = function newNode(node, namespace) {
  15697. if (namespace) {
  15698. if (/^ +$/.test(namespace)) {
  15699. if (!this.options.lossy) {
  15700. this.spaces = (this.spaces || '') + namespace;
  15701. }
  15702. namespace = true;
  15703. }
  15704. node.namespace = namespace;
  15705. unescapeProp(node, "namespace");
  15706. }
  15707. if (this.spaces) {
  15708. node.spaces.before = this.spaces;
  15709. this.spaces = '';
  15710. }
  15711. return this.current.append(node);
  15712. };
  15713. _proto.content = function content(token) {
  15714. if (token === void 0) {
  15715. token = this.currToken;
  15716. }
  15717. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  15718. };
  15719. /**
  15720. * returns the index of the next non-whitespace, non-comment token.
  15721. * returns -1 if no meaningful token is found.
  15722. */
  15723. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  15724. if (startPosition === void 0) {
  15725. startPosition = this.position + 1;
  15726. }
  15727. var searchPosition = startPosition;
  15728. while (searchPosition < this.tokens.length) {
  15729. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  15730. searchPosition++;
  15731. continue;
  15732. } else {
  15733. return searchPosition;
  15734. }
  15735. }
  15736. return -1;
  15737. };
  15738. _createClass(Parser, [{
  15739. key: "currToken",
  15740. get: function get() {
  15741. return this.tokens[this.position];
  15742. }
  15743. }, {
  15744. key: "nextToken",
  15745. get: function get() {
  15746. return this.tokens[this.position + 1];
  15747. }
  15748. }, {
  15749. key: "prevToken",
  15750. get: function get() {
  15751. return this.tokens[this.position - 1];
  15752. }
  15753. }]);
  15754. return Parser;
  15755. }();
  15756. exports$1["default"] = Parser;
  15757. module.exports = exports$1.default;
  15758. } (parser, parser.exports));
  15759. return parser.exports;
  15760. }
  15761. var hasRequiredProcessor;
  15762. function requireProcessor () {
  15763. if (hasRequiredProcessor) return processor.exports;
  15764. hasRequiredProcessor = 1;
  15765. (function (module, exports$1) {
  15766. exports$1.__esModule = true;
  15767. exports$1["default"] = void 0;
  15768. var _parser = _interopRequireDefault(/*@__PURE__*/ requireParser());
  15769. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  15770. var Processor = /*#__PURE__*/function () {
  15771. function Processor(func, options) {
  15772. this.func = func || function noop() {};
  15773. this.funcRes = null;
  15774. this.options = options;
  15775. }
  15776. var _proto = Processor.prototype;
  15777. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  15778. if (options === void 0) {
  15779. options = {};
  15780. }
  15781. var merged = Object.assign({}, this.options, options);
  15782. if (merged.updateSelector === false) {
  15783. return false;
  15784. } else {
  15785. return typeof rule !== "string";
  15786. }
  15787. };
  15788. _proto._isLossy = function _isLossy(options) {
  15789. if (options === void 0) {
  15790. options = {};
  15791. }
  15792. var merged = Object.assign({}, this.options, options);
  15793. if (merged.lossless === false) {
  15794. return true;
  15795. } else {
  15796. return false;
  15797. }
  15798. };
  15799. _proto._root = function _root(rule, options) {
  15800. if (options === void 0) {
  15801. options = {};
  15802. }
  15803. var parser = new _parser["default"](rule, this._parseOptions(options));
  15804. return parser.root;
  15805. };
  15806. _proto._parseOptions = function _parseOptions(options) {
  15807. return {
  15808. lossy: this._isLossy(options)
  15809. };
  15810. };
  15811. _proto._run = function _run(rule, options) {
  15812. var _this = this;
  15813. if (options === void 0) {
  15814. options = {};
  15815. }
  15816. return new Promise(function (resolve, reject) {
  15817. try {
  15818. var root = _this._root(rule, options);
  15819. Promise.resolve(_this.func(root)).then(function (transform) {
  15820. var string = undefined;
  15821. if (_this._shouldUpdateSelector(rule, options)) {
  15822. string = root.toString();
  15823. rule.selector = string;
  15824. }
  15825. return {
  15826. transform: transform,
  15827. root: root,
  15828. string: string
  15829. };
  15830. }).then(resolve, reject);
  15831. } catch (e) {
  15832. reject(e);
  15833. return;
  15834. }
  15835. });
  15836. };
  15837. _proto._runSync = function _runSync(rule, options) {
  15838. if (options === void 0) {
  15839. options = {};
  15840. }
  15841. var root = this._root(rule, options);
  15842. var transform = this.func(root);
  15843. if (transform && typeof transform.then === "function") {
  15844. throw new Error("Selector processor returned a promise to a synchronous call.");
  15845. }
  15846. var string = undefined;
  15847. if (options.updateSelector && typeof rule !== "string") {
  15848. string = root.toString();
  15849. rule.selector = string;
  15850. }
  15851. return {
  15852. transform: transform,
  15853. root: root,
  15854. string: string
  15855. };
  15856. }
  15857. /**
  15858. * Process rule into a selector AST.
  15859. *
  15860. * @param rule {postcss.Rule | string} The css selector to be processed
  15861. * @param options The options for processing
  15862. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  15863. */;
  15864. _proto.ast = function ast(rule, options) {
  15865. return this._run(rule, options).then(function (result) {
  15866. return result.root;
  15867. });
  15868. }
  15869. /**
  15870. * Process rule into a selector AST synchronously.
  15871. *
  15872. * @param rule {postcss.Rule | string} The css selector to be processed
  15873. * @param options The options for processing
  15874. * @returns {parser.Root} The AST of the selector after processing it.
  15875. */;
  15876. _proto.astSync = function astSync(rule, options) {
  15877. return this._runSync(rule, options).root;
  15878. }
  15879. /**
  15880. * Process a selector into a transformed value asynchronously
  15881. *
  15882. * @param rule {postcss.Rule | string} The css selector to be processed
  15883. * @param options The options for processing
  15884. * @returns {Promise<any>} The value returned by the processor.
  15885. */;
  15886. _proto.transform = function transform(rule, options) {
  15887. return this._run(rule, options).then(function (result) {
  15888. return result.transform;
  15889. });
  15890. }
  15891. /**
  15892. * Process a selector into a transformed value synchronously.
  15893. *
  15894. * @param rule {postcss.Rule | string} The css selector to be processed
  15895. * @param options The options for processing
  15896. * @returns {any} The value returned by the processor.
  15897. */;
  15898. _proto.transformSync = function transformSync(rule, options) {
  15899. return this._runSync(rule, options).transform;
  15900. }
  15901. /**
  15902. * Process a selector into a new selector string asynchronously.
  15903. *
  15904. * @param rule {postcss.Rule | string} The css selector to be processed
  15905. * @param options The options for processing
  15906. * @returns {string} the selector after processing.
  15907. */;
  15908. _proto.process = function process(rule, options) {
  15909. return this._run(rule, options).then(function (result) {
  15910. return result.string || result.root.toString();
  15911. });
  15912. }
  15913. /**
  15914. * Process a selector into a new selector string synchronously.
  15915. *
  15916. * @param rule {postcss.Rule | string} The css selector to be processed
  15917. * @param options The options for processing
  15918. * @returns {string} the selector after processing.
  15919. */;
  15920. _proto.processSync = function processSync(rule, options) {
  15921. var result = this._runSync(rule, options);
  15922. return result.string || result.root.toString();
  15923. };
  15924. return Processor;
  15925. }();
  15926. exports$1["default"] = Processor;
  15927. module.exports = exports$1.default;
  15928. } (processor, processor.exports));
  15929. return processor.exports;
  15930. }
  15931. var selectors = {};
  15932. var constructors = {};
  15933. var hasRequiredConstructors;
  15934. function requireConstructors () {
  15935. if (hasRequiredConstructors) return constructors;
  15936. hasRequiredConstructors = 1;
  15937. constructors.__esModule = true;
  15938. 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;
  15939. var _attribute = _interopRequireDefault(/*@__PURE__*/ requireAttribute());
  15940. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName());
  15941. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator());
  15942. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment());
  15943. var _id = _interopRequireDefault(/*@__PURE__*/ requireId());
  15944. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting());
  15945. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo());
  15946. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot());
  15947. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector());
  15948. var _string = _interopRequireDefault(/*@__PURE__*/ requireString());
  15949. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag());
  15950. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal());
  15951. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  15952. var attribute = function attribute(opts) {
  15953. return new _attribute["default"](opts);
  15954. };
  15955. constructors.attribute = attribute;
  15956. var className = function className(opts) {
  15957. return new _className["default"](opts);
  15958. };
  15959. constructors.className = className;
  15960. var combinator = function combinator(opts) {
  15961. return new _combinator["default"](opts);
  15962. };
  15963. constructors.combinator = combinator;
  15964. var comment = function comment(opts) {
  15965. return new _comment["default"](opts);
  15966. };
  15967. constructors.comment = comment;
  15968. var id = function id(opts) {
  15969. return new _id["default"](opts);
  15970. };
  15971. constructors.id = id;
  15972. var nesting = function nesting(opts) {
  15973. return new _nesting["default"](opts);
  15974. };
  15975. constructors.nesting = nesting;
  15976. var pseudo = function pseudo(opts) {
  15977. return new _pseudo["default"](opts);
  15978. };
  15979. constructors.pseudo = pseudo;
  15980. var root = function root(opts) {
  15981. return new _root["default"](opts);
  15982. };
  15983. constructors.root = root;
  15984. var selector = function selector(opts) {
  15985. return new _selector["default"](opts);
  15986. };
  15987. constructors.selector = selector;
  15988. var string = function string(opts) {
  15989. return new _string["default"](opts);
  15990. };
  15991. constructors.string = string;
  15992. var tag = function tag(opts) {
  15993. return new _tag["default"](opts);
  15994. };
  15995. constructors.tag = tag;
  15996. var universal = function universal(opts) {
  15997. return new _universal["default"](opts);
  15998. };
  15999. constructors.universal = universal;
  16000. return constructors;
  16001. }
  16002. var guards = {};
  16003. var hasRequiredGuards;
  16004. function requireGuards () {
  16005. if (hasRequiredGuards) return guards;
  16006. hasRequiredGuards = 1;
  16007. guards.__esModule = true;
  16008. guards.isComment = guards.isCombinator = guards.isClassName = guards.isAttribute = void 0;
  16009. guards.isContainer = isContainer;
  16010. guards.isIdentifier = void 0;
  16011. guards.isNamespace = isNamespace;
  16012. guards.isNesting = void 0;
  16013. guards.isNode = isNode;
  16014. guards.isPseudo = void 0;
  16015. guards.isPseudoClass = isPseudoClass;
  16016. guards.isPseudoElement = isPseudoElement;
  16017. guards.isUniversal = guards.isTag = guards.isString = guards.isSelector = guards.isRoot = void 0;
  16018. var _types = /*@__PURE__*/ requireTypes();
  16019. var _IS_TYPE;
  16020. 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);
  16021. function isNode(node) {
  16022. return typeof node === "object" && IS_TYPE[node.type];
  16023. }
  16024. function isNodeType(type, node) {
  16025. return isNode(node) && node.type === type;
  16026. }
  16027. var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  16028. guards.isAttribute = isAttribute;
  16029. var isClassName = isNodeType.bind(null, _types.CLASS);
  16030. guards.isClassName = isClassName;
  16031. var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  16032. guards.isCombinator = isCombinator;
  16033. var isComment = isNodeType.bind(null, _types.COMMENT);
  16034. guards.isComment = isComment;
  16035. var isIdentifier = isNodeType.bind(null, _types.ID);
  16036. guards.isIdentifier = isIdentifier;
  16037. var isNesting = isNodeType.bind(null, _types.NESTING);
  16038. guards.isNesting = isNesting;
  16039. var isPseudo = isNodeType.bind(null, _types.PSEUDO);
  16040. guards.isPseudo = isPseudo;
  16041. var isRoot = isNodeType.bind(null, _types.ROOT);
  16042. guards.isRoot = isRoot;
  16043. var isSelector = isNodeType.bind(null, _types.SELECTOR);
  16044. guards.isSelector = isSelector;
  16045. var isString = isNodeType.bind(null, _types.STRING);
  16046. guards.isString = isString;
  16047. var isTag = isNodeType.bind(null, _types.TAG);
  16048. guards.isTag = isTag;
  16049. var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  16050. guards.isUniversal = isUniversal;
  16051. function isPseudoElement(node) {
  16052. 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");
  16053. }
  16054. function isPseudoClass(node) {
  16055. return isPseudo(node) && !isPseudoElement(node);
  16056. }
  16057. function isContainer(node) {
  16058. return !!(isNode(node) && node.walk);
  16059. }
  16060. function isNamespace(node) {
  16061. return isAttribute(node) || isTag(node);
  16062. }
  16063. return guards;
  16064. }
  16065. var hasRequiredSelectors;
  16066. function requireSelectors () {
  16067. if (hasRequiredSelectors) return selectors;
  16068. hasRequiredSelectors = 1;
  16069. (function (exports$1) {
  16070. exports$1.__esModule = true;
  16071. var _types = /*@__PURE__*/ requireTypes();
  16072. Object.keys(_types).forEach(function (key) {
  16073. if (key === "default" || key === "__esModule") return;
  16074. if (key in exports$1 && exports$1[key] === _types[key]) return;
  16075. exports$1[key] = _types[key];
  16076. });
  16077. var _constructors = /*@__PURE__*/ requireConstructors();
  16078. Object.keys(_constructors).forEach(function (key) {
  16079. if (key === "default" || key === "__esModule") return;
  16080. if (key in exports$1 && exports$1[key] === _constructors[key]) return;
  16081. exports$1[key] = _constructors[key];
  16082. });
  16083. var _guards = /*@__PURE__*/ requireGuards();
  16084. Object.keys(_guards).forEach(function (key) {
  16085. if (key === "default" || key === "__esModule") return;
  16086. if (key in exports$1 && exports$1[key] === _guards[key]) return;
  16087. exports$1[key] = _guards[key];
  16088. });
  16089. } (selectors));
  16090. return selectors;
  16091. }
  16092. var hasRequiredDist;
  16093. function requireDist () {
  16094. if (hasRequiredDist) return dist.exports;
  16095. hasRequiredDist = 1;
  16096. (function (module, exports$1) {
  16097. exports$1.__esModule = true;
  16098. exports$1["default"] = void 0;
  16099. var _processor = _interopRequireDefault(/*@__PURE__*/ requireProcessor());
  16100. var selectors = _interopRequireWildcard(/*@__PURE__*/ requireSelectors());
  16101. 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); }
  16102. 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; }
  16103. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  16104. var parser = function parser(processor) {
  16105. return new _processor["default"](processor);
  16106. };
  16107. Object.assign(parser, selectors);
  16108. delete parser.__esModule;
  16109. var _default = parser;
  16110. exports$1["default"] = _default;
  16111. module.exports = exports$1.default;
  16112. } (dist, dist.exports));
  16113. return dist.exports;
  16114. }
  16115. var parse;
  16116. var hasRequiredParse;
  16117. function requireParse () {
  16118. if (hasRequiredParse) return parse;
  16119. hasRequiredParse = 1;
  16120. var openParentheses = "(".charCodeAt(0);
  16121. var closeParentheses = ")".charCodeAt(0);
  16122. var singleQuote = "'".charCodeAt(0);
  16123. var doubleQuote = '"'.charCodeAt(0);
  16124. var backslash = "\\".charCodeAt(0);
  16125. var slash = "/".charCodeAt(0);
  16126. var comma = ",".charCodeAt(0);
  16127. var colon = ":".charCodeAt(0);
  16128. var star = "*".charCodeAt(0);
  16129. var uLower = "u".charCodeAt(0);
  16130. var uUpper = "U".charCodeAt(0);
  16131. var plus = "+".charCodeAt(0);
  16132. var isUnicodeRange = /^[a-f0-9?-]+$/i;
  16133. parse = function(input) {
  16134. var tokens = [];
  16135. var value = input;
  16136. var next,
  16137. quote,
  16138. prev,
  16139. token,
  16140. escape,
  16141. escapePos,
  16142. whitespacePos,
  16143. parenthesesOpenPos;
  16144. var pos = 0;
  16145. var code = value.charCodeAt(pos);
  16146. var max = value.length;
  16147. var stack = [{ nodes: tokens }];
  16148. var balanced = 0;
  16149. var parent;
  16150. var name = "";
  16151. var before = "";
  16152. var after = "";
  16153. while (pos < max) {
  16154. // Whitespaces
  16155. if (code <= 32) {
  16156. next = pos;
  16157. do {
  16158. next += 1;
  16159. code = value.charCodeAt(next);
  16160. } while (code <= 32);
  16161. token = value.slice(pos, next);
  16162. prev = tokens[tokens.length - 1];
  16163. if (code === closeParentheses && balanced) {
  16164. after = token;
  16165. } else if (prev && prev.type === "div") {
  16166. prev.after = token;
  16167. prev.sourceEndIndex += token.length;
  16168. } else if (
  16169. code === comma ||
  16170. code === colon ||
  16171. (code === slash &&
  16172. value.charCodeAt(next + 1) !== star &&
  16173. (!parent ||
  16174. (parent && parent.type === "function" && parent.value !== "calc")))
  16175. ) {
  16176. before = token;
  16177. } else {
  16178. tokens.push({
  16179. type: "space",
  16180. sourceIndex: pos,
  16181. sourceEndIndex: next,
  16182. value: token
  16183. });
  16184. }
  16185. pos = next;
  16186. // Quotes
  16187. } else if (code === singleQuote || code === doubleQuote) {
  16188. next = pos;
  16189. quote = code === singleQuote ? "'" : '"';
  16190. token = {
  16191. type: "string",
  16192. sourceIndex: pos,
  16193. quote: quote
  16194. };
  16195. do {
  16196. escape = false;
  16197. next = value.indexOf(quote, next + 1);
  16198. if (~next) {
  16199. escapePos = next;
  16200. while (value.charCodeAt(escapePos - 1) === backslash) {
  16201. escapePos -= 1;
  16202. escape = !escape;
  16203. }
  16204. } else {
  16205. value += quote;
  16206. next = value.length - 1;
  16207. token.unclosed = true;
  16208. }
  16209. } while (escape);
  16210. token.value = value.slice(pos + 1, next);
  16211. token.sourceEndIndex = token.unclosed ? next : next + 1;
  16212. tokens.push(token);
  16213. pos = next + 1;
  16214. code = value.charCodeAt(pos);
  16215. // Comments
  16216. } else if (code === slash && value.charCodeAt(pos + 1) === star) {
  16217. next = value.indexOf("*/", pos);
  16218. token = {
  16219. type: "comment",
  16220. sourceIndex: pos,
  16221. sourceEndIndex: next + 2
  16222. };
  16223. if (next === -1) {
  16224. token.unclosed = true;
  16225. next = value.length;
  16226. token.sourceEndIndex = next;
  16227. }
  16228. token.value = value.slice(pos + 2, next);
  16229. tokens.push(token);
  16230. pos = next + 2;
  16231. code = value.charCodeAt(pos);
  16232. // Operation within calc
  16233. } else if (
  16234. (code === slash || code === star) &&
  16235. parent &&
  16236. parent.type === "function" &&
  16237. parent.value === "calc"
  16238. ) {
  16239. token = value[pos];
  16240. tokens.push({
  16241. type: "word",
  16242. sourceIndex: pos - before.length,
  16243. sourceEndIndex: pos + token.length,
  16244. value: token
  16245. });
  16246. pos += 1;
  16247. code = value.charCodeAt(pos);
  16248. // Dividers
  16249. } else if (code === slash || code === comma || code === colon) {
  16250. token = value[pos];
  16251. tokens.push({
  16252. type: "div",
  16253. sourceIndex: pos - before.length,
  16254. sourceEndIndex: pos + token.length,
  16255. value: token,
  16256. before: before,
  16257. after: ""
  16258. });
  16259. before = "";
  16260. pos += 1;
  16261. code = value.charCodeAt(pos);
  16262. // Open parentheses
  16263. } else if (openParentheses === code) {
  16264. // Whitespaces after open parentheses
  16265. next = pos;
  16266. do {
  16267. next += 1;
  16268. code = value.charCodeAt(next);
  16269. } while (code <= 32);
  16270. parenthesesOpenPos = pos;
  16271. token = {
  16272. type: "function",
  16273. sourceIndex: pos - name.length,
  16274. value: name,
  16275. before: value.slice(parenthesesOpenPos + 1, next)
  16276. };
  16277. pos = next;
  16278. if (name === "url" && code !== singleQuote && code !== doubleQuote) {
  16279. next -= 1;
  16280. do {
  16281. escape = false;
  16282. next = value.indexOf(")", next + 1);
  16283. if (~next) {
  16284. escapePos = next;
  16285. while (value.charCodeAt(escapePos - 1) === backslash) {
  16286. escapePos -= 1;
  16287. escape = !escape;
  16288. }
  16289. } else {
  16290. value += ")";
  16291. next = value.length - 1;
  16292. token.unclosed = true;
  16293. }
  16294. } while (escape);
  16295. // Whitespaces before closed
  16296. whitespacePos = next;
  16297. do {
  16298. whitespacePos -= 1;
  16299. code = value.charCodeAt(whitespacePos);
  16300. } while (code <= 32);
  16301. if (parenthesesOpenPos < whitespacePos) {
  16302. if (pos !== whitespacePos + 1) {
  16303. token.nodes = [
  16304. {
  16305. type: "word",
  16306. sourceIndex: pos,
  16307. sourceEndIndex: whitespacePos + 1,
  16308. value: value.slice(pos, whitespacePos + 1)
  16309. }
  16310. ];
  16311. } else {
  16312. token.nodes = [];
  16313. }
  16314. if (token.unclosed && whitespacePos + 1 !== next) {
  16315. token.after = "";
  16316. token.nodes.push({
  16317. type: "space",
  16318. sourceIndex: whitespacePos + 1,
  16319. sourceEndIndex: next,
  16320. value: value.slice(whitespacePos + 1, next)
  16321. });
  16322. } else {
  16323. token.after = value.slice(whitespacePos + 1, next);
  16324. token.sourceEndIndex = next;
  16325. }
  16326. } else {
  16327. token.after = "";
  16328. token.nodes = [];
  16329. }
  16330. pos = next + 1;
  16331. token.sourceEndIndex = token.unclosed ? next : pos;
  16332. code = value.charCodeAt(pos);
  16333. tokens.push(token);
  16334. } else {
  16335. balanced += 1;
  16336. token.after = "";
  16337. token.sourceEndIndex = pos + 1;
  16338. tokens.push(token);
  16339. stack.push(token);
  16340. tokens = token.nodes = [];
  16341. parent = token;
  16342. }
  16343. name = "";
  16344. // Close parentheses
  16345. } else if (closeParentheses === code && balanced) {
  16346. pos += 1;
  16347. code = value.charCodeAt(pos);
  16348. parent.after = after;
  16349. parent.sourceEndIndex += after.length;
  16350. after = "";
  16351. balanced -= 1;
  16352. stack[stack.length - 1].sourceEndIndex = pos;
  16353. stack.pop();
  16354. parent = stack[balanced];
  16355. tokens = parent.nodes;
  16356. // Words
  16357. } else {
  16358. next = pos;
  16359. do {
  16360. if (code === backslash) {
  16361. next += 1;
  16362. }
  16363. next += 1;
  16364. code = value.charCodeAt(next);
  16365. } while (
  16366. next < max &&
  16367. !(
  16368. code <= 32 ||
  16369. code === singleQuote ||
  16370. code === doubleQuote ||
  16371. code === comma ||
  16372. code === colon ||
  16373. code === slash ||
  16374. code === openParentheses ||
  16375. (code === star &&
  16376. parent &&
  16377. parent.type === "function" &&
  16378. parent.value === "calc") ||
  16379. (code === slash &&
  16380. parent.type === "function" &&
  16381. parent.value === "calc") ||
  16382. (code === closeParentheses && balanced)
  16383. )
  16384. );
  16385. token = value.slice(pos, next);
  16386. if (openParentheses === code) {
  16387. name = token;
  16388. } else if (
  16389. (uLower === token.charCodeAt(0) || uUpper === token.charCodeAt(0)) &&
  16390. plus === token.charCodeAt(1) &&
  16391. isUnicodeRange.test(token.slice(2))
  16392. ) {
  16393. tokens.push({
  16394. type: "unicode-range",
  16395. sourceIndex: pos,
  16396. sourceEndIndex: next,
  16397. value: token
  16398. });
  16399. } else {
  16400. tokens.push({
  16401. type: "word",
  16402. sourceIndex: pos,
  16403. sourceEndIndex: next,
  16404. value: token
  16405. });
  16406. }
  16407. pos = next;
  16408. }
  16409. }
  16410. for (pos = stack.length - 1; pos; pos -= 1) {
  16411. stack[pos].unclosed = true;
  16412. stack[pos].sourceEndIndex = value.length;
  16413. }
  16414. return stack[0].nodes;
  16415. };
  16416. return parse;
  16417. }
  16418. var walk$1;
  16419. var hasRequiredWalk;
  16420. function requireWalk () {
  16421. if (hasRequiredWalk) return walk$1;
  16422. hasRequiredWalk = 1;
  16423. walk$1 = function walk(nodes, cb, bubble) {
  16424. var i, max, node, result;
  16425. for (i = 0, max = nodes.length; i < max; i += 1) {
  16426. node = nodes[i];
  16427. if (!bubble) {
  16428. result = cb(node, i, nodes);
  16429. }
  16430. if (
  16431. result !== false &&
  16432. node.type === "function" &&
  16433. Array.isArray(node.nodes)
  16434. ) {
  16435. walk(node.nodes, cb, bubble);
  16436. }
  16437. if (bubble) {
  16438. cb(node, i, nodes);
  16439. }
  16440. }
  16441. };
  16442. return walk$1;
  16443. }
  16444. var stringify_1;
  16445. var hasRequiredStringify;
  16446. function requireStringify () {
  16447. if (hasRequiredStringify) return stringify_1;
  16448. hasRequiredStringify = 1;
  16449. function stringifyNode(node, custom) {
  16450. var type = node.type;
  16451. var value = node.value;
  16452. var buf;
  16453. var customResult;
  16454. if (custom && (customResult = custom(node)) !== undefined) {
  16455. return customResult;
  16456. } else if (type === "word" || type === "space") {
  16457. return value;
  16458. } else if (type === "string") {
  16459. buf = node.quote || "";
  16460. return buf + value + (node.unclosed ? "" : buf);
  16461. } else if (type === "comment") {
  16462. return "/*" + value + (node.unclosed ? "" : "*/");
  16463. } else if (type === "div") {
  16464. return (node.before || "") + value + (node.after || "");
  16465. } else if (Array.isArray(node.nodes)) {
  16466. buf = stringify(node.nodes, custom);
  16467. if (type !== "function") {
  16468. return buf;
  16469. }
  16470. return (
  16471. value +
  16472. "(" +
  16473. (node.before || "") +
  16474. buf +
  16475. (node.after || "") +
  16476. (node.unclosed ? "" : ")")
  16477. );
  16478. }
  16479. return value;
  16480. }
  16481. function stringify(nodes, custom) {
  16482. var result, i;
  16483. if (Array.isArray(nodes)) {
  16484. result = "";
  16485. for (i = nodes.length - 1; ~i; i -= 1) {
  16486. result = stringifyNode(nodes[i], custom) + result;
  16487. }
  16488. return result;
  16489. }
  16490. return stringifyNode(nodes, custom);
  16491. }
  16492. stringify_1 = stringify;
  16493. return stringify_1;
  16494. }
  16495. var unit;
  16496. var hasRequiredUnit;
  16497. function requireUnit () {
  16498. if (hasRequiredUnit) return unit;
  16499. hasRequiredUnit = 1;
  16500. var minus = "-".charCodeAt(0);
  16501. var plus = "+".charCodeAt(0);
  16502. var dot = ".".charCodeAt(0);
  16503. var exp = "e".charCodeAt(0);
  16504. var EXP = "E".charCodeAt(0);
  16505. // Check if three code points would start a number
  16506. // https://www.w3.org/TR/css-syntax-3/#starts-with-a-number
  16507. function likeNumber(value) {
  16508. var code = value.charCodeAt(0);
  16509. var nextCode;
  16510. if (code === plus || code === minus) {
  16511. nextCode = value.charCodeAt(1);
  16512. if (nextCode >= 48 && nextCode <= 57) {
  16513. return true;
  16514. }
  16515. var nextNextCode = value.charCodeAt(2);
  16516. if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) {
  16517. return true;
  16518. }
  16519. return false;
  16520. }
  16521. if (code === dot) {
  16522. nextCode = value.charCodeAt(1);
  16523. if (nextCode >= 48 && nextCode <= 57) {
  16524. return true;
  16525. }
  16526. return false;
  16527. }
  16528. if (code >= 48 && code <= 57) {
  16529. return true;
  16530. }
  16531. return false;
  16532. }
  16533. // Consume a number
  16534. // https://www.w3.org/TR/css-syntax-3/#consume-number
  16535. unit = function(value) {
  16536. var pos = 0;
  16537. var length = value.length;
  16538. var code;
  16539. var nextCode;
  16540. var nextNextCode;
  16541. if (length === 0 || !likeNumber(value)) {
  16542. return false;
  16543. }
  16544. code = value.charCodeAt(pos);
  16545. if (code === plus || code === minus) {
  16546. pos++;
  16547. }
  16548. while (pos < length) {
  16549. code = value.charCodeAt(pos);
  16550. if (code < 48 || code > 57) {
  16551. break;
  16552. }
  16553. pos += 1;
  16554. }
  16555. code = value.charCodeAt(pos);
  16556. nextCode = value.charCodeAt(pos + 1);
  16557. if (code === dot && nextCode >= 48 && nextCode <= 57) {
  16558. pos += 2;
  16559. while (pos < length) {
  16560. code = value.charCodeAt(pos);
  16561. if (code < 48 || code > 57) {
  16562. break;
  16563. }
  16564. pos += 1;
  16565. }
  16566. }
  16567. code = value.charCodeAt(pos);
  16568. nextCode = value.charCodeAt(pos + 1);
  16569. nextNextCode = value.charCodeAt(pos + 2);
  16570. if (
  16571. (code === exp || code === EXP) &&
  16572. ((nextCode >= 48 && nextCode <= 57) ||
  16573. ((nextCode === plus || nextCode === minus) &&
  16574. nextNextCode >= 48 &&
  16575. nextNextCode <= 57))
  16576. ) {
  16577. pos += nextCode === plus || nextCode === minus ? 3 : 2;
  16578. while (pos < length) {
  16579. code = value.charCodeAt(pos);
  16580. if (code < 48 || code > 57) {
  16581. break;
  16582. }
  16583. pos += 1;
  16584. }
  16585. }
  16586. return {
  16587. number: value.slice(0, pos),
  16588. unit: value.slice(pos)
  16589. };
  16590. };
  16591. return unit;
  16592. }
  16593. var lib;
  16594. var hasRequiredLib;
  16595. function requireLib () {
  16596. if (hasRequiredLib) return lib;
  16597. hasRequiredLib = 1;
  16598. var parse = /*@__PURE__*/ requireParse();
  16599. var walk = /*@__PURE__*/ requireWalk();
  16600. var stringify = /*@__PURE__*/ requireStringify();
  16601. function ValueParser(value) {
  16602. if (this instanceof ValueParser) {
  16603. this.nodes = parse(value);
  16604. return this;
  16605. }
  16606. return new ValueParser(value);
  16607. }
  16608. ValueParser.prototype.toString = function() {
  16609. return Array.isArray(this.nodes) ? stringify(this.nodes) : "";
  16610. };
  16611. ValueParser.prototype.walk = function(cb, bubble) {
  16612. walk(this.nodes, cb, bubble);
  16613. return this;
  16614. };
  16615. ValueParser.unit = /*@__PURE__*/ requireUnit();
  16616. ValueParser.walk = walk;
  16617. ValueParser.stringify = stringify;
  16618. lib = ValueParser;
  16619. return lib;
  16620. }
  16621. var hasRequiredSrc$2;
  16622. function requireSrc$2 () {
  16623. if (hasRequiredSrc$2) return src$2.exports;
  16624. hasRequiredSrc$2 = 1;
  16625. const selectorParser = /*@__PURE__*/ requireDist();
  16626. const valueParser = /*@__PURE__*/ requireLib();
  16627. const { extractICSS } = /*@__PURE__*/ requireSrc$4();
  16628. const isSpacing = (node) => node.type === "combinator" && node.value === " ";
  16629. function normalizeNodeArray(nodes) {
  16630. const array = [];
  16631. nodes.forEach((x) => {
  16632. if (Array.isArray(x)) {
  16633. normalizeNodeArray(x).forEach((item) => {
  16634. array.push(item);
  16635. });
  16636. } else if (x) {
  16637. array.push(x);
  16638. }
  16639. });
  16640. if (array.length > 0 && isSpacing(array[array.length - 1])) {
  16641. array.pop();
  16642. }
  16643. return array;
  16644. }
  16645. function localizeNode(rule, mode, localAliasMap) {
  16646. const transform = (node, context) => {
  16647. if (context.ignoreNextSpacing && !isSpacing(node)) {
  16648. throw new Error("Missing whitespace after " + context.ignoreNextSpacing);
  16649. }
  16650. if (context.enforceNoSpacing && isSpacing(node)) {
  16651. throw new Error("Missing whitespace before " + context.enforceNoSpacing);
  16652. }
  16653. let newNodes;
  16654. switch (node.type) {
  16655. case "root": {
  16656. let resultingGlobal;
  16657. context.hasPureGlobals = false;
  16658. newNodes = node.nodes.map((n) => {
  16659. const nContext = {
  16660. global: context.global,
  16661. lastWasSpacing: true,
  16662. hasLocals: false,
  16663. explicit: false,
  16664. };
  16665. n = transform(n, nContext);
  16666. if (typeof resultingGlobal === "undefined") {
  16667. resultingGlobal = nContext.global;
  16668. } else if (resultingGlobal !== nContext.global) {
  16669. throw new Error(
  16670. 'Inconsistent rule global/local result in rule "' +
  16671. node +
  16672. '" (multiple selectors must result in the same mode for the rule)'
  16673. );
  16674. }
  16675. if (!nContext.hasLocals) {
  16676. context.hasPureGlobals = true;
  16677. }
  16678. return n;
  16679. });
  16680. context.global = resultingGlobal;
  16681. node.nodes = normalizeNodeArray(newNodes);
  16682. break;
  16683. }
  16684. case "selector": {
  16685. newNodes = node.map((childNode) => transform(childNode, context));
  16686. node = node.clone();
  16687. node.nodes = normalizeNodeArray(newNodes);
  16688. break;
  16689. }
  16690. case "combinator": {
  16691. if (isSpacing(node)) {
  16692. if (context.ignoreNextSpacing) {
  16693. context.ignoreNextSpacing = false;
  16694. context.lastWasSpacing = false;
  16695. context.enforceNoSpacing = false;
  16696. return null;
  16697. }
  16698. context.lastWasSpacing = true;
  16699. return node;
  16700. }
  16701. break;
  16702. }
  16703. case "pseudo": {
  16704. let childContext;
  16705. const isNested = !!node.length;
  16706. const isScoped = node.value === ":local" || node.value === ":global";
  16707. const isImportExport =
  16708. node.value === ":import" || node.value === ":export";
  16709. if (isImportExport) {
  16710. context.hasLocals = true;
  16711. // :local(.foo)
  16712. } else if (isNested) {
  16713. if (isScoped) {
  16714. if (node.nodes.length === 0) {
  16715. throw new Error(`${node.value}() can't be empty`);
  16716. }
  16717. if (context.inside) {
  16718. throw new Error(
  16719. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  16720. );
  16721. }
  16722. childContext = {
  16723. global: node.value === ":global",
  16724. inside: node.value,
  16725. hasLocals: false,
  16726. explicit: true,
  16727. };
  16728. newNodes = node
  16729. .map((childNode) => transform(childNode, childContext))
  16730. .reduce((acc, next) => acc.concat(next.nodes), []);
  16731. if (newNodes.length) {
  16732. const { before, after } = node.spaces;
  16733. const first = newNodes[0];
  16734. const last = newNodes[newNodes.length - 1];
  16735. first.spaces = { before, after: first.spaces.after };
  16736. last.spaces = { before: last.spaces.before, after };
  16737. }
  16738. node = newNodes;
  16739. break;
  16740. } else {
  16741. childContext = {
  16742. global: context.global,
  16743. inside: context.inside,
  16744. lastWasSpacing: true,
  16745. hasLocals: false,
  16746. explicit: context.explicit,
  16747. };
  16748. newNodes = node.map((childNode) => {
  16749. const newContext = {
  16750. ...childContext,
  16751. enforceNoSpacing: false,
  16752. };
  16753. const result = transform(childNode, newContext);
  16754. childContext.global = newContext.global;
  16755. childContext.hasLocals = newContext.hasLocals;
  16756. return result;
  16757. });
  16758. node = node.clone();
  16759. node.nodes = normalizeNodeArray(newNodes);
  16760. if (childContext.hasLocals) {
  16761. context.hasLocals = true;
  16762. }
  16763. }
  16764. break;
  16765. //:local .foo .bar
  16766. } else if (isScoped) {
  16767. if (context.inside) {
  16768. throw new Error(
  16769. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  16770. );
  16771. }
  16772. const addBackSpacing = !!node.spaces.before;
  16773. context.ignoreNextSpacing = context.lastWasSpacing
  16774. ? node.value
  16775. : false;
  16776. context.enforceNoSpacing = context.lastWasSpacing
  16777. ? false
  16778. : node.value;
  16779. context.global = node.value === ":global";
  16780. context.explicit = true;
  16781. // because this node has spacing that is lost when we remove it
  16782. // we make up for it by adding an extra combinator in since adding
  16783. // spacing on the parent selector doesn't work
  16784. return addBackSpacing
  16785. ? selectorParser.combinator({ value: " " })
  16786. : null;
  16787. }
  16788. break;
  16789. }
  16790. case "id":
  16791. case "class": {
  16792. if (!node.value) {
  16793. throw new Error("Invalid class or id selector syntax");
  16794. }
  16795. if (context.global) {
  16796. break;
  16797. }
  16798. const isImportedValue = localAliasMap.has(node.value);
  16799. const isImportedWithExplicitScope = isImportedValue && context.explicit;
  16800. if (!isImportedValue || isImportedWithExplicitScope) {
  16801. const innerNode = node.clone();
  16802. innerNode.spaces = { before: "", after: "" };
  16803. node = selectorParser.pseudo({
  16804. value: ":local",
  16805. nodes: [innerNode],
  16806. spaces: node.spaces,
  16807. });
  16808. context.hasLocals = true;
  16809. }
  16810. break;
  16811. }
  16812. case "nesting": {
  16813. if (node.value === "&") {
  16814. context.hasLocals = true;
  16815. }
  16816. }
  16817. }
  16818. context.lastWasSpacing = false;
  16819. context.ignoreNextSpacing = false;
  16820. context.enforceNoSpacing = false;
  16821. return node;
  16822. };
  16823. const rootContext = {
  16824. global: mode === "global",
  16825. hasPureGlobals: false,
  16826. };
  16827. rootContext.selector = selectorParser((root) => {
  16828. transform(root, rootContext);
  16829. }).processSync(rule, { updateSelector: false, lossless: true });
  16830. return rootContext;
  16831. }
  16832. function localizeDeclNode(node, context) {
  16833. switch (node.type) {
  16834. case "word":
  16835. if (context.localizeNextItem) {
  16836. if (!context.localAliasMap.has(node.value)) {
  16837. node.value = ":local(" + node.value + ")";
  16838. context.localizeNextItem = false;
  16839. }
  16840. }
  16841. break;
  16842. case "function":
  16843. if (
  16844. context.options &&
  16845. context.options.rewriteUrl &&
  16846. node.value.toLowerCase() === "url"
  16847. ) {
  16848. node.nodes.map((nestedNode) => {
  16849. if (nestedNode.type !== "string" && nestedNode.type !== "word") {
  16850. return;
  16851. }
  16852. let newUrl = context.options.rewriteUrl(
  16853. context.global,
  16854. nestedNode.value
  16855. );
  16856. switch (nestedNode.type) {
  16857. case "string":
  16858. if (nestedNode.quote === "'") {
  16859. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/'/g, "\\'");
  16860. }
  16861. if (nestedNode.quote === '"') {
  16862. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/"/g, '\\"');
  16863. }
  16864. break;
  16865. case "word":
  16866. newUrl = newUrl.replace(/("|'|\)|\\)/g, "\\$1");
  16867. break;
  16868. }
  16869. nestedNode.value = newUrl;
  16870. });
  16871. }
  16872. break;
  16873. }
  16874. return node;
  16875. }
  16876. // `none` is special value, other is global values
  16877. const specialKeywords = [
  16878. "none",
  16879. "inherit",
  16880. "initial",
  16881. "revert",
  16882. "revert-layer",
  16883. "unset",
  16884. ];
  16885. function localizeDeclarationValues(localize, declaration, context) {
  16886. const valueNodes = valueParser(declaration.value);
  16887. valueNodes.walk((node, index, nodes) => {
  16888. if (
  16889. node.type === "function" &&
  16890. (node.value.toLowerCase() === "var" || node.value.toLowerCase() === "env")
  16891. ) {
  16892. return false;
  16893. }
  16894. if (
  16895. node.type === "word" &&
  16896. specialKeywords.includes(node.value.toLowerCase())
  16897. ) {
  16898. return;
  16899. }
  16900. const subContext = {
  16901. options: context.options,
  16902. global: context.global,
  16903. localizeNextItem: localize && !context.global,
  16904. localAliasMap: context.localAliasMap,
  16905. };
  16906. nodes[index] = localizeDeclNode(node, subContext);
  16907. });
  16908. declaration.value = valueNodes.toString();
  16909. }
  16910. function localizeDeclaration(declaration, context) {
  16911. const isAnimation = /animation$/i.test(declaration.prop);
  16912. if (isAnimation) {
  16913. // letter
  16914. // An uppercase letter or a lowercase letter.
  16915. //
  16916. // ident-start code point
  16917. // A letter, a non-ASCII code point, or U+005F LOW LINE (_).
  16918. //
  16919. // ident code point
  16920. // An ident-start code point, a digit, or U+002D HYPHEN-MINUS (-).
  16921. // We don't validate `hex digits`, because we don't need it, it is work of linters.
  16922. const validIdent =
  16923. /^-?([a-z\u0080-\uFFFF_]|(\\[^\r\n\f])|-(?![0-9]))((\\[^\r\n\f])|[a-z\u0080-\uFFFF_0-9-])*$/i;
  16924. /*
  16925. The spec defines some keywords that you can use to describe properties such as the timing
  16926. function. These are still valid animation names, so as long as there is a property that accepts
  16927. a keyword, it is given priority. Only when all the properties that can take a keyword are
  16928. exhausted can the animation name be set to the keyword. I.e.
  16929. animation: infinite infinite;
  16930. The animation will repeat an infinite number of times from the first argument, and will have an
  16931. animation name of infinite from the second.
  16932. */
  16933. const animationKeywords = {
  16934. // animation-direction
  16935. $normal: 1,
  16936. $reverse: 1,
  16937. $alternate: 1,
  16938. "$alternate-reverse": 1,
  16939. // animation-fill-mode
  16940. $forwards: 1,
  16941. $backwards: 1,
  16942. $both: 1,
  16943. // animation-iteration-count
  16944. $infinite: 1,
  16945. // animation-play-state
  16946. $paused: 1,
  16947. $running: 1,
  16948. // animation-timing-function
  16949. $ease: 1,
  16950. "$ease-in": 1,
  16951. "$ease-out": 1,
  16952. "$ease-in-out": 1,
  16953. $linear: 1,
  16954. "$step-end": 1,
  16955. "$step-start": 1,
  16956. // Special
  16957. $none: Infinity, // No matter how many times you write none, it will never be an animation name
  16958. // Global values
  16959. $initial: Infinity,
  16960. $inherit: Infinity,
  16961. $unset: Infinity,
  16962. $revert: Infinity,
  16963. "$revert-layer": Infinity,
  16964. };
  16965. let parsedAnimationKeywords = {};
  16966. const valueNodes = valueParser(declaration.value).walk((node) => {
  16967. // If div-token appeared (represents as comma ','), a possibility of an animation-keywords should be reflesh.
  16968. if (node.type === "div") {
  16969. parsedAnimationKeywords = {};
  16970. return;
  16971. }
  16972. // Do not handle nested functions
  16973. else if (node.type === "function") {
  16974. return false;
  16975. }
  16976. // Ignore all except word
  16977. else if (node.type !== "word") {
  16978. return;
  16979. }
  16980. const value = node.type === "word" ? node.value.toLowerCase() : null;
  16981. let shouldParseAnimationName = false;
  16982. if (value && validIdent.test(value)) {
  16983. if ("$" + value in animationKeywords) {
  16984. parsedAnimationKeywords["$" + value] =
  16985. "$" + value in parsedAnimationKeywords
  16986. ? parsedAnimationKeywords["$" + value] + 1
  16987. : 0;
  16988. shouldParseAnimationName =
  16989. parsedAnimationKeywords["$" + value] >=
  16990. animationKeywords["$" + value];
  16991. } else {
  16992. shouldParseAnimationName = true;
  16993. }
  16994. }
  16995. const subContext = {
  16996. options: context.options,
  16997. global: context.global,
  16998. localizeNextItem: shouldParseAnimationName && !context.global,
  16999. localAliasMap: context.localAliasMap,
  17000. };
  17001. return localizeDeclNode(node, subContext);
  17002. });
  17003. declaration.value = valueNodes.toString();
  17004. return;
  17005. }
  17006. const isAnimationName = /animation(-name)?$/i.test(declaration.prop);
  17007. if (isAnimationName) {
  17008. return localizeDeclarationValues(true, declaration, context);
  17009. }
  17010. const hasUrl = /url\(/i.test(declaration.value);
  17011. if (hasUrl) {
  17012. return localizeDeclarationValues(false, declaration, context);
  17013. }
  17014. }
  17015. src$2.exports = (options = {}) => {
  17016. if (
  17017. options &&
  17018. options.mode &&
  17019. options.mode !== "global" &&
  17020. options.mode !== "local" &&
  17021. options.mode !== "pure"
  17022. ) {
  17023. throw new Error(
  17024. 'options.mode must be either "global", "local" or "pure" (default "local")'
  17025. );
  17026. }
  17027. const pureMode = options && options.mode === "pure";
  17028. const globalMode = options && options.mode === "global";
  17029. return {
  17030. postcssPlugin: "postcss-modules-local-by-default",
  17031. prepare() {
  17032. const localAliasMap = new Map();
  17033. return {
  17034. Once(root) {
  17035. const { icssImports } = extractICSS(root, false);
  17036. Object.keys(icssImports).forEach((key) => {
  17037. Object.keys(icssImports[key]).forEach((prop) => {
  17038. localAliasMap.set(prop, icssImports[key][prop]);
  17039. });
  17040. });
  17041. root.walkAtRules((atRule) => {
  17042. if (/keyframes$/i.test(atRule.name)) {
  17043. const globalMatch = /^\s*:global\s*\((.+)\)\s*$/.exec(
  17044. atRule.params
  17045. );
  17046. const localMatch = /^\s*:local\s*\((.+)\)\s*$/.exec(
  17047. atRule.params
  17048. );
  17049. let globalKeyframes = globalMode;
  17050. if (globalMatch) {
  17051. if (pureMode) {
  17052. throw atRule.error(
  17053. "@keyframes :global(...) is not allowed in pure mode"
  17054. );
  17055. }
  17056. atRule.params = globalMatch[1];
  17057. globalKeyframes = true;
  17058. } else if (localMatch) {
  17059. atRule.params = localMatch[0];
  17060. globalKeyframes = false;
  17061. } else if (
  17062. atRule.params &&
  17063. !globalMode &&
  17064. !localAliasMap.has(atRule.params)
  17065. ) {
  17066. atRule.params = ":local(" + atRule.params + ")";
  17067. }
  17068. atRule.walkDecls((declaration) => {
  17069. localizeDeclaration(declaration, {
  17070. localAliasMap,
  17071. options: options,
  17072. global: globalKeyframes,
  17073. });
  17074. });
  17075. } else if (/scope$/i.test(atRule.name)) {
  17076. if (atRule.params) {
  17077. atRule.params = atRule.params
  17078. .split("to")
  17079. .map((item) => {
  17080. const selector = item.trim().slice(1, -1).trim();
  17081. const context = localizeNode(
  17082. selector,
  17083. options.mode,
  17084. localAliasMap
  17085. );
  17086. context.options = options;
  17087. context.localAliasMap = localAliasMap;
  17088. if (pureMode && context.hasPureGlobals) {
  17089. throw atRule.error(
  17090. 'Selector in at-rule"' +
  17091. selector +
  17092. '" is not pure ' +
  17093. "(pure selectors must contain at least one local class or id)"
  17094. );
  17095. }
  17096. return `(${context.selector})`;
  17097. })
  17098. .join(" to ");
  17099. }
  17100. atRule.nodes.forEach((declaration) => {
  17101. if (declaration.type === "decl") {
  17102. localizeDeclaration(declaration, {
  17103. localAliasMap,
  17104. options: options,
  17105. global: globalMode,
  17106. });
  17107. }
  17108. });
  17109. } else if (atRule.nodes) {
  17110. atRule.nodes.forEach((declaration) => {
  17111. if (declaration.type === "decl") {
  17112. localizeDeclaration(declaration, {
  17113. localAliasMap,
  17114. options: options,
  17115. global: globalMode,
  17116. });
  17117. }
  17118. });
  17119. }
  17120. });
  17121. root.walkRules((rule) => {
  17122. if (
  17123. rule.parent &&
  17124. rule.parent.type === "atrule" &&
  17125. /keyframes$/i.test(rule.parent.name)
  17126. ) {
  17127. // ignore keyframe rules
  17128. return;
  17129. }
  17130. const context = localizeNode(rule, options.mode, localAliasMap);
  17131. context.options = options;
  17132. context.localAliasMap = localAliasMap;
  17133. if (pureMode && context.hasPureGlobals) {
  17134. throw rule.error(
  17135. 'Selector "' +
  17136. rule.selector +
  17137. '" is not pure ' +
  17138. "(pure selectors must contain at least one local class or id)"
  17139. );
  17140. }
  17141. rule.selector = context.selector;
  17142. // Less-syntax mixins parse as rules with no nodes
  17143. if (rule.nodes) {
  17144. rule.nodes.forEach((declaration) =>
  17145. localizeDeclaration(declaration, context)
  17146. );
  17147. }
  17148. });
  17149. },
  17150. };
  17151. },
  17152. };
  17153. };
  17154. src$2.exports.postcss = true;
  17155. return src$2.exports;
  17156. }
  17157. var src$1;
  17158. var hasRequiredSrc$1;
  17159. function requireSrc$1 () {
  17160. if (hasRequiredSrc$1) return src$1;
  17161. hasRequiredSrc$1 = 1;
  17162. const selectorParser = /*@__PURE__*/ requireDist();
  17163. const hasOwnProperty = Object.prototype.hasOwnProperty;
  17164. function isNestedRule(rule) {
  17165. if (!rule.parent || rule.parent.type === "root") {
  17166. return false;
  17167. }
  17168. if (rule.parent.type === "rule") {
  17169. return true;
  17170. }
  17171. return isNestedRule(rule.parent);
  17172. }
  17173. function getSingleLocalNamesForComposes(root, rule) {
  17174. if (isNestedRule(rule)) {
  17175. throw new Error(`composition is not allowed in nested rule \n\n${rule}`);
  17176. }
  17177. return root.nodes.map((node) => {
  17178. if (node.type !== "selector" || node.nodes.length !== 1) {
  17179. throw new Error(
  17180. `composition is only allowed when selector is single :local class name not in "${root}"`
  17181. );
  17182. }
  17183. node = node.nodes[0];
  17184. if (
  17185. node.type !== "pseudo" ||
  17186. node.value !== ":local" ||
  17187. node.nodes.length !== 1
  17188. ) {
  17189. throw new Error(
  17190. 'composition is only allowed when selector is single :local class name not in "' +
  17191. root +
  17192. '", "' +
  17193. node +
  17194. '" is weird'
  17195. );
  17196. }
  17197. node = node.first;
  17198. if (node.type !== "selector" || node.length !== 1) {
  17199. throw new Error(
  17200. 'composition is only allowed when selector is single :local class name not in "' +
  17201. root +
  17202. '", "' +
  17203. node +
  17204. '" is weird'
  17205. );
  17206. }
  17207. node = node.first;
  17208. if (node.type !== "class") {
  17209. // 'id' is not possible, because you can't compose ids
  17210. throw new Error(
  17211. 'composition is only allowed when selector is single :local class name not in "' +
  17212. root +
  17213. '", "' +
  17214. node +
  17215. '" is weird'
  17216. );
  17217. }
  17218. return node.value;
  17219. });
  17220. }
  17221. const whitespace = "[\\x20\\t\\r\\n\\f]";
  17222. const unescapeRegExp = new RegExp(
  17223. "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)",
  17224. "ig"
  17225. );
  17226. function unescape(str) {
  17227. return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => {
  17228. const high = "0x" + escaped - 0x10000;
  17229. // NaN means non-codepoint
  17230. // Workaround erroneous numeric interpretation of +"0x"
  17231. return high !== high || escapedWhitespace
  17232. ? escaped
  17233. : high < 0
  17234. ? // BMP codepoint
  17235. String.fromCharCode(high + 0x10000)
  17236. : // Supplemental Plane codepoint (surrogate pair)
  17237. String.fromCharCode((high >> 10) | 0xd800, (high & 0x3ff) | 0xdc00);
  17238. });
  17239. }
  17240. const plugin = (options = {}) => {
  17241. const generateScopedName =
  17242. (options && options.generateScopedName) || plugin.generateScopedName;
  17243. const generateExportEntry =
  17244. (options && options.generateExportEntry) || plugin.generateExportEntry;
  17245. const exportGlobals = options && options.exportGlobals;
  17246. return {
  17247. postcssPlugin: "postcss-modules-scope",
  17248. Once(root, { rule }) {
  17249. const exports$1 = Object.create(null);
  17250. function exportScopedName(name, rawName, node) {
  17251. const scopedName = generateScopedName(
  17252. rawName ? rawName : name,
  17253. root.source.input.from,
  17254. root.source.input.css,
  17255. node
  17256. );
  17257. const exportEntry = generateExportEntry(
  17258. rawName ? rawName : name,
  17259. scopedName,
  17260. root.source.input.from,
  17261. root.source.input.css,
  17262. node
  17263. );
  17264. const { key, value } = exportEntry;
  17265. exports$1[key] = exports$1[key] || [];
  17266. if (exports$1[key].indexOf(value) < 0) {
  17267. exports$1[key].push(value);
  17268. }
  17269. return scopedName;
  17270. }
  17271. function localizeNode(node) {
  17272. switch (node.type) {
  17273. case "selector":
  17274. node.nodes = node.map((item) => localizeNode(item));
  17275. return node;
  17276. case "class":
  17277. return selectorParser.className({
  17278. value: exportScopedName(
  17279. node.value,
  17280. node.raws && node.raws.value ? node.raws.value : null,
  17281. node
  17282. ),
  17283. });
  17284. case "id": {
  17285. return selectorParser.id({
  17286. value: exportScopedName(
  17287. node.value,
  17288. node.raws && node.raws.value ? node.raws.value : null,
  17289. node
  17290. ),
  17291. });
  17292. }
  17293. case "attribute": {
  17294. if (node.attribute === "class" && node.operator === "=") {
  17295. return selectorParser.attribute({
  17296. attribute: node.attribute,
  17297. operator: node.operator,
  17298. quoteMark: "'",
  17299. value: exportScopedName(node.value, null, null),
  17300. });
  17301. }
  17302. }
  17303. }
  17304. throw new Error(
  17305. `${node.type} ("${node}") is not allowed in a :local block`
  17306. );
  17307. }
  17308. function traverseNode(node) {
  17309. switch (node.type) {
  17310. case "pseudo":
  17311. if (node.value === ":local") {
  17312. if (node.nodes.length !== 1) {
  17313. throw new Error('Unexpected comma (",") in :local block');
  17314. }
  17315. const selector = localizeNode(node.first);
  17316. // move the spaces that were around the pseudo selector to the first
  17317. // non-container node
  17318. selector.first.spaces = node.spaces;
  17319. const nextNode = node.next();
  17320. if (
  17321. nextNode &&
  17322. nextNode.type === "combinator" &&
  17323. nextNode.value === " " &&
  17324. /\\[A-F0-9]{1,6}$/.test(selector.last.value)
  17325. ) {
  17326. selector.last.spaces.after = " ";
  17327. }
  17328. node.replaceWith(selector);
  17329. return;
  17330. }
  17331. /* falls through */
  17332. case "root":
  17333. case "selector": {
  17334. node.each((item) => traverseNode(item));
  17335. break;
  17336. }
  17337. case "id":
  17338. case "class":
  17339. if (exportGlobals) {
  17340. exports$1[node.value] = [node.value];
  17341. }
  17342. break;
  17343. }
  17344. return node;
  17345. }
  17346. // Find any :import and remember imported names
  17347. const importedNames = {};
  17348. root.walkRules(/^:import\(.+\)$/, (rule) => {
  17349. rule.walkDecls((decl) => {
  17350. importedNames[decl.prop] = true;
  17351. });
  17352. });
  17353. // Find any :local selectors
  17354. root.walkRules((rule) => {
  17355. let parsedSelector = selectorParser().astSync(rule);
  17356. rule.selector = traverseNode(parsedSelector.clone()).toString();
  17357. rule.walkDecls(/^(composes|compose-with)$/i, (decl) => {
  17358. const localNames = getSingleLocalNamesForComposes(
  17359. parsedSelector,
  17360. decl.parent
  17361. );
  17362. const multiple = decl.value.split(",");
  17363. multiple.forEach((value) => {
  17364. const classes = value.trim().split(/\s+/);
  17365. classes.forEach((className) => {
  17366. const global = /^global\(([^)]+)\)$/.exec(className);
  17367. if (global) {
  17368. localNames.forEach((exportedName) => {
  17369. exports$1[exportedName].push(global[1]);
  17370. });
  17371. } else if (hasOwnProperty.call(importedNames, className)) {
  17372. localNames.forEach((exportedName) => {
  17373. exports$1[exportedName].push(className);
  17374. });
  17375. } else if (hasOwnProperty.call(exports$1, className)) {
  17376. localNames.forEach((exportedName) => {
  17377. exports$1[className].forEach((item) => {
  17378. exports$1[exportedName].push(item);
  17379. });
  17380. });
  17381. } else {
  17382. throw decl.error(
  17383. `referenced class name "${className}" in ${decl.prop} not found`
  17384. );
  17385. }
  17386. });
  17387. });
  17388. decl.remove();
  17389. });
  17390. // Find any :local values
  17391. rule.walkDecls((decl) => {
  17392. if (!/:local\s*\((.+?)\)/.test(decl.value)) {
  17393. return;
  17394. }
  17395. let tokens = decl.value.split(/(,|'[^']*'|"[^"]*")/);
  17396. tokens = tokens.map((token, idx) => {
  17397. if (idx === 0 || tokens[idx - 1] === ",") {
  17398. let result = token;
  17399. const localMatch = /:local\s*\((.+?)\)/.exec(token);
  17400. if (localMatch) {
  17401. const input = localMatch.input;
  17402. const matchPattern = localMatch[0];
  17403. const matchVal = localMatch[1];
  17404. const newVal = exportScopedName(matchVal);
  17405. result = input.replace(matchPattern, newVal);
  17406. } else {
  17407. return token;
  17408. }
  17409. return result;
  17410. } else {
  17411. return token;
  17412. }
  17413. });
  17414. decl.value = tokens.join("");
  17415. });
  17416. });
  17417. // Find any :local keyframes
  17418. root.walkAtRules(/keyframes$/i, (atRule) => {
  17419. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(atRule.params);
  17420. if (!localMatch) {
  17421. return;
  17422. }
  17423. atRule.params = exportScopedName(localMatch[1]);
  17424. });
  17425. root.walkAtRules(/scope$/i, (atRule) => {
  17426. if (atRule.params) {
  17427. atRule.params = atRule.params
  17428. .split("to")
  17429. .map((item) => {
  17430. const selector = item.trim().slice(1, -1).trim();
  17431. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(selector);
  17432. if (!localMatch) {
  17433. return `(${selector})`;
  17434. }
  17435. let parsedSelector = selectorParser().astSync(selector);
  17436. return `(${traverseNode(parsedSelector).toString()})`;
  17437. })
  17438. .join(" to ");
  17439. }
  17440. });
  17441. // If we found any :locals, insert an :export rule
  17442. const exportedNames = Object.keys(exports$1);
  17443. if (exportedNames.length > 0) {
  17444. const exportRule = rule({ selector: ":export" });
  17445. exportedNames.forEach((exportedName) =>
  17446. exportRule.append({
  17447. prop: exportedName,
  17448. value: exports$1[exportedName].join(" "),
  17449. raws: { before: "\n " },
  17450. })
  17451. );
  17452. root.append(exportRule);
  17453. }
  17454. },
  17455. };
  17456. };
  17457. plugin.postcss = true;
  17458. plugin.generateScopedName = function (name, path) {
  17459. const sanitisedPath = path
  17460. .replace(/\.[^./\\]+$/, "")
  17461. .replace(/[\W_]+/g, "_")
  17462. .replace(/^_|_$/g, "");
  17463. return `_${sanitisedPath}__${name}`.trim();
  17464. };
  17465. plugin.generateExportEntry = function (name, scopedName) {
  17466. return {
  17467. key: unescape(name),
  17468. value: unescape(scopedName),
  17469. };
  17470. };
  17471. src$1 = plugin;
  17472. return src$1;
  17473. }
  17474. var stringHash;
  17475. var hasRequiredStringHash;
  17476. function requireStringHash () {
  17477. if (hasRequiredStringHash) return stringHash;
  17478. hasRequiredStringHash = 1;
  17479. function hash(str) {
  17480. var hash = 5381,
  17481. i = str.length;
  17482. while(i) {
  17483. hash = (hash * 33) ^ str.charCodeAt(--i);
  17484. }
  17485. /* JavaScript does bitwise operations (like XOR, above) on 32-bit signed
  17486. * integers. Since we want the results to be always positive, convert the
  17487. * signed int to an unsigned by doing an unsigned bitshift. */
  17488. return hash >>> 0;
  17489. }
  17490. stringHash = hash;
  17491. return stringHash;
  17492. }
  17493. var src = {exports: {}};
  17494. var hasRequiredSrc;
  17495. function requireSrc () {
  17496. if (hasRequiredSrc) return src.exports;
  17497. hasRequiredSrc = 1;
  17498. const ICSSUtils = /*@__PURE__*/ requireSrc$4();
  17499. const matchImports = /^(.+?|\([\s\S]+?\))\s+from\s+("[^"]*"|'[^']*'|[\w-]+)$/;
  17500. const matchValueDefinition = /(?:\s+|^)([\w-]+):?(.*?)$/;
  17501. const matchImport = /^([\w-]+)(?:\s+as\s+([\w-]+))?/;
  17502. src.exports = (options) => {
  17503. let importIndex = 0;
  17504. const createImportedName =
  17505. (options && options.createImportedName) ||
  17506. ((importName /*, path*/) =>
  17507. `i__const_${importName.replace(/\W/g, "_")}_${importIndex++}`);
  17508. return {
  17509. postcssPlugin: "postcss-modules-values",
  17510. prepare(result) {
  17511. const importAliases = [];
  17512. const definitions = {};
  17513. return {
  17514. Once(root, postcss) {
  17515. root.walkAtRules(/value/i, (atRule) => {
  17516. const matches = atRule.params.match(matchImports);
  17517. if (matches) {
  17518. let [, /*match*/ aliases, path] = matches;
  17519. // We can use constants for path names
  17520. if (definitions[path]) {
  17521. path = definitions[path];
  17522. }
  17523. const imports = aliases
  17524. .replace(/^\(\s*([\s\S]+)\s*\)$/, "$1")
  17525. .split(/\s*,\s*/)
  17526. .map((alias) => {
  17527. const tokens = matchImport.exec(alias);
  17528. if (tokens) {
  17529. const [, /*match*/ theirName, myName = theirName] = tokens;
  17530. const importedName = createImportedName(myName);
  17531. definitions[myName] = importedName;
  17532. return { theirName, importedName };
  17533. } else {
  17534. throw new Error(`@import statement "${alias}" is invalid!`);
  17535. }
  17536. });
  17537. importAliases.push({ path, imports });
  17538. atRule.remove();
  17539. return;
  17540. }
  17541. if (atRule.params.indexOf("@value") !== -1) {
  17542. result.warn("Invalid value definition: " + atRule.params);
  17543. }
  17544. let [, key, value] = `${atRule.params}${atRule.raws.between}`.match(
  17545. matchValueDefinition
  17546. );
  17547. const normalizedValue = value.replace(/\/\*((?!\*\/).*?)\*\//g, "");
  17548. if (normalizedValue.length === 0) {
  17549. result.warn("Invalid value definition: " + atRule.params);
  17550. atRule.remove();
  17551. return;
  17552. }
  17553. let isOnlySpace = /^\s+$/.test(normalizedValue);
  17554. if (!isOnlySpace) {
  17555. value = value.trim();
  17556. }
  17557. // Add to the definitions, knowing that values can refer to each other
  17558. definitions[key] = ICSSUtils.replaceValueSymbols(
  17559. value,
  17560. definitions
  17561. );
  17562. atRule.remove();
  17563. });
  17564. /* If we have no definitions, don't continue */
  17565. if (!Object.keys(definitions).length) {
  17566. return;
  17567. }
  17568. /* Perform replacements */
  17569. ICSSUtils.replaceSymbols(root, definitions);
  17570. /* 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 */
  17571. const exportDeclarations = Object.keys(definitions).map((key) =>
  17572. postcss.decl({
  17573. value: definitions[key],
  17574. prop: key,
  17575. raws: { before: "\n " },
  17576. })
  17577. );
  17578. /* Add export rules if any */
  17579. if (exportDeclarations.length > 0) {
  17580. const exportRule = postcss.rule({
  17581. selector: ":export",
  17582. raws: { after: "\n" },
  17583. });
  17584. exportRule.append(exportDeclarations);
  17585. root.prepend(exportRule);
  17586. }
  17587. /* Add import rules */
  17588. importAliases.reverse().forEach(({ path, imports }) => {
  17589. const importRule = postcss.rule({
  17590. selector: `:import(${path})`,
  17591. raws: { after: "\n" },
  17592. });
  17593. imports.forEach(({ theirName, importedName }) => {
  17594. importRule.append({
  17595. value: theirName,
  17596. prop: importedName,
  17597. raws: { before: "\n " },
  17598. });
  17599. });
  17600. root.prepend(importRule);
  17601. });
  17602. },
  17603. };
  17604. },
  17605. };
  17606. };
  17607. src.exports.postcss = true;
  17608. return src.exports;
  17609. }
  17610. var hasRequiredScoping;
  17611. function requireScoping () {
  17612. if (hasRequiredScoping) return scoping;
  17613. hasRequiredScoping = 1;
  17614. Object.defineProperty(scoping, "__esModule", {
  17615. value: true
  17616. });
  17617. scoping.behaviours = void 0;
  17618. scoping.getDefaultPlugins = getDefaultPlugins;
  17619. scoping.getDefaultScopeBehaviour = getDefaultScopeBehaviour;
  17620. scoping.getScopedNameGenerator = getScopedNameGenerator;
  17621. var _postcssModulesExtractImports = _interopRequireDefault(/*@__PURE__*/ requireSrc$3());
  17622. var _genericNames = _interopRequireDefault(/*@__PURE__*/ requireGenericNames());
  17623. var _postcssModulesLocalByDefault = _interopRequireDefault(/*@__PURE__*/ requireSrc$2());
  17624. var _postcssModulesScope = _interopRequireDefault(/*@__PURE__*/ requireSrc$1());
  17625. var _stringHash = _interopRequireDefault(/*@__PURE__*/ requireStringHash());
  17626. var _postcssModulesValues = _interopRequireDefault(/*@__PURE__*/ requireSrc());
  17627. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  17628. const behaviours = {
  17629. LOCAL: "local",
  17630. GLOBAL: "global"
  17631. };
  17632. scoping.behaviours = behaviours;
  17633. function getDefaultPlugins({
  17634. behaviour,
  17635. generateScopedName,
  17636. exportGlobals
  17637. }) {
  17638. const scope = (0, _postcssModulesScope.default)({
  17639. generateScopedName,
  17640. exportGlobals
  17641. });
  17642. const plugins = {
  17643. [behaviours.LOCAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  17644. mode: "local"
  17645. }), _postcssModulesExtractImports.default, scope],
  17646. [behaviours.GLOBAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  17647. mode: "global"
  17648. }), _postcssModulesExtractImports.default, scope]
  17649. };
  17650. return plugins[behaviour];
  17651. }
  17652. function isValidBehaviour(behaviour) {
  17653. return Object.keys(behaviours).map(key => behaviours[key]).indexOf(behaviour) > -1;
  17654. }
  17655. function getDefaultScopeBehaviour(scopeBehaviour) {
  17656. return scopeBehaviour && isValidBehaviour(scopeBehaviour) ? scopeBehaviour : behaviours.LOCAL;
  17657. }
  17658. function generateScopedNameDefault(name, filename, css) {
  17659. const i = css.indexOf(`.${name}`);
  17660. const lineNumber = css.substr(0, i).split(/[\r\n]/).length;
  17661. const hash = (0, _stringHash.default)(css).toString(36).substr(0, 5);
  17662. return `_${name}_${hash}_${lineNumber}`;
  17663. }
  17664. function getScopedNameGenerator(generateScopedName, hashPrefix) {
  17665. const scopedNameGenerator = generateScopedName || generateScopedNameDefault;
  17666. if (typeof scopedNameGenerator === "function") {
  17667. return scopedNameGenerator;
  17668. }
  17669. return (0, _genericNames.default)(scopedNameGenerator, {
  17670. context: process.cwd(),
  17671. hashPrefix: hashPrefix
  17672. });
  17673. }
  17674. return scoping;
  17675. }
  17676. var hasRequiredPluginFactory;
  17677. function requirePluginFactory () {
  17678. if (hasRequiredPluginFactory) return pluginFactory;
  17679. hasRequiredPluginFactory = 1;
  17680. Object.defineProperty(pluginFactory, "__esModule", {
  17681. value: true
  17682. });
  17683. pluginFactory.makePlugin = makePlugin;
  17684. var _postcss = _interopRequireDefault(require$$0$1);
  17685. var _unquote = _interopRequireDefault(/*@__PURE__*/ requireUnquote());
  17686. var _Parser = _interopRequireDefault(/*@__PURE__*/ requireParser$1());
  17687. var _saveJSON = _interopRequireDefault(/*@__PURE__*/ requireSaveJSON());
  17688. var _localsConvention = /*@__PURE__*/ requireLocalsConvention();
  17689. var _FileSystemLoader = _interopRequireDefault(/*@__PURE__*/ requireFileSystemLoader());
  17690. var _scoping = /*@__PURE__*/ requireScoping();
  17691. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  17692. const PLUGIN_NAME = "postcss-modules";
  17693. function isGlobalModule(globalModules, inputFile) {
  17694. return globalModules.some(regex => inputFile.match(regex));
  17695. }
  17696. function getDefaultPluginsList(opts, inputFile) {
  17697. const globalModulesList = opts.globalModulePaths || null;
  17698. const exportGlobals = opts.exportGlobals || false;
  17699. const defaultBehaviour = (0, _scoping.getDefaultScopeBehaviour)(opts.scopeBehaviour);
  17700. const generateScopedName = (0, _scoping.getScopedNameGenerator)(opts.generateScopedName, opts.hashPrefix);
  17701. if (globalModulesList && isGlobalModule(globalModulesList, inputFile)) {
  17702. return (0, _scoping.getDefaultPlugins)({
  17703. behaviour: _scoping.behaviours.GLOBAL,
  17704. generateScopedName,
  17705. exportGlobals
  17706. });
  17707. }
  17708. return (0, _scoping.getDefaultPlugins)({
  17709. behaviour: defaultBehaviour,
  17710. generateScopedName,
  17711. exportGlobals
  17712. });
  17713. }
  17714. function getLoader(opts, plugins) {
  17715. const root = typeof opts.root === "undefined" ? "/" : opts.root;
  17716. return typeof opts.Loader === "function" ? new opts.Loader(root, plugins, opts.resolve) : new _FileSystemLoader.default(root, plugins, opts.resolve);
  17717. }
  17718. function isOurPlugin(plugin) {
  17719. return plugin.postcssPlugin === PLUGIN_NAME;
  17720. }
  17721. function makePlugin(opts) {
  17722. return {
  17723. postcssPlugin: PLUGIN_NAME,
  17724. async OnceExit(css, {
  17725. result
  17726. }) {
  17727. const getJSON = opts.getJSON || _saveJSON.default;
  17728. const inputFile = css.source.input.file;
  17729. const pluginList = getDefaultPluginsList(opts, inputFile);
  17730. const resultPluginIndex = result.processor.plugins.findIndex(plugin => isOurPlugin(plugin));
  17731. if (resultPluginIndex === -1) {
  17732. throw new Error("Plugin missing from options.");
  17733. }
  17734. const earlierPlugins = result.processor.plugins.slice(0, resultPluginIndex);
  17735. const loaderPlugins = [...earlierPlugins, ...pluginList];
  17736. const loader = getLoader(opts, loaderPlugins);
  17737. const fetcher = async (file, relativeTo, depTrace) => {
  17738. const unquoteFile = (0, _unquote.default)(file);
  17739. return loader.fetch.call(loader, unquoteFile, relativeTo, depTrace);
  17740. };
  17741. const parser = new _Parser.default(fetcher);
  17742. await (0, _postcss.default)([...pluginList, parser.plugin()]).process(css, {
  17743. from: inputFile
  17744. });
  17745. const out = loader.finalSource;
  17746. if (out) css.prepend(out);
  17747. if (opts.localsConvention) {
  17748. const reducer = (0, _localsConvention.makeLocalsConventionReducer)(opts.localsConvention, inputFile);
  17749. parser.exportTokens = Object.entries(parser.exportTokens).reduce(reducer, {});
  17750. }
  17751. result.messages.push({
  17752. type: "export",
  17753. plugin: "postcss-modules",
  17754. exportTokens: parser.exportTokens
  17755. }); // getJSON may return a promise
  17756. return getJSON(css.source.input.file, parser.exportTokens, result.opts.to);
  17757. }
  17758. };
  17759. }
  17760. return pluginFactory;
  17761. }
  17762. var hasRequiredBuild;
  17763. function requireBuild () {
  17764. if (hasRequiredBuild) return build.exports;
  17765. hasRequiredBuild = 1;
  17766. var _fs = require$$0;
  17767. var _fs2 = /*@__PURE__*/ requireFs();
  17768. var _pluginFactory = /*@__PURE__*/ requirePluginFactory();
  17769. (0, _fs2.setFileSystem)({
  17770. readFile: _fs.readFile,
  17771. writeFile: _fs.writeFile
  17772. });
  17773. build.exports = (opts = {}) => (0, _pluginFactory.makePlugin)(opts);
  17774. build.exports.postcss = true;
  17775. return build.exports;
  17776. }
  17777. var buildExports = /*@__PURE__*/ requireBuild();
  17778. var postcssModules = /*@__PURE__*/getDefaultExportFromCjs(buildExports);
  17779. function compileStyle(options) {
  17780. return doCompileStyle({
  17781. ...options,
  17782. isAsync: false
  17783. });
  17784. }
  17785. function compileStyleAsync(options) {
  17786. return doCompileStyle({
  17787. ...options,
  17788. isAsync: true
  17789. });
  17790. }
  17791. function doCompileStyle(options) {
  17792. const {
  17793. filename,
  17794. id,
  17795. scoped = false,
  17796. trim = true,
  17797. isProd = false,
  17798. modules = false,
  17799. modulesOptions = {},
  17800. preprocessLang,
  17801. postcssOptions,
  17802. postcssPlugins
  17803. } = options;
  17804. const preprocessor = preprocessLang && processors[preprocessLang];
  17805. const preProcessedSource = preprocessor && preprocess(options, preprocessor);
  17806. const map = preProcessedSource ? preProcessedSource.map : options.inMap || options.map;
  17807. const source = preProcessedSource ? preProcessedSource.code : options.source;
  17808. const shortId = id.replace(/^data-v-/, "");
  17809. const longId = `data-v-${shortId}`;
  17810. const plugins = (postcssPlugins || []).slice();
  17811. plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
  17812. if (trim) {
  17813. plugins.push(trimPlugin());
  17814. }
  17815. if (scoped) {
  17816. plugins.push(scopedPlugin(longId));
  17817. }
  17818. let cssModules;
  17819. if (modules) {
  17820. if (!options.isAsync) {
  17821. throw new Error(
  17822. "[@vue/compiler-sfc] `modules` option can only be used with compileStyleAsync()."
  17823. );
  17824. }
  17825. plugins.push(
  17826. postcssModules({
  17827. ...modulesOptions,
  17828. getJSON: (_cssFileName, json) => {
  17829. cssModules = json;
  17830. }
  17831. })
  17832. );
  17833. }
  17834. const postCSSOptions = {
  17835. ...postcssOptions,
  17836. to: filename,
  17837. from: filename
  17838. };
  17839. if (map) {
  17840. postCSSOptions.map = {
  17841. inline: false,
  17842. annotation: false,
  17843. prev: map
  17844. };
  17845. }
  17846. let result;
  17847. let code;
  17848. let outMap;
  17849. const dependencies = new Set(
  17850. preProcessedSource ? preProcessedSource.dependencies : []
  17851. );
  17852. dependencies.delete(filename);
  17853. const errors = [];
  17854. if (preProcessedSource && preProcessedSource.errors.length) {
  17855. errors.push(...preProcessedSource.errors);
  17856. }
  17857. const recordPlainCssDependencies = (messages) => {
  17858. messages.forEach((msg) => {
  17859. if (msg.type === "dependency") {
  17860. dependencies.add(msg.file);
  17861. }
  17862. });
  17863. return dependencies;
  17864. };
  17865. try {
  17866. result = require$$0$1(plugins).process(source, postCSSOptions);
  17867. if (options.isAsync) {
  17868. return result.then((result2) => ({
  17869. code: result2.css || "",
  17870. map: result2.map && result2.map.toJSON(),
  17871. errors,
  17872. modules: cssModules,
  17873. rawResult: result2,
  17874. dependencies: recordPlainCssDependencies(result2.messages)
  17875. })).catch((error) => ({
  17876. code: "",
  17877. map: void 0,
  17878. errors: [...errors, error],
  17879. rawResult: void 0,
  17880. dependencies
  17881. }));
  17882. }
  17883. recordPlainCssDependencies(result.messages);
  17884. code = result.css;
  17885. outMap = result.map;
  17886. } catch (e) {
  17887. errors.push(e);
  17888. }
  17889. return {
  17890. code: code || ``,
  17891. map: outMap && outMap.toJSON(),
  17892. errors,
  17893. rawResult: result,
  17894. dependencies
  17895. };
  17896. }
  17897. function preprocess(options, preprocessor) {
  17898. return preprocessor(
  17899. options.source,
  17900. options.inMap || options.map,
  17901. {
  17902. filename: options.filename,
  17903. ...options.preprocessOptions
  17904. },
  17905. options.preprocessCustomRequire
  17906. );
  17907. }
  17908. const UNKNOWN_TYPE = "Unknown";
  17909. function resolveObjectKey(node, computed) {
  17910. switch (node.type) {
  17911. case "StringLiteral":
  17912. case "NumericLiteral":
  17913. return String(node.value);
  17914. case "Identifier":
  17915. if (!computed) return node.name;
  17916. }
  17917. return void 0;
  17918. }
  17919. function concatStrings(strs) {
  17920. return strs.filter((s) => !!s).join(", ");
  17921. }
  17922. function isLiteralNode(node) {
  17923. return node.type.endsWith("Literal");
  17924. }
  17925. function isCallOf(node, test) {
  17926. return !!(node && test && node.type === "CallExpression" && node.callee.type === "Identifier" && (typeof test === "string" ? node.callee.name === test : test(node.callee.name)));
  17927. }
  17928. function toRuntimeTypeString(types) {
  17929. return types.length > 1 ? `[${types.join(", ")}]` : types[0];
  17930. }
  17931. function getImportedName(specifier) {
  17932. if (specifier.type === "ImportSpecifier")
  17933. return specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
  17934. else if (specifier.type === "ImportNamespaceSpecifier") return "*";
  17935. return "default";
  17936. }
  17937. function getId(node) {
  17938. return node.type === "Identifier" ? node.name : node.type === "StringLiteral" ? node.value : null;
  17939. }
  17940. function getStringLiteralKey(node) {
  17941. 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;
  17942. }
  17943. const identity = (str) => str;
  17944. const fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
  17945. const toLowerCase = (str) => str.toLowerCase();
  17946. function toFileNameLowerCase(x) {
  17947. return fileNameLowerCaseRegExp.test(x) ? x.replace(fileNameLowerCaseRegExp, toLowerCase) : x;
  17948. }
  17949. function createGetCanonicalFileName(useCaseSensitiveFileNames) {
  17950. return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
  17951. }
  17952. const normalize = (path$1.posix || path$1).normalize;
  17953. const windowsSlashRE = /\\/g;
  17954. function normalizePath(p) {
  17955. return normalize(p.replace(windowsSlashRE, "/"));
  17956. }
  17957. const joinPaths = (path$1.posix || path$1).join;
  17958. const propNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~\-]/;
  17959. function getEscapedPropName(key) {
  17960. return propNameEscapeSymbolsRE.test(key) ? JSON.stringify(key) : key;
  17961. }
  17962. const isJS = (...langs) => langs.some((lang) => lang === "js" || lang === "jsx");
  17963. const isTS = (...langs) => langs.some((lang) => lang === "ts" || lang === "tsx");
  17964. function analyzeScriptBindings(ast) {
  17965. for (const node of ast) {
  17966. if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "ObjectExpression") {
  17967. return analyzeBindingsFromOptions(node.declaration);
  17968. }
  17969. }
  17970. return {};
  17971. }
  17972. function analyzeBindingsFromOptions(node) {
  17973. const bindings = {};
  17974. Object.defineProperty(bindings, "__isScriptSetup", {
  17975. enumerable: false,
  17976. value: false
  17977. });
  17978. for (const property of node.properties) {
  17979. if (property.type === "ObjectProperty" && !property.computed && property.key.type === "Identifier") {
  17980. if (property.key.name === "props") {
  17981. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  17982. bindings[key] = "props";
  17983. }
  17984. } else if (property.key.name === "inject") {
  17985. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  17986. bindings[key] = "options";
  17987. }
  17988. } else if (property.value.type === "ObjectExpression" && (property.key.name === "computed" || property.key.name === "methods")) {
  17989. for (const key of getObjectExpressionKeys(property.value)) {
  17990. bindings[key] = "options";
  17991. }
  17992. }
  17993. } else if (property.type === "ObjectMethod" && property.key.type === "Identifier" && (property.key.name === "setup" || property.key.name === "data")) {
  17994. for (const bodyItem of property.body.body) {
  17995. if (bodyItem.type === "ReturnStatement" && bodyItem.argument && bodyItem.argument.type === "ObjectExpression") {
  17996. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  17997. bindings[key] = property.key.name === "setup" ? "setup-maybe-ref" : "data";
  17998. }
  17999. }
  18000. }
  18001. }
  18002. }
  18003. return bindings;
  18004. }
  18005. function getObjectExpressionKeys(node) {
  18006. const keys = [];
  18007. for (const prop of node.properties) {
  18008. if (prop.type === "SpreadElement") continue;
  18009. const key = resolveObjectKey(prop.key, prop.computed);
  18010. if (key) keys.push(String(key));
  18011. }
  18012. return keys;
  18013. }
  18014. function getArrayExpressionKeys(node) {
  18015. const keys = [];
  18016. for (const element of node.elements) {
  18017. if (element && element.type === "StringLiteral") {
  18018. keys.push(element.value);
  18019. }
  18020. }
  18021. return keys;
  18022. }
  18023. function getObjectOrArrayExpressionKeys(value) {
  18024. if (value.type === "ArrayExpression") {
  18025. return getArrayExpressionKeys(value);
  18026. }
  18027. if (value.type === "ObjectExpression") {
  18028. return getObjectExpressionKeys(value);
  18029. }
  18030. return [];
  18031. }
  18032. var _a$1, _b;
  18033. class ScriptCompileContext {
  18034. constructor(descriptor, options) {
  18035. this.descriptor = descriptor;
  18036. this.options = options;
  18037. this.isCE = false;
  18038. this.source = this.descriptor.source;
  18039. this.filename = this.descriptor.filename;
  18040. this.s = new MagicString(this.source);
  18041. this.startOffset = (_a$1 = this.descriptor.scriptSetup) == null ? void 0 : _a$1.loc.start.offset;
  18042. this.endOffset = (_b = this.descriptor.scriptSetup) == null ? void 0 : _b.loc.end.offset;
  18043. this.userImports = /* @__PURE__ */ Object.create(null);
  18044. // macros presence check
  18045. this.hasDefinePropsCall = false;
  18046. this.hasDefineEmitCall = false;
  18047. this.hasDefineExposeCall = false;
  18048. this.hasDefaultExportName = false;
  18049. this.hasDefaultExportRender = false;
  18050. this.hasDefineOptionsCall = false;
  18051. this.hasDefineSlotsCall = false;
  18052. this.hasDefineModelCall = false;
  18053. this.propsDestructuredBindings = /* @__PURE__ */ Object.create(null);
  18054. // defineModel
  18055. this.modelDecls = /* @__PURE__ */ Object.create(null);
  18056. // codegen
  18057. this.bindingMetadata = {};
  18058. this.helperImports = /* @__PURE__ */ new Set();
  18059. const { script, scriptSetup } = descriptor;
  18060. const scriptLang = script && script.lang;
  18061. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  18062. this.isJS = isJS(scriptLang, scriptSetupLang);
  18063. this.isTS = isTS(scriptLang, scriptSetupLang);
  18064. const customElement = options.customElement;
  18065. const filename = this.descriptor.filename;
  18066. if (customElement) {
  18067. this.isCE = typeof customElement === "boolean" ? customElement : customElement(filename);
  18068. }
  18069. const plugins = resolveParserPlugins(
  18070. scriptLang || scriptSetupLang,
  18071. options.babelParserPlugins
  18072. );
  18073. function parse(input, offset) {
  18074. try {
  18075. return parser$2.parse(input, {
  18076. plugins,
  18077. sourceType: "module"
  18078. }).program;
  18079. } catch (e) {
  18080. e.message = `[vue/compiler-sfc] ${e.message}
  18081. ${descriptor.filename}
  18082. ${shared.generateCodeFrame(
  18083. descriptor.source,
  18084. e.pos + offset,
  18085. e.pos + offset + 1
  18086. )}`;
  18087. throw e;
  18088. }
  18089. }
  18090. this.scriptAst = descriptor.script && parse(descriptor.script.content, descriptor.script.loc.start.offset);
  18091. this.scriptSetupAst = descriptor.scriptSetup && parse(descriptor.scriptSetup.content, this.startOffset);
  18092. }
  18093. helper(key) {
  18094. this.helperImports.add(key);
  18095. return `_${key}`;
  18096. }
  18097. getString(node, scriptSetup = true) {
  18098. const block = scriptSetup ? this.descriptor.scriptSetup : this.descriptor.script;
  18099. return block.content.slice(node.start, node.end);
  18100. }
  18101. warn(msg, node, scope) {
  18102. warn(generateError(msg, node, this, scope));
  18103. }
  18104. error(msg, node, scope) {
  18105. throw new Error(
  18106. `[@vue/compiler-sfc] ${generateError(msg, node, this, scope)}`
  18107. );
  18108. }
  18109. }
  18110. function generateError(msg, node, ctx, scope) {
  18111. const offset = scope ? scope.offset : ctx.startOffset;
  18112. return `${msg}
  18113. ${(scope || ctx.descriptor).filename}
  18114. ${shared.generateCodeFrame(
  18115. (scope || ctx.descriptor).source,
  18116. node.start + offset,
  18117. node.end + offset
  18118. )}`;
  18119. }
  18120. function resolveParserPlugins(lang, userPlugins, dts = false) {
  18121. const plugins = [];
  18122. if (!userPlugins || !userPlugins.some(
  18123. (p) => p === "importAssertions" || p === "importAttributes" || shared.isArray(p) && p[0] === "importAttributes"
  18124. )) {
  18125. plugins.push("importAttributes");
  18126. }
  18127. if (lang === "jsx" || lang === "tsx" || lang === "mtsx") {
  18128. plugins.push("jsx");
  18129. } else if (userPlugins) {
  18130. userPlugins = userPlugins.filter((p) => p !== "jsx");
  18131. }
  18132. if (lang === "ts" || lang === "mts" || lang === "tsx" || lang === "cts" || lang === "mtsx") {
  18133. plugins.push(["typescript", { dts }], "explicitResourceManagement");
  18134. if (!userPlugins || !userPlugins.includes("decorators")) {
  18135. plugins.push("decorators-legacy");
  18136. }
  18137. }
  18138. if (userPlugins) {
  18139. plugins.push(...userPlugins);
  18140. }
  18141. return plugins;
  18142. }
  18143. function rewriteDefault(input, as, parserPlugins) {
  18144. const ast = parser$2.parse(input, {
  18145. sourceType: "module",
  18146. plugins: resolveParserPlugins("js", parserPlugins)
  18147. }).program.body;
  18148. const s = new MagicString(input);
  18149. rewriteDefaultAST(ast, s, as);
  18150. return s.toString();
  18151. }
  18152. function rewriteDefaultAST(ast, s, as) {
  18153. if (!hasDefaultExport(ast)) {
  18154. s.append(`
  18155. const ${as} = {}`);
  18156. return;
  18157. }
  18158. ast.forEach((node) => {
  18159. if (node.type === "ExportDefaultDeclaration") {
  18160. if (node.declaration.type === "ClassDeclaration" && node.declaration.id) {
  18161. const start = node.declaration.decorators && node.declaration.decorators.length > 0 ? node.declaration.decorators[node.declaration.decorators.length - 1].end : node.start;
  18162. s.overwrite(start, node.declaration.id.start, ` class `);
  18163. s.append(`
  18164. const ${as} = ${node.declaration.id.name}`);
  18165. } else {
  18166. s.overwrite(node.start, node.declaration.start, `const ${as} = `);
  18167. }
  18168. } else if (node.type === "ExportNamedDeclaration") {
  18169. for (const specifier of node.specifiers) {
  18170. if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier" && specifier.exported.name === "default") {
  18171. if (node.source) {
  18172. if (specifier.local.name === "default") {
  18173. s.prepend(
  18174. `import { default as __VUE_DEFAULT__ } from '${node.source.value}'
  18175. `
  18176. );
  18177. const end2 = specifierEnd(s, specifier.local.end, node.end);
  18178. s.remove(specifier.start, end2);
  18179. s.append(`
  18180. const ${as} = __VUE_DEFAULT__`);
  18181. continue;
  18182. } else {
  18183. s.prepend(
  18184. `import { ${s.slice(
  18185. specifier.local.start,
  18186. specifier.local.end
  18187. )} as __VUE_DEFAULT__ } from '${node.source.value}'
  18188. `
  18189. );
  18190. const end2 = specifierEnd(s, specifier.exported.end, node.end);
  18191. s.remove(specifier.start, end2);
  18192. s.append(`
  18193. const ${as} = __VUE_DEFAULT__`);
  18194. continue;
  18195. }
  18196. }
  18197. const end = specifierEnd(s, specifier.end, node.end);
  18198. s.remove(specifier.start, end);
  18199. s.append(`
  18200. const ${as} = ${specifier.local.name}`);
  18201. }
  18202. }
  18203. }
  18204. });
  18205. }
  18206. function hasDefaultExport(ast) {
  18207. for (const stmt of ast) {
  18208. if (stmt.type === "ExportDefaultDeclaration") {
  18209. return true;
  18210. } else if (stmt.type === "ExportNamedDeclaration" && stmt.specifiers.some(
  18211. (spec) => spec.exported.name === "default"
  18212. )) {
  18213. return true;
  18214. }
  18215. }
  18216. return false;
  18217. }
  18218. function specifierEnd(s, end, nodeEnd) {
  18219. let hasCommas = false;
  18220. let oldEnd = end;
  18221. while (end < nodeEnd) {
  18222. if (/\s/.test(s.slice(end, end + 1))) {
  18223. end++;
  18224. } else if (s.slice(end, end + 1) === ",") {
  18225. end++;
  18226. hasCommas = true;
  18227. break;
  18228. } else if (s.slice(end, end + 1) === "}") {
  18229. break;
  18230. }
  18231. }
  18232. return hasCommas ? end : oldEnd;
  18233. }
  18234. const normalScriptDefaultVar = `__default__`;
  18235. function processNormalScript(ctx, scopeId) {
  18236. var _a;
  18237. const script = ctx.descriptor.script;
  18238. try {
  18239. let content = script.content;
  18240. let map = script.map;
  18241. const scriptAst = ctx.scriptAst;
  18242. const bindings = analyzeScriptBindings(scriptAst.body);
  18243. const { cssVars } = ctx.descriptor;
  18244. const { genDefaultAs, isProd } = ctx.options;
  18245. if (cssVars.length || genDefaultAs) {
  18246. const defaultVar = genDefaultAs || normalScriptDefaultVar;
  18247. const s = new MagicString(content);
  18248. rewriteDefaultAST(scriptAst.body, s, defaultVar);
  18249. content = s.toString();
  18250. if (cssVars.length && !((_a = ctx.options.templateOptions) == null ? void 0 : _a.ssr)) {
  18251. content += genNormalScriptCssVarsCode(
  18252. cssVars,
  18253. bindings,
  18254. scopeId,
  18255. !!isProd,
  18256. defaultVar
  18257. );
  18258. }
  18259. if (!genDefaultAs) {
  18260. content += `
  18261. export default ${defaultVar}`;
  18262. }
  18263. }
  18264. return {
  18265. ...script,
  18266. content,
  18267. map,
  18268. bindings,
  18269. scriptAst: scriptAst.body
  18270. };
  18271. } catch (e) {
  18272. return script;
  18273. }
  18274. }
  18275. const balanced = (a, b, str) => {
  18276. const ma = a instanceof RegExp ? maybeMatch(a, str) : a;
  18277. const mb = b instanceof RegExp ? maybeMatch(b, str) : b;
  18278. const r = ma !== null && mb != null && range(ma, mb, str);
  18279. return (r && {
  18280. start: r[0],
  18281. end: r[1],
  18282. pre: str.slice(0, r[0]),
  18283. body: str.slice(r[0] + ma.length, r[1]),
  18284. post: str.slice(r[1] + mb.length),
  18285. });
  18286. };
  18287. const maybeMatch = (reg, str) => {
  18288. const m = str.match(reg);
  18289. return m ? m[0] : null;
  18290. };
  18291. const range = (a, b, str) => {
  18292. let begs, beg, left, right = undefined, result;
  18293. let ai = str.indexOf(a);
  18294. let bi = str.indexOf(b, ai + 1);
  18295. let i = ai;
  18296. if (ai >= 0 && bi > 0) {
  18297. if (a === b) {
  18298. return [ai, bi];
  18299. }
  18300. begs = [];
  18301. left = str.length;
  18302. while (i >= 0 && !result) {
  18303. if (i === ai) {
  18304. begs.push(i);
  18305. ai = str.indexOf(a, i + 1);
  18306. }
  18307. else if (begs.length === 1) {
  18308. const r = begs.pop();
  18309. if (r !== undefined)
  18310. result = [r, bi];
  18311. }
  18312. else {
  18313. beg = begs.pop();
  18314. if (beg !== undefined && beg < left) {
  18315. left = beg;
  18316. right = bi;
  18317. }
  18318. bi = str.indexOf(b, i + 1);
  18319. }
  18320. i = ai < bi && ai >= 0 ? ai : bi;
  18321. }
  18322. if (begs.length && right !== undefined) {
  18323. result = [left, right];
  18324. }
  18325. }
  18326. return result;
  18327. };
  18328. const escSlash = '\0SLASH' + Math.random() + '\0';
  18329. const escOpen = '\0OPEN' + Math.random() + '\0';
  18330. const escClose = '\0CLOSE' + Math.random() + '\0';
  18331. const escComma = '\0COMMA' + Math.random() + '\0';
  18332. const escPeriod = '\0PERIOD' + Math.random() + '\0';
  18333. const escSlashPattern = new RegExp(escSlash, 'g');
  18334. const escOpenPattern = new RegExp(escOpen, 'g');
  18335. const escClosePattern = new RegExp(escClose, 'g');
  18336. const escCommaPattern = new RegExp(escComma, 'g');
  18337. const escPeriodPattern = new RegExp(escPeriod, 'g');
  18338. const slashPattern = /\\\\/g;
  18339. const openPattern = /\\{/g;
  18340. const closePattern = /\\}/g;
  18341. const commaPattern = /\\,/g;
  18342. const periodPattern = /\\\./g;
  18343. const EXPANSION_MAX = 100_000;
  18344. function numeric(str) {
  18345. return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0);
  18346. }
  18347. function escapeBraces(str) {
  18348. return str
  18349. .replace(slashPattern, escSlash)
  18350. .replace(openPattern, escOpen)
  18351. .replace(closePattern, escClose)
  18352. .replace(commaPattern, escComma)
  18353. .replace(periodPattern, escPeriod);
  18354. }
  18355. function unescapeBraces(str) {
  18356. return str
  18357. .replace(escSlashPattern, '\\')
  18358. .replace(escOpenPattern, '{')
  18359. .replace(escClosePattern, '}')
  18360. .replace(escCommaPattern, ',')
  18361. .replace(escPeriodPattern, '.');
  18362. }
  18363. /**
  18364. * Basically just str.split(","), but handling cases
  18365. * where we have nested braced sections, which should be
  18366. * treated as individual members, like {a,{b,c},d}
  18367. */
  18368. function parseCommaParts(str) {
  18369. if (!str) {
  18370. return [''];
  18371. }
  18372. const parts = [];
  18373. const m = balanced('{', '}', str);
  18374. if (!m) {
  18375. return str.split(',');
  18376. }
  18377. const { pre, body, post } = m;
  18378. const p = pre.split(',');
  18379. p[p.length - 1] += '{' + body + '}';
  18380. const postParts = parseCommaParts(post);
  18381. if (post.length) {
  18382. p[p.length - 1] += postParts.shift();
  18383. p.push.apply(p, postParts);
  18384. }
  18385. parts.push.apply(parts, p);
  18386. return parts;
  18387. }
  18388. function expand(str, options = {}) {
  18389. if (!str) {
  18390. return [];
  18391. }
  18392. const { max = EXPANSION_MAX } = options;
  18393. // I don't know why Bash 4.3 does this, but it does.
  18394. // Anything starting with {} will have the first two bytes preserved
  18395. // but *only* at the top level, so {},a}b will not expand to anything,
  18396. // but a{},b}c will be expanded to [a}c,abc].
  18397. // One could argue that this is a bug in Bash, but since the goal of
  18398. // this module is to match Bash's rules, we escape a leading {}
  18399. if (str.slice(0, 2) === '{}') {
  18400. str = '\\{\\}' + str.slice(2);
  18401. }
  18402. return expand_(escapeBraces(str), max, true).map(unescapeBraces);
  18403. }
  18404. function embrace(str) {
  18405. return '{' + str + '}';
  18406. }
  18407. function isPadded(el) {
  18408. return /^-?0\d/.test(el);
  18409. }
  18410. function lte(i, y) {
  18411. return i <= y;
  18412. }
  18413. function gte(i, y) {
  18414. return i >= y;
  18415. }
  18416. function expand_(str, max, isTop) {
  18417. /** @type {string[]} */
  18418. const expansions = [];
  18419. const m = balanced('{', '}', str);
  18420. if (!m)
  18421. return [str];
  18422. // no need to expand pre, since it is guaranteed to be free of brace-sets
  18423. const pre = m.pre;
  18424. const post = m.post.length ? expand_(m.post, max, false) : [''];
  18425. if (/\$$/.test(m.pre)) {
  18426. for (let k = 0; k < post.length && k < max; k++) {
  18427. const expansion = pre + '{' + m.body + '}' + post[k];
  18428. expansions.push(expansion);
  18429. }
  18430. }
  18431. else {
  18432. const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  18433. const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  18434. const isSequence = isNumericSequence || isAlphaSequence;
  18435. const isOptions = m.body.indexOf(',') >= 0;
  18436. if (!isSequence && !isOptions) {
  18437. // {a},b}
  18438. if (m.post.match(/,(?!,).*\}/)) {
  18439. str = m.pre + '{' + m.body + escClose + m.post;
  18440. return expand_(str, max, true);
  18441. }
  18442. return [str];
  18443. }
  18444. let n;
  18445. if (isSequence) {
  18446. n = m.body.split(/\.\./);
  18447. }
  18448. else {
  18449. n = parseCommaParts(m.body);
  18450. if (n.length === 1 && n[0] !== undefined) {
  18451. // x{{a,b}}y ==> x{a}y x{b}y
  18452. n = expand_(n[0], max, false).map(embrace);
  18453. //XXX is this necessary? Can't seem to hit it in tests.
  18454. /* c8 ignore start */
  18455. if (n.length === 1) {
  18456. return post.map(p => m.pre + n[0] + p);
  18457. }
  18458. /* c8 ignore stop */
  18459. }
  18460. }
  18461. // at this point, n is the parts, and we know it's not a comma set
  18462. // with a single entry.
  18463. let N;
  18464. if (isSequence && n[0] !== undefined && n[1] !== undefined) {
  18465. const x = numeric(n[0]);
  18466. const y = numeric(n[1]);
  18467. const width = Math.max(n[0].length, n[1].length);
  18468. let incr = n.length === 3 && n[2] !== undefined ?
  18469. Math.max(Math.abs(numeric(n[2])), 1)
  18470. : 1;
  18471. let test = lte;
  18472. const reverse = y < x;
  18473. if (reverse) {
  18474. incr *= -1;
  18475. test = gte;
  18476. }
  18477. const pad = n.some(isPadded);
  18478. N = [];
  18479. for (let i = x; test(i, y); i += incr) {
  18480. let c;
  18481. if (isAlphaSequence) {
  18482. c = String.fromCharCode(i);
  18483. if (c === '\\') {
  18484. c = '';
  18485. }
  18486. }
  18487. else {
  18488. c = String(i);
  18489. if (pad) {
  18490. const need = width - c.length;
  18491. if (need > 0) {
  18492. const z = new Array(need + 1).join('0');
  18493. if (i < 0) {
  18494. c = '-' + z + c.slice(1);
  18495. }
  18496. else {
  18497. c = z + c;
  18498. }
  18499. }
  18500. }
  18501. }
  18502. N.push(c);
  18503. }
  18504. }
  18505. else {
  18506. N = [];
  18507. for (let j = 0; j < n.length; j++) {
  18508. N.push.apply(N, expand_(n[j], max, false));
  18509. }
  18510. }
  18511. for (let j = 0; j < N.length; j++) {
  18512. for (let k = 0; k < post.length && expansions.length < max; k++) {
  18513. const expansion = pre + N[j] + post[k];
  18514. if (!isTop || isSequence || expansion) {
  18515. expansions.push(expansion);
  18516. }
  18517. }
  18518. }
  18519. }
  18520. return expansions;
  18521. }
  18522. const MAX_PATTERN_LENGTH = 1024 * 64;
  18523. const assertValidPattern = (pattern) => {
  18524. if (typeof pattern !== 'string') {
  18525. throw new TypeError('invalid pattern');
  18526. }
  18527. if (pattern.length > MAX_PATTERN_LENGTH) {
  18528. throw new TypeError('pattern is too long');
  18529. }
  18530. };
  18531. // translate the various posix character classes into unicode properties
  18532. // this works across all unicode locales
  18533. // { <posix class>: [<translation>, /u flag required, negated]
  18534. const posixClasses = {
  18535. '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
  18536. '[:alpha:]': ['\\p{L}\\p{Nl}', true],
  18537. '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
  18538. '[:blank:]': ['\\p{Zs}\\t', true],
  18539. '[:cntrl:]': ['\\p{Cc}', true],
  18540. '[:digit:]': ['\\p{Nd}', true],
  18541. '[:graph:]': ['\\p{Z}\\p{C}', true, true],
  18542. '[:lower:]': ['\\p{Ll}', true],
  18543. '[:print:]': ['\\p{C}', true],
  18544. '[:punct:]': ['\\p{P}', true],
  18545. '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
  18546. '[:upper:]': ['\\p{Lu}', true],
  18547. '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
  18548. '[:xdigit:]': ['A-Fa-f0-9', false],
  18549. };
  18550. // only need to escape a few things inside of brace expressions
  18551. // escapes: [ \ ] -
  18552. const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
  18553. // escape all regexp magic characters
  18554. const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  18555. // everything has already been escaped, we just have to join
  18556. const rangesToString = (ranges) => ranges.join('');
  18557. // takes a glob string at a posix brace expression, and returns
  18558. // an equivalent regular expression source, and boolean indicating
  18559. // whether the /u flag needs to be applied, and the number of chars
  18560. // consumed to parse the character class.
  18561. // This also removes out of order ranges, and returns ($.) if the
  18562. // entire class just no good.
  18563. const parseClass = (glob, position) => {
  18564. const pos = position;
  18565. /* c8 ignore start */
  18566. if (glob.charAt(pos) !== '[') {
  18567. throw new Error('not in a brace expression');
  18568. }
  18569. /* c8 ignore stop */
  18570. const ranges = [];
  18571. const negs = [];
  18572. let i = pos + 1;
  18573. let sawStart = false;
  18574. let uflag = false;
  18575. let escaping = false;
  18576. let negate = false;
  18577. let endPos = pos;
  18578. let rangeStart = '';
  18579. WHILE: while (i < glob.length) {
  18580. const c = glob.charAt(i);
  18581. if ((c === '!' || c === '^') && i === pos + 1) {
  18582. negate = true;
  18583. i++;
  18584. continue;
  18585. }
  18586. if (c === ']' && sawStart && !escaping) {
  18587. endPos = i + 1;
  18588. break;
  18589. }
  18590. sawStart = true;
  18591. if (c === '\\') {
  18592. if (!escaping) {
  18593. escaping = true;
  18594. i++;
  18595. continue;
  18596. }
  18597. // escaped \ char, fall through and treat like normal char
  18598. }
  18599. if (c === '[' && !escaping) {
  18600. // either a posix class, a collation equivalent, or just a [
  18601. for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
  18602. if (glob.startsWith(cls, i)) {
  18603. // invalid, [a-[] is fine, but not [a-[:alpha]]
  18604. if (rangeStart) {
  18605. return ['$.', false, glob.length - pos, true];
  18606. }
  18607. i += cls.length;
  18608. if (neg)
  18609. negs.push(unip);
  18610. else
  18611. ranges.push(unip);
  18612. uflag = uflag || u;
  18613. continue WHILE;
  18614. }
  18615. }
  18616. }
  18617. // now it's just a normal character, effectively
  18618. escaping = false;
  18619. if (rangeStart) {
  18620. // throw this range away if it's not valid, but others
  18621. // can still match.
  18622. if (c > rangeStart) {
  18623. ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
  18624. }
  18625. else if (c === rangeStart) {
  18626. ranges.push(braceEscape(c));
  18627. }
  18628. rangeStart = '';
  18629. i++;
  18630. continue;
  18631. }
  18632. // now might be the start of a range.
  18633. // can be either c-d or c-] or c<more...>] or c] at this point
  18634. if (glob.startsWith('-]', i + 1)) {
  18635. ranges.push(braceEscape(c + '-'));
  18636. i += 2;
  18637. continue;
  18638. }
  18639. if (glob.startsWith('-', i + 1)) {
  18640. rangeStart = c;
  18641. i += 2;
  18642. continue;
  18643. }
  18644. // not the start of a range, just a single character
  18645. ranges.push(braceEscape(c));
  18646. i++;
  18647. }
  18648. if (endPos < i) {
  18649. // didn't see the end of the class, not a valid class,
  18650. // but might still be valid as a literal match.
  18651. return ['', false, 0, false];
  18652. }
  18653. // if we got no ranges and no negates, then we have a range that
  18654. // cannot possibly match anything, and that poisons the whole glob
  18655. if (!ranges.length && !negs.length) {
  18656. return ['$.', false, glob.length - pos, true];
  18657. }
  18658. // if we got one positive range, and it's a single character, then that's
  18659. // not actually a magic pattern, it's just that one literal character.
  18660. // we should not treat that as "magic", we should just return the literal
  18661. // character. [_] is a perfectly valid way to escape glob magic chars.
  18662. if (negs.length === 0 &&
  18663. ranges.length === 1 &&
  18664. /^\\?.$/.test(ranges[0]) &&
  18665. !negate) {
  18666. const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
  18667. return [regexpEscape(r), false, endPos - pos, false];
  18668. }
  18669. const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
  18670. const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
  18671. const comb = ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'
  18672. : ranges.length ? sranges
  18673. : snegs;
  18674. return [comb, uflag, endPos - pos, true];
  18675. };
  18676. /**
  18677. * Un-escape a string that has been escaped with {@link escape}.
  18678. *
  18679. * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then
  18680. * square-bracket escapes are removed, but not backslash escapes.
  18681. *
  18682. * For example, it will turn the string `'[*]'` into `*`, but it will not
  18683. * turn `'\\*'` into `'*'`, because `\` is a path separator in
  18684. * `windowsPathsNoEscape` mode.
  18685. *
  18686. * When `windowsPathsNoEscape` is not set, then both square-bracket escapes and
  18687. * backslash escapes are removed.
  18688. *
  18689. * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
  18690. * or unescaped.
  18691. *
  18692. * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be
  18693. * unescaped.
  18694. */
  18695. const unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true, } = {}) => {
  18696. if (magicalBraces) {
  18697. return windowsPathsNoEscape ?
  18698. s.replace(/\[([^/\\])\]/g, '$1')
  18699. : s
  18700. .replace(/((?!\\).|^)\[([^/\\])\]/g, '$1$2')
  18701. .replace(/\\([^/])/g, '$1');
  18702. }
  18703. return windowsPathsNoEscape ?
  18704. s.replace(/\[([^/\\{}])\]/g, '$1')
  18705. : s
  18706. .replace(/((?!\\).|^)\[([^/\\{}])\]/g, '$1$2')
  18707. .replace(/\\([^/{}])/g, '$1');
  18708. };
  18709. // parse a single path portion
  18710. var _a;
  18711. const types = new Set(['!', '?', '+', '*', '@']);
  18712. const isExtglobType = (c) => types.has(c);
  18713. const isExtglobAST = (c) => isExtglobType(c.type);
  18714. // Map of which extglob types can adopt the children of a nested extglob
  18715. //
  18716. // anything but ! can adopt a matching type:
  18717. // +(a|+(b|c)|d) => +(a|b|c|d)
  18718. // *(a|*(b|c)|d) => *(a|b|c|d)
  18719. // @(a|@(b|c)|d) => @(a|b|c|d)
  18720. // ?(a|?(b|c)|d) => ?(a|b|c|d)
  18721. //
  18722. // * can adopt anything, because 0 or repetition is allowed
  18723. // *(a|?(b|c)|d) => *(a|b|c|d)
  18724. // *(a|+(b|c)|d) => *(a|b|c|d)
  18725. // *(a|@(b|c)|d) => *(a|b|c|d)
  18726. //
  18727. // + can adopt @, because 1 or repetition is allowed
  18728. // +(a|@(b|c)|d) => +(a|b|c|d)
  18729. //
  18730. // + and @ CANNOT adopt *, because 0 would be allowed
  18731. // +(a|*(b|c)|d) => would match "", on *(b|c)
  18732. // @(a|*(b|c)|d) => would match "", on *(b|c)
  18733. //
  18734. // + and @ CANNOT adopt ?, because 0 would be allowed
  18735. // +(a|?(b|c)|d) => would match "", on ?(b|c)
  18736. // @(a|?(b|c)|d) => would match "", on ?(b|c)
  18737. //
  18738. // ? can adopt @, because 0 or 1 is allowed
  18739. // ?(a|@(b|c)|d) => ?(a|b|c|d)
  18740. //
  18741. // ? and @ CANNOT adopt * or +, because >1 would be allowed
  18742. // ?(a|*(b|c)|d) => would match bbb on *(b|c)
  18743. // @(a|*(b|c)|d) => would match bbb on *(b|c)
  18744. // ?(a|+(b|c)|d) => would match bbb on +(b|c)
  18745. // @(a|+(b|c)|d) => would match bbb on +(b|c)
  18746. //
  18747. // ! CANNOT adopt ! (nothing else can either)
  18748. // !(a|!(b|c)|d) => !(a|b|c|d) would fail to match on b (not not b|c)
  18749. //
  18750. // ! can adopt @
  18751. // !(a|@(b|c)|d) => !(a|b|c|d)
  18752. //
  18753. // ! CANNOT adopt *
  18754. // !(a|*(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed
  18755. //
  18756. // ! CANNOT adopt +
  18757. // !(a|+(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed
  18758. //
  18759. // ! CANNOT adopt ?
  18760. // x!(a|?(b|c)|d) => x!(a|b|c|d) would fail to match "x"
  18761. const adoptionMap = new Map([
  18762. ['!', ['@']],
  18763. ['?', ['?', '@']],
  18764. ['@', ['@']],
  18765. ['*', ['*', '+', '?', '@']],
  18766. ['+', ['+', '@']],
  18767. ]);
  18768. // nested extglobs that can be adopted in, but with the addition of
  18769. // a blank '' element.
  18770. const adoptionWithSpaceMap = new Map([
  18771. ['!', ['?']],
  18772. ['@', ['?']],
  18773. ['+', ['?', '*']],
  18774. ]);
  18775. // union of the previous two maps
  18776. const adoptionAnyMap = new Map([
  18777. ['!', ['?', '@']],
  18778. ['?', ['?', '@']],
  18779. ['@', ['?', '@']],
  18780. ['*', ['*', '+', '?', '@']],
  18781. ['+', ['+', '@', '?', '*']],
  18782. ]);
  18783. // Extglobs that can take over their parent if they are the only child
  18784. // the key is parent, value maps child to resulting extglob parent type
  18785. // '@' is omitted because it's a special case. An `@` extglob with a single
  18786. // member can always be usurped by that subpattern.
  18787. const usurpMap = new Map([
  18788. ['!', new Map([['!', '@']])],
  18789. [
  18790. '?',
  18791. new Map([
  18792. ['*', '*'],
  18793. ['+', '*'],
  18794. ]),
  18795. ],
  18796. [
  18797. '@',
  18798. new Map([
  18799. ['!', '!'],
  18800. ['?', '?'],
  18801. ['@', '@'],
  18802. ['*', '*'],
  18803. ['+', '+'],
  18804. ]),
  18805. ],
  18806. [
  18807. '+',
  18808. new Map([
  18809. ['?', '*'],
  18810. ['*', '*'],
  18811. ]),
  18812. ],
  18813. ]);
  18814. // Patterns that get prepended to bind to the start of either the
  18815. // entire string, or just a single path portion, to prevent dots
  18816. // and/or traversal patterns, when needed.
  18817. // Exts don't need the ^ or / bit, because the root binds that already.
  18818. const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
  18819. const startNoDot = '(?!\\.)';
  18820. // characters that indicate a start of pattern needs the "no dots" bit,
  18821. // because a dot *might* be matched. ( is not in the list, because in
  18822. // the case of a child extglob, it will handle the prevention itself.
  18823. const addPatternStart = new Set(['[', '.']);
  18824. // cases where traversal is A-OK, no dot prevention needed
  18825. const justDots = new Set(['..', '.']);
  18826. const reSpecials = new Set('().*{}+?[]^$\\!');
  18827. const regExpEscape$1 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  18828. // any single thing other than /
  18829. const qmark$1 = '[^/]';
  18830. // * => any number of characters
  18831. const star$1 = qmark$1 + '*?';
  18832. // use + when we need to ensure that *something* matches, because the * is
  18833. // the only thing in the path portion.
  18834. const starNoEmpty = qmark$1 + '+?';
  18835. // remove the \ chars that we added if we end up doing a nonmagic compare
  18836. // const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
  18837. let ID = 0;
  18838. class AST {
  18839. type;
  18840. #root;
  18841. #hasMagic;
  18842. #uflag = false;
  18843. #parts = [];
  18844. #parent;
  18845. #parentIndex;
  18846. #negs;
  18847. #filledNegs = false;
  18848. #options;
  18849. #toString;
  18850. // set to true if it's an extglob with no children
  18851. // (which really means one child of '')
  18852. #emptyExt = false;
  18853. id = ++ID;
  18854. get depth() {
  18855. return (this.#parent?.depth ?? -1) + 1;
  18856. }
  18857. [Symbol.for('nodejs.util.inspect.custom')]() {
  18858. return {
  18859. '@@type': 'AST',
  18860. id: this.id,
  18861. type: this.type,
  18862. root: this.#root.id,
  18863. parent: this.#parent?.id,
  18864. depth: this.depth,
  18865. partsLength: this.#parts.length,
  18866. parts: this.#parts,
  18867. };
  18868. }
  18869. constructor(type, parent, options = {}) {
  18870. this.type = type;
  18871. // extglobs are inherently magical
  18872. if (type)
  18873. this.#hasMagic = true;
  18874. this.#parent = parent;
  18875. this.#root = this.#parent ? this.#parent.#root : this;
  18876. this.#options = this.#root === this ? options : this.#root.#options;
  18877. this.#negs = this.#root === this ? [] : this.#root.#negs;
  18878. if (type === '!' && !this.#root.#filledNegs)
  18879. this.#negs.push(this);
  18880. this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
  18881. }
  18882. get hasMagic() {
  18883. /* c8 ignore start */
  18884. if (this.#hasMagic !== undefined)
  18885. return this.#hasMagic;
  18886. /* c8 ignore stop */
  18887. for (const p of this.#parts) {
  18888. if (typeof p === 'string')
  18889. continue;
  18890. if (p.type || p.hasMagic)
  18891. return (this.#hasMagic = true);
  18892. }
  18893. // note: will be undefined until we generate the regexp src and find out
  18894. return this.#hasMagic;
  18895. }
  18896. // reconstructs the pattern
  18897. toString() {
  18898. return (this.#toString !== undefined ? this.#toString
  18899. : !this.type ?
  18900. (this.#toString = this.#parts.map(p => String(p)).join(''))
  18901. : (this.#toString =
  18902. this.type +
  18903. '(' +
  18904. this.#parts.map(p => String(p)).join('|') +
  18905. ')'));
  18906. }
  18907. #fillNegs() {
  18908. /* c8 ignore start */
  18909. if (this !== this.#root)
  18910. throw new Error('should only call on root');
  18911. if (this.#filledNegs)
  18912. return this;
  18913. /* c8 ignore stop */
  18914. // call toString() once to fill this out
  18915. this.toString();
  18916. this.#filledNegs = true;
  18917. let n;
  18918. while ((n = this.#negs.pop())) {
  18919. if (n.type !== '!')
  18920. continue;
  18921. // walk up the tree, appending everthing that comes AFTER parentIndex
  18922. let p = n;
  18923. let pp = p.#parent;
  18924. while (pp) {
  18925. for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
  18926. for (const part of n.#parts) {
  18927. /* c8 ignore start */
  18928. if (typeof part === 'string') {
  18929. throw new Error('string part in extglob AST??');
  18930. }
  18931. /* c8 ignore stop */
  18932. part.copyIn(pp.#parts[i]);
  18933. }
  18934. }
  18935. p = pp;
  18936. pp = p.#parent;
  18937. }
  18938. }
  18939. return this;
  18940. }
  18941. push(...parts) {
  18942. for (const p of parts) {
  18943. if (p === '')
  18944. continue;
  18945. /* c8 ignore start */
  18946. if (typeof p !== 'string' &&
  18947. !(p instanceof _a && p.#parent === this)) {
  18948. throw new Error('invalid part: ' + p);
  18949. }
  18950. /* c8 ignore stop */
  18951. this.#parts.push(p);
  18952. }
  18953. }
  18954. toJSON() {
  18955. const ret = this.type === null ?
  18956. this.#parts
  18957. .slice()
  18958. .map(p => (typeof p === 'string' ? p : p.toJSON()))
  18959. : [this.type, ...this.#parts.map(p => p.toJSON())];
  18960. if (this.isStart() && !this.type)
  18961. ret.unshift([]);
  18962. if (this.isEnd() &&
  18963. (this === this.#root ||
  18964. (this.#root.#filledNegs && this.#parent?.type === '!'))) {
  18965. ret.push({});
  18966. }
  18967. return ret;
  18968. }
  18969. isStart() {
  18970. if (this.#root === this)
  18971. return true;
  18972. // if (this.type) return !!this.#parent?.isStart()
  18973. if (!this.#parent?.isStart())
  18974. return false;
  18975. if (this.#parentIndex === 0)
  18976. return true;
  18977. // if everything AHEAD of this is a negation, then it's still the "start"
  18978. const p = this.#parent;
  18979. for (let i = 0; i < this.#parentIndex; i++) {
  18980. const pp = p.#parts[i];
  18981. if (!(pp instanceof _a && pp.type === '!')) {
  18982. return false;
  18983. }
  18984. }
  18985. return true;
  18986. }
  18987. isEnd() {
  18988. if (this.#root === this)
  18989. return true;
  18990. if (this.#parent?.type === '!')
  18991. return true;
  18992. if (!this.#parent?.isEnd())
  18993. return false;
  18994. if (!this.type)
  18995. return this.#parent?.isEnd();
  18996. // if not root, it'll always have a parent
  18997. /* c8 ignore start */
  18998. const pl = this.#parent ? this.#parent.#parts.length : 0;
  18999. /* c8 ignore stop */
  19000. return this.#parentIndex === pl - 1;
  19001. }
  19002. copyIn(part) {
  19003. if (typeof part === 'string')
  19004. this.push(part);
  19005. else
  19006. this.push(part.clone(this));
  19007. }
  19008. clone(parent) {
  19009. const c = new _a(this.type, parent);
  19010. for (const p of this.#parts) {
  19011. c.copyIn(p);
  19012. }
  19013. return c;
  19014. }
  19015. static #parseAST(str, ast, pos, opt, extDepth) {
  19016. const maxDepth = opt.maxExtglobRecursion ?? 2;
  19017. let escaping = false;
  19018. let inBrace = false;
  19019. let braceStart = -1;
  19020. let braceNeg = false;
  19021. if (ast.type === null) {
  19022. // outside of a extglob, append until we find a start
  19023. let i = pos;
  19024. let acc = '';
  19025. while (i < str.length) {
  19026. const c = str.charAt(i++);
  19027. // still accumulate escapes at this point, but we do ignore
  19028. // starts that are escaped
  19029. if (escaping || c === '\\') {
  19030. escaping = !escaping;
  19031. acc += c;
  19032. continue;
  19033. }
  19034. if (inBrace) {
  19035. if (i === braceStart + 1) {
  19036. if (c === '^' || c === '!') {
  19037. braceNeg = true;
  19038. }
  19039. }
  19040. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  19041. inBrace = false;
  19042. }
  19043. acc += c;
  19044. continue;
  19045. }
  19046. else if (c === '[') {
  19047. inBrace = true;
  19048. braceStart = i;
  19049. braceNeg = false;
  19050. acc += c;
  19051. continue;
  19052. }
  19053. // we don't have to check for adoption here, because that's
  19054. // done at the other recursion point.
  19055. const doRecurse = !opt.noext &&
  19056. isExtglobType(c) &&
  19057. str.charAt(i) === '(' &&
  19058. extDepth <= maxDepth;
  19059. if (doRecurse) {
  19060. ast.push(acc);
  19061. acc = '';
  19062. const ext = new _a(c, ast);
  19063. i = _a.#parseAST(str, ext, i, opt, extDepth + 1);
  19064. ast.push(ext);
  19065. continue;
  19066. }
  19067. acc += c;
  19068. }
  19069. ast.push(acc);
  19070. return i;
  19071. }
  19072. // some kind of extglob, pos is at the (
  19073. // find the next | or )
  19074. let i = pos + 1;
  19075. let part = new _a(null, ast);
  19076. const parts = [];
  19077. let acc = '';
  19078. while (i < str.length) {
  19079. const c = str.charAt(i++);
  19080. // still accumulate escapes at this point, but we do ignore
  19081. // starts that are escaped
  19082. if (escaping || c === '\\') {
  19083. escaping = !escaping;
  19084. acc += c;
  19085. continue;
  19086. }
  19087. if (inBrace) {
  19088. if (i === braceStart + 1) {
  19089. if (c === '^' || c === '!') {
  19090. braceNeg = true;
  19091. }
  19092. }
  19093. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  19094. inBrace = false;
  19095. }
  19096. acc += c;
  19097. continue;
  19098. }
  19099. else if (c === '[') {
  19100. inBrace = true;
  19101. braceStart = i;
  19102. braceNeg = false;
  19103. acc += c;
  19104. continue;
  19105. }
  19106. const doRecurse = !opt.noext &&
  19107. isExtglobType(c) &&
  19108. str.charAt(i) === '(' &&
  19109. /* c8 ignore start - the maxDepth is sufficient here */
  19110. (extDepth <= maxDepth || (ast && ast.#canAdoptType(c)));
  19111. /* c8 ignore stop */
  19112. if (doRecurse) {
  19113. const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1;
  19114. part.push(acc);
  19115. acc = '';
  19116. const ext = new _a(c, part);
  19117. part.push(ext);
  19118. i = _a.#parseAST(str, ext, i, opt, extDepth + depthAdd);
  19119. continue;
  19120. }
  19121. if (c === '|') {
  19122. part.push(acc);
  19123. acc = '';
  19124. parts.push(part);
  19125. part = new _a(null, ast);
  19126. continue;
  19127. }
  19128. if (c === ')') {
  19129. if (acc === '' && ast.#parts.length === 0) {
  19130. ast.#emptyExt = true;
  19131. }
  19132. part.push(acc);
  19133. acc = '';
  19134. ast.push(...parts, part);
  19135. return i;
  19136. }
  19137. acc += c;
  19138. }
  19139. // unfinished extglob
  19140. // if we got here, it was a malformed extglob! not an extglob, but
  19141. // maybe something else in there.
  19142. ast.type = null;
  19143. ast.#hasMagic = undefined;
  19144. ast.#parts = [str.substring(pos - 1)];
  19145. return i;
  19146. }
  19147. #canAdoptWithSpace(child) {
  19148. return this.#canAdopt(child, adoptionWithSpaceMap);
  19149. }
  19150. #canAdopt(child, map = adoptionMap) {
  19151. if (!child ||
  19152. typeof child !== 'object' ||
  19153. child.type !== null ||
  19154. child.#parts.length !== 1 ||
  19155. this.type === null) {
  19156. return false;
  19157. }
  19158. const gc = child.#parts[0];
  19159. if (!gc || typeof gc !== 'object' || gc.type === null) {
  19160. return false;
  19161. }
  19162. return this.#canAdoptType(gc.type, map);
  19163. }
  19164. #canAdoptType(c, map = adoptionAnyMap) {
  19165. return !!map.get(this.type)?.includes(c);
  19166. }
  19167. #adoptWithSpace(child, index) {
  19168. const gc = child.#parts[0];
  19169. const blank = new _a(null, gc, this.options);
  19170. blank.#parts.push('');
  19171. gc.push(blank);
  19172. this.#adopt(child, index);
  19173. }
  19174. #adopt(child, index) {
  19175. const gc = child.#parts[0];
  19176. this.#parts.splice(index, 1, ...gc.#parts);
  19177. for (const p of gc.#parts) {
  19178. if (typeof p === 'object')
  19179. p.#parent = this;
  19180. }
  19181. this.#toString = undefined;
  19182. }
  19183. #canUsurpType(c) {
  19184. const m = usurpMap.get(this.type);
  19185. return !!m?.has(c);
  19186. }
  19187. #canUsurp(child) {
  19188. if (!child ||
  19189. typeof child !== 'object' ||
  19190. child.type !== null ||
  19191. child.#parts.length !== 1 ||
  19192. this.type === null ||
  19193. this.#parts.length !== 1) {
  19194. return false;
  19195. }
  19196. const gc = child.#parts[0];
  19197. if (!gc || typeof gc !== 'object' || gc.type === null) {
  19198. return false;
  19199. }
  19200. return this.#canUsurpType(gc.type);
  19201. }
  19202. #usurp(child) {
  19203. const m = usurpMap.get(this.type);
  19204. const gc = child.#parts[0];
  19205. const nt = m?.get(gc.type);
  19206. /* c8 ignore start - impossible */
  19207. if (!nt)
  19208. return false;
  19209. /* c8 ignore stop */
  19210. this.#parts = gc.#parts;
  19211. for (const p of this.#parts) {
  19212. if (typeof p === 'object') {
  19213. p.#parent = this;
  19214. }
  19215. }
  19216. this.type = nt;
  19217. this.#toString = undefined;
  19218. this.#emptyExt = false;
  19219. }
  19220. static fromGlob(pattern, options = {}) {
  19221. const ast = new _a(null, undefined, options);
  19222. _a.#parseAST(pattern, ast, 0, options, 0);
  19223. return ast;
  19224. }
  19225. // returns the regular expression if there's magic, or the unescaped
  19226. // string if not.
  19227. toMMPattern() {
  19228. // should only be called on root
  19229. /* c8 ignore start */
  19230. if (this !== this.#root)
  19231. return this.#root.toMMPattern();
  19232. /* c8 ignore stop */
  19233. const glob = this.toString();
  19234. const [re, body, hasMagic, uflag] = this.toRegExpSource();
  19235. // if we're in nocase mode, and not nocaseMagicOnly, then we do
  19236. // still need a regular expression if we have to case-insensitively
  19237. // match capital/lowercase characters.
  19238. const anyMagic = hasMagic ||
  19239. this.#hasMagic ||
  19240. (this.#options.nocase &&
  19241. !this.#options.nocaseMagicOnly &&
  19242. glob.toUpperCase() !== glob.toLowerCase());
  19243. if (!anyMagic) {
  19244. return body;
  19245. }
  19246. const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
  19247. return Object.assign(new RegExp(`^${re}$`, flags), {
  19248. _src: re,
  19249. _glob: glob,
  19250. });
  19251. }
  19252. get options() {
  19253. return this.#options;
  19254. }
  19255. // returns the string match, the regexp source, whether there's magic
  19256. // in the regexp (so a regular expression is required) and whether or
  19257. // not the uflag is needed for the regular expression (for posix classes)
  19258. // TODO: instead of injecting the start/end at this point, just return
  19259. // the BODY of the regexp, along with the start/end portions suitable
  19260. // for binding the start/end in either a joined full-path makeRe context
  19261. // (where we bind to (^|/), or a standalone matchPart context (where
  19262. // we bind to ^, and not /). Otherwise slashes get duped!
  19263. //
  19264. // In part-matching mode, the start is:
  19265. // - if not isStart: nothing
  19266. // - if traversal possible, but not allowed: ^(?!\.\.?$)
  19267. // - if dots allowed or not possible: ^
  19268. // - if dots possible and not allowed: ^(?!\.)
  19269. // end is:
  19270. // - if not isEnd(): nothing
  19271. // - else: $
  19272. //
  19273. // In full-path matching mode, we put the slash at the START of the
  19274. // pattern, so start is:
  19275. // - if first pattern: same as part-matching mode
  19276. // - if not isStart(): nothing
  19277. // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
  19278. // - if dots allowed or not possible: /
  19279. // - if dots possible and not allowed: /(?!\.)
  19280. // end is:
  19281. // - if last pattern, same as part-matching mode
  19282. // - else nothing
  19283. //
  19284. // Always put the (?:$|/) on negated tails, though, because that has to be
  19285. // there to bind the end of the negated pattern portion, and it's easier to
  19286. // just stick it in now rather than try to inject it later in the middle of
  19287. // the pattern.
  19288. //
  19289. // We can just always return the same end, and leave it up to the caller
  19290. // to know whether it's going to be used joined or in parts.
  19291. // And, if the start is adjusted slightly, can do the same there:
  19292. // - if not isStart: nothing
  19293. // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
  19294. // - if dots allowed or not possible: (?:/|^)
  19295. // - if dots possible and not allowed: (?:/|^)(?!\.)
  19296. //
  19297. // But it's better to have a simpler binding without a conditional, for
  19298. // performance, so probably better to return both start options.
  19299. //
  19300. // Then the caller just ignores the end if it's not the first pattern,
  19301. // and the start always gets applied.
  19302. //
  19303. // But that's always going to be $ if it's the ending pattern, or nothing,
  19304. // so the caller can just attach $ at the end of the pattern when building.
  19305. //
  19306. // So the todo is:
  19307. // - better detect what kind of start is needed
  19308. // - return both flavors of starting pattern
  19309. // - attach $ at the end of the pattern when creating the actual RegExp
  19310. //
  19311. // Ah, but wait, no, that all only applies to the root when the first pattern
  19312. // is not an extglob. If the first pattern IS an extglob, then we need all
  19313. // that dot prevention biz to live in the extglob portions, because eg
  19314. // +(*|.x*) can match .xy but not .yx.
  19315. //
  19316. // So, return the two flavors if it's #root and the first child is not an
  19317. // AST, otherwise leave it to the child AST to handle it, and there,
  19318. // use the (?:^|/) style of start binding.
  19319. //
  19320. // Even simplified further:
  19321. // - Since the start for a join is eg /(?!\.) and the start for a part
  19322. // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
  19323. // or start or whatever) and prepend ^ or / at the Regexp construction.
  19324. toRegExpSource(allowDot) {
  19325. const dot = allowDot ?? !!this.#options.dot;
  19326. if (this.#root === this) {
  19327. this.#flatten();
  19328. this.#fillNegs();
  19329. }
  19330. if (!isExtglobAST(this)) {
  19331. const noEmpty = this.isStart() &&
  19332. this.isEnd() &&
  19333. !this.#parts.some(s => typeof s !== 'string');
  19334. const src = this.#parts
  19335. .map(p => {
  19336. const [re, _, hasMagic, uflag] = typeof p === 'string' ?
  19337. _a.#parseGlob(p, this.#hasMagic, noEmpty)
  19338. : p.toRegExpSource(allowDot);
  19339. this.#hasMagic = this.#hasMagic || hasMagic;
  19340. this.#uflag = this.#uflag || uflag;
  19341. return re;
  19342. })
  19343. .join('');
  19344. let start = '';
  19345. if (this.isStart()) {
  19346. if (typeof this.#parts[0] === 'string') {
  19347. // this is the string that will match the start of the pattern,
  19348. // so we need to protect against dots and such.
  19349. // '.' and '..' cannot match unless the pattern is that exactly,
  19350. // even if it starts with . or dot:true is set.
  19351. const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
  19352. if (!dotTravAllowed) {
  19353. const aps = addPatternStart;
  19354. // check if we have a possibility of matching . or ..,
  19355. // and prevent that.
  19356. const needNoTrav =
  19357. // dots are allowed, and the pattern starts with [ or .
  19358. (dot && aps.has(src.charAt(0))) ||
  19359. // the pattern starts with \., and then [ or .
  19360. (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
  19361. // the pattern starts with \.\., and then [ or .
  19362. (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
  19363. // no need to prevent dots if it can't match a dot, or if a
  19364. // sub-pattern will be preventing it anyway.
  19365. const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
  19366. start =
  19367. needNoTrav ? startNoTraversal
  19368. : needNoDot ? startNoDot
  19369. : '';
  19370. }
  19371. }
  19372. }
  19373. // append the "end of path portion" pattern to negation tails
  19374. let end = '';
  19375. if (this.isEnd() &&
  19376. this.#root.#filledNegs &&
  19377. this.#parent?.type === '!') {
  19378. end = '(?:$|\\/)';
  19379. }
  19380. const final = start + src + end;
  19381. return [
  19382. final,
  19383. unescape(src),
  19384. (this.#hasMagic = !!this.#hasMagic),
  19385. this.#uflag,
  19386. ];
  19387. }
  19388. // We need to calculate the body *twice* if it's a repeat pattern
  19389. // at the start, once in nodot mode, then again in dot mode, so a
  19390. // pattern like *(?) can match 'x.y'
  19391. const repeated = this.type === '*' || this.type === '+';
  19392. // some kind of extglob
  19393. const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
  19394. let body = this.#partsToRegExp(dot);
  19395. if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
  19396. // invalid extglob, has to at least be *something* present, if it's
  19397. // the entire path portion.
  19398. const s = this.toString();
  19399. const me = this;
  19400. me.#parts = [s];
  19401. me.type = null;
  19402. me.#hasMagic = undefined;
  19403. return [s, unescape(this.toString()), false, false];
  19404. }
  19405. let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ?
  19406. ''
  19407. : this.#partsToRegExp(true);
  19408. if (bodyDotAllowed === body) {
  19409. bodyDotAllowed = '';
  19410. }
  19411. if (bodyDotAllowed) {
  19412. body = `(?:${body})(?:${bodyDotAllowed})*?`;
  19413. }
  19414. // an empty !() is exactly equivalent to a starNoEmpty
  19415. let final = '';
  19416. if (this.type === '!' && this.#emptyExt) {
  19417. final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
  19418. }
  19419. else {
  19420. const close = this.type === '!' ?
  19421. // !() must match something,but !(x) can match ''
  19422. '))' +
  19423. (this.isStart() && !dot && !allowDot ? startNoDot : '') +
  19424. star$1 +
  19425. ')'
  19426. : this.type === '@' ? ')'
  19427. : this.type === '?' ? ')?'
  19428. : this.type === '+' && bodyDotAllowed ? ')'
  19429. : this.type === '*' && bodyDotAllowed ? `)?`
  19430. : `)${this.type}`;
  19431. final = start + body + close;
  19432. }
  19433. return [
  19434. final,
  19435. unescape(body),
  19436. (this.#hasMagic = !!this.#hasMagic),
  19437. this.#uflag,
  19438. ];
  19439. }
  19440. #flatten() {
  19441. if (!isExtglobAST(this)) {
  19442. for (const p of this.#parts) {
  19443. if (typeof p === 'object') {
  19444. p.#flatten();
  19445. }
  19446. }
  19447. }
  19448. else {
  19449. // do up to 10 passes to flatten as much as possible
  19450. let iterations = 0;
  19451. let done = false;
  19452. do {
  19453. done = true;
  19454. for (let i = 0; i < this.#parts.length; i++) {
  19455. const c = this.#parts[i];
  19456. if (typeof c === 'object') {
  19457. c.#flatten();
  19458. if (this.#canAdopt(c)) {
  19459. done = false;
  19460. this.#adopt(c, i);
  19461. }
  19462. else if (this.#canAdoptWithSpace(c)) {
  19463. done = false;
  19464. this.#adoptWithSpace(c, i);
  19465. }
  19466. else if (this.#canUsurp(c)) {
  19467. done = false;
  19468. this.#usurp(c);
  19469. }
  19470. }
  19471. }
  19472. } while (!done && ++iterations < 10);
  19473. }
  19474. this.#toString = undefined;
  19475. }
  19476. #partsToRegExp(dot) {
  19477. return this.#parts
  19478. .map(p => {
  19479. // extglob ASTs should only contain parent ASTs
  19480. /* c8 ignore start */
  19481. if (typeof p === 'string') {
  19482. throw new Error('string type in extglob ast??');
  19483. }
  19484. /* c8 ignore stop */
  19485. // can ignore hasMagic, because extglobs are already always magic
  19486. const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
  19487. this.#uflag = this.#uflag || uflag;
  19488. return re;
  19489. })
  19490. .filter(p => !(this.isStart() && this.isEnd()) || !!p)
  19491. .join('|');
  19492. }
  19493. static #parseGlob(glob, hasMagic, noEmpty = false) {
  19494. let escaping = false;
  19495. let re = '';
  19496. let uflag = false;
  19497. // multiple stars that aren't globstars coalesce into one *
  19498. let inStar = false;
  19499. for (let i = 0; i < glob.length; i++) {
  19500. const c = glob.charAt(i);
  19501. if (escaping) {
  19502. escaping = false;
  19503. re += (reSpecials.has(c) ? '\\' : '') + c;
  19504. continue;
  19505. }
  19506. if (c === '*') {
  19507. if (inStar)
  19508. continue;
  19509. inStar = true;
  19510. re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star$1;
  19511. hasMagic = true;
  19512. continue;
  19513. }
  19514. else {
  19515. inStar = false;
  19516. }
  19517. if (c === '\\') {
  19518. if (i === glob.length - 1) {
  19519. re += '\\\\';
  19520. }
  19521. else {
  19522. escaping = true;
  19523. }
  19524. continue;
  19525. }
  19526. if (c === '[') {
  19527. const [src, needUflag, consumed, magic] = parseClass(glob, i);
  19528. if (consumed) {
  19529. re += src;
  19530. uflag = uflag || needUflag;
  19531. i += consumed - 1;
  19532. hasMagic = hasMagic || magic;
  19533. continue;
  19534. }
  19535. }
  19536. if (c === '?') {
  19537. re += qmark$1;
  19538. hasMagic = true;
  19539. continue;
  19540. }
  19541. re += regExpEscape$1(c);
  19542. }
  19543. return [re, unescape(glob), !!hasMagic, uflag];
  19544. }
  19545. }
  19546. _a = AST;
  19547. /**
  19548. * Escape all magic characters in a glob pattern.
  19549. *
  19550. * If the {@link MinimatchOptions.windowsPathsNoEscape}
  19551. * option is used, then characters are escaped by wrapping in `[]`, because
  19552. * a magic character wrapped in a character class can only be satisfied by
  19553. * that exact character. In this mode, `\` is _not_ escaped, because it is
  19554. * not interpreted as a magic character, but instead as a path separator.
  19555. *
  19556. * If the {@link MinimatchOptions.magicalBraces} option is used,
  19557. * then braces (`{` and `}`) will be escaped.
  19558. */
  19559. const escape = (s, { windowsPathsNoEscape = false, magicalBraces = false, } = {}) => {
  19560. // don't need to escape +@! because we escape the parens
  19561. // that make those magic, and escaping ! as [!] isn't valid,
  19562. // because [!]] is a valid glob class meaning not ']'.
  19563. if (magicalBraces) {
  19564. return windowsPathsNoEscape ?
  19565. s.replace(/[?*()[\]{}]/g, '[$&]')
  19566. : s.replace(/[?*()[\]\\{}]/g, '\\$&');
  19567. }
  19568. return windowsPathsNoEscape ?
  19569. s.replace(/[?*()[\]]/g, '[$&]')
  19570. : s.replace(/[?*()[\]\\]/g, '\\$&');
  19571. };
  19572. const minimatch = (p, pattern, options = {}) => {
  19573. assertValidPattern(pattern);
  19574. // shortcut: comments match nothing.
  19575. if (!options.nocomment && pattern.charAt(0) === '#') {
  19576. return false;
  19577. }
  19578. return new Minimatch(pattern, options).match(p);
  19579. };
  19580. // Optimized checking for the most common glob patterns.
  19581. const starDotExtRE = /^\*+([^+@!?*[(]*)$/;
  19582. const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
  19583. const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
  19584. const starDotExtTestNocase = (ext) => {
  19585. ext = ext.toLowerCase();
  19586. return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
  19587. };
  19588. const starDotExtTestNocaseDot = (ext) => {
  19589. ext = ext.toLowerCase();
  19590. return (f) => f.toLowerCase().endsWith(ext);
  19591. };
  19592. const starDotStarRE = /^\*+\.\*+$/;
  19593. const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
  19594. const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
  19595. const dotStarRE = /^\.\*+$/;
  19596. const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
  19597. const starRE = /^\*+$/;
  19598. const starTest = (f) => f.length !== 0 && !f.startsWith('.');
  19599. const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
  19600. const qmarksRE = /^\?+([^+@!?*[(]*)?$/;
  19601. const qmarksTestNocase = ([$0, ext = '']) => {
  19602. const noext = qmarksTestNoExt([$0]);
  19603. if (!ext)
  19604. return noext;
  19605. ext = ext.toLowerCase();
  19606. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  19607. };
  19608. const qmarksTestNocaseDot = ([$0, ext = '']) => {
  19609. const noext = qmarksTestNoExtDot([$0]);
  19610. if (!ext)
  19611. return noext;
  19612. ext = ext.toLowerCase();
  19613. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  19614. };
  19615. const qmarksTestDot = ([$0, ext = '']) => {
  19616. const noext = qmarksTestNoExtDot([$0]);
  19617. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  19618. };
  19619. const qmarksTest = ([$0, ext = '']) => {
  19620. const noext = qmarksTestNoExt([$0]);
  19621. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  19622. };
  19623. const qmarksTestNoExt = ([$0]) => {
  19624. const len = $0.length;
  19625. return (f) => f.length === len && !f.startsWith('.');
  19626. };
  19627. const qmarksTestNoExtDot = ([$0]) => {
  19628. const len = $0.length;
  19629. return (f) => f.length === len && f !== '.' && f !== '..';
  19630. };
  19631. /* c8 ignore start */
  19632. const defaultPlatform = (typeof process === 'object' && process ?
  19633. (typeof process.env === 'object' &&
  19634. process.env &&
  19635. process.env.__MINIMATCH_TESTING_PLATFORM__) ||
  19636. process.platform
  19637. : 'posix');
  19638. const path = {
  19639. win32: { sep: '\\' },
  19640. posix: { sep: '/' },
  19641. };
  19642. /* c8 ignore stop */
  19643. const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
  19644. minimatch.sep = sep;
  19645. const GLOBSTAR = Symbol('globstar **');
  19646. minimatch.GLOBSTAR = GLOBSTAR;
  19647. // any single thing other than /
  19648. // don't need to escape / when using new RegExp()
  19649. const qmark = '[^/]';
  19650. // * => any number of characters
  19651. const star = qmark + '*?';
  19652. // ** when dots are allowed. Anything goes, except .. and .
  19653. // not (^ or / followed by one or two dots followed by $ or /),
  19654. // followed by anything, any number of times.
  19655. const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
  19656. // not a ^ or / followed by a dot,
  19657. // followed by anything, any number of times.
  19658. const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
  19659. const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
  19660. minimatch.filter = filter;
  19661. const ext = (a, b = {}) => Object.assign({}, a, b);
  19662. const defaults = (def) => {
  19663. if (!def || typeof def !== 'object' || !Object.keys(def).length) {
  19664. return minimatch;
  19665. }
  19666. const orig = minimatch;
  19667. const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
  19668. return Object.assign(m, {
  19669. Minimatch: class Minimatch extends orig.Minimatch {
  19670. constructor(pattern, options = {}) {
  19671. super(pattern, ext(def, options));
  19672. }
  19673. static defaults(options) {
  19674. return orig.defaults(ext(def, options)).Minimatch;
  19675. }
  19676. },
  19677. AST: class AST extends orig.AST {
  19678. /* c8 ignore start */
  19679. constructor(type, parent, options = {}) {
  19680. super(type, parent, ext(def, options));
  19681. }
  19682. /* c8 ignore stop */
  19683. static fromGlob(pattern, options = {}) {
  19684. return orig.AST.fromGlob(pattern, ext(def, options));
  19685. }
  19686. },
  19687. unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
  19688. escape: (s, options = {}) => orig.escape(s, ext(def, options)),
  19689. filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
  19690. defaults: (options) => orig.defaults(ext(def, options)),
  19691. makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
  19692. braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
  19693. match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
  19694. sep: orig.sep,
  19695. GLOBSTAR: GLOBSTAR,
  19696. });
  19697. };
  19698. minimatch.defaults = defaults;
  19699. // Brace expansion:
  19700. // a{b,c}d -> abd acd
  19701. // a{b,}c -> abc ac
  19702. // a{0..3}d -> a0d a1d a2d a3d
  19703. // a{b,c{d,e}f}g -> abg acdfg acefg
  19704. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  19705. //
  19706. // Invalid sets are not expanded.
  19707. // a{2..}b -> a{2..}b
  19708. // a{b}c -> a{b}c
  19709. const braceExpand = (pattern, options = {}) => {
  19710. assertValidPattern(pattern);
  19711. // Thanks to Yeting Li <https://github.com/yetingli> for
  19712. // improving this regexp to avoid a ReDOS vulnerability.
  19713. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
  19714. // shortcut. no need to expand.
  19715. return [pattern];
  19716. }
  19717. return expand(pattern, { max: options.braceExpandMax });
  19718. };
  19719. minimatch.braceExpand = braceExpand;
  19720. // parse a component of the expanded set.
  19721. // At this point, no pattern may contain "/" in it
  19722. // so we're going to return a 2d array, where each entry is the full
  19723. // pattern, split on '/', and then turned into a regular expression.
  19724. // A regexp is made at the end which joins each array with an
  19725. // escaped /, and another full one which joins each regexp with |.
  19726. //
  19727. // Following the lead of Bash 4.1, note that "**" only has special meaning
  19728. // when it is the *only* thing in a path portion. Otherwise, any series
  19729. // of * is equivalent to a single *. Globstar behavior is enabled by
  19730. // default, and can be disabled by setting options.noglobstar.
  19731. const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
  19732. minimatch.makeRe = makeRe;
  19733. const match = (list, pattern, options = {}) => {
  19734. const mm = new Minimatch(pattern, options);
  19735. list = list.filter(f => mm.match(f));
  19736. if (mm.options.nonull && !list.length) {
  19737. list.push(pattern);
  19738. }
  19739. return list;
  19740. };
  19741. minimatch.match = match;
  19742. // replace stuff like \* with *
  19743. const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
  19744. const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  19745. class Minimatch {
  19746. options;
  19747. set;
  19748. pattern;
  19749. windowsPathsNoEscape;
  19750. nonegate;
  19751. negate;
  19752. comment;
  19753. empty;
  19754. preserveMultipleSlashes;
  19755. partial;
  19756. globSet;
  19757. globParts;
  19758. nocase;
  19759. isWindows;
  19760. platform;
  19761. windowsNoMagicRoot;
  19762. maxGlobstarRecursion;
  19763. regexp;
  19764. constructor(pattern, options = {}) {
  19765. assertValidPattern(pattern);
  19766. options = options || {};
  19767. this.options = options;
  19768. this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? 200;
  19769. this.pattern = pattern;
  19770. this.platform = options.platform || defaultPlatform;
  19771. this.isWindows = this.platform === 'win32';
  19772. // avoid the annoying deprecation flag lol
  19773. const awe = ('allowWindow' + 'sEscape');
  19774. this.windowsPathsNoEscape =
  19775. !!options.windowsPathsNoEscape || options[awe] === false;
  19776. if (this.windowsPathsNoEscape) {
  19777. this.pattern = this.pattern.replace(/\\/g, '/');
  19778. }
  19779. this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
  19780. this.regexp = null;
  19781. this.negate = false;
  19782. this.nonegate = !!options.nonegate;
  19783. this.comment = false;
  19784. this.empty = false;
  19785. this.partial = !!options.partial;
  19786. this.nocase = !!this.options.nocase;
  19787. this.windowsNoMagicRoot =
  19788. options.windowsNoMagicRoot !== undefined ?
  19789. options.windowsNoMagicRoot
  19790. : !!(this.isWindows && this.nocase);
  19791. this.globSet = [];
  19792. this.globParts = [];
  19793. this.set = [];
  19794. // make the set of regexps etc.
  19795. this.make();
  19796. }
  19797. hasMagic() {
  19798. if (this.options.magicalBraces && this.set.length > 1) {
  19799. return true;
  19800. }
  19801. for (const pattern of this.set) {
  19802. for (const part of pattern) {
  19803. if (typeof part !== 'string')
  19804. return true;
  19805. }
  19806. }
  19807. return false;
  19808. }
  19809. debug(..._) { }
  19810. make() {
  19811. const pattern = this.pattern;
  19812. const options = this.options;
  19813. // empty patterns and comments match nothing.
  19814. if (!options.nocomment && pattern.charAt(0) === '#') {
  19815. this.comment = true;
  19816. return;
  19817. }
  19818. if (!pattern) {
  19819. this.empty = true;
  19820. return;
  19821. }
  19822. // step 1: figure out negation, etc.
  19823. this.parseNegate();
  19824. // step 2: expand braces
  19825. this.globSet = [...new Set(this.braceExpand())];
  19826. if (options.debug) {
  19827. //oxlint-disable-next-line no-console
  19828. this.debug = (...args) => console.error(...args);
  19829. }
  19830. this.debug(this.pattern, this.globSet);
  19831. // step 3: now we have a set, so turn each one into a series of
  19832. // path-portion matching patterns.
  19833. // These will be regexps, except in the case of "**", which is
  19834. // set to the GLOBSTAR object for globstar behavior,
  19835. // and will not contain any / characters
  19836. //
  19837. // First, we preprocess to make the glob pattern sets a bit simpler
  19838. // and deduped. There are some perf-killing patterns that can cause
  19839. // problems with a glob walk, but we can simplify them down a bit.
  19840. const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
  19841. this.globParts = this.preprocess(rawGlobParts);
  19842. this.debug(this.pattern, this.globParts);
  19843. // glob --> regexps
  19844. let set = this.globParts.map((s, _, __) => {
  19845. if (this.isWindows && this.windowsNoMagicRoot) {
  19846. // check if it's a drive or unc path.
  19847. const isUNC = s[0] === '' &&
  19848. s[1] === '' &&
  19849. (s[2] === '?' || !globMagic.test(s[2])) &&
  19850. !globMagic.test(s[3]);
  19851. const isDrive = /^[a-z]:/i.test(s[0]);
  19852. if (isUNC) {
  19853. return [
  19854. ...s.slice(0, 4),
  19855. ...s.slice(4).map(ss => this.parse(ss)),
  19856. ];
  19857. }
  19858. else if (isDrive) {
  19859. return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
  19860. }
  19861. }
  19862. return s.map(ss => this.parse(ss));
  19863. });
  19864. this.debug(this.pattern, set);
  19865. // filter out everything that didn't compile properly.
  19866. this.set = set.filter(s => s.indexOf(false) === -1);
  19867. // do not treat the ? in UNC paths as magic
  19868. if (this.isWindows) {
  19869. for (let i = 0; i < this.set.length; i++) {
  19870. const p = this.set[i];
  19871. if (p[0] === '' &&
  19872. p[1] === '' &&
  19873. this.globParts[i][2] === '?' &&
  19874. typeof p[3] === 'string' &&
  19875. /^[a-z]:$/i.test(p[3])) {
  19876. p[2] = '?';
  19877. }
  19878. }
  19879. }
  19880. this.debug(this.pattern, this.set);
  19881. }
  19882. // various transforms to equivalent pattern sets that are
  19883. // faster to process in a filesystem walk. The goal is to
  19884. // eliminate what we can, and push all ** patterns as far
  19885. // to the right as possible, even if it increases the number
  19886. // of patterns that we have to process.
  19887. preprocess(globParts) {
  19888. // if we're not in globstar mode, then turn ** into *
  19889. if (this.options.noglobstar) {
  19890. for (const partset of globParts) {
  19891. for (let j = 0; j < partset.length; j++) {
  19892. if (partset[j] === '**') {
  19893. partset[j] = '*';
  19894. }
  19895. }
  19896. }
  19897. }
  19898. const { optimizationLevel = 1 } = this.options;
  19899. if (optimizationLevel >= 2) {
  19900. // aggressive optimization for the purpose of fs walking
  19901. globParts = this.firstPhasePreProcess(globParts);
  19902. globParts = this.secondPhasePreProcess(globParts);
  19903. }
  19904. else if (optimizationLevel >= 1) {
  19905. // just basic optimizations to remove some .. parts
  19906. globParts = this.levelOneOptimize(globParts);
  19907. }
  19908. else {
  19909. // just collapse multiple ** portions into one
  19910. globParts = this.adjascentGlobstarOptimize(globParts);
  19911. }
  19912. return globParts;
  19913. }
  19914. // just get rid of adjascent ** portions
  19915. adjascentGlobstarOptimize(globParts) {
  19916. return globParts.map(parts => {
  19917. let gs = -1;
  19918. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  19919. let i = gs;
  19920. while (parts[i + 1] === '**') {
  19921. i++;
  19922. }
  19923. if (i !== gs) {
  19924. parts.splice(gs, i - gs);
  19925. }
  19926. }
  19927. return parts;
  19928. });
  19929. }
  19930. // get rid of adjascent ** and resolve .. portions
  19931. levelOneOptimize(globParts) {
  19932. return globParts.map(parts => {
  19933. parts = parts.reduce((set, part) => {
  19934. const prev = set[set.length - 1];
  19935. if (part === '**' && prev === '**') {
  19936. return set;
  19937. }
  19938. if (part === '..') {
  19939. if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
  19940. set.pop();
  19941. return set;
  19942. }
  19943. }
  19944. set.push(part);
  19945. return set;
  19946. }, []);
  19947. return parts.length === 0 ? [''] : parts;
  19948. });
  19949. }
  19950. levelTwoFileOptimize(parts) {
  19951. if (!Array.isArray(parts)) {
  19952. parts = this.slashSplit(parts);
  19953. }
  19954. let didSomething = false;
  19955. do {
  19956. didSomething = false;
  19957. // <pre>/<e>/<rest> -> <pre>/<rest>
  19958. if (!this.preserveMultipleSlashes) {
  19959. for (let i = 1; i < parts.length - 1; i++) {
  19960. const p = parts[i];
  19961. // don't squeeze out UNC patterns
  19962. if (i === 1 && p === '' && parts[0] === '')
  19963. continue;
  19964. if (p === '.' || p === '') {
  19965. didSomething = true;
  19966. parts.splice(i, 1);
  19967. i--;
  19968. }
  19969. }
  19970. if (parts[0] === '.' &&
  19971. parts.length === 2 &&
  19972. (parts[1] === '.' || parts[1] === '')) {
  19973. didSomething = true;
  19974. parts.pop();
  19975. }
  19976. }
  19977. // <pre>/<p>/../<rest> -> <pre>/<rest>
  19978. let dd = 0;
  19979. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  19980. const p = parts[dd - 1];
  19981. if (p &&
  19982. p !== '.' &&
  19983. p !== '..' &&
  19984. p !== '**' &&
  19985. !(this.isWindows && /^[a-z]:$/i.test(p))) {
  19986. didSomething = true;
  19987. parts.splice(dd - 1, 2);
  19988. dd -= 2;
  19989. }
  19990. }
  19991. } while (didSomething);
  19992. return parts.length === 0 ? [''] : parts;
  19993. }
  19994. // First phase: single-pattern processing
  19995. // <pre> is 1 or more portions
  19996. // <rest> is 1 or more portions
  19997. // <p> is any portion other than ., .., '', or **
  19998. // <e> is . or ''
  19999. //
  20000. // **/.. is *brutal* for filesystem walking performance, because
  20001. // it effectively resets the recursive walk each time it occurs,
  20002. // and ** cannot be reduced out by a .. pattern part like a regexp
  20003. // or most strings (other than .., ., and '') can be.
  20004. //
  20005. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  20006. // <pre>/<e>/<rest> -> <pre>/<rest>
  20007. // <pre>/<p>/../<rest> -> <pre>/<rest>
  20008. // **/**/<rest> -> **/<rest>
  20009. //
  20010. // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
  20011. // this WOULD be allowed if ** did follow symlinks, or * didn't
  20012. firstPhasePreProcess(globParts) {
  20013. let didSomething = false;
  20014. do {
  20015. didSomething = false;
  20016. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  20017. for (let parts of globParts) {
  20018. let gs = -1;
  20019. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  20020. let gss = gs;
  20021. while (parts[gss + 1] === '**') {
  20022. // <pre>/**/**/<rest> -> <pre>/**/<rest>
  20023. gss++;
  20024. }
  20025. // eg, if gs is 2 and gss is 4, that means we have 3 **
  20026. // parts, and can remove 2 of them.
  20027. if (gss > gs) {
  20028. parts.splice(gs + 1, gss - gs);
  20029. }
  20030. let next = parts[gs + 1];
  20031. const p = parts[gs + 2];
  20032. const p2 = parts[gs + 3];
  20033. if (next !== '..')
  20034. continue;
  20035. if (!p ||
  20036. p === '.' ||
  20037. p === '..' ||
  20038. !p2 ||
  20039. p2 === '.' ||
  20040. p2 === '..') {
  20041. continue;
  20042. }
  20043. didSomething = true;
  20044. // edit parts in place, and push the new one
  20045. parts.splice(gs, 1);
  20046. const other = parts.slice(0);
  20047. other[gs] = '**';
  20048. globParts.push(other);
  20049. gs--;
  20050. }
  20051. // <pre>/<e>/<rest> -> <pre>/<rest>
  20052. if (!this.preserveMultipleSlashes) {
  20053. for (let i = 1; i < parts.length - 1; i++) {
  20054. const p = parts[i];
  20055. // don't squeeze out UNC patterns
  20056. if (i === 1 && p === '' && parts[0] === '')
  20057. continue;
  20058. if (p === '.' || p === '') {
  20059. didSomething = true;
  20060. parts.splice(i, 1);
  20061. i--;
  20062. }
  20063. }
  20064. if (parts[0] === '.' &&
  20065. parts.length === 2 &&
  20066. (parts[1] === '.' || parts[1] === '')) {
  20067. didSomething = true;
  20068. parts.pop();
  20069. }
  20070. }
  20071. // <pre>/<p>/../<rest> -> <pre>/<rest>
  20072. let dd = 0;
  20073. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  20074. const p = parts[dd - 1];
  20075. if (p && p !== '.' && p !== '..' && p !== '**') {
  20076. didSomething = true;
  20077. const needDot = dd === 1 && parts[dd + 1] === '**';
  20078. const splin = needDot ? ['.'] : [];
  20079. parts.splice(dd - 1, 2, ...splin);
  20080. if (parts.length === 0)
  20081. parts.push('');
  20082. dd -= 2;
  20083. }
  20084. }
  20085. }
  20086. } while (didSomething);
  20087. return globParts;
  20088. }
  20089. // second phase: multi-pattern dedupes
  20090. // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
  20091. // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
  20092. // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
  20093. //
  20094. // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
  20095. // ^-- not valid because ** doens't follow symlinks
  20096. secondPhasePreProcess(globParts) {
  20097. for (let i = 0; i < globParts.length - 1; i++) {
  20098. for (let j = i + 1; j < globParts.length; j++) {
  20099. const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
  20100. if (matched) {
  20101. globParts[i] = [];
  20102. globParts[j] = matched;
  20103. break;
  20104. }
  20105. }
  20106. }
  20107. return globParts.filter(gs => gs.length);
  20108. }
  20109. partsMatch(a, b, emptyGSMatch = false) {
  20110. let ai = 0;
  20111. let bi = 0;
  20112. let result = [];
  20113. let which = '';
  20114. while (ai < a.length && bi < b.length) {
  20115. if (a[ai] === b[bi]) {
  20116. result.push(which === 'b' ? b[bi] : a[ai]);
  20117. ai++;
  20118. bi++;
  20119. }
  20120. else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
  20121. result.push(a[ai]);
  20122. ai++;
  20123. }
  20124. else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
  20125. result.push(b[bi]);
  20126. bi++;
  20127. }
  20128. else if (a[ai] === '*' &&
  20129. b[bi] &&
  20130. (this.options.dot || !b[bi].startsWith('.')) &&
  20131. b[bi] !== '**') {
  20132. if (which === 'b')
  20133. return false;
  20134. which = 'a';
  20135. result.push(a[ai]);
  20136. ai++;
  20137. bi++;
  20138. }
  20139. else if (b[bi] === '*' &&
  20140. a[ai] &&
  20141. (this.options.dot || !a[ai].startsWith('.')) &&
  20142. a[ai] !== '**') {
  20143. if (which === 'a')
  20144. return false;
  20145. which = 'b';
  20146. result.push(b[bi]);
  20147. ai++;
  20148. bi++;
  20149. }
  20150. else {
  20151. return false;
  20152. }
  20153. }
  20154. // if we fall out of the loop, it means they two are identical
  20155. // as long as their lengths match
  20156. return a.length === b.length && result;
  20157. }
  20158. parseNegate() {
  20159. if (this.nonegate)
  20160. return;
  20161. const pattern = this.pattern;
  20162. let negate = false;
  20163. let negateOffset = 0;
  20164. for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
  20165. negate = !negate;
  20166. negateOffset++;
  20167. }
  20168. if (negateOffset)
  20169. this.pattern = pattern.slice(negateOffset);
  20170. this.negate = negate;
  20171. }
  20172. // set partial to true to test if, for example,
  20173. // "/a/b" matches the start of "/*/b/*/d"
  20174. // Partial means, if you run out of file before you run
  20175. // out of pattern, then that's fine, as long as all
  20176. // the parts match.
  20177. matchOne(file, pattern, partial = false) {
  20178. let fileStartIndex = 0;
  20179. let patternStartIndex = 0;
  20180. // UNC paths like //?/X:/... can match X:/... and vice versa
  20181. // Drive letters in absolute drive or unc paths are always compared
  20182. // case-insensitively.
  20183. if (this.isWindows) {
  20184. const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
  20185. const fileUNC = !fileDrive &&
  20186. file[0] === '' &&
  20187. file[1] === '' &&
  20188. file[2] === '?' &&
  20189. /^[a-z]:$/i.test(file[3]);
  20190. const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
  20191. const patternUNC = !patternDrive &&
  20192. pattern[0] === '' &&
  20193. pattern[1] === '' &&
  20194. pattern[2] === '?' &&
  20195. typeof pattern[3] === 'string' &&
  20196. /^[a-z]:$/i.test(pattern[3]);
  20197. const fdi = fileUNC ? 3
  20198. : fileDrive ? 0
  20199. : undefined;
  20200. const pdi = patternUNC ? 3
  20201. : patternDrive ? 0
  20202. : undefined;
  20203. if (typeof fdi === 'number' && typeof pdi === 'number') {
  20204. const [fd, pd] = [
  20205. file[fdi],
  20206. pattern[pdi],
  20207. ];
  20208. // start matching at the drive letter index of each
  20209. if (fd.toLowerCase() === pd.toLowerCase()) {
  20210. pattern[pdi] = fd;
  20211. patternStartIndex = pdi;
  20212. fileStartIndex = fdi;
  20213. }
  20214. }
  20215. }
  20216. // resolve and reduce . and .. portions in the file as well.
  20217. // don't need to do the second phase, because it's only one string[]
  20218. const { optimizationLevel = 1 } = this.options;
  20219. if (optimizationLevel >= 2) {
  20220. file = this.levelTwoFileOptimize(file);
  20221. }
  20222. if (pattern.includes(GLOBSTAR)) {
  20223. return this.#matchGlobstar(file, pattern, partial, fileStartIndex, patternStartIndex);
  20224. }
  20225. return this.#matchOne(file, pattern, partial, fileStartIndex, patternStartIndex);
  20226. }
  20227. #matchGlobstar(file, pattern, partial, fileIndex, patternIndex) {
  20228. // split the pattern into head, tail, and middle of ** delimited parts
  20229. const firstgs = pattern.indexOf(GLOBSTAR, patternIndex);
  20230. const lastgs = pattern.lastIndexOf(GLOBSTAR);
  20231. // split the pattern up into globstar-delimited sections
  20232. // the tail has to be at the end, and the others just have
  20233. // to be found in order from the head.
  20234. const [head, body, tail] = partial ?
  20235. [
  20236. pattern.slice(patternIndex, firstgs),
  20237. pattern.slice(firstgs + 1),
  20238. [],
  20239. ]
  20240. : [
  20241. pattern.slice(patternIndex, firstgs),
  20242. pattern.slice(firstgs + 1, lastgs),
  20243. pattern.slice(lastgs + 1),
  20244. ];
  20245. // check the head, from the current file/pattern index.
  20246. if (head.length) {
  20247. const fileHead = file.slice(fileIndex, fileIndex + head.length);
  20248. if (!this.#matchOne(fileHead, head, partial, 0, 0)) {
  20249. return false;
  20250. }
  20251. fileIndex += head.length;
  20252. patternIndex += head.length;
  20253. }
  20254. // now we know the head matches!
  20255. // if the last portion is not empty, it MUST match the end
  20256. // check the tail
  20257. let fileTailMatch = 0;
  20258. if (tail.length) {
  20259. // if head + tail > file, then we cannot possibly match
  20260. if (tail.length + fileIndex > file.length)
  20261. return false;
  20262. // try to match the tail
  20263. let tailStart = file.length - tail.length;
  20264. if (this.#matchOne(file, tail, partial, tailStart, 0)) {
  20265. fileTailMatch = tail.length;
  20266. }
  20267. else {
  20268. // affordance for stuff like a/**/* matching a/b/
  20269. // if the last file portion is '', and there's more to the pattern
  20270. // then try without the '' bit.
  20271. if (file[file.length - 1] !== '' ||
  20272. fileIndex + tail.length === file.length) {
  20273. return false;
  20274. }
  20275. tailStart--;
  20276. if (!this.#matchOne(file, tail, partial, tailStart, 0)) {
  20277. return false;
  20278. }
  20279. fileTailMatch = tail.length + 1;
  20280. }
  20281. }
  20282. // now we know the tail matches!
  20283. // the middle is zero or more portions wrapped in **, possibly
  20284. // containing more ** sections.
  20285. // so a/**/b/**/c/**/d has become **/b/**/c/**
  20286. // if it's empty, it means a/**/b, just verify we have no bad dots
  20287. // if there's no tail, so it ends on /**, then we must have *something*
  20288. // after the head, or it's not a matc
  20289. if (!body.length) {
  20290. let sawSome = !!fileTailMatch;
  20291. for (let i = fileIndex; i < file.length - fileTailMatch; i++) {
  20292. const f = String(file[i]);
  20293. sawSome = true;
  20294. if (f === '.' ||
  20295. f === '..' ||
  20296. (!this.options.dot && f.startsWith('.'))) {
  20297. return false;
  20298. }
  20299. }
  20300. // in partial mode, we just need to get past all file parts
  20301. return partial || sawSome;
  20302. }
  20303. // now we know that there's one or more body sections, which can
  20304. // be matched anywhere from the 0 index (because the head was pruned)
  20305. // through to the length-fileTailMatch index.
  20306. // split the body up into sections, and note the minimum index it can
  20307. // be found at (start with the length of all previous segments)
  20308. // [section, before, after]
  20309. const bodySegments = [[[], 0]];
  20310. let currentBody = bodySegments[0];
  20311. let nonGsParts = 0;
  20312. const nonGsPartsSums = [0];
  20313. for (const b of body) {
  20314. if (b === GLOBSTAR) {
  20315. nonGsPartsSums.push(nonGsParts);
  20316. currentBody = [[], 0];
  20317. bodySegments.push(currentBody);
  20318. }
  20319. else {
  20320. currentBody[0].push(b);
  20321. nonGsParts++;
  20322. }
  20323. }
  20324. let i = bodySegments.length - 1;
  20325. const fileLength = file.length - fileTailMatch;
  20326. for (const b of bodySegments) {
  20327. b[1] = fileLength - (nonGsPartsSums[i--] + b[0].length);
  20328. }
  20329. return !!this.#matchGlobStarBodySections(file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch);
  20330. }
  20331. // return false for "nope, not matching"
  20332. // return null for "not matching, cannot keep trying"
  20333. #matchGlobStarBodySections(file,
  20334. // pattern section, last possible position for it
  20335. bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail) {
  20336. // take the first body segment, and walk from fileIndex to its "after"
  20337. // value at the end
  20338. // If it doesn't match at that position, we increment, until we hit
  20339. // that final possible position, and give up.
  20340. // If it does match, then advance and try to rest.
  20341. // If any of them fail we keep walking forward.
  20342. // this is still a bit recursively painful, but it's more constrained
  20343. // than previous implementations, because we never test something that
  20344. // can't possibly be a valid matching condition.
  20345. const bs = bodySegments[bodyIndex];
  20346. if (!bs) {
  20347. // just make sure that there's no bad dots
  20348. for (let i = fileIndex; i < file.length; i++) {
  20349. sawTail = true;
  20350. const f = file[i];
  20351. if (f === '.' ||
  20352. f === '..' ||
  20353. (!this.options.dot && f.startsWith('.'))) {
  20354. return false;
  20355. }
  20356. }
  20357. return sawTail;
  20358. }
  20359. // have a non-globstar body section to test
  20360. const [body, after] = bs;
  20361. while (fileIndex <= after) {
  20362. const m = this.#matchOne(file.slice(0, fileIndex + body.length), body, partial, fileIndex, 0);
  20363. // if limit exceeded, no match. intentional false negative,
  20364. // acceptable break in correctness for security.
  20365. if (m && globStarDepth < this.maxGlobstarRecursion) {
  20366. // match! see if the rest match. if so, we're done!
  20367. const sub = this.#matchGlobStarBodySections(file, bodySegments, fileIndex + body.length, bodyIndex + 1, partial, globStarDepth + 1, sawTail);
  20368. if (sub !== false) {
  20369. return sub;
  20370. }
  20371. }
  20372. const f = file[fileIndex];
  20373. if (f === '.' ||
  20374. f === '..' ||
  20375. (!this.options.dot && f.startsWith('.'))) {
  20376. return false;
  20377. }
  20378. fileIndex++;
  20379. }
  20380. // walked off. no point continuing
  20381. return partial || null;
  20382. }
  20383. #matchOne(file, pattern, partial, fileIndex, patternIndex) {
  20384. let fi;
  20385. let pi;
  20386. let pl;
  20387. let fl;
  20388. for (fi = fileIndex,
  20389. pi = patternIndex,
  20390. fl = file.length,
  20391. pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
  20392. this.debug('matchOne loop');
  20393. let p = pattern[pi];
  20394. let f = file[fi];
  20395. this.debug(pattern, p, f);
  20396. // should be impossible.
  20397. // some invalid regexp stuff in the set.
  20398. /* c8 ignore start */
  20399. if (p === false || p === GLOBSTAR) {
  20400. return false;
  20401. }
  20402. /* c8 ignore stop */
  20403. // something other than **
  20404. // non-magic patterns just have to match exactly
  20405. // patterns with magic have been turned into regexps.
  20406. let hit;
  20407. if (typeof p === 'string') {
  20408. hit = f === p;
  20409. this.debug('string match', p, f, hit);
  20410. }
  20411. else {
  20412. hit = p.test(f);
  20413. this.debug('pattern match', p, f, hit);
  20414. }
  20415. if (!hit)
  20416. return false;
  20417. }
  20418. // Note: ending in / means that we'll get a final ""
  20419. // at the end of the pattern. This can only match a
  20420. // corresponding "" at the end of the file.
  20421. // If the file ends in /, then it can only match a
  20422. // a pattern that ends in /, unless the pattern just
  20423. // doesn't have any more for it. But, a/b/ should *not*
  20424. // match "a/b/*", even though "" matches against the
  20425. // [^/]*? pattern, except in partial mode, where it might
  20426. // simply not be reached yet.
  20427. // However, a/b/ should still satisfy a/*
  20428. // now either we fell off the end of the pattern, or we're done.
  20429. if (fi === fl && pi === pl) {
  20430. // ran out of pattern and filename at the same time.
  20431. // an exact hit!
  20432. return true;
  20433. }
  20434. else if (fi === fl) {
  20435. // ran out of file, but still had pattern left.
  20436. // this is ok if we're doing the match as part of
  20437. // a glob fs traversal.
  20438. return partial;
  20439. }
  20440. else if (pi === pl) {
  20441. // ran out of pattern, still have file left.
  20442. // this is only acceptable if we're on the very last
  20443. // empty segment of a file with a trailing slash.
  20444. // a/* should match a/b/
  20445. return fi === fl - 1 && file[fi] === '';
  20446. /* c8 ignore start */
  20447. }
  20448. else {
  20449. // should be unreachable.
  20450. throw new Error('wtf?');
  20451. }
  20452. /* c8 ignore stop */
  20453. }
  20454. braceExpand() {
  20455. return braceExpand(this.pattern, this.options);
  20456. }
  20457. parse(pattern) {
  20458. assertValidPattern(pattern);
  20459. const options = this.options;
  20460. // shortcuts
  20461. if (pattern === '**')
  20462. return GLOBSTAR;
  20463. if (pattern === '')
  20464. return '';
  20465. // far and away, the most common glob pattern parts are
  20466. // *, *.*, and *.<ext> Add a fast check method for those.
  20467. let m;
  20468. let fastTest = null;
  20469. if ((m = pattern.match(starRE))) {
  20470. fastTest = options.dot ? starTestDot : starTest;
  20471. }
  20472. else if ((m = pattern.match(starDotExtRE))) {
  20473. fastTest = (options.nocase ?
  20474. options.dot ?
  20475. starDotExtTestNocaseDot
  20476. : starDotExtTestNocase
  20477. : options.dot ? starDotExtTestDot
  20478. : starDotExtTest)(m[1]);
  20479. }
  20480. else if ((m = pattern.match(qmarksRE))) {
  20481. fastTest = (options.nocase ?
  20482. options.dot ?
  20483. qmarksTestNocaseDot
  20484. : qmarksTestNocase
  20485. : options.dot ? qmarksTestDot
  20486. : qmarksTest)(m);
  20487. }
  20488. else if ((m = pattern.match(starDotStarRE))) {
  20489. fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
  20490. }
  20491. else if ((m = pattern.match(dotStarRE))) {
  20492. fastTest = dotStarTest;
  20493. }
  20494. const re = AST.fromGlob(pattern, this.options).toMMPattern();
  20495. if (fastTest && typeof re === 'object') {
  20496. // Avoids overriding in frozen environments
  20497. Reflect.defineProperty(re, 'test', { value: fastTest });
  20498. }
  20499. return re;
  20500. }
  20501. makeRe() {
  20502. if (this.regexp || this.regexp === false)
  20503. return this.regexp;
  20504. // at this point, this.set is a 2d array of partial
  20505. // pattern strings, or "**".
  20506. //
  20507. // It's better to use .match(). This function shouldn't
  20508. // be used, really, but it's pretty convenient sometimes,
  20509. // when you just want to work with a regex.
  20510. const set = this.set;
  20511. if (!set.length) {
  20512. this.regexp = false;
  20513. return this.regexp;
  20514. }
  20515. const options = this.options;
  20516. const twoStar = options.noglobstar ? star
  20517. : options.dot ? twoStarDot
  20518. : twoStarNoDot;
  20519. const flags = new Set(options.nocase ? ['i'] : []);
  20520. // regexpify non-globstar patterns
  20521. // if ** is only item, then we just do one twoStar
  20522. // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
  20523. // if ** is last, append (\/twoStar|) to previous
  20524. // if ** is in the middle, append (\/|\/twoStar\/) to previous
  20525. // then filter out GLOBSTAR symbols
  20526. let re = set
  20527. .map(pattern => {
  20528. const pp = pattern.map(p => {
  20529. if (p instanceof RegExp) {
  20530. for (const f of p.flags.split(''))
  20531. flags.add(f);
  20532. }
  20533. return (typeof p === 'string' ? regExpEscape(p)
  20534. : p === GLOBSTAR ? GLOBSTAR
  20535. : p._src);
  20536. });
  20537. pp.forEach((p, i) => {
  20538. const next = pp[i + 1];
  20539. const prev = pp[i - 1];
  20540. if (p !== GLOBSTAR || prev === GLOBSTAR) {
  20541. return;
  20542. }
  20543. if (prev === undefined) {
  20544. if (next !== undefined && next !== GLOBSTAR) {
  20545. pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
  20546. }
  20547. else {
  20548. pp[i] = twoStar;
  20549. }
  20550. }
  20551. else if (next === undefined) {
  20552. pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + ')?';
  20553. }
  20554. else if (next !== GLOBSTAR) {
  20555. pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
  20556. pp[i + 1] = GLOBSTAR;
  20557. }
  20558. });
  20559. const filtered = pp.filter(p => p !== GLOBSTAR);
  20560. // For partial matches, we need to make the pattern match
  20561. // any prefix of the full path. We do this by generating
  20562. // alternative patterns that match progressively longer prefixes.
  20563. if (this.partial && filtered.length >= 1) {
  20564. const prefixes = [];
  20565. for (let i = 1; i <= filtered.length; i++) {
  20566. prefixes.push(filtered.slice(0, i).join('/'));
  20567. }
  20568. return '(?:' + prefixes.join('|') + ')';
  20569. }
  20570. return filtered.join('/');
  20571. })
  20572. .join('|');
  20573. // need to wrap in parens if we had more than one thing with |,
  20574. // otherwise only the first will be anchored to ^ and the last to $
  20575. const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
  20576. // must match entire pattern
  20577. // ending in a * or ** will make it less strict.
  20578. re = '^' + open + re + close + '$';
  20579. // In partial mode, '/' should always match as it's a valid prefix for any pattern
  20580. if (this.partial) {
  20581. re = '^(?:\\/|' + open + re.slice(1, -1) + close + ')$';
  20582. }
  20583. // can match anything, as long as it's not this.
  20584. if (this.negate)
  20585. re = '^(?!' + re + ').+$';
  20586. try {
  20587. this.regexp = new RegExp(re, [...flags].join(''));
  20588. /* c8 ignore start */
  20589. }
  20590. catch {
  20591. // should be impossible
  20592. this.regexp = false;
  20593. }
  20594. /* c8 ignore stop */
  20595. return this.regexp;
  20596. }
  20597. slashSplit(p) {
  20598. // if p starts with // on windows, we preserve that
  20599. // so that UNC paths aren't broken. Otherwise, any number of
  20600. // / characters are coalesced into one, unless
  20601. // preserveMultipleSlashes is set to true.
  20602. if (this.preserveMultipleSlashes) {
  20603. return p.split('/');
  20604. }
  20605. else if (this.isWindows && /^\/\/[^/]+/.test(p)) {
  20606. // add an extra '' for the one we lose
  20607. return ['', ...p.split(/\/+/)];
  20608. }
  20609. else {
  20610. return p.split(/\/+/);
  20611. }
  20612. }
  20613. match(f, partial = this.partial) {
  20614. this.debug('match', f, this.pattern);
  20615. // short-circuit in the case of busted things.
  20616. // comments, etc.
  20617. if (this.comment) {
  20618. return false;
  20619. }
  20620. if (this.empty) {
  20621. return f === '';
  20622. }
  20623. if (f === '/' && partial) {
  20624. return true;
  20625. }
  20626. const options = this.options;
  20627. // windows: need to use /, not \
  20628. if (this.isWindows) {
  20629. f = f.split('\\').join('/');
  20630. }
  20631. // treat the test path as a set of pathparts.
  20632. const ff = this.slashSplit(f);
  20633. this.debug(this.pattern, 'split', ff);
  20634. // just ONE of the pattern sets in this.set needs to match
  20635. // in order for it to be valid. If negating, then just one
  20636. // match means that we have failed.
  20637. // Either way, return on the first hit.
  20638. const set = this.set;
  20639. this.debug(this.pattern, 'set', set);
  20640. // Find the basename of the path by looking for the last non-empty segment
  20641. let filename = ff[ff.length - 1];
  20642. if (!filename) {
  20643. for (let i = ff.length - 2; !filename && i >= 0; i--) {
  20644. filename = ff[i];
  20645. }
  20646. }
  20647. for (const pattern of set) {
  20648. let file = ff;
  20649. if (options.matchBase && pattern.length === 1) {
  20650. file = [filename];
  20651. }
  20652. const hit = this.matchOne(file, pattern, partial);
  20653. if (hit) {
  20654. if (options.flipNegate) {
  20655. return true;
  20656. }
  20657. return !this.negate;
  20658. }
  20659. }
  20660. // didn't get any hits. this is success if it's a negative
  20661. // pattern, failure otherwise.
  20662. if (options.flipNegate) {
  20663. return false;
  20664. }
  20665. return this.negate;
  20666. }
  20667. static defaults(def) {
  20668. return minimatch.defaults(def).Minimatch;
  20669. }
  20670. }
  20671. /* c8 ignore stop */
  20672. minimatch.AST = AST;
  20673. minimatch.Minimatch = Minimatch;
  20674. minimatch.escape = escape;
  20675. minimatch.unescape = unescape;
  20676. class TypeScope {
  20677. constructor(filename, source, offset = 0, imports = /* @__PURE__ */ Object.create(null), types = /* @__PURE__ */ Object.create(null), declares = /* @__PURE__ */ Object.create(null)) {
  20678. this.filename = filename;
  20679. this.source = source;
  20680. this.offset = offset;
  20681. this.imports = imports;
  20682. this.types = types;
  20683. this.declares = declares;
  20684. this.isGenericScope = false;
  20685. this.resolvedImportSources = /* @__PURE__ */ Object.create(null);
  20686. this.exportedTypes = /* @__PURE__ */ Object.create(null);
  20687. this.exportedDeclares = /* @__PURE__ */ Object.create(null);
  20688. }
  20689. }
  20690. function resolveTypeElements(ctx, node, scope, typeParameters) {
  20691. const canCache = !typeParameters;
  20692. if (canCache && node._resolvedElements) {
  20693. return node._resolvedElements;
  20694. }
  20695. const resolved = innerResolveTypeElements(
  20696. ctx,
  20697. node,
  20698. node._ownerScope || scope || ctxToScope(ctx),
  20699. typeParameters
  20700. );
  20701. return canCache ? node._resolvedElements = resolved : resolved;
  20702. }
  20703. function innerResolveTypeElements(ctx, node, scope, typeParameters) {
  20704. var _a, _b;
  20705. if (node.leadingComments && node.leadingComments.some((c) => c.value.includes("@vue-ignore"))) {
  20706. return { props: {} };
  20707. }
  20708. switch (node.type) {
  20709. case "TSTypeLiteral":
  20710. return typeElementsToMap(ctx, node.members, scope, typeParameters);
  20711. case "TSInterfaceDeclaration":
  20712. return resolveInterfaceMembers(ctx, node, scope, typeParameters);
  20713. case "TSTypeAliasDeclaration":
  20714. case "TSTypeAnnotation":
  20715. case "TSParenthesizedType":
  20716. return resolveTypeElements(
  20717. ctx,
  20718. node.typeAnnotation,
  20719. scope,
  20720. typeParameters
  20721. );
  20722. case "TSFunctionType": {
  20723. return { props: {}, calls: [node] };
  20724. }
  20725. case "TSUnionType":
  20726. case "TSIntersectionType":
  20727. return mergeElements(
  20728. node.types.map((t) => resolveTypeElements(ctx, t, scope, typeParameters)),
  20729. node.type
  20730. );
  20731. case "TSMappedType":
  20732. return resolveMappedType(ctx, node, scope, typeParameters);
  20733. case "TSIndexedAccessType": {
  20734. const types = resolveIndexType(ctx, node, scope);
  20735. return mergeElements(
  20736. types.map((t) => resolveTypeElements(ctx, t, t._ownerScope)),
  20737. "TSUnionType"
  20738. );
  20739. }
  20740. case "TSExpressionWithTypeArguments":
  20741. // referenced by interface extends
  20742. case "TSTypeReference": {
  20743. const typeName = getReferenceName(node);
  20744. if ((typeName === "ExtractPropTypes" || typeName === "ExtractPublicPropTypes") && node.typeParameters && ((_a = scope.imports[typeName]) == null ? void 0 : _a.source) === "vue") {
  20745. return resolveExtractPropTypes(
  20746. resolveTypeElements(
  20747. ctx,
  20748. node.typeParameters.params[0],
  20749. scope,
  20750. typeParameters
  20751. ),
  20752. scope
  20753. );
  20754. }
  20755. const resolved = resolveTypeReference(ctx, node, scope);
  20756. if (resolved) {
  20757. let typeParams;
  20758. if ((resolved.type === "TSTypeAliasDeclaration" || resolved.type === "TSInterfaceDeclaration") && resolved.typeParameters && node.typeParameters) {
  20759. typeParams = /* @__PURE__ */ Object.create(null);
  20760. resolved.typeParameters.params.forEach((p, i) => {
  20761. let param = typeParameters && typeParameters[p.name];
  20762. if (!param) param = node.typeParameters.params[i];
  20763. typeParams[p.name] = param;
  20764. });
  20765. }
  20766. return resolveTypeElements(
  20767. ctx,
  20768. resolved,
  20769. resolved._ownerScope,
  20770. typeParams
  20771. );
  20772. } else {
  20773. if (typeof typeName === "string") {
  20774. if (typeParameters && typeParameters[typeName]) {
  20775. return resolveTypeElements(
  20776. ctx,
  20777. typeParameters[typeName],
  20778. scope,
  20779. typeParameters
  20780. );
  20781. }
  20782. if (
  20783. // @ts-expect-error
  20784. SupportedBuiltinsSet.has(typeName)
  20785. ) {
  20786. return resolveBuiltin(
  20787. ctx,
  20788. node,
  20789. typeName,
  20790. scope,
  20791. typeParameters
  20792. );
  20793. } else if (typeName === "ReturnType" && node.typeParameters) {
  20794. const ret = resolveReturnType(
  20795. ctx,
  20796. node.typeParameters.params[0],
  20797. scope
  20798. );
  20799. if (ret) {
  20800. return resolveTypeElements(ctx, ret, scope);
  20801. }
  20802. }
  20803. }
  20804. return ctx.error(
  20805. `Unresolvable type reference or unsupported built-in utility type`,
  20806. node,
  20807. scope
  20808. );
  20809. }
  20810. }
  20811. case "TSImportType": {
  20812. if (getId(node.argument) === "vue" && ((_b = node.qualifier) == null ? void 0 : _b.type) === "Identifier" && node.qualifier.name === "ExtractPropTypes" && node.typeParameters) {
  20813. return resolveExtractPropTypes(
  20814. resolveTypeElements(ctx, node.typeParameters.params[0], scope),
  20815. scope
  20816. );
  20817. }
  20818. const sourceScope = importSourceToScope(
  20819. ctx,
  20820. node.argument,
  20821. scope,
  20822. node.argument.value
  20823. );
  20824. const resolved = resolveTypeReference(ctx, node, sourceScope);
  20825. if (resolved) {
  20826. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  20827. }
  20828. break;
  20829. }
  20830. case "TSTypeQuery":
  20831. {
  20832. const resolved = resolveTypeReference(ctx, node, scope);
  20833. if (resolved) {
  20834. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  20835. }
  20836. }
  20837. break;
  20838. }
  20839. return ctx.error(`Unresolvable type: ${node.type}`, node, scope);
  20840. }
  20841. function typeElementsToMap(ctx, elements, scope = ctxToScope(ctx), typeParameters) {
  20842. const res = { props: {} };
  20843. for (const e of elements) {
  20844. if (e.type === "TSPropertySignature" || e.type === "TSMethodSignature") {
  20845. if (typeParameters) {
  20846. scope = createChildScope(scope);
  20847. scope.isGenericScope = true;
  20848. Object.assign(scope.types, typeParameters);
  20849. }
  20850. e._ownerScope = scope;
  20851. const name = getStringLiteralKey(e);
  20852. if (name !== null) {
  20853. res.props[name] = e;
  20854. } else {
  20855. ctx.error(
  20856. `Unsupported computed key in type referenced by a macro`,
  20857. e.key,
  20858. scope
  20859. );
  20860. }
  20861. } else if (e.type === "TSCallSignatureDeclaration") {
  20862. (res.calls || (res.calls = [])).push(e);
  20863. }
  20864. }
  20865. return res;
  20866. }
  20867. function mergeElements(maps, type) {
  20868. if (maps.length === 1) return maps[0];
  20869. const res = { props: {} };
  20870. const { props: baseProps } = res;
  20871. for (const { props, calls } of maps) {
  20872. for (const key in props) {
  20873. if (!shared.hasOwn(baseProps, key)) {
  20874. baseProps[key] = props[key];
  20875. } else {
  20876. baseProps[key] = createProperty(
  20877. baseProps[key].key,
  20878. {
  20879. type,
  20880. // @ts-expect-error
  20881. types: [baseProps[key], props[key]]
  20882. },
  20883. baseProps[key]._ownerScope,
  20884. baseProps[key].optional || props[key].optional
  20885. );
  20886. }
  20887. }
  20888. if (calls) {
  20889. (res.calls || (res.calls = [])).push(...calls);
  20890. }
  20891. }
  20892. return res;
  20893. }
  20894. function createProperty(key, typeAnnotation, scope, optional) {
  20895. return {
  20896. type: "TSPropertySignature",
  20897. key,
  20898. kind: "get",
  20899. optional,
  20900. typeAnnotation: {
  20901. type: "TSTypeAnnotation",
  20902. typeAnnotation
  20903. },
  20904. _ownerScope: scope
  20905. };
  20906. }
  20907. function resolveInterfaceMembers(ctx, node, scope, typeParameters) {
  20908. const base = typeElementsToMap(
  20909. ctx,
  20910. node.body.body,
  20911. node._ownerScope,
  20912. typeParameters
  20913. );
  20914. if (node.extends) {
  20915. for (const ext of node.extends) {
  20916. try {
  20917. const { props, calls } = resolveTypeElements(ctx, ext, scope);
  20918. for (const key in props) {
  20919. if (!shared.hasOwn(base.props, key)) {
  20920. base.props[key] = props[key];
  20921. }
  20922. }
  20923. if (calls) {
  20924. ;
  20925. (base.calls || (base.calls = [])).push(...calls);
  20926. }
  20927. } catch (e) {
  20928. if (!ctx.silentOnExtendsFailure) {
  20929. ctx.error(
  20930. `Failed to resolve extends base type.
  20931. If this previously worked in 3.2, you can instruct the compiler to ignore this extend by adding /* @vue-ignore */ before it, for example:
  20932. interface Props extends /* @vue-ignore */ Base {}
  20933. Note: both in 3.2 or with the ignore, the properties in the base type are treated as fallthrough attrs at runtime.`,
  20934. ext,
  20935. scope
  20936. );
  20937. }
  20938. }
  20939. }
  20940. }
  20941. return base;
  20942. }
  20943. function resolveMappedType(ctx, node, scope, typeParameters) {
  20944. const res = { props: {} };
  20945. let keys;
  20946. if (node.nameType) {
  20947. const { name, constraint } = node.typeParameter;
  20948. scope = createChildScope(scope);
  20949. Object.assign(scope.types, { ...typeParameters, [name]: constraint });
  20950. keys = resolveStringType(ctx, node.nameType, scope);
  20951. } else {
  20952. keys = resolveStringType(ctx, node.typeParameter.constraint, scope);
  20953. }
  20954. for (const key of keys) {
  20955. res.props[key] = createProperty(
  20956. {
  20957. type: "Identifier",
  20958. name: key
  20959. },
  20960. node.typeAnnotation,
  20961. scope,
  20962. !!node.optional
  20963. );
  20964. }
  20965. return res;
  20966. }
  20967. function resolveIndexType(ctx, node, scope) {
  20968. var _a, _b;
  20969. if (node.indexType.type === "TSNumberKeyword") {
  20970. return resolveArrayElementType(ctx, node.objectType, scope);
  20971. }
  20972. const { indexType, objectType } = node;
  20973. const types = [];
  20974. let keys;
  20975. let resolved;
  20976. if (indexType.type === "TSStringKeyword") {
  20977. resolved = resolveTypeElements(ctx, objectType, scope);
  20978. keys = Object.keys(resolved.props);
  20979. } else {
  20980. keys = resolveStringType(ctx, indexType, scope);
  20981. resolved = resolveTypeElements(ctx, objectType, scope);
  20982. }
  20983. for (const key of keys) {
  20984. const targetType = (_b = (_a = resolved.props[key]) == null ? void 0 : _a.typeAnnotation) == null ? void 0 : _b.typeAnnotation;
  20985. if (targetType) {
  20986. targetType._ownerScope = resolved.props[key]._ownerScope;
  20987. types.push(targetType);
  20988. }
  20989. }
  20990. return types;
  20991. }
  20992. function resolveArrayElementType(ctx, node, scope) {
  20993. if (node.type === "TSArrayType") {
  20994. return [node.elementType];
  20995. }
  20996. if (node.type === "TSTupleType") {
  20997. return node.elementTypes.map(
  20998. (t) => t.type === "TSNamedTupleMember" ? t.elementType : t
  20999. );
  21000. }
  21001. if (node.type === "TSTypeReference") {
  21002. if (getReferenceName(node) === "Array" && node.typeParameters) {
  21003. return node.typeParameters.params;
  21004. } else {
  21005. const resolved = resolveTypeReference(ctx, node, scope);
  21006. if (resolved) {
  21007. return resolveArrayElementType(ctx, resolved, scope);
  21008. }
  21009. }
  21010. }
  21011. return ctx.error(
  21012. "Failed to resolve element type from target type",
  21013. node,
  21014. scope
  21015. );
  21016. }
  21017. function resolveStringType(ctx, node, scope, typeParameters) {
  21018. switch (node.type) {
  21019. case "StringLiteral":
  21020. return [node.value];
  21021. case "TSLiteralType":
  21022. return resolveStringType(ctx, node.literal, scope, typeParameters);
  21023. case "TSUnionType":
  21024. return node.types.map((t) => resolveStringType(ctx, t, scope, typeParameters)).flat();
  21025. case "TemplateLiteral": {
  21026. return resolveTemplateKeys(ctx, node, scope);
  21027. }
  21028. case "TSTypeReference": {
  21029. const resolved = resolveTypeReference(ctx, node, scope);
  21030. if (resolved) {
  21031. return resolveStringType(ctx, resolved, scope, typeParameters);
  21032. }
  21033. if (node.typeName.type === "Identifier") {
  21034. const name = node.typeName.name;
  21035. if (typeParameters && typeParameters[name]) {
  21036. return resolveStringType(
  21037. ctx,
  21038. typeParameters[name],
  21039. scope,
  21040. typeParameters
  21041. );
  21042. }
  21043. const getParam = (index = 0) => resolveStringType(
  21044. ctx,
  21045. node.typeParameters.params[index],
  21046. scope,
  21047. typeParameters
  21048. );
  21049. switch (name) {
  21050. case "Extract":
  21051. return getParam(1);
  21052. case "Exclude": {
  21053. const excluded = getParam(1);
  21054. return getParam().filter((s) => !excluded.includes(s));
  21055. }
  21056. case "Uppercase":
  21057. return getParam().map((s) => s.toUpperCase());
  21058. case "Lowercase":
  21059. return getParam().map((s) => s.toLowerCase());
  21060. case "Capitalize":
  21061. return getParam().map(shared.capitalize);
  21062. case "Uncapitalize":
  21063. return getParam().map((s) => s[0].toLowerCase() + s.slice(1));
  21064. default:
  21065. ctx.error(
  21066. "Unsupported type when resolving index type",
  21067. node.typeName,
  21068. scope
  21069. );
  21070. }
  21071. }
  21072. }
  21073. }
  21074. return ctx.error("Failed to resolve index type into finite keys", node, scope);
  21075. }
  21076. function resolveTemplateKeys(ctx, node, scope) {
  21077. if (!node.expressions.length) {
  21078. return [node.quasis[0].value.raw];
  21079. }
  21080. const res = [];
  21081. const e = node.expressions[0];
  21082. const q = node.quasis[0];
  21083. const leading = q ? q.value.raw : ``;
  21084. const resolved = resolveStringType(ctx, e, scope);
  21085. const restResolved = resolveTemplateKeys(
  21086. ctx,
  21087. {
  21088. ...node,
  21089. expressions: node.expressions.slice(1),
  21090. quasis: q ? node.quasis.slice(1) : node.quasis
  21091. },
  21092. scope
  21093. );
  21094. for (const r of resolved) {
  21095. for (const rr of restResolved) {
  21096. res.push(leading + r + rr);
  21097. }
  21098. }
  21099. return res;
  21100. }
  21101. const SupportedBuiltinsSet = /* @__PURE__ */ new Set([
  21102. "Partial",
  21103. "Required",
  21104. "Readonly",
  21105. "Pick",
  21106. "Omit"
  21107. ]);
  21108. function resolveBuiltin(ctx, node, name, scope, typeParameters) {
  21109. const t = resolveTypeElements(
  21110. ctx,
  21111. node.typeParameters.params[0],
  21112. scope,
  21113. typeParameters
  21114. );
  21115. switch (name) {
  21116. case "Partial": {
  21117. const res2 = { props: {}, calls: t.calls };
  21118. Object.keys(t.props).forEach((key) => {
  21119. res2.props[key] = { ...t.props[key], optional: true };
  21120. });
  21121. return res2;
  21122. }
  21123. case "Required": {
  21124. const res2 = { props: {}, calls: t.calls };
  21125. Object.keys(t.props).forEach((key) => {
  21126. res2.props[key] = { ...t.props[key], optional: false };
  21127. });
  21128. return res2;
  21129. }
  21130. case "Readonly":
  21131. return t;
  21132. case "Pick": {
  21133. const picked = resolveStringType(
  21134. ctx,
  21135. node.typeParameters.params[1],
  21136. scope,
  21137. typeParameters
  21138. );
  21139. const res2 = { props: {}, calls: t.calls };
  21140. for (const key of picked) {
  21141. res2.props[key] = t.props[key];
  21142. }
  21143. return res2;
  21144. }
  21145. case "Omit":
  21146. const omitted = resolveStringType(
  21147. ctx,
  21148. node.typeParameters.params[1],
  21149. scope,
  21150. typeParameters
  21151. );
  21152. const res = { props: {}, calls: t.calls };
  21153. for (const key in t.props) {
  21154. if (!omitted.includes(key)) {
  21155. res.props[key] = t.props[key];
  21156. }
  21157. }
  21158. return res;
  21159. }
  21160. }
  21161. function resolveTypeReference(ctx, node, scope, name, onlyExported = false) {
  21162. const canCache = !(scope == null ? void 0 : scope.isGenericScope);
  21163. if (canCache && node._resolvedReference) {
  21164. return node._resolvedReference;
  21165. }
  21166. const resolved = innerResolveTypeReference(
  21167. ctx,
  21168. scope || ctxToScope(ctx),
  21169. name || getReferenceName(node),
  21170. node,
  21171. onlyExported
  21172. );
  21173. return canCache ? node._resolvedReference = resolved : resolved;
  21174. }
  21175. function innerResolveTypeReference(ctx, scope, name, node, onlyExported) {
  21176. if (typeof name === "string") {
  21177. if (scope.imports[name]) {
  21178. return resolveTypeFromImport(ctx, node, name, scope);
  21179. } else {
  21180. const lookupSource = node.type === "TSTypeQuery" ? onlyExported ? scope.exportedDeclares : scope.declares : onlyExported ? scope.exportedTypes : scope.types;
  21181. if (lookupSource[name]) {
  21182. return lookupSource[name];
  21183. } else {
  21184. const globalScopes = resolveGlobalScope(ctx);
  21185. if (globalScopes) {
  21186. for (const s of globalScopes) {
  21187. const src = node.type === "TSTypeQuery" ? s.declares : s.types;
  21188. if (src[name]) {
  21189. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(s.filename);
  21190. return src[name];
  21191. }
  21192. }
  21193. }
  21194. }
  21195. }
  21196. } else {
  21197. let ns = innerResolveTypeReference(ctx, scope, name[0], node, onlyExported);
  21198. if (ns) {
  21199. if (ns.type !== "TSModuleDeclaration") {
  21200. ns = ns._ns;
  21201. }
  21202. if (ns) {
  21203. const childScope = moduleDeclToScope(ctx, ns, ns._ownerScope || scope);
  21204. return innerResolveTypeReference(
  21205. ctx,
  21206. childScope,
  21207. name.length > 2 ? name.slice(1) : name[name.length - 1],
  21208. node,
  21209. !ns.declare
  21210. );
  21211. }
  21212. }
  21213. }
  21214. }
  21215. function getReferenceName(node) {
  21216. const ref = node.type === "TSTypeReference" ? node.typeName : node.type === "TSExpressionWithTypeArguments" ? node.expression : node.type === "TSImportType" ? node.qualifier : node.exprName;
  21217. if ((ref == null ? void 0 : ref.type) === "Identifier") {
  21218. return ref.name;
  21219. } else if ((ref == null ? void 0 : ref.type) === "TSQualifiedName") {
  21220. return qualifiedNameToPath(ref);
  21221. } else {
  21222. return "default";
  21223. }
  21224. }
  21225. function qualifiedNameToPath(node) {
  21226. if (node.type === "Identifier") {
  21227. return [node.name];
  21228. } else {
  21229. return [...qualifiedNameToPath(node.left), node.right.name];
  21230. }
  21231. }
  21232. function resolveGlobalScope(ctx) {
  21233. if (ctx.options.globalTypeFiles) {
  21234. const fs = resolveFS(ctx);
  21235. if (!fs) {
  21236. throw new Error("[vue/compiler-sfc] globalTypeFiles requires fs access.");
  21237. }
  21238. return ctx.options.globalTypeFiles.map(
  21239. (file) => fileToScope(ctx, normalizePath(file), true)
  21240. );
  21241. }
  21242. }
  21243. let ts;
  21244. let loadTS;
  21245. function registerTS(_loadTS) {
  21246. loadTS = () => {
  21247. try {
  21248. return _loadTS();
  21249. } catch (err) {
  21250. if (typeof err.message === "string" && err.message.includes("Cannot find module")) {
  21251. throw new Error(
  21252. 'Failed to load TypeScript, which is required for resolving imported types. Please make sure "TypeScript" is installed as a project dependency.'
  21253. );
  21254. } else {
  21255. throw new Error(
  21256. "Failed to load TypeScript for resolving imported types."
  21257. );
  21258. }
  21259. }
  21260. };
  21261. }
  21262. function resolveFS(ctx) {
  21263. if (ctx.fs) {
  21264. return ctx.fs;
  21265. }
  21266. if (!ts && loadTS) {
  21267. ts = loadTS();
  21268. }
  21269. const fs = ctx.options.fs || (ts == null ? void 0 : ts.sys);
  21270. if (!fs) {
  21271. return;
  21272. }
  21273. return ctx.fs = {
  21274. fileExists(file) {
  21275. if (file.endsWith(".vue.ts") && !file.endsWith(".d.vue.ts")) {
  21276. file = file.replace(/\.ts$/, "");
  21277. }
  21278. return fs.fileExists(file);
  21279. },
  21280. readFile(file) {
  21281. if (file.endsWith(".vue.ts") && !file.endsWith(".d.vue.ts")) {
  21282. file = file.replace(/\.ts$/, "");
  21283. }
  21284. return fs.readFile(file);
  21285. },
  21286. realpath: fs.realpath
  21287. };
  21288. }
  21289. function resolveTypeFromImport(ctx, node, name, scope) {
  21290. const { source, imported } = scope.imports[name];
  21291. const sourceScope = importSourceToScope(ctx, node, scope, source);
  21292. return resolveTypeReference(ctx, node, sourceScope, imported, true);
  21293. }
  21294. function importSourceToScope(ctx, node, scope, source) {
  21295. let fs;
  21296. try {
  21297. fs = resolveFS(ctx);
  21298. } catch (err) {
  21299. return ctx.error(err.message, node, scope);
  21300. }
  21301. if (!fs) {
  21302. return ctx.error(
  21303. `No fs option provided to \`compileScript\` in non-Node environment. File system access is required for resolving imported types.`,
  21304. node,
  21305. scope
  21306. );
  21307. }
  21308. let resolved = scope.resolvedImportSources[source];
  21309. if (!resolved) {
  21310. if (source.startsWith("..")) {
  21311. const osSpecificJoinFn = process__namespace.platform === "win32" ? path$1.join : joinPaths;
  21312. const filename = osSpecificJoinFn(path$1.dirname(scope.filename), source);
  21313. resolved = resolveExt(filename, fs);
  21314. } else if (source[0] === ".") {
  21315. const filename = joinPaths(path$1.dirname(scope.filename), source);
  21316. resolved = resolveExt(filename, fs);
  21317. } else {
  21318. if (!ts) {
  21319. if (loadTS) ts = loadTS();
  21320. if (!ts) {
  21321. return ctx.error(
  21322. `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.`,
  21323. node,
  21324. scope
  21325. );
  21326. }
  21327. }
  21328. resolved = resolveWithTS(scope.filename, source, ts, fs);
  21329. }
  21330. if (resolved) {
  21331. resolved = scope.resolvedImportSources[source] = normalizePath(resolved);
  21332. }
  21333. }
  21334. if (resolved) {
  21335. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(resolved);
  21336. return fileToScope(ctx, resolved);
  21337. } else {
  21338. return ctx.error(
  21339. `Failed to resolve import source ${JSON.stringify(source)}.`,
  21340. node,
  21341. scope
  21342. );
  21343. }
  21344. }
  21345. function resolveExt(filename, fs) {
  21346. let moduleType = "u";
  21347. if (filename.endsWith(".mjs")) {
  21348. moduleType = "m";
  21349. } else if (filename.endsWith(".cjs")) {
  21350. moduleType = "c";
  21351. }
  21352. filename = filename.replace(/\.[cm]?jsx?$/, "");
  21353. const tryResolve = (filename2) => {
  21354. if (fs.fileExists(filename2)) return filename2;
  21355. };
  21356. const resolveTs = () => tryResolve(filename + `.ts`) || tryResolve(filename + `.tsx`) || tryResolve(filename + `.d.ts`);
  21357. const resolveMts = () => tryResolve(filename + `.mts`) || tryResolve(filename + `.d.mts`);
  21358. const resolveCts = () => tryResolve(filename + `.cts`) || tryResolve(filename + `.d.cts`);
  21359. return tryResolve(filename) || // For explicit .mjs/.cjs imports, prefer .mts/.cts declarations first.
  21360. (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`));
  21361. }
  21362. const tsConfigCache = createCache();
  21363. const tsConfigRefMap = /* @__PURE__ */ new Map();
  21364. function resolveWithTS(containingFile, source, ts2, fs) {
  21365. var _a, _b;
  21366. const configPath = ts2.findConfigFile(containingFile, fs.fileExists);
  21367. let tsCompilerOptions;
  21368. let tsResolveCache;
  21369. if (configPath) {
  21370. let configs;
  21371. const normalizedConfigPath = normalizePath(configPath);
  21372. const cached = tsConfigCache.get(normalizedConfigPath);
  21373. if (!cached) {
  21374. configs = loadTSConfig(configPath, ts2, fs).map((config) => ({ config }));
  21375. tsConfigCache.set(normalizedConfigPath, configs);
  21376. } else {
  21377. configs = cached;
  21378. }
  21379. let matchedConfig;
  21380. if (configs.length === 1) {
  21381. matchedConfig = configs[0];
  21382. } else {
  21383. const [major, minor] = ts2.versionMajorMinor.split(".").map(Number);
  21384. const getPattern = (base, p) => {
  21385. const supportsConfigDir = major > 5 || major === 5 && minor >= 5;
  21386. return p.startsWith("${configDir}") && supportsConfigDir ? normalizePath(p.replace("${configDir}", path$1.dirname(configPath))) : joinPaths(base, p);
  21387. };
  21388. for (const c of configs) {
  21389. const base = normalizePath(
  21390. c.config.options.pathsBasePath || path$1.dirname(c.config.options.configFilePath)
  21391. );
  21392. const included = (_a = c.config.raw) == null ? void 0 : _a.include;
  21393. const excluded = (_b = c.config.raw) == null ? void 0 : _b.exclude;
  21394. if (!included && (!base || containingFile.startsWith(base)) || (included == null ? void 0 : included.some((p) => minimatch(containingFile, getPattern(base, p))))) {
  21395. if (excluded && excluded.some((p) => minimatch(containingFile, getPattern(base, p)))) {
  21396. continue;
  21397. }
  21398. matchedConfig = c;
  21399. break;
  21400. }
  21401. }
  21402. if (!matchedConfig) {
  21403. matchedConfig = configs[configs.length - 1];
  21404. }
  21405. }
  21406. tsCompilerOptions = matchedConfig.config.options;
  21407. tsResolveCache = matchedConfig.cache || (matchedConfig.cache = ts2.createModuleResolutionCache(
  21408. process__namespace.cwd(),
  21409. createGetCanonicalFileName(ts2.sys.useCaseSensitiveFileNames),
  21410. tsCompilerOptions
  21411. ));
  21412. } else {
  21413. tsCompilerOptions = {};
  21414. }
  21415. const res = ts2.resolveModuleName(
  21416. source,
  21417. containingFile,
  21418. tsCompilerOptions,
  21419. fs,
  21420. tsResolveCache
  21421. );
  21422. if (res.resolvedModule) {
  21423. let filename = res.resolvedModule.resolvedFileName;
  21424. if (filename.endsWith(".vue.ts") && !filename.endsWith(".d.vue.ts")) {
  21425. filename = filename.replace(/\.ts$/, "");
  21426. }
  21427. return fs.realpath ? fs.realpath(filename) : filename;
  21428. }
  21429. }
  21430. function loadTSConfig(configPath, ts2, fs, visited = /* @__PURE__ */ new Set()) {
  21431. const parseConfigHost = ts2.sys;
  21432. const config = ts2.parseJsonConfigFileContent(
  21433. ts2.readConfigFile(configPath, fs.readFile).config,
  21434. parseConfigHost,
  21435. path$1.dirname(configPath),
  21436. void 0,
  21437. configPath
  21438. );
  21439. const res = [config];
  21440. visited.add(configPath);
  21441. if (config.projectReferences) {
  21442. for (const ref of config.projectReferences) {
  21443. const refPath = ts2.resolveProjectReferencePath(ref);
  21444. if (visited.has(refPath) || !fs.fileExists(refPath)) {
  21445. continue;
  21446. }
  21447. tsConfigRefMap.set(refPath, configPath);
  21448. res.unshift(...loadTSConfig(refPath, ts2, fs, visited));
  21449. }
  21450. }
  21451. return res;
  21452. }
  21453. const fileToScopeCache = createCache();
  21454. function invalidateTypeCache(filename) {
  21455. filename = normalizePath(filename);
  21456. fileToScopeCache.delete(filename);
  21457. tsConfigCache.delete(filename);
  21458. const affectedConfig = tsConfigRefMap.get(filename);
  21459. if (affectedConfig) tsConfigCache.delete(affectedConfig);
  21460. }
  21461. function fileToScope(ctx, filename, asGlobal = false) {
  21462. const cached = fileToScopeCache.get(filename);
  21463. if (cached) {
  21464. return cached;
  21465. }
  21466. const fs = resolveFS(ctx);
  21467. const source = fs.readFile(filename) || "";
  21468. const body = parseFile(filename, source, fs, ctx.options.babelParserPlugins);
  21469. const scope = new TypeScope(filename, source, 0, recordImports(body));
  21470. recordTypes(ctx, body, scope, asGlobal);
  21471. fileToScopeCache.set(filename, scope);
  21472. return scope;
  21473. }
  21474. function parseFile(filename, content, fs, parserPlugins) {
  21475. const ext = path$1.extname(filename);
  21476. if (ext === ".ts" || ext === ".mts" || ext === ".tsx" || ext === ".cts" || ext === ".mtsx") {
  21477. return parser$2.parse(content, {
  21478. plugins: resolveParserPlugins(
  21479. ext.slice(1),
  21480. parserPlugins,
  21481. /\.d\.[cm]?ts$/.test(filename)
  21482. ),
  21483. sourceType: "module"
  21484. }).program.body;
  21485. }
  21486. const isUnknownTypeSource = !/\.[cm]?[tj]sx?$/.test(filename);
  21487. const arbitraryTypeSource = `${filename.slice(0, -ext.length)}.d${ext}.ts`;
  21488. const hasArbitraryTypeDeclaration = isUnknownTypeSource && fs.fileExists(arbitraryTypeSource);
  21489. if (hasArbitraryTypeDeclaration) {
  21490. return parser$2.parse(fs.readFile(arbitraryTypeSource), {
  21491. plugins: resolveParserPlugins("ts", parserPlugins, true),
  21492. sourceType: "module"
  21493. }).program.body;
  21494. }
  21495. if (ext === ".vue") {
  21496. const {
  21497. descriptor: { script, scriptSetup }
  21498. } = parse$1(content);
  21499. if (!script && !scriptSetup) {
  21500. return [];
  21501. }
  21502. const scriptOffset = script ? script.loc.start.offset : Infinity;
  21503. const scriptSetupOffset = scriptSetup ? scriptSetup.loc.start.offset : Infinity;
  21504. const firstBlock = scriptOffset < scriptSetupOffset ? script : scriptSetup;
  21505. const secondBlock = scriptOffset < scriptSetupOffset ? scriptSetup : script;
  21506. let scriptContent = " ".repeat(Math.min(scriptOffset, scriptSetupOffset)) + firstBlock.content;
  21507. if (secondBlock) {
  21508. scriptContent += " ".repeat(secondBlock.loc.start.offset - script.loc.end.offset) + secondBlock.content;
  21509. }
  21510. const lang = (script == null ? void 0 : script.lang) || (scriptSetup == null ? void 0 : scriptSetup.lang);
  21511. return parser$2.parse(scriptContent, {
  21512. plugins: resolveParserPlugins(lang, parserPlugins),
  21513. sourceType: "module"
  21514. }).program.body;
  21515. }
  21516. return [];
  21517. }
  21518. function ctxToScope(ctx) {
  21519. if (ctx.scope) {
  21520. return ctx.scope;
  21521. }
  21522. const body = "ast" in ctx ? ctx.ast : ctx.scriptAst ? [...ctx.scriptAst.body, ...ctx.scriptSetupAst.body] : ctx.scriptSetupAst.body;
  21523. const scope = new TypeScope(
  21524. ctx.filename,
  21525. ctx.source,
  21526. "startOffset" in ctx ? ctx.startOffset : 0,
  21527. "userImports" in ctx ? Object.create(ctx.userImports) : recordImports(body)
  21528. );
  21529. recordTypes(ctx, body, scope);
  21530. return ctx.scope = scope;
  21531. }
  21532. function moduleDeclToScope(ctx, node, parentScope) {
  21533. if (node._resolvedChildScope) {
  21534. return node._resolvedChildScope;
  21535. }
  21536. const scope = createChildScope(parentScope);
  21537. if (node.body.type === "TSModuleDeclaration") {
  21538. const decl = node.body;
  21539. decl._ownerScope = scope;
  21540. const id = getId(decl.id);
  21541. scope.types[id] = scope.exportedTypes[id] = decl;
  21542. } else {
  21543. recordTypes(ctx, node.body.body, scope);
  21544. }
  21545. return node._resolvedChildScope = scope;
  21546. }
  21547. function createChildScope(parentScope) {
  21548. return new TypeScope(
  21549. parentScope.filename,
  21550. parentScope.source,
  21551. parentScope.offset,
  21552. Object.create(parentScope.imports),
  21553. Object.create(parentScope.types),
  21554. Object.create(parentScope.declares)
  21555. );
  21556. }
  21557. const importExportRE = /^Import|^Export/;
  21558. function recordTypes(ctx, body, scope, asGlobal = false) {
  21559. const { types, declares, exportedTypes, exportedDeclares, imports } = scope;
  21560. const isAmbient = asGlobal ? !body.some((s) => importExportRE.test(s.type)) : false;
  21561. for (const stmt of body) {
  21562. if (asGlobal) {
  21563. if (isAmbient) {
  21564. if (stmt.declare) {
  21565. recordType(stmt, types, declares);
  21566. }
  21567. } else if (stmt.type === "TSModuleDeclaration" && stmt.global) {
  21568. for (const s of stmt.body.body) {
  21569. if (s.type === "ExportNamedDeclaration" && s.declaration) {
  21570. recordType(s.declaration, types, declares);
  21571. } else {
  21572. recordType(s, types, declares);
  21573. }
  21574. }
  21575. }
  21576. } else {
  21577. recordType(stmt, types, declares);
  21578. }
  21579. }
  21580. if (!asGlobal) {
  21581. for (const stmt of body) {
  21582. if (stmt.type === "ExportNamedDeclaration") {
  21583. if (stmt.declaration) {
  21584. recordType(stmt.declaration, types, declares);
  21585. recordType(stmt.declaration, exportedTypes, exportedDeclares);
  21586. } else {
  21587. for (const spec of stmt.specifiers) {
  21588. if (spec.type === "ExportSpecifier") {
  21589. const local = spec.local.name;
  21590. const exported = getId(spec.exported);
  21591. if (stmt.source) {
  21592. imports[exported] = {
  21593. source: stmt.source.value,
  21594. imported: local
  21595. };
  21596. exportedTypes[exported] = {
  21597. type: "TSTypeReference",
  21598. typeName: {
  21599. type: "Identifier",
  21600. name: local
  21601. },
  21602. _ownerScope: scope
  21603. };
  21604. } else if (types[local]) {
  21605. exportedTypes[exported] = types[local];
  21606. }
  21607. }
  21608. }
  21609. }
  21610. } else if (stmt.type === "ExportAllDeclaration") {
  21611. const sourceScope = importSourceToScope(
  21612. ctx,
  21613. stmt.source,
  21614. scope,
  21615. stmt.source.value
  21616. );
  21617. Object.assign(scope.exportedTypes, sourceScope.exportedTypes);
  21618. } else if (stmt.type === "ExportDefaultDeclaration" && stmt.declaration) {
  21619. if (stmt.declaration.type !== "Identifier") {
  21620. recordType(stmt.declaration, types, declares, "default");
  21621. recordType(
  21622. stmt.declaration,
  21623. exportedTypes,
  21624. exportedDeclares,
  21625. "default"
  21626. );
  21627. } else if (types[stmt.declaration.name]) {
  21628. exportedTypes["default"] = types[stmt.declaration.name];
  21629. }
  21630. }
  21631. }
  21632. }
  21633. for (const key of Object.keys(types)) {
  21634. const node = types[key];
  21635. node._ownerScope = scope;
  21636. if (node._ns) node._ns._ownerScope = scope;
  21637. }
  21638. for (const key of Object.keys(declares)) {
  21639. declares[key]._ownerScope = scope;
  21640. }
  21641. }
  21642. function recordType(node, types, declares, overwriteId) {
  21643. switch (node.type) {
  21644. case "TSInterfaceDeclaration":
  21645. case "TSEnumDeclaration":
  21646. case "TSModuleDeclaration": {
  21647. if (node.type === "TSModuleDeclaration" && node.global) {
  21648. const body = node.body;
  21649. for (const s of body.body) {
  21650. if (s.type === "ExportNamedDeclaration" && s.declaration) {
  21651. recordType(s.declaration, types, declares);
  21652. } else {
  21653. recordType(s, types, declares);
  21654. }
  21655. }
  21656. break;
  21657. }
  21658. const id = overwriteId || getId(node.id);
  21659. let existing = types[id];
  21660. if (existing) {
  21661. if (node.type === "TSModuleDeclaration") {
  21662. if (existing.type === "TSModuleDeclaration") {
  21663. mergeNamespaces(existing, node);
  21664. } else {
  21665. attachNamespace(existing, node);
  21666. }
  21667. break;
  21668. }
  21669. if (existing.type === "TSModuleDeclaration") {
  21670. types[id] = node;
  21671. attachNamespace(node, existing);
  21672. break;
  21673. }
  21674. if (existing.type !== node.type) {
  21675. break;
  21676. }
  21677. if (node.type === "TSInterfaceDeclaration") {
  21678. existing.body.body.push(...node.body.body);
  21679. } else {
  21680. existing.members.push(...node.members);
  21681. }
  21682. } else {
  21683. types[id] = node;
  21684. }
  21685. break;
  21686. }
  21687. case "ClassDeclaration":
  21688. if (overwriteId || node.id) types[overwriteId || getId(node.id)] = node;
  21689. break;
  21690. case "TSTypeAliasDeclaration":
  21691. types[node.id.name] = node.typeParameters ? node : node.typeAnnotation;
  21692. break;
  21693. case "TSDeclareFunction":
  21694. if (node.id) declares[node.id.name] = node;
  21695. break;
  21696. case "VariableDeclaration": {
  21697. if (node.declare) {
  21698. for (const decl of node.declarations) {
  21699. if (decl.id.type === "Identifier" && decl.id.typeAnnotation) {
  21700. declares[decl.id.name] = decl.id.typeAnnotation.typeAnnotation;
  21701. }
  21702. }
  21703. }
  21704. break;
  21705. }
  21706. }
  21707. }
  21708. function mergeNamespaces(to, from) {
  21709. const toBody = to.body;
  21710. const fromBody = from.body;
  21711. if (toBody.type === "TSModuleDeclaration") {
  21712. if (fromBody.type === "TSModuleDeclaration") {
  21713. mergeNamespaces(toBody, fromBody);
  21714. } else {
  21715. fromBody.body.push({
  21716. type: "ExportNamedDeclaration",
  21717. declaration: toBody,
  21718. exportKind: "type",
  21719. specifiers: []
  21720. });
  21721. }
  21722. } else if (fromBody.type === "TSModuleDeclaration") {
  21723. toBody.body.push({
  21724. type: "ExportNamedDeclaration",
  21725. declaration: fromBody,
  21726. exportKind: "type",
  21727. specifiers: []
  21728. });
  21729. } else {
  21730. toBody.body.push(...fromBody.body);
  21731. }
  21732. }
  21733. function attachNamespace(to, ns) {
  21734. if (!to._ns) {
  21735. to._ns = ns;
  21736. } else {
  21737. mergeNamespaces(to._ns, ns);
  21738. }
  21739. }
  21740. function recordImports(body) {
  21741. const imports = /* @__PURE__ */ Object.create(null);
  21742. for (const s of body) {
  21743. recordImport(s, imports);
  21744. }
  21745. return imports;
  21746. }
  21747. function recordImport(node, imports) {
  21748. if (node.type !== "ImportDeclaration") {
  21749. return;
  21750. }
  21751. for (const s of node.specifiers) {
  21752. imports[s.local.name] = {
  21753. imported: getImportedName(s),
  21754. source: node.source.value
  21755. };
  21756. }
  21757. }
  21758. function inferRuntimeType(ctx, node, scope = node._ownerScope || ctxToScope(ctx), isKeyOf = false, typeParameters) {
  21759. if (node.leadingComments && node.leadingComments.some((c) => c.value.includes("@vue-ignore"))) {
  21760. return [UNKNOWN_TYPE];
  21761. }
  21762. const prevSilent = ctx.silentOnExtendsFailure;
  21763. ctx.silentOnExtendsFailure = true;
  21764. try {
  21765. switch (node.type) {
  21766. case "TSStringKeyword":
  21767. return ["String"];
  21768. case "TSNumberKeyword":
  21769. return ["Number"];
  21770. case "TSBooleanKeyword":
  21771. return ["Boolean"];
  21772. case "TSObjectKeyword":
  21773. return ["Object"];
  21774. case "TSNullKeyword":
  21775. return ["null"];
  21776. case "TSTypeLiteral":
  21777. case "TSInterfaceDeclaration": {
  21778. const types = /* @__PURE__ */ new Set();
  21779. const members = node.type === "TSTypeLiteral" ? node.members : node.body.body;
  21780. for (const m of members) {
  21781. if (isKeyOf) {
  21782. if (m.type === "TSPropertySignature" && m.key.type === "NumericLiteral") {
  21783. types.add("Number");
  21784. } else if (m.type === "TSIndexSignature") {
  21785. const annotation = m.parameters[0].typeAnnotation;
  21786. if (annotation && annotation.type !== "Noop") {
  21787. const type = inferRuntimeType(
  21788. ctx,
  21789. annotation.typeAnnotation,
  21790. scope
  21791. )[0];
  21792. if (type === UNKNOWN_TYPE) return [UNKNOWN_TYPE];
  21793. types.add(type);
  21794. }
  21795. } else {
  21796. types.add("String");
  21797. }
  21798. } else if (m.type === "TSCallSignatureDeclaration" || m.type === "TSConstructSignatureDeclaration") {
  21799. types.add("Function");
  21800. } else {
  21801. types.add("Object");
  21802. }
  21803. }
  21804. return types.size ? Array.from(types) : [isKeyOf ? UNKNOWN_TYPE : "Object"];
  21805. }
  21806. case "TSPropertySignature":
  21807. if (node.typeAnnotation) {
  21808. return inferRuntimeType(
  21809. ctx,
  21810. node.typeAnnotation.typeAnnotation,
  21811. scope
  21812. );
  21813. }
  21814. break;
  21815. case "TSMethodSignature":
  21816. case "TSFunctionType":
  21817. return ["Function"];
  21818. case "TSArrayType":
  21819. case "TSTupleType":
  21820. return ["Array"];
  21821. case "TSLiteralType":
  21822. switch (node.literal.type) {
  21823. case "StringLiteral":
  21824. return ["String"];
  21825. case "BooleanLiteral":
  21826. return ["Boolean"];
  21827. case "NumericLiteral":
  21828. case "BigIntLiteral":
  21829. return ["Number"];
  21830. default:
  21831. return [UNKNOWN_TYPE];
  21832. }
  21833. case "TSTypeReference": {
  21834. const resolved = resolveTypeReference(ctx, node, scope);
  21835. if (resolved) {
  21836. if (resolved.type === "TSTypeAliasDeclaration") {
  21837. if (resolved.typeAnnotation.type === "TSFunctionType") {
  21838. return ["Function"];
  21839. }
  21840. if (node.typeParameters) {
  21841. const typeParams = /* @__PURE__ */ Object.create(null);
  21842. if (resolved.typeParameters) {
  21843. resolved.typeParameters.params.forEach((p, i) => {
  21844. typeParams[p.name] = node.typeParameters.params[i];
  21845. });
  21846. }
  21847. return inferRuntimeType(
  21848. ctx,
  21849. resolved.typeAnnotation,
  21850. resolved._ownerScope,
  21851. isKeyOf,
  21852. typeParams
  21853. );
  21854. }
  21855. }
  21856. return inferRuntimeType(ctx, resolved, resolved._ownerScope, isKeyOf);
  21857. }
  21858. if (node.typeName.type === "Identifier") {
  21859. if (typeParameters && typeParameters[node.typeName.name]) {
  21860. return inferRuntimeType(
  21861. ctx,
  21862. typeParameters[node.typeName.name],
  21863. scope,
  21864. isKeyOf,
  21865. typeParameters
  21866. );
  21867. }
  21868. if (isKeyOf) {
  21869. switch (node.typeName.name) {
  21870. case "String":
  21871. case "Array":
  21872. case "ArrayLike":
  21873. case "Parameters":
  21874. case "ConstructorParameters":
  21875. case "ReadonlyArray":
  21876. return ["String", "Number"];
  21877. // TS built-in utility types
  21878. case "Record":
  21879. case "Partial":
  21880. case "Required":
  21881. case "Readonly":
  21882. if (node.typeParameters && node.typeParameters.params[0]) {
  21883. return inferRuntimeType(
  21884. ctx,
  21885. node.typeParameters.params[0],
  21886. scope,
  21887. true
  21888. );
  21889. }
  21890. break;
  21891. case "Pick":
  21892. case "Extract":
  21893. if (node.typeParameters && node.typeParameters.params[1]) {
  21894. return inferRuntimeType(
  21895. ctx,
  21896. node.typeParameters.params[1],
  21897. scope
  21898. );
  21899. }
  21900. break;
  21901. case "Function":
  21902. case "Object":
  21903. case "Set":
  21904. case "Map":
  21905. case "WeakSet":
  21906. case "WeakMap":
  21907. case "Date":
  21908. case "Promise":
  21909. case "Error":
  21910. case "Uppercase":
  21911. case "Lowercase":
  21912. case "Capitalize":
  21913. case "Uncapitalize":
  21914. case "ReadonlyMap":
  21915. case "ReadonlySet":
  21916. return ["String"];
  21917. }
  21918. } else {
  21919. switch (node.typeName.name) {
  21920. case "Array":
  21921. case "Function":
  21922. case "Object":
  21923. case "Set":
  21924. case "Map":
  21925. case "WeakSet":
  21926. case "WeakMap":
  21927. case "Date":
  21928. case "Promise":
  21929. case "Error":
  21930. return [node.typeName.name];
  21931. // TS built-in utility types
  21932. // https://www.typescriptlang.org/docs/handbook/utility-types.html
  21933. case "Partial":
  21934. case "Required":
  21935. case "Readonly":
  21936. case "Record":
  21937. case "Pick":
  21938. case "Omit":
  21939. case "InstanceType":
  21940. return ["Object"];
  21941. case "Uppercase":
  21942. case "Lowercase":
  21943. case "Capitalize":
  21944. case "Uncapitalize":
  21945. return ["String"];
  21946. case "Parameters":
  21947. case "ConstructorParameters":
  21948. case "ReadonlyArray":
  21949. return ["Array"];
  21950. case "ReadonlyMap":
  21951. return ["Map"];
  21952. case "ReadonlySet":
  21953. return ["Set"];
  21954. case "NonNullable":
  21955. if (node.typeParameters && node.typeParameters.params[0]) {
  21956. return inferRuntimeType(
  21957. ctx,
  21958. node.typeParameters.params[0],
  21959. scope
  21960. ).filter((t) => t !== "null");
  21961. }
  21962. break;
  21963. case "Extract":
  21964. if (node.typeParameters && node.typeParameters.params[1]) {
  21965. return inferRuntimeType(
  21966. ctx,
  21967. node.typeParameters.params[1],
  21968. scope
  21969. );
  21970. }
  21971. break;
  21972. case "Exclude":
  21973. case "OmitThisParameter":
  21974. if (node.typeParameters && node.typeParameters.params[0]) {
  21975. return inferRuntimeType(
  21976. ctx,
  21977. node.typeParameters.params[0],
  21978. scope
  21979. );
  21980. }
  21981. break;
  21982. }
  21983. }
  21984. }
  21985. break;
  21986. }
  21987. case "TSParenthesizedType":
  21988. return inferRuntimeType(ctx, node.typeAnnotation, scope);
  21989. case "TSUnionType":
  21990. return flattenTypes(ctx, node.types, scope, isKeyOf, typeParameters);
  21991. case "TSIntersectionType": {
  21992. return flattenTypes(
  21993. ctx,
  21994. node.types,
  21995. scope,
  21996. isKeyOf,
  21997. typeParameters
  21998. ).filter((t) => t !== UNKNOWN_TYPE);
  21999. }
  22000. case "TSMappedType": {
  22001. const { typeAnnotation, typeParameter } = node;
  22002. if (typeAnnotation && typeAnnotation.type === "TSIndexedAccessType" && typeParameter && typeParameter.constraint && typeParameters) {
  22003. const constraint = typeParameter.constraint;
  22004. if (constraint.type === "TSTypeOperator" && constraint.operator === "keyof" && constraint.typeAnnotation && constraint.typeAnnotation.type === "TSTypeReference" && constraint.typeAnnotation.typeName.type === "Identifier") {
  22005. const typeName = constraint.typeAnnotation.typeName.name;
  22006. const index = typeAnnotation.indexType;
  22007. const obj = typeAnnotation.objectType;
  22008. 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) {
  22009. const targetType = typeParameters[typeName];
  22010. if (targetType) {
  22011. return inferRuntimeType(ctx, targetType, scope);
  22012. }
  22013. }
  22014. }
  22015. }
  22016. return [UNKNOWN_TYPE];
  22017. }
  22018. case "TSEnumDeclaration":
  22019. return inferEnumType(node);
  22020. case "TSSymbolKeyword":
  22021. return ["Symbol"];
  22022. case "TSIndexedAccessType": {
  22023. const types = resolveIndexType(ctx, node, scope);
  22024. return flattenTypes(ctx, types, scope, isKeyOf);
  22025. }
  22026. case "ClassDeclaration":
  22027. return ["Object"];
  22028. case "TSImportType": {
  22029. const sourceScope = importSourceToScope(
  22030. ctx,
  22031. node.argument,
  22032. scope,
  22033. node.argument.value
  22034. );
  22035. const resolved = resolveTypeReference(ctx, node, sourceScope);
  22036. if (resolved) {
  22037. return inferRuntimeType(ctx, resolved, resolved._ownerScope);
  22038. }
  22039. break;
  22040. }
  22041. case "TSTypeQuery": {
  22042. const id = node.exprName;
  22043. if (id.type === "Identifier") {
  22044. const matched = scope.declares[id.name];
  22045. if (matched) {
  22046. return inferRuntimeType(ctx, matched, matched._ownerScope, isKeyOf);
  22047. }
  22048. }
  22049. break;
  22050. }
  22051. // e.g. readonly
  22052. case "TSTypeOperator": {
  22053. return inferRuntimeType(
  22054. ctx,
  22055. node.typeAnnotation,
  22056. scope,
  22057. node.operator === "keyof"
  22058. );
  22059. }
  22060. case "TSAnyKeyword": {
  22061. if (isKeyOf) {
  22062. return ["String", "Number", "Symbol"];
  22063. }
  22064. break;
  22065. }
  22066. }
  22067. } catch (e) {
  22068. } finally {
  22069. ctx.silentOnExtendsFailure = prevSilent;
  22070. }
  22071. return [UNKNOWN_TYPE];
  22072. }
  22073. function flattenTypes(ctx, types, scope, isKeyOf = false, typeParameters = void 0) {
  22074. if (types.length === 1) {
  22075. return inferRuntimeType(
  22076. ctx,
  22077. types[0],
  22078. types[0]._ownerScope || scope,
  22079. isKeyOf,
  22080. typeParameters
  22081. );
  22082. }
  22083. return [
  22084. ...new Set(
  22085. [].concat(
  22086. ...types.map(
  22087. (t) => inferRuntimeType(
  22088. ctx,
  22089. t,
  22090. t._ownerScope || scope,
  22091. isKeyOf,
  22092. typeParameters
  22093. )
  22094. )
  22095. )
  22096. )
  22097. ];
  22098. }
  22099. function inferEnumType(node) {
  22100. const types = /* @__PURE__ */ new Set();
  22101. for (const m of node.members) {
  22102. if (m.initializer) {
  22103. switch (m.initializer.type) {
  22104. case "StringLiteral":
  22105. types.add("String");
  22106. break;
  22107. case "NumericLiteral":
  22108. types.add("Number");
  22109. break;
  22110. }
  22111. }
  22112. }
  22113. return types.size ? [...types] : ["Number"];
  22114. }
  22115. function resolveExtractPropTypes({ props }, scope) {
  22116. const res = { props: {} };
  22117. for (const key in props) {
  22118. const raw = props[key];
  22119. res.props[key] = reverseInferType(
  22120. raw.key,
  22121. raw.typeAnnotation.typeAnnotation,
  22122. scope
  22123. );
  22124. }
  22125. return res;
  22126. }
  22127. function reverseInferType(key, node, scope, optional = true, checkObjectSyntax = true) {
  22128. if (checkObjectSyntax && node.type === "TSTypeLiteral") {
  22129. const typeType = findStaticPropertyType(node, "type");
  22130. if (typeType) {
  22131. const requiredType = findStaticPropertyType(node, "required");
  22132. const optional2 = requiredType && requiredType.type === "TSLiteralType" && requiredType.literal.type === "BooleanLiteral" ? !requiredType.literal.value : true;
  22133. return reverseInferType(key, typeType, scope, optional2, false);
  22134. }
  22135. } else if (node.type === "TSTypeReference" && node.typeName.type === "Identifier") {
  22136. if (node.typeName.name.endsWith("Constructor")) {
  22137. return createProperty(
  22138. key,
  22139. ctorToType(node.typeName.name),
  22140. scope,
  22141. optional
  22142. );
  22143. } else if (node.typeName.name === "PropType" && node.typeParameters) {
  22144. return createProperty(key, node.typeParameters.params[0], scope, optional);
  22145. }
  22146. }
  22147. if ((node.type === "TSTypeReference" || node.type === "TSImportType") && node.typeParameters) {
  22148. for (const t of node.typeParameters.params) {
  22149. const inferred = reverseInferType(key, t, scope, optional);
  22150. if (inferred) return inferred;
  22151. }
  22152. }
  22153. return createProperty(key, { type: `TSNullKeyword` }, scope, optional);
  22154. }
  22155. function ctorToType(ctorType) {
  22156. const ctor = ctorType.slice(0, -11);
  22157. switch (ctor) {
  22158. case "String":
  22159. case "Number":
  22160. case "Boolean":
  22161. return { type: `TS${ctor}Keyword` };
  22162. case "Array":
  22163. case "Function":
  22164. case "Object":
  22165. case "Set":
  22166. case "Map":
  22167. case "WeakSet":
  22168. case "WeakMap":
  22169. case "Date":
  22170. case "Promise":
  22171. return {
  22172. type: "TSTypeReference",
  22173. typeName: { type: "Identifier", name: ctor }
  22174. };
  22175. }
  22176. return { type: `TSNullKeyword` };
  22177. }
  22178. function findStaticPropertyType(node, key) {
  22179. const prop = node.members.find(
  22180. (m) => m.type === "TSPropertySignature" && getStringLiteralKey(m) === key && m.typeAnnotation
  22181. );
  22182. return prop && prop.typeAnnotation.typeAnnotation;
  22183. }
  22184. function resolveReturnType(ctx, arg, scope) {
  22185. var _a;
  22186. let resolved = arg;
  22187. if (arg.type === "TSTypeReference" || arg.type === "TSTypeQuery" || arg.type === "TSImportType") {
  22188. resolved = resolveTypeReference(ctx, arg, scope);
  22189. }
  22190. if (!resolved) return;
  22191. if (resolved.type === "TSFunctionType") {
  22192. return (_a = resolved.typeAnnotation) == null ? void 0 : _a.typeAnnotation;
  22193. }
  22194. if (resolved.type === "TSDeclareFunction") {
  22195. return resolved.returnType;
  22196. }
  22197. }
  22198. function resolveUnionType(ctx, node, scope) {
  22199. if (node.type === "TSTypeReference") {
  22200. const resolved = resolveTypeReference(ctx, node, scope);
  22201. if (resolved) node = resolved;
  22202. }
  22203. let types;
  22204. if (node.type === "TSUnionType") {
  22205. types = node.types.flatMap((node2) => resolveUnionType(ctx, node2, scope));
  22206. } else {
  22207. types = [node];
  22208. }
  22209. return types;
  22210. }
  22211. const DEFINE_MODEL = "defineModel";
  22212. function processDefineModel(ctx, node, declId) {
  22213. if (!isCallOf(node, DEFINE_MODEL)) {
  22214. return false;
  22215. }
  22216. ctx.hasDefineModelCall = true;
  22217. const type = node.typeParameters && node.typeParameters.params[0] || void 0;
  22218. let modelName;
  22219. let options;
  22220. const arg0 = node.arguments[0] && CompilerDOM.unwrapTSNode(node.arguments[0]);
  22221. const hasName = arg0 && (arg0.type === "StringLiteral" || arg0.type === "TemplateLiteral" && arg0.expressions.length === 0);
  22222. if (hasName) {
  22223. modelName = arg0.type === "StringLiteral" ? arg0.value : arg0.quasis[0].value.cooked;
  22224. options = node.arguments[1];
  22225. } else {
  22226. modelName = "modelValue";
  22227. options = arg0;
  22228. }
  22229. if (ctx.modelDecls[modelName]) {
  22230. ctx.error(`duplicate model name ${JSON.stringify(modelName)}`, node);
  22231. }
  22232. let optionsString = options && ctx.getString(options);
  22233. let optionsRemoved = !options;
  22234. const runtimeOptionNodes = [];
  22235. if (options && options.type === "ObjectExpression" && !options.properties.some((p) => p.type === "SpreadElement" || p.computed)) {
  22236. let removed = 0;
  22237. for (let i = options.properties.length - 1; i >= 0; i--) {
  22238. const p = options.properties[i];
  22239. const next = options.properties[i + 1];
  22240. const start = p.start;
  22241. const end = next ? next.start : options.end - 1;
  22242. 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"))) {
  22243. optionsString = optionsString.slice(0, start - options.start) + optionsString.slice(end - options.start);
  22244. } else {
  22245. removed++;
  22246. ctx.s.remove(ctx.startOffset + start, ctx.startOffset + end);
  22247. runtimeOptionNodes.push(p);
  22248. }
  22249. }
  22250. if (removed === options.properties.length) {
  22251. optionsRemoved = true;
  22252. ctx.s.remove(
  22253. ctx.startOffset + (hasName ? arg0.end : options.start),
  22254. ctx.startOffset + options.end
  22255. );
  22256. }
  22257. }
  22258. ctx.modelDecls[modelName] = {
  22259. type,
  22260. options: optionsString,
  22261. runtimeOptionNodes,
  22262. identifier: declId && declId.type === "Identifier" ? declId.name : void 0
  22263. };
  22264. ctx.bindingMetadata[modelName] = "props";
  22265. ctx.s.overwrite(
  22266. ctx.startOffset + node.callee.start,
  22267. ctx.startOffset + node.callee.end,
  22268. ctx.helper("useModel")
  22269. );
  22270. ctx.s.appendLeft(
  22271. ctx.startOffset + (node.arguments.length ? node.arguments[0].start : node.end - 1),
  22272. `__props, ` + (hasName ? `` : `${JSON.stringify(modelName)}${optionsRemoved ? `` : `, `}`)
  22273. );
  22274. return true;
  22275. }
  22276. function genModelProps(ctx) {
  22277. if (!ctx.hasDefineModelCall) return;
  22278. const isProd = !!ctx.options.isProd;
  22279. let modelPropsDecl = "";
  22280. for (const [name, { type, options: runtimeOptions }] of Object.entries(
  22281. ctx.modelDecls
  22282. )) {
  22283. let skipCheck = false;
  22284. let codegenOptions = ``;
  22285. let runtimeTypes = type && inferRuntimeType(ctx, type);
  22286. if (runtimeTypes) {
  22287. const hasBoolean = runtimeTypes.includes("Boolean");
  22288. const hasFunction = runtimeTypes.includes("Function");
  22289. const hasUnknownType = runtimeTypes.includes(UNKNOWN_TYPE);
  22290. if (hasUnknownType) {
  22291. if (hasBoolean || hasFunction) {
  22292. runtimeTypes = runtimeTypes.filter((t) => t !== UNKNOWN_TYPE);
  22293. skipCheck = true;
  22294. } else {
  22295. runtimeTypes = ["null"];
  22296. }
  22297. }
  22298. if (!isProd) {
  22299. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}` + (skipCheck ? ", skipCheck: true" : "");
  22300. } else if (hasBoolean || runtimeOptions && hasFunction) {
  22301. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}`;
  22302. } else ;
  22303. }
  22304. let decl;
  22305. if (codegenOptions && runtimeOptions) {
  22306. decl = ctx.isTS ? `{ ${codegenOptions}, ...${runtimeOptions} }` : `Object.assign({ ${codegenOptions} }, ${runtimeOptions})`;
  22307. } else if (codegenOptions) {
  22308. decl = `{ ${codegenOptions} }`;
  22309. } else if (runtimeOptions) {
  22310. decl = runtimeOptions;
  22311. } else {
  22312. decl = `{}`;
  22313. }
  22314. modelPropsDecl += `
  22315. ${JSON.stringify(name)}: ${decl},`;
  22316. const modifierPropName = JSON.stringify(
  22317. name === "modelValue" ? `modelModifiers` : `${name}Modifiers`
  22318. );
  22319. modelPropsDecl += `
  22320. ${modifierPropName}: {},`;
  22321. }
  22322. return `{${modelPropsDecl}
  22323. }`;
  22324. }
  22325. const DEFINE_PROPS = "defineProps";
  22326. const WITH_DEFAULTS = "withDefaults";
  22327. function processDefineProps(ctx, node, declId, isWithDefaults = false) {
  22328. if (!isCallOf(node, DEFINE_PROPS)) {
  22329. return processWithDefaults(ctx, node, declId);
  22330. }
  22331. if (ctx.hasDefinePropsCall) {
  22332. ctx.error(`duplicate ${DEFINE_PROPS}() call`, node);
  22333. }
  22334. ctx.hasDefinePropsCall = true;
  22335. ctx.propsRuntimeDecl = node.arguments[0];
  22336. if (ctx.propsRuntimeDecl) {
  22337. for (const key of getObjectOrArrayExpressionKeys(ctx.propsRuntimeDecl)) {
  22338. if (!(key in ctx.bindingMetadata)) {
  22339. ctx.bindingMetadata[key] = "props";
  22340. }
  22341. }
  22342. }
  22343. if (node.typeParameters) {
  22344. if (ctx.propsRuntimeDecl) {
  22345. ctx.error(
  22346. `${DEFINE_PROPS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  22347. node
  22348. );
  22349. }
  22350. ctx.propsTypeDecl = node.typeParameters.params[0];
  22351. }
  22352. if (!isWithDefaults && declId && declId.type === "ObjectPattern") {
  22353. processPropsDestructure(ctx, declId);
  22354. }
  22355. ctx.propsCall = node;
  22356. ctx.propsDecl = declId;
  22357. return true;
  22358. }
  22359. function processWithDefaults(ctx, node, declId) {
  22360. if (!isCallOf(node, WITH_DEFAULTS)) {
  22361. return false;
  22362. }
  22363. if (!processDefineProps(
  22364. ctx,
  22365. node.arguments[0],
  22366. declId,
  22367. true
  22368. )) {
  22369. ctx.error(
  22370. `${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`,
  22371. node.arguments[0] || node
  22372. );
  22373. }
  22374. if (ctx.propsRuntimeDecl) {
  22375. ctx.error(
  22376. `${WITH_DEFAULTS} can only be used with type-based ${DEFINE_PROPS} declaration.`,
  22377. node
  22378. );
  22379. }
  22380. if (declId && declId.type === "ObjectPattern") {
  22381. ctx.warn(
  22382. `${WITH_DEFAULTS}() is unnecessary when using destructure with ${DEFINE_PROPS}().
  22383. Reactive destructure will be disabled when using withDefaults().
  22384. Prefer using destructure default values, e.g. const { foo = 1 } = defineProps(...). `,
  22385. node.callee
  22386. );
  22387. }
  22388. ctx.propsRuntimeDefaults = node.arguments[1];
  22389. if (!ctx.propsRuntimeDefaults) {
  22390. ctx.error(`The 2nd argument of ${WITH_DEFAULTS} is required.`, node);
  22391. }
  22392. ctx.propsCall = node;
  22393. return true;
  22394. }
  22395. function genRuntimeProps(ctx) {
  22396. let propsDecls;
  22397. if (ctx.propsRuntimeDecl) {
  22398. propsDecls = ctx.getString(ctx.propsRuntimeDecl).trim();
  22399. if (ctx.propsDestructureDecl) {
  22400. const defaults = [];
  22401. for (const key in ctx.propsDestructuredBindings) {
  22402. const d = genDestructuredDefaultValue(ctx, key);
  22403. const finalKey = getEscapedPropName(key);
  22404. if (d)
  22405. defaults.push(
  22406. `${finalKey}: ${d.valueString}${d.needSkipFactory ? `, __skip_${finalKey}: true` : ``}`
  22407. );
  22408. }
  22409. if (defaults.length) {
  22410. propsDecls = `/*@__PURE__*/${ctx.helper(
  22411. `mergeDefaults`
  22412. )}(${propsDecls}, {
  22413. ${defaults.join(",\n ")}
  22414. })`;
  22415. }
  22416. }
  22417. } else if (ctx.propsTypeDecl) {
  22418. propsDecls = extractRuntimeProps(ctx);
  22419. }
  22420. const modelsDecls = genModelProps(ctx);
  22421. if (propsDecls && modelsDecls) {
  22422. return `/*@__PURE__*/${ctx.helper(
  22423. "mergeModels"
  22424. )}(${propsDecls}, ${modelsDecls})`;
  22425. } else {
  22426. return modelsDecls || propsDecls;
  22427. }
  22428. }
  22429. function extractRuntimeProps(ctx) {
  22430. const props = resolveRuntimePropsFromType(ctx, ctx.propsTypeDecl);
  22431. if (!props.length) {
  22432. return;
  22433. }
  22434. const propStrings = [];
  22435. const hasStaticDefaults = hasStaticWithDefaults(ctx);
  22436. for (const prop of props) {
  22437. propStrings.push(genRuntimePropFromType(ctx, prop, hasStaticDefaults));
  22438. if ("bindingMetadata" in ctx && !(prop.key in ctx.bindingMetadata)) {
  22439. ctx.bindingMetadata[prop.key] = "props";
  22440. }
  22441. }
  22442. let propsDecls = `{
  22443. ${propStrings.join(",\n ")}
  22444. }`;
  22445. if (ctx.propsRuntimeDefaults && !hasStaticDefaults) {
  22446. propsDecls = `/*@__PURE__*/${ctx.helper(
  22447. "mergeDefaults"
  22448. )}(${propsDecls}, ${ctx.getString(ctx.propsRuntimeDefaults)})`;
  22449. }
  22450. return propsDecls;
  22451. }
  22452. function resolveRuntimePropsFromType(ctx, node) {
  22453. const props = [];
  22454. const elements = resolveTypeElements(ctx, node);
  22455. for (const key in elements.props) {
  22456. const e = elements.props[key];
  22457. let type = inferRuntimeType(ctx, e);
  22458. let skipCheck = false;
  22459. if (type.includes(UNKNOWN_TYPE)) {
  22460. if (type.includes("Boolean") || type.includes("Function")) {
  22461. type = type.filter((t) => t !== UNKNOWN_TYPE);
  22462. skipCheck = true;
  22463. } else {
  22464. type = ["null"];
  22465. }
  22466. }
  22467. props.push({
  22468. key,
  22469. required: !e.optional,
  22470. type: type || [`null`],
  22471. skipCheck
  22472. });
  22473. }
  22474. return props;
  22475. }
  22476. function genRuntimePropFromType(ctx, { key, required, type, skipCheck }, hasStaticDefaults) {
  22477. let defaultString;
  22478. const destructured = genDestructuredDefaultValue(ctx, key, type);
  22479. if (destructured) {
  22480. defaultString = `default: ${destructured.valueString}${destructured.needSkipFactory ? `, skipFactory: true` : ``}`;
  22481. } else if (hasStaticDefaults) {
  22482. const prop = ctx.propsRuntimeDefaults.properties.find(
  22483. (node) => {
  22484. if (node.type === "SpreadElement") return false;
  22485. return resolveObjectKey(node.key, node.computed) === key;
  22486. }
  22487. );
  22488. if (prop) {
  22489. if (prop.type === "ObjectProperty") {
  22490. defaultString = `default: ${ctx.getString(prop.value)}`;
  22491. } else {
  22492. let paramsString = "";
  22493. if (prop.params.length) {
  22494. const start = prop.params[0].start;
  22495. const end = prop.params[prop.params.length - 1].end;
  22496. paramsString = ctx.getString({ start, end });
  22497. }
  22498. defaultString = `${prop.async ? "async " : ""}${prop.kind !== "method" ? `${prop.kind} ` : ""}default(${paramsString}) ${ctx.getString(prop.body)}`;
  22499. }
  22500. }
  22501. }
  22502. const finalKey = getEscapedPropName(key);
  22503. if (!ctx.options.isProd) {
  22504. return `${finalKey}: { ${concatStrings([
  22505. `type: ${toRuntimeTypeString(type)}`,
  22506. `required: ${required}`,
  22507. skipCheck && "skipCheck: true",
  22508. defaultString
  22509. ])} }`;
  22510. } else if (type.some(
  22511. (el) => el === "Boolean" || (!hasStaticDefaults || defaultString) && el === "Function"
  22512. )) {
  22513. return `${finalKey}: { ${concatStrings([
  22514. `type: ${toRuntimeTypeString(type)}`,
  22515. defaultString
  22516. ])} }`;
  22517. } else {
  22518. if (ctx.isCE) {
  22519. if (defaultString) {
  22520. return `${finalKey}: ${`{ ${defaultString}, type: ${toRuntimeTypeString(
  22521. type
  22522. )} }`}`;
  22523. } else {
  22524. return `${finalKey}: {type: ${toRuntimeTypeString(type)}}`;
  22525. }
  22526. }
  22527. return `${finalKey}: ${defaultString ? `{ ${defaultString} }` : `{}`}`;
  22528. }
  22529. }
  22530. function hasStaticWithDefaults(ctx) {
  22531. return !!(ctx.propsRuntimeDefaults && ctx.propsRuntimeDefaults.type === "ObjectExpression" && ctx.propsRuntimeDefaults.properties.every(
  22532. (node) => node.type !== "SpreadElement" && (!node.computed || node.key.type.endsWith("Literal"))
  22533. ));
  22534. }
  22535. function genDestructuredDefaultValue(ctx, key, inferredType) {
  22536. const destructured = ctx.propsDestructuredBindings[key];
  22537. const defaultVal = destructured && destructured.default;
  22538. if (defaultVal) {
  22539. const value = ctx.getString(defaultVal);
  22540. const unwrapped = CompilerDOM.unwrapTSNode(defaultVal);
  22541. if (inferredType && inferredType.length && !inferredType.includes("null")) {
  22542. const valueType = inferValueType(unwrapped);
  22543. if (valueType && !inferredType.includes(valueType)) {
  22544. ctx.error(
  22545. `Default value of prop "${key}" does not match declared type.`,
  22546. unwrapped
  22547. );
  22548. }
  22549. }
  22550. const needSkipFactory = !inferredType && (CompilerDOM.isFunctionType(unwrapped) || unwrapped.type === "Identifier");
  22551. const needFactoryWrap = !needSkipFactory && !isLiteralNode(unwrapped) && !(inferredType == null ? void 0 : inferredType.includes("Function"));
  22552. return {
  22553. valueString: needFactoryWrap ? `() => (${value})` : value,
  22554. needSkipFactory
  22555. };
  22556. }
  22557. }
  22558. function inferValueType(node) {
  22559. switch (node.type) {
  22560. case "StringLiteral":
  22561. return "String";
  22562. case "NumericLiteral":
  22563. return "Number";
  22564. case "BooleanLiteral":
  22565. return "Boolean";
  22566. case "ObjectExpression":
  22567. return "Object";
  22568. case "ArrayExpression":
  22569. return "Array";
  22570. case "FunctionExpression":
  22571. case "ArrowFunctionExpression":
  22572. return "Function";
  22573. }
  22574. }
  22575. function processPropsDestructure(ctx, declId) {
  22576. if (ctx.options.propsDestructure === "error") {
  22577. ctx.error(`Props destructure is explicitly prohibited via config.`, declId);
  22578. } else if (ctx.options.propsDestructure === false) {
  22579. return;
  22580. }
  22581. ctx.propsDestructureDecl = declId;
  22582. const registerBinding = (key, local, defaultValue) => {
  22583. ctx.propsDestructuredBindings[key] = { local, default: defaultValue };
  22584. if (local !== key) {
  22585. ctx.bindingMetadata[local] = "props-aliased";
  22586. (ctx.bindingMetadata.__propsAliases || (ctx.bindingMetadata.__propsAliases = {}))[local] = key;
  22587. }
  22588. };
  22589. for (const prop of declId.properties) {
  22590. if (prop.type === "ObjectProperty") {
  22591. const propKey = resolveObjectKey(prop.key, prop.computed);
  22592. if (!propKey) {
  22593. ctx.error(
  22594. `${DEFINE_PROPS}() destructure cannot use computed key.`,
  22595. prop.key
  22596. );
  22597. }
  22598. if (prop.value.type === "AssignmentPattern") {
  22599. const { left, right } = prop.value;
  22600. if (left.type !== "Identifier") {
  22601. ctx.error(
  22602. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  22603. left
  22604. );
  22605. }
  22606. registerBinding(propKey, left.name, right);
  22607. } else if (prop.value.type === "Identifier") {
  22608. registerBinding(propKey, prop.value.name);
  22609. } else {
  22610. ctx.error(
  22611. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  22612. prop.value
  22613. );
  22614. }
  22615. } else {
  22616. ctx.propsDestructureRestId = prop.argument.name;
  22617. ctx.bindingMetadata[ctx.propsDestructureRestId] = "setup-reactive-const";
  22618. }
  22619. }
  22620. }
  22621. function transformDestructuredProps(ctx, vueImportAliases) {
  22622. if (ctx.options.propsDestructure === false) {
  22623. return;
  22624. }
  22625. const rootScope = /* @__PURE__ */ Object.create(null);
  22626. const scopeStack = [rootScope];
  22627. let currentScope = rootScope;
  22628. const excludedIds = /* @__PURE__ */ new WeakSet();
  22629. const parentStack = [];
  22630. const propsLocalToPublicMap = /* @__PURE__ */ Object.create(null);
  22631. for (const key in ctx.propsDestructuredBindings) {
  22632. const { local } = ctx.propsDestructuredBindings[key];
  22633. rootScope[local] = true;
  22634. propsLocalToPublicMap[local] = key;
  22635. }
  22636. function pushScope() {
  22637. scopeStack.push(currentScope = Object.create(currentScope));
  22638. }
  22639. function popScope() {
  22640. scopeStack.pop();
  22641. currentScope = scopeStack[scopeStack.length - 1] || null;
  22642. }
  22643. function registerLocalBinding(id) {
  22644. excludedIds.add(id);
  22645. if (currentScope) {
  22646. currentScope[id.name] = false;
  22647. } else {
  22648. ctx.error(
  22649. "registerBinding called without active scope, something is wrong.",
  22650. id
  22651. );
  22652. }
  22653. }
  22654. function walkScope(node, isRoot = false) {
  22655. for (const stmt of node.body) {
  22656. if (stmt.type === "VariableDeclaration") {
  22657. walkVariableDeclaration(stmt, isRoot);
  22658. } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
  22659. if (stmt.declare || !stmt.id) continue;
  22660. registerLocalBinding(stmt.id);
  22661. } else if (stmt.type === "ExportNamedDeclaration" && stmt.declaration && stmt.declaration.type === "VariableDeclaration") {
  22662. walkVariableDeclaration(stmt.declaration, isRoot);
  22663. } else if (stmt.type === "LabeledStatement" && stmt.body.type === "VariableDeclaration") {
  22664. walkVariableDeclaration(stmt.body, isRoot);
  22665. }
  22666. }
  22667. }
  22668. function walkVariableDeclaration(stmt, isRoot = false) {
  22669. if (stmt.declare) {
  22670. return;
  22671. }
  22672. for (const decl of stmt.declarations) {
  22673. const isDefineProps = isRoot && decl.init && isCallOf(CompilerDOM.unwrapTSNode(decl.init), "defineProps");
  22674. for (const id of CompilerDOM.extractIdentifiers(decl.id)) {
  22675. if (isDefineProps) {
  22676. excludedIds.add(id);
  22677. } else {
  22678. registerLocalBinding(id);
  22679. }
  22680. }
  22681. }
  22682. }
  22683. function rewriteId(id, parent, parentStack2) {
  22684. if (parent.type === "AssignmentExpression" && id === parent.left || parent.type === "UpdateExpression") {
  22685. ctx.error(`Cannot assign to destructured props as they are readonly.`, id);
  22686. }
  22687. if (CompilerDOM.isStaticProperty(parent) && parent.shorthand) {
  22688. if (!parent.inPattern || CompilerDOM.isInDestructureAssignment(parent, parentStack2)) {
  22689. ctx.s.appendLeft(
  22690. id.end + ctx.startOffset,
  22691. `: ${shared.genPropsAccessExp(propsLocalToPublicMap[id.name])}`
  22692. );
  22693. }
  22694. } else {
  22695. ctx.s.overwrite(
  22696. id.start + ctx.startOffset,
  22697. id.end + ctx.startOffset,
  22698. shared.genPropsAccessExp(propsLocalToPublicMap[id.name])
  22699. );
  22700. }
  22701. }
  22702. function checkUsage(node, method, alias = method) {
  22703. if (isCallOf(node, alias)) {
  22704. const arg = CompilerDOM.unwrapTSNode(node.arguments[0]);
  22705. if (arg.type === "Identifier" && currentScope[arg.name]) {
  22706. ctx.error(
  22707. `"${arg.name}" is a destructured prop and should not be passed directly to ${method}(). Pass a getter () => ${arg.name} instead.`,
  22708. arg
  22709. );
  22710. }
  22711. }
  22712. }
  22713. const ast = ctx.scriptSetupAst;
  22714. walkScope(ast, true);
  22715. estreeWalker.walk(ast, {
  22716. enter(node, parent) {
  22717. parent && parentStack.push(parent);
  22718. if (parent && parent.type.startsWith("TS") && !CompilerDOM.TS_NODE_TYPES.includes(parent.type)) {
  22719. return this.skip();
  22720. }
  22721. checkUsage(node, "watch", vueImportAliases.watch);
  22722. checkUsage(node, "toRef", vueImportAliases.toRef);
  22723. if (CompilerDOM.isFunctionType(node)) {
  22724. pushScope();
  22725. CompilerDOM.walkFunctionParams(node, registerLocalBinding);
  22726. if (node.body.type === "BlockStatement") {
  22727. walkScope(node.body);
  22728. }
  22729. return;
  22730. }
  22731. if (node.type === "CatchClause") {
  22732. pushScope();
  22733. if (node.param && node.param.type === "Identifier") {
  22734. registerLocalBinding(node.param);
  22735. }
  22736. walkScope(node.body);
  22737. return;
  22738. }
  22739. if (node.type === "ForOfStatement" || node.type === "ForInStatement" || node.type === "ForStatement") {
  22740. pushScope();
  22741. const varDecl = node.type === "ForStatement" ? node.init : node.left;
  22742. if (varDecl && varDecl.type === "VariableDeclaration") {
  22743. walkVariableDeclaration(varDecl);
  22744. }
  22745. if (node.body.type === "BlockStatement") {
  22746. walkScope(node.body);
  22747. }
  22748. return;
  22749. }
  22750. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent)) {
  22751. pushScope();
  22752. walkScope(node);
  22753. return;
  22754. }
  22755. if (node.type === "Identifier") {
  22756. if (CompilerDOM.isReferencedIdentifier(node, parent, parentStack) && !excludedIds.has(node)) {
  22757. if (currentScope[node.name]) {
  22758. rewriteId(node, parent, parentStack);
  22759. }
  22760. }
  22761. }
  22762. },
  22763. leave(node, parent) {
  22764. parent && parentStack.pop();
  22765. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent) || CompilerDOM.isFunctionType(node) || node.type === "CatchClause" || node.type === "ForOfStatement" || node.type === "ForInStatement" || node.type === "ForStatement") {
  22766. popScope();
  22767. }
  22768. }
  22769. });
  22770. }
  22771. const DEFINE_EMITS = "defineEmits";
  22772. function processDefineEmits(ctx, node, declId) {
  22773. if (!isCallOf(node, DEFINE_EMITS)) {
  22774. return false;
  22775. }
  22776. if (ctx.hasDefineEmitCall) {
  22777. ctx.error(`duplicate ${DEFINE_EMITS}() call`, node);
  22778. }
  22779. ctx.hasDefineEmitCall = true;
  22780. ctx.emitsRuntimeDecl = node.arguments[0];
  22781. if (node.typeParameters) {
  22782. if (ctx.emitsRuntimeDecl) {
  22783. ctx.error(
  22784. `${DEFINE_EMITS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  22785. node
  22786. );
  22787. }
  22788. ctx.emitsTypeDecl = node.typeParameters.params[0];
  22789. }
  22790. ctx.emitDecl = declId;
  22791. return true;
  22792. }
  22793. function genRuntimeEmits(ctx) {
  22794. let emitsDecl = "";
  22795. if (ctx.emitsRuntimeDecl) {
  22796. emitsDecl = ctx.getString(ctx.emitsRuntimeDecl).trim();
  22797. } else if (ctx.emitsTypeDecl) {
  22798. const typeDeclaredEmits = extractRuntimeEmits(ctx);
  22799. emitsDecl = typeDeclaredEmits.size ? `[${Array.from(typeDeclaredEmits).map((k) => JSON.stringify(k)).join(", ")}]` : ``;
  22800. }
  22801. if (ctx.hasDefineModelCall) {
  22802. let modelEmitsDecl = `[${Object.keys(ctx.modelDecls).map((n) => JSON.stringify(`update:${n}`)).join(", ")}]`;
  22803. emitsDecl = emitsDecl ? `/*@__PURE__*/${ctx.helper(
  22804. "mergeModels"
  22805. )}(${emitsDecl}, ${modelEmitsDecl})` : modelEmitsDecl;
  22806. }
  22807. return emitsDecl;
  22808. }
  22809. function extractRuntimeEmits(ctx) {
  22810. const emits = /* @__PURE__ */ new Set();
  22811. const node = ctx.emitsTypeDecl;
  22812. if (node.type === "TSFunctionType") {
  22813. extractEventNames(ctx, node.parameters[0], emits);
  22814. return emits;
  22815. }
  22816. const { props, calls } = resolveTypeElements(ctx, node);
  22817. let hasProperty = false;
  22818. for (const key in props) {
  22819. emits.add(key);
  22820. hasProperty = true;
  22821. }
  22822. if (calls) {
  22823. if (hasProperty) {
  22824. ctx.error(
  22825. `defineEmits() type cannot mixed call signature and property syntax.`,
  22826. node
  22827. );
  22828. }
  22829. for (const call of calls) {
  22830. extractEventNames(ctx, call.parameters[0], emits);
  22831. }
  22832. }
  22833. return emits;
  22834. }
  22835. function extractEventNames(ctx, eventName, emits) {
  22836. if (eventName.type === "Identifier" && eventName.typeAnnotation && eventName.typeAnnotation.type === "TSTypeAnnotation") {
  22837. const types = resolveUnionType(ctx, eventName.typeAnnotation.typeAnnotation);
  22838. for (const type of types) {
  22839. if (type.type === "TSLiteralType") {
  22840. if (type.literal.type !== "UnaryExpression" && type.literal.type !== "TemplateLiteral") {
  22841. emits.add(String(type.literal.value));
  22842. }
  22843. }
  22844. }
  22845. }
  22846. }
  22847. const DEFINE_EXPOSE = "defineExpose";
  22848. function processDefineExpose(ctx, node) {
  22849. if (isCallOf(node, DEFINE_EXPOSE)) {
  22850. if (ctx.hasDefineExposeCall) {
  22851. ctx.error(`duplicate ${DEFINE_EXPOSE}() call`, node);
  22852. }
  22853. ctx.hasDefineExposeCall = true;
  22854. return true;
  22855. }
  22856. return false;
  22857. }
  22858. const DEFINE_SLOTS = "defineSlots";
  22859. function processDefineSlots(ctx, node, declId) {
  22860. if (!isCallOf(node, DEFINE_SLOTS)) {
  22861. return false;
  22862. }
  22863. if (ctx.hasDefineSlotsCall) {
  22864. ctx.error(`duplicate ${DEFINE_SLOTS}() call`, node);
  22865. }
  22866. ctx.hasDefineSlotsCall = true;
  22867. if (node.arguments.length > 0) {
  22868. ctx.error(`${DEFINE_SLOTS}() cannot accept arguments`, node);
  22869. }
  22870. if (declId) {
  22871. ctx.s.overwrite(
  22872. ctx.startOffset + node.start,
  22873. ctx.startOffset + node.end,
  22874. `${ctx.helper("useSlots")}()`
  22875. );
  22876. }
  22877. return true;
  22878. }
  22879. const DEFINE_OPTIONS = "defineOptions";
  22880. function processDefineOptions(ctx, node) {
  22881. if (!isCallOf(node, DEFINE_OPTIONS)) {
  22882. return false;
  22883. }
  22884. if (ctx.hasDefineOptionsCall) {
  22885. ctx.error(`duplicate ${DEFINE_OPTIONS}() call`, node);
  22886. }
  22887. if (node.typeParameters) {
  22888. ctx.error(`${DEFINE_OPTIONS}() cannot accept type arguments`, node);
  22889. }
  22890. if (!node.arguments[0]) return true;
  22891. ctx.hasDefineOptionsCall = true;
  22892. ctx.optionsRuntimeDecl = CompilerDOM.unwrapTSNode(node.arguments[0]);
  22893. let propsOption = void 0;
  22894. let emitsOption = void 0;
  22895. let exposeOption = void 0;
  22896. let slotsOption = void 0;
  22897. if (ctx.optionsRuntimeDecl.type === "ObjectExpression") {
  22898. for (const prop of ctx.optionsRuntimeDecl.properties) {
  22899. if ((prop.type === "ObjectProperty" || prop.type === "ObjectMethod") && prop.key.type === "Identifier") {
  22900. switch (prop.key.name) {
  22901. case "props":
  22902. propsOption = prop;
  22903. break;
  22904. case "emits":
  22905. emitsOption = prop;
  22906. break;
  22907. case "expose":
  22908. exposeOption = prop;
  22909. break;
  22910. case "slots":
  22911. slotsOption = prop;
  22912. break;
  22913. }
  22914. }
  22915. }
  22916. }
  22917. if (propsOption) {
  22918. ctx.error(
  22919. `${DEFINE_OPTIONS}() cannot be used to declare props. Use ${DEFINE_PROPS}() instead.`,
  22920. propsOption
  22921. );
  22922. }
  22923. if (emitsOption) {
  22924. ctx.error(
  22925. `${DEFINE_OPTIONS}() cannot be used to declare emits. Use ${DEFINE_EMITS}() instead.`,
  22926. emitsOption
  22927. );
  22928. }
  22929. if (exposeOption) {
  22930. ctx.error(
  22931. `${DEFINE_OPTIONS}() cannot be used to declare expose. Use ${DEFINE_EXPOSE}() instead.`,
  22932. exposeOption
  22933. );
  22934. }
  22935. if (slotsOption) {
  22936. ctx.error(
  22937. `${DEFINE_OPTIONS}() cannot be used to declare slots. Use ${DEFINE_SLOTS}() instead.`,
  22938. slotsOption
  22939. );
  22940. }
  22941. return true;
  22942. }
  22943. function processAwait(ctx, node, needSemi, isStatement) {
  22944. const argumentStart = node.argument.extra && node.argument.extra.parenthesized ? node.argument.extra.parenStart : node.argument.start;
  22945. const startOffset = ctx.startOffset;
  22946. const argumentStr = ctx.descriptor.source.slice(
  22947. argumentStart + startOffset,
  22948. node.argument.end + startOffset
  22949. );
  22950. const containsNestedAwait = /\bawait\b/.test(argumentStr);
  22951. ctx.s.overwrite(
  22952. node.start + startOffset,
  22953. argumentStart + startOffset,
  22954. `${needSemi ? `;` : ``}(
  22955. ([__temp,__restore] = ${ctx.helper(
  22956. `withAsyncContext`
  22957. )}(${containsNestedAwait ? `async ` : ``}() => `
  22958. );
  22959. ctx.s.appendLeft(
  22960. node.end + startOffset,
  22961. `)),
  22962. ${isStatement ? `` : `__temp = `}await __temp,
  22963. __restore()${isStatement ? `` : `,
  22964. __temp`}
  22965. )`
  22966. );
  22967. }
  22968. const MACROS = [
  22969. DEFINE_PROPS,
  22970. DEFINE_EMITS,
  22971. DEFINE_EXPOSE,
  22972. DEFINE_OPTIONS,
  22973. DEFINE_SLOTS,
  22974. DEFINE_MODEL,
  22975. WITH_DEFAULTS
  22976. ];
  22977. function compileScript(sfc, options) {
  22978. var _a, _b, _c;
  22979. if (!options.id) {
  22980. warnOnce(
  22981. `compileScript now requires passing the \`id\` option.
  22982. Upgrade your vite or vue-loader version for compatibility with the latest experimental proposals.`
  22983. );
  22984. }
  22985. const { script, scriptSetup, source, filename } = sfc;
  22986. const hoistStatic = options.hoistStatic !== false && !script;
  22987. const scopeId = options.id ? options.id.replace(/^data-v-/, "") : "";
  22988. const scriptLang = script && script.lang;
  22989. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  22990. const isJSOrTS = isJS(scriptLang, scriptSetupLang) || isTS(scriptLang, scriptSetupLang);
  22991. if (script && scriptSetup && scriptLang !== scriptSetupLang) {
  22992. throw new Error(
  22993. `[@vue/compiler-sfc] <script> and <script setup> must have the same language type.`
  22994. );
  22995. }
  22996. if (!scriptSetup) {
  22997. if (!script) {
  22998. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
  22999. }
  23000. if (script.lang && !isJSOrTS) {
  23001. return script;
  23002. }
  23003. const ctx2 = new ScriptCompileContext(sfc, options);
  23004. return processNormalScript(ctx2, scopeId);
  23005. }
  23006. if (scriptSetupLang && !isJSOrTS) {
  23007. return scriptSetup;
  23008. }
  23009. const ctx = new ScriptCompileContext(sfc, options);
  23010. const scriptBindings = /* @__PURE__ */ Object.create(null);
  23011. const setupBindings = /* @__PURE__ */ Object.create(null);
  23012. let defaultExport;
  23013. let hasAwait = false;
  23014. let hasInlinedSsrRenderFn = false;
  23015. const startOffset = ctx.startOffset;
  23016. const endOffset = ctx.endOffset;
  23017. const scriptStartOffset = script && script.loc.start.offset;
  23018. const scriptEndOffset = script && script.loc.end.offset;
  23019. function hoistNode(node) {
  23020. const start = node.start + startOffset;
  23021. let end = node.end + startOffset;
  23022. if (node.trailingComments && node.trailingComments.length > 0) {
  23023. const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
  23024. end = lastCommentNode.end + startOffset;
  23025. }
  23026. while (end <= source.length) {
  23027. if (!/\s/.test(source.charAt(end))) {
  23028. break;
  23029. }
  23030. end++;
  23031. }
  23032. ctx.s.move(start, end, 0);
  23033. }
  23034. function registerUserImport(source2, local, imported, isType, isFromSetup, needTemplateUsageCheck) {
  23035. let isUsedInTemplate = needTemplateUsageCheck;
  23036. if (needTemplateUsageCheck && ctx.isTS && sfc.template && !sfc.template.src && !sfc.template.lang) {
  23037. isUsedInTemplate = isImportUsed(local, sfc);
  23038. }
  23039. ctx.userImports[local] = {
  23040. isType,
  23041. imported,
  23042. local,
  23043. source: source2,
  23044. isFromSetup,
  23045. isUsedInTemplate
  23046. };
  23047. }
  23048. function checkInvalidScopeReference(node, method) {
  23049. if (!node) return;
  23050. CompilerDOM.walkIdentifiers(node, (id) => {
  23051. const binding = setupBindings[id.name];
  23052. if (binding && binding !== "literal-const") {
  23053. ctx.error(
  23054. `\`${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.`,
  23055. id
  23056. );
  23057. }
  23058. });
  23059. }
  23060. const scriptAst = ctx.scriptAst;
  23061. const scriptSetupAst = ctx.scriptSetupAst;
  23062. if (scriptAst) {
  23063. for (const node of scriptAst.body) {
  23064. if (node.type === "ImportDeclaration") {
  23065. for (const specifier of node.specifiers) {
  23066. const imported = getImportedName(specifier);
  23067. registerUserImport(
  23068. node.source.value,
  23069. specifier.local.name,
  23070. imported,
  23071. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  23072. false,
  23073. !options.inlineTemplate
  23074. );
  23075. }
  23076. }
  23077. }
  23078. }
  23079. for (const node of scriptSetupAst.body) {
  23080. if (node.type === "ImportDeclaration") {
  23081. hoistNode(node);
  23082. let removed = 0;
  23083. const removeSpecifier = (i) => {
  23084. const removeLeft = i > removed;
  23085. removed++;
  23086. const current = node.specifiers[i];
  23087. const next = node.specifiers[i + 1];
  23088. ctx.s.remove(
  23089. removeLeft ? node.specifiers[i - 1].end + startOffset : current.start + startOffset,
  23090. next && !removeLeft ? next.start + startOffset : current.end + startOffset
  23091. );
  23092. };
  23093. for (let i = 0; i < node.specifiers.length; i++) {
  23094. const specifier = node.specifiers[i];
  23095. const local = specifier.local.name;
  23096. const imported = getImportedName(specifier);
  23097. const source2 = node.source.value;
  23098. const existing = ctx.userImports[local];
  23099. if (source2 === "vue" && MACROS.includes(imported)) {
  23100. if (local === imported) {
  23101. warnOnce(
  23102. `\`${imported}\` is a compiler macro and no longer needs to be imported.`
  23103. );
  23104. } else {
  23105. ctx.error(
  23106. `\`${imported}\` is a compiler macro and cannot be aliased to a different name.`,
  23107. specifier
  23108. );
  23109. }
  23110. removeSpecifier(i);
  23111. } else if (existing) {
  23112. if (existing.source === source2 && existing.imported === imported) {
  23113. removeSpecifier(i);
  23114. } else {
  23115. ctx.error(
  23116. `different imports aliased to same local name.`,
  23117. specifier
  23118. );
  23119. }
  23120. } else {
  23121. registerUserImport(
  23122. source2,
  23123. local,
  23124. imported,
  23125. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  23126. true,
  23127. !options.inlineTemplate
  23128. );
  23129. }
  23130. }
  23131. if (node.specifiers.length && removed === node.specifiers.length) {
  23132. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  23133. }
  23134. }
  23135. }
  23136. const vueImportAliases = {};
  23137. for (const key in ctx.userImports) {
  23138. const { source: source2, imported, local } = ctx.userImports[key];
  23139. if (source2 === "vue") vueImportAliases[imported] = local;
  23140. }
  23141. if (script && scriptAst) {
  23142. for (const node of scriptAst.body) {
  23143. if (node.type === "ExportDefaultDeclaration") {
  23144. defaultExport = node;
  23145. let optionProperties;
  23146. if (defaultExport.declaration.type === "ObjectExpression") {
  23147. optionProperties = defaultExport.declaration.properties;
  23148. } else if (defaultExport.declaration.type === "CallExpression" && defaultExport.declaration.arguments[0] && defaultExport.declaration.arguments[0].type === "ObjectExpression") {
  23149. optionProperties = defaultExport.declaration.arguments[0].properties;
  23150. }
  23151. if (optionProperties) {
  23152. for (const p of optionProperties) {
  23153. if (p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name") {
  23154. ctx.hasDefaultExportName = true;
  23155. }
  23156. if ((p.type === "ObjectMethod" || p.type === "ObjectProperty") && p.key.type === "Identifier" && p.key.name === "render") {
  23157. ctx.hasDefaultExportRender = true;
  23158. }
  23159. }
  23160. }
  23161. const start = node.start + scriptStartOffset;
  23162. const end = node.declaration.start + scriptStartOffset;
  23163. ctx.s.overwrite(start, end, `const ${normalScriptDefaultVar} = `);
  23164. } else if (node.type === "ExportNamedDeclaration") {
  23165. const defaultSpecifier = node.specifiers.find(
  23166. (s) => s.exported.type === "Identifier" && s.exported.name === "default"
  23167. );
  23168. if (defaultSpecifier) {
  23169. defaultExport = node;
  23170. if (node.specifiers.length > 1) {
  23171. ctx.s.remove(
  23172. defaultSpecifier.start + scriptStartOffset,
  23173. defaultSpecifier.end + scriptStartOffset
  23174. );
  23175. } else {
  23176. ctx.s.remove(
  23177. node.start + scriptStartOffset,
  23178. node.end + scriptStartOffset
  23179. );
  23180. }
  23181. if (node.source) {
  23182. ctx.s.prepend(
  23183. `import { ${defaultSpecifier.local.name} as ${normalScriptDefaultVar} } from '${node.source.value}'
  23184. `
  23185. );
  23186. } else {
  23187. ctx.s.appendLeft(
  23188. scriptEndOffset,
  23189. `
  23190. const ${normalScriptDefaultVar} = ${defaultSpecifier.local.name}
  23191. `
  23192. );
  23193. }
  23194. }
  23195. if (node.declaration) {
  23196. walkDeclaration(
  23197. "script",
  23198. node.declaration,
  23199. scriptBindings,
  23200. vueImportAliases,
  23201. hoistStatic
  23202. );
  23203. }
  23204. } else if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  23205. walkDeclaration(
  23206. "script",
  23207. node,
  23208. scriptBindings,
  23209. vueImportAliases,
  23210. hoistStatic
  23211. );
  23212. }
  23213. }
  23214. if (scriptStartOffset > startOffset) {
  23215. if (!/\n$/.test(script.content.trim())) {
  23216. ctx.s.appendLeft(scriptEndOffset, `
  23217. `);
  23218. }
  23219. ctx.s.move(scriptStartOffset, scriptEndOffset, 0);
  23220. }
  23221. }
  23222. for (const node of scriptSetupAst.body) {
  23223. if (node.type === "ExpressionStatement") {
  23224. const expr = CompilerDOM.unwrapTSNode(node.expression);
  23225. if (processDefineProps(ctx, expr) || processDefineEmits(ctx, expr) || processDefineOptions(ctx, expr) || processDefineSlots(ctx, expr)) {
  23226. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  23227. } else if (processDefineExpose(ctx, expr)) {
  23228. const callee = expr.callee;
  23229. ctx.s.overwrite(
  23230. callee.start + startOffset,
  23231. callee.end + startOffset,
  23232. "__expose"
  23233. );
  23234. } else {
  23235. processDefineModel(ctx, expr);
  23236. }
  23237. }
  23238. if (node.type === "VariableDeclaration" && !node.declare) {
  23239. const total = node.declarations.length;
  23240. let left = total;
  23241. let lastNonRemoved;
  23242. for (let i = 0; i < total; i++) {
  23243. const decl = node.declarations[i];
  23244. const init = decl.init && CompilerDOM.unwrapTSNode(decl.init);
  23245. if (init) {
  23246. if (processDefineOptions(ctx, init)) {
  23247. ctx.error(
  23248. `${DEFINE_OPTIONS}() has no returning value, it cannot be assigned.`,
  23249. node
  23250. );
  23251. }
  23252. const isDefineProps = processDefineProps(ctx, init, decl.id);
  23253. if (ctx.propsDestructureRestId) {
  23254. setupBindings[ctx.propsDestructureRestId] = "setup-reactive-const";
  23255. }
  23256. const isDefineEmits = !isDefineProps && processDefineEmits(ctx, init, decl.id);
  23257. !isDefineEmits && (processDefineSlots(ctx, init, decl.id) || processDefineModel(ctx, init, decl.id));
  23258. if (isDefineProps && !ctx.propsDestructureRestId && ctx.propsDestructureDecl) {
  23259. if (left === 1) {
  23260. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  23261. } else {
  23262. let start = decl.start + startOffset;
  23263. let end = decl.end + startOffset;
  23264. if (i === total - 1) {
  23265. start = node.declarations[lastNonRemoved].end + startOffset;
  23266. } else {
  23267. end = node.declarations[i + 1].start + startOffset;
  23268. }
  23269. ctx.s.remove(start, end);
  23270. left--;
  23271. }
  23272. } else if (isDefineEmits) {
  23273. ctx.s.overwrite(
  23274. startOffset + init.start,
  23275. startOffset + init.end,
  23276. "__emit"
  23277. );
  23278. } else {
  23279. lastNonRemoved = i;
  23280. }
  23281. }
  23282. }
  23283. }
  23284. let isAllLiteral = false;
  23285. if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  23286. isAllLiteral = walkDeclaration(
  23287. "scriptSetup",
  23288. node,
  23289. setupBindings,
  23290. vueImportAliases,
  23291. hoistStatic,
  23292. !!ctx.propsDestructureDecl
  23293. );
  23294. }
  23295. if (hoistStatic && isAllLiteral) {
  23296. hoistNode(node);
  23297. }
  23298. if (node.type === "VariableDeclaration" && !node.declare || node.type.endsWith("Statement")) {
  23299. const scope = [scriptSetupAst.body];
  23300. estreeWalker.walk(node, {
  23301. enter(child, parent) {
  23302. if (CompilerDOM.isFunctionType(child)) {
  23303. this.skip();
  23304. }
  23305. if (child.type === "BlockStatement") {
  23306. scope.push(child.body);
  23307. }
  23308. if (child.type === "AwaitExpression") {
  23309. hasAwait = true;
  23310. const currentScope = scope[scope.length - 1];
  23311. const needsSemi = currentScope.some((n, i) => {
  23312. return (scope.length === 1 || i > 0) && n.type === "ExpressionStatement" && n.start === child.start;
  23313. });
  23314. processAwait(
  23315. ctx,
  23316. child,
  23317. needsSemi,
  23318. parent.type === "ExpressionStatement"
  23319. );
  23320. }
  23321. },
  23322. exit(node2) {
  23323. if (node2.type === "BlockStatement") scope.pop();
  23324. }
  23325. });
  23326. }
  23327. if (node.type === "ExportNamedDeclaration" && node.exportKind !== "type" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration") {
  23328. ctx.error(
  23329. `<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.`,
  23330. node
  23331. );
  23332. }
  23333. if (ctx.isTS) {
  23334. if (node.type.startsWith("TS") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "VariableDeclaration" && node.declare) {
  23335. if (node.type !== "TSEnumDeclaration") {
  23336. hoistNode(node);
  23337. }
  23338. }
  23339. }
  23340. }
  23341. if (ctx.propsDestructureDecl) {
  23342. transformDestructuredProps(ctx, vueImportAliases);
  23343. }
  23344. checkInvalidScopeReference(ctx.propsRuntimeDecl, DEFINE_PROPS);
  23345. checkInvalidScopeReference(ctx.propsRuntimeDefaults, DEFINE_PROPS);
  23346. checkInvalidScopeReference(ctx.propsDestructureDecl, DEFINE_PROPS);
  23347. checkInvalidScopeReference(ctx.emitsRuntimeDecl, DEFINE_EMITS);
  23348. checkInvalidScopeReference(ctx.optionsRuntimeDecl, DEFINE_OPTIONS);
  23349. for (const { runtimeOptionNodes } of Object.values(ctx.modelDecls)) {
  23350. for (const node of runtimeOptionNodes) {
  23351. checkInvalidScopeReference(node, DEFINE_MODEL);
  23352. }
  23353. }
  23354. if (script) {
  23355. if (startOffset < scriptStartOffset) {
  23356. ctx.s.remove(0, startOffset);
  23357. ctx.s.remove(endOffset, scriptStartOffset);
  23358. ctx.s.remove(scriptEndOffset, source.length);
  23359. } else {
  23360. ctx.s.remove(0, scriptStartOffset);
  23361. ctx.s.remove(scriptEndOffset, startOffset);
  23362. ctx.s.remove(endOffset, source.length);
  23363. }
  23364. } else {
  23365. ctx.s.remove(0, startOffset);
  23366. ctx.s.remove(endOffset, source.length);
  23367. }
  23368. if (scriptAst) {
  23369. Object.assign(ctx.bindingMetadata, analyzeScriptBindings(scriptAst.body));
  23370. }
  23371. for (const [key, { isType, imported, source: source2 }] of Object.entries(
  23372. ctx.userImports
  23373. )) {
  23374. if (isType) continue;
  23375. ctx.bindingMetadata[key] = imported === "*" || imported === "default" && source2.endsWith(".vue") || source2 === "vue" ? "setup-const" : "setup-maybe-ref";
  23376. }
  23377. for (const key in scriptBindings) {
  23378. ctx.bindingMetadata[key] = scriptBindings[key];
  23379. }
  23380. for (const key in setupBindings) {
  23381. ctx.bindingMetadata[key] = setupBindings[key];
  23382. }
  23383. if (sfc.template && !sfc.template.src && sfc.template.ast) {
  23384. const vModelIds = resolveTemplateVModelIdentifiers(sfc);
  23385. if (vModelIds.size) {
  23386. const toDemote = /* @__PURE__ */ new Set();
  23387. for (const id of vModelIds) {
  23388. if (setupBindings[id] === "setup-reactive-const") {
  23389. toDemote.add(id);
  23390. }
  23391. }
  23392. if (toDemote.size) {
  23393. for (const node of scriptSetupAst.body) {
  23394. if (node.type === "VariableDeclaration" && node.kind === "const" && !node.declare) {
  23395. const demotedInDecl = [];
  23396. for (const decl of node.declarations) {
  23397. if (decl.id.type === "Identifier" && toDemote.has(decl.id.name)) {
  23398. demotedInDecl.push(decl.id.name);
  23399. }
  23400. }
  23401. if (demotedInDecl.length) {
  23402. ctx.s.overwrite(
  23403. node.start + startOffset,
  23404. node.start + startOffset + "const".length,
  23405. "let"
  23406. );
  23407. for (const id of demotedInDecl) {
  23408. setupBindings[id] = "setup-let";
  23409. ctx.bindingMetadata[id] = "setup-let";
  23410. warnOnce(
  23411. `\`v-model\` cannot update a \`const\` reactive binding \`${id}\`. The compiler has transformed it to \`let\` to make the update work.`
  23412. );
  23413. }
  23414. }
  23415. }
  23416. }
  23417. }
  23418. }
  23419. }
  23420. if (sfc.cssVars.length && // no need to do this when targeting SSR
  23421. !((_a = options.templateOptions) == null ? void 0 : _a.ssr)) {
  23422. ctx.helperImports.add(CSS_VARS_HELPER);
  23423. ctx.helperImports.add("unref");
  23424. ctx.s.prependLeft(
  23425. startOffset,
  23426. `
  23427. ${genCssVarsCode(
  23428. sfc.cssVars,
  23429. ctx.bindingMetadata,
  23430. scopeId,
  23431. !!options.isProd
  23432. )}
  23433. `
  23434. );
  23435. }
  23436. let args = `__props`;
  23437. if (ctx.propsTypeDecl) {
  23438. args += `: any`;
  23439. }
  23440. if (ctx.propsDecl) {
  23441. if (ctx.propsDestructureRestId) {
  23442. ctx.s.overwrite(
  23443. startOffset + ctx.propsCall.start,
  23444. startOffset + ctx.propsCall.end,
  23445. `${ctx.helper(`createPropsRestProxy`)}(__props, ${JSON.stringify(
  23446. Object.keys(ctx.propsDestructuredBindings)
  23447. )})`
  23448. );
  23449. ctx.s.overwrite(
  23450. startOffset + ctx.propsDestructureDecl.start,
  23451. startOffset + ctx.propsDestructureDecl.end,
  23452. ctx.propsDestructureRestId
  23453. );
  23454. } else if (!ctx.propsDestructureDecl) {
  23455. ctx.s.overwrite(
  23456. startOffset + ctx.propsCall.start,
  23457. startOffset + ctx.propsCall.end,
  23458. "__props"
  23459. );
  23460. }
  23461. }
  23462. if (hasAwait) {
  23463. const any = ctx.isTS ? `: any` : ``;
  23464. ctx.s.prependLeft(startOffset, `
  23465. let __temp${any}, __restore${any}
  23466. `);
  23467. }
  23468. const destructureElements = ctx.hasDefineExposeCall || !options.inlineTemplate ? [`expose: __expose`] : [];
  23469. if (ctx.emitDecl) {
  23470. destructureElements.push(`emit: __emit`);
  23471. }
  23472. if (destructureElements.length) {
  23473. args += `, { ${destructureElements.join(", ")} }`;
  23474. }
  23475. let templateMap;
  23476. let returned;
  23477. const propsDecl = genRuntimeProps(ctx);
  23478. if (!options.inlineTemplate || !sfc.template && ctx.hasDefaultExportRender) {
  23479. const allBindings = {
  23480. ...scriptBindings,
  23481. ...setupBindings
  23482. };
  23483. for (const key in ctx.userImports) {
  23484. if (!ctx.userImports[key].isType && ctx.userImports[key].isUsedInTemplate) {
  23485. allBindings[key] = true;
  23486. }
  23487. }
  23488. returned = `{ `;
  23489. for (const key in allBindings) {
  23490. if (allBindings[key] === true && ctx.userImports[key].source !== "vue" && !ctx.userImports[key].source.endsWith(".vue")) {
  23491. returned += `get ${key}() { return ${key} }, `;
  23492. } else if (ctx.bindingMetadata[key] === "setup-let") {
  23493. const setArg = key === "v" ? `_v` : `v`;
  23494. returned += `get ${key}() { return ${key} }, set ${key}(${setArg}) { ${key} = ${setArg} }, `;
  23495. } else {
  23496. returned += `${key}, `;
  23497. }
  23498. }
  23499. returned = returned.replace(/, $/, "") + ` }`;
  23500. } else {
  23501. if (sfc.template && !sfc.template.src) {
  23502. if (options.templateOptions && options.templateOptions.ssr) {
  23503. hasInlinedSsrRenderFn = true;
  23504. }
  23505. const { code, ast, preamble, tips, errors, map: map2 } = compileTemplate({
  23506. filename,
  23507. ast: sfc.template.ast,
  23508. source: sfc.template.content,
  23509. inMap: sfc.template.map,
  23510. ...options.templateOptions,
  23511. id: scopeId,
  23512. scoped: sfc.styles.some((s) => s.scoped),
  23513. isProd: options.isProd,
  23514. ssrCssVars: sfc.cssVars,
  23515. compilerOptions: {
  23516. ...options.templateOptions && options.templateOptions.compilerOptions,
  23517. inline: true,
  23518. isTS: ctx.isTS,
  23519. bindingMetadata: ctx.bindingMetadata
  23520. }
  23521. });
  23522. templateMap = map2;
  23523. if (tips.length) {
  23524. tips.forEach(warnOnce);
  23525. }
  23526. const err = errors[0];
  23527. if (typeof err === "string") {
  23528. throw new Error(err);
  23529. } else if (err) {
  23530. if (err.loc) {
  23531. err.message += `
  23532. ` + sfc.filename + "\n" + shared.generateCodeFrame(
  23533. source,
  23534. err.loc.start.offset,
  23535. err.loc.end.offset
  23536. ) + `
  23537. `;
  23538. }
  23539. throw err;
  23540. }
  23541. if (preamble) {
  23542. ctx.s.prepend(preamble);
  23543. }
  23544. if (ast && ast.helpers.has(CompilerDOM.UNREF)) {
  23545. ctx.helperImports.delete("unref");
  23546. }
  23547. returned = code;
  23548. } else {
  23549. returned = `() => {}`;
  23550. }
  23551. }
  23552. if (!options.inlineTemplate && true) {
  23553. ctx.s.appendRight(
  23554. endOffset,
  23555. `
  23556. const __returned__ = ${returned}
  23557. Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })
  23558. return __returned__
  23559. }
  23560. `
  23561. );
  23562. } else {
  23563. ctx.s.appendRight(endOffset, `
  23564. return ${returned}
  23565. }
  23566. `);
  23567. }
  23568. const genDefaultAs = options.genDefaultAs ? `const ${options.genDefaultAs} =` : `export default`;
  23569. let runtimeOptions = ``;
  23570. if (!ctx.hasDefaultExportName && filename && filename !== DEFAULT_FILENAME) {
  23571. const match = filename.match(/([^/\\]+)\.\w+$/);
  23572. if (match) {
  23573. runtimeOptions += `
  23574. __name: '${match[1]}',`;
  23575. }
  23576. }
  23577. if (hasInlinedSsrRenderFn) {
  23578. runtimeOptions += `
  23579. __ssrInlineRender: true,`;
  23580. }
  23581. if (propsDecl) runtimeOptions += `
  23582. props: ${propsDecl},`;
  23583. const emitsDecl = genRuntimeEmits(ctx);
  23584. if (emitsDecl) runtimeOptions += `
  23585. emits: ${emitsDecl},`;
  23586. let definedOptions = "";
  23587. if (ctx.optionsRuntimeDecl) {
  23588. definedOptions = scriptSetup.content.slice(ctx.optionsRuntimeDecl.start, ctx.optionsRuntimeDecl.end).trim();
  23589. }
  23590. const exposeCall = ctx.hasDefineExposeCall || options.inlineTemplate ? `` : ` __expose();
  23591. `;
  23592. if (ctx.isTS) {
  23593. const def = (defaultExport ? `
  23594. ...${normalScriptDefaultVar},` : ``) + (definedOptions ? `
  23595. ...${definedOptions},` : "");
  23596. ctx.s.prependLeft(
  23597. startOffset,
  23598. `
  23599. ${genDefaultAs} /*@__PURE__*/${ctx.helper(
  23600. `defineComponent`
  23601. )}({${def}${runtimeOptions}
  23602. ${hasAwait ? `async ` : ``}setup(${args}) {
  23603. ${exposeCall}`
  23604. );
  23605. ctx.s.appendRight(endOffset, `})`);
  23606. } else {
  23607. if (defaultExport || definedOptions) {
  23608. ctx.s.prependLeft(
  23609. startOffset,
  23610. `
  23611. ${genDefaultAs} /*@__PURE__*/Object.assign(${defaultExport ? `${normalScriptDefaultVar}, ` : ""}${definedOptions ? `${definedOptions}, ` : ""}{${runtimeOptions}
  23612. ${hasAwait ? `async ` : ``}setup(${args}) {
  23613. ${exposeCall}`
  23614. );
  23615. ctx.s.appendRight(endOffset, `})`);
  23616. } else {
  23617. ctx.s.prependLeft(
  23618. startOffset,
  23619. `
  23620. ${genDefaultAs} {${runtimeOptions}
  23621. ${hasAwait ? `async ` : ``}setup(${args}) {
  23622. ${exposeCall}`
  23623. );
  23624. ctx.s.appendRight(endOffset, `}`);
  23625. }
  23626. }
  23627. if (ctx.helperImports.size > 0) {
  23628. const runtimeModuleName = (_c = (_b = options.templateOptions) == null ? void 0 : _b.compilerOptions) == null ? void 0 : _c.runtimeModuleName;
  23629. const importSrc = runtimeModuleName ? JSON.stringify(runtimeModuleName) : `'vue'`;
  23630. ctx.s.prepend(
  23631. `import { ${[...ctx.helperImports].map((h) => `${h} as _${h}`).join(", ")} } from ${importSrc}
  23632. `
  23633. );
  23634. }
  23635. const content = ctx.s.toString();
  23636. let map = options.sourceMap !== false ? ctx.s.generateMap({
  23637. source: filename,
  23638. hires: true,
  23639. includeContent: true
  23640. }) : void 0;
  23641. if (templateMap && map) {
  23642. const offset = content.indexOf(returned);
  23643. const templateLineOffset = content.slice(0, offset).split(/\r?\n/).length - 1;
  23644. map = mergeSourceMaps(map, templateMap, templateLineOffset);
  23645. }
  23646. return {
  23647. ...scriptSetup,
  23648. bindings: ctx.bindingMetadata,
  23649. imports: ctx.userImports,
  23650. content,
  23651. map,
  23652. scriptAst: scriptAst == null ? void 0 : scriptAst.body,
  23653. scriptSetupAst: scriptSetupAst == null ? void 0 : scriptSetupAst.body,
  23654. deps: ctx.deps ? [...ctx.deps] : void 0
  23655. };
  23656. }
  23657. function registerBinding(bindings, node, type) {
  23658. bindings[node.name] = type;
  23659. }
  23660. function walkDeclaration(from, node, bindings, userImportAliases, hoistStatic, isPropsDestructureEnabled = false) {
  23661. let isAllLiteral = false;
  23662. if (node.type === "VariableDeclaration") {
  23663. const isConst = node.kind === "const";
  23664. isAllLiteral = isConst && node.declarations.every(
  23665. (decl) => decl.id.type === "Identifier" && isStaticNode(decl.init)
  23666. );
  23667. for (const { id, init: _init } of node.declarations) {
  23668. const init = _init && CompilerDOM.unwrapTSNode(_init);
  23669. const isConstMacroCall = isConst && isCallOf(
  23670. init,
  23671. (c) => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS || c === DEFINE_SLOTS
  23672. );
  23673. if (id.type === "Identifier") {
  23674. let bindingType;
  23675. const userReactiveBinding = userImportAliases["reactive"];
  23676. if ((hoistStatic || from === "script") && (isAllLiteral || isConst && isStaticNode(init))) {
  23677. bindingType = "literal-const";
  23678. } else if (isCallOf(init, userReactiveBinding)) {
  23679. bindingType = isConst ? "setup-reactive-const" : "setup-let";
  23680. } else if (
  23681. // if a declaration is a const literal, we can mark it so that
  23682. // the generated render fn code doesn't need to unref() it
  23683. isConstMacroCall || isConst && canNeverBeRef(init, userReactiveBinding)
  23684. ) {
  23685. bindingType = isCallOf(init, DEFINE_PROPS) ? "setup-reactive-const" : "setup-const";
  23686. } else if (isConst) {
  23687. if (isCallOf(
  23688. init,
  23689. (m) => m === userImportAliases["ref"] || m === userImportAliases["computed"] || m === userImportAliases["shallowRef"] || m === userImportAliases["customRef"] || m === userImportAliases["toRef"] || m === userImportAliases["useTemplateRef"] || m === DEFINE_MODEL
  23690. )) {
  23691. bindingType = "setup-ref";
  23692. } else {
  23693. bindingType = "setup-maybe-ref";
  23694. }
  23695. } else {
  23696. bindingType = "setup-let";
  23697. }
  23698. registerBinding(bindings, id, bindingType);
  23699. } else {
  23700. if (isCallOf(init, DEFINE_PROPS) && isPropsDestructureEnabled) {
  23701. continue;
  23702. }
  23703. if (id.type === "ObjectPattern") {
  23704. walkObjectPattern(id, bindings, isConst, isConstMacroCall);
  23705. } else if (id.type === "ArrayPattern") {
  23706. walkArrayPattern(id, bindings, isConst, isConstMacroCall);
  23707. }
  23708. }
  23709. }
  23710. } else if (node.type === "TSEnumDeclaration") {
  23711. isAllLiteral = node.members.every(
  23712. (member) => !member.initializer || isStaticNode(member.initializer)
  23713. );
  23714. bindings[node.id.name] = isAllLiteral ? "literal-const" : "setup-const";
  23715. } else if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
  23716. bindings[node.id.name] = "setup-const";
  23717. }
  23718. return isAllLiteral;
  23719. }
  23720. function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
  23721. for (const p of node.properties) {
  23722. if (p.type === "ObjectProperty") {
  23723. if (p.key.type === "Identifier" && p.key === p.value) {
  23724. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  23725. registerBinding(bindings, p.key, type);
  23726. } else {
  23727. walkPattern(p.value, bindings, isConst, isDefineCall);
  23728. }
  23729. } else {
  23730. const type = isConst ? "setup-const" : "setup-let";
  23731. registerBinding(bindings, p.argument, type);
  23732. }
  23733. }
  23734. }
  23735. function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
  23736. for (const e of node.elements) {
  23737. e && walkPattern(e, bindings, isConst, isDefineCall);
  23738. }
  23739. }
  23740. function walkPattern(node, bindings, isConst, isDefineCall = false) {
  23741. if (node.type === "Identifier") {
  23742. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  23743. registerBinding(bindings, node, type);
  23744. } else if (node.type === "RestElement") {
  23745. const type = isConst ? "setup-const" : "setup-let";
  23746. registerBinding(bindings, node.argument, type);
  23747. } else if (node.type === "ObjectPattern") {
  23748. walkObjectPattern(node, bindings, isConst);
  23749. } else if (node.type === "ArrayPattern") {
  23750. walkArrayPattern(node, bindings, isConst);
  23751. } else if (node.type === "AssignmentPattern") {
  23752. if (node.left.type === "Identifier") {
  23753. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  23754. registerBinding(bindings, node.left, type);
  23755. } else {
  23756. walkPattern(node.left, bindings, isConst);
  23757. }
  23758. }
  23759. }
  23760. function canNeverBeRef(node, userReactiveImport) {
  23761. if (isCallOf(node, userReactiveImport)) {
  23762. return true;
  23763. }
  23764. switch (node.type) {
  23765. case "UnaryExpression":
  23766. case "BinaryExpression":
  23767. case "ArrayExpression":
  23768. case "ObjectExpression":
  23769. case "FunctionExpression":
  23770. case "ArrowFunctionExpression":
  23771. case "UpdateExpression":
  23772. case "ClassExpression":
  23773. case "TaggedTemplateExpression":
  23774. return true;
  23775. case "SequenceExpression":
  23776. return canNeverBeRef(
  23777. node.expressions[node.expressions.length - 1],
  23778. userReactiveImport
  23779. );
  23780. default:
  23781. if (isLiteralNode(node)) {
  23782. return true;
  23783. }
  23784. return false;
  23785. }
  23786. }
  23787. function isStaticNode(node) {
  23788. node = CompilerDOM.unwrapTSNode(node);
  23789. switch (node.type) {
  23790. case "UnaryExpression":
  23791. return isStaticNode(node.argument);
  23792. case "LogicalExpression":
  23793. // 1 > 2
  23794. case "BinaryExpression":
  23795. return isStaticNode(node.left) && isStaticNode(node.right);
  23796. case "ConditionalExpression": {
  23797. return isStaticNode(node.test) && isStaticNode(node.consequent) && isStaticNode(node.alternate);
  23798. }
  23799. case "SequenceExpression":
  23800. // (1, 2)
  23801. case "TemplateLiteral":
  23802. return node.expressions.every((expr) => isStaticNode(expr));
  23803. case "ParenthesizedExpression":
  23804. return isStaticNode(node.expression);
  23805. case "StringLiteral":
  23806. case "NumericLiteral":
  23807. case "BooleanLiteral":
  23808. case "NullLiteral":
  23809. case "BigIntLiteral":
  23810. return true;
  23811. }
  23812. return false;
  23813. }
  23814. function mergeSourceMaps(scriptMap, templateMap, templateLineOffset) {
  23815. const generator = new sourceMapJs.SourceMapGenerator();
  23816. const addMapping = (map, lineOffset = 0) => {
  23817. const consumer = new sourceMapJs.SourceMapConsumer(map);
  23818. consumer.sources.forEach((sourceFile) => {
  23819. generator._sources.add(sourceFile);
  23820. const sourceContent = consumer.sourceContentFor(sourceFile);
  23821. if (sourceContent != null) {
  23822. generator.setSourceContent(sourceFile, sourceContent);
  23823. }
  23824. });
  23825. consumer.eachMapping((m) => {
  23826. if (m.originalLine == null) return;
  23827. generator.addMapping({
  23828. generated: {
  23829. line: m.generatedLine + lineOffset,
  23830. column: m.generatedColumn
  23831. },
  23832. original: {
  23833. line: m.originalLine,
  23834. column: m.originalColumn
  23835. },
  23836. source: m.source,
  23837. name: m.name
  23838. });
  23839. });
  23840. };
  23841. addMapping(scriptMap);
  23842. addMapping(templateMap, templateLineOffset);
  23843. generator._sourceRoot = scriptMap.sourceRoot;
  23844. generator._file = scriptMap.file;
  23845. return generator.toJSON();
  23846. }
  23847. const version = "3.5.33";
  23848. const parseCache = parseCache$1;
  23849. const errorMessages = {
  23850. ...CompilerDOM.errorMessages,
  23851. ...CompilerDOM.DOMErrorMessages
  23852. };
  23853. const walk = estreeWalker.walk;
  23854. const shouldTransformRef = () => false;
  23855. exports.extractIdentifiers = compilerCore.extractIdentifiers;
  23856. exports.generateCodeFrame = compilerCore.generateCodeFrame;
  23857. exports.isInDestructureAssignment = compilerCore.isInDestructureAssignment;
  23858. exports.isStaticProperty = compilerCore.isStaticProperty;
  23859. exports.walkIdentifiers = compilerCore.walkIdentifiers;
  23860. exports.MagicString = MagicString;
  23861. exports.babelParse = parser$2.parse;
  23862. exports.compileScript = compileScript;
  23863. exports.compileStyle = compileStyle;
  23864. exports.compileStyleAsync = compileStyleAsync;
  23865. exports.compileTemplate = compileTemplate;
  23866. exports.errorMessages = errorMessages;
  23867. exports.extractRuntimeEmits = extractRuntimeEmits;
  23868. exports.extractRuntimeProps = extractRuntimeProps;
  23869. exports.inferRuntimeType = inferRuntimeType;
  23870. exports.invalidateTypeCache = invalidateTypeCache;
  23871. exports.parse = parse$1;
  23872. exports.parseCache = parseCache;
  23873. exports.registerTS = registerTS;
  23874. exports.resolveTypeElements = resolveTypeElements;
  23875. exports.rewriteDefault = rewriteDefault;
  23876. exports.rewriteDefaultAST = rewriteDefaultAST;
  23877. exports.shouldTransformRef = shouldTransformRef;
  23878. exports.version = version;
  23879. exports.walk = walk;