compiler-sfc.cjs.js 819 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019
  1. /**
  2. * @vue/compiler-sfc v3.5.18
  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);
  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 templateUsageCheckCache = createCache();
  1687. function resolveTemplateUsedIdentifiers(sfc) {
  1688. const { content, ast } = sfc.template;
  1689. const cached = templateUsageCheckCache.get(content);
  1690. if (cached) {
  1691. return cached;
  1692. }
  1693. const ids = /* @__PURE__ */ new Set();
  1694. ast.children.forEach(walk);
  1695. function walk(node) {
  1696. var _a;
  1697. switch (node.type) {
  1698. case 1:
  1699. let tag = node.tag;
  1700. if (tag.includes(".")) tag = tag.split(".")[0].trim();
  1701. if (!CompilerDOM.parserOptions.isNativeTag(tag) && !CompilerDOM.parserOptions.isBuiltInComponent(tag)) {
  1702. ids.add(shared.camelize(tag));
  1703. ids.add(shared.capitalize(shared.camelize(tag)));
  1704. }
  1705. for (let i = 0; i < node.props.length; i++) {
  1706. const prop = node.props[i];
  1707. if (prop.type === 7) {
  1708. if (!shared.isBuiltInDirective(prop.name)) {
  1709. ids.add(`v${shared.capitalize(shared.camelize(prop.name))}`);
  1710. }
  1711. if (prop.arg && !prop.arg.isStatic) {
  1712. extractIdentifiers(ids, prop.arg);
  1713. }
  1714. if (prop.name === "for") {
  1715. extractIdentifiers(ids, prop.forParseResult.source);
  1716. } else if (prop.exp) {
  1717. extractIdentifiers(ids, prop.exp);
  1718. } else if (prop.name === "bind" && !prop.exp) {
  1719. ids.add(shared.camelize(prop.arg.content));
  1720. }
  1721. }
  1722. if (prop.type === 6 && prop.name === "ref" && ((_a = prop.value) == null ? void 0 : _a.content)) {
  1723. ids.add(prop.value.content);
  1724. }
  1725. }
  1726. node.children.forEach(walk);
  1727. break;
  1728. case 5:
  1729. extractIdentifiers(ids, node.content);
  1730. break;
  1731. }
  1732. }
  1733. templateUsageCheckCache.set(content, ids);
  1734. return ids;
  1735. }
  1736. function extractIdentifiers(ids, node) {
  1737. if (node.ast) {
  1738. CompilerDOM.walkIdentifiers(node.ast, (n) => ids.add(n.name));
  1739. } else if (node.ast === null) {
  1740. ids.add(node.content);
  1741. }
  1742. }
  1743. const DEFAULT_FILENAME = "anonymous.vue";
  1744. const parseCache$1 = createCache();
  1745. function parse$1(source, options = {}) {
  1746. var _a;
  1747. const sourceKey = shared.genCacheKey(source, {
  1748. ...options,
  1749. compiler: { parse: (_a = options.compiler) == null ? void 0 : _a.parse }
  1750. });
  1751. const cache = parseCache$1.get(sourceKey);
  1752. if (cache) {
  1753. return cache;
  1754. }
  1755. const {
  1756. sourceMap = true,
  1757. filename = DEFAULT_FILENAME,
  1758. sourceRoot = "",
  1759. pad = false,
  1760. ignoreEmpty = true,
  1761. compiler = CompilerDOM__namespace,
  1762. templateParseOptions = {}
  1763. } = options;
  1764. const descriptor = {
  1765. filename,
  1766. source,
  1767. template: null,
  1768. script: null,
  1769. scriptSetup: null,
  1770. styles: [],
  1771. customBlocks: [],
  1772. cssVars: [],
  1773. slotted: false,
  1774. shouldForceReload: (prevImports) => hmrShouldReload(prevImports, descriptor)
  1775. };
  1776. const errors = [];
  1777. const ast = compiler.parse(source, {
  1778. parseMode: "sfc",
  1779. prefixIdentifiers: true,
  1780. ...templateParseOptions,
  1781. onError: (e) => {
  1782. errors.push(e);
  1783. }
  1784. });
  1785. ast.children.forEach((node) => {
  1786. if (node.type !== 1) {
  1787. return;
  1788. }
  1789. if (ignoreEmpty && node.tag !== "template" && isEmpty(node) && !hasSrc(node)) {
  1790. return;
  1791. }
  1792. switch (node.tag) {
  1793. case "template":
  1794. if (!descriptor.template) {
  1795. const templateBlock = descriptor.template = createBlock(
  1796. node,
  1797. source,
  1798. false
  1799. );
  1800. if (!templateBlock.attrs.src) {
  1801. templateBlock.ast = compilerCore.createRoot(node.children, source);
  1802. }
  1803. if (templateBlock.attrs.functional) {
  1804. const err = new SyntaxError(
  1805. `<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.`
  1806. );
  1807. err.loc = node.props.find(
  1808. (p) => p.type === 6 && p.name === "functional"
  1809. ).loc;
  1810. errors.push(err);
  1811. }
  1812. } else {
  1813. errors.push(createDuplicateBlockError(node));
  1814. }
  1815. break;
  1816. case "script":
  1817. const scriptBlock = createBlock(node, source, pad);
  1818. const isSetup = !!scriptBlock.attrs.setup;
  1819. if (isSetup && !descriptor.scriptSetup) {
  1820. descriptor.scriptSetup = scriptBlock;
  1821. break;
  1822. }
  1823. if (!isSetup && !descriptor.script) {
  1824. descriptor.script = scriptBlock;
  1825. break;
  1826. }
  1827. errors.push(createDuplicateBlockError(node, isSetup));
  1828. break;
  1829. case "style":
  1830. const styleBlock = createBlock(node, source, pad);
  1831. if (styleBlock.attrs.vars) {
  1832. errors.push(
  1833. new SyntaxError(
  1834. `<style vars> has been replaced by a new proposal: https://github.com/vuejs/rfcs/pull/231`
  1835. )
  1836. );
  1837. }
  1838. descriptor.styles.push(styleBlock);
  1839. break;
  1840. default:
  1841. descriptor.customBlocks.push(createBlock(node, source, pad));
  1842. break;
  1843. }
  1844. });
  1845. if (!descriptor.template && !descriptor.script && !descriptor.scriptSetup) {
  1846. errors.push(
  1847. new SyntaxError(
  1848. `At least one <template> or <script> is required in a single file component. ${descriptor.filename}`
  1849. )
  1850. );
  1851. }
  1852. if (descriptor.scriptSetup) {
  1853. if (descriptor.scriptSetup.src) {
  1854. errors.push(
  1855. new SyntaxError(
  1856. `<script setup> cannot use the "src" attribute because its syntax will be ambiguous outside of the component.`
  1857. )
  1858. );
  1859. descriptor.scriptSetup = null;
  1860. }
  1861. if (descriptor.script && descriptor.script.src) {
  1862. errors.push(
  1863. new SyntaxError(
  1864. `<script> cannot use the "src" attribute when <script setup> is also present because they must be processed together.`
  1865. )
  1866. );
  1867. descriptor.script = null;
  1868. }
  1869. }
  1870. let templateColumnOffset = 0;
  1871. if (descriptor.template && (descriptor.template.lang === "pug" || descriptor.template.lang === "jade")) {
  1872. [descriptor.template.content, templateColumnOffset] = dedent(
  1873. descriptor.template.content
  1874. );
  1875. }
  1876. if (sourceMap) {
  1877. const genMap = (block, columnOffset = 0) => {
  1878. if (block && !block.src) {
  1879. block.map = generateSourceMap(
  1880. filename,
  1881. source,
  1882. block.content,
  1883. sourceRoot,
  1884. !pad || block.type === "template" ? block.loc.start.line - 1 : 0,
  1885. columnOffset
  1886. );
  1887. }
  1888. };
  1889. genMap(descriptor.template, templateColumnOffset);
  1890. genMap(descriptor.script);
  1891. descriptor.styles.forEach((s) => genMap(s));
  1892. descriptor.customBlocks.forEach((s) => genMap(s));
  1893. }
  1894. descriptor.cssVars = parseCssVars(descriptor);
  1895. const slottedRE = /(?:::v-|:)slotted\(/;
  1896. descriptor.slotted = descriptor.styles.some(
  1897. (s) => s.scoped && slottedRE.test(s.content)
  1898. );
  1899. const result = {
  1900. descriptor,
  1901. errors
  1902. };
  1903. parseCache$1.set(sourceKey, result);
  1904. return result;
  1905. }
  1906. function createDuplicateBlockError(node, isScriptSetup = false) {
  1907. const err = new SyntaxError(
  1908. `Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element`
  1909. );
  1910. err.loc = node.loc;
  1911. return err;
  1912. }
  1913. function createBlock(node, source, pad) {
  1914. const type = node.tag;
  1915. const loc = node.innerLoc;
  1916. const attrs = {};
  1917. const block = {
  1918. type,
  1919. content: source.slice(loc.start.offset, loc.end.offset),
  1920. loc,
  1921. attrs
  1922. };
  1923. if (pad) {
  1924. block.content = padContent(source, block, pad) + block.content;
  1925. }
  1926. node.props.forEach((p) => {
  1927. if (p.type === 6) {
  1928. const name = p.name;
  1929. attrs[name] = p.value ? p.value.content || true : true;
  1930. if (name === "lang") {
  1931. block.lang = p.value && p.value.content;
  1932. } else if (name === "src") {
  1933. block.src = p.value && p.value.content;
  1934. } else if (type === "style") {
  1935. if (name === "scoped") {
  1936. block.scoped = true;
  1937. } else if (name === "module") {
  1938. block.module = attrs[name];
  1939. }
  1940. } else if (type === "script" && name === "setup") {
  1941. block.setup = attrs.setup;
  1942. }
  1943. }
  1944. });
  1945. return block;
  1946. }
  1947. const splitRE = /\r?\n/g;
  1948. const emptyRE = /^(?:\/\/)?\s*$/;
  1949. const replaceRE = /./g;
  1950. function generateSourceMap(filename, source, generated, sourceRoot, lineOffset, columnOffset) {
  1951. const map = new sourceMapJs.SourceMapGenerator({
  1952. file: filename.replace(/\\/g, "/"),
  1953. sourceRoot: sourceRoot.replace(/\\/g, "/")
  1954. });
  1955. map.setSourceContent(filename, source);
  1956. map._sources.add(filename);
  1957. generated.split(splitRE).forEach((line, index) => {
  1958. if (!emptyRE.test(line)) {
  1959. const originalLine = index + 1 + lineOffset;
  1960. const generatedLine = index + 1;
  1961. for (let i = 0; i < line.length; i++) {
  1962. if (!/\s/.test(line[i])) {
  1963. map._mappings.add({
  1964. originalLine,
  1965. originalColumn: i + columnOffset,
  1966. generatedLine,
  1967. generatedColumn: i,
  1968. source: filename,
  1969. name: null
  1970. });
  1971. }
  1972. }
  1973. }
  1974. });
  1975. return map.toJSON();
  1976. }
  1977. function padContent(content, block, pad) {
  1978. content = content.slice(0, block.loc.start.offset);
  1979. if (pad === "space") {
  1980. return content.replace(replaceRE, " ");
  1981. } else {
  1982. const offset = content.split(splitRE).length;
  1983. const padChar = block.type === "script" && !block.lang ? "//\n" : "\n";
  1984. return Array(offset).join(padChar);
  1985. }
  1986. }
  1987. function hasSrc(node) {
  1988. return node.props.some((p) => {
  1989. if (p.type !== 6) {
  1990. return false;
  1991. }
  1992. return p.name === "src";
  1993. });
  1994. }
  1995. function isEmpty(node) {
  1996. for (let i = 0; i < node.children.length; i++) {
  1997. const child = node.children[i];
  1998. if (child.type !== 2 || child.content.trim() !== "") {
  1999. return false;
  2000. }
  2001. }
  2002. return true;
  2003. }
  2004. function hmrShouldReload(prevImports, next) {
  2005. if (!next.scriptSetup || next.scriptSetup.lang !== "ts" && next.scriptSetup.lang !== "tsx") {
  2006. return false;
  2007. }
  2008. for (const key in prevImports) {
  2009. if (!prevImports[key].isUsedInTemplate && isImportUsed(key, next)) {
  2010. return true;
  2011. }
  2012. }
  2013. return false;
  2014. }
  2015. function dedent(s) {
  2016. const lines = s.split("\n");
  2017. const minIndent = lines.reduce(function(minIndent2, line) {
  2018. var _a, _b;
  2019. if (line.trim() === "") {
  2020. return minIndent2;
  2021. }
  2022. const indent = ((_b = (_a = line.match(/^\s*/)) == null ? void 0 : _a[0]) == null ? void 0 : _b.length) || 0;
  2023. return Math.min(indent, minIndent2);
  2024. }, Infinity);
  2025. if (minIndent === 0) {
  2026. return [s, minIndent];
  2027. }
  2028. return [
  2029. lines.map(function(line) {
  2030. return line.slice(minIndent);
  2031. }).join("\n"),
  2032. minIndent
  2033. ];
  2034. }
  2035. function isRelativeUrl(url) {
  2036. const firstChar = url.charAt(0);
  2037. return firstChar === "." || firstChar === "~" || firstChar === "@";
  2038. }
  2039. const externalRE = /^(https?:)?\/\//;
  2040. function isExternalUrl(url) {
  2041. return externalRE.test(url);
  2042. }
  2043. const dataUrlRE = /^\s*data:/i;
  2044. function isDataUrl(url) {
  2045. return dataUrlRE.test(url);
  2046. }
  2047. function parseUrl(url) {
  2048. const firstChar = url.charAt(0);
  2049. if (firstChar === "~") {
  2050. const secondChar = url.charAt(1);
  2051. url = url.slice(secondChar === "/" ? 2 : 1);
  2052. }
  2053. return parseUriParts(url);
  2054. }
  2055. function parseUriParts(urlString) {
  2056. return url.parse(shared.isString(urlString) ? urlString : "", false, true);
  2057. }
  2058. const defaultAssetUrlOptions = {
  2059. base: null,
  2060. includeAbsolute: false,
  2061. tags: {
  2062. video: ["src", "poster"],
  2063. source: ["src"],
  2064. img: ["src"],
  2065. image: ["xlink:href", "href"],
  2066. use: ["xlink:href", "href"]
  2067. }
  2068. };
  2069. const normalizeOptions = (options) => {
  2070. if (Object.keys(options).some((key) => shared.isArray(options[key]))) {
  2071. return {
  2072. ...defaultAssetUrlOptions,
  2073. tags: options
  2074. };
  2075. }
  2076. return {
  2077. ...defaultAssetUrlOptions,
  2078. ...options
  2079. };
  2080. };
  2081. const createAssetUrlTransformWithOptions = (options) => {
  2082. return (node, context) => transformAssetUrl(node, context, options);
  2083. };
  2084. const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
  2085. if (node.type === 1) {
  2086. if (!node.props.length) {
  2087. return;
  2088. }
  2089. const tags = options.tags || defaultAssetUrlOptions.tags;
  2090. const attrs = tags[node.tag];
  2091. const wildCardAttrs = tags["*"];
  2092. if (!attrs && !wildCardAttrs) {
  2093. return;
  2094. }
  2095. const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
  2096. node.props.forEach((attr, index) => {
  2097. if (attr.type !== 6 || !assetAttrs.includes(attr.name) || !attr.value || isExternalUrl(attr.value.content) || isDataUrl(attr.value.content) || attr.value.content[0] === "#" || !options.includeAbsolute && !isRelativeUrl(attr.value.content)) {
  2098. return;
  2099. }
  2100. const url = parseUrl(attr.value.content);
  2101. if (options.base && attr.value.content[0] === ".") {
  2102. const base = parseUrl(options.base);
  2103. const protocol = base.protocol || "";
  2104. const host = base.host ? protocol + "//" + base.host : "";
  2105. const basePath = base.path || "/";
  2106. attr.value.content = host + (path$1.posix || path$1).join(basePath, url.path + (url.hash || ""));
  2107. return;
  2108. }
  2109. const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
  2110. node.props[index] = {
  2111. type: 7,
  2112. name: "bind",
  2113. arg: compilerCore.createSimpleExpression(attr.name, true, attr.loc),
  2114. exp,
  2115. modifiers: [],
  2116. loc: attr.loc
  2117. };
  2118. });
  2119. }
  2120. };
  2121. function getImportsExpressionExp(path2, hash, loc, context) {
  2122. if (path2) {
  2123. let name;
  2124. let exp;
  2125. const existingIndex = context.imports.findIndex((i) => i.path === path2);
  2126. if (existingIndex > -1) {
  2127. name = `_imports_${existingIndex}`;
  2128. exp = context.imports[existingIndex].exp;
  2129. } else {
  2130. name = `_imports_${context.imports.length}`;
  2131. exp = compilerCore.createSimpleExpression(
  2132. name,
  2133. false,
  2134. loc,
  2135. 3
  2136. );
  2137. context.imports.push({
  2138. exp,
  2139. path: decodeURIComponent(path2)
  2140. });
  2141. }
  2142. if (!hash) {
  2143. return exp;
  2144. }
  2145. const hashExp = `${name} + '${hash}'`;
  2146. const finalExp = compilerCore.createSimpleExpression(
  2147. hashExp,
  2148. false,
  2149. loc,
  2150. 3
  2151. );
  2152. if (!context.hoistStatic) {
  2153. return finalExp;
  2154. }
  2155. const existingHoistIndex = context.hoists.findIndex((h) => {
  2156. return h && h.type === 4 && !h.isStatic && h.content === hashExp;
  2157. });
  2158. if (existingHoistIndex > -1) {
  2159. return compilerCore.createSimpleExpression(
  2160. `_hoisted_${existingHoistIndex + 1}`,
  2161. false,
  2162. loc,
  2163. 3
  2164. );
  2165. }
  2166. return context.hoist(finalExp);
  2167. } else {
  2168. return compilerCore.createSimpleExpression(`''`, false, loc, 3);
  2169. }
  2170. }
  2171. const srcsetTags = ["img", "source"];
  2172. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  2173. const createSrcsetTransformWithOptions = (options) => {
  2174. return (node, context) => transformSrcset(node, context, options);
  2175. };
  2176. const transformSrcset = (node, context, options = defaultAssetUrlOptions) => {
  2177. if (node.type === 1) {
  2178. if (srcsetTags.includes(node.tag) && node.props.length) {
  2179. node.props.forEach((attr, index) => {
  2180. if (attr.name === "srcset" && attr.type === 6) {
  2181. if (!attr.value) return;
  2182. const value = attr.value.content;
  2183. if (!value) return;
  2184. const imageCandidates = value.split(",").map((s) => {
  2185. const [url, descriptor] = s.replace(escapedSpaceCharacters, " ").trim().split(" ", 2);
  2186. return { url, descriptor };
  2187. });
  2188. for (let i = 0; i < imageCandidates.length; i++) {
  2189. const { url } = imageCandidates[i];
  2190. if (isDataUrl(url)) {
  2191. imageCandidates[i + 1].url = url + "," + imageCandidates[i + 1].url;
  2192. imageCandidates.splice(i, 1);
  2193. }
  2194. }
  2195. const shouldProcessUrl = (url) => {
  2196. return url && !isExternalUrl(url) && !isDataUrl(url) && (options.includeAbsolute || isRelativeUrl(url));
  2197. };
  2198. if (!imageCandidates.some(({ url }) => shouldProcessUrl(url))) {
  2199. return;
  2200. }
  2201. if (options.base) {
  2202. const base = options.base;
  2203. const set = [];
  2204. let needImportTransform = false;
  2205. imageCandidates.forEach((candidate) => {
  2206. let { url, descriptor } = candidate;
  2207. descriptor = descriptor ? ` ${descriptor}` : ``;
  2208. if (url[0] === ".") {
  2209. candidate.url = (path$1.posix || path$1).join(base, url);
  2210. set.push(candidate.url + descriptor);
  2211. } else if (shouldProcessUrl(url)) {
  2212. needImportTransform = true;
  2213. } else {
  2214. set.push(url + descriptor);
  2215. }
  2216. });
  2217. if (!needImportTransform) {
  2218. attr.value.content = set.join(", ");
  2219. return;
  2220. }
  2221. }
  2222. const compoundExpression = compilerCore.createCompoundExpression([], attr.loc);
  2223. imageCandidates.forEach(({ url, descriptor }, index2) => {
  2224. if (shouldProcessUrl(url)) {
  2225. const { path: path2 } = parseUrl(url);
  2226. let exp2;
  2227. if (path2) {
  2228. const existingImportsIndex = context.imports.findIndex(
  2229. (i) => i.path === path2
  2230. );
  2231. if (existingImportsIndex > -1) {
  2232. exp2 = compilerCore.createSimpleExpression(
  2233. `_imports_${existingImportsIndex}`,
  2234. false,
  2235. attr.loc,
  2236. 3
  2237. );
  2238. } else {
  2239. exp2 = compilerCore.createSimpleExpression(
  2240. `_imports_${context.imports.length}`,
  2241. false,
  2242. attr.loc,
  2243. 3
  2244. );
  2245. context.imports.push({ exp: exp2, path: path2 });
  2246. }
  2247. compoundExpression.children.push(exp2);
  2248. }
  2249. } else {
  2250. const exp2 = compilerCore.createSimpleExpression(
  2251. `"${url}"`,
  2252. false,
  2253. attr.loc,
  2254. 3
  2255. );
  2256. compoundExpression.children.push(exp2);
  2257. }
  2258. const isNotLast = imageCandidates.length - 1 > index2;
  2259. if (descriptor && isNotLast) {
  2260. compoundExpression.children.push(` + ' ${descriptor}, ' + `);
  2261. } else if (descriptor) {
  2262. compoundExpression.children.push(` + ' ${descriptor}'`);
  2263. } else if (isNotLast) {
  2264. compoundExpression.children.push(` + ', ' + `);
  2265. }
  2266. });
  2267. let exp = compoundExpression;
  2268. if (context.hoistStatic) {
  2269. exp = context.hoist(compoundExpression);
  2270. exp.constType = 3;
  2271. }
  2272. node.props[index] = {
  2273. type: 7,
  2274. name: "bind",
  2275. arg: compilerCore.createSimpleExpression("srcset", true, attr.loc),
  2276. exp,
  2277. modifiers: [],
  2278. loc: attr.loc
  2279. };
  2280. }
  2281. });
  2282. }
  2283. }
  2284. };
  2285. function commonjsRequire(path) {
  2286. 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.');
  2287. }
  2288. var consolidate$2 = {exports: {}};
  2289. var hasRequiredConsolidate$1;
  2290. function requireConsolidate$1 () {
  2291. if (hasRequiredConsolidate$1) return consolidate$2.exports;
  2292. hasRequiredConsolidate$1 = 1;
  2293. (function (module, exports) {
  2294. /*
  2295. * Engines which do not support caching of their file contents
  2296. * should use the `read()` function defined in consolidate.js
  2297. * On top of this, when an engine compiles to a `Function`,
  2298. * these functions should either be cached within consolidate.js
  2299. * or the engine itself via `options.cache`. This will allow
  2300. * users and frameworks to pass `options.cache = true` for
  2301. * `NODE_ENV=production`, however edit the file(s) without
  2302. * re-loading the application in development.
  2303. */
  2304. /**
  2305. * Module dependencies.
  2306. */
  2307. var fs = require$$0;
  2308. var path = path$1;
  2309. var util = require$$2;
  2310. var join = path.join;
  2311. var resolve = path.resolve;
  2312. var extname = path.extname;
  2313. var dirname = path.dirname;
  2314. var isAbsolute = path.isAbsolute;
  2315. var readCache = {};
  2316. /**
  2317. * Require cache.
  2318. */
  2319. var cacheStore = {};
  2320. /**
  2321. * Require cache.
  2322. */
  2323. var requires = {};
  2324. /**
  2325. * Clear the cache.
  2326. *
  2327. * @api public
  2328. */
  2329. exports.clearCache = function() {
  2330. readCache = {};
  2331. cacheStore = {};
  2332. };
  2333. /**
  2334. * Conditionally cache `compiled` template based
  2335. * on the `options` filename and `.cache` boolean.
  2336. *
  2337. * @param {Object} options
  2338. * @param {Function} compiled
  2339. * @return {Function}
  2340. * @api private
  2341. */
  2342. function cache(options, compiled) {
  2343. // cachable
  2344. if (compiled && options.filename && options.cache) {
  2345. delete readCache[options.filename];
  2346. cacheStore[options.filename] = compiled;
  2347. return compiled;
  2348. }
  2349. // check cache
  2350. if (options.filename && options.cache) {
  2351. return cacheStore[options.filename];
  2352. }
  2353. return compiled;
  2354. }
  2355. /**
  2356. * Read `path` with `options` with
  2357. * callback `(err, str)`. When `options.cache`
  2358. * is true the template string will be cached.
  2359. *
  2360. * @param {String} options
  2361. * @param {Function} cb
  2362. * @api private
  2363. */
  2364. function read(path, options, cb) {
  2365. var str = readCache[path];
  2366. var cached = options.cache && str && typeof str === 'string';
  2367. // cached (only if cached is a string and not a compiled template function)
  2368. if (cached) return cb(null, str);
  2369. // read
  2370. fs.readFile(path, 'utf8', function(err, str) {
  2371. if (err) return cb(err);
  2372. // remove extraneous utf8 BOM marker
  2373. str = str.replace(/^\uFEFF/, '');
  2374. if (options.cache) readCache[path] = str;
  2375. cb(null, str);
  2376. });
  2377. }
  2378. /**
  2379. * Read `path` with `options` with
  2380. * callback `(err, str)`. When `options.cache`
  2381. * is true the partial string will be cached.
  2382. *
  2383. * @param {String} options
  2384. * @param {Function} fn
  2385. * @api private
  2386. */
  2387. function readPartials(path, options, cb) {
  2388. if (!options.partials) return cb();
  2389. var keys = Object.keys(options.partials);
  2390. var partials = {};
  2391. function next(index) {
  2392. if (index === keys.length) return cb(null, partials);
  2393. var key = keys[index];
  2394. var partialPath = options.partials[key];
  2395. if (partialPath === undefined || partialPath === null || partialPath === false) {
  2396. return next(++index);
  2397. }
  2398. var file;
  2399. if (isAbsolute(partialPath)) {
  2400. if (extname(partialPath) !== '') {
  2401. file = partialPath;
  2402. } else {
  2403. file = join(partialPath + extname(path));
  2404. }
  2405. } else {
  2406. file = join(dirname(path), partialPath + extname(path));
  2407. }
  2408. read(file, options, function(err, str) {
  2409. if (err) return cb(err);
  2410. partials[key] = str;
  2411. next(++index);
  2412. });
  2413. }
  2414. next(0);
  2415. }
  2416. /**
  2417. * promisify
  2418. */
  2419. function promisify(cb, fn) {
  2420. return new Promise(function(resolve, reject) {
  2421. cb = cb || function(err, html) {
  2422. if (err) {
  2423. return reject(err);
  2424. }
  2425. resolve(html);
  2426. };
  2427. fn(cb);
  2428. });
  2429. }
  2430. /**
  2431. * fromStringRenderer
  2432. */
  2433. function fromStringRenderer(name) {
  2434. return function(path, options, cb) {
  2435. options.filename = path;
  2436. return promisify(cb, function(cb) {
  2437. readPartials(path, options, function(err, partials) {
  2438. var extend = (requires.extend || (requires.extend = require$$2._extend));
  2439. var opts = extend({}, options);
  2440. opts.partials = partials;
  2441. if (err) return cb(err);
  2442. if (cache(opts)) {
  2443. exports[name].render('', opts, cb);
  2444. } else {
  2445. read(path, opts, function(err, str) {
  2446. if (err) return cb(err);
  2447. exports[name].render(str, opts, cb);
  2448. });
  2449. }
  2450. });
  2451. });
  2452. };
  2453. }
  2454. /**
  2455. * velocity support.
  2456. */
  2457. exports.velocityjs = fromStringRenderer('velocityjs');
  2458. /**
  2459. * velocity string support.
  2460. */
  2461. exports.velocityjs.render = function(str, options, cb) {
  2462. return promisify(cb, function(cb) {
  2463. var engine = requires.velocityjs || (requires.velocityjs = require('velocityjs'));
  2464. try {
  2465. options.locals = options;
  2466. cb(null, engine.render(str, options).trimLeft());
  2467. } catch (err) {
  2468. cb(err);
  2469. }
  2470. });
  2471. };
  2472. /**
  2473. * Liquid support.
  2474. */
  2475. exports.liquid = fromStringRenderer('liquid');
  2476. /**
  2477. * Liquid string support.
  2478. */
  2479. /**
  2480. * Note that in order to get filters and custom tags we've had to push
  2481. * all user-defined locals down into @locals. However, just to make things
  2482. * backwards-compatible, any property of `options` that is left after
  2483. * processing and removing `locals`, `meta`, `filters`, `customTags` and
  2484. * `includeDir` will also become a local.
  2485. */
  2486. function _renderTinyliquid(engine, str, options, cb) {
  2487. var context = engine.newContext();
  2488. var k;
  2489. /**
  2490. * Note that there's a bug in the library that doesn't allow us to pass
  2491. * the locals to newContext(), hence looping through the keys:
  2492. */
  2493. if (options.locals) {
  2494. for (k in options.locals) {
  2495. context.setLocals(k, options.locals[k]);
  2496. }
  2497. delete options.locals;
  2498. }
  2499. if (options.meta) {
  2500. context.setLocals('page', options.meta);
  2501. delete options.meta;
  2502. }
  2503. /**
  2504. * Add any defined filters:
  2505. */
  2506. if (options.filters) {
  2507. for (k in options.filters) {
  2508. context.setFilter(k, options.filters[k]);
  2509. }
  2510. delete options.filters;
  2511. }
  2512. /**
  2513. * Set up a callback for the include directory:
  2514. */
  2515. var includeDir = options.includeDir || process.cwd();
  2516. context.onInclude(function(name, callback) {
  2517. var extname = path.extname(name) ? '' : '.liquid';
  2518. var filename = path.resolve(includeDir, name + extname);
  2519. fs.readFile(filename, {encoding: 'utf8'}, function(err, data) {
  2520. if (err) return callback(err);
  2521. callback(null, engine.parse(data));
  2522. });
  2523. });
  2524. delete options.includeDir;
  2525. /**
  2526. * The custom tag functions need to have their results pushed back
  2527. * through the parser, so set up a shim before calling the provided
  2528. * callback:
  2529. */
  2530. var compileOptions = {
  2531. customTags: {}
  2532. };
  2533. if (options.customTags) {
  2534. var tagFunctions = options.customTags;
  2535. for (k in options.customTags) {
  2536. /*Tell jshint there's no problem with having this function in the loop */
  2537. /*jshint -W083 */
  2538. compileOptions.customTags[k] = function(context, name, body) {
  2539. var tpl = tagFunctions[name](body.trim());
  2540. context.astStack.push(engine.parse(tpl));
  2541. };
  2542. /*jshint +W083 */
  2543. }
  2544. delete options.customTags;
  2545. }
  2546. /**
  2547. * Now anything left in `options` becomes a local:
  2548. */
  2549. for (k in options) {
  2550. context.setLocals(k, options[k]);
  2551. }
  2552. /**
  2553. * Finally, execute the template:
  2554. */
  2555. var tmpl = cache(context) || cache(context, engine.compile(str, compileOptions));
  2556. tmpl(context, cb);
  2557. }
  2558. exports.liquid.render = function(str, options, cb) {
  2559. return promisify(cb, function(cb) {
  2560. var engine = requires.liquid;
  2561. var Liquid;
  2562. try {
  2563. // set up tinyliquid engine
  2564. engine = requires.liquid = require('tinyliquid');
  2565. // use tinyliquid engine
  2566. _renderTinyliquid(engine, str, options, cb);
  2567. return;
  2568. } catch (err) {
  2569. // set up liquid-node engine
  2570. try {
  2571. Liquid = requires.liquid = require('liquid-node');
  2572. engine = new Liquid.Engine();
  2573. } catch (err) {
  2574. throw err;
  2575. }
  2576. }
  2577. // use liquid-node engine
  2578. try {
  2579. var locals = options.locals || {};
  2580. if (options.meta) {
  2581. locals.pages = options.meta;
  2582. delete options.meta;
  2583. }
  2584. /**
  2585. * Add any defined filters:
  2586. */
  2587. if (options.filters) {
  2588. engine.registerFilters(options.filters);
  2589. delete options.filters;
  2590. }
  2591. /**
  2592. * Set up a callback for the include directory:
  2593. */
  2594. var includeDir = options.includeDir || process.cwd();
  2595. engine.fileSystem = new Liquid.LocalFileSystem(includeDir, 'liquid');
  2596. delete options.includeDir;
  2597. /**
  2598. * The custom tag functions need to have their results pushed back
  2599. * through the parser, so set up a shim before calling the provided
  2600. * callback:
  2601. */
  2602. if (options.customTags) {
  2603. var tagFunctions = options.customTags;
  2604. for (k in options.customTags) {
  2605. engine.registerTag(k, tagFunctions[k]);
  2606. }
  2607. delete options.customTags;
  2608. }
  2609. /**
  2610. * Now anything left in `options` becomes a local:
  2611. */
  2612. for (var k in options) {
  2613. locals[k] = options[k];
  2614. }
  2615. /**
  2616. * Finally, execute the template:
  2617. */
  2618. return engine
  2619. .parseAndRender(str, locals)
  2620. .nodeify(function(err, result) {
  2621. if (err) {
  2622. throw new Error(err);
  2623. } else {
  2624. return cb(null, result);
  2625. }
  2626. });
  2627. } catch (err) {
  2628. cb(err);
  2629. }
  2630. });
  2631. };
  2632. /**
  2633. * Jade support.
  2634. */
  2635. exports.jade = function(path, options, cb) {
  2636. return promisify(cb, function(cb) {
  2637. var engine = requires.jade;
  2638. if (!engine) {
  2639. try {
  2640. engine = requires.jade = require('jade');
  2641. } catch (err) {
  2642. try {
  2643. engine = requires.jade = require('then-jade');
  2644. } catch (otherError) {
  2645. throw err;
  2646. }
  2647. }
  2648. }
  2649. try {
  2650. var tmpl = cache(options) || cache(options, engine.compileFile(path, options));
  2651. cb(null, tmpl(options));
  2652. } catch (err) {
  2653. cb(err);
  2654. }
  2655. });
  2656. };
  2657. /**
  2658. * Jade string support.
  2659. */
  2660. exports.jade.render = function(str, options, cb) {
  2661. return promisify(cb, function(cb) {
  2662. var engine = requires.jade;
  2663. if (!engine) {
  2664. try {
  2665. engine = requires.jade = require('jade');
  2666. } catch (err) {
  2667. try {
  2668. engine = requires.jade = require('then-jade');
  2669. } catch (otherError) {
  2670. throw err;
  2671. }
  2672. }
  2673. }
  2674. try {
  2675. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2676. cb(null, tmpl(options));
  2677. } catch (err) {
  2678. cb(err);
  2679. }
  2680. });
  2681. };
  2682. /**
  2683. * Dust support.
  2684. */
  2685. exports.dust = fromStringRenderer('dust');
  2686. /**
  2687. * Dust string support.
  2688. */
  2689. exports.dust.render = function(str, options, cb) {
  2690. return promisify(cb, function(cb) {
  2691. var engine = requires.dust;
  2692. if (!engine) {
  2693. try {
  2694. engine = requires.dust = require('dust');
  2695. } catch (err) {
  2696. try {
  2697. engine = requires.dust = require('dustjs-helpers');
  2698. } catch (err) {
  2699. engine = requires.dust = require('dustjs-linkedin');
  2700. }
  2701. }
  2702. }
  2703. var ext = 'dust';
  2704. var views = '.';
  2705. if (options) {
  2706. if (options.ext) ext = options.ext;
  2707. if (options.views) views = options.views;
  2708. if (options.settings && options.settings.views) views = options.settings.views;
  2709. }
  2710. if (!options || (options && !options.cache)) engine.cache = {};
  2711. engine.onLoad = function(path, callback) {
  2712. if (extname(path) === '') path += '.' + ext;
  2713. if (path[0] !== '/') path = views + '/' + path;
  2714. read(path, options, callback);
  2715. };
  2716. try {
  2717. var templateName;
  2718. if (options.filename) {
  2719. templateName = options.filename.replace(new RegExp('^' + views + '/'), '').replace(new RegExp('\\.' + ext), '');
  2720. }
  2721. var tmpl = cache(options) || cache(options, engine.compileFn(str, templateName));
  2722. tmpl(options, cb);
  2723. } catch (err) {
  2724. cb(err);
  2725. }
  2726. });
  2727. };
  2728. /**
  2729. * Swig support.
  2730. */
  2731. exports.swig = fromStringRenderer('swig');
  2732. /**
  2733. * Swig string support.
  2734. */
  2735. exports.swig.render = function(str, options, cb) {
  2736. return promisify(cb, function(cb) {
  2737. var engine = requires.swig;
  2738. if (!engine) {
  2739. try {
  2740. engine = requires.swig = require('swig');
  2741. } catch (err) {
  2742. try {
  2743. engine = requires.swig = require('swig-templates');
  2744. } catch (otherError) {
  2745. throw err;
  2746. }
  2747. }
  2748. }
  2749. try {
  2750. if (options.cache === true) options.cache = 'memory';
  2751. engine.setDefaults({ cache: options.cache });
  2752. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2753. cb(null, tmpl(options));
  2754. } catch (err) {
  2755. cb(err);
  2756. }
  2757. });
  2758. };
  2759. /**
  2760. * Razor support.
  2761. */
  2762. exports.razor = function(path, options, cb) {
  2763. return promisify(cb, function(cb) {
  2764. var engine = requires.razor;
  2765. if (!engine) {
  2766. try {
  2767. engine = requires.razor = require('razor-tmpl');
  2768. } catch (err) {
  2769. throw err;
  2770. }
  2771. }
  2772. try {
  2773. var tmpl = cache(options) || cache(options, (locals) => {
  2774. console.log('Rendering razor file', path);
  2775. return engine.renderFileSync(path, locals);
  2776. });
  2777. cb(null, tmpl(options));
  2778. } catch (err) {
  2779. cb(err);
  2780. }
  2781. });
  2782. };
  2783. /**
  2784. * razor string support.
  2785. */
  2786. exports.razor.render = function(str, options, cb) {
  2787. return promisify(cb, function(cb) {
  2788. try {
  2789. var engine = requires.razor = require('razor-tmpl');
  2790. } catch (err) {
  2791. throw err;
  2792. }
  2793. try {
  2794. var tf = engine.compile(str);
  2795. var tmpl = cache(options) || cache(options, tf);
  2796. cb(null, tmpl(options));
  2797. } catch (err) {
  2798. cb(err);
  2799. }
  2800. });
  2801. };
  2802. /**
  2803. * Atpl support.
  2804. */
  2805. exports.atpl = fromStringRenderer('atpl');
  2806. /**
  2807. * Atpl string support.
  2808. */
  2809. exports.atpl.render = function(str, options, cb) {
  2810. return promisify(cb, function(cb) {
  2811. var engine = requires.atpl || (requires.atpl = require('atpl'));
  2812. try {
  2813. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2814. cb(null, tmpl(options));
  2815. } catch (err) {
  2816. cb(err);
  2817. }
  2818. });
  2819. };
  2820. /**
  2821. * Liquor support,
  2822. */
  2823. exports.liquor = fromStringRenderer('liquor');
  2824. /**
  2825. * Liquor string support.
  2826. */
  2827. exports.liquor.render = function(str, options, cb) {
  2828. return promisify(cb, function(cb) {
  2829. var engine = requires.liquor || (requires.liquor = require('liquor'));
  2830. try {
  2831. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2832. cb(null, tmpl(options));
  2833. } catch (err) {
  2834. cb(err);
  2835. }
  2836. });
  2837. };
  2838. /**
  2839. * Twig support.
  2840. */
  2841. exports.twig = fromStringRenderer('twig');
  2842. /**
  2843. * Twig string support.
  2844. */
  2845. exports.twig.render = function(str, options, cb) {
  2846. return promisify(cb, function(cb) {
  2847. var engine = requires.twig || (requires.twig = require('twig').twig);
  2848. var templateData = {
  2849. data: str,
  2850. allowInlineIncludes: options.allowInlineIncludes,
  2851. namespaces: options.namespaces,
  2852. path: options.path
  2853. };
  2854. try {
  2855. var tmpl = cache(templateData) || cache(templateData, engine(templateData));
  2856. cb(null, tmpl.render(options));
  2857. } catch (err) {
  2858. cb(err);
  2859. }
  2860. });
  2861. };
  2862. /**
  2863. * EJS support.
  2864. */
  2865. exports.ejs = fromStringRenderer('ejs');
  2866. /**
  2867. * EJS string support.
  2868. */
  2869. exports.ejs.render = function(str, options, cb) {
  2870. return promisify(cb, function(cb) {
  2871. var engine = requires.ejs || (requires.ejs = require('ejs'));
  2872. try {
  2873. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2874. cb(null, tmpl(options));
  2875. } catch (err) {
  2876. cb(err);
  2877. }
  2878. });
  2879. };
  2880. /**
  2881. * Eco support.
  2882. */
  2883. exports.eco = fromStringRenderer('eco');
  2884. /**
  2885. * Eco string support.
  2886. */
  2887. exports.eco.render = function(str, options, cb) {
  2888. return promisify(cb, function(cb) {
  2889. var engine = requires.eco || (requires.eco = require('eco'));
  2890. try {
  2891. cb(null, engine.render(str, options));
  2892. } catch (err) {
  2893. cb(err);
  2894. }
  2895. });
  2896. };
  2897. /**
  2898. * Jazz support.
  2899. */
  2900. exports.jazz = fromStringRenderer('jazz');
  2901. /**
  2902. * Jazz string support.
  2903. */
  2904. exports.jazz.render = function(str, options, cb) {
  2905. return promisify(cb, function(cb) {
  2906. var engine = requires.jazz || (requires.jazz = require('jazz'));
  2907. try {
  2908. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  2909. tmpl.eval(options, function(str) {
  2910. cb(null, str);
  2911. });
  2912. } catch (err) {
  2913. cb(err);
  2914. }
  2915. });
  2916. };
  2917. /**
  2918. * JQTPL support.
  2919. */
  2920. exports.jqtpl = fromStringRenderer('jqtpl');
  2921. /**
  2922. * JQTPL string support.
  2923. */
  2924. exports.jqtpl.render = function(str, options, cb) {
  2925. return promisify(cb, function(cb) {
  2926. var engine = requires.jqtpl || (requires.jqtpl = require('jqtpl'));
  2927. try {
  2928. engine.template(str, str);
  2929. cb(null, engine.tmpl(str, options));
  2930. } catch (err) {
  2931. cb(err);
  2932. }
  2933. });
  2934. };
  2935. /**
  2936. * Haml support.
  2937. */
  2938. exports.haml = fromStringRenderer('haml');
  2939. /**
  2940. * Haml string support.
  2941. */
  2942. exports.haml.render = function(str, options, cb) {
  2943. return promisify(cb, function(cb) {
  2944. var engine = requires.haml || (requires.haml = require('hamljs'));
  2945. try {
  2946. options.locals = options;
  2947. cb(null, engine.render(str, options).trimLeft());
  2948. } catch (err) {
  2949. cb(err);
  2950. }
  2951. });
  2952. };
  2953. /**
  2954. * Hamlet support.
  2955. */
  2956. exports.hamlet = fromStringRenderer('hamlet');
  2957. /**
  2958. * Hamlet string support.
  2959. */
  2960. exports.hamlet.render = function(str, options, cb) {
  2961. return promisify(cb, function(cb) {
  2962. var engine = requires.hamlet || (requires.hamlet = require('hamlet'));
  2963. try {
  2964. options.locals = options;
  2965. cb(null, engine.render(str, options).trimLeft());
  2966. } catch (err) {
  2967. cb(err);
  2968. }
  2969. });
  2970. };
  2971. /**
  2972. * Whiskers support.
  2973. */
  2974. exports.whiskers = function(path, options, cb) {
  2975. return promisify(cb, function(cb) {
  2976. var engine = requires.whiskers || (requires.whiskers = require('whiskers'));
  2977. engine.__express(path, options, cb);
  2978. });
  2979. };
  2980. /**
  2981. * Whiskers string support.
  2982. */
  2983. exports.whiskers.render = function(str, options, cb) {
  2984. return promisify(cb, function(cb) {
  2985. var engine = requires.whiskers || (requires.whiskers = require('whiskers'));
  2986. try {
  2987. cb(null, engine.render(str, options));
  2988. } catch (err) {
  2989. cb(err);
  2990. }
  2991. });
  2992. };
  2993. /**
  2994. * Coffee-HAML support.
  2995. */
  2996. exports['haml-coffee'] = fromStringRenderer('haml-coffee');
  2997. /**
  2998. * Coffee-HAML string support.
  2999. */
  3000. exports['haml-coffee'].render = function(str, options, cb) {
  3001. return promisify(cb, function(cb) {
  3002. var engine = requires['haml-coffee'] || (requires['haml-coffee'] = require('haml-coffee'));
  3003. try {
  3004. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3005. cb(null, tmpl(options));
  3006. } catch (err) {
  3007. cb(err);
  3008. }
  3009. });
  3010. };
  3011. /**
  3012. * Hogan support.
  3013. */
  3014. exports.hogan = fromStringRenderer('hogan');
  3015. /**
  3016. * Hogan string support.
  3017. */
  3018. exports.hogan.render = function(str, options, cb) {
  3019. return promisify(cb, function(cb) {
  3020. var engine = requires.hogan || (requires.hogan = require('hogan.js'));
  3021. try {
  3022. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3023. cb(null, tmpl.render(options, options.partials));
  3024. } catch (err) {
  3025. cb(err);
  3026. }
  3027. });
  3028. };
  3029. /**
  3030. * templayed.js support.
  3031. */
  3032. exports.templayed = fromStringRenderer('templayed');
  3033. /**
  3034. * templayed.js string support.
  3035. */
  3036. exports.templayed.render = function(str, options, cb) {
  3037. return promisify(cb, function(cb) {
  3038. var engine = requires.templayed || (requires.templayed = require('templayed'));
  3039. try {
  3040. var tmpl = cache(options) || cache(options, engine(str));
  3041. cb(null, tmpl(options));
  3042. } catch (err) {
  3043. cb(err);
  3044. }
  3045. });
  3046. };
  3047. /**
  3048. * Handlebars support.
  3049. */
  3050. exports.handlebars = fromStringRenderer('handlebars');
  3051. /**
  3052. * Handlebars string support.
  3053. */
  3054. exports.handlebars.render = function(str, options, cb) {
  3055. return promisify(cb, function(cb) {
  3056. var engine = requires.handlebars || (requires.handlebars = require('handlebars'));
  3057. try {
  3058. for (var partial in options.partials) {
  3059. engine.registerPartial(partial, options.partials[partial]);
  3060. }
  3061. for (var helper in options.helpers) {
  3062. engine.registerHelper(helper, options.helpers[helper]);
  3063. }
  3064. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3065. cb(null, tmpl(options));
  3066. } catch (err) {
  3067. cb(err);
  3068. }
  3069. });
  3070. };
  3071. /**
  3072. * Underscore support.
  3073. */
  3074. exports.underscore = fromStringRenderer('underscore');
  3075. /**
  3076. * Underscore string support.
  3077. */
  3078. exports.underscore.render = function(str, options, cb) {
  3079. return promisify(cb, function(cb) {
  3080. var engine = requires.underscore || (requires.underscore = require('underscore'));
  3081. try {
  3082. const partials = {};
  3083. for (var partial in options.partials) {
  3084. partials[partial] = engine.template(options.partials[partial]);
  3085. }
  3086. options.partials = partials;
  3087. var tmpl = cache(options) || cache(options, engine.template(str, null, options));
  3088. cb(null, tmpl(options).replace(/\n$/, ''));
  3089. } catch (err) {
  3090. cb(err);
  3091. }
  3092. });
  3093. };
  3094. /**
  3095. * Lodash support.
  3096. */
  3097. exports.lodash = fromStringRenderer('lodash');
  3098. /**
  3099. * Lodash string support.
  3100. */
  3101. exports.lodash.render = function(str, options, cb) {
  3102. return promisify(cb, function(cb) {
  3103. var engine = requires.lodash || (requires.lodash = require('lodash'));
  3104. try {
  3105. var tmpl = cache(options) || cache(options, engine.template(str, options));
  3106. cb(null, tmpl(options).replace(/\n$/, ''));
  3107. } catch (err) {
  3108. cb(err);
  3109. }
  3110. });
  3111. };
  3112. /**
  3113. * Pug support. (formerly Jade)
  3114. */
  3115. exports.pug = function(path, options, cb) {
  3116. return promisify(cb, function(cb) {
  3117. var engine = requires.pug;
  3118. if (!engine) {
  3119. try {
  3120. engine = requires.pug = require('pug');
  3121. } catch (err) {
  3122. try {
  3123. engine = requires.pug = require('then-pug');
  3124. } catch (otherError) {
  3125. throw err;
  3126. }
  3127. }
  3128. }
  3129. try {
  3130. var tmpl = cache(options) || cache(options, engine.compileFile(path, options));
  3131. cb(null, tmpl(options));
  3132. } catch (err) {
  3133. cb(err);
  3134. }
  3135. });
  3136. };
  3137. /**
  3138. * Pug string support.
  3139. */
  3140. exports.pug.render = function(str, options, cb) {
  3141. return promisify(cb, function(cb) {
  3142. var engine = requires.pug;
  3143. if (!engine) {
  3144. try {
  3145. engine = requires.pug = require('pug');
  3146. } catch (err) {
  3147. try {
  3148. engine = requires.pug = require('then-pug');
  3149. } catch (otherError) {
  3150. throw err;
  3151. }
  3152. }
  3153. }
  3154. try {
  3155. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3156. cb(null, tmpl(options));
  3157. } catch (err) {
  3158. cb(err);
  3159. }
  3160. });
  3161. };
  3162. /**
  3163. * QEJS support.
  3164. */
  3165. exports.qejs = fromStringRenderer('qejs');
  3166. /**
  3167. * QEJS string support.
  3168. */
  3169. exports.qejs.render = function(str, options, cb) {
  3170. return promisify(cb, function(cb) {
  3171. try {
  3172. var engine = requires.qejs || (requires.qejs = require('qejs'));
  3173. engine.render(str, options).then(function(result) {
  3174. cb(null, result);
  3175. }, function(err) {
  3176. cb(err);
  3177. }).done();
  3178. } catch (err) {
  3179. cb(err);
  3180. }
  3181. });
  3182. };
  3183. /**
  3184. * Walrus support.
  3185. */
  3186. exports.walrus = fromStringRenderer('walrus');
  3187. /**
  3188. * Walrus string support.
  3189. */
  3190. exports.walrus.render = function(str, options, cb) {
  3191. return promisify(cb, function(cb) {
  3192. var engine = requires.walrus || (requires.walrus = require('walrus'));
  3193. try {
  3194. var tmpl = cache(options) || cache(options, engine.parse(str));
  3195. cb(null, tmpl.compile(options));
  3196. } catch (err) {
  3197. cb(err);
  3198. }
  3199. });
  3200. };
  3201. /**
  3202. * Mustache support.
  3203. */
  3204. exports.mustache = fromStringRenderer('mustache');
  3205. /**
  3206. * Mustache string support.
  3207. */
  3208. exports.mustache.render = function(str, options, cb) {
  3209. return promisify(cb, function(cb) {
  3210. var engine = requires.mustache || (requires.mustache = require('mustache'));
  3211. try {
  3212. cb(null, engine.render(str, options, options.partials));
  3213. } catch (err) {
  3214. cb(err);
  3215. }
  3216. });
  3217. };
  3218. /**
  3219. * Just support.
  3220. */
  3221. exports.just = function(path, options, cb) {
  3222. return promisify(cb, function(cb) {
  3223. var engine = requires.just;
  3224. if (!engine) {
  3225. var JUST = require('just');
  3226. engine = requires.just = new JUST();
  3227. }
  3228. engine.configure({ useCache: options.cache });
  3229. engine.render(path, options, cb);
  3230. });
  3231. };
  3232. /**
  3233. * Just string support.
  3234. */
  3235. exports.just.render = function(str, options, cb) {
  3236. return promisify(cb, function(cb) {
  3237. var JUST = require('just');
  3238. var engine = new JUST({ root: { page: str }});
  3239. engine.render('page', options, cb);
  3240. });
  3241. };
  3242. /**
  3243. * ECT support.
  3244. */
  3245. exports.ect = function(path, options, cb) {
  3246. return promisify(cb, function(cb) {
  3247. var engine = requires.ect;
  3248. if (!engine) {
  3249. var ECT = require('ect');
  3250. engine = requires.ect = new ECT(options);
  3251. }
  3252. engine.configure({ cache: options.cache });
  3253. engine.render(path, options, cb);
  3254. });
  3255. };
  3256. /**
  3257. * ECT string support.
  3258. */
  3259. exports.ect.render = function(str, options, cb) {
  3260. return promisify(cb, function(cb) {
  3261. var ECT = require('ect');
  3262. var engine = new ECT({ root: { page: str }});
  3263. engine.render('page', options, cb);
  3264. });
  3265. };
  3266. /**
  3267. * mote support.
  3268. */
  3269. exports.mote = fromStringRenderer('mote');
  3270. /**
  3271. * mote string support.
  3272. */
  3273. exports.mote.render = function(str, options, cb) {
  3274. return promisify(cb, function(cb) {
  3275. var engine = requires.mote || (requires.mote = require('mote'));
  3276. try {
  3277. var tmpl = cache(options) || cache(options, engine.compile(str));
  3278. cb(null, tmpl(options));
  3279. } catch (err) {
  3280. cb(err);
  3281. }
  3282. });
  3283. };
  3284. /**
  3285. * Toffee support.
  3286. */
  3287. exports.toffee = function(path, options, cb) {
  3288. return promisify(cb, function(cb) {
  3289. var toffee = requires.toffee || (requires.toffee = require('toffee'));
  3290. toffee.__consolidate_engine_render(path, options, cb);
  3291. });
  3292. };
  3293. /**
  3294. * Toffee string support.
  3295. */
  3296. exports.toffee.render = function(str, options, cb) {
  3297. return promisify(cb, function(cb) {
  3298. var engine = requires.toffee || (requires.toffee = require('toffee'));
  3299. try {
  3300. engine.str_render(str, options, cb);
  3301. } catch (err) {
  3302. cb(err);
  3303. }
  3304. });
  3305. };
  3306. /**
  3307. * doT support.
  3308. */
  3309. exports.dot = fromStringRenderer('dot');
  3310. /**
  3311. * doT string support.
  3312. */
  3313. exports.dot.render = function(str, options, cb) {
  3314. return promisify(cb, function(cb) {
  3315. var engine = requires.dot || (requires.dot = require('dot'));
  3316. var extend = (requires.extend || (requires.extend = require$$2._extend));
  3317. try {
  3318. var settings = {};
  3319. settings = extend(settings, engine.templateSettings);
  3320. settings = extend(settings, options ? options.dot : {});
  3321. var tmpl = cache(options) || cache(options, engine.template(str, settings, options));
  3322. cb(null, tmpl(options));
  3323. } catch (err) {
  3324. cb(err);
  3325. }
  3326. });
  3327. };
  3328. /**
  3329. * bracket support.
  3330. */
  3331. exports.bracket = fromStringRenderer('bracket');
  3332. /**
  3333. * bracket string support.
  3334. */
  3335. exports.bracket.render = function(str, options, cb) {
  3336. return promisify(cb, function(cb) {
  3337. var engine = requires.bracket || (requires.bracket = require('bracket-template'));
  3338. try {
  3339. var tmpl = cache(options) || cache(options, engine.default.compile(str, options));
  3340. cb(null, tmpl(options));
  3341. } catch (err) {
  3342. cb(err);
  3343. }
  3344. });
  3345. };
  3346. /**
  3347. * Ractive support.
  3348. */
  3349. exports.ractive = fromStringRenderer('ractive');
  3350. /**
  3351. * Ractive string support.
  3352. */
  3353. exports.ractive.render = function(str, options, cb) {
  3354. return promisify(cb, function(cb) {
  3355. var Engine = requires.ractive || (requires.ractive = require('ractive'));
  3356. var template = cache(options) || cache(options, Engine.parse(str));
  3357. options.template = template;
  3358. if (options.data === null || options.data === undefined) {
  3359. var extend = (requires.extend || (requires.extend = require$$2._extend));
  3360. // Shallow clone the options object
  3361. options.data = extend({}, options);
  3362. // Remove consolidate-specific properties from the clone
  3363. var i;
  3364. var length;
  3365. var properties = ['template', 'filename', 'cache', 'partials'];
  3366. for (i = 0, length = properties.length; i < length; i++) {
  3367. var property = properties[i];
  3368. delete options.data[property];
  3369. }
  3370. }
  3371. try {
  3372. cb(null, new Engine(options).toHTML());
  3373. } catch (err) {
  3374. cb(err);
  3375. }
  3376. });
  3377. };
  3378. /**
  3379. * Nunjucks support.
  3380. */
  3381. exports.nunjucks = fromStringRenderer('nunjucks');
  3382. /**
  3383. * Nunjucks string support.
  3384. */
  3385. exports.nunjucks.render = function(str, options, cb) {
  3386. return promisify(cb, function(cb) {
  3387. try {
  3388. var engine = options.nunjucksEnv || requires.nunjucks || (requires.nunjucks = require('nunjucks'));
  3389. var env = engine;
  3390. // deprecated fallback support for express
  3391. // <https://github.com/tj/consolidate.js/pull/152>
  3392. // <https://github.com/tj/consolidate.js/pull/224>
  3393. if (options.settings && options.settings.views) {
  3394. env = engine.configure(options.settings.views);
  3395. } else if (options.nunjucks && options.nunjucks.configure) {
  3396. env = engine.configure.apply(engine, options.nunjucks.configure);
  3397. }
  3398. //
  3399. // because `renderString` does not initiate loaders
  3400. // we must manually create a loader for it based off
  3401. // either `options.settings.views` or `options.nunjucks` or `options.nunjucks.root`
  3402. //
  3403. // <https://github.com/mozilla/nunjucks/issues/730>
  3404. // <https://github.com/crocodilejs/node-email-templates/issues/182>
  3405. //
  3406. // so instead we simply check if we passed a custom loader
  3407. // otherwise we create a simple file based loader
  3408. if (options.loader) {
  3409. env = new engine.Environment(options.loader);
  3410. } else if (options.settings && options.settings.views) {
  3411. env = new engine.Environment(
  3412. new engine.FileSystemLoader(options.settings.views)
  3413. );
  3414. } else if (options.nunjucks && options.nunjucks.loader) {
  3415. if (typeof options.nunjucks.loader === 'string') {
  3416. env = new engine.Environment(new engine.FileSystemLoader(options.nunjucks.loader));
  3417. } else {
  3418. env = new engine.Environment(
  3419. new engine.FileSystemLoader(
  3420. options.nunjucks.loader[0],
  3421. options.nunjucks.loader[1]
  3422. )
  3423. );
  3424. }
  3425. }
  3426. env.renderString(str, options, cb);
  3427. } catch (err) {
  3428. throw cb(err);
  3429. }
  3430. });
  3431. };
  3432. /**
  3433. * HTMLing support.
  3434. */
  3435. exports.htmling = fromStringRenderer('htmling');
  3436. /**
  3437. * HTMLing string support.
  3438. */
  3439. exports.htmling.render = function(str, options, cb) {
  3440. return promisify(cb, function(cb) {
  3441. var engine = requires.htmling || (requires.htmling = require('htmling'));
  3442. try {
  3443. var tmpl = cache(options) || cache(options, engine.string(str));
  3444. cb(null, tmpl.render(options));
  3445. } catch (err) {
  3446. cb(err);
  3447. }
  3448. });
  3449. };
  3450. /**
  3451. * Rendering function
  3452. */
  3453. function requireReact(module, filename) {
  3454. var babel = requires.babel || (requires.babel = require('babel-core'));
  3455. var compiled = babel.transformFileSync(filename, { presets: [ 'react' ] }).code;
  3456. return module._compile(compiled, filename);
  3457. }
  3458. exports.requireReact = requireReact;
  3459. /**
  3460. * Converting a string into a node module.
  3461. */
  3462. function requireReactString(src, filename) {
  3463. var babel = requires.babel || (requires.babel = require('babel-core'));
  3464. if (!filename) filename = '';
  3465. var m = new module.constructor();
  3466. filename = filename || '';
  3467. // Compile Using React
  3468. var compiled = babel.transform(src, { presets: [ 'react' ] }).code;
  3469. // Compile as a module
  3470. m.paths = module.paths;
  3471. m._compile(compiled, filename);
  3472. return m.exports;
  3473. }
  3474. /**
  3475. * A naive helper to replace {{tags}} with options.tags content
  3476. */
  3477. function reactBaseTmpl(data, options) {
  3478. var exp;
  3479. var regex;
  3480. // Iterates through the keys in file object
  3481. // and interpolate / replace {{key}} with it's value
  3482. for (var k in options) {
  3483. if (options.hasOwnProperty(k)) {
  3484. exp = '{{' + k + '}}';
  3485. regex = new RegExp(exp, 'g');
  3486. if (data.match(regex)) {
  3487. data = data.replace(regex, options[k]);
  3488. }
  3489. }
  3490. }
  3491. return data;
  3492. }
  3493. /**
  3494. * Plates Support.
  3495. */
  3496. exports.plates = fromStringRenderer('plates');
  3497. /**
  3498. * Plates string support.
  3499. */
  3500. exports.plates.render = function(str, options, cb) {
  3501. return promisify(cb, function(cb) {
  3502. var engine = requires.plates || (requires.plates = require('plates'));
  3503. var map = options.map || undefined;
  3504. try {
  3505. var tmpl = engine.bind(str, options, map);
  3506. cb(null, tmpl);
  3507. } catch (err) {
  3508. cb(err);
  3509. }
  3510. });
  3511. };
  3512. /**
  3513. * The main render parser for React bsaed templates
  3514. */
  3515. function reactRenderer(type) {
  3516. if (commonjsRequire.extensions) {
  3517. // Ensure JSX is transformed on require
  3518. if (!commonjsRequire.extensions['.jsx']) {
  3519. commonjsRequire.extensions['.jsx'] = requireReact;
  3520. }
  3521. // Supporting .react extension as well as test cases
  3522. // Using .react extension is not recommended.
  3523. if (!commonjsRequire.extensions['.react']) {
  3524. commonjsRequire.extensions['.react'] = requireReact;
  3525. }
  3526. }
  3527. // Return rendering fx
  3528. return function(str, options, cb) {
  3529. return promisify(cb, function(cb) {
  3530. // React Import
  3531. var ReactDOM = requires.ReactDOM || (requires.ReactDOM = require('react-dom/server'));
  3532. var react = requires.react || (requires.react = require('react'));
  3533. // Assign HTML Base
  3534. var base = options.base;
  3535. delete options.base;
  3536. var enableCache = options.cache;
  3537. delete options.cache;
  3538. var isNonStatic = options.isNonStatic;
  3539. delete options.isNonStatic;
  3540. // Start Conversion
  3541. try {
  3542. var Code;
  3543. var Factory;
  3544. var baseStr;
  3545. var content;
  3546. var parsed;
  3547. if (!cache(options)) {
  3548. // Parsing
  3549. if (type === 'path') {
  3550. var path = resolve(str);
  3551. delete require.cache[path];
  3552. Code = commonjsRequire(path);
  3553. } else {
  3554. Code = requireReactString(str);
  3555. }
  3556. Factory = cache(options, react.createFactory(Code));
  3557. } else {
  3558. Factory = cache(options);
  3559. }
  3560. parsed = new Factory(options);
  3561. content = (isNonStatic) ? ReactDOM.renderToString(parsed) : ReactDOM.renderToStaticMarkup(parsed);
  3562. if (base) {
  3563. baseStr = readCache[str] || fs.readFileSync(resolve(base), 'utf8');
  3564. if (enableCache) {
  3565. readCache[str] = baseStr;
  3566. }
  3567. options.content = content;
  3568. content = reactBaseTmpl(baseStr, options);
  3569. }
  3570. cb(null, content);
  3571. } catch (err) {
  3572. cb(err);
  3573. }
  3574. });
  3575. };
  3576. }
  3577. /**
  3578. * React JS Support
  3579. */
  3580. exports.react = reactRenderer('path');
  3581. /**
  3582. * React JS string support.
  3583. */
  3584. exports.react.render = reactRenderer('string');
  3585. /**
  3586. * ARC-templates support.
  3587. */
  3588. exports['arc-templates'] = fromStringRenderer('arc-templates');
  3589. /**
  3590. * ARC-templates string support.
  3591. */
  3592. exports['arc-templates'].render = function(str, options, cb) {
  3593. var readFileWithOptions = util.promisify(read);
  3594. var consolidateFileSystem = {};
  3595. consolidateFileSystem.readFile = function(path) {
  3596. return readFileWithOptions(path, options);
  3597. };
  3598. return promisify(cb, function(cb) {
  3599. try {
  3600. var engine = requires['arc-templates'];
  3601. if (!engine) {
  3602. var Engine = require('arc-templates/dist/es5');
  3603. engine = requires['arc-templates'] = new Engine({ filesystem: consolidateFileSystem });
  3604. }
  3605. var compiler = cache(options) || cache(options, engine.compileString(str, options.filename));
  3606. compiler.then(function(func) { return func(options); })
  3607. .then(function(result) { cb(null, result.content); })
  3608. .catch(cb);
  3609. } catch (err) {
  3610. cb(err);
  3611. }
  3612. });
  3613. };
  3614. /**
  3615. * Vash support
  3616. */
  3617. exports.vash = fromStringRenderer('vash');
  3618. /**
  3619. * Vash string support
  3620. */
  3621. exports.vash.render = function(str, options, cb) {
  3622. return promisify(cb, function(cb) {
  3623. var engine = requires.vash || (requires.vash = require('vash'));
  3624. try {
  3625. // helper system : https://github.com/kirbysayshi/vash#helper-system
  3626. if (options.helpers) {
  3627. for (var key in options.helpers) {
  3628. if (!options.helpers.hasOwnProperty(key) || typeof options.helpers[key] !== 'function') {
  3629. continue;
  3630. }
  3631. engine.helpers[key] = options.helpers[key];
  3632. }
  3633. }
  3634. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3635. tmpl(options, function sealLayout(err, ctx) {
  3636. if (err) cb(err);
  3637. ctx.finishLayout();
  3638. cb(null, ctx.toString().replace(/\n$/, ''));
  3639. });
  3640. } catch (err) {
  3641. cb(err);
  3642. }
  3643. });
  3644. };
  3645. /**
  3646. * Slm support.
  3647. */
  3648. exports.slm = fromStringRenderer('slm');
  3649. /**
  3650. * Slm string support.
  3651. */
  3652. exports.slm.render = function(str, options, cb) {
  3653. return promisify(cb, function(cb) {
  3654. var engine = requires.slm || (requires.slm = require('slm'));
  3655. try {
  3656. var tmpl = cache(options) || cache(options, engine.compile(str, options));
  3657. cb(null, tmpl(options));
  3658. } catch (err) {
  3659. cb(err);
  3660. }
  3661. });
  3662. };
  3663. /**
  3664. * Marko support.
  3665. */
  3666. exports.marko = function(path, options, cb) {
  3667. return promisify(cb, function(cb) {
  3668. var engine = requires.marko || (requires.marko = require('marko'));
  3669. options.writeToDisk = !!options.cache;
  3670. try {
  3671. var tmpl = cache(options) || cache(options, engine.load(path, options));
  3672. tmpl.renderToString(options, cb);
  3673. } catch (err) {
  3674. cb(err);
  3675. }
  3676. });
  3677. };
  3678. /**
  3679. * Marko string support.
  3680. */
  3681. exports.marko.render = function(str, options, cb) {
  3682. return promisify(cb, function(cb) {
  3683. var engine = requires.marko || (requires.marko = require('marko'));
  3684. options.writeToDisk = !!options.cache;
  3685. options.filename = options.filename || 'string.marko';
  3686. try {
  3687. var tmpl = cache(options) || cache(options, engine.load(options.filename, str, options));
  3688. tmpl.renderToString(options, cb);
  3689. } catch (err) {
  3690. cb(err);
  3691. }
  3692. });
  3693. };
  3694. /**
  3695. * Teacup support.
  3696. */
  3697. exports.teacup = function(path, options, cb) {
  3698. return promisify(cb, function(cb) {
  3699. var engine = requires.teacup || (requires.teacup = require('teacup/lib/express'));
  3700. commonjsRequire.extensions['.teacup'] = commonjsRequire.extensions['.coffee'];
  3701. if (path[0] !== '/') {
  3702. path = join(process.cwd(), path);
  3703. }
  3704. if (!options.cache) {
  3705. var callback = cb;
  3706. cb = function() {
  3707. delete require.cache[path];
  3708. callback.apply(this, arguments);
  3709. };
  3710. }
  3711. engine.renderFile(path, options, cb);
  3712. });
  3713. };
  3714. /**
  3715. * Teacup string support.
  3716. */
  3717. exports.teacup.render = function(str, options, cb) {
  3718. var coffee = require('coffee-script');
  3719. var vm = require('vm');
  3720. var sandbox = {
  3721. module: {exports: {}},
  3722. require: commonjsRequire
  3723. };
  3724. return promisify(cb, function(cb) {
  3725. vm.runInNewContext(coffee.compile(str), sandbox);
  3726. var tmpl = sandbox.module.exports;
  3727. cb(null, tmpl(options));
  3728. });
  3729. };
  3730. /**
  3731. * Squirrelly support.
  3732. */
  3733. exports.squirrelly = fromStringRenderer('squirrelly');
  3734. /**
  3735. * Squirrelly string support.
  3736. */
  3737. exports.squirrelly.render = function(str, options, cb) {
  3738. return promisify(cb, function(cb) {
  3739. var engine = requires.squirrelly || (requires.squirrelly = require('squirrelly'));
  3740. try {
  3741. for (var partial in options.partials) {
  3742. engine.definePartial(partial, options.partials[partial]);
  3743. }
  3744. for (var helper in options.helpers) {
  3745. engine.defineHelper(helper, options.helpers[helper]);
  3746. }
  3747. var tmpl = cache(options) || cache(options, engine.Compile(str, options));
  3748. cb(null, tmpl(options, engine));
  3749. } catch (err) {
  3750. cb(err);
  3751. }
  3752. });
  3753. };
  3754. /**
  3755. * Twing support.
  3756. */
  3757. exports.twing = fromStringRenderer('twing');
  3758. /**
  3759. * Twing string support.
  3760. */
  3761. exports.twing.render = function(str, options, cb) {
  3762. return promisify(cb, function(cb) {
  3763. var engine = requires.twing || (requires.twing = require('twing'));
  3764. try {
  3765. new engine.TwingEnvironment(new engine.TwingLoaderNull()).createTemplate(str).then((twingTemplate) => {
  3766. twingTemplate.render(options).then((rendTmpl) => {
  3767. var tmpl = cache(options) || cache(options, rendTmpl);
  3768. cb(null, tmpl);
  3769. });
  3770. });
  3771. } catch (err) {
  3772. cb(err);
  3773. }
  3774. });
  3775. };
  3776. /**
  3777. * expose the instance of the engine
  3778. */
  3779. exports.requires = requires;
  3780. } (consolidate$2, consolidate$2.exports));
  3781. return consolidate$2.exports;
  3782. }
  3783. var consolidate$1;
  3784. var hasRequiredConsolidate;
  3785. function requireConsolidate () {
  3786. if (hasRequiredConsolidate) return consolidate$1;
  3787. hasRequiredConsolidate = 1;
  3788. consolidate$1 = /*@__PURE__*/ requireConsolidate$1();
  3789. return consolidate$1;
  3790. }
  3791. var consolidateExports = /*@__PURE__*/ requireConsolidate();
  3792. var consolidate = /*@__PURE__*/getDefaultExportFromCjs(consolidateExports);
  3793. const hasWarned = {};
  3794. function warnOnce(msg) {
  3795. const isNodeProd = typeof process !== "undefined" && process.env.NODE_ENV === "production";
  3796. if (!isNodeProd && true && !hasWarned[msg]) {
  3797. hasWarned[msg] = true;
  3798. warn(msg);
  3799. }
  3800. }
  3801. function warn(msg) {
  3802. console.warn(
  3803. `\x1B[1m\x1B[33m[@vue/compiler-sfc]\x1B[0m\x1B[33m ${msg}\x1B[0m
  3804. `
  3805. );
  3806. }
  3807. function preprocess$1({ source, filename, preprocessOptions }, preprocessor) {
  3808. let res = "";
  3809. let err = null;
  3810. preprocessor.render(
  3811. source,
  3812. { filename, ...preprocessOptions },
  3813. (_err, _res) => {
  3814. if (_err) err = _err;
  3815. res = _res;
  3816. }
  3817. );
  3818. if (err) throw err;
  3819. return res;
  3820. }
  3821. function compileTemplate(options) {
  3822. const { preprocessLang, preprocessCustomRequire } = options;
  3823. const preprocessor = preprocessLang ? preprocessCustomRequire ? preprocessCustomRequire(preprocessLang) : consolidate[preprocessLang] : false;
  3824. if (preprocessor) {
  3825. try {
  3826. return doCompileTemplate({
  3827. ...options,
  3828. source: preprocess$1(options, preprocessor),
  3829. ast: void 0
  3830. // invalidate AST if template goes through preprocessor
  3831. });
  3832. } catch (e) {
  3833. return {
  3834. code: `export default function render() {}`,
  3835. source: options.source,
  3836. tips: [],
  3837. errors: [e]
  3838. };
  3839. }
  3840. } else if (preprocessLang) {
  3841. return {
  3842. code: `export default function render() {}`,
  3843. source: options.source,
  3844. tips: [
  3845. `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
  3846. ],
  3847. errors: [
  3848. `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
  3849. ]
  3850. };
  3851. } else {
  3852. return doCompileTemplate(options);
  3853. }
  3854. }
  3855. function doCompileTemplate({
  3856. filename,
  3857. id,
  3858. scoped,
  3859. slotted,
  3860. inMap,
  3861. source,
  3862. ast: inAST,
  3863. ssr = false,
  3864. ssrCssVars,
  3865. isProd = false,
  3866. compiler,
  3867. compilerOptions = {},
  3868. transformAssetUrls
  3869. }) {
  3870. const errors = [];
  3871. const warnings = [];
  3872. let nodeTransforms = [];
  3873. if (shared.isObject(transformAssetUrls)) {
  3874. const assetOptions = normalizeOptions(transformAssetUrls);
  3875. nodeTransforms = [
  3876. createAssetUrlTransformWithOptions(assetOptions),
  3877. createSrcsetTransformWithOptions(assetOptions)
  3878. ];
  3879. } else if (transformAssetUrls !== false) {
  3880. nodeTransforms = [transformAssetUrl, transformSrcset];
  3881. }
  3882. if (ssr && !ssrCssVars) {
  3883. warnOnce(
  3884. `compileTemplate is called with \`ssr: true\` but no corresponding \`cssVars\` option.`
  3885. );
  3886. }
  3887. if (!id) {
  3888. warnOnce(`compileTemplate now requires the \`id\` option.`);
  3889. id = "";
  3890. }
  3891. const shortId = id.replace(/^data-v-/, "");
  3892. const longId = `data-v-${shortId}`;
  3893. const defaultCompiler = ssr ? CompilerSSR__namespace : CompilerDOM__namespace;
  3894. compiler = compiler || defaultCompiler;
  3895. if (compiler !== defaultCompiler) {
  3896. inAST = void 0;
  3897. }
  3898. if (inAST == null ? void 0 : inAST.transformed) {
  3899. const newAST = (ssr ? CompilerDOM__namespace : compiler).parse(inAST.source, {
  3900. prefixIdentifiers: true,
  3901. ...compilerOptions,
  3902. parseMode: "sfc",
  3903. onError: (e) => errors.push(e)
  3904. });
  3905. const template = newAST.children.find(
  3906. (node) => node.type === 1 && node.tag === "template"
  3907. );
  3908. inAST = compilerCore.createRoot(template.children, inAST.source);
  3909. }
  3910. let { code, ast, preamble, map } = compiler.compile(inAST || source, {
  3911. mode: "module",
  3912. prefixIdentifiers: true,
  3913. hoistStatic: true,
  3914. cacheHandlers: true,
  3915. ssrCssVars: ssr && ssrCssVars && ssrCssVars.length ? genCssVarsFromList(ssrCssVars, shortId, isProd, true) : "",
  3916. scopeId: scoped ? longId : void 0,
  3917. slotted,
  3918. sourceMap: true,
  3919. ...compilerOptions,
  3920. hmr: !isProd,
  3921. nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []),
  3922. filename,
  3923. onError: (e) => errors.push(e),
  3924. onWarn: (w) => warnings.push(w)
  3925. });
  3926. if (inMap && !inAST) {
  3927. if (map) {
  3928. map = mapLines(inMap, map);
  3929. }
  3930. if (errors.length) {
  3931. patchErrors(errors, source, inMap);
  3932. }
  3933. }
  3934. const tips = warnings.map((w) => {
  3935. let msg = w.message;
  3936. if (w.loc) {
  3937. msg += `
  3938. ${shared.generateCodeFrame(
  3939. (inAST == null ? void 0 : inAST.source) || source,
  3940. w.loc.start.offset,
  3941. w.loc.end.offset
  3942. )}`;
  3943. }
  3944. return msg;
  3945. });
  3946. return { code, ast, preamble, source, errors, tips, map };
  3947. }
  3948. function mapLines(oldMap, newMap) {
  3949. if (!oldMap) return newMap;
  3950. if (!newMap) return oldMap;
  3951. const oldMapConsumer = new sourceMapJs.SourceMapConsumer(oldMap);
  3952. const newMapConsumer = new sourceMapJs.SourceMapConsumer(newMap);
  3953. const mergedMapGenerator = new sourceMapJs.SourceMapGenerator();
  3954. newMapConsumer.eachMapping((m) => {
  3955. if (m.originalLine == null) {
  3956. return;
  3957. }
  3958. const origPosInOldMap = oldMapConsumer.originalPositionFor({
  3959. line: m.originalLine,
  3960. column: m.originalColumn
  3961. });
  3962. if (origPosInOldMap.source == null) {
  3963. return;
  3964. }
  3965. mergedMapGenerator.addMapping({
  3966. generated: {
  3967. line: m.generatedLine,
  3968. column: m.generatedColumn
  3969. },
  3970. original: {
  3971. line: origPosInOldMap.line,
  3972. // map line
  3973. // use current column, since the oldMap produced by @vue/compiler-sfc
  3974. // does not
  3975. column: m.originalColumn
  3976. },
  3977. source: origPosInOldMap.source,
  3978. name: origPosInOldMap.name
  3979. });
  3980. });
  3981. const generator = mergedMapGenerator;
  3982. oldMapConsumer.sources.forEach((sourceFile) => {
  3983. generator._sources.add(sourceFile);
  3984. const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
  3985. if (sourceContent != null) {
  3986. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  3987. }
  3988. });
  3989. generator._sourceRoot = oldMap.sourceRoot;
  3990. generator._file = oldMap.file;
  3991. return generator.toJSON();
  3992. }
  3993. function patchErrors(errors, source, inMap) {
  3994. const originalSource = inMap.sourcesContent[0];
  3995. const offset = originalSource.indexOf(source);
  3996. const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
  3997. errors.forEach((err) => {
  3998. if (err.loc) {
  3999. err.loc.start.line += lineOffset;
  4000. err.loc.start.offset += offset;
  4001. if (err.loc.end !== err.loc.start) {
  4002. err.loc.end.line += lineOffset;
  4003. err.loc.end.offset += offset;
  4004. }
  4005. }
  4006. });
  4007. }
  4008. const trimPlugin = () => {
  4009. return {
  4010. postcssPlugin: "vue-sfc-trim",
  4011. Once(root) {
  4012. root.walk(({ type, raws }) => {
  4013. if (type === "rule" || type === "atrule") {
  4014. if (raws.before) raws.before = "\n";
  4015. if ("after" in raws && raws.after) raws.after = "\n";
  4016. }
  4017. });
  4018. }
  4019. };
  4020. };
  4021. trimPlugin.postcss = true;
  4022. var dist$1 = {exports: {}};
  4023. var processor$1 = {exports: {}};
  4024. var parser$1 = {exports: {}};
  4025. var root$1 = {exports: {}};
  4026. var container$1 = {exports: {}};
  4027. var node$2 = {exports: {}};
  4028. var util$2 = {};
  4029. var unesc$1 = {exports: {}};
  4030. var hasRequiredUnesc$1;
  4031. function requireUnesc$1 () {
  4032. if (hasRequiredUnesc$1) return unesc$1.exports;
  4033. hasRequiredUnesc$1 = 1;
  4034. (function (module, exports) {
  4035. exports.__esModule = true;
  4036. exports["default"] = unesc;
  4037. // Many thanks for this post which made this migration much easier.
  4038. // https://mathiasbynens.be/notes/css-escapes
  4039. /**
  4040. *
  4041. * @param {string} str
  4042. * @returns {[string, number]|undefined}
  4043. */
  4044. function gobbleHex(str) {
  4045. var lower = str.toLowerCase();
  4046. var hex = '';
  4047. var spaceTerminated = false;
  4048. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  4049. var code = lower.charCodeAt(i);
  4050. // check to see if we are dealing with a valid hex char [a-f|0-9]
  4051. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
  4052. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  4053. spaceTerminated = code === 32;
  4054. if (!valid) {
  4055. break;
  4056. }
  4057. hex += lower[i];
  4058. }
  4059. if (hex.length === 0) {
  4060. return undefined;
  4061. }
  4062. var codePoint = parseInt(hex, 16);
  4063. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
  4064. // Add special case for
  4065. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  4066. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  4067. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  4068. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  4069. }
  4070. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  4071. }
  4072. var CONTAINS_ESCAPE = /\\/;
  4073. function unesc(str) {
  4074. var needToProcess = CONTAINS_ESCAPE.test(str);
  4075. if (!needToProcess) {
  4076. return str;
  4077. }
  4078. var ret = "";
  4079. for (var i = 0; i < str.length; i++) {
  4080. if (str[i] === "\\") {
  4081. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  4082. if (gobbled !== undefined) {
  4083. ret += gobbled[0];
  4084. i += gobbled[1];
  4085. continue;
  4086. }
  4087. // Retain a pair of \\ if double escaped `\\\\`
  4088. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  4089. if (str[i + 1] === "\\") {
  4090. ret += "\\";
  4091. i++;
  4092. continue;
  4093. }
  4094. // if \\ is at the end of the string retain it
  4095. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  4096. if (str.length === i + 1) {
  4097. ret += str[i];
  4098. }
  4099. continue;
  4100. }
  4101. ret += str[i];
  4102. }
  4103. return ret;
  4104. }
  4105. module.exports = exports.default;
  4106. } (unesc$1, unesc$1.exports));
  4107. return unesc$1.exports;
  4108. }
  4109. var getProp$1 = {exports: {}};
  4110. var hasRequiredGetProp$1;
  4111. function requireGetProp$1 () {
  4112. if (hasRequiredGetProp$1) return getProp$1.exports;
  4113. hasRequiredGetProp$1 = 1;
  4114. (function (module, exports) {
  4115. exports.__esModule = true;
  4116. exports["default"] = getProp;
  4117. function getProp(obj) {
  4118. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4119. props[_key - 1] = arguments[_key];
  4120. }
  4121. while (props.length > 0) {
  4122. var prop = props.shift();
  4123. if (!obj[prop]) {
  4124. return undefined;
  4125. }
  4126. obj = obj[prop];
  4127. }
  4128. return obj;
  4129. }
  4130. module.exports = exports.default;
  4131. } (getProp$1, getProp$1.exports));
  4132. return getProp$1.exports;
  4133. }
  4134. var ensureObject$1 = {exports: {}};
  4135. var hasRequiredEnsureObject$1;
  4136. function requireEnsureObject$1 () {
  4137. if (hasRequiredEnsureObject$1) return ensureObject$1.exports;
  4138. hasRequiredEnsureObject$1 = 1;
  4139. (function (module, exports) {
  4140. exports.__esModule = true;
  4141. exports["default"] = ensureObject;
  4142. function ensureObject(obj) {
  4143. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4144. props[_key - 1] = arguments[_key];
  4145. }
  4146. while (props.length > 0) {
  4147. var prop = props.shift();
  4148. if (!obj[prop]) {
  4149. obj[prop] = {};
  4150. }
  4151. obj = obj[prop];
  4152. }
  4153. }
  4154. module.exports = exports.default;
  4155. } (ensureObject$1, ensureObject$1.exports));
  4156. return ensureObject$1.exports;
  4157. }
  4158. var stripComments$1 = {exports: {}};
  4159. var hasRequiredStripComments$1;
  4160. function requireStripComments$1 () {
  4161. if (hasRequiredStripComments$1) return stripComments$1.exports;
  4162. hasRequiredStripComments$1 = 1;
  4163. (function (module, exports) {
  4164. exports.__esModule = true;
  4165. exports["default"] = stripComments;
  4166. function stripComments(str) {
  4167. var s = "";
  4168. var commentStart = str.indexOf("/*");
  4169. var lastEnd = 0;
  4170. while (commentStart >= 0) {
  4171. s = s + str.slice(lastEnd, commentStart);
  4172. var commentEnd = str.indexOf("*/", commentStart + 2);
  4173. if (commentEnd < 0) {
  4174. return s;
  4175. }
  4176. lastEnd = commentEnd + 2;
  4177. commentStart = str.indexOf("/*", lastEnd);
  4178. }
  4179. s = s + str.slice(lastEnd);
  4180. return s;
  4181. }
  4182. module.exports = exports.default;
  4183. } (stripComments$1, stripComments$1.exports));
  4184. return stripComments$1.exports;
  4185. }
  4186. var hasRequiredUtil$2;
  4187. function requireUtil$2 () {
  4188. if (hasRequiredUtil$2) return util$2;
  4189. hasRequiredUtil$2 = 1;
  4190. util$2.__esModule = true;
  4191. util$2.unesc = util$2.stripComments = util$2.getProp = util$2.ensureObject = void 0;
  4192. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc$1());
  4193. util$2.unesc = _unesc["default"];
  4194. var _getProp = _interopRequireDefault(/*@__PURE__*/ requireGetProp$1());
  4195. util$2.getProp = _getProp["default"];
  4196. var _ensureObject = _interopRequireDefault(/*@__PURE__*/ requireEnsureObject$1());
  4197. util$2.ensureObject = _ensureObject["default"];
  4198. var _stripComments = _interopRequireDefault(/*@__PURE__*/ requireStripComments$1());
  4199. util$2.stripComments = _stripComments["default"];
  4200. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4201. return util$2;
  4202. }
  4203. var hasRequiredNode$2;
  4204. function requireNode$2 () {
  4205. if (hasRequiredNode$2) return node$2.exports;
  4206. hasRequiredNode$2 = 1;
  4207. (function (module, exports) {
  4208. exports.__esModule = true;
  4209. exports["default"] = void 0;
  4210. var _util = /*@__PURE__*/ requireUtil$2();
  4211. 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); } }
  4212. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4213. var cloneNode = function cloneNode(obj, parent) {
  4214. if (typeof obj !== 'object' || obj === null) {
  4215. return obj;
  4216. }
  4217. var cloned = new obj.constructor();
  4218. for (var i in obj) {
  4219. if (!obj.hasOwnProperty(i)) {
  4220. continue;
  4221. }
  4222. var value = obj[i];
  4223. var type = typeof value;
  4224. if (i === 'parent' && type === 'object') {
  4225. if (parent) {
  4226. cloned[i] = parent;
  4227. }
  4228. } else if (value instanceof Array) {
  4229. cloned[i] = value.map(function (j) {
  4230. return cloneNode(j, cloned);
  4231. });
  4232. } else {
  4233. cloned[i] = cloneNode(value, cloned);
  4234. }
  4235. }
  4236. return cloned;
  4237. };
  4238. var Node = /*#__PURE__*/function () {
  4239. function Node(opts) {
  4240. if (opts === void 0) {
  4241. opts = {};
  4242. }
  4243. Object.assign(this, opts);
  4244. this.spaces = this.spaces || {};
  4245. this.spaces.before = this.spaces.before || '';
  4246. this.spaces.after = this.spaces.after || '';
  4247. }
  4248. var _proto = Node.prototype;
  4249. _proto.remove = function remove() {
  4250. if (this.parent) {
  4251. this.parent.removeChild(this);
  4252. }
  4253. this.parent = undefined;
  4254. return this;
  4255. };
  4256. _proto.replaceWith = function replaceWith() {
  4257. if (this.parent) {
  4258. for (var index in arguments) {
  4259. this.parent.insertBefore(this, arguments[index]);
  4260. }
  4261. this.remove();
  4262. }
  4263. return this;
  4264. };
  4265. _proto.next = function next() {
  4266. return this.parent.at(this.parent.index(this) + 1);
  4267. };
  4268. _proto.prev = function prev() {
  4269. return this.parent.at(this.parent.index(this) - 1);
  4270. };
  4271. _proto.clone = function clone(overrides) {
  4272. if (overrides === void 0) {
  4273. overrides = {};
  4274. }
  4275. var cloned = cloneNode(this);
  4276. for (var name in overrides) {
  4277. cloned[name] = overrides[name];
  4278. }
  4279. return cloned;
  4280. }
  4281. /**
  4282. * Some non-standard syntax doesn't follow normal escaping rules for css.
  4283. * This allows non standard syntax to be appended to an existing property
  4284. * by specifying the escaped value. By specifying the escaped value,
  4285. * illegal characters are allowed to be directly inserted into css output.
  4286. * @param {string} name the property to set
  4287. * @param {any} value the unescaped value of the property
  4288. * @param {string} valueEscaped optional. the escaped value of the property.
  4289. */;
  4290. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  4291. if (!this.raws) {
  4292. this.raws = {};
  4293. }
  4294. var originalValue = this[name];
  4295. var originalEscaped = this.raws[name];
  4296. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  4297. if (originalEscaped || valueEscaped !== value) {
  4298. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  4299. } else {
  4300. delete this.raws[name]; // delete any escaped value that was created by the setter.
  4301. }
  4302. }
  4303. /**
  4304. * Some non-standard syntax doesn't follow normal escaping rules for css.
  4305. * This allows the escaped value to be specified directly, allowing illegal
  4306. * characters to be directly inserted into css output.
  4307. * @param {string} name the property to set
  4308. * @param {any} value the unescaped value of the property
  4309. * @param {string} valueEscaped the escaped value of the property.
  4310. */;
  4311. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  4312. if (!this.raws) {
  4313. this.raws = {};
  4314. }
  4315. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  4316. this.raws[name] = valueEscaped;
  4317. }
  4318. /**
  4319. * When you want a value to passed through to CSS directly. This method
  4320. * deletes the corresponding raw value causing the stringifier to fallback
  4321. * to the unescaped value.
  4322. * @param {string} name the property to set.
  4323. * @param {any} value The value that is both escaped and unescaped.
  4324. */;
  4325. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  4326. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  4327. if (this.raws) {
  4328. delete this.raws[name];
  4329. }
  4330. }
  4331. /**
  4332. *
  4333. * @param {number} line The number (starting with 1)
  4334. * @param {number} column The column number (starting with 1)
  4335. */;
  4336. _proto.isAtPosition = function isAtPosition(line, column) {
  4337. if (this.source && this.source.start && this.source.end) {
  4338. if (this.source.start.line > line) {
  4339. return false;
  4340. }
  4341. if (this.source.end.line < line) {
  4342. return false;
  4343. }
  4344. if (this.source.start.line === line && this.source.start.column > column) {
  4345. return false;
  4346. }
  4347. if (this.source.end.line === line && this.source.end.column < column) {
  4348. return false;
  4349. }
  4350. return true;
  4351. }
  4352. return undefined;
  4353. };
  4354. _proto.stringifyProperty = function stringifyProperty(name) {
  4355. return this.raws && this.raws[name] || this[name];
  4356. };
  4357. _proto.valueToString = function valueToString() {
  4358. return String(this.stringifyProperty("value"));
  4359. };
  4360. _proto.toString = function toString() {
  4361. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  4362. };
  4363. _createClass(Node, [{
  4364. key: "rawSpaceBefore",
  4365. get: function get() {
  4366. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  4367. if (rawSpace === undefined) {
  4368. rawSpace = this.spaces && this.spaces.before;
  4369. }
  4370. return rawSpace || "";
  4371. },
  4372. set: function set(raw) {
  4373. (0, _util.ensureObject)(this, "raws", "spaces");
  4374. this.raws.spaces.before = raw;
  4375. }
  4376. }, {
  4377. key: "rawSpaceAfter",
  4378. get: function get() {
  4379. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  4380. if (rawSpace === undefined) {
  4381. rawSpace = this.spaces.after;
  4382. }
  4383. return rawSpace || "";
  4384. },
  4385. set: function set(raw) {
  4386. (0, _util.ensureObject)(this, "raws", "spaces");
  4387. this.raws.spaces.after = raw;
  4388. }
  4389. }]);
  4390. return Node;
  4391. }();
  4392. exports["default"] = Node;
  4393. module.exports = exports.default;
  4394. } (node$2, node$2.exports));
  4395. return node$2.exports;
  4396. }
  4397. var types$2 = {};
  4398. var hasRequiredTypes$1;
  4399. function requireTypes$1 () {
  4400. if (hasRequiredTypes$1) return types$2;
  4401. hasRequiredTypes$1 = 1;
  4402. types$2.__esModule = true;
  4403. 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;
  4404. var TAG = 'tag';
  4405. types$2.TAG = TAG;
  4406. var STRING = 'string';
  4407. types$2.STRING = STRING;
  4408. var SELECTOR = 'selector';
  4409. types$2.SELECTOR = SELECTOR;
  4410. var ROOT = 'root';
  4411. types$2.ROOT = ROOT;
  4412. var PSEUDO = 'pseudo';
  4413. types$2.PSEUDO = PSEUDO;
  4414. var NESTING = 'nesting';
  4415. types$2.NESTING = NESTING;
  4416. var ID = 'id';
  4417. types$2.ID = ID;
  4418. var COMMENT = 'comment';
  4419. types$2.COMMENT = COMMENT;
  4420. var COMBINATOR = 'combinator';
  4421. types$2.COMBINATOR = COMBINATOR;
  4422. var CLASS = 'class';
  4423. types$2.CLASS = CLASS;
  4424. var ATTRIBUTE = 'attribute';
  4425. types$2.ATTRIBUTE = ATTRIBUTE;
  4426. var UNIVERSAL = 'universal';
  4427. types$2.UNIVERSAL = UNIVERSAL;
  4428. return types$2;
  4429. }
  4430. var hasRequiredContainer$1;
  4431. function requireContainer$1 () {
  4432. if (hasRequiredContainer$1) return container$1.exports;
  4433. hasRequiredContainer$1 = 1;
  4434. (function (module, exports) {
  4435. exports.__esModule = true;
  4436. exports["default"] = void 0;
  4437. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  4438. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes$1());
  4439. 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); }
  4440. 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; }
  4441. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4442. 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."); }
  4443. 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); }
  4444. 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; }
  4445. 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); } }
  4446. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4447. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4448. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4449. var Container = /*#__PURE__*/function (_Node) {
  4450. _inheritsLoose(Container, _Node);
  4451. function Container(opts) {
  4452. var _this;
  4453. _this = _Node.call(this, opts) || this;
  4454. if (!_this.nodes) {
  4455. _this.nodes = [];
  4456. }
  4457. return _this;
  4458. }
  4459. var _proto = Container.prototype;
  4460. _proto.append = function append(selector) {
  4461. selector.parent = this;
  4462. this.nodes.push(selector);
  4463. return this;
  4464. };
  4465. _proto.prepend = function prepend(selector) {
  4466. selector.parent = this;
  4467. this.nodes.unshift(selector);
  4468. for (var id in this.indexes) {
  4469. this.indexes[id]++;
  4470. }
  4471. return this;
  4472. };
  4473. _proto.at = function at(index) {
  4474. return this.nodes[index];
  4475. };
  4476. _proto.index = function index(child) {
  4477. if (typeof child === 'number') {
  4478. return child;
  4479. }
  4480. return this.nodes.indexOf(child);
  4481. };
  4482. _proto.removeChild = function removeChild(child) {
  4483. child = this.index(child);
  4484. this.at(child).parent = undefined;
  4485. this.nodes.splice(child, 1);
  4486. var index;
  4487. for (var id in this.indexes) {
  4488. index = this.indexes[id];
  4489. if (index >= child) {
  4490. this.indexes[id] = index - 1;
  4491. }
  4492. }
  4493. return this;
  4494. };
  4495. _proto.removeAll = function removeAll() {
  4496. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  4497. var node = _step.value;
  4498. node.parent = undefined;
  4499. }
  4500. this.nodes = [];
  4501. return this;
  4502. };
  4503. _proto.empty = function empty() {
  4504. return this.removeAll();
  4505. };
  4506. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  4507. var _this$nodes;
  4508. newNode.parent = this;
  4509. var oldIndex = this.index(oldNode);
  4510. var resetNode = [];
  4511. for (var i = 2; i < arguments.length; i++) {
  4512. resetNode.push(arguments[i]);
  4513. }
  4514. (_this$nodes = this.nodes).splice.apply(_this$nodes, [oldIndex + 1, 0, newNode].concat(resetNode));
  4515. newNode.parent = this;
  4516. var index;
  4517. for (var id in this.indexes) {
  4518. index = this.indexes[id];
  4519. if (oldIndex < index) {
  4520. this.indexes[id] = index + arguments.length - 1;
  4521. }
  4522. }
  4523. return this;
  4524. };
  4525. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  4526. var _this$nodes2;
  4527. newNode.parent = this;
  4528. var oldIndex = this.index(oldNode);
  4529. var resetNode = [];
  4530. for (var i = 2; i < arguments.length; i++) {
  4531. resetNode.push(arguments[i]);
  4532. }
  4533. (_this$nodes2 = this.nodes).splice.apply(_this$nodes2, [oldIndex, 0, newNode].concat(resetNode));
  4534. newNode.parent = this;
  4535. var index;
  4536. for (var id in this.indexes) {
  4537. index = this.indexes[id];
  4538. if (index >= oldIndex) {
  4539. this.indexes[id] = index + arguments.length - 1;
  4540. }
  4541. }
  4542. return this;
  4543. };
  4544. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  4545. var found = undefined;
  4546. this.each(function (node) {
  4547. if (node.atPosition) {
  4548. var foundChild = node.atPosition(line, col);
  4549. if (foundChild) {
  4550. found = foundChild;
  4551. return false;
  4552. }
  4553. } else if (node.isAtPosition(line, col)) {
  4554. found = node;
  4555. return false;
  4556. }
  4557. });
  4558. return found;
  4559. }
  4560. /**
  4561. * Return the most specific node at the line and column number given.
  4562. * The source location is based on the original parsed location, locations aren't
  4563. * updated as selector nodes are mutated.
  4564. *
  4565. * Note that this location is relative to the location of the first character
  4566. * of the selector, and not the location of the selector in the overall document
  4567. * when used in conjunction with postcss.
  4568. *
  4569. * If not found, returns undefined.
  4570. * @param {number} line The line number of the node to find. (1-based index)
  4571. * @param {number} col The column number of the node to find. (1-based index)
  4572. */;
  4573. _proto.atPosition = function atPosition(line, col) {
  4574. if (this.isAtPosition(line, col)) {
  4575. return this._findChildAtPosition(line, col) || this;
  4576. } else {
  4577. return undefined;
  4578. }
  4579. };
  4580. _proto._inferEndPosition = function _inferEndPosition() {
  4581. if (this.last && this.last.source && this.last.source.end) {
  4582. this.source = this.source || {};
  4583. this.source.end = this.source.end || {};
  4584. Object.assign(this.source.end, this.last.source.end);
  4585. }
  4586. };
  4587. _proto.each = function each(callback) {
  4588. if (!this.lastEach) {
  4589. this.lastEach = 0;
  4590. }
  4591. if (!this.indexes) {
  4592. this.indexes = {};
  4593. }
  4594. this.lastEach++;
  4595. var id = this.lastEach;
  4596. this.indexes[id] = 0;
  4597. if (!this.length) {
  4598. return undefined;
  4599. }
  4600. var index, result;
  4601. while (this.indexes[id] < this.length) {
  4602. index = this.indexes[id];
  4603. result = callback(this.at(index), index);
  4604. if (result === false) {
  4605. break;
  4606. }
  4607. this.indexes[id] += 1;
  4608. }
  4609. delete this.indexes[id];
  4610. if (result === false) {
  4611. return false;
  4612. }
  4613. };
  4614. _proto.walk = function walk(callback) {
  4615. return this.each(function (node, i) {
  4616. var result = callback(node, i);
  4617. if (result !== false && node.length) {
  4618. result = node.walk(callback);
  4619. }
  4620. if (result === false) {
  4621. return false;
  4622. }
  4623. });
  4624. };
  4625. _proto.walkAttributes = function walkAttributes(callback) {
  4626. var _this2 = this;
  4627. return this.walk(function (selector) {
  4628. if (selector.type === types.ATTRIBUTE) {
  4629. return callback.call(_this2, selector);
  4630. }
  4631. });
  4632. };
  4633. _proto.walkClasses = function walkClasses(callback) {
  4634. var _this3 = this;
  4635. return this.walk(function (selector) {
  4636. if (selector.type === types.CLASS) {
  4637. return callback.call(_this3, selector);
  4638. }
  4639. });
  4640. };
  4641. _proto.walkCombinators = function walkCombinators(callback) {
  4642. var _this4 = this;
  4643. return this.walk(function (selector) {
  4644. if (selector.type === types.COMBINATOR) {
  4645. return callback.call(_this4, selector);
  4646. }
  4647. });
  4648. };
  4649. _proto.walkComments = function walkComments(callback) {
  4650. var _this5 = this;
  4651. return this.walk(function (selector) {
  4652. if (selector.type === types.COMMENT) {
  4653. return callback.call(_this5, selector);
  4654. }
  4655. });
  4656. };
  4657. _proto.walkIds = function walkIds(callback) {
  4658. var _this6 = this;
  4659. return this.walk(function (selector) {
  4660. if (selector.type === types.ID) {
  4661. return callback.call(_this6, selector);
  4662. }
  4663. });
  4664. };
  4665. _proto.walkNesting = function walkNesting(callback) {
  4666. var _this7 = this;
  4667. return this.walk(function (selector) {
  4668. if (selector.type === types.NESTING) {
  4669. return callback.call(_this7, selector);
  4670. }
  4671. });
  4672. };
  4673. _proto.walkPseudos = function walkPseudos(callback) {
  4674. var _this8 = this;
  4675. return this.walk(function (selector) {
  4676. if (selector.type === types.PSEUDO) {
  4677. return callback.call(_this8, selector);
  4678. }
  4679. });
  4680. };
  4681. _proto.walkTags = function walkTags(callback) {
  4682. var _this9 = this;
  4683. return this.walk(function (selector) {
  4684. if (selector.type === types.TAG) {
  4685. return callback.call(_this9, selector);
  4686. }
  4687. });
  4688. };
  4689. _proto.walkUniversals = function walkUniversals(callback) {
  4690. var _this10 = this;
  4691. return this.walk(function (selector) {
  4692. if (selector.type === types.UNIVERSAL) {
  4693. return callback.call(_this10, selector);
  4694. }
  4695. });
  4696. };
  4697. _proto.split = function split(callback) {
  4698. var _this11 = this;
  4699. var current = [];
  4700. return this.reduce(function (memo, node, index) {
  4701. var split = callback.call(_this11, node);
  4702. current.push(node);
  4703. if (split) {
  4704. memo.push(current);
  4705. current = [];
  4706. } else if (index === _this11.length - 1) {
  4707. memo.push(current);
  4708. }
  4709. return memo;
  4710. }, []);
  4711. };
  4712. _proto.map = function map(callback) {
  4713. return this.nodes.map(callback);
  4714. };
  4715. _proto.reduce = function reduce(callback, memo) {
  4716. return this.nodes.reduce(callback, memo);
  4717. };
  4718. _proto.every = function every(callback) {
  4719. return this.nodes.every(callback);
  4720. };
  4721. _proto.some = function some(callback) {
  4722. return this.nodes.some(callback);
  4723. };
  4724. _proto.filter = function filter(callback) {
  4725. return this.nodes.filter(callback);
  4726. };
  4727. _proto.sort = function sort(callback) {
  4728. return this.nodes.sort(callback);
  4729. };
  4730. _proto.toString = function toString() {
  4731. return this.map(String).join('');
  4732. };
  4733. _createClass(Container, [{
  4734. key: "first",
  4735. get: function get() {
  4736. return this.at(0);
  4737. }
  4738. }, {
  4739. key: "last",
  4740. get: function get() {
  4741. return this.at(this.length - 1);
  4742. }
  4743. }, {
  4744. key: "length",
  4745. get: function get() {
  4746. return this.nodes.length;
  4747. }
  4748. }]);
  4749. return Container;
  4750. }(_node["default"]);
  4751. exports["default"] = Container;
  4752. module.exports = exports.default;
  4753. } (container$1, container$1.exports));
  4754. return container$1.exports;
  4755. }
  4756. var hasRequiredRoot$1;
  4757. function requireRoot$1 () {
  4758. if (hasRequiredRoot$1) return root$1.exports;
  4759. hasRequiredRoot$1 = 1;
  4760. (function (module, exports) {
  4761. exports.__esModule = true;
  4762. exports["default"] = void 0;
  4763. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer$1());
  4764. var _types = /*@__PURE__*/ requireTypes$1();
  4765. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4766. 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); } }
  4767. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4768. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4769. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4770. var Root = /*#__PURE__*/function (_Container) {
  4771. _inheritsLoose(Root, _Container);
  4772. function Root(opts) {
  4773. var _this;
  4774. _this = _Container.call(this, opts) || this;
  4775. _this.type = _types.ROOT;
  4776. return _this;
  4777. }
  4778. var _proto = Root.prototype;
  4779. _proto.toString = function toString() {
  4780. var str = this.reduce(function (memo, selector) {
  4781. memo.push(String(selector));
  4782. return memo;
  4783. }, []).join(',');
  4784. return this.trailingComma ? str + ',' : str;
  4785. };
  4786. _proto.error = function error(message, options) {
  4787. if (this._error) {
  4788. return this._error(message, options);
  4789. } else {
  4790. return new Error(message);
  4791. }
  4792. };
  4793. _createClass(Root, [{
  4794. key: "errorGenerator",
  4795. set: function set(handler) {
  4796. this._error = handler;
  4797. }
  4798. }]);
  4799. return Root;
  4800. }(_container["default"]);
  4801. exports["default"] = Root;
  4802. module.exports = exports.default;
  4803. } (root$1, root$1.exports));
  4804. return root$1.exports;
  4805. }
  4806. var selector$1 = {exports: {}};
  4807. var hasRequiredSelector$1;
  4808. function requireSelector$1 () {
  4809. if (hasRequiredSelector$1) return selector$1.exports;
  4810. hasRequiredSelector$1 = 1;
  4811. (function (module, exports) {
  4812. exports.__esModule = true;
  4813. exports["default"] = void 0;
  4814. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer$1());
  4815. var _types = /*@__PURE__*/ requireTypes$1();
  4816. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4817. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4818. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4819. var Selector = /*#__PURE__*/function (_Container) {
  4820. _inheritsLoose(Selector, _Container);
  4821. function Selector(opts) {
  4822. var _this;
  4823. _this = _Container.call(this, opts) || this;
  4824. _this.type = _types.SELECTOR;
  4825. return _this;
  4826. }
  4827. return Selector;
  4828. }(_container["default"]);
  4829. exports["default"] = Selector;
  4830. module.exports = exports.default;
  4831. } (selector$1, selector$1.exports));
  4832. return selector$1.exports;
  4833. }
  4834. var className$1 = {exports: {}};
  4835. /*! https://mths.be/cssesc v3.0.0 by @mathias */
  4836. var cssesc_1;
  4837. var hasRequiredCssesc;
  4838. function requireCssesc () {
  4839. if (hasRequiredCssesc) return cssesc_1;
  4840. hasRequiredCssesc = 1;
  4841. var object = {};
  4842. var hasOwnProperty = object.hasOwnProperty;
  4843. var merge = function merge(options, defaults) {
  4844. if (!options) {
  4845. return defaults;
  4846. }
  4847. var result = {};
  4848. for (var key in defaults) {
  4849. // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
  4850. // only recognized option names are used.
  4851. result[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key];
  4852. }
  4853. return result;
  4854. };
  4855. var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
  4856. var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
  4857. var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  4858. // https://mathiasbynens.be/notes/css-escapes#css
  4859. var cssesc = function cssesc(string, options) {
  4860. options = merge(options, cssesc.options);
  4861. if (options.quotes != 'single' && options.quotes != 'double') {
  4862. options.quotes = 'single';
  4863. }
  4864. var quote = options.quotes == 'double' ? '"' : '\'';
  4865. var isIdentifier = options.isIdentifier;
  4866. var firstChar = string.charAt(0);
  4867. var output = '';
  4868. var counter = 0;
  4869. var length = string.length;
  4870. while (counter < length) {
  4871. var character = string.charAt(counter++);
  4872. var codePoint = character.charCodeAt();
  4873. var value = void 0;
  4874. // If it’s not a printable ASCII character…
  4875. if (codePoint < 0x20 || codePoint > 0x7E) {
  4876. if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
  4877. // It’s a high surrogate, and there is a next character.
  4878. var extra = string.charCodeAt(counter++);
  4879. if ((extra & 0xFC00) == 0xDC00) {
  4880. // next character is low surrogate
  4881. codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
  4882. } else {
  4883. // It’s an unmatched surrogate; only append this code unit, in case
  4884. // the next code unit is the high surrogate of a surrogate pair.
  4885. counter--;
  4886. }
  4887. }
  4888. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4889. } else {
  4890. if (options.escapeEverything) {
  4891. if (regexAnySingleEscape.test(character)) {
  4892. value = '\\' + character;
  4893. } else {
  4894. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4895. }
  4896. } else if (/[\t\n\f\r\x0B]/.test(character)) {
  4897. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  4898. } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
  4899. value = '\\' + character;
  4900. } else {
  4901. value = character;
  4902. }
  4903. }
  4904. output += value;
  4905. }
  4906. if (isIdentifier) {
  4907. if (/^-[-\d]/.test(output)) {
  4908. output = '\\-' + output.slice(1);
  4909. } else if (/\d/.test(firstChar)) {
  4910. output = '\\3' + firstChar + ' ' + output.slice(1);
  4911. }
  4912. }
  4913. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  4914. // since they’re redundant. Note that this is only possible if the escape
  4915. // sequence isn’t preceded by an odd number of backslashes.
  4916. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
  4917. if ($1 && $1.length % 2) {
  4918. // It’s not safe to remove the space, so don’t.
  4919. return $0;
  4920. }
  4921. // Strip the space.
  4922. return ($1 || '') + $2;
  4923. });
  4924. if (!isIdentifier && options.wrap) {
  4925. return quote + output + quote;
  4926. }
  4927. return output;
  4928. };
  4929. // Expose default options (so they can be overridden globally).
  4930. cssesc.options = {
  4931. 'escapeEverything': false,
  4932. 'isIdentifier': false,
  4933. 'quotes': 'single',
  4934. 'wrap': false
  4935. };
  4936. cssesc.version = '3.0.0';
  4937. cssesc_1 = cssesc;
  4938. return cssesc_1;
  4939. }
  4940. var hasRequiredClassName$1;
  4941. function requireClassName$1 () {
  4942. if (hasRequiredClassName$1) return className$1.exports;
  4943. hasRequiredClassName$1 = 1;
  4944. (function (module, exports) {
  4945. exports.__esModule = true;
  4946. exports["default"] = void 0;
  4947. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  4948. var _util = /*@__PURE__*/ requireUtil$2();
  4949. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  4950. var _types = /*@__PURE__*/ requireTypes$1();
  4951. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  4952. 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); } }
  4953. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4954. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  4955. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4956. var ClassName = /*#__PURE__*/function (_Node) {
  4957. _inheritsLoose(ClassName, _Node);
  4958. function ClassName(opts) {
  4959. var _this;
  4960. _this = _Node.call(this, opts) || this;
  4961. _this.type = _types.CLASS;
  4962. _this._constructed = true;
  4963. return _this;
  4964. }
  4965. var _proto = ClassName.prototype;
  4966. _proto.valueToString = function valueToString() {
  4967. return '.' + _Node.prototype.valueToString.call(this);
  4968. };
  4969. _createClass(ClassName, [{
  4970. key: "value",
  4971. get: function get() {
  4972. return this._value;
  4973. },
  4974. set: function set(v) {
  4975. if (this._constructed) {
  4976. var escaped = (0, _cssesc["default"])(v, {
  4977. isIdentifier: true
  4978. });
  4979. if (escaped !== v) {
  4980. (0, _util.ensureObject)(this, "raws");
  4981. this.raws.value = escaped;
  4982. } else if (this.raws) {
  4983. delete this.raws.value;
  4984. }
  4985. }
  4986. this._value = v;
  4987. }
  4988. }]);
  4989. return ClassName;
  4990. }(_node["default"]);
  4991. exports["default"] = ClassName;
  4992. module.exports = exports.default;
  4993. } (className$1, className$1.exports));
  4994. return className$1.exports;
  4995. }
  4996. var comment$1 = {exports: {}};
  4997. var hasRequiredComment$1;
  4998. function requireComment$1 () {
  4999. if (hasRequiredComment$1) return comment$1.exports;
  5000. hasRequiredComment$1 = 1;
  5001. (function (module, exports) {
  5002. exports.__esModule = true;
  5003. exports["default"] = void 0;
  5004. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5005. var _types = /*@__PURE__*/ requireTypes$1();
  5006. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5007. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5008. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5009. var Comment = /*#__PURE__*/function (_Node) {
  5010. _inheritsLoose(Comment, _Node);
  5011. function Comment(opts) {
  5012. var _this;
  5013. _this = _Node.call(this, opts) || this;
  5014. _this.type = _types.COMMENT;
  5015. return _this;
  5016. }
  5017. return Comment;
  5018. }(_node["default"]);
  5019. exports["default"] = Comment;
  5020. module.exports = exports.default;
  5021. } (comment$1, comment$1.exports));
  5022. return comment$1.exports;
  5023. }
  5024. var id$1 = {exports: {}};
  5025. var hasRequiredId$1;
  5026. function requireId$1 () {
  5027. if (hasRequiredId$1) return id$1.exports;
  5028. hasRequiredId$1 = 1;
  5029. (function (module, exports) {
  5030. exports.__esModule = true;
  5031. exports["default"] = void 0;
  5032. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5033. var _types = /*@__PURE__*/ requireTypes$1();
  5034. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5035. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5036. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5037. var ID = /*#__PURE__*/function (_Node) {
  5038. _inheritsLoose(ID, _Node);
  5039. function ID(opts) {
  5040. var _this;
  5041. _this = _Node.call(this, opts) || this;
  5042. _this.type = _types.ID;
  5043. return _this;
  5044. }
  5045. var _proto = ID.prototype;
  5046. _proto.valueToString = function valueToString() {
  5047. return '#' + _Node.prototype.valueToString.call(this);
  5048. };
  5049. return ID;
  5050. }(_node["default"]);
  5051. exports["default"] = ID;
  5052. module.exports = exports.default;
  5053. } (id$1, id$1.exports));
  5054. return id$1.exports;
  5055. }
  5056. var tag$1 = {exports: {}};
  5057. var namespace$1 = {exports: {}};
  5058. var hasRequiredNamespace$1;
  5059. function requireNamespace$1 () {
  5060. if (hasRequiredNamespace$1) return namespace$1.exports;
  5061. hasRequiredNamespace$1 = 1;
  5062. (function (module, exports) {
  5063. exports.__esModule = true;
  5064. exports["default"] = void 0;
  5065. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  5066. var _util = /*@__PURE__*/ requireUtil$2();
  5067. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5068. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5069. 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); } }
  5070. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  5071. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5072. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5073. var Namespace = /*#__PURE__*/function (_Node) {
  5074. _inheritsLoose(Namespace, _Node);
  5075. function Namespace() {
  5076. return _Node.apply(this, arguments) || this;
  5077. }
  5078. var _proto = Namespace.prototype;
  5079. _proto.qualifiedName = function qualifiedName(value) {
  5080. if (this.namespace) {
  5081. return this.namespaceString + "|" + value;
  5082. } else {
  5083. return value;
  5084. }
  5085. };
  5086. _proto.valueToString = function valueToString() {
  5087. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  5088. };
  5089. _createClass(Namespace, [{
  5090. key: "namespace",
  5091. get: function get() {
  5092. return this._namespace;
  5093. },
  5094. set: function set(namespace) {
  5095. if (namespace === true || namespace === "*" || namespace === "&") {
  5096. this._namespace = namespace;
  5097. if (this.raws) {
  5098. delete this.raws.namespace;
  5099. }
  5100. return;
  5101. }
  5102. var escaped = (0, _cssesc["default"])(namespace, {
  5103. isIdentifier: true
  5104. });
  5105. this._namespace = namespace;
  5106. if (escaped !== namespace) {
  5107. (0, _util.ensureObject)(this, "raws");
  5108. this.raws.namespace = escaped;
  5109. } else if (this.raws) {
  5110. delete this.raws.namespace;
  5111. }
  5112. }
  5113. }, {
  5114. key: "ns",
  5115. get: function get() {
  5116. return this._namespace;
  5117. },
  5118. set: function set(namespace) {
  5119. this.namespace = namespace;
  5120. }
  5121. }, {
  5122. key: "namespaceString",
  5123. get: function get() {
  5124. if (this.namespace) {
  5125. var ns = this.stringifyProperty("namespace");
  5126. if (ns === true) {
  5127. return '';
  5128. } else {
  5129. return ns;
  5130. }
  5131. } else {
  5132. return '';
  5133. }
  5134. }
  5135. }]);
  5136. return Namespace;
  5137. }(_node["default"]);
  5138. exports["default"] = Namespace;
  5139. module.exports = exports.default;
  5140. } (namespace$1, namespace$1.exports));
  5141. return namespace$1.exports;
  5142. }
  5143. var hasRequiredTag$1;
  5144. function requireTag$1 () {
  5145. if (hasRequiredTag$1) return tag$1.exports;
  5146. hasRequiredTag$1 = 1;
  5147. (function (module, exports) {
  5148. exports.__esModule = true;
  5149. exports["default"] = void 0;
  5150. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace$1());
  5151. var _types = /*@__PURE__*/ requireTypes$1();
  5152. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5153. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5154. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5155. var Tag = /*#__PURE__*/function (_Namespace) {
  5156. _inheritsLoose(Tag, _Namespace);
  5157. function Tag(opts) {
  5158. var _this;
  5159. _this = _Namespace.call(this, opts) || this;
  5160. _this.type = _types.TAG;
  5161. return _this;
  5162. }
  5163. return Tag;
  5164. }(_namespace["default"]);
  5165. exports["default"] = Tag;
  5166. module.exports = exports.default;
  5167. } (tag$1, tag$1.exports));
  5168. return tag$1.exports;
  5169. }
  5170. var string$1 = {exports: {}};
  5171. var hasRequiredString$1;
  5172. function requireString$1 () {
  5173. if (hasRequiredString$1) return string$1.exports;
  5174. hasRequiredString$1 = 1;
  5175. (function (module, exports) {
  5176. exports.__esModule = true;
  5177. exports["default"] = void 0;
  5178. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5179. var _types = /*@__PURE__*/ requireTypes$1();
  5180. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5181. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5182. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5183. var String = /*#__PURE__*/function (_Node) {
  5184. _inheritsLoose(String, _Node);
  5185. function String(opts) {
  5186. var _this;
  5187. _this = _Node.call(this, opts) || this;
  5188. _this.type = _types.STRING;
  5189. return _this;
  5190. }
  5191. return String;
  5192. }(_node["default"]);
  5193. exports["default"] = String;
  5194. module.exports = exports.default;
  5195. } (string$1, string$1.exports));
  5196. return string$1.exports;
  5197. }
  5198. var pseudo$1 = {exports: {}};
  5199. var hasRequiredPseudo$1;
  5200. function requirePseudo$1 () {
  5201. if (hasRequiredPseudo$1) return pseudo$1.exports;
  5202. hasRequiredPseudo$1 = 1;
  5203. (function (module, exports) {
  5204. exports.__esModule = true;
  5205. exports["default"] = void 0;
  5206. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer$1());
  5207. var _types = /*@__PURE__*/ requireTypes$1();
  5208. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5209. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5210. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5211. var Pseudo = /*#__PURE__*/function (_Container) {
  5212. _inheritsLoose(Pseudo, _Container);
  5213. function Pseudo(opts) {
  5214. var _this;
  5215. _this = _Container.call(this, opts) || this;
  5216. _this.type = _types.PSEUDO;
  5217. return _this;
  5218. }
  5219. var _proto = Pseudo.prototype;
  5220. _proto.toString = function toString() {
  5221. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  5222. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  5223. };
  5224. return Pseudo;
  5225. }(_container["default"]);
  5226. exports["default"] = Pseudo;
  5227. module.exports = exports.default;
  5228. } (pseudo$1, pseudo$1.exports));
  5229. return pseudo$1.exports;
  5230. }
  5231. var attribute$1 = {};
  5232. var node$1;
  5233. var hasRequiredNode$1;
  5234. function requireNode$1 () {
  5235. if (hasRequiredNode$1) return node$1;
  5236. hasRequiredNode$1 = 1;
  5237. /**
  5238. * For Node.js, simply re-export the core `util.deprecate` function.
  5239. */
  5240. node$1 = require$$2.deprecate;
  5241. return node$1;
  5242. }
  5243. var hasRequiredAttribute$1;
  5244. function requireAttribute$1 () {
  5245. if (hasRequiredAttribute$1) return attribute$1;
  5246. hasRequiredAttribute$1 = 1;
  5247. (function (exports) {
  5248. exports.__esModule = true;
  5249. exports["default"] = void 0;
  5250. exports.unescapeValue = unescapeValue;
  5251. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  5252. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc$1());
  5253. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace$1());
  5254. var _types = /*@__PURE__*/ requireTypes$1();
  5255. var _CSSESC_QUOTE_OPTIONS;
  5256. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5257. 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); } }
  5258. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  5259. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5260. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5261. var deprecate = /*@__PURE__*/ requireNode$1();
  5262. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  5263. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  5264. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  5265. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  5266. function unescapeValue(value) {
  5267. var deprecatedUsage = false;
  5268. var quoteMark = null;
  5269. var unescaped = value;
  5270. var m = unescaped.match(WRAPPED_IN_QUOTES);
  5271. if (m) {
  5272. quoteMark = m[1];
  5273. unescaped = m[2];
  5274. }
  5275. unescaped = (0, _unesc["default"])(unescaped);
  5276. if (unescaped !== value) {
  5277. deprecatedUsage = true;
  5278. }
  5279. return {
  5280. deprecatedUsage: deprecatedUsage,
  5281. unescaped: unescaped,
  5282. quoteMark: quoteMark
  5283. };
  5284. }
  5285. function handleDeprecatedContructorOpts(opts) {
  5286. if (opts.quoteMark !== undefined) {
  5287. return opts;
  5288. }
  5289. if (opts.value === undefined) {
  5290. return opts;
  5291. }
  5292. warnOfDeprecatedConstructor();
  5293. var _unescapeValue = unescapeValue(opts.value),
  5294. quoteMark = _unescapeValue.quoteMark,
  5295. unescaped = _unescapeValue.unescaped;
  5296. if (!opts.raws) {
  5297. opts.raws = {};
  5298. }
  5299. if (opts.raws.value === undefined) {
  5300. opts.raws.value = opts.value;
  5301. }
  5302. opts.value = unescaped;
  5303. opts.quoteMark = quoteMark;
  5304. return opts;
  5305. }
  5306. var Attribute = /*#__PURE__*/function (_Namespace) {
  5307. _inheritsLoose(Attribute, _Namespace);
  5308. function Attribute(opts) {
  5309. var _this;
  5310. if (opts === void 0) {
  5311. opts = {};
  5312. }
  5313. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  5314. _this.type = _types.ATTRIBUTE;
  5315. _this.raws = _this.raws || {};
  5316. Object.defineProperty(_this.raws, 'unquoted', {
  5317. get: deprecate(function () {
  5318. return _this.value;
  5319. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  5320. set: deprecate(function () {
  5321. return _this.value;
  5322. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  5323. });
  5324. _this._constructed = true;
  5325. return _this;
  5326. }
  5327. /**
  5328. * Returns the Attribute's value quoted such that it would be legal to use
  5329. * in the value of a css file. The original value's quotation setting
  5330. * used for stringification is left unchanged. See `setValue(value, options)`
  5331. * if you want to control the quote settings of a new value for the attribute.
  5332. *
  5333. * You can also change the quotation used for the current value by setting quoteMark.
  5334. *
  5335. * Options:
  5336. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  5337. * option is not set, the original value for quoteMark will be used. If
  5338. * indeterminate, a double quote is used. The legal values are:
  5339. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  5340. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  5341. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  5342. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  5343. * over the quoteMark option value.
  5344. * * smart {boolean} - if true, will select a quote mark based on the value
  5345. * and the other options specified here. See the `smartQuoteMark()`
  5346. * method.
  5347. **/
  5348. var _proto = Attribute.prototype;
  5349. _proto.getQuotedValue = function getQuotedValue(options) {
  5350. if (options === void 0) {
  5351. options = {};
  5352. }
  5353. var quoteMark = this._determineQuoteMark(options);
  5354. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  5355. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  5356. return escaped;
  5357. };
  5358. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  5359. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  5360. }
  5361. /**
  5362. * Set the unescaped value with the specified quotation options. The value
  5363. * provided must not include any wrapping quote marks -- those quotes will
  5364. * be interpreted as part of the value and escaped accordingly.
  5365. */;
  5366. _proto.setValue = function setValue(value, options) {
  5367. if (options === void 0) {
  5368. options = {};
  5369. }
  5370. this._value = value;
  5371. this._quoteMark = this._determineQuoteMark(options);
  5372. this._syncRawValue();
  5373. }
  5374. /**
  5375. * Intelligently select a quoteMark value based on the value's contents. If
  5376. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  5377. * mark will be picked that minimizes the number of escapes.
  5378. *
  5379. * If there's no clear winner, the quote mark from these options is used,
  5380. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  5381. * true). If the quoteMark is unspecified, a double quote is used.
  5382. *
  5383. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  5384. * from the quoteValue method.
  5385. */;
  5386. _proto.smartQuoteMark = function smartQuoteMark(options) {
  5387. var v = this.value;
  5388. var numSingleQuotes = v.replace(/[^']/g, '').length;
  5389. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  5390. if (numSingleQuotes + numDoubleQuotes === 0) {
  5391. var escaped = (0, _cssesc["default"])(v, {
  5392. isIdentifier: true
  5393. });
  5394. if (escaped === v) {
  5395. return Attribute.NO_QUOTE;
  5396. } else {
  5397. var pref = this.preferredQuoteMark(options);
  5398. if (pref === Attribute.NO_QUOTE) {
  5399. // pick a quote mark that isn't none and see if it's smaller
  5400. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  5401. var opts = CSSESC_QUOTE_OPTIONS[quote];
  5402. var quoteValue = (0, _cssesc["default"])(v, opts);
  5403. if (quoteValue.length < escaped.length) {
  5404. return quote;
  5405. }
  5406. }
  5407. return pref;
  5408. }
  5409. } else if (numDoubleQuotes === numSingleQuotes) {
  5410. return this.preferredQuoteMark(options);
  5411. } else if (numDoubleQuotes < numSingleQuotes) {
  5412. return Attribute.DOUBLE_QUOTE;
  5413. } else {
  5414. return Attribute.SINGLE_QUOTE;
  5415. }
  5416. }
  5417. /**
  5418. * Selects the preferred quote mark based on the options and the current quote mark value.
  5419. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  5420. * instead.
  5421. */;
  5422. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  5423. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  5424. if (quoteMark === undefined) {
  5425. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  5426. }
  5427. if (quoteMark === undefined) {
  5428. quoteMark = Attribute.DOUBLE_QUOTE;
  5429. }
  5430. return quoteMark;
  5431. };
  5432. _proto._syncRawValue = function _syncRawValue() {
  5433. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  5434. if (rawValue === this._value) {
  5435. if (this.raws) {
  5436. delete this.raws.value;
  5437. }
  5438. } else {
  5439. this.raws.value = rawValue;
  5440. }
  5441. };
  5442. _proto._handleEscapes = function _handleEscapes(prop, value) {
  5443. if (this._constructed) {
  5444. var escaped = (0, _cssesc["default"])(value, {
  5445. isIdentifier: true
  5446. });
  5447. if (escaped !== value) {
  5448. this.raws[prop] = escaped;
  5449. } else {
  5450. delete this.raws[prop];
  5451. }
  5452. }
  5453. };
  5454. _proto._spacesFor = function _spacesFor(name) {
  5455. var attrSpaces = {
  5456. before: '',
  5457. after: ''
  5458. };
  5459. var spaces = this.spaces[name] || {};
  5460. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  5461. return Object.assign(attrSpaces, spaces, rawSpaces);
  5462. };
  5463. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  5464. if (spaceName === void 0) {
  5465. spaceName = name;
  5466. }
  5467. if (concat === void 0) {
  5468. concat = defaultAttrConcat;
  5469. }
  5470. var attrSpaces = this._spacesFor(spaceName);
  5471. return concat(this.stringifyProperty(name), attrSpaces);
  5472. }
  5473. /**
  5474. * returns the offset of the attribute part specified relative to the
  5475. * start of the node of the output string.
  5476. *
  5477. * * "ns" - alias for "namespace"
  5478. * * "namespace" - the namespace if it exists.
  5479. * * "attribute" - the attribute name
  5480. * * "attributeNS" - the start of the attribute or its namespace
  5481. * * "operator" - the match operator of the attribute
  5482. * * "value" - The value (string or identifier)
  5483. * * "insensitive" - the case insensitivity flag;
  5484. * @param part One of the possible values inside an attribute.
  5485. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  5486. */;
  5487. _proto.offsetOf = function offsetOf(name) {
  5488. var count = 1;
  5489. var attributeSpaces = this._spacesFor("attribute");
  5490. count += attributeSpaces.before.length;
  5491. if (name === "namespace" || name === "ns") {
  5492. return this.namespace ? count : -1;
  5493. }
  5494. if (name === "attributeNS") {
  5495. return count;
  5496. }
  5497. count += this.namespaceString.length;
  5498. if (this.namespace) {
  5499. count += 1;
  5500. }
  5501. if (name === "attribute") {
  5502. return count;
  5503. }
  5504. count += this.stringifyProperty("attribute").length;
  5505. count += attributeSpaces.after.length;
  5506. var operatorSpaces = this._spacesFor("operator");
  5507. count += operatorSpaces.before.length;
  5508. var operator = this.stringifyProperty("operator");
  5509. if (name === "operator") {
  5510. return operator ? count : -1;
  5511. }
  5512. count += operator.length;
  5513. count += operatorSpaces.after.length;
  5514. var valueSpaces = this._spacesFor("value");
  5515. count += valueSpaces.before.length;
  5516. var value = this.stringifyProperty("value");
  5517. if (name === "value") {
  5518. return value ? count : -1;
  5519. }
  5520. count += value.length;
  5521. count += valueSpaces.after.length;
  5522. var insensitiveSpaces = this._spacesFor("insensitive");
  5523. count += insensitiveSpaces.before.length;
  5524. if (name === "insensitive") {
  5525. return this.insensitive ? count : -1;
  5526. }
  5527. return -1;
  5528. };
  5529. _proto.toString = function toString() {
  5530. var _this2 = this;
  5531. var selector = [this.rawSpaceBefore, '['];
  5532. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  5533. if (this.operator && (this.value || this.value === '')) {
  5534. selector.push(this._stringFor('operator'));
  5535. selector.push(this._stringFor('value'));
  5536. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  5537. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  5538. attrSpaces.before = " ";
  5539. }
  5540. return defaultAttrConcat(attrValue, attrSpaces);
  5541. }));
  5542. }
  5543. selector.push(']');
  5544. selector.push(this.rawSpaceAfter);
  5545. return selector.join('');
  5546. };
  5547. _createClass(Attribute, [{
  5548. key: "quoted",
  5549. get: function get() {
  5550. var qm = this.quoteMark;
  5551. return qm === "'" || qm === '"';
  5552. },
  5553. set: function set(value) {
  5554. warnOfDeprecatedQuotedAssignment();
  5555. }
  5556. /**
  5557. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  5558. * returns `null` if the value is not quoted.
  5559. * returns `undefined` if the quotation state is unknown (this can happen when
  5560. * the attribute is constructed without specifying a quote mark.)
  5561. */
  5562. }, {
  5563. key: "quoteMark",
  5564. get: function get() {
  5565. return this._quoteMark;
  5566. }
  5567. /**
  5568. * Set the quote mark to be used by this attribute's value.
  5569. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  5570. * value is updated accordingly.
  5571. *
  5572. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  5573. */,
  5574. set: function set(quoteMark) {
  5575. if (!this._constructed) {
  5576. this._quoteMark = quoteMark;
  5577. return;
  5578. }
  5579. if (this._quoteMark !== quoteMark) {
  5580. this._quoteMark = quoteMark;
  5581. this._syncRawValue();
  5582. }
  5583. }
  5584. }, {
  5585. key: "qualifiedAttribute",
  5586. get: function get() {
  5587. return this.qualifiedName(this.raws.attribute || this.attribute);
  5588. }
  5589. }, {
  5590. key: "insensitiveFlag",
  5591. get: function get() {
  5592. return this.insensitive ? 'i' : '';
  5593. }
  5594. }, {
  5595. key: "value",
  5596. get: function get() {
  5597. return this._value;
  5598. },
  5599. set:
  5600. /**
  5601. * Before 3.0, the value had to be set to an escaped value including any wrapped
  5602. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  5603. * is unescaped during parsing and any quote marks are removed.
  5604. *
  5605. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  5606. * a deprecation warning is raised when the new value contains any characters that would
  5607. * require escaping (including if it contains wrapped quotes).
  5608. *
  5609. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  5610. * how the new value is quoted.
  5611. */
  5612. function set(v) {
  5613. if (this._constructed) {
  5614. var _unescapeValue2 = unescapeValue(v),
  5615. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  5616. unescaped = _unescapeValue2.unescaped,
  5617. quoteMark = _unescapeValue2.quoteMark;
  5618. if (deprecatedUsage) {
  5619. warnOfDeprecatedValueAssignment();
  5620. }
  5621. if (unescaped === this._value && quoteMark === this._quoteMark) {
  5622. return;
  5623. }
  5624. this._value = unescaped;
  5625. this._quoteMark = quoteMark;
  5626. this._syncRawValue();
  5627. } else {
  5628. this._value = v;
  5629. }
  5630. }
  5631. }, {
  5632. key: "insensitive",
  5633. get: function get() {
  5634. return this._insensitive;
  5635. }
  5636. /**
  5637. * Set the case insensitive flag.
  5638. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  5639. * of the attribute is updated accordingly.
  5640. *
  5641. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  5642. */,
  5643. set: function set(insensitive) {
  5644. if (!insensitive) {
  5645. this._insensitive = false;
  5646. // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  5647. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  5648. if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
  5649. this.raws.insensitiveFlag = undefined;
  5650. }
  5651. }
  5652. this._insensitive = insensitive;
  5653. }
  5654. }, {
  5655. key: "attribute",
  5656. get: function get() {
  5657. return this._attribute;
  5658. },
  5659. set: function set(name) {
  5660. this._handleEscapes("attribute", name);
  5661. this._attribute = name;
  5662. }
  5663. }]);
  5664. return Attribute;
  5665. }(_namespace["default"]);
  5666. exports["default"] = Attribute;
  5667. Attribute.NO_QUOTE = null;
  5668. Attribute.SINGLE_QUOTE = "'";
  5669. Attribute.DOUBLE_QUOTE = '"';
  5670. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  5671. "'": {
  5672. quotes: 'single',
  5673. wrap: true
  5674. },
  5675. '"': {
  5676. quotes: 'double',
  5677. wrap: true
  5678. }
  5679. }, _CSSESC_QUOTE_OPTIONS[null] = {
  5680. isIdentifier: true
  5681. }, _CSSESC_QUOTE_OPTIONS);
  5682. function defaultAttrConcat(attrValue, attrSpaces) {
  5683. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  5684. }
  5685. } (attribute$1));
  5686. return attribute$1;
  5687. }
  5688. var universal$1 = {exports: {}};
  5689. var hasRequiredUniversal$1;
  5690. function requireUniversal$1 () {
  5691. if (hasRequiredUniversal$1) return universal$1.exports;
  5692. hasRequiredUniversal$1 = 1;
  5693. (function (module, exports) {
  5694. exports.__esModule = true;
  5695. exports["default"] = void 0;
  5696. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace$1());
  5697. var _types = /*@__PURE__*/ requireTypes$1();
  5698. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5699. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5700. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5701. var Universal = /*#__PURE__*/function (_Namespace) {
  5702. _inheritsLoose(Universal, _Namespace);
  5703. function Universal(opts) {
  5704. var _this;
  5705. _this = _Namespace.call(this, opts) || this;
  5706. _this.type = _types.UNIVERSAL;
  5707. _this.value = '*';
  5708. return _this;
  5709. }
  5710. return Universal;
  5711. }(_namespace["default"]);
  5712. exports["default"] = Universal;
  5713. module.exports = exports.default;
  5714. } (universal$1, universal$1.exports));
  5715. return universal$1.exports;
  5716. }
  5717. var combinator$1 = {exports: {}};
  5718. var hasRequiredCombinator$1;
  5719. function requireCombinator$1 () {
  5720. if (hasRequiredCombinator$1) return combinator$1.exports;
  5721. hasRequiredCombinator$1 = 1;
  5722. (function (module, exports) {
  5723. exports.__esModule = true;
  5724. exports["default"] = void 0;
  5725. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5726. var _types = /*@__PURE__*/ requireTypes$1();
  5727. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5728. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5729. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5730. var Combinator = /*#__PURE__*/function (_Node) {
  5731. _inheritsLoose(Combinator, _Node);
  5732. function Combinator(opts) {
  5733. var _this;
  5734. _this = _Node.call(this, opts) || this;
  5735. _this.type = _types.COMBINATOR;
  5736. return _this;
  5737. }
  5738. return Combinator;
  5739. }(_node["default"]);
  5740. exports["default"] = Combinator;
  5741. module.exports = exports.default;
  5742. } (combinator$1, combinator$1.exports));
  5743. return combinator$1.exports;
  5744. }
  5745. var nesting$1 = {exports: {}};
  5746. var hasRequiredNesting$1;
  5747. function requireNesting$1 () {
  5748. if (hasRequiredNesting$1) return nesting$1.exports;
  5749. hasRequiredNesting$1 = 1;
  5750. (function (module, exports) {
  5751. exports.__esModule = true;
  5752. exports["default"] = void 0;
  5753. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode$2());
  5754. var _types = /*@__PURE__*/ requireTypes$1();
  5755. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  5756. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  5757. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  5758. var Nesting = /*#__PURE__*/function (_Node) {
  5759. _inheritsLoose(Nesting, _Node);
  5760. function Nesting(opts) {
  5761. var _this;
  5762. _this = _Node.call(this, opts) || this;
  5763. _this.type = _types.NESTING;
  5764. _this.value = '&';
  5765. return _this;
  5766. }
  5767. return Nesting;
  5768. }(_node["default"]);
  5769. exports["default"] = Nesting;
  5770. module.exports = exports.default;
  5771. } (nesting$1, nesting$1.exports));
  5772. return nesting$1.exports;
  5773. }
  5774. var sortAscending$1 = {exports: {}};
  5775. var hasRequiredSortAscending$1;
  5776. function requireSortAscending$1 () {
  5777. if (hasRequiredSortAscending$1) return sortAscending$1.exports;
  5778. hasRequiredSortAscending$1 = 1;
  5779. (function (module, exports) {
  5780. exports.__esModule = true;
  5781. exports["default"] = sortAscending;
  5782. function sortAscending(list) {
  5783. return list.sort(function (a, b) {
  5784. return a - b;
  5785. });
  5786. }
  5787. module.exports = exports.default;
  5788. } (sortAscending$1, sortAscending$1.exports));
  5789. return sortAscending$1.exports;
  5790. }
  5791. var tokenize$1 = {};
  5792. var tokenTypes$1 = {};
  5793. var hasRequiredTokenTypes$1;
  5794. function requireTokenTypes$1 () {
  5795. if (hasRequiredTokenTypes$1) return tokenTypes$1;
  5796. hasRequiredTokenTypes$1 = 1;
  5797. tokenTypes$1.__esModule = true;
  5798. 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;
  5799. var ampersand = 38; // `&`.charCodeAt(0);
  5800. tokenTypes$1.ampersand = ampersand;
  5801. var asterisk = 42; // `*`.charCodeAt(0);
  5802. tokenTypes$1.asterisk = asterisk;
  5803. var at = 64; // `@`.charCodeAt(0);
  5804. tokenTypes$1.at = at;
  5805. var comma = 44; // `,`.charCodeAt(0);
  5806. tokenTypes$1.comma = comma;
  5807. var colon = 58; // `:`.charCodeAt(0);
  5808. tokenTypes$1.colon = colon;
  5809. var semicolon = 59; // `;`.charCodeAt(0);
  5810. tokenTypes$1.semicolon = semicolon;
  5811. var openParenthesis = 40; // `(`.charCodeAt(0);
  5812. tokenTypes$1.openParenthesis = openParenthesis;
  5813. var closeParenthesis = 41; // `)`.charCodeAt(0);
  5814. tokenTypes$1.closeParenthesis = closeParenthesis;
  5815. var openSquare = 91; // `[`.charCodeAt(0);
  5816. tokenTypes$1.openSquare = openSquare;
  5817. var closeSquare = 93; // `]`.charCodeAt(0);
  5818. tokenTypes$1.closeSquare = closeSquare;
  5819. var dollar = 36; // `$`.charCodeAt(0);
  5820. tokenTypes$1.dollar = dollar;
  5821. var tilde = 126; // `~`.charCodeAt(0);
  5822. tokenTypes$1.tilde = tilde;
  5823. var caret = 94; // `^`.charCodeAt(0);
  5824. tokenTypes$1.caret = caret;
  5825. var plus = 43; // `+`.charCodeAt(0);
  5826. tokenTypes$1.plus = plus;
  5827. var equals = 61; // `=`.charCodeAt(0);
  5828. tokenTypes$1.equals = equals;
  5829. var pipe = 124; // `|`.charCodeAt(0);
  5830. tokenTypes$1.pipe = pipe;
  5831. var greaterThan = 62; // `>`.charCodeAt(0);
  5832. tokenTypes$1.greaterThan = greaterThan;
  5833. var space = 32; // ` `.charCodeAt(0);
  5834. tokenTypes$1.space = space;
  5835. var singleQuote = 39; // `'`.charCodeAt(0);
  5836. tokenTypes$1.singleQuote = singleQuote;
  5837. var doubleQuote = 34; // `"`.charCodeAt(0);
  5838. tokenTypes$1.doubleQuote = doubleQuote;
  5839. var slash = 47; // `/`.charCodeAt(0);
  5840. tokenTypes$1.slash = slash;
  5841. var bang = 33; // `!`.charCodeAt(0);
  5842. tokenTypes$1.bang = bang;
  5843. var backslash = 92; // '\\'.charCodeAt(0);
  5844. tokenTypes$1.backslash = backslash;
  5845. var cr = 13; // '\r'.charCodeAt(0);
  5846. tokenTypes$1.cr = cr;
  5847. var feed = 12; // '\f'.charCodeAt(0);
  5848. tokenTypes$1.feed = feed;
  5849. var newline = 10; // '\n'.charCodeAt(0);
  5850. tokenTypes$1.newline = newline;
  5851. var tab = 9; // '\t'.charCodeAt(0);
  5852. // Expose aliases primarily for readability.
  5853. tokenTypes$1.tab = tab;
  5854. var str = singleQuote;
  5855. // No good single character representation!
  5856. tokenTypes$1.str = str;
  5857. var comment = -1;
  5858. tokenTypes$1.comment = comment;
  5859. var word = -2;
  5860. tokenTypes$1.word = word;
  5861. var combinator = -3;
  5862. tokenTypes$1.combinator = combinator;
  5863. return tokenTypes$1;
  5864. }
  5865. var hasRequiredTokenize$1;
  5866. function requireTokenize$1 () {
  5867. if (hasRequiredTokenize$1) return tokenize$1;
  5868. hasRequiredTokenize$1 = 1;
  5869. (function (exports) {
  5870. exports.__esModule = true;
  5871. exports.FIELDS = void 0;
  5872. exports["default"] = tokenize;
  5873. var t = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes$1());
  5874. var _unescapable, _wordDelimiters;
  5875. 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); }
  5876. 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; }
  5877. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  5878. 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);
  5879. var hex = {};
  5880. var hexChars = "0123456789abcdefABCDEF";
  5881. for (var i = 0; i < hexChars.length; i++) {
  5882. hex[hexChars.charCodeAt(i)] = true;
  5883. }
  5884. /**
  5885. * Returns the last index of the bar css word
  5886. * @param {string} css The string in which the word begins
  5887. * @param {number} start The index into the string where word's first letter occurs
  5888. */
  5889. function consumeWord(css, start) {
  5890. var next = start;
  5891. var code;
  5892. do {
  5893. code = css.charCodeAt(next);
  5894. if (wordDelimiters[code]) {
  5895. return next - 1;
  5896. } else if (code === t.backslash) {
  5897. next = consumeEscape(css, next) + 1;
  5898. } else {
  5899. // All other characters are part of the word
  5900. next++;
  5901. }
  5902. } while (next < css.length);
  5903. return next - 1;
  5904. }
  5905. /**
  5906. * Returns the last index of the escape sequence
  5907. * @param {string} css The string in which the sequence begins
  5908. * @param {number} start The index into the string where escape character (`\`) occurs.
  5909. */
  5910. function consumeEscape(css, start) {
  5911. var next = start;
  5912. var code = css.charCodeAt(next + 1);
  5913. if (unescapable[code]) ; else if (hex[code]) {
  5914. var hexDigits = 0;
  5915. // consume up to 6 hex chars
  5916. do {
  5917. next++;
  5918. hexDigits++;
  5919. code = css.charCodeAt(next + 1);
  5920. } while (hex[code] && hexDigits < 6);
  5921. // if fewer than 6 hex chars, a trailing space ends the escape
  5922. if (hexDigits < 6 && code === t.space) {
  5923. next++;
  5924. }
  5925. } else {
  5926. // the next char is part of the current word
  5927. next++;
  5928. }
  5929. return next;
  5930. }
  5931. var FIELDS = {
  5932. TYPE: 0,
  5933. START_LINE: 1,
  5934. START_COL: 2,
  5935. END_LINE: 3,
  5936. END_COL: 4,
  5937. START_POS: 5,
  5938. END_POS: 6
  5939. };
  5940. exports.FIELDS = FIELDS;
  5941. function tokenize(input) {
  5942. var tokens = [];
  5943. var css = input.css.valueOf();
  5944. var _css = css,
  5945. length = _css.length;
  5946. var offset = -1;
  5947. var line = 1;
  5948. var start = 0;
  5949. var end = 0;
  5950. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  5951. function unclosed(what, fix) {
  5952. if (input.safe) {
  5953. // fyi: this is never set to true.
  5954. css += fix;
  5955. next = css.length - 1;
  5956. } else {
  5957. throw input.error('Unclosed ' + what, line, start - offset, start);
  5958. }
  5959. }
  5960. while (start < length) {
  5961. code = css.charCodeAt(start);
  5962. if (code === t.newline) {
  5963. offset = start;
  5964. line += 1;
  5965. }
  5966. switch (code) {
  5967. case t.space:
  5968. case t.tab:
  5969. case t.newline:
  5970. case t.cr:
  5971. case t.feed:
  5972. next = start;
  5973. do {
  5974. next += 1;
  5975. code = css.charCodeAt(next);
  5976. if (code === t.newline) {
  5977. offset = next;
  5978. line += 1;
  5979. }
  5980. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  5981. tokenType = t.space;
  5982. endLine = line;
  5983. endColumn = next - offset - 1;
  5984. end = next;
  5985. break;
  5986. case t.plus:
  5987. case t.greaterThan:
  5988. case t.tilde:
  5989. case t.pipe:
  5990. next = start;
  5991. do {
  5992. next += 1;
  5993. code = css.charCodeAt(next);
  5994. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  5995. tokenType = t.combinator;
  5996. endLine = line;
  5997. endColumn = start - offset;
  5998. end = next;
  5999. break;
  6000. // Consume these characters as single tokens.
  6001. case t.asterisk:
  6002. case t.ampersand:
  6003. case t.bang:
  6004. case t.comma:
  6005. case t.equals:
  6006. case t.dollar:
  6007. case t.caret:
  6008. case t.openSquare:
  6009. case t.closeSquare:
  6010. case t.colon:
  6011. case t.semicolon:
  6012. case t.openParenthesis:
  6013. case t.closeParenthesis:
  6014. next = start;
  6015. tokenType = code;
  6016. endLine = line;
  6017. endColumn = start - offset;
  6018. end = next + 1;
  6019. break;
  6020. case t.singleQuote:
  6021. case t.doubleQuote:
  6022. quote = code === t.singleQuote ? "'" : '"';
  6023. next = start;
  6024. do {
  6025. escaped = false;
  6026. next = css.indexOf(quote, next + 1);
  6027. if (next === -1) {
  6028. unclosed('quote', quote);
  6029. }
  6030. escapePos = next;
  6031. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  6032. escapePos -= 1;
  6033. escaped = !escaped;
  6034. }
  6035. } while (escaped);
  6036. tokenType = t.str;
  6037. endLine = line;
  6038. endColumn = start - offset;
  6039. end = next + 1;
  6040. break;
  6041. default:
  6042. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  6043. next = css.indexOf('*/', start + 2) + 1;
  6044. if (next === 0) {
  6045. unclosed('comment', '*/');
  6046. }
  6047. content = css.slice(start, next + 1);
  6048. lines = content.split('\n');
  6049. last = lines.length - 1;
  6050. if (last > 0) {
  6051. nextLine = line + last;
  6052. nextOffset = next - lines[last].length;
  6053. } else {
  6054. nextLine = line;
  6055. nextOffset = offset;
  6056. }
  6057. tokenType = t.comment;
  6058. line = nextLine;
  6059. endLine = nextLine;
  6060. endColumn = next - nextOffset;
  6061. } else if (code === t.slash) {
  6062. next = start;
  6063. tokenType = code;
  6064. endLine = line;
  6065. endColumn = start - offset;
  6066. end = next + 1;
  6067. } else {
  6068. next = consumeWord(css, start);
  6069. tokenType = t.word;
  6070. endLine = line;
  6071. endColumn = next - offset;
  6072. }
  6073. end = next + 1;
  6074. break;
  6075. }
  6076. // Ensure that the token structure remains consistent
  6077. tokens.push([tokenType,
  6078. // [0] Token type
  6079. line,
  6080. // [1] Starting line
  6081. start - offset,
  6082. // [2] Starting column
  6083. endLine,
  6084. // [3] Ending line
  6085. endColumn,
  6086. // [4] Ending column
  6087. start,
  6088. // [5] Start position / Source index
  6089. end // [6] End position
  6090. ]);
  6091. // Reset offset for the next token
  6092. if (nextOffset) {
  6093. offset = nextOffset;
  6094. nextOffset = null;
  6095. }
  6096. start = end;
  6097. }
  6098. return tokens;
  6099. }
  6100. } (tokenize$1));
  6101. return tokenize$1;
  6102. }
  6103. var hasRequiredParser$2;
  6104. function requireParser$2 () {
  6105. if (hasRequiredParser$2) return parser$1.exports;
  6106. hasRequiredParser$2 = 1;
  6107. (function (module, exports) {
  6108. exports.__esModule = true;
  6109. exports["default"] = void 0;
  6110. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot$1());
  6111. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector$1());
  6112. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName$1());
  6113. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment$1());
  6114. var _id = _interopRequireDefault(/*@__PURE__*/ requireId$1());
  6115. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag$1());
  6116. var _string = _interopRequireDefault(/*@__PURE__*/ requireString$1());
  6117. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo$1());
  6118. var _attribute = _interopRequireWildcard(/*@__PURE__*/ requireAttribute$1());
  6119. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal$1());
  6120. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator$1());
  6121. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting$1());
  6122. var _sortAscending = _interopRequireDefault(/*@__PURE__*/ requireSortAscending$1());
  6123. var _tokenize = _interopRequireWildcard(/*@__PURE__*/ requireTokenize$1());
  6124. var tokens = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes$1());
  6125. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes$1());
  6126. var _util = /*@__PURE__*/ requireUtil$2();
  6127. var _WHITESPACE_TOKENS, _Object$assign;
  6128. 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); }
  6129. 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; }
  6130. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  6131. 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); } }
  6132. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  6133. 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);
  6134. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  6135. function tokenStart(token) {
  6136. return {
  6137. line: token[_tokenize.FIELDS.START_LINE],
  6138. column: token[_tokenize.FIELDS.START_COL]
  6139. };
  6140. }
  6141. function tokenEnd(token) {
  6142. return {
  6143. line: token[_tokenize.FIELDS.END_LINE],
  6144. column: token[_tokenize.FIELDS.END_COL]
  6145. };
  6146. }
  6147. function getSource(startLine, startColumn, endLine, endColumn) {
  6148. return {
  6149. start: {
  6150. line: startLine,
  6151. column: startColumn
  6152. },
  6153. end: {
  6154. line: endLine,
  6155. column: endColumn
  6156. }
  6157. };
  6158. }
  6159. function getTokenSource(token) {
  6160. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  6161. }
  6162. function getTokenSourceSpan(startToken, endToken) {
  6163. if (!startToken) {
  6164. return undefined;
  6165. }
  6166. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  6167. }
  6168. function unescapeProp(node, prop) {
  6169. var value = node[prop];
  6170. if (typeof value !== "string") {
  6171. return;
  6172. }
  6173. if (value.indexOf("\\") !== -1) {
  6174. (0, _util.ensureObject)(node, 'raws');
  6175. node[prop] = (0, _util.unesc)(value);
  6176. if (node.raws[prop] === undefined) {
  6177. node.raws[prop] = value;
  6178. }
  6179. }
  6180. return node;
  6181. }
  6182. function indexesOf(array, item) {
  6183. var i = -1;
  6184. var indexes = [];
  6185. while ((i = array.indexOf(item, i + 1)) !== -1) {
  6186. indexes.push(i);
  6187. }
  6188. return indexes;
  6189. }
  6190. function uniqs() {
  6191. var list = Array.prototype.concat.apply([], arguments);
  6192. return list.filter(function (item, i) {
  6193. return i === list.indexOf(item);
  6194. });
  6195. }
  6196. var Parser = /*#__PURE__*/function () {
  6197. function Parser(rule, options) {
  6198. if (options === void 0) {
  6199. options = {};
  6200. }
  6201. this.rule = rule;
  6202. this.options = Object.assign({
  6203. lossy: false,
  6204. safe: false
  6205. }, options);
  6206. this.position = 0;
  6207. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  6208. this.tokens = (0, _tokenize["default"])({
  6209. css: this.css,
  6210. error: this._errorGenerator(),
  6211. safe: this.options.safe
  6212. });
  6213. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  6214. this.root = new _root["default"]({
  6215. source: rootSource
  6216. });
  6217. this.root.errorGenerator = this._errorGenerator();
  6218. var selector = new _selector["default"]({
  6219. source: {
  6220. start: {
  6221. line: 1,
  6222. column: 1
  6223. }
  6224. },
  6225. sourceIndex: 0
  6226. });
  6227. this.root.append(selector);
  6228. this.current = selector;
  6229. this.loop();
  6230. }
  6231. var _proto = Parser.prototype;
  6232. _proto._errorGenerator = function _errorGenerator() {
  6233. var _this = this;
  6234. return function (message, errorOptions) {
  6235. if (typeof _this.rule === 'string') {
  6236. return new Error(message);
  6237. }
  6238. return _this.rule.error(message, errorOptions);
  6239. };
  6240. };
  6241. _proto.attribute = function attribute() {
  6242. var attr = [];
  6243. var startingToken = this.currToken;
  6244. this.position++;
  6245. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  6246. attr.push(this.currToken);
  6247. this.position++;
  6248. }
  6249. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  6250. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  6251. }
  6252. var len = attr.length;
  6253. var node = {
  6254. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  6255. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  6256. };
  6257. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  6258. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  6259. }
  6260. var pos = 0;
  6261. var spaceBefore = '';
  6262. var commentBefore = '';
  6263. var lastAdded = null;
  6264. var spaceAfterMeaningfulToken = false;
  6265. while (pos < len) {
  6266. var token = attr[pos];
  6267. var content = this.content(token);
  6268. var next = attr[pos + 1];
  6269. switch (token[_tokenize.FIELDS.TYPE]) {
  6270. case tokens.space:
  6271. // if (
  6272. // len === 1 ||
  6273. // pos === 0 && this.content(next) === '|'
  6274. // ) {
  6275. // return this.expected('attribute', token[TOKEN.START_POS], content);
  6276. // }
  6277. spaceAfterMeaningfulToken = true;
  6278. if (this.options.lossy) {
  6279. break;
  6280. }
  6281. if (lastAdded) {
  6282. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  6283. var prevContent = node.spaces[lastAdded].after || '';
  6284. node.spaces[lastAdded].after = prevContent + content;
  6285. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  6286. if (existingComment) {
  6287. node.raws.spaces[lastAdded].after = existingComment + content;
  6288. }
  6289. } else {
  6290. spaceBefore = spaceBefore + content;
  6291. commentBefore = commentBefore + content;
  6292. }
  6293. break;
  6294. case tokens.asterisk:
  6295. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6296. node.operator = content;
  6297. lastAdded = 'operator';
  6298. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  6299. if (spaceBefore) {
  6300. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  6301. node.spaces.attribute.before = spaceBefore;
  6302. spaceBefore = '';
  6303. }
  6304. if (commentBefore) {
  6305. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  6306. node.raws.spaces.attribute.before = spaceBefore;
  6307. commentBefore = '';
  6308. }
  6309. node.namespace = (node.namespace || "") + content;
  6310. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  6311. if (rawValue) {
  6312. node.raws.namespace += content;
  6313. }
  6314. lastAdded = 'namespace';
  6315. }
  6316. spaceAfterMeaningfulToken = false;
  6317. break;
  6318. case tokens.dollar:
  6319. if (lastAdded === "value") {
  6320. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  6321. node.value += "$";
  6322. if (oldRawValue) {
  6323. node.raws.value = oldRawValue + "$";
  6324. }
  6325. break;
  6326. }
  6327. // Falls through
  6328. case tokens.caret:
  6329. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6330. node.operator = content;
  6331. lastAdded = 'operator';
  6332. }
  6333. spaceAfterMeaningfulToken = false;
  6334. break;
  6335. case tokens.combinator:
  6336. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6337. node.operator = content;
  6338. lastAdded = 'operator';
  6339. }
  6340. if (content !== '|') {
  6341. spaceAfterMeaningfulToken = false;
  6342. break;
  6343. }
  6344. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  6345. node.operator = content;
  6346. lastAdded = 'operator';
  6347. } else if (!node.namespace && !node.attribute) {
  6348. node.namespace = true;
  6349. }
  6350. spaceAfterMeaningfulToken = false;
  6351. break;
  6352. case tokens.word:
  6353. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
  6354. // this look-ahead probably fails with comment nodes involved.
  6355. !node.operator && !node.namespace) {
  6356. node.namespace = content;
  6357. lastAdded = 'namespace';
  6358. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  6359. if (spaceBefore) {
  6360. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  6361. node.spaces.attribute.before = spaceBefore;
  6362. spaceBefore = '';
  6363. }
  6364. if (commentBefore) {
  6365. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  6366. node.raws.spaces.attribute.before = commentBefore;
  6367. commentBefore = '';
  6368. }
  6369. node.attribute = (node.attribute || "") + content;
  6370. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  6371. if (_rawValue) {
  6372. node.raws.attribute += content;
  6373. }
  6374. lastAdded = 'attribute';
  6375. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  6376. var _unescaped = (0, _util.unesc)(content);
  6377. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  6378. var oldValue = node.value || '';
  6379. node.value = oldValue + _unescaped;
  6380. node.quoteMark = null;
  6381. if (_unescaped !== content || _oldRawValue) {
  6382. (0, _util.ensureObject)(node, 'raws');
  6383. node.raws.value = (_oldRawValue || oldValue) + content;
  6384. }
  6385. lastAdded = 'value';
  6386. } else {
  6387. var insensitive = content === 'i' || content === "I";
  6388. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  6389. node.insensitive = insensitive;
  6390. if (!insensitive || content === "I") {
  6391. (0, _util.ensureObject)(node, 'raws');
  6392. node.raws.insensitiveFlag = content;
  6393. }
  6394. lastAdded = 'insensitive';
  6395. if (spaceBefore) {
  6396. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  6397. node.spaces.insensitive.before = spaceBefore;
  6398. spaceBefore = '';
  6399. }
  6400. if (commentBefore) {
  6401. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  6402. node.raws.spaces.insensitive.before = commentBefore;
  6403. commentBefore = '';
  6404. }
  6405. } else if (node.value || node.value === '') {
  6406. lastAdded = 'value';
  6407. node.value += content;
  6408. if (node.raws.value) {
  6409. node.raws.value += content;
  6410. }
  6411. }
  6412. }
  6413. spaceAfterMeaningfulToken = false;
  6414. break;
  6415. case tokens.str:
  6416. if (!node.attribute || !node.operator) {
  6417. return this.error("Expected an attribute followed by an operator preceding the string.", {
  6418. index: token[_tokenize.FIELDS.START_POS]
  6419. });
  6420. }
  6421. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  6422. unescaped = _unescapeValue.unescaped,
  6423. quoteMark = _unescapeValue.quoteMark;
  6424. node.value = unescaped;
  6425. node.quoteMark = quoteMark;
  6426. lastAdded = 'value';
  6427. (0, _util.ensureObject)(node, 'raws');
  6428. node.raws.value = content;
  6429. spaceAfterMeaningfulToken = false;
  6430. break;
  6431. case tokens.equals:
  6432. if (!node.attribute) {
  6433. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  6434. }
  6435. if (node.value) {
  6436. return this.error('Unexpected "=" found; an operator was already defined.', {
  6437. index: token[_tokenize.FIELDS.START_POS]
  6438. });
  6439. }
  6440. node.operator = node.operator ? node.operator + content : content;
  6441. lastAdded = 'operator';
  6442. spaceAfterMeaningfulToken = false;
  6443. break;
  6444. case tokens.comment:
  6445. if (lastAdded) {
  6446. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  6447. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  6448. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  6449. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  6450. node.raws.spaces[lastAdded].after = rawLastComment + content;
  6451. } else {
  6452. var lastValue = node[lastAdded] || '';
  6453. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  6454. (0, _util.ensureObject)(node, 'raws');
  6455. node.raws[lastAdded] = rawLastValue + content;
  6456. }
  6457. } else {
  6458. commentBefore = commentBefore + content;
  6459. }
  6460. break;
  6461. default:
  6462. return this.error("Unexpected \"" + content + "\" found.", {
  6463. index: token[_tokenize.FIELDS.START_POS]
  6464. });
  6465. }
  6466. pos++;
  6467. }
  6468. unescapeProp(node, "attribute");
  6469. unescapeProp(node, "namespace");
  6470. this.newNode(new _attribute["default"](node));
  6471. this.position++;
  6472. }
  6473. /**
  6474. * return a node containing meaningless garbage up to (but not including) the specified token position.
  6475. * if the token position is negative, all remaining tokens are consumed.
  6476. *
  6477. * This returns an array containing a single string node if all whitespace,
  6478. * otherwise an array of comment nodes with space before and after.
  6479. *
  6480. * These tokens are not added to the current selector, the caller can add them or use them to amend
  6481. * a previous node's space metadata.
  6482. *
  6483. * In lossy mode, this returns only comments.
  6484. */;
  6485. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  6486. if (stopPosition < 0) {
  6487. stopPosition = this.tokens.length;
  6488. }
  6489. var startPosition = this.position;
  6490. var nodes = [];
  6491. var space = "";
  6492. var lastComment = undefined;
  6493. do {
  6494. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  6495. if (!this.options.lossy) {
  6496. space += this.content();
  6497. }
  6498. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  6499. var spaces = {};
  6500. if (space) {
  6501. spaces.before = space;
  6502. space = "";
  6503. }
  6504. lastComment = new _comment["default"]({
  6505. value: this.content(),
  6506. source: getTokenSource(this.currToken),
  6507. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  6508. spaces: spaces
  6509. });
  6510. nodes.push(lastComment);
  6511. }
  6512. } while (++this.position < stopPosition);
  6513. if (space) {
  6514. if (lastComment) {
  6515. lastComment.spaces.after = space;
  6516. } else if (!this.options.lossy) {
  6517. var firstToken = this.tokens[startPosition];
  6518. var lastToken = this.tokens[this.position - 1];
  6519. nodes.push(new _string["default"]({
  6520. value: '',
  6521. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  6522. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  6523. spaces: {
  6524. before: space,
  6525. after: ''
  6526. }
  6527. }));
  6528. }
  6529. }
  6530. return nodes;
  6531. }
  6532. /**
  6533. *
  6534. * @param {*} nodes
  6535. */;
  6536. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  6537. var _this2 = this;
  6538. if (requiredSpace === void 0) {
  6539. requiredSpace = false;
  6540. }
  6541. var space = "";
  6542. var rawSpace = "";
  6543. nodes.forEach(function (n) {
  6544. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  6545. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  6546. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  6547. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  6548. });
  6549. if (rawSpace === space) {
  6550. rawSpace = undefined;
  6551. }
  6552. var result = {
  6553. space: space,
  6554. rawSpace: rawSpace
  6555. };
  6556. return result;
  6557. };
  6558. _proto.isNamedCombinator = function isNamedCombinator(position) {
  6559. if (position === void 0) {
  6560. position = this.position;
  6561. }
  6562. 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;
  6563. };
  6564. _proto.namedCombinator = function namedCombinator() {
  6565. if (this.isNamedCombinator()) {
  6566. var nameRaw = this.content(this.tokens[this.position + 1]);
  6567. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  6568. var raws = {};
  6569. if (name !== nameRaw) {
  6570. raws.value = "/" + nameRaw + "/";
  6571. }
  6572. var node = new _combinator["default"]({
  6573. value: "/" + name + "/",
  6574. 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]),
  6575. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  6576. raws: raws
  6577. });
  6578. this.position = this.position + 3;
  6579. return node;
  6580. } else {
  6581. this.unexpected();
  6582. }
  6583. };
  6584. _proto.combinator = function combinator() {
  6585. var _this3 = this;
  6586. if (this.content() === '|') {
  6587. return this.namespace();
  6588. }
  6589. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  6590. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  6591. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6592. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  6593. if (nodes.length > 0) {
  6594. var last = this.current.last;
  6595. if (last) {
  6596. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  6597. space = _this$convertWhitespa.space,
  6598. rawSpace = _this$convertWhitespa.rawSpace;
  6599. if (rawSpace !== undefined) {
  6600. last.rawSpaceAfter += rawSpace;
  6601. }
  6602. last.spaces.after += space;
  6603. } else {
  6604. nodes.forEach(function (n) {
  6605. return _this3.newNode(n);
  6606. });
  6607. }
  6608. }
  6609. return;
  6610. }
  6611. var firstToken = this.currToken;
  6612. var spaceOrDescendantSelectorNodes = undefined;
  6613. if (nextSigTokenPos > this.position) {
  6614. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  6615. }
  6616. var node;
  6617. if (this.isNamedCombinator()) {
  6618. node = this.namedCombinator();
  6619. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  6620. node = new _combinator["default"]({
  6621. value: this.content(),
  6622. source: getTokenSource(this.currToken),
  6623. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  6624. });
  6625. this.position++;
  6626. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  6627. this.unexpected();
  6628. }
  6629. if (node) {
  6630. if (spaceOrDescendantSelectorNodes) {
  6631. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  6632. _space = _this$convertWhitespa2.space,
  6633. _rawSpace = _this$convertWhitespa2.rawSpace;
  6634. node.spaces.before = _space;
  6635. node.rawSpaceBefore = _rawSpace;
  6636. }
  6637. } else {
  6638. // descendant combinator
  6639. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  6640. _space2 = _this$convertWhitespa3.space,
  6641. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  6642. if (!_rawSpace2) {
  6643. _rawSpace2 = _space2;
  6644. }
  6645. var spaces = {};
  6646. var raws = {
  6647. spaces: {}
  6648. };
  6649. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  6650. spaces.before = _space2.slice(0, _space2.length - 1);
  6651. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  6652. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  6653. spaces.after = _space2.slice(1);
  6654. raws.spaces.after = _rawSpace2.slice(1);
  6655. } else {
  6656. raws.value = _rawSpace2;
  6657. }
  6658. node = new _combinator["default"]({
  6659. value: ' ',
  6660. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  6661. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  6662. spaces: spaces,
  6663. raws: raws
  6664. });
  6665. }
  6666. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  6667. node.spaces.after = this.optionalSpace(this.content());
  6668. this.position++;
  6669. }
  6670. return this.newNode(node);
  6671. };
  6672. _proto.comma = function comma() {
  6673. if (this.position === this.tokens.length - 1) {
  6674. this.root.trailingComma = true;
  6675. this.position++;
  6676. return;
  6677. }
  6678. this.current._inferEndPosition();
  6679. var selector = new _selector["default"]({
  6680. source: {
  6681. start: tokenStart(this.tokens[this.position + 1])
  6682. },
  6683. sourceIndex: this.tokens[this.position + 1][_tokenize.FIELDS.START_POS]
  6684. });
  6685. this.current.parent.append(selector);
  6686. this.current = selector;
  6687. this.position++;
  6688. };
  6689. _proto.comment = function comment() {
  6690. var current = this.currToken;
  6691. this.newNode(new _comment["default"]({
  6692. value: this.content(),
  6693. source: getTokenSource(current),
  6694. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6695. }));
  6696. this.position++;
  6697. };
  6698. _proto.error = function error(message, opts) {
  6699. throw this.root.error(message, opts);
  6700. };
  6701. _proto.missingBackslash = function missingBackslash() {
  6702. return this.error('Expected a backslash preceding the semicolon.', {
  6703. index: this.currToken[_tokenize.FIELDS.START_POS]
  6704. });
  6705. };
  6706. _proto.missingParenthesis = function missingParenthesis() {
  6707. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  6708. };
  6709. _proto.missingSquareBracket = function missingSquareBracket() {
  6710. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  6711. };
  6712. _proto.unexpected = function unexpected() {
  6713. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  6714. };
  6715. _proto.unexpectedPipe = function unexpectedPipe() {
  6716. return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  6717. };
  6718. _proto.namespace = function namespace() {
  6719. var before = this.prevToken && this.content(this.prevToken) || true;
  6720. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  6721. this.position++;
  6722. return this.word(before);
  6723. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  6724. this.position++;
  6725. return this.universal(before);
  6726. }
  6727. this.unexpectedPipe();
  6728. };
  6729. _proto.nesting = function nesting() {
  6730. if (this.nextToken) {
  6731. var nextContent = this.content(this.nextToken);
  6732. if (nextContent === "|") {
  6733. this.position++;
  6734. return;
  6735. }
  6736. }
  6737. var current = this.currToken;
  6738. this.newNode(new _nesting["default"]({
  6739. value: this.content(),
  6740. source: getTokenSource(current),
  6741. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6742. }));
  6743. this.position++;
  6744. };
  6745. _proto.parentheses = function parentheses() {
  6746. var last = this.current.last;
  6747. var unbalanced = 1;
  6748. this.position++;
  6749. if (last && last.type === types.PSEUDO) {
  6750. var selector = new _selector["default"]({
  6751. source: {
  6752. start: tokenStart(this.tokens[this.position])
  6753. },
  6754. sourceIndex: this.tokens[this.position][_tokenize.FIELDS.START_POS]
  6755. });
  6756. var cache = this.current;
  6757. last.append(selector);
  6758. this.current = selector;
  6759. while (this.position < this.tokens.length && unbalanced) {
  6760. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6761. unbalanced++;
  6762. }
  6763. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6764. unbalanced--;
  6765. }
  6766. if (unbalanced) {
  6767. this.parse();
  6768. } else {
  6769. this.current.source.end = tokenEnd(this.currToken);
  6770. this.current.parent.source.end = tokenEnd(this.currToken);
  6771. this.position++;
  6772. }
  6773. }
  6774. this.current = cache;
  6775. } else {
  6776. // I think this case should be an error. It's used to implement a basic parse of media queries
  6777. // but I don't think it's a good idea.
  6778. var parenStart = this.currToken;
  6779. var parenValue = "(";
  6780. var parenEnd;
  6781. while (this.position < this.tokens.length && unbalanced) {
  6782. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6783. unbalanced++;
  6784. }
  6785. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6786. unbalanced--;
  6787. }
  6788. parenEnd = this.currToken;
  6789. parenValue += this.parseParenthesisToken(this.currToken);
  6790. this.position++;
  6791. }
  6792. if (last) {
  6793. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  6794. } else {
  6795. this.newNode(new _string["default"]({
  6796. value: parenValue,
  6797. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  6798. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  6799. }));
  6800. }
  6801. }
  6802. if (unbalanced) {
  6803. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  6804. }
  6805. };
  6806. _proto.pseudo = function pseudo() {
  6807. var _this4 = this;
  6808. var pseudoStr = '';
  6809. var startingToken = this.currToken;
  6810. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  6811. pseudoStr += this.content();
  6812. this.position++;
  6813. }
  6814. if (!this.currToken) {
  6815. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  6816. }
  6817. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  6818. this.splitWord(false, function (first, length) {
  6819. pseudoStr += first;
  6820. _this4.newNode(new _pseudo["default"]({
  6821. value: pseudoStr,
  6822. source: getTokenSourceSpan(startingToken, _this4.currToken),
  6823. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  6824. }));
  6825. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  6826. _this4.error('Misplaced parenthesis.', {
  6827. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  6828. });
  6829. }
  6830. });
  6831. } else {
  6832. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  6833. }
  6834. };
  6835. _proto.space = function space() {
  6836. var content = this.content();
  6837. // Handle space before and after the selector
  6838. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  6839. return node.type === 'comment';
  6840. })) {
  6841. this.spaces = this.optionalSpace(content);
  6842. this.position++;
  6843. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  6844. this.current.last.spaces.after = this.optionalSpace(content);
  6845. this.position++;
  6846. } else {
  6847. this.combinator();
  6848. }
  6849. };
  6850. _proto.string = function string() {
  6851. var current = this.currToken;
  6852. this.newNode(new _string["default"]({
  6853. value: this.content(),
  6854. source: getTokenSource(current),
  6855. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6856. }));
  6857. this.position++;
  6858. };
  6859. _proto.universal = function universal(namespace) {
  6860. var nextToken = this.nextToken;
  6861. if (nextToken && this.content(nextToken) === '|') {
  6862. this.position++;
  6863. return this.namespace();
  6864. }
  6865. var current = this.currToken;
  6866. this.newNode(new _universal["default"]({
  6867. value: this.content(),
  6868. source: getTokenSource(current),
  6869. sourceIndex: current[_tokenize.FIELDS.START_POS]
  6870. }), namespace);
  6871. this.position++;
  6872. };
  6873. _proto.splitWord = function splitWord(namespace, firstCallback) {
  6874. var _this5 = this;
  6875. var nextToken = this.nextToken;
  6876. var word = this.content();
  6877. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  6878. this.position++;
  6879. var current = this.content();
  6880. word += current;
  6881. if (current.lastIndexOf('\\') === current.length - 1) {
  6882. var next = this.nextToken;
  6883. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  6884. word += this.requiredSpace(this.content(next));
  6885. this.position++;
  6886. }
  6887. }
  6888. nextToken = this.nextToken;
  6889. }
  6890. var hasClass = indexesOf(word, '.').filter(function (i) {
  6891. // Allow escaped dot within class name
  6892. var escapedDot = word[i - 1] === '\\';
  6893. // Allow decimal numbers percent in @keyframes
  6894. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  6895. return !escapedDot && !isKeyframesPercent;
  6896. });
  6897. var hasId = indexesOf(word, '#').filter(function (i) {
  6898. return word[i - 1] !== '\\';
  6899. });
  6900. // Eliminate Sass interpolations from the list of id indexes
  6901. var interpolations = indexesOf(word, '#{');
  6902. if (interpolations.length) {
  6903. hasId = hasId.filter(function (hashIndex) {
  6904. return !~interpolations.indexOf(hashIndex);
  6905. });
  6906. }
  6907. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  6908. indices.forEach(function (ind, i) {
  6909. var index = indices[i + 1] || word.length;
  6910. var value = word.slice(ind, index);
  6911. if (i === 0 && firstCallback) {
  6912. return firstCallback.call(_this5, value, indices.length);
  6913. }
  6914. var node;
  6915. var current = _this5.currToken;
  6916. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  6917. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  6918. if (~hasClass.indexOf(ind)) {
  6919. var classNameOpts = {
  6920. value: value.slice(1),
  6921. source: source,
  6922. sourceIndex: sourceIndex
  6923. };
  6924. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  6925. } else if (~hasId.indexOf(ind)) {
  6926. var idOpts = {
  6927. value: value.slice(1),
  6928. source: source,
  6929. sourceIndex: sourceIndex
  6930. };
  6931. node = new _id["default"](unescapeProp(idOpts, "value"));
  6932. } else {
  6933. var tagOpts = {
  6934. value: value,
  6935. source: source,
  6936. sourceIndex: sourceIndex
  6937. };
  6938. unescapeProp(tagOpts, "value");
  6939. node = new _tag["default"](tagOpts);
  6940. }
  6941. _this5.newNode(node, namespace);
  6942. // Ensure that the namespace is used only once
  6943. namespace = null;
  6944. });
  6945. this.position++;
  6946. };
  6947. _proto.word = function word(namespace) {
  6948. var nextToken = this.nextToken;
  6949. if (nextToken && this.content(nextToken) === '|') {
  6950. this.position++;
  6951. return this.namespace();
  6952. }
  6953. return this.splitWord(namespace);
  6954. };
  6955. _proto.loop = function loop() {
  6956. while (this.position < this.tokens.length) {
  6957. this.parse(true);
  6958. }
  6959. this.current._inferEndPosition();
  6960. return this.root;
  6961. };
  6962. _proto.parse = function parse(throwOnParenthesis) {
  6963. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  6964. case tokens.space:
  6965. this.space();
  6966. break;
  6967. case tokens.comment:
  6968. this.comment();
  6969. break;
  6970. case tokens.openParenthesis:
  6971. this.parentheses();
  6972. break;
  6973. case tokens.closeParenthesis:
  6974. if (throwOnParenthesis) {
  6975. this.missingParenthesis();
  6976. }
  6977. break;
  6978. case tokens.openSquare:
  6979. this.attribute();
  6980. break;
  6981. case tokens.dollar:
  6982. case tokens.caret:
  6983. case tokens.equals:
  6984. case tokens.word:
  6985. this.word();
  6986. break;
  6987. case tokens.colon:
  6988. this.pseudo();
  6989. break;
  6990. case tokens.comma:
  6991. this.comma();
  6992. break;
  6993. case tokens.asterisk:
  6994. this.universal();
  6995. break;
  6996. case tokens.ampersand:
  6997. this.nesting();
  6998. break;
  6999. case tokens.slash:
  7000. case tokens.combinator:
  7001. this.combinator();
  7002. break;
  7003. case tokens.str:
  7004. this.string();
  7005. break;
  7006. // These cases throw; no break needed.
  7007. case tokens.closeSquare:
  7008. this.missingSquareBracket();
  7009. case tokens.semicolon:
  7010. this.missingBackslash();
  7011. default:
  7012. this.unexpected();
  7013. }
  7014. }
  7015. /**
  7016. * Helpers
  7017. */;
  7018. _proto.expected = function expected(description, index, found) {
  7019. if (Array.isArray(description)) {
  7020. var last = description.pop();
  7021. description = description.join(', ') + " or " + last;
  7022. }
  7023. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  7024. if (!found) {
  7025. return this.error("Expected " + an + " " + description + ".", {
  7026. index: index
  7027. });
  7028. }
  7029. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  7030. index: index
  7031. });
  7032. };
  7033. _proto.requiredSpace = function requiredSpace(space) {
  7034. return this.options.lossy ? ' ' : space;
  7035. };
  7036. _proto.optionalSpace = function optionalSpace(space) {
  7037. return this.options.lossy ? '' : space;
  7038. };
  7039. _proto.lossySpace = function lossySpace(space, required) {
  7040. if (this.options.lossy) {
  7041. return required ? ' ' : '';
  7042. } else {
  7043. return space;
  7044. }
  7045. };
  7046. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  7047. var content = this.content(token);
  7048. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  7049. return this.requiredSpace(content);
  7050. } else {
  7051. return content;
  7052. }
  7053. };
  7054. _proto.newNode = function newNode(node, namespace) {
  7055. if (namespace) {
  7056. if (/^ +$/.test(namespace)) {
  7057. if (!this.options.lossy) {
  7058. this.spaces = (this.spaces || '') + namespace;
  7059. }
  7060. namespace = true;
  7061. }
  7062. node.namespace = namespace;
  7063. unescapeProp(node, "namespace");
  7064. }
  7065. if (this.spaces) {
  7066. node.spaces.before = this.spaces;
  7067. this.spaces = '';
  7068. }
  7069. return this.current.append(node);
  7070. };
  7071. _proto.content = function content(token) {
  7072. if (token === void 0) {
  7073. token = this.currToken;
  7074. }
  7075. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  7076. };
  7077. /**
  7078. * returns the index of the next non-whitespace, non-comment token.
  7079. * returns -1 if no meaningful token is found.
  7080. */
  7081. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  7082. if (startPosition === void 0) {
  7083. startPosition = this.position + 1;
  7084. }
  7085. var searchPosition = startPosition;
  7086. while (searchPosition < this.tokens.length) {
  7087. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  7088. searchPosition++;
  7089. continue;
  7090. } else {
  7091. return searchPosition;
  7092. }
  7093. }
  7094. return -1;
  7095. };
  7096. _createClass(Parser, [{
  7097. key: "currToken",
  7098. get: function get() {
  7099. return this.tokens[this.position];
  7100. }
  7101. }, {
  7102. key: "nextToken",
  7103. get: function get() {
  7104. return this.tokens[this.position + 1];
  7105. }
  7106. }, {
  7107. key: "prevToken",
  7108. get: function get() {
  7109. return this.tokens[this.position - 1];
  7110. }
  7111. }]);
  7112. return Parser;
  7113. }();
  7114. exports["default"] = Parser;
  7115. module.exports = exports.default;
  7116. } (parser$1, parser$1.exports));
  7117. return parser$1.exports;
  7118. }
  7119. var hasRequiredProcessor$1;
  7120. function requireProcessor$1 () {
  7121. if (hasRequiredProcessor$1) return processor$1.exports;
  7122. hasRequiredProcessor$1 = 1;
  7123. (function (module, exports) {
  7124. exports.__esModule = true;
  7125. exports["default"] = void 0;
  7126. var _parser = _interopRequireDefault(/*@__PURE__*/ requireParser$2());
  7127. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7128. var Processor = /*#__PURE__*/function () {
  7129. function Processor(func, options) {
  7130. this.func = func || function noop() {};
  7131. this.funcRes = null;
  7132. this.options = options;
  7133. }
  7134. var _proto = Processor.prototype;
  7135. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  7136. if (options === void 0) {
  7137. options = {};
  7138. }
  7139. var merged = Object.assign({}, this.options, options);
  7140. if (merged.updateSelector === false) {
  7141. return false;
  7142. } else {
  7143. return typeof rule !== "string";
  7144. }
  7145. };
  7146. _proto._isLossy = function _isLossy(options) {
  7147. if (options === void 0) {
  7148. options = {};
  7149. }
  7150. var merged = Object.assign({}, this.options, options);
  7151. if (merged.lossless === false) {
  7152. return true;
  7153. } else {
  7154. return false;
  7155. }
  7156. };
  7157. _proto._root = function _root(rule, options) {
  7158. if (options === void 0) {
  7159. options = {};
  7160. }
  7161. var parser = new _parser["default"](rule, this._parseOptions(options));
  7162. return parser.root;
  7163. };
  7164. _proto._parseOptions = function _parseOptions(options) {
  7165. return {
  7166. lossy: this._isLossy(options)
  7167. };
  7168. };
  7169. _proto._run = function _run(rule, options) {
  7170. var _this = this;
  7171. if (options === void 0) {
  7172. options = {};
  7173. }
  7174. return new Promise(function (resolve, reject) {
  7175. try {
  7176. var root = _this._root(rule, options);
  7177. Promise.resolve(_this.func(root)).then(function (transform) {
  7178. var string = undefined;
  7179. if (_this._shouldUpdateSelector(rule, options)) {
  7180. string = root.toString();
  7181. rule.selector = string;
  7182. }
  7183. return {
  7184. transform: transform,
  7185. root: root,
  7186. string: string
  7187. };
  7188. }).then(resolve, reject);
  7189. } catch (e) {
  7190. reject(e);
  7191. return;
  7192. }
  7193. });
  7194. };
  7195. _proto._runSync = function _runSync(rule, options) {
  7196. if (options === void 0) {
  7197. options = {};
  7198. }
  7199. var root = this._root(rule, options);
  7200. var transform = this.func(root);
  7201. if (transform && typeof transform.then === "function") {
  7202. throw new Error("Selector processor returned a promise to a synchronous call.");
  7203. }
  7204. var string = undefined;
  7205. if (options.updateSelector && typeof rule !== "string") {
  7206. string = root.toString();
  7207. rule.selector = string;
  7208. }
  7209. return {
  7210. transform: transform,
  7211. root: root,
  7212. string: string
  7213. };
  7214. }
  7215. /**
  7216. * Process rule into a selector AST.
  7217. *
  7218. * @param rule {postcss.Rule | string} The css selector to be processed
  7219. * @param options The options for processing
  7220. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  7221. */;
  7222. _proto.ast = function ast(rule, options) {
  7223. return this._run(rule, options).then(function (result) {
  7224. return result.root;
  7225. });
  7226. }
  7227. /**
  7228. * Process rule into a selector AST synchronously.
  7229. *
  7230. * @param rule {postcss.Rule | string} The css selector to be processed
  7231. * @param options The options for processing
  7232. * @returns {parser.Root} The AST of the selector after processing it.
  7233. */;
  7234. _proto.astSync = function astSync(rule, options) {
  7235. return this._runSync(rule, options).root;
  7236. }
  7237. /**
  7238. * Process a selector into a transformed value asynchronously
  7239. *
  7240. * @param rule {postcss.Rule | string} The css selector to be processed
  7241. * @param options The options for processing
  7242. * @returns {Promise<any>} The value returned by the processor.
  7243. */;
  7244. _proto.transform = function transform(rule, options) {
  7245. return this._run(rule, options).then(function (result) {
  7246. return result.transform;
  7247. });
  7248. }
  7249. /**
  7250. * Process a selector into a transformed value synchronously.
  7251. *
  7252. * @param rule {postcss.Rule | string} The css selector to be processed
  7253. * @param options The options for processing
  7254. * @returns {any} The value returned by the processor.
  7255. */;
  7256. _proto.transformSync = function transformSync(rule, options) {
  7257. return this._runSync(rule, options).transform;
  7258. }
  7259. /**
  7260. * Process a selector into a new selector string asynchronously.
  7261. *
  7262. * @param rule {postcss.Rule | string} The css selector to be processed
  7263. * @param options The options for processing
  7264. * @returns {string} the selector after processing.
  7265. */;
  7266. _proto.process = function process(rule, options) {
  7267. return this._run(rule, options).then(function (result) {
  7268. return result.string || result.root.toString();
  7269. });
  7270. }
  7271. /**
  7272. * Process a selector into a new selector string synchronously.
  7273. *
  7274. * @param rule {postcss.Rule | string} The css selector to be processed
  7275. * @param options The options for processing
  7276. * @returns {string} the selector after processing.
  7277. */;
  7278. _proto.processSync = function processSync(rule, options) {
  7279. var result = this._runSync(rule, options);
  7280. return result.string || result.root.toString();
  7281. };
  7282. return Processor;
  7283. }();
  7284. exports["default"] = Processor;
  7285. module.exports = exports.default;
  7286. } (processor$1, processor$1.exports));
  7287. return processor$1.exports;
  7288. }
  7289. var selectors$1 = {};
  7290. var constructors$1 = {};
  7291. var hasRequiredConstructors$1;
  7292. function requireConstructors$1 () {
  7293. if (hasRequiredConstructors$1) return constructors$1;
  7294. hasRequiredConstructors$1 = 1;
  7295. constructors$1.__esModule = true;
  7296. 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;
  7297. var _attribute = _interopRequireDefault(/*@__PURE__*/ requireAttribute$1());
  7298. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName$1());
  7299. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator$1());
  7300. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment$1());
  7301. var _id = _interopRequireDefault(/*@__PURE__*/ requireId$1());
  7302. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting$1());
  7303. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo$1());
  7304. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot$1());
  7305. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector$1());
  7306. var _string = _interopRequireDefault(/*@__PURE__*/ requireString$1());
  7307. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag$1());
  7308. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal$1());
  7309. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7310. var attribute = function attribute(opts) {
  7311. return new _attribute["default"](opts);
  7312. };
  7313. constructors$1.attribute = attribute;
  7314. var className = function className(opts) {
  7315. return new _className["default"](opts);
  7316. };
  7317. constructors$1.className = className;
  7318. var combinator = function combinator(opts) {
  7319. return new _combinator["default"](opts);
  7320. };
  7321. constructors$1.combinator = combinator;
  7322. var comment = function comment(opts) {
  7323. return new _comment["default"](opts);
  7324. };
  7325. constructors$1.comment = comment;
  7326. var id = function id(opts) {
  7327. return new _id["default"](opts);
  7328. };
  7329. constructors$1.id = id;
  7330. var nesting = function nesting(opts) {
  7331. return new _nesting["default"](opts);
  7332. };
  7333. constructors$1.nesting = nesting;
  7334. var pseudo = function pseudo(opts) {
  7335. return new _pseudo["default"](opts);
  7336. };
  7337. constructors$1.pseudo = pseudo;
  7338. var root = function root(opts) {
  7339. return new _root["default"](opts);
  7340. };
  7341. constructors$1.root = root;
  7342. var selector = function selector(opts) {
  7343. return new _selector["default"](opts);
  7344. };
  7345. constructors$1.selector = selector;
  7346. var string = function string(opts) {
  7347. return new _string["default"](opts);
  7348. };
  7349. constructors$1.string = string;
  7350. var tag = function tag(opts) {
  7351. return new _tag["default"](opts);
  7352. };
  7353. constructors$1.tag = tag;
  7354. var universal = function universal(opts) {
  7355. return new _universal["default"](opts);
  7356. };
  7357. constructors$1.universal = universal;
  7358. return constructors$1;
  7359. }
  7360. var guards$1 = {};
  7361. var hasRequiredGuards$1;
  7362. function requireGuards$1 () {
  7363. if (hasRequiredGuards$1) return guards$1;
  7364. hasRequiredGuards$1 = 1;
  7365. guards$1.__esModule = true;
  7366. guards$1.isComment = guards$1.isCombinator = guards$1.isClassName = guards$1.isAttribute = void 0;
  7367. guards$1.isContainer = isContainer;
  7368. guards$1.isIdentifier = void 0;
  7369. guards$1.isNamespace = isNamespace;
  7370. guards$1.isNesting = void 0;
  7371. guards$1.isNode = isNode;
  7372. guards$1.isPseudo = void 0;
  7373. guards$1.isPseudoClass = isPseudoClass;
  7374. guards$1.isPseudoElement = isPseudoElement;
  7375. guards$1.isUniversal = guards$1.isTag = guards$1.isString = guards$1.isSelector = guards$1.isRoot = void 0;
  7376. var _types = /*@__PURE__*/ requireTypes$1();
  7377. var _IS_TYPE;
  7378. 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);
  7379. function isNode(node) {
  7380. return typeof node === "object" && IS_TYPE[node.type];
  7381. }
  7382. function isNodeType(type, node) {
  7383. return isNode(node) && node.type === type;
  7384. }
  7385. var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  7386. guards$1.isAttribute = isAttribute;
  7387. var isClassName = isNodeType.bind(null, _types.CLASS);
  7388. guards$1.isClassName = isClassName;
  7389. var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  7390. guards$1.isCombinator = isCombinator;
  7391. var isComment = isNodeType.bind(null, _types.COMMENT);
  7392. guards$1.isComment = isComment;
  7393. var isIdentifier = isNodeType.bind(null, _types.ID);
  7394. guards$1.isIdentifier = isIdentifier;
  7395. var isNesting = isNodeType.bind(null, _types.NESTING);
  7396. guards$1.isNesting = isNesting;
  7397. var isPseudo = isNodeType.bind(null, _types.PSEUDO);
  7398. guards$1.isPseudo = isPseudo;
  7399. var isRoot = isNodeType.bind(null, _types.ROOT);
  7400. guards$1.isRoot = isRoot;
  7401. var isSelector = isNodeType.bind(null, _types.SELECTOR);
  7402. guards$1.isSelector = isSelector;
  7403. var isString = isNodeType.bind(null, _types.STRING);
  7404. guards$1.isString = isString;
  7405. var isTag = isNodeType.bind(null, _types.TAG);
  7406. guards$1.isTag = isTag;
  7407. var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  7408. guards$1.isUniversal = isUniversal;
  7409. function isPseudoElement(node) {
  7410. 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");
  7411. }
  7412. function isPseudoClass(node) {
  7413. return isPseudo(node) && !isPseudoElement(node);
  7414. }
  7415. function isContainer(node) {
  7416. return !!(isNode(node) && node.walk);
  7417. }
  7418. function isNamespace(node) {
  7419. return isAttribute(node) || isTag(node);
  7420. }
  7421. return guards$1;
  7422. }
  7423. var hasRequiredSelectors$1;
  7424. function requireSelectors$1 () {
  7425. if (hasRequiredSelectors$1) return selectors$1;
  7426. hasRequiredSelectors$1 = 1;
  7427. (function (exports) {
  7428. exports.__esModule = true;
  7429. var _types = /*@__PURE__*/ requireTypes$1();
  7430. Object.keys(_types).forEach(function (key) {
  7431. if (key === "default" || key === "__esModule") return;
  7432. if (key in exports && exports[key] === _types[key]) return;
  7433. exports[key] = _types[key];
  7434. });
  7435. var _constructors = /*@__PURE__*/ requireConstructors$1();
  7436. Object.keys(_constructors).forEach(function (key) {
  7437. if (key === "default" || key === "__esModule") return;
  7438. if (key in exports && exports[key] === _constructors[key]) return;
  7439. exports[key] = _constructors[key];
  7440. });
  7441. var _guards = /*@__PURE__*/ requireGuards$1();
  7442. Object.keys(_guards).forEach(function (key) {
  7443. if (key === "default" || key === "__esModule") return;
  7444. if (key in exports && exports[key] === _guards[key]) return;
  7445. exports[key] = _guards[key];
  7446. });
  7447. } (selectors$1));
  7448. return selectors$1;
  7449. }
  7450. var hasRequiredDist$1;
  7451. function requireDist$1 () {
  7452. if (hasRequiredDist$1) return dist$1.exports;
  7453. hasRequiredDist$1 = 1;
  7454. (function (module, exports) {
  7455. exports.__esModule = true;
  7456. exports["default"] = void 0;
  7457. var _processor = _interopRequireDefault(/*@__PURE__*/ requireProcessor$1());
  7458. var selectors = _interopRequireWildcard(/*@__PURE__*/ requireSelectors$1());
  7459. 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); }
  7460. 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; }
  7461. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  7462. var parser = function parser(processor) {
  7463. return new _processor["default"](processor);
  7464. };
  7465. Object.assign(parser, selectors);
  7466. delete parser.__esModule;
  7467. var _default = parser;
  7468. exports["default"] = _default;
  7469. module.exports = exports.default;
  7470. } (dist$1, dist$1.exports));
  7471. return dist$1.exports;
  7472. }
  7473. var distExports = /*@__PURE__*/ requireDist$1();
  7474. var selectorParser = /*@__PURE__*/getDefaultExportFromCjs(distExports);
  7475. const animationNameRE = /^(-\w+-)?animation-name$/;
  7476. const animationRE = /^(-\w+-)?animation$/;
  7477. const keyframesRE = /^(?:-\w+-)?keyframes$/;
  7478. const scopedPlugin = (id = "") => {
  7479. const keyframes = /* @__PURE__ */ Object.create(null);
  7480. const shortId = id.replace(/^data-v-/, "");
  7481. return {
  7482. postcssPlugin: "vue-sfc-scoped",
  7483. Rule(rule) {
  7484. processRule(id, rule);
  7485. },
  7486. AtRule(node) {
  7487. if (keyframesRE.test(node.name) && !node.params.endsWith(`-${shortId}`)) {
  7488. keyframes[node.params] = node.params = node.params + "-" + shortId;
  7489. }
  7490. },
  7491. OnceExit(root) {
  7492. if (Object.keys(keyframes).length) {
  7493. root.walkDecls((decl) => {
  7494. if (animationNameRE.test(decl.prop)) {
  7495. decl.value = decl.value.split(",").map((v) => keyframes[v.trim()] || v.trim()).join(",");
  7496. }
  7497. if (animationRE.test(decl.prop)) {
  7498. decl.value = decl.value.split(",").map((v) => {
  7499. const vals = v.trim().split(/\s+/);
  7500. const i = vals.findIndex((val) => keyframes[val]);
  7501. if (i !== -1) {
  7502. vals.splice(i, 1, keyframes[vals[i]]);
  7503. return vals.join(" ");
  7504. } else {
  7505. return v;
  7506. }
  7507. }).join(",");
  7508. }
  7509. });
  7510. }
  7511. }
  7512. };
  7513. };
  7514. const processedRules = /* @__PURE__ */ new WeakSet();
  7515. function processRule(id, rule) {
  7516. if (processedRules.has(rule) || rule.parent && rule.parent.type === "atrule" && keyframesRE.test(rule.parent.name)) {
  7517. return;
  7518. }
  7519. processedRules.add(rule);
  7520. let deep = false;
  7521. let parent = rule.parent;
  7522. while (parent && parent.type !== "root") {
  7523. if (parent.__deep) {
  7524. deep = true;
  7525. break;
  7526. }
  7527. parent = parent.parent;
  7528. }
  7529. rule.selector = selectorParser((selectorRoot) => {
  7530. selectorRoot.each((selector) => {
  7531. rewriteSelector(id, rule, selector, selectorRoot, deep);
  7532. });
  7533. }).processSync(rule.selector);
  7534. }
  7535. function rewriteSelector(id, rule, selector, selectorRoot, deep, slotted = false) {
  7536. let node = null;
  7537. let shouldInject = !deep;
  7538. selector.each((n) => {
  7539. if (n.type === "combinator" && (n.value === ">>>" || n.value === "/deep/")) {
  7540. n.value = " ";
  7541. n.spaces.before = n.spaces.after = "";
  7542. warn(
  7543. `the >>> and /deep/ combinators have been deprecated. Use :deep() instead.`
  7544. );
  7545. return false;
  7546. }
  7547. if (n.type === "pseudo") {
  7548. const { value } = n;
  7549. if (value === ":deep" || value === "::v-deep") {
  7550. rule.__deep = true;
  7551. if (n.nodes.length) {
  7552. let last = n;
  7553. n.nodes[0].each((ss) => {
  7554. selector.insertAfter(last, ss);
  7555. last = ss;
  7556. });
  7557. const prev = selector.at(selector.index(n) - 1);
  7558. if (!prev || !isSpaceCombinator(prev)) {
  7559. selector.insertAfter(
  7560. n,
  7561. selectorParser.combinator({
  7562. value: " "
  7563. })
  7564. );
  7565. }
  7566. selector.removeChild(n);
  7567. } else {
  7568. warn(
  7569. `${value} usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead of ${value} <inner-selector>.`
  7570. );
  7571. const prev = selector.at(selector.index(n) - 1);
  7572. if (prev && isSpaceCombinator(prev)) {
  7573. selector.removeChild(prev);
  7574. }
  7575. selector.removeChild(n);
  7576. }
  7577. return false;
  7578. }
  7579. if (value === ":slotted" || value === "::v-slotted") {
  7580. rewriteSelector(
  7581. id,
  7582. rule,
  7583. n.nodes[0],
  7584. selectorRoot,
  7585. deep,
  7586. true
  7587. );
  7588. let last = n;
  7589. n.nodes[0].each((ss) => {
  7590. selector.insertAfter(last, ss);
  7591. last = ss;
  7592. });
  7593. selector.removeChild(n);
  7594. shouldInject = false;
  7595. return false;
  7596. }
  7597. if (value === ":global" || value === "::v-global") {
  7598. selector.replaceWith(n.nodes[0]);
  7599. return false;
  7600. }
  7601. }
  7602. if (n.type === "universal") {
  7603. const prev = selector.at(selector.index(n) - 1);
  7604. const next = selector.at(selector.index(n) + 1);
  7605. if (!prev) {
  7606. if (next) {
  7607. if (next.type === "combinator" && next.value === " ") {
  7608. selector.removeChild(next);
  7609. }
  7610. selector.removeChild(n);
  7611. return;
  7612. } else {
  7613. node = selectorParser.combinator({
  7614. value: ""
  7615. });
  7616. selector.insertBefore(n, node);
  7617. selector.removeChild(n);
  7618. return false;
  7619. }
  7620. }
  7621. if (node) return;
  7622. }
  7623. if (n.type !== "pseudo" && n.type !== "combinator" || n.type === "pseudo" && (n.value === ":is" || n.value === ":where") && !node) {
  7624. node = n;
  7625. }
  7626. });
  7627. if (rule.nodes.some((node2) => node2.type === "rule")) {
  7628. const deep2 = rule.__deep;
  7629. if (!deep2) {
  7630. extractAndWrapNodes(rule);
  7631. const atruleNodes = rule.nodes.filter((node2) => node2.type === "atrule");
  7632. for (const atnode of atruleNodes) {
  7633. extractAndWrapNodes(atnode);
  7634. }
  7635. }
  7636. shouldInject = deep2;
  7637. }
  7638. if (node) {
  7639. const { type, value } = node;
  7640. if (type === "pseudo" && (value === ":is" || value === ":where")) {
  7641. node.nodes.forEach(
  7642. (value2) => rewriteSelector(id, rule, value2, selectorRoot, deep, slotted)
  7643. );
  7644. shouldInject = false;
  7645. }
  7646. }
  7647. if (node) {
  7648. node.spaces.after = "";
  7649. } else {
  7650. selector.first.spaces.before = "";
  7651. }
  7652. if (shouldInject) {
  7653. const idToAdd = slotted ? id + "-s" : id;
  7654. selector.insertAfter(
  7655. // If node is null it means we need to inject [id] at the start
  7656. // insertAfter can handle `null` here
  7657. node,
  7658. selectorParser.attribute({
  7659. attribute: idToAdd,
  7660. value: idToAdd,
  7661. raws: {},
  7662. quoteMark: `"`
  7663. })
  7664. );
  7665. }
  7666. }
  7667. function isSpaceCombinator(node) {
  7668. return node.type === "combinator" && /^\s+$/.test(node.value);
  7669. }
  7670. function extractAndWrapNodes(parentNode) {
  7671. if (!parentNode.nodes) return;
  7672. const nodes = parentNode.nodes.filter(
  7673. (node) => node.type === "decl" || node.type === "comment"
  7674. );
  7675. if (nodes.length) {
  7676. for (const node of nodes) {
  7677. parentNode.removeChild(node);
  7678. }
  7679. const wrappedRule = new require$$0$1.Rule({
  7680. nodes,
  7681. selector: "&"
  7682. });
  7683. parentNode.prepend(wrappedRule);
  7684. }
  7685. }
  7686. scopedPlugin.postcss = true;
  7687. var sourceMap = {};
  7688. var sourceMapGenerator = {};
  7689. var base64Vlq = {};
  7690. var base64 = {};
  7691. /* -*- Mode: js; js-indent-level: 2; -*- */
  7692. var hasRequiredBase64;
  7693. function requireBase64 () {
  7694. if (hasRequiredBase64) return base64;
  7695. hasRequiredBase64 = 1;
  7696. /*
  7697. * Copyright 2011 Mozilla Foundation and contributors
  7698. * Licensed under the New BSD license. See LICENSE or:
  7699. * http://opensource.org/licenses/BSD-3-Clause
  7700. */
  7701. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  7702. /**
  7703. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  7704. */
  7705. base64.encode = function (number) {
  7706. if (0 <= number && number < intToCharMap.length) {
  7707. return intToCharMap[number];
  7708. }
  7709. throw new TypeError("Must be between 0 and 63: " + number);
  7710. };
  7711. /**
  7712. * Decode a single base 64 character code digit to an integer. Returns -1 on
  7713. * failure.
  7714. */
  7715. base64.decode = function (charCode) {
  7716. var bigA = 65; // 'A'
  7717. var bigZ = 90; // 'Z'
  7718. var littleA = 97; // 'a'
  7719. var littleZ = 122; // 'z'
  7720. var zero = 48; // '0'
  7721. var nine = 57; // '9'
  7722. var plus = 43; // '+'
  7723. var slash = 47; // '/'
  7724. var littleOffset = 26;
  7725. var numberOffset = 52;
  7726. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  7727. if (bigA <= charCode && charCode <= bigZ) {
  7728. return (charCode - bigA);
  7729. }
  7730. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  7731. if (littleA <= charCode && charCode <= littleZ) {
  7732. return (charCode - littleA + littleOffset);
  7733. }
  7734. // 52 - 61: 0123456789
  7735. if (zero <= charCode && charCode <= nine) {
  7736. return (charCode - zero + numberOffset);
  7737. }
  7738. // 62: +
  7739. if (charCode == plus) {
  7740. return 62;
  7741. }
  7742. // 63: /
  7743. if (charCode == slash) {
  7744. return 63;
  7745. }
  7746. // Invalid base64 digit.
  7747. return -1;
  7748. };
  7749. return base64;
  7750. }
  7751. /* -*- Mode: js; js-indent-level: 2; -*- */
  7752. var hasRequiredBase64Vlq;
  7753. function requireBase64Vlq () {
  7754. if (hasRequiredBase64Vlq) return base64Vlq;
  7755. hasRequiredBase64Vlq = 1;
  7756. /*
  7757. * Copyright 2011 Mozilla Foundation and contributors
  7758. * Licensed under the New BSD license. See LICENSE or:
  7759. * http://opensource.org/licenses/BSD-3-Clause
  7760. *
  7761. * Based on the Base 64 VLQ implementation in Closure Compiler:
  7762. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  7763. *
  7764. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  7765. * Redistribution and use in source and binary forms, with or without
  7766. * modification, are permitted provided that the following conditions are
  7767. * met:
  7768. *
  7769. * * Redistributions of source code must retain the above copyright
  7770. * notice, this list of conditions and the following disclaimer.
  7771. * * Redistributions in binary form must reproduce the above
  7772. * copyright notice, this list of conditions and the following
  7773. * disclaimer in the documentation and/or other materials provided
  7774. * with the distribution.
  7775. * * Neither the name of Google Inc. nor the names of its
  7776. * contributors may be used to endorse or promote products derived
  7777. * from this software without specific prior written permission.
  7778. *
  7779. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  7780. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7781. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  7782. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7783. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  7784. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  7785. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  7786. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  7787. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  7788. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  7789. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  7790. */
  7791. var base64 = /*@__PURE__*/ requireBase64();
  7792. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  7793. // length quantities we use in the source map spec, the first bit is the sign,
  7794. // the next four bits are the actual value, and the 6th bit is the
  7795. // continuation bit. The continuation bit tells us whether there are more
  7796. // digits in this value following this digit.
  7797. //
  7798. // Continuation
  7799. // | Sign
  7800. // | |
  7801. // V V
  7802. // 101011
  7803. var VLQ_BASE_SHIFT = 5;
  7804. // binary: 100000
  7805. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  7806. // binary: 011111
  7807. var VLQ_BASE_MASK = VLQ_BASE - 1;
  7808. // binary: 100000
  7809. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  7810. /**
  7811. * Converts from a two-complement value to a value where the sign bit is
  7812. * placed in the least significant bit. For example, as decimals:
  7813. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  7814. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  7815. */
  7816. function toVLQSigned(aValue) {
  7817. return aValue < 0
  7818. ? ((-aValue) << 1) + 1
  7819. : (aValue << 1) + 0;
  7820. }
  7821. /**
  7822. * Converts to a two-complement value from a value where the sign bit is
  7823. * placed in the least significant bit. For example, as decimals:
  7824. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  7825. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  7826. */
  7827. function fromVLQSigned(aValue) {
  7828. var isNegative = (aValue & 1) === 1;
  7829. var shifted = aValue >> 1;
  7830. return isNegative
  7831. ? -shifted
  7832. : shifted;
  7833. }
  7834. /**
  7835. * Returns the base 64 VLQ encoded value.
  7836. */
  7837. base64Vlq.encode = function base64VLQ_encode(aValue) {
  7838. var encoded = "";
  7839. var digit;
  7840. var vlq = toVLQSigned(aValue);
  7841. do {
  7842. digit = vlq & VLQ_BASE_MASK;
  7843. vlq >>>= VLQ_BASE_SHIFT;
  7844. if (vlq > 0) {
  7845. // There are still more digits in this value, so we must make sure the
  7846. // continuation bit is marked.
  7847. digit |= VLQ_CONTINUATION_BIT;
  7848. }
  7849. encoded += base64.encode(digit);
  7850. } while (vlq > 0);
  7851. return encoded;
  7852. };
  7853. /**
  7854. * Decodes the next base 64 VLQ value from the given string and returns the
  7855. * value and the rest of the string via the out parameter.
  7856. */
  7857. base64Vlq.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  7858. var strLen = aStr.length;
  7859. var result = 0;
  7860. var shift = 0;
  7861. var continuation, digit;
  7862. do {
  7863. if (aIndex >= strLen) {
  7864. throw new Error("Expected more digits in base 64 VLQ value.");
  7865. }
  7866. digit = base64.decode(aStr.charCodeAt(aIndex++));
  7867. if (digit === -1) {
  7868. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  7869. }
  7870. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  7871. digit &= VLQ_BASE_MASK;
  7872. result = result + (digit << shift);
  7873. shift += VLQ_BASE_SHIFT;
  7874. } while (continuation);
  7875. aOutParam.value = fromVLQSigned(result);
  7876. aOutParam.rest = aIndex;
  7877. };
  7878. return base64Vlq;
  7879. }
  7880. var util$1 = {};
  7881. /* -*- Mode: js; js-indent-level: 2; -*- */
  7882. var hasRequiredUtil$1;
  7883. function requireUtil$1 () {
  7884. if (hasRequiredUtil$1) return util$1;
  7885. hasRequiredUtil$1 = 1;
  7886. (function (exports) {
  7887. /*
  7888. * Copyright 2011 Mozilla Foundation and contributors
  7889. * Licensed under the New BSD license. See LICENSE or:
  7890. * http://opensource.org/licenses/BSD-3-Clause
  7891. */
  7892. /**
  7893. * This is a helper function for getting values from parameter/options
  7894. * objects.
  7895. *
  7896. * @param args The object we are extracting values from
  7897. * @param name The name of the property we are getting.
  7898. * @param defaultValue An optional value to return if the property is missing
  7899. * from the object. If this is not specified and the property is missing, an
  7900. * error will be thrown.
  7901. */
  7902. function getArg(aArgs, aName, aDefaultValue) {
  7903. if (aName in aArgs) {
  7904. return aArgs[aName];
  7905. } else if (arguments.length === 3) {
  7906. return aDefaultValue;
  7907. } else {
  7908. throw new Error('"' + aName + '" is a required argument.');
  7909. }
  7910. }
  7911. exports.getArg = getArg;
  7912. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  7913. var dataUrlRegexp = /^data:.+\,.+$/;
  7914. function urlParse(aUrl) {
  7915. var match = aUrl.match(urlRegexp);
  7916. if (!match) {
  7917. return null;
  7918. }
  7919. return {
  7920. scheme: match[1],
  7921. auth: match[2],
  7922. host: match[3],
  7923. port: match[4],
  7924. path: match[5]
  7925. };
  7926. }
  7927. exports.urlParse = urlParse;
  7928. function urlGenerate(aParsedUrl) {
  7929. var url = '';
  7930. if (aParsedUrl.scheme) {
  7931. url += aParsedUrl.scheme + ':';
  7932. }
  7933. url += '//';
  7934. if (aParsedUrl.auth) {
  7935. url += aParsedUrl.auth + '@';
  7936. }
  7937. if (aParsedUrl.host) {
  7938. url += aParsedUrl.host;
  7939. }
  7940. if (aParsedUrl.port) {
  7941. url += ":" + aParsedUrl.port;
  7942. }
  7943. if (aParsedUrl.path) {
  7944. url += aParsedUrl.path;
  7945. }
  7946. return url;
  7947. }
  7948. exports.urlGenerate = urlGenerate;
  7949. /**
  7950. * Normalizes a path, or the path portion of a URL:
  7951. *
  7952. * - Replaces consecutive slashes with one slash.
  7953. * - Removes unnecessary '.' parts.
  7954. * - Removes unnecessary '<dir>/..' parts.
  7955. *
  7956. * Based on code in the Node.js 'path' core module.
  7957. *
  7958. * @param aPath The path or url to normalize.
  7959. */
  7960. function normalize(aPath) {
  7961. var path = aPath;
  7962. var url = urlParse(aPath);
  7963. if (url) {
  7964. if (!url.path) {
  7965. return aPath;
  7966. }
  7967. path = url.path;
  7968. }
  7969. var isAbsolute = exports.isAbsolute(path);
  7970. var parts = path.split(/\/+/);
  7971. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  7972. part = parts[i];
  7973. if (part === '.') {
  7974. parts.splice(i, 1);
  7975. } else if (part === '..') {
  7976. up++;
  7977. } else if (up > 0) {
  7978. if (part === '') {
  7979. // The first part is blank if the path is absolute. Trying to go
  7980. // above the root is a no-op. Therefore we can remove all '..' parts
  7981. // directly after the root.
  7982. parts.splice(i + 1, up);
  7983. up = 0;
  7984. } else {
  7985. parts.splice(i, 2);
  7986. up--;
  7987. }
  7988. }
  7989. }
  7990. path = parts.join('/');
  7991. if (path === '') {
  7992. path = isAbsolute ? '/' : '.';
  7993. }
  7994. if (url) {
  7995. url.path = path;
  7996. return urlGenerate(url);
  7997. }
  7998. return path;
  7999. }
  8000. exports.normalize = normalize;
  8001. /**
  8002. * Joins two paths/URLs.
  8003. *
  8004. * @param aRoot The root path or URL.
  8005. * @param aPath The path or URL to be joined with the root.
  8006. *
  8007. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  8008. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  8009. * first.
  8010. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  8011. * is updated with the result and aRoot is returned. Otherwise the result
  8012. * is returned.
  8013. * - If aPath is absolute, the result is aPath.
  8014. * - Otherwise the two paths are joined with a slash.
  8015. * - Joining for example 'http://' and 'www.example.com' is also supported.
  8016. */
  8017. function join(aRoot, aPath) {
  8018. if (aRoot === "") {
  8019. aRoot = ".";
  8020. }
  8021. if (aPath === "") {
  8022. aPath = ".";
  8023. }
  8024. var aPathUrl = urlParse(aPath);
  8025. var aRootUrl = urlParse(aRoot);
  8026. if (aRootUrl) {
  8027. aRoot = aRootUrl.path || '/';
  8028. }
  8029. // `join(foo, '//www.example.org')`
  8030. if (aPathUrl && !aPathUrl.scheme) {
  8031. if (aRootUrl) {
  8032. aPathUrl.scheme = aRootUrl.scheme;
  8033. }
  8034. return urlGenerate(aPathUrl);
  8035. }
  8036. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  8037. return aPath;
  8038. }
  8039. // `join('http://', 'www.example.com')`
  8040. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  8041. aRootUrl.host = aPath;
  8042. return urlGenerate(aRootUrl);
  8043. }
  8044. var joined = aPath.charAt(0) === '/'
  8045. ? aPath
  8046. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  8047. if (aRootUrl) {
  8048. aRootUrl.path = joined;
  8049. return urlGenerate(aRootUrl);
  8050. }
  8051. return joined;
  8052. }
  8053. exports.join = join;
  8054. exports.isAbsolute = function (aPath) {
  8055. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  8056. };
  8057. /**
  8058. * Make a path relative to a URL or another path.
  8059. *
  8060. * @param aRoot The root path or URL.
  8061. * @param aPath The path or URL to be made relative to aRoot.
  8062. */
  8063. function relative(aRoot, aPath) {
  8064. if (aRoot === "") {
  8065. aRoot = ".";
  8066. }
  8067. aRoot = aRoot.replace(/\/$/, '');
  8068. // It is possible for the path to be above the root. In this case, simply
  8069. // checking whether the root is a prefix of the path won't work. Instead, we
  8070. // need to remove components from the root one by one, until either we find
  8071. // a prefix that fits, or we run out of components to remove.
  8072. var level = 0;
  8073. while (aPath.indexOf(aRoot + '/') !== 0) {
  8074. var index = aRoot.lastIndexOf("/");
  8075. if (index < 0) {
  8076. return aPath;
  8077. }
  8078. // If the only part of the root that is left is the scheme (i.e. http://,
  8079. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  8080. // have exhausted all components, so the path is not relative to the root.
  8081. aRoot = aRoot.slice(0, index);
  8082. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  8083. return aPath;
  8084. }
  8085. ++level;
  8086. }
  8087. // Make sure we add a "../" for each component we removed from the root.
  8088. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  8089. }
  8090. exports.relative = relative;
  8091. var supportsNullProto = (function () {
  8092. var obj = Object.create(null);
  8093. return !('__proto__' in obj);
  8094. }());
  8095. function identity (s) {
  8096. return s;
  8097. }
  8098. /**
  8099. * Because behavior goes wacky when you set `__proto__` on objects, we
  8100. * have to prefix all the strings in our set with an arbitrary character.
  8101. *
  8102. * See https://github.com/mozilla/source-map/pull/31 and
  8103. * https://github.com/mozilla/source-map/issues/30
  8104. *
  8105. * @param String aStr
  8106. */
  8107. function toSetString(aStr) {
  8108. if (isProtoString(aStr)) {
  8109. return '$' + aStr;
  8110. }
  8111. return aStr;
  8112. }
  8113. exports.toSetString = supportsNullProto ? identity : toSetString;
  8114. function fromSetString(aStr) {
  8115. if (isProtoString(aStr)) {
  8116. return aStr.slice(1);
  8117. }
  8118. return aStr;
  8119. }
  8120. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  8121. function isProtoString(s) {
  8122. if (!s) {
  8123. return false;
  8124. }
  8125. var length = s.length;
  8126. if (length < 9 /* "__proto__".length */) {
  8127. return false;
  8128. }
  8129. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  8130. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  8131. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  8132. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  8133. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  8134. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  8135. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  8136. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  8137. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  8138. return false;
  8139. }
  8140. for (var i = length - 10; i >= 0; i--) {
  8141. if (s.charCodeAt(i) !== 36 /* '$' */) {
  8142. return false;
  8143. }
  8144. }
  8145. return true;
  8146. }
  8147. /**
  8148. * Comparator between two mappings where the original positions are compared.
  8149. *
  8150. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  8151. * mappings with the same original source/line/column, but different generated
  8152. * line and column the same. Useful when searching for a mapping with a
  8153. * stubbed out mapping.
  8154. */
  8155. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  8156. var cmp = strcmp(mappingA.source, mappingB.source);
  8157. if (cmp !== 0) {
  8158. return cmp;
  8159. }
  8160. cmp = mappingA.originalLine - mappingB.originalLine;
  8161. if (cmp !== 0) {
  8162. return cmp;
  8163. }
  8164. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8165. if (cmp !== 0 || onlyCompareOriginal) {
  8166. return cmp;
  8167. }
  8168. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8169. if (cmp !== 0) {
  8170. return cmp;
  8171. }
  8172. cmp = mappingA.generatedLine - mappingB.generatedLine;
  8173. if (cmp !== 0) {
  8174. return cmp;
  8175. }
  8176. return strcmp(mappingA.name, mappingB.name);
  8177. }
  8178. exports.compareByOriginalPositions = compareByOriginalPositions;
  8179. /**
  8180. * Comparator between two mappings with deflated source and name indices where
  8181. * the generated positions are compared.
  8182. *
  8183. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  8184. * mappings with the same generated line and column, but different
  8185. * source/name/original line and column the same. Useful when searching for a
  8186. * mapping with a stubbed out mapping.
  8187. */
  8188. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  8189. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  8190. if (cmp !== 0) {
  8191. return cmp;
  8192. }
  8193. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8194. if (cmp !== 0 || onlyCompareGenerated) {
  8195. return cmp;
  8196. }
  8197. cmp = strcmp(mappingA.source, mappingB.source);
  8198. if (cmp !== 0) {
  8199. return cmp;
  8200. }
  8201. cmp = mappingA.originalLine - mappingB.originalLine;
  8202. if (cmp !== 0) {
  8203. return cmp;
  8204. }
  8205. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8206. if (cmp !== 0) {
  8207. return cmp;
  8208. }
  8209. return strcmp(mappingA.name, mappingB.name);
  8210. }
  8211. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  8212. function strcmp(aStr1, aStr2) {
  8213. if (aStr1 === aStr2) {
  8214. return 0;
  8215. }
  8216. if (aStr1 === null) {
  8217. return 1; // aStr2 !== null
  8218. }
  8219. if (aStr2 === null) {
  8220. return -1; // aStr1 !== null
  8221. }
  8222. if (aStr1 > aStr2) {
  8223. return 1;
  8224. }
  8225. return -1;
  8226. }
  8227. /**
  8228. * Comparator between two mappings with inflated source and name strings where
  8229. * the generated positions are compared.
  8230. */
  8231. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  8232. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  8233. if (cmp !== 0) {
  8234. return cmp;
  8235. }
  8236. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  8237. if (cmp !== 0) {
  8238. return cmp;
  8239. }
  8240. cmp = strcmp(mappingA.source, mappingB.source);
  8241. if (cmp !== 0) {
  8242. return cmp;
  8243. }
  8244. cmp = mappingA.originalLine - mappingB.originalLine;
  8245. if (cmp !== 0) {
  8246. return cmp;
  8247. }
  8248. cmp = mappingA.originalColumn - mappingB.originalColumn;
  8249. if (cmp !== 0) {
  8250. return cmp;
  8251. }
  8252. return strcmp(mappingA.name, mappingB.name);
  8253. }
  8254. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  8255. /**
  8256. * Strip any JSON XSSI avoidance prefix from the string (as documented
  8257. * in the source maps specification), and then parse the string as
  8258. * JSON.
  8259. */
  8260. function parseSourceMapInput(str) {
  8261. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  8262. }
  8263. exports.parseSourceMapInput = parseSourceMapInput;
  8264. /**
  8265. * Compute the URL of a source given the the source root, the source's
  8266. * URL, and the source map's URL.
  8267. */
  8268. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  8269. sourceURL = sourceURL || '';
  8270. if (sourceRoot) {
  8271. // This follows what Chrome does.
  8272. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  8273. sourceRoot += '/';
  8274. }
  8275. // The spec says:
  8276. // Line 4: An optional source root, useful for relocating source
  8277. // files on a server or removing repeated values in the
  8278. // “sources” entry. This value is prepended to the individual
  8279. // entries in the “source” field.
  8280. sourceURL = sourceRoot + sourceURL;
  8281. }
  8282. // Historically, SourceMapConsumer did not take the sourceMapURL as
  8283. // a parameter. This mode is still somewhat supported, which is why
  8284. // this code block is conditional. However, it's preferable to pass
  8285. // the source map URL to SourceMapConsumer, so that this function
  8286. // can implement the source URL resolution algorithm as outlined in
  8287. // the spec. This block is basically the equivalent of:
  8288. // new URL(sourceURL, sourceMapURL).toString()
  8289. // ... except it avoids using URL, which wasn't available in the
  8290. // older releases of node still supported by this library.
  8291. //
  8292. // The spec says:
  8293. // If the sources are not absolute URLs after prepending of the
  8294. // “sourceRoot”, the sources are resolved relative to the
  8295. // SourceMap (like resolving script src in a html document).
  8296. if (sourceMapURL) {
  8297. var parsed = urlParse(sourceMapURL);
  8298. if (!parsed) {
  8299. throw new Error("sourceMapURL could not be parsed");
  8300. }
  8301. if (parsed.path) {
  8302. // Strip the last path component, but keep the "/".
  8303. var index = parsed.path.lastIndexOf('/');
  8304. if (index >= 0) {
  8305. parsed.path = parsed.path.substring(0, index + 1);
  8306. }
  8307. }
  8308. sourceURL = join(urlGenerate(parsed), sourceURL);
  8309. }
  8310. return normalize(sourceURL);
  8311. }
  8312. exports.computeSourceURL = computeSourceURL;
  8313. } (util$1));
  8314. return util$1;
  8315. }
  8316. var arraySet = {};
  8317. /* -*- Mode: js; js-indent-level: 2; -*- */
  8318. var hasRequiredArraySet;
  8319. function requireArraySet () {
  8320. if (hasRequiredArraySet) return arraySet;
  8321. hasRequiredArraySet = 1;
  8322. /*
  8323. * Copyright 2011 Mozilla Foundation and contributors
  8324. * Licensed under the New BSD license. See LICENSE or:
  8325. * http://opensource.org/licenses/BSD-3-Clause
  8326. */
  8327. var util = /*@__PURE__*/ requireUtil$1();
  8328. var has = Object.prototype.hasOwnProperty;
  8329. var hasNativeMap = typeof Map !== "undefined";
  8330. /**
  8331. * A data structure which is a combination of an array and a set. Adding a new
  8332. * member is O(1), testing for membership is O(1), and finding the index of an
  8333. * element is O(1). Removing elements from the set is not supported. Only
  8334. * strings are supported for membership.
  8335. */
  8336. function ArraySet() {
  8337. this._array = [];
  8338. this._set = hasNativeMap ? new Map() : Object.create(null);
  8339. }
  8340. /**
  8341. * Static method for creating ArraySet instances from an existing array.
  8342. */
  8343. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  8344. var set = new ArraySet();
  8345. for (var i = 0, len = aArray.length; i < len; i++) {
  8346. set.add(aArray[i], aAllowDuplicates);
  8347. }
  8348. return set;
  8349. };
  8350. /**
  8351. * Return how many unique items are in this ArraySet. If duplicates have been
  8352. * added, than those do not count towards the size.
  8353. *
  8354. * @returns Number
  8355. */
  8356. ArraySet.prototype.size = function ArraySet_size() {
  8357. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  8358. };
  8359. /**
  8360. * Add the given string to this set.
  8361. *
  8362. * @param String aStr
  8363. */
  8364. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  8365. var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
  8366. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  8367. var idx = this._array.length;
  8368. if (!isDuplicate || aAllowDuplicates) {
  8369. this._array.push(aStr);
  8370. }
  8371. if (!isDuplicate) {
  8372. if (hasNativeMap) {
  8373. this._set.set(aStr, idx);
  8374. } else {
  8375. this._set[sStr] = idx;
  8376. }
  8377. }
  8378. };
  8379. /**
  8380. * Is the given string a member of this set?
  8381. *
  8382. * @param String aStr
  8383. */
  8384. ArraySet.prototype.has = function ArraySet_has(aStr) {
  8385. if (hasNativeMap) {
  8386. return this._set.has(aStr);
  8387. } else {
  8388. var sStr = util.toSetString(aStr);
  8389. return has.call(this._set, sStr);
  8390. }
  8391. };
  8392. /**
  8393. * What is the index of the given string in the array?
  8394. *
  8395. * @param String aStr
  8396. */
  8397. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  8398. if (hasNativeMap) {
  8399. var idx = this._set.get(aStr);
  8400. if (idx >= 0) {
  8401. return idx;
  8402. }
  8403. } else {
  8404. var sStr = util.toSetString(aStr);
  8405. if (has.call(this._set, sStr)) {
  8406. return this._set[sStr];
  8407. }
  8408. }
  8409. throw new Error('"' + aStr + '" is not in the set.');
  8410. };
  8411. /**
  8412. * What is the element at the given index?
  8413. *
  8414. * @param Number aIdx
  8415. */
  8416. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  8417. if (aIdx >= 0 && aIdx < this._array.length) {
  8418. return this._array[aIdx];
  8419. }
  8420. throw new Error('No element indexed by ' + aIdx);
  8421. };
  8422. /**
  8423. * Returns the array representation of this set (which has the proper indices
  8424. * indicated by indexOf). Note that this is a copy of the internal array used
  8425. * for storing the members so that no one can mess with internal state.
  8426. */
  8427. ArraySet.prototype.toArray = function ArraySet_toArray() {
  8428. return this._array.slice();
  8429. };
  8430. arraySet.ArraySet = ArraySet;
  8431. return arraySet;
  8432. }
  8433. var mappingList = {};
  8434. /* -*- Mode: js; js-indent-level: 2; -*- */
  8435. var hasRequiredMappingList;
  8436. function requireMappingList () {
  8437. if (hasRequiredMappingList) return mappingList;
  8438. hasRequiredMappingList = 1;
  8439. /*
  8440. * Copyright 2014 Mozilla Foundation and contributors
  8441. * Licensed under the New BSD license. See LICENSE or:
  8442. * http://opensource.org/licenses/BSD-3-Clause
  8443. */
  8444. var util = /*@__PURE__*/ requireUtil$1();
  8445. /**
  8446. * Determine whether mappingB is after mappingA with respect to generated
  8447. * position.
  8448. */
  8449. function generatedPositionAfter(mappingA, mappingB) {
  8450. // Optimized for most common case
  8451. var lineA = mappingA.generatedLine;
  8452. var lineB = mappingB.generatedLine;
  8453. var columnA = mappingA.generatedColumn;
  8454. var columnB = mappingB.generatedColumn;
  8455. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  8456. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  8457. }
  8458. /**
  8459. * A data structure to provide a sorted view of accumulated mappings in a
  8460. * performance conscious manner. It trades a neglibable overhead in general
  8461. * case for a large speedup in case of mappings being added in order.
  8462. */
  8463. function MappingList() {
  8464. this._array = [];
  8465. this._sorted = true;
  8466. // Serves as infimum
  8467. this._last = {generatedLine: -1, generatedColumn: 0};
  8468. }
  8469. /**
  8470. * Iterate through internal items. This method takes the same arguments that
  8471. * `Array.prototype.forEach` takes.
  8472. *
  8473. * NOTE: The order of the mappings is NOT guaranteed.
  8474. */
  8475. MappingList.prototype.unsortedForEach =
  8476. function MappingList_forEach(aCallback, aThisArg) {
  8477. this._array.forEach(aCallback, aThisArg);
  8478. };
  8479. /**
  8480. * Add the given source mapping.
  8481. *
  8482. * @param Object aMapping
  8483. */
  8484. MappingList.prototype.add = function MappingList_add(aMapping) {
  8485. if (generatedPositionAfter(this._last, aMapping)) {
  8486. this._last = aMapping;
  8487. this._array.push(aMapping);
  8488. } else {
  8489. this._sorted = false;
  8490. this._array.push(aMapping);
  8491. }
  8492. };
  8493. /**
  8494. * Returns the flat, sorted array of mappings. The mappings are sorted by
  8495. * generated position.
  8496. *
  8497. * WARNING: This method returns internal data without copying, for
  8498. * performance. The return value must NOT be mutated, and should be treated as
  8499. * an immutable borrow. If you want to take ownership, you must make your own
  8500. * copy.
  8501. */
  8502. MappingList.prototype.toArray = function MappingList_toArray() {
  8503. if (!this._sorted) {
  8504. this._array.sort(util.compareByGeneratedPositionsInflated);
  8505. this._sorted = true;
  8506. }
  8507. return this._array;
  8508. };
  8509. mappingList.MappingList = MappingList;
  8510. return mappingList;
  8511. }
  8512. /* -*- Mode: js; js-indent-level: 2; -*- */
  8513. var hasRequiredSourceMapGenerator;
  8514. function requireSourceMapGenerator () {
  8515. if (hasRequiredSourceMapGenerator) return sourceMapGenerator;
  8516. hasRequiredSourceMapGenerator = 1;
  8517. /*
  8518. * Copyright 2011 Mozilla Foundation and contributors
  8519. * Licensed under the New BSD license. See LICENSE or:
  8520. * http://opensource.org/licenses/BSD-3-Clause
  8521. */
  8522. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  8523. var util = /*@__PURE__*/ requireUtil$1();
  8524. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  8525. var MappingList = /*@__PURE__*/ requireMappingList().MappingList;
  8526. /**
  8527. * An instance of the SourceMapGenerator represents a source map which is
  8528. * being built incrementally. You may pass an object with the following
  8529. * properties:
  8530. *
  8531. * - file: The filename of the generated source.
  8532. * - sourceRoot: A root for all relative URLs in this source map.
  8533. */
  8534. function SourceMapGenerator(aArgs) {
  8535. if (!aArgs) {
  8536. aArgs = {};
  8537. }
  8538. this._file = util.getArg(aArgs, 'file', null);
  8539. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  8540. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  8541. this._sources = new ArraySet();
  8542. this._names = new ArraySet();
  8543. this._mappings = new MappingList();
  8544. this._sourcesContents = null;
  8545. }
  8546. SourceMapGenerator.prototype._version = 3;
  8547. /**
  8548. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  8549. *
  8550. * @param aSourceMapConsumer The SourceMap.
  8551. */
  8552. SourceMapGenerator.fromSourceMap =
  8553. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  8554. var sourceRoot = aSourceMapConsumer.sourceRoot;
  8555. var generator = new SourceMapGenerator({
  8556. file: aSourceMapConsumer.file,
  8557. sourceRoot: sourceRoot
  8558. });
  8559. aSourceMapConsumer.eachMapping(function (mapping) {
  8560. var newMapping = {
  8561. generated: {
  8562. line: mapping.generatedLine,
  8563. column: mapping.generatedColumn
  8564. }
  8565. };
  8566. if (mapping.source != null) {
  8567. newMapping.source = mapping.source;
  8568. if (sourceRoot != null) {
  8569. newMapping.source = util.relative(sourceRoot, newMapping.source);
  8570. }
  8571. newMapping.original = {
  8572. line: mapping.originalLine,
  8573. column: mapping.originalColumn
  8574. };
  8575. if (mapping.name != null) {
  8576. newMapping.name = mapping.name;
  8577. }
  8578. }
  8579. generator.addMapping(newMapping);
  8580. });
  8581. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8582. var sourceRelative = sourceFile;
  8583. if (sourceRoot !== null) {
  8584. sourceRelative = util.relative(sourceRoot, sourceFile);
  8585. }
  8586. if (!generator._sources.has(sourceRelative)) {
  8587. generator._sources.add(sourceRelative);
  8588. }
  8589. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8590. if (content != null) {
  8591. generator.setSourceContent(sourceFile, content);
  8592. }
  8593. });
  8594. return generator;
  8595. };
  8596. /**
  8597. * Add a single mapping from original source line and column to the generated
  8598. * source's line and column for this source map being created. The mapping
  8599. * object should have the following properties:
  8600. *
  8601. * - generated: An object with the generated line and column positions.
  8602. * - original: An object with the original line and column positions.
  8603. * - source: The original source file (relative to the sourceRoot).
  8604. * - name: An optional original token name for this mapping.
  8605. */
  8606. SourceMapGenerator.prototype.addMapping =
  8607. function SourceMapGenerator_addMapping(aArgs) {
  8608. var generated = util.getArg(aArgs, 'generated');
  8609. var original = util.getArg(aArgs, 'original', null);
  8610. var source = util.getArg(aArgs, 'source', null);
  8611. var name = util.getArg(aArgs, 'name', null);
  8612. if (!this._skipValidation) {
  8613. this._validateMapping(generated, original, source, name);
  8614. }
  8615. if (source != null) {
  8616. source = String(source);
  8617. if (!this._sources.has(source)) {
  8618. this._sources.add(source);
  8619. }
  8620. }
  8621. if (name != null) {
  8622. name = String(name);
  8623. if (!this._names.has(name)) {
  8624. this._names.add(name);
  8625. }
  8626. }
  8627. this._mappings.add({
  8628. generatedLine: generated.line,
  8629. generatedColumn: generated.column,
  8630. originalLine: original != null && original.line,
  8631. originalColumn: original != null && original.column,
  8632. source: source,
  8633. name: name
  8634. });
  8635. };
  8636. /**
  8637. * Set the source content for a source file.
  8638. */
  8639. SourceMapGenerator.prototype.setSourceContent =
  8640. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  8641. var source = aSourceFile;
  8642. if (this._sourceRoot != null) {
  8643. source = util.relative(this._sourceRoot, source);
  8644. }
  8645. if (aSourceContent != null) {
  8646. // Add the source content to the _sourcesContents map.
  8647. // Create a new _sourcesContents map if the property is null.
  8648. if (!this._sourcesContents) {
  8649. this._sourcesContents = Object.create(null);
  8650. }
  8651. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  8652. } else if (this._sourcesContents) {
  8653. // Remove the source file from the _sourcesContents map.
  8654. // If the _sourcesContents map is empty, set the property to null.
  8655. delete this._sourcesContents[util.toSetString(source)];
  8656. if (Object.keys(this._sourcesContents).length === 0) {
  8657. this._sourcesContents = null;
  8658. }
  8659. }
  8660. };
  8661. /**
  8662. * Applies the mappings of a sub-source-map for a specific source file to the
  8663. * source map being generated. Each mapping to the supplied source file is
  8664. * rewritten using the supplied source map. Note: The resolution for the
  8665. * resulting mappings is the minimium of this map and the supplied map.
  8666. *
  8667. * @param aSourceMapConsumer The source map to be applied.
  8668. * @param aSourceFile Optional. The filename of the source file.
  8669. * If omitted, SourceMapConsumer's file property will be used.
  8670. * @param aSourceMapPath Optional. The dirname of the path to the source map
  8671. * to be applied. If relative, it is relative to the SourceMapConsumer.
  8672. * This parameter is needed when the two source maps aren't in the same
  8673. * directory, and the source map to be applied contains relative source
  8674. * paths. If so, those relative source paths need to be rewritten
  8675. * relative to the SourceMapGenerator.
  8676. */
  8677. SourceMapGenerator.prototype.applySourceMap =
  8678. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  8679. var sourceFile = aSourceFile;
  8680. // If aSourceFile is omitted, we will use the file property of the SourceMap
  8681. if (aSourceFile == null) {
  8682. if (aSourceMapConsumer.file == null) {
  8683. throw new Error(
  8684. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  8685. 'or the source map\'s "file" property. Both were omitted.'
  8686. );
  8687. }
  8688. sourceFile = aSourceMapConsumer.file;
  8689. }
  8690. var sourceRoot = this._sourceRoot;
  8691. // Make "sourceFile" relative if an absolute Url is passed.
  8692. if (sourceRoot != null) {
  8693. sourceFile = util.relative(sourceRoot, sourceFile);
  8694. }
  8695. // Applying the SourceMap can add and remove items from the sources and
  8696. // the names array.
  8697. var newSources = new ArraySet();
  8698. var newNames = new ArraySet();
  8699. // Find mappings for the "sourceFile"
  8700. this._mappings.unsortedForEach(function (mapping) {
  8701. if (mapping.source === sourceFile && mapping.originalLine != null) {
  8702. // Check if it can be mapped by the source map, then update the mapping.
  8703. var original = aSourceMapConsumer.originalPositionFor({
  8704. line: mapping.originalLine,
  8705. column: mapping.originalColumn
  8706. });
  8707. if (original.source != null) {
  8708. // Copy mapping
  8709. mapping.source = original.source;
  8710. if (aSourceMapPath != null) {
  8711. mapping.source = util.join(aSourceMapPath, mapping.source);
  8712. }
  8713. if (sourceRoot != null) {
  8714. mapping.source = util.relative(sourceRoot, mapping.source);
  8715. }
  8716. mapping.originalLine = original.line;
  8717. mapping.originalColumn = original.column;
  8718. if (original.name != null) {
  8719. mapping.name = original.name;
  8720. }
  8721. }
  8722. }
  8723. var source = mapping.source;
  8724. if (source != null && !newSources.has(source)) {
  8725. newSources.add(source);
  8726. }
  8727. var name = mapping.name;
  8728. if (name != null && !newNames.has(name)) {
  8729. newNames.add(name);
  8730. }
  8731. }, this);
  8732. this._sources = newSources;
  8733. this._names = newNames;
  8734. // Copy sourcesContents of applied map.
  8735. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  8736. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  8737. if (content != null) {
  8738. if (aSourceMapPath != null) {
  8739. sourceFile = util.join(aSourceMapPath, sourceFile);
  8740. }
  8741. if (sourceRoot != null) {
  8742. sourceFile = util.relative(sourceRoot, sourceFile);
  8743. }
  8744. this.setSourceContent(sourceFile, content);
  8745. }
  8746. }, this);
  8747. };
  8748. /**
  8749. * A mapping can have one of the three levels of data:
  8750. *
  8751. * 1. Just the generated position.
  8752. * 2. The Generated position, original position, and original source.
  8753. * 3. Generated and original position, original source, as well as a name
  8754. * token.
  8755. *
  8756. * To maintain consistency, we validate that any new mapping being added falls
  8757. * in to one of these categories.
  8758. */
  8759. SourceMapGenerator.prototype._validateMapping =
  8760. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  8761. aName) {
  8762. // When aOriginal is truthy but has empty values for .line and .column,
  8763. // it is most likely a programmer error. In this case we throw a very
  8764. // specific error message to try to guide them the right way.
  8765. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  8766. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  8767. throw new Error(
  8768. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  8769. 'the original mapping entirely and only map the generated position. If so, pass ' +
  8770. 'null for the original mapping instead of an object with empty or null values.'
  8771. );
  8772. }
  8773. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8774. && aGenerated.line > 0 && aGenerated.column >= 0
  8775. && !aOriginal && !aSource && !aName) {
  8776. // Case 1.
  8777. return;
  8778. }
  8779. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  8780. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  8781. && aGenerated.line > 0 && aGenerated.column >= 0
  8782. && aOriginal.line > 0 && aOriginal.column >= 0
  8783. && aSource) {
  8784. // Cases 2 and 3.
  8785. return;
  8786. }
  8787. else {
  8788. throw new Error('Invalid mapping: ' + JSON.stringify({
  8789. generated: aGenerated,
  8790. source: aSource,
  8791. original: aOriginal,
  8792. name: aName
  8793. }));
  8794. }
  8795. };
  8796. /**
  8797. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  8798. * specified by the source map format.
  8799. */
  8800. SourceMapGenerator.prototype._serializeMappings =
  8801. function SourceMapGenerator_serializeMappings() {
  8802. var previousGeneratedColumn = 0;
  8803. var previousGeneratedLine = 1;
  8804. var previousOriginalColumn = 0;
  8805. var previousOriginalLine = 0;
  8806. var previousName = 0;
  8807. var previousSource = 0;
  8808. var result = '';
  8809. var next;
  8810. var mapping;
  8811. var nameIdx;
  8812. var sourceIdx;
  8813. var mappings = this._mappings.toArray();
  8814. for (var i = 0, len = mappings.length; i < len; i++) {
  8815. mapping = mappings[i];
  8816. next = '';
  8817. if (mapping.generatedLine !== previousGeneratedLine) {
  8818. previousGeneratedColumn = 0;
  8819. while (mapping.generatedLine !== previousGeneratedLine) {
  8820. next += ';';
  8821. previousGeneratedLine++;
  8822. }
  8823. }
  8824. else {
  8825. if (i > 0) {
  8826. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  8827. continue;
  8828. }
  8829. next += ',';
  8830. }
  8831. }
  8832. next += base64VLQ.encode(mapping.generatedColumn
  8833. - previousGeneratedColumn);
  8834. previousGeneratedColumn = mapping.generatedColumn;
  8835. if (mapping.source != null) {
  8836. sourceIdx = this._sources.indexOf(mapping.source);
  8837. next += base64VLQ.encode(sourceIdx - previousSource);
  8838. previousSource = sourceIdx;
  8839. // lines are stored 0-based in SourceMap spec version 3
  8840. next += base64VLQ.encode(mapping.originalLine - 1
  8841. - previousOriginalLine);
  8842. previousOriginalLine = mapping.originalLine - 1;
  8843. next += base64VLQ.encode(mapping.originalColumn
  8844. - previousOriginalColumn);
  8845. previousOriginalColumn = mapping.originalColumn;
  8846. if (mapping.name != null) {
  8847. nameIdx = this._names.indexOf(mapping.name);
  8848. next += base64VLQ.encode(nameIdx - previousName);
  8849. previousName = nameIdx;
  8850. }
  8851. }
  8852. result += next;
  8853. }
  8854. return result;
  8855. };
  8856. SourceMapGenerator.prototype._generateSourcesContent =
  8857. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  8858. return aSources.map(function (source) {
  8859. if (!this._sourcesContents) {
  8860. return null;
  8861. }
  8862. if (aSourceRoot != null) {
  8863. source = util.relative(aSourceRoot, source);
  8864. }
  8865. var key = util.toSetString(source);
  8866. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  8867. ? this._sourcesContents[key]
  8868. : null;
  8869. }, this);
  8870. };
  8871. /**
  8872. * Externalize the source map.
  8873. */
  8874. SourceMapGenerator.prototype.toJSON =
  8875. function SourceMapGenerator_toJSON() {
  8876. var map = {
  8877. version: this._version,
  8878. sources: this._sources.toArray(),
  8879. names: this._names.toArray(),
  8880. mappings: this._serializeMappings()
  8881. };
  8882. if (this._file != null) {
  8883. map.file = this._file;
  8884. }
  8885. if (this._sourceRoot != null) {
  8886. map.sourceRoot = this._sourceRoot;
  8887. }
  8888. if (this._sourcesContents) {
  8889. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  8890. }
  8891. return map;
  8892. };
  8893. /**
  8894. * Render the source map being generated to a string.
  8895. */
  8896. SourceMapGenerator.prototype.toString =
  8897. function SourceMapGenerator_toString() {
  8898. return JSON.stringify(this.toJSON());
  8899. };
  8900. sourceMapGenerator.SourceMapGenerator = SourceMapGenerator;
  8901. return sourceMapGenerator;
  8902. }
  8903. var sourceMapConsumer = {};
  8904. var binarySearch = {};
  8905. /* -*- Mode: js; js-indent-level: 2; -*- */
  8906. var hasRequiredBinarySearch;
  8907. function requireBinarySearch () {
  8908. if (hasRequiredBinarySearch) return binarySearch;
  8909. hasRequiredBinarySearch = 1;
  8910. (function (exports) {
  8911. /*
  8912. * Copyright 2011 Mozilla Foundation and contributors
  8913. * Licensed under the New BSD license. See LICENSE or:
  8914. * http://opensource.org/licenses/BSD-3-Clause
  8915. */
  8916. exports.GREATEST_LOWER_BOUND = 1;
  8917. exports.LEAST_UPPER_BOUND = 2;
  8918. /**
  8919. * Recursive implementation of binary search.
  8920. *
  8921. * @param aLow Indices here and lower do not contain the needle.
  8922. * @param aHigh Indices here and higher do not contain the needle.
  8923. * @param aNeedle The element being searched for.
  8924. * @param aHaystack The non-empty array being searched.
  8925. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  8926. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  8927. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  8928. * closest element that is smaller than or greater than the one we are
  8929. * searching for, respectively, if the exact element cannot be found.
  8930. */
  8931. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  8932. // This function terminates when one of the following is true:
  8933. //
  8934. // 1. We find the exact element we are looking for.
  8935. //
  8936. // 2. We did not find the exact element, but we can return the index of
  8937. // the next-closest element.
  8938. //
  8939. // 3. We did not find the exact element, and there is no next-closest
  8940. // element than the one we are searching for, so we return -1.
  8941. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  8942. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  8943. if (cmp === 0) {
  8944. // Found the element we are looking for.
  8945. return mid;
  8946. }
  8947. else if (cmp > 0) {
  8948. // Our needle is greater than aHaystack[mid].
  8949. if (aHigh - mid > 1) {
  8950. // The element is in the upper half.
  8951. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  8952. }
  8953. // The exact needle element was not found in this haystack. Determine if
  8954. // we are in termination case (3) or (2) and return the appropriate thing.
  8955. if (aBias == exports.LEAST_UPPER_BOUND) {
  8956. return aHigh < aHaystack.length ? aHigh : -1;
  8957. } else {
  8958. return mid;
  8959. }
  8960. }
  8961. else {
  8962. // Our needle is less than aHaystack[mid].
  8963. if (mid - aLow > 1) {
  8964. // The element is in the lower half.
  8965. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  8966. }
  8967. // we are in termination case (3) or (2) and return the appropriate thing.
  8968. if (aBias == exports.LEAST_UPPER_BOUND) {
  8969. return mid;
  8970. } else {
  8971. return aLow < 0 ? -1 : aLow;
  8972. }
  8973. }
  8974. }
  8975. /**
  8976. * This is an implementation of binary search which will always try and return
  8977. * the index of the closest element if there is no exact hit. This is because
  8978. * mappings between original and generated line/col pairs are single points,
  8979. * and there is an implicit region between each of them, so a miss just means
  8980. * that you aren't on the very start of a region.
  8981. *
  8982. * @param aNeedle The element you are looking for.
  8983. * @param aHaystack The array that is being searched.
  8984. * @param aCompare A function which takes the needle and an element in the
  8985. * array and returns -1, 0, or 1 depending on whether the needle is less
  8986. * than, equal to, or greater than the element, respectively.
  8987. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  8988. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  8989. * closest element that is smaller than or greater than the one we are
  8990. * searching for, respectively, if the exact element cannot be found.
  8991. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  8992. */
  8993. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  8994. if (aHaystack.length === 0) {
  8995. return -1;
  8996. }
  8997. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  8998. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  8999. if (index < 0) {
  9000. return -1;
  9001. }
  9002. // We have found either the exact element, or the next-closest element than
  9003. // the one we are searching for. However, there may be more than one such
  9004. // element. Make sure we always return the smallest of these.
  9005. while (index - 1 >= 0) {
  9006. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  9007. break;
  9008. }
  9009. --index;
  9010. }
  9011. return index;
  9012. };
  9013. } (binarySearch));
  9014. return binarySearch;
  9015. }
  9016. var quickSort = {};
  9017. /* -*- Mode: js; js-indent-level: 2; -*- */
  9018. var hasRequiredQuickSort;
  9019. function requireQuickSort () {
  9020. if (hasRequiredQuickSort) return quickSort;
  9021. hasRequiredQuickSort = 1;
  9022. /*
  9023. * Copyright 2011 Mozilla Foundation and contributors
  9024. * Licensed under the New BSD license. See LICENSE or:
  9025. * http://opensource.org/licenses/BSD-3-Clause
  9026. */
  9027. // It turns out that some (most?) JavaScript engines don't self-host
  9028. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  9029. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  9030. // custom comparator function, calling back and forth between the VM's C++ and
  9031. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  9032. // worse generated code for the comparator function than would be optimal. In
  9033. // fact, when sorting with a comparator, these costs outweigh the benefits of
  9034. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  9035. // a ~3500ms mean speed-up in `bench/bench.html`.
  9036. /**
  9037. * Swap the elements indexed by `x` and `y` in the array `ary`.
  9038. *
  9039. * @param {Array} ary
  9040. * The array.
  9041. * @param {Number} x
  9042. * The index of the first item.
  9043. * @param {Number} y
  9044. * The index of the second item.
  9045. */
  9046. function swap(ary, x, y) {
  9047. var temp = ary[x];
  9048. ary[x] = ary[y];
  9049. ary[y] = temp;
  9050. }
  9051. /**
  9052. * Returns a random integer within the range `low .. high` inclusive.
  9053. *
  9054. * @param {Number} low
  9055. * The lower bound on the range.
  9056. * @param {Number} high
  9057. * The upper bound on the range.
  9058. */
  9059. function randomIntInRange(low, high) {
  9060. return Math.round(low + (Math.random() * (high - low)));
  9061. }
  9062. /**
  9063. * The Quick Sort algorithm.
  9064. *
  9065. * @param {Array} ary
  9066. * An array to sort.
  9067. * @param {function} comparator
  9068. * Function to use to compare two items.
  9069. * @param {Number} p
  9070. * Start index of the array
  9071. * @param {Number} r
  9072. * End index of the array
  9073. */
  9074. function doQuickSort(ary, comparator, p, r) {
  9075. // If our lower bound is less than our upper bound, we (1) partition the
  9076. // array into two pieces and (2) recurse on each half. If it is not, this is
  9077. // the empty array and our base case.
  9078. if (p < r) {
  9079. // (1) Partitioning.
  9080. //
  9081. // The partitioning chooses a pivot between `p` and `r` and moves all
  9082. // elements that are less than or equal to the pivot to the before it, and
  9083. // all the elements that are greater than it after it. The effect is that
  9084. // once partition is done, the pivot is in the exact place it will be when
  9085. // the array is put in sorted order, and it will not need to be moved
  9086. // again. This runs in O(n) time.
  9087. // Always choose a random pivot so that an input array which is reverse
  9088. // sorted does not cause O(n^2) running time.
  9089. var pivotIndex = randomIntInRange(p, r);
  9090. var i = p - 1;
  9091. swap(ary, pivotIndex, r);
  9092. var pivot = ary[r];
  9093. // Immediately after `j` is incremented in this loop, the following hold
  9094. // true:
  9095. //
  9096. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  9097. //
  9098. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  9099. for (var j = p; j < r; j++) {
  9100. if (comparator(ary[j], pivot) <= 0) {
  9101. i += 1;
  9102. swap(ary, i, j);
  9103. }
  9104. }
  9105. swap(ary, i + 1, j);
  9106. var q = i + 1;
  9107. // (2) Recurse on each half.
  9108. doQuickSort(ary, comparator, p, q - 1);
  9109. doQuickSort(ary, comparator, q + 1, r);
  9110. }
  9111. }
  9112. /**
  9113. * Sort the given array in-place with the given comparator function.
  9114. *
  9115. * @param {Array} ary
  9116. * An array to sort.
  9117. * @param {function} comparator
  9118. * Function to use to compare two items.
  9119. */
  9120. quickSort.quickSort = function (ary, comparator) {
  9121. doQuickSort(ary, comparator, 0, ary.length - 1);
  9122. };
  9123. return quickSort;
  9124. }
  9125. /* -*- Mode: js; js-indent-level: 2; -*- */
  9126. var hasRequiredSourceMapConsumer;
  9127. function requireSourceMapConsumer () {
  9128. if (hasRequiredSourceMapConsumer) return sourceMapConsumer;
  9129. hasRequiredSourceMapConsumer = 1;
  9130. /*
  9131. * Copyright 2011 Mozilla Foundation and contributors
  9132. * Licensed under the New BSD license. See LICENSE or:
  9133. * http://opensource.org/licenses/BSD-3-Clause
  9134. */
  9135. var util = /*@__PURE__*/ requireUtil$1();
  9136. var binarySearch = /*@__PURE__*/ requireBinarySearch();
  9137. var ArraySet = /*@__PURE__*/ requireArraySet().ArraySet;
  9138. var base64VLQ = /*@__PURE__*/ requireBase64Vlq();
  9139. var quickSort = /*@__PURE__*/ requireQuickSort().quickSort;
  9140. function SourceMapConsumer(aSourceMap, aSourceMapURL) {
  9141. var sourceMap = aSourceMap;
  9142. if (typeof aSourceMap === 'string') {
  9143. sourceMap = util.parseSourceMapInput(aSourceMap);
  9144. }
  9145. return sourceMap.sections != null
  9146. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  9147. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  9148. }
  9149. SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  9150. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  9151. };
  9152. /**
  9153. * The version of the source mapping spec that we are consuming.
  9154. */
  9155. SourceMapConsumer.prototype._version = 3;
  9156. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  9157. // parsed mapping coordinates from the source map's "mappings" attribute. They
  9158. // are lazily instantiated, accessed via the `_generatedMappings` and
  9159. // `_originalMappings` getters respectively, and we only parse the mappings
  9160. // and create these arrays once queried for a source location. We jump through
  9161. // these hoops because there can be many thousands of mappings, and parsing
  9162. // them is expensive, so we only want to do it if we must.
  9163. //
  9164. // Each object in the arrays is of the form:
  9165. //
  9166. // {
  9167. // generatedLine: The line number in the generated code,
  9168. // generatedColumn: The column number in the generated code,
  9169. // source: The path to the original source file that generated this
  9170. // chunk of code,
  9171. // originalLine: The line number in the original source that
  9172. // corresponds to this chunk of generated code,
  9173. // originalColumn: The column number in the original source that
  9174. // corresponds to this chunk of generated code,
  9175. // name: The name of the original symbol which generated this chunk of
  9176. // code.
  9177. // }
  9178. //
  9179. // All properties except for `generatedLine` and `generatedColumn` can be
  9180. // `null`.
  9181. //
  9182. // `_generatedMappings` is ordered by the generated positions.
  9183. //
  9184. // `_originalMappings` is ordered by the original positions.
  9185. SourceMapConsumer.prototype.__generatedMappings = null;
  9186. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  9187. configurable: true,
  9188. enumerable: true,
  9189. get: function () {
  9190. if (!this.__generatedMappings) {
  9191. this._parseMappings(this._mappings, this.sourceRoot);
  9192. }
  9193. return this.__generatedMappings;
  9194. }
  9195. });
  9196. SourceMapConsumer.prototype.__originalMappings = null;
  9197. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  9198. configurable: true,
  9199. enumerable: true,
  9200. get: function () {
  9201. if (!this.__originalMappings) {
  9202. this._parseMappings(this._mappings, this.sourceRoot);
  9203. }
  9204. return this.__originalMappings;
  9205. }
  9206. });
  9207. SourceMapConsumer.prototype._charIsMappingSeparator =
  9208. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  9209. var c = aStr.charAt(index);
  9210. return c === ";" || c === ",";
  9211. };
  9212. /**
  9213. * Parse the mappings in a string in to a data structure which we can easily
  9214. * query (the ordered arrays in the `this.__generatedMappings` and
  9215. * `this.__originalMappings` properties).
  9216. */
  9217. SourceMapConsumer.prototype._parseMappings =
  9218. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9219. throw new Error("Subclasses must implement _parseMappings");
  9220. };
  9221. SourceMapConsumer.GENERATED_ORDER = 1;
  9222. SourceMapConsumer.ORIGINAL_ORDER = 2;
  9223. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  9224. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  9225. /**
  9226. * Iterate over each mapping between an original source/line/column and a
  9227. * generated line/column in this source map.
  9228. *
  9229. * @param Function aCallback
  9230. * The function that is called with each mapping.
  9231. * @param Object aContext
  9232. * Optional. If specified, this object will be the value of `this` every
  9233. * time that `aCallback` is called.
  9234. * @param aOrder
  9235. * Either `SourceMapConsumer.GENERATED_ORDER` or
  9236. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  9237. * iterate over the mappings sorted by the generated file's line/column
  9238. * order or the original's source/line/column order, respectively. Defaults to
  9239. * `SourceMapConsumer.GENERATED_ORDER`.
  9240. */
  9241. SourceMapConsumer.prototype.eachMapping =
  9242. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  9243. var context = aContext || null;
  9244. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  9245. var mappings;
  9246. switch (order) {
  9247. case SourceMapConsumer.GENERATED_ORDER:
  9248. mappings = this._generatedMappings;
  9249. break;
  9250. case SourceMapConsumer.ORIGINAL_ORDER:
  9251. mappings = this._originalMappings;
  9252. break;
  9253. default:
  9254. throw new Error("Unknown order of iteration.");
  9255. }
  9256. var sourceRoot = this.sourceRoot;
  9257. mappings.map(function (mapping) {
  9258. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  9259. source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  9260. return {
  9261. source: source,
  9262. generatedLine: mapping.generatedLine,
  9263. generatedColumn: mapping.generatedColumn,
  9264. originalLine: mapping.originalLine,
  9265. originalColumn: mapping.originalColumn,
  9266. name: mapping.name === null ? null : this._names.at(mapping.name)
  9267. };
  9268. }, this).forEach(aCallback, context);
  9269. };
  9270. /**
  9271. * Returns all generated line and column information for the original source,
  9272. * line, and column provided. If no column is provided, returns all mappings
  9273. * corresponding to a either the line we are searching for or the next
  9274. * closest line that has any mappings. Otherwise, returns all mappings
  9275. * corresponding to the given line and either the column we are searching for
  9276. * or the next closest column that has any offsets.
  9277. *
  9278. * The only argument is an object with the following properties:
  9279. *
  9280. * - source: The filename of the original source.
  9281. * - line: The line number in the original source. The line number is 1-based.
  9282. * - column: Optional. the column number in the original source.
  9283. * The column number is 0-based.
  9284. *
  9285. * and an array of objects is returned, each with the following properties:
  9286. *
  9287. * - line: The line number in the generated source, or null. The
  9288. * line number is 1-based.
  9289. * - column: The column number in the generated source, or null.
  9290. * The column number is 0-based.
  9291. */
  9292. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  9293. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  9294. var line = util.getArg(aArgs, 'line');
  9295. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  9296. // returns the index of the closest mapping less than the needle. By
  9297. // setting needle.originalColumn to 0, we thus find the last mapping for
  9298. // the given line, provided such a mapping exists.
  9299. var needle = {
  9300. source: util.getArg(aArgs, 'source'),
  9301. originalLine: line,
  9302. originalColumn: util.getArg(aArgs, 'column', 0)
  9303. };
  9304. needle.source = this._findSourceIndex(needle.source);
  9305. if (needle.source < 0) {
  9306. return [];
  9307. }
  9308. var mappings = [];
  9309. var index = this._findMapping(needle,
  9310. this._originalMappings,
  9311. "originalLine",
  9312. "originalColumn",
  9313. util.compareByOriginalPositions,
  9314. binarySearch.LEAST_UPPER_BOUND);
  9315. if (index >= 0) {
  9316. var mapping = this._originalMappings[index];
  9317. if (aArgs.column === undefined) {
  9318. var originalLine = mapping.originalLine;
  9319. // Iterate until either we run out of mappings, or we run into
  9320. // a mapping for a different line than the one we found. Since
  9321. // mappings are sorted, this is guaranteed to find all mappings for
  9322. // the line we found.
  9323. while (mapping && mapping.originalLine === originalLine) {
  9324. mappings.push({
  9325. line: util.getArg(mapping, 'generatedLine', null),
  9326. column: util.getArg(mapping, 'generatedColumn', null),
  9327. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9328. });
  9329. mapping = this._originalMappings[++index];
  9330. }
  9331. } else {
  9332. var originalColumn = mapping.originalColumn;
  9333. // Iterate until either we run out of mappings, or we run into
  9334. // a mapping for a different line than the one we were searching for.
  9335. // Since mappings are sorted, this is guaranteed to find all mappings for
  9336. // the line we are searching for.
  9337. while (mapping &&
  9338. mapping.originalLine === line &&
  9339. mapping.originalColumn == originalColumn) {
  9340. mappings.push({
  9341. line: util.getArg(mapping, 'generatedLine', null),
  9342. column: util.getArg(mapping, 'generatedColumn', null),
  9343. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9344. });
  9345. mapping = this._originalMappings[++index];
  9346. }
  9347. }
  9348. }
  9349. return mappings;
  9350. };
  9351. sourceMapConsumer.SourceMapConsumer = SourceMapConsumer;
  9352. /**
  9353. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  9354. * query for information about the original file positions by giving it a file
  9355. * position in the generated source.
  9356. *
  9357. * The first parameter is the raw source map (either as a JSON string, or
  9358. * already parsed to an object). According to the spec, source maps have the
  9359. * following attributes:
  9360. *
  9361. * - version: Which version of the source map spec this map is following.
  9362. * - sources: An array of URLs to the original source files.
  9363. * - names: An array of identifiers which can be referrenced by individual mappings.
  9364. * - sourceRoot: Optional. The URL root from which all sources are relative.
  9365. * - sourcesContent: Optional. An array of contents of the original source files.
  9366. * - mappings: A string of base64 VLQs which contain the actual mappings.
  9367. * - file: Optional. The generated file this source map is associated with.
  9368. *
  9369. * Here is an example source map, taken from the source map spec[0]:
  9370. *
  9371. * {
  9372. * version : 3,
  9373. * file: "out.js",
  9374. * sourceRoot : "",
  9375. * sources: ["foo.js", "bar.js"],
  9376. * names: ["src", "maps", "are", "fun"],
  9377. * mappings: "AA,AB;;ABCDE;"
  9378. * }
  9379. *
  9380. * The second parameter, if given, is a string whose value is the URL
  9381. * at which the source map was found. This URL is used to compute the
  9382. * sources array.
  9383. *
  9384. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  9385. */
  9386. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  9387. var sourceMap = aSourceMap;
  9388. if (typeof aSourceMap === 'string') {
  9389. sourceMap = util.parseSourceMapInput(aSourceMap);
  9390. }
  9391. var version = util.getArg(sourceMap, 'version');
  9392. var sources = util.getArg(sourceMap, 'sources');
  9393. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  9394. // requires the array) to play nice here.
  9395. var names = util.getArg(sourceMap, 'names', []);
  9396. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  9397. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  9398. var mappings = util.getArg(sourceMap, 'mappings');
  9399. var file = util.getArg(sourceMap, 'file', null);
  9400. // Once again, Sass deviates from the spec and supplies the version as a
  9401. // string rather than a number, so we use loose equality checking here.
  9402. if (version != this._version) {
  9403. throw new Error('Unsupported version: ' + version);
  9404. }
  9405. if (sourceRoot) {
  9406. sourceRoot = util.normalize(sourceRoot);
  9407. }
  9408. sources = sources
  9409. .map(String)
  9410. // Some source maps produce relative source paths like "./foo.js" instead of
  9411. // "foo.js". Normalize these first so that future comparisons will succeed.
  9412. // See bugzil.la/1090768.
  9413. .map(util.normalize)
  9414. // Always ensure that absolute sources are internally stored relative to
  9415. // the source root, if the source root is absolute. Not doing this would
  9416. // be particularly problematic when the source root is a prefix of the
  9417. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  9418. .map(function (source) {
  9419. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  9420. ? util.relative(sourceRoot, source)
  9421. : source;
  9422. });
  9423. // Pass `true` below to allow duplicate names and sources. While source maps
  9424. // are intended to be compressed and deduplicated, the TypeScript compiler
  9425. // sometimes generates source maps with duplicates in them. See Github issue
  9426. // #72 and bugzil.la/889492.
  9427. this._names = ArraySet.fromArray(names.map(String), true);
  9428. this._sources = ArraySet.fromArray(sources, true);
  9429. this._absoluteSources = this._sources.toArray().map(function (s) {
  9430. return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
  9431. });
  9432. this.sourceRoot = sourceRoot;
  9433. this.sourcesContent = sourcesContent;
  9434. this._mappings = mappings;
  9435. this._sourceMapURL = aSourceMapURL;
  9436. this.file = file;
  9437. }
  9438. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  9439. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  9440. /**
  9441. * Utility function to find the index of a source. Returns -1 if not
  9442. * found.
  9443. */
  9444. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  9445. var relativeSource = aSource;
  9446. if (this.sourceRoot != null) {
  9447. relativeSource = util.relative(this.sourceRoot, relativeSource);
  9448. }
  9449. if (this._sources.has(relativeSource)) {
  9450. return this._sources.indexOf(relativeSource);
  9451. }
  9452. // Maybe aSource is an absolute URL as returned by |sources|. In
  9453. // this case we can't simply undo the transform.
  9454. var i;
  9455. for (i = 0; i < this._absoluteSources.length; ++i) {
  9456. if (this._absoluteSources[i] == aSource) {
  9457. return i;
  9458. }
  9459. }
  9460. return -1;
  9461. };
  9462. /**
  9463. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  9464. *
  9465. * @param SourceMapGenerator aSourceMap
  9466. * The source map that will be consumed.
  9467. * @param String aSourceMapURL
  9468. * The URL at which the source map can be found (optional)
  9469. * @returns BasicSourceMapConsumer
  9470. */
  9471. BasicSourceMapConsumer.fromSourceMap =
  9472. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  9473. var smc = Object.create(BasicSourceMapConsumer.prototype);
  9474. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  9475. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  9476. smc.sourceRoot = aSourceMap._sourceRoot;
  9477. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  9478. smc.sourceRoot);
  9479. smc.file = aSourceMap._file;
  9480. smc._sourceMapURL = aSourceMapURL;
  9481. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  9482. return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  9483. });
  9484. // Because we are modifying the entries (by converting string sources and
  9485. // names to indices into the sources and names ArraySets), we have to make
  9486. // a copy of the entry or else bad things happen. Shared mutable state
  9487. // strikes again! See github issue #191.
  9488. var generatedMappings = aSourceMap._mappings.toArray().slice();
  9489. var destGeneratedMappings = smc.__generatedMappings = [];
  9490. var destOriginalMappings = smc.__originalMappings = [];
  9491. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  9492. var srcMapping = generatedMappings[i];
  9493. var destMapping = new Mapping;
  9494. destMapping.generatedLine = srcMapping.generatedLine;
  9495. destMapping.generatedColumn = srcMapping.generatedColumn;
  9496. if (srcMapping.source) {
  9497. destMapping.source = sources.indexOf(srcMapping.source);
  9498. destMapping.originalLine = srcMapping.originalLine;
  9499. destMapping.originalColumn = srcMapping.originalColumn;
  9500. if (srcMapping.name) {
  9501. destMapping.name = names.indexOf(srcMapping.name);
  9502. }
  9503. destOriginalMappings.push(destMapping);
  9504. }
  9505. destGeneratedMappings.push(destMapping);
  9506. }
  9507. quickSort(smc.__originalMappings, util.compareByOriginalPositions);
  9508. return smc;
  9509. };
  9510. /**
  9511. * The version of the source mapping spec that we are consuming.
  9512. */
  9513. BasicSourceMapConsumer.prototype._version = 3;
  9514. /**
  9515. * The list of original sources.
  9516. */
  9517. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  9518. get: function () {
  9519. return this._absoluteSources.slice();
  9520. }
  9521. });
  9522. /**
  9523. * Provide the JIT with a nice shape / hidden class.
  9524. */
  9525. function Mapping() {
  9526. this.generatedLine = 0;
  9527. this.generatedColumn = 0;
  9528. this.source = null;
  9529. this.originalLine = null;
  9530. this.originalColumn = null;
  9531. this.name = null;
  9532. }
  9533. /**
  9534. * Parse the mappings in a string in to a data structure which we can easily
  9535. * query (the ordered arrays in the `this.__generatedMappings` and
  9536. * `this.__originalMappings` properties).
  9537. */
  9538. BasicSourceMapConsumer.prototype._parseMappings =
  9539. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  9540. var generatedLine = 1;
  9541. var previousGeneratedColumn = 0;
  9542. var previousOriginalLine = 0;
  9543. var previousOriginalColumn = 0;
  9544. var previousSource = 0;
  9545. var previousName = 0;
  9546. var length = aStr.length;
  9547. var index = 0;
  9548. var cachedSegments = {};
  9549. var temp = {};
  9550. var originalMappings = [];
  9551. var generatedMappings = [];
  9552. var mapping, str, segment, end, value;
  9553. while (index < length) {
  9554. if (aStr.charAt(index) === ';') {
  9555. generatedLine++;
  9556. index++;
  9557. previousGeneratedColumn = 0;
  9558. }
  9559. else if (aStr.charAt(index) === ',') {
  9560. index++;
  9561. }
  9562. else {
  9563. mapping = new Mapping();
  9564. mapping.generatedLine = generatedLine;
  9565. // Because each offset is encoded relative to the previous one,
  9566. // many segments often have the same encoding. We can exploit this
  9567. // fact by caching the parsed variable length fields of each segment,
  9568. // allowing us to avoid a second parse if we encounter the same
  9569. // segment again.
  9570. for (end = index; end < length; end++) {
  9571. if (this._charIsMappingSeparator(aStr, end)) {
  9572. break;
  9573. }
  9574. }
  9575. str = aStr.slice(index, end);
  9576. segment = cachedSegments[str];
  9577. if (segment) {
  9578. index += str.length;
  9579. } else {
  9580. segment = [];
  9581. while (index < end) {
  9582. base64VLQ.decode(aStr, index, temp);
  9583. value = temp.value;
  9584. index = temp.rest;
  9585. segment.push(value);
  9586. }
  9587. if (segment.length === 2) {
  9588. throw new Error('Found a source, but no line and column');
  9589. }
  9590. if (segment.length === 3) {
  9591. throw new Error('Found a source and line, but no column');
  9592. }
  9593. cachedSegments[str] = segment;
  9594. }
  9595. // Generated column.
  9596. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  9597. previousGeneratedColumn = mapping.generatedColumn;
  9598. if (segment.length > 1) {
  9599. // Original source.
  9600. mapping.source = previousSource + segment[1];
  9601. previousSource += segment[1];
  9602. // Original line.
  9603. mapping.originalLine = previousOriginalLine + segment[2];
  9604. previousOriginalLine = mapping.originalLine;
  9605. // Lines are stored 0-based
  9606. mapping.originalLine += 1;
  9607. // Original column.
  9608. mapping.originalColumn = previousOriginalColumn + segment[3];
  9609. previousOriginalColumn = mapping.originalColumn;
  9610. if (segment.length > 4) {
  9611. // Original name.
  9612. mapping.name = previousName + segment[4];
  9613. previousName += segment[4];
  9614. }
  9615. }
  9616. generatedMappings.push(mapping);
  9617. if (typeof mapping.originalLine === 'number') {
  9618. originalMappings.push(mapping);
  9619. }
  9620. }
  9621. }
  9622. quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
  9623. this.__generatedMappings = generatedMappings;
  9624. quickSort(originalMappings, util.compareByOriginalPositions);
  9625. this.__originalMappings = originalMappings;
  9626. };
  9627. /**
  9628. * Find the mapping that best matches the hypothetical "needle" mapping that
  9629. * we are searching for in the given "haystack" of mappings.
  9630. */
  9631. BasicSourceMapConsumer.prototype._findMapping =
  9632. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  9633. aColumnName, aComparator, aBias) {
  9634. // To return the position we are searching for, we must first find the
  9635. // mapping for the given position and then return the opposite position it
  9636. // points to. Because the mappings are sorted, we can use binary search to
  9637. // find the best mapping.
  9638. if (aNeedle[aLineName] <= 0) {
  9639. throw new TypeError('Line must be greater than or equal to 1, got '
  9640. + aNeedle[aLineName]);
  9641. }
  9642. if (aNeedle[aColumnName] < 0) {
  9643. throw new TypeError('Column must be greater than or equal to 0, got '
  9644. + aNeedle[aColumnName]);
  9645. }
  9646. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  9647. };
  9648. /**
  9649. * Compute the last column for each generated mapping. The last column is
  9650. * inclusive.
  9651. */
  9652. BasicSourceMapConsumer.prototype.computeColumnSpans =
  9653. function SourceMapConsumer_computeColumnSpans() {
  9654. for (var index = 0; index < this._generatedMappings.length; ++index) {
  9655. var mapping = this._generatedMappings[index];
  9656. // Mappings do not contain a field for the last generated columnt. We
  9657. // can come up with an optimistic estimate, however, by assuming that
  9658. // mappings are contiguous (i.e. given two consecutive mappings, the
  9659. // first mapping ends where the second one starts).
  9660. if (index + 1 < this._generatedMappings.length) {
  9661. var nextMapping = this._generatedMappings[index + 1];
  9662. if (mapping.generatedLine === nextMapping.generatedLine) {
  9663. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  9664. continue;
  9665. }
  9666. }
  9667. // The last mapping for each line spans the entire line.
  9668. mapping.lastGeneratedColumn = Infinity;
  9669. }
  9670. };
  9671. /**
  9672. * Returns the original source, line, and column information for the generated
  9673. * source's line and column positions provided. The only argument is an object
  9674. * with the following properties:
  9675. *
  9676. * - line: The line number in the generated source. The line number
  9677. * is 1-based.
  9678. * - column: The column number in the generated source. The column
  9679. * number is 0-based.
  9680. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  9681. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  9682. * closest element that is smaller than or greater than the one we are
  9683. * searching for, respectively, if the exact element cannot be found.
  9684. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  9685. *
  9686. * and an object is returned with the following properties:
  9687. *
  9688. * - source: The original source file, or null.
  9689. * - line: The line number in the original source, or null. The
  9690. * line number is 1-based.
  9691. * - column: The column number in the original source, or null. The
  9692. * column number is 0-based.
  9693. * - name: The original identifier, or null.
  9694. */
  9695. BasicSourceMapConsumer.prototype.originalPositionFor =
  9696. function SourceMapConsumer_originalPositionFor(aArgs) {
  9697. var needle = {
  9698. generatedLine: util.getArg(aArgs, 'line'),
  9699. generatedColumn: util.getArg(aArgs, 'column')
  9700. };
  9701. var index = this._findMapping(
  9702. needle,
  9703. this._generatedMappings,
  9704. "generatedLine",
  9705. "generatedColumn",
  9706. util.compareByGeneratedPositionsDeflated,
  9707. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  9708. );
  9709. if (index >= 0) {
  9710. var mapping = this._generatedMappings[index];
  9711. if (mapping.generatedLine === needle.generatedLine) {
  9712. var source = util.getArg(mapping, 'source', null);
  9713. if (source !== null) {
  9714. source = this._sources.at(source);
  9715. source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  9716. }
  9717. var name = util.getArg(mapping, 'name', null);
  9718. if (name !== null) {
  9719. name = this._names.at(name);
  9720. }
  9721. return {
  9722. source: source,
  9723. line: util.getArg(mapping, 'originalLine', null),
  9724. column: util.getArg(mapping, 'originalColumn', null),
  9725. name: name
  9726. };
  9727. }
  9728. }
  9729. return {
  9730. source: null,
  9731. line: null,
  9732. column: null,
  9733. name: null
  9734. };
  9735. };
  9736. /**
  9737. * Return true if we have the source content for every source in the source
  9738. * map, false otherwise.
  9739. */
  9740. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  9741. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  9742. if (!this.sourcesContent) {
  9743. return false;
  9744. }
  9745. return this.sourcesContent.length >= this._sources.size() &&
  9746. !this.sourcesContent.some(function (sc) { return sc == null; });
  9747. };
  9748. /**
  9749. * Returns the original source content. The only argument is the url of the
  9750. * original source file. Returns null if no original source content is
  9751. * available.
  9752. */
  9753. BasicSourceMapConsumer.prototype.sourceContentFor =
  9754. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  9755. if (!this.sourcesContent) {
  9756. return null;
  9757. }
  9758. var index = this._findSourceIndex(aSource);
  9759. if (index >= 0) {
  9760. return this.sourcesContent[index];
  9761. }
  9762. var relativeSource = aSource;
  9763. if (this.sourceRoot != null) {
  9764. relativeSource = util.relative(this.sourceRoot, relativeSource);
  9765. }
  9766. var url;
  9767. if (this.sourceRoot != null
  9768. && (url = util.urlParse(this.sourceRoot))) {
  9769. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  9770. // many users. We can help them out when they expect file:// URIs to
  9771. // behave like it would if they were running a local HTTP server. See
  9772. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  9773. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  9774. if (url.scheme == "file"
  9775. && this._sources.has(fileUriAbsPath)) {
  9776. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  9777. }
  9778. if ((!url.path || url.path == "/")
  9779. && this._sources.has("/" + relativeSource)) {
  9780. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  9781. }
  9782. }
  9783. // This function is used recursively from
  9784. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  9785. // don't want to throw if we can't find the source - we just want to
  9786. // return null, so we provide a flag to exit gracefully.
  9787. if (nullOnMissing) {
  9788. return null;
  9789. }
  9790. else {
  9791. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  9792. }
  9793. };
  9794. /**
  9795. * Returns the generated line and column information for the original source,
  9796. * line, and column positions provided. The only argument is an object with
  9797. * the following properties:
  9798. *
  9799. * - source: The filename of the original source.
  9800. * - line: The line number in the original source. The line number
  9801. * is 1-based.
  9802. * - column: The column number in the original source. The column
  9803. * number is 0-based.
  9804. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  9805. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  9806. * closest element that is smaller than or greater than the one we are
  9807. * searching for, respectively, if the exact element cannot be found.
  9808. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  9809. *
  9810. * and an object is returned with the following properties:
  9811. *
  9812. * - line: The line number in the generated source, or null. The
  9813. * line number is 1-based.
  9814. * - column: The column number in the generated source, or null.
  9815. * The column number is 0-based.
  9816. */
  9817. BasicSourceMapConsumer.prototype.generatedPositionFor =
  9818. function SourceMapConsumer_generatedPositionFor(aArgs) {
  9819. var source = util.getArg(aArgs, 'source');
  9820. source = this._findSourceIndex(source);
  9821. if (source < 0) {
  9822. return {
  9823. line: null,
  9824. column: null,
  9825. lastColumn: null
  9826. };
  9827. }
  9828. var needle = {
  9829. source: source,
  9830. originalLine: util.getArg(aArgs, 'line'),
  9831. originalColumn: util.getArg(aArgs, 'column')
  9832. };
  9833. var index = this._findMapping(
  9834. needle,
  9835. this._originalMappings,
  9836. "originalLine",
  9837. "originalColumn",
  9838. util.compareByOriginalPositions,
  9839. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  9840. );
  9841. if (index >= 0) {
  9842. var mapping = this._originalMappings[index];
  9843. if (mapping.source === needle.source) {
  9844. return {
  9845. line: util.getArg(mapping, 'generatedLine', null),
  9846. column: util.getArg(mapping, 'generatedColumn', null),
  9847. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  9848. };
  9849. }
  9850. }
  9851. return {
  9852. line: null,
  9853. column: null,
  9854. lastColumn: null
  9855. };
  9856. };
  9857. sourceMapConsumer.BasicSourceMapConsumer = BasicSourceMapConsumer;
  9858. /**
  9859. * An IndexedSourceMapConsumer instance represents a parsed source map which
  9860. * we can query for information. It differs from BasicSourceMapConsumer in
  9861. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  9862. * input.
  9863. *
  9864. * The first parameter is a raw source map (either as a JSON string, or already
  9865. * parsed to an object). According to the spec for indexed source maps, they
  9866. * have the following attributes:
  9867. *
  9868. * - version: Which version of the source map spec this map is following.
  9869. * - file: Optional. The generated file this source map is associated with.
  9870. * - sections: A list of section definitions.
  9871. *
  9872. * Each value under the "sections" field has two fields:
  9873. * - offset: The offset into the original specified at which this section
  9874. * begins to apply, defined as an object with a "line" and "column"
  9875. * field.
  9876. * - map: A source map definition. This source map could also be indexed,
  9877. * but doesn't have to be.
  9878. *
  9879. * Instead of the "map" field, it's also possible to have a "url" field
  9880. * specifying a URL to retrieve a source map from, but that's currently
  9881. * unsupported.
  9882. *
  9883. * Here's an example source map, taken from the source map spec[0], but
  9884. * modified to omit a section which uses the "url" field.
  9885. *
  9886. * {
  9887. * version : 3,
  9888. * file: "app.js",
  9889. * sections: [{
  9890. * offset: {line:100, column:10},
  9891. * map: {
  9892. * version : 3,
  9893. * file: "section.js",
  9894. * sources: ["foo.js", "bar.js"],
  9895. * names: ["src", "maps", "are", "fun"],
  9896. * mappings: "AAAA,E;;ABCDE;"
  9897. * }
  9898. * }],
  9899. * }
  9900. *
  9901. * The second parameter, if given, is a string whose value is the URL
  9902. * at which the source map was found. This URL is used to compute the
  9903. * sources array.
  9904. *
  9905. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  9906. */
  9907. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  9908. var sourceMap = aSourceMap;
  9909. if (typeof aSourceMap === 'string') {
  9910. sourceMap = util.parseSourceMapInput(aSourceMap);
  9911. }
  9912. var version = util.getArg(sourceMap, 'version');
  9913. var sections = util.getArg(sourceMap, 'sections');
  9914. if (version != this._version) {
  9915. throw new Error('Unsupported version: ' + version);
  9916. }
  9917. this._sources = new ArraySet();
  9918. this._names = new ArraySet();
  9919. var lastOffset = {
  9920. line: -1,
  9921. column: 0
  9922. };
  9923. this._sections = sections.map(function (s) {
  9924. if (s.url) {
  9925. // The url field will require support for asynchronicity.
  9926. // See https://github.com/mozilla/source-map/issues/16
  9927. throw new Error('Support for url field in sections not implemented.');
  9928. }
  9929. var offset = util.getArg(s, 'offset');
  9930. var offsetLine = util.getArg(offset, 'line');
  9931. var offsetColumn = util.getArg(offset, 'column');
  9932. if (offsetLine < lastOffset.line ||
  9933. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  9934. throw new Error('Section offsets must be ordered and non-overlapping.');
  9935. }
  9936. lastOffset = offset;
  9937. return {
  9938. generatedOffset: {
  9939. // The offset fields are 0-based, but we use 1-based indices when
  9940. // encoding/decoding from VLQ.
  9941. generatedLine: offsetLine + 1,
  9942. generatedColumn: offsetColumn + 1
  9943. },
  9944. consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
  9945. }
  9946. });
  9947. }
  9948. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  9949. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  9950. /**
  9951. * The version of the source mapping spec that we are consuming.
  9952. */
  9953. IndexedSourceMapConsumer.prototype._version = 3;
  9954. /**
  9955. * The list of original sources.
  9956. */
  9957. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  9958. get: function () {
  9959. var sources = [];
  9960. for (var i = 0; i < this._sections.length; i++) {
  9961. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  9962. sources.push(this._sections[i].consumer.sources[j]);
  9963. }
  9964. }
  9965. return sources;
  9966. }
  9967. });
  9968. /**
  9969. * Returns the original source, line, and column information for the generated
  9970. * source's line and column positions provided. The only argument is an object
  9971. * with the following properties:
  9972. *
  9973. * - line: The line number in the generated source. The line number
  9974. * is 1-based.
  9975. * - column: The column number in the generated source. The column
  9976. * number is 0-based.
  9977. *
  9978. * and an object is returned with the following properties:
  9979. *
  9980. * - source: The original source file, or null.
  9981. * - line: The line number in the original source, or null. The
  9982. * line number is 1-based.
  9983. * - column: The column number in the original source, or null. The
  9984. * column number is 0-based.
  9985. * - name: The original identifier, or null.
  9986. */
  9987. IndexedSourceMapConsumer.prototype.originalPositionFor =
  9988. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  9989. var needle = {
  9990. generatedLine: util.getArg(aArgs, 'line'),
  9991. generatedColumn: util.getArg(aArgs, 'column')
  9992. };
  9993. // Find the section containing the generated position we're trying to map
  9994. // to an original position.
  9995. var sectionIndex = binarySearch.search(needle, this._sections,
  9996. function(needle, section) {
  9997. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  9998. if (cmp) {
  9999. return cmp;
  10000. }
  10001. return (needle.generatedColumn -
  10002. section.generatedOffset.generatedColumn);
  10003. });
  10004. var section = this._sections[sectionIndex];
  10005. if (!section) {
  10006. return {
  10007. source: null,
  10008. line: null,
  10009. column: null,
  10010. name: null
  10011. };
  10012. }
  10013. return section.consumer.originalPositionFor({
  10014. line: needle.generatedLine -
  10015. (section.generatedOffset.generatedLine - 1),
  10016. column: needle.generatedColumn -
  10017. (section.generatedOffset.generatedLine === needle.generatedLine
  10018. ? section.generatedOffset.generatedColumn - 1
  10019. : 0),
  10020. bias: aArgs.bias
  10021. });
  10022. };
  10023. /**
  10024. * Return true if we have the source content for every source in the source
  10025. * map, false otherwise.
  10026. */
  10027. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  10028. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  10029. return this._sections.every(function (s) {
  10030. return s.consumer.hasContentsOfAllSources();
  10031. });
  10032. };
  10033. /**
  10034. * Returns the original source content. The only argument is the url of the
  10035. * original source file. Returns null if no original source content is
  10036. * available.
  10037. */
  10038. IndexedSourceMapConsumer.prototype.sourceContentFor =
  10039. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  10040. for (var i = 0; i < this._sections.length; i++) {
  10041. var section = this._sections[i];
  10042. var content = section.consumer.sourceContentFor(aSource, true);
  10043. if (content) {
  10044. return content;
  10045. }
  10046. }
  10047. if (nullOnMissing) {
  10048. return null;
  10049. }
  10050. else {
  10051. throw new Error('"' + aSource + '" is not in the SourceMap.');
  10052. }
  10053. };
  10054. /**
  10055. * Returns the generated line and column information for the original source,
  10056. * line, and column positions provided. The only argument is an object with
  10057. * the following properties:
  10058. *
  10059. * - source: The filename of the original source.
  10060. * - line: The line number in the original source. The line number
  10061. * is 1-based.
  10062. * - column: The column number in the original source. The column
  10063. * number is 0-based.
  10064. *
  10065. * and an object is returned with the following properties:
  10066. *
  10067. * - line: The line number in the generated source, or null. The
  10068. * line number is 1-based.
  10069. * - column: The column number in the generated source, or null.
  10070. * The column number is 0-based.
  10071. */
  10072. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  10073. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  10074. for (var i = 0; i < this._sections.length; i++) {
  10075. var section = this._sections[i];
  10076. // Only consider this section if the requested source is in the list of
  10077. // sources of the consumer.
  10078. if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
  10079. continue;
  10080. }
  10081. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  10082. if (generatedPosition) {
  10083. var ret = {
  10084. line: generatedPosition.line +
  10085. (section.generatedOffset.generatedLine - 1),
  10086. column: generatedPosition.column +
  10087. (section.generatedOffset.generatedLine === generatedPosition.line
  10088. ? section.generatedOffset.generatedColumn - 1
  10089. : 0)
  10090. };
  10091. return ret;
  10092. }
  10093. }
  10094. return {
  10095. line: null,
  10096. column: null
  10097. };
  10098. };
  10099. /**
  10100. * Parse the mappings in a string in to a data structure which we can easily
  10101. * query (the ordered arrays in the `this.__generatedMappings` and
  10102. * `this.__originalMappings` properties).
  10103. */
  10104. IndexedSourceMapConsumer.prototype._parseMappings =
  10105. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  10106. this.__generatedMappings = [];
  10107. this.__originalMappings = [];
  10108. for (var i = 0; i < this._sections.length; i++) {
  10109. var section = this._sections[i];
  10110. var sectionMappings = section.consumer._generatedMappings;
  10111. for (var j = 0; j < sectionMappings.length; j++) {
  10112. var mapping = sectionMappings[j];
  10113. var source = section.consumer._sources.at(mapping.source);
  10114. source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  10115. this._sources.add(source);
  10116. source = this._sources.indexOf(source);
  10117. var name = null;
  10118. if (mapping.name) {
  10119. name = section.consumer._names.at(mapping.name);
  10120. this._names.add(name);
  10121. name = this._names.indexOf(name);
  10122. }
  10123. // The mappings coming from the consumer for the section have
  10124. // generated positions relative to the start of the section, so we
  10125. // need to offset them to be relative to the start of the concatenated
  10126. // generated file.
  10127. var adjustedMapping = {
  10128. source: source,
  10129. generatedLine: mapping.generatedLine +
  10130. (section.generatedOffset.generatedLine - 1),
  10131. generatedColumn: mapping.generatedColumn +
  10132. (section.generatedOffset.generatedLine === mapping.generatedLine
  10133. ? section.generatedOffset.generatedColumn - 1
  10134. : 0),
  10135. originalLine: mapping.originalLine,
  10136. originalColumn: mapping.originalColumn,
  10137. name: name
  10138. };
  10139. this.__generatedMappings.push(adjustedMapping);
  10140. if (typeof adjustedMapping.originalLine === 'number') {
  10141. this.__originalMappings.push(adjustedMapping);
  10142. }
  10143. }
  10144. }
  10145. quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  10146. quickSort(this.__originalMappings, util.compareByOriginalPositions);
  10147. };
  10148. sourceMapConsumer.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  10149. return sourceMapConsumer;
  10150. }
  10151. var sourceNode = {};
  10152. /* -*- Mode: js; js-indent-level: 2; -*- */
  10153. var hasRequiredSourceNode;
  10154. function requireSourceNode () {
  10155. if (hasRequiredSourceNode) return sourceNode;
  10156. hasRequiredSourceNode = 1;
  10157. /*
  10158. * Copyright 2011 Mozilla Foundation and contributors
  10159. * Licensed under the New BSD license. See LICENSE or:
  10160. * http://opensource.org/licenses/BSD-3-Clause
  10161. */
  10162. var SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  10163. var util = /*@__PURE__*/ requireUtil$1();
  10164. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  10165. // operating systems these days (capturing the result).
  10166. var REGEX_NEWLINE = /(\r?\n)/;
  10167. // Newline character code for charCodeAt() comparisons
  10168. var NEWLINE_CODE = 10;
  10169. // Private symbol for identifying `SourceNode`s when multiple versions of
  10170. // the source-map library are loaded. This MUST NOT CHANGE across
  10171. // versions!
  10172. var isSourceNode = "$$$isSourceNode$$$";
  10173. /**
  10174. * SourceNodes provide a way to abstract over interpolating/concatenating
  10175. * snippets of generated JavaScript source code while maintaining the line and
  10176. * column information associated with the original source code.
  10177. *
  10178. * @param aLine The original line number.
  10179. * @param aColumn The original column number.
  10180. * @param aSource The original source's filename.
  10181. * @param aChunks Optional. An array of strings which are snippets of
  10182. * generated JS, or other SourceNodes.
  10183. * @param aName The original identifier.
  10184. */
  10185. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  10186. this.children = [];
  10187. this.sourceContents = {};
  10188. this.line = aLine == null ? null : aLine;
  10189. this.column = aColumn == null ? null : aColumn;
  10190. this.source = aSource == null ? null : aSource;
  10191. this.name = aName == null ? null : aName;
  10192. this[isSourceNode] = true;
  10193. if (aChunks != null) this.add(aChunks);
  10194. }
  10195. /**
  10196. * Creates a SourceNode from generated code and a SourceMapConsumer.
  10197. *
  10198. * @param aGeneratedCode The generated code
  10199. * @param aSourceMapConsumer The SourceMap for the generated code
  10200. * @param aRelativePath Optional. The path that relative sources in the
  10201. * SourceMapConsumer should be relative to.
  10202. */
  10203. SourceNode.fromStringWithSourceMap =
  10204. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  10205. // The SourceNode we want to fill with the generated code
  10206. // and the SourceMap
  10207. var node = new SourceNode();
  10208. // All even indices of this array are one line of the generated code,
  10209. // while all odd indices are the newlines between two adjacent lines
  10210. // (since `REGEX_NEWLINE` captures its match).
  10211. // Processed fragments are accessed by calling `shiftNextLine`.
  10212. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  10213. var remainingLinesIndex = 0;
  10214. var shiftNextLine = function() {
  10215. var lineContents = getNextLine();
  10216. // The last line of a file might not have a newline.
  10217. var newLine = getNextLine() || "";
  10218. return lineContents + newLine;
  10219. function getNextLine() {
  10220. return remainingLinesIndex < remainingLines.length ?
  10221. remainingLines[remainingLinesIndex++] : undefined;
  10222. }
  10223. };
  10224. // We need to remember the position of "remainingLines"
  10225. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  10226. // The generate SourceNodes we need a code range.
  10227. // To extract it current and last mapping is used.
  10228. // Here we store the last mapping.
  10229. var lastMapping = null;
  10230. aSourceMapConsumer.eachMapping(function (mapping) {
  10231. if (lastMapping !== null) {
  10232. // We add the code from "lastMapping" to "mapping":
  10233. // First check if there is a new line in between.
  10234. if (lastGeneratedLine < mapping.generatedLine) {
  10235. // Associate first line with "lastMapping"
  10236. addMappingWithCode(lastMapping, shiftNextLine());
  10237. lastGeneratedLine++;
  10238. lastGeneratedColumn = 0;
  10239. // The remaining code is added without mapping
  10240. } else {
  10241. // There is no new line in between.
  10242. // Associate the code between "lastGeneratedColumn" and
  10243. // "mapping.generatedColumn" with "lastMapping"
  10244. var nextLine = remainingLines[remainingLinesIndex] || '';
  10245. var code = nextLine.substr(0, mapping.generatedColumn -
  10246. lastGeneratedColumn);
  10247. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  10248. lastGeneratedColumn);
  10249. lastGeneratedColumn = mapping.generatedColumn;
  10250. addMappingWithCode(lastMapping, code);
  10251. // No more remaining code, continue
  10252. lastMapping = mapping;
  10253. return;
  10254. }
  10255. }
  10256. // We add the generated code until the first mapping
  10257. // to the SourceNode without any mapping.
  10258. // Each line is added as separate string.
  10259. while (lastGeneratedLine < mapping.generatedLine) {
  10260. node.add(shiftNextLine());
  10261. lastGeneratedLine++;
  10262. }
  10263. if (lastGeneratedColumn < mapping.generatedColumn) {
  10264. var nextLine = remainingLines[remainingLinesIndex] || '';
  10265. node.add(nextLine.substr(0, mapping.generatedColumn));
  10266. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  10267. lastGeneratedColumn = mapping.generatedColumn;
  10268. }
  10269. lastMapping = mapping;
  10270. }, this);
  10271. // We have processed all mappings.
  10272. if (remainingLinesIndex < remainingLines.length) {
  10273. if (lastMapping) {
  10274. // Associate the remaining code in the current line with "lastMapping"
  10275. addMappingWithCode(lastMapping, shiftNextLine());
  10276. }
  10277. // and add the remaining lines without any mapping
  10278. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  10279. }
  10280. // Copy sourcesContent into SourceNode
  10281. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  10282. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  10283. if (content != null) {
  10284. if (aRelativePath != null) {
  10285. sourceFile = util.join(aRelativePath, sourceFile);
  10286. }
  10287. node.setSourceContent(sourceFile, content);
  10288. }
  10289. });
  10290. return node;
  10291. function addMappingWithCode(mapping, code) {
  10292. if (mapping === null || mapping.source === undefined) {
  10293. node.add(code);
  10294. } else {
  10295. var source = aRelativePath
  10296. ? util.join(aRelativePath, mapping.source)
  10297. : mapping.source;
  10298. node.add(new SourceNode(mapping.originalLine,
  10299. mapping.originalColumn,
  10300. source,
  10301. code,
  10302. mapping.name));
  10303. }
  10304. }
  10305. };
  10306. /**
  10307. * Add a chunk of generated JS to this source node.
  10308. *
  10309. * @param aChunk A string snippet of generated JS code, another instance of
  10310. * SourceNode, or an array where each member is one of those things.
  10311. */
  10312. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  10313. if (Array.isArray(aChunk)) {
  10314. aChunk.forEach(function (chunk) {
  10315. this.add(chunk);
  10316. }, this);
  10317. }
  10318. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10319. if (aChunk) {
  10320. this.children.push(aChunk);
  10321. }
  10322. }
  10323. else {
  10324. throw new TypeError(
  10325. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10326. );
  10327. }
  10328. return this;
  10329. };
  10330. /**
  10331. * Add a chunk of generated JS to the beginning of this source node.
  10332. *
  10333. * @param aChunk A string snippet of generated JS code, another instance of
  10334. * SourceNode, or an array where each member is one of those things.
  10335. */
  10336. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  10337. if (Array.isArray(aChunk)) {
  10338. for (var i = aChunk.length-1; i >= 0; i--) {
  10339. this.prepend(aChunk[i]);
  10340. }
  10341. }
  10342. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  10343. this.children.unshift(aChunk);
  10344. }
  10345. else {
  10346. throw new TypeError(
  10347. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  10348. );
  10349. }
  10350. return this;
  10351. };
  10352. /**
  10353. * Walk over the tree of JS snippets in this node and its children. The
  10354. * walking function is called once for each snippet of JS and is passed that
  10355. * snippet and the its original associated source's line/column location.
  10356. *
  10357. * @param aFn The traversal function.
  10358. */
  10359. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  10360. var chunk;
  10361. for (var i = 0, len = this.children.length; i < len; i++) {
  10362. chunk = this.children[i];
  10363. if (chunk[isSourceNode]) {
  10364. chunk.walk(aFn);
  10365. }
  10366. else {
  10367. if (chunk !== '') {
  10368. aFn(chunk, { source: this.source,
  10369. line: this.line,
  10370. column: this.column,
  10371. name: this.name });
  10372. }
  10373. }
  10374. }
  10375. };
  10376. /**
  10377. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  10378. * each of `this.children`.
  10379. *
  10380. * @param aSep The separator.
  10381. */
  10382. SourceNode.prototype.join = function SourceNode_join(aSep) {
  10383. var newChildren;
  10384. var i;
  10385. var len = this.children.length;
  10386. if (len > 0) {
  10387. newChildren = [];
  10388. for (i = 0; i < len-1; i++) {
  10389. newChildren.push(this.children[i]);
  10390. newChildren.push(aSep);
  10391. }
  10392. newChildren.push(this.children[i]);
  10393. this.children = newChildren;
  10394. }
  10395. return this;
  10396. };
  10397. /**
  10398. * Call String.prototype.replace on the very right-most source snippet. Useful
  10399. * for trimming whitespace from the end of a source node, etc.
  10400. *
  10401. * @param aPattern The pattern to replace.
  10402. * @param aReplacement The thing to replace the pattern with.
  10403. */
  10404. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  10405. var lastChild = this.children[this.children.length - 1];
  10406. if (lastChild[isSourceNode]) {
  10407. lastChild.replaceRight(aPattern, aReplacement);
  10408. }
  10409. else if (typeof lastChild === 'string') {
  10410. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  10411. }
  10412. else {
  10413. this.children.push(''.replace(aPattern, aReplacement));
  10414. }
  10415. return this;
  10416. };
  10417. /**
  10418. * Set the source content for a source file. This will be added to the SourceMapGenerator
  10419. * in the sourcesContent field.
  10420. *
  10421. * @param aSourceFile The filename of the source file
  10422. * @param aSourceContent The content of the source file
  10423. */
  10424. SourceNode.prototype.setSourceContent =
  10425. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  10426. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  10427. };
  10428. /**
  10429. * Walk over the tree of SourceNodes. The walking function is called for each
  10430. * source file content and is passed the filename and source content.
  10431. *
  10432. * @param aFn The traversal function.
  10433. */
  10434. SourceNode.prototype.walkSourceContents =
  10435. function SourceNode_walkSourceContents(aFn) {
  10436. for (var i = 0, len = this.children.length; i < len; i++) {
  10437. if (this.children[i][isSourceNode]) {
  10438. this.children[i].walkSourceContents(aFn);
  10439. }
  10440. }
  10441. var sources = Object.keys(this.sourceContents);
  10442. for (var i = 0, len = sources.length; i < len; i++) {
  10443. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  10444. }
  10445. };
  10446. /**
  10447. * Return the string representation of this source node. Walks over the tree
  10448. * and concatenates all the various snippets together to one string.
  10449. */
  10450. SourceNode.prototype.toString = function SourceNode_toString() {
  10451. var str = "";
  10452. this.walk(function (chunk) {
  10453. str += chunk;
  10454. });
  10455. return str;
  10456. };
  10457. /**
  10458. * Returns the string representation of this source node along with a source
  10459. * map.
  10460. */
  10461. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  10462. var generated = {
  10463. code: "",
  10464. line: 1,
  10465. column: 0
  10466. };
  10467. var map = new SourceMapGenerator(aArgs);
  10468. var sourceMappingActive = false;
  10469. var lastOriginalSource = null;
  10470. var lastOriginalLine = null;
  10471. var lastOriginalColumn = null;
  10472. var lastOriginalName = null;
  10473. this.walk(function (chunk, original) {
  10474. generated.code += chunk;
  10475. if (original.source !== null
  10476. && original.line !== null
  10477. && original.column !== null) {
  10478. if(lastOriginalSource !== original.source
  10479. || lastOriginalLine !== original.line
  10480. || lastOriginalColumn !== original.column
  10481. || lastOriginalName !== original.name) {
  10482. map.addMapping({
  10483. source: original.source,
  10484. original: {
  10485. line: original.line,
  10486. column: original.column
  10487. },
  10488. generated: {
  10489. line: generated.line,
  10490. column: generated.column
  10491. },
  10492. name: original.name
  10493. });
  10494. }
  10495. lastOriginalSource = original.source;
  10496. lastOriginalLine = original.line;
  10497. lastOriginalColumn = original.column;
  10498. lastOriginalName = original.name;
  10499. sourceMappingActive = true;
  10500. } else if (sourceMappingActive) {
  10501. map.addMapping({
  10502. generated: {
  10503. line: generated.line,
  10504. column: generated.column
  10505. }
  10506. });
  10507. lastOriginalSource = null;
  10508. sourceMappingActive = false;
  10509. }
  10510. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  10511. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  10512. generated.line++;
  10513. generated.column = 0;
  10514. // Mappings end at eol
  10515. if (idx + 1 === length) {
  10516. lastOriginalSource = null;
  10517. sourceMappingActive = false;
  10518. } else if (sourceMappingActive) {
  10519. map.addMapping({
  10520. source: original.source,
  10521. original: {
  10522. line: original.line,
  10523. column: original.column
  10524. },
  10525. generated: {
  10526. line: generated.line,
  10527. column: generated.column
  10528. },
  10529. name: original.name
  10530. });
  10531. }
  10532. } else {
  10533. generated.column++;
  10534. }
  10535. }
  10536. });
  10537. this.walkSourceContents(function (sourceFile, sourceContent) {
  10538. map.setSourceContent(sourceFile, sourceContent);
  10539. });
  10540. return { code: generated.code, map: map };
  10541. };
  10542. sourceNode.SourceNode = SourceNode;
  10543. return sourceNode;
  10544. }
  10545. /*
  10546. * Copyright 2009-2011 Mozilla Foundation and contributors
  10547. * Licensed under the New BSD license. See LICENSE.txt or:
  10548. * http://opensource.org/licenses/BSD-3-Clause
  10549. */
  10550. var hasRequiredSourceMap;
  10551. function requireSourceMap () {
  10552. if (hasRequiredSourceMap) return sourceMap;
  10553. hasRequiredSourceMap = 1;
  10554. sourceMap.SourceMapGenerator = /*@__PURE__*/ requireSourceMapGenerator().SourceMapGenerator;
  10555. sourceMap.SourceMapConsumer = /*@__PURE__*/ requireSourceMapConsumer().SourceMapConsumer;
  10556. sourceMap.SourceNode = /*@__PURE__*/ requireSourceNode().SourceNode;
  10557. return sourceMap;
  10558. }
  10559. var mergeSourceMap;
  10560. var hasRequiredMergeSourceMap;
  10561. function requireMergeSourceMap () {
  10562. if (hasRequiredMergeSourceMap) return mergeSourceMap;
  10563. hasRequiredMergeSourceMap = 1;
  10564. var sourceMap = /*@__PURE__*/ requireSourceMap();
  10565. var SourceMapConsumer = sourceMap.SourceMapConsumer;
  10566. var SourceMapGenerator = sourceMap.SourceMapGenerator;
  10567. mergeSourceMap = merge;
  10568. /**
  10569. * Merge old source map and new source map and return merged.
  10570. * If old or new source map value is falsy, return another one as it is.
  10571. *
  10572. * @param {object|string} [oldMap] old source map object
  10573. * @param {object|string} [newmap] new source map object
  10574. * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
  10575. */
  10576. function merge(oldMap, newMap) {
  10577. if (!oldMap) return newMap
  10578. if (!newMap) return oldMap
  10579. var oldMapConsumer = new SourceMapConsumer(oldMap);
  10580. var newMapConsumer = new SourceMapConsumer(newMap);
  10581. var mergedMapGenerator = new SourceMapGenerator();
  10582. // iterate on new map and overwrite original position of new map with one of old map
  10583. newMapConsumer.eachMapping(function(m) {
  10584. // pass when `originalLine` is null.
  10585. // It occurs in case that the node does not have origin in original code.
  10586. if (m.originalLine == null) return
  10587. var origPosInOldMap = oldMapConsumer.originalPositionFor({
  10588. line: m.originalLine,
  10589. column: m.originalColumn
  10590. });
  10591. if (origPosInOldMap.source == null) return
  10592. mergedMapGenerator.addMapping({
  10593. original: {
  10594. line: origPosInOldMap.line,
  10595. column: origPosInOldMap.column
  10596. },
  10597. generated: {
  10598. line: m.generatedLine,
  10599. column: m.generatedColumn
  10600. },
  10601. source: origPosInOldMap.source,
  10602. name: origPosInOldMap.name
  10603. });
  10604. });
  10605. var consumers = [oldMapConsumer, newMapConsumer];
  10606. consumers.forEach(function(consumer) {
  10607. consumer.sources.forEach(function(sourceFile) {
  10608. mergedMapGenerator._sources.add(sourceFile);
  10609. var sourceContent = consumer.sourceContentFor(sourceFile);
  10610. if (sourceContent != null) {
  10611. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  10612. }
  10613. });
  10614. });
  10615. mergedMapGenerator._sourceRoot = oldMap.sourceRoot;
  10616. mergedMapGenerator._file = oldMap.file;
  10617. return JSON.parse(mergedMapGenerator.toString())
  10618. }
  10619. return mergeSourceMap;
  10620. }
  10621. var mergeSourceMapExports = /*@__PURE__*/ requireMergeSourceMap();
  10622. var merge = /*@__PURE__*/getDefaultExportFromCjs(mergeSourceMapExports);
  10623. const scss = (source, map, options, load = require) => {
  10624. const nodeSass = load("sass");
  10625. const { compileString, renderSync } = nodeSass;
  10626. const data = getSource(source, options.filename, options.additionalData);
  10627. let css;
  10628. let dependencies;
  10629. let sourceMap;
  10630. try {
  10631. if (compileString) {
  10632. const { pathToFileURL, fileURLToPath } = load("url");
  10633. const result = compileString(data, {
  10634. ...options,
  10635. url: pathToFileURL(options.filename),
  10636. sourceMap: !!map
  10637. });
  10638. css = result.css;
  10639. dependencies = result.loadedUrls.map((url) => fileURLToPath(url));
  10640. sourceMap = map ? result.sourceMap : void 0;
  10641. } else {
  10642. const result = renderSync({
  10643. ...options,
  10644. data,
  10645. file: options.filename,
  10646. outFile: options.filename,
  10647. sourceMap: !!map
  10648. });
  10649. css = result.css.toString();
  10650. dependencies = result.stats.includedFiles;
  10651. sourceMap = map ? JSON.parse(result.map.toString()) : void 0;
  10652. }
  10653. if (map) {
  10654. return {
  10655. code: css,
  10656. errors: [],
  10657. dependencies,
  10658. map: merge(map, sourceMap)
  10659. };
  10660. }
  10661. return { code: css, errors: [], dependencies };
  10662. } catch (e) {
  10663. return { code: "", errors: [e], dependencies: [] };
  10664. }
  10665. };
  10666. const sass = (source, map, options, load) => scss(
  10667. source,
  10668. map,
  10669. {
  10670. ...options,
  10671. indentedSyntax: true
  10672. },
  10673. load
  10674. );
  10675. const less = (source, map, options, load = require) => {
  10676. const nodeLess = load("less");
  10677. let result;
  10678. let error = null;
  10679. nodeLess.render(
  10680. getSource(source, options.filename, options.additionalData),
  10681. { ...options, syncImport: true },
  10682. (err, output) => {
  10683. error = err;
  10684. result = output;
  10685. }
  10686. );
  10687. if (error) return { code: "", errors: [error], dependencies: [] };
  10688. const dependencies = result.imports;
  10689. if (map) {
  10690. return {
  10691. code: result.css.toString(),
  10692. map: merge(map, result.map),
  10693. errors: [],
  10694. dependencies
  10695. };
  10696. }
  10697. return {
  10698. code: result.css.toString(),
  10699. errors: [],
  10700. dependencies
  10701. };
  10702. };
  10703. const styl = (source, map, options, load = require) => {
  10704. const nodeStylus = load("stylus");
  10705. try {
  10706. const ref = nodeStylus(source, options);
  10707. if (map) ref.set("sourcemap", { inline: false, comment: false });
  10708. const result = ref.render();
  10709. const dependencies = ref.deps();
  10710. if (map) {
  10711. return {
  10712. code: result,
  10713. map: merge(map, ref.sourcemap),
  10714. errors: [],
  10715. dependencies
  10716. };
  10717. }
  10718. return { code: result, errors: [], dependencies };
  10719. } catch (e) {
  10720. return { code: "", errors: [e], dependencies: [] };
  10721. }
  10722. };
  10723. function getSource(source, filename, additionalData) {
  10724. if (!additionalData) return source;
  10725. if (shared.isFunction(additionalData)) {
  10726. return additionalData(source, filename);
  10727. }
  10728. return additionalData + source;
  10729. }
  10730. const processors = {
  10731. less,
  10732. sass,
  10733. scss,
  10734. styl,
  10735. stylus: styl
  10736. };
  10737. var build = {exports: {}};
  10738. var fs = {};
  10739. var hasRequiredFs;
  10740. function requireFs () {
  10741. if (hasRequiredFs) return fs;
  10742. hasRequiredFs = 1;
  10743. Object.defineProperty(fs, "__esModule", {
  10744. value: true
  10745. });
  10746. fs.getFileSystem = getFileSystem;
  10747. fs.setFileSystem = setFileSystem;
  10748. let fileSystem = {
  10749. readFile: () => {
  10750. throw Error("readFile not implemented");
  10751. },
  10752. writeFile: () => {
  10753. throw Error("writeFile not implemented");
  10754. }
  10755. };
  10756. function setFileSystem(fs) {
  10757. fileSystem.readFile = fs.readFile;
  10758. fileSystem.writeFile = fs.writeFile;
  10759. }
  10760. function getFileSystem() {
  10761. return fileSystem;
  10762. }
  10763. return fs;
  10764. }
  10765. var pluginFactory = {};
  10766. var unquote = {};
  10767. var hasRequiredUnquote;
  10768. function requireUnquote () {
  10769. if (hasRequiredUnquote) return unquote;
  10770. hasRequiredUnquote = 1;
  10771. Object.defineProperty(unquote, "__esModule", {
  10772. value: true
  10773. });
  10774. unquote.default = unquote$1;
  10775. // copied from https://github.com/lakenen/node-unquote
  10776. const reg = /['"]/;
  10777. function unquote$1(str) {
  10778. if (!str) {
  10779. return "";
  10780. }
  10781. if (reg.test(str.charAt(0))) {
  10782. str = str.substr(1);
  10783. }
  10784. if (reg.test(str.charAt(str.length - 1))) {
  10785. str = str.substr(0, str.length - 1);
  10786. }
  10787. return str;
  10788. }
  10789. return unquote;
  10790. }
  10791. var Parser = {};
  10792. var replaceValueSymbols_1;
  10793. var hasRequiredReplaceValueSymbols;
  10794. function requireReplaceValueSymbols () {
  10795. if (hasRequiredReplaceValueSymbols) return replaceValueSymbols_1;
  10796. hasRequiredReplaceValueSymbols = 1;
  10797. const matchValueName = /[$]?[\w-]+/g;
  10798. const replaceValueSymbols = (value, replacements) => {
  10799. let matches;
  10800. while ((matches = matchValueName.exec(value))) {
  10801. const replacement = replacements[matches[0]];
  10802. if (replacement) {
  10803. value =
  10804. value.slice(0, matches.index) +
  10805. replacement +
  10806. value.slice(matchValueName.lastIndex);
  10807. matchValueName.lastIndex -= matches[0].length - replacement.length;
  10808. }
  10809. }
  10810. return value;
  10811. };
  10812. replaceValueSymbols_1 = replaceValueSymbols;
  10813. return replaceValueSymbols_1;
  10814. }
  10815. var replaceSymbols_1;
  10816. var hasRequiredReplaceSymbols;
  10817. function requireReplaceSymbols () {
  10818. if (hasRequiredReplaceSymbols) return replaceSymbols_1;
  10819. hasRequiredReplaceSymbols = 1;
  10820. const replaceValueSymbols = /*@__PURE__*/ requireReplaceValueSymbols();
  10821. const replaceSymbols = (css, replacements) => {
  10822. css.walk((node) => {
  10823. if (node.type === "decl" && node.value) {
  10824. node.value = replaceValueSymbols(node.value.toString(), replacements);
  10825. } else if (node.type === "rule" && node.selector) {
  10826. node.selector = replaceValueSymbols(
  10827. node.selector.toString(),
  10828. replacements
  10829. );
  10830. } else if (node.type === "atrule" && node.params) {
  10831. node.params = replaceValueSymbols(node.params.toString(), replacements);
  10832. }
  10833. });
  10834. };
  10835. replaceSymbols_1 = replaceSymbols;
  10836. return replaceSymbols_1;
  10837. }
  10838. var extractICSS_1;
  10839. var hasRequiredExtractICSS;
  10840. function requireExtractICSS () {
  10841. if (hasRequiredExtractICSS) return extractICSS_1;
  10842. hasRequiredExtractICSS = 1;
  10843. const importPattern = /^:import\(("[^"]*"|'[^']*'|[^"']+)\)$/;
  10844. const balancedQuotes = /^("[^"]*"|'[^']*'|[^"']+)$/;
  10845. const getDeclsObject = (rule) => {
  10846. const object = {};
  10847. rule.walkDecls((decl) => {
  10848. const before = decl.raws.before ? decl.raws.before.trim() : "";
  10849. object[before + decl.prop] = decl.value;
  10850. });
  10851. return object;
  10852. };
  10853. /**
  10854. *
  10855. * @param {string} css
  10856. * @param {boolean} removeRules
  10857. * @param {'auto' | 'rule' | 'at-rule'} mode
  10858. */
  10859. const extractICSS = (css, removeRules = true, mode = "auto") => {
  10860. const icssImports = {};
  10861. const icssExports = {};
  10862. function addImports(node, path) {
  10863. const unquoted = path.replace(/'|"/g, "");
  10864. icssImports[unquoted] = Object.assign(
  10865. icssImports[unquoted] || {},
  10866. getDeclsObject(node)
  10867. );
  10868. if (removeRules) {
  10869. node.remove();
  10870. }
  10871. }
  10872. function addExports(node) {
  10873. Object.assign(icssExports, getDeclsObject(node));
  10874. if (removeRules) {
  10875. node.remove();
  10876. }
  10877. }
  10878. css.each((node) => {
  10879. if (node.type === "rule" && mode !== "at-rule") {
  10880. if (node.selector.slice(0, 7) === ":import") {
  10881. const matches = importPattern.exec(node.selector);
  10882. if (matches) {
  10883. addImports(node, matches[1]);
  10884. }
  10885. }
  10886. if (node.selector === ":export") {
  10887. addExports(node);
  10888. }
  10889. }
  10890. if (node.type === "atrule" && mode !== "rule") {
  10891. if (node.name === "icss-import") {
  10892. const matches = balancedQuotes.exec(node.params);
  10893. if (matches) {
  10894. addImports(node, matches[1]);
  10895. }
  10896. }
  10897. if (node.name === "icss-export") {
  10898. addExports(node);
  10899. }
  10900. }
  10901. });
  10902. return { icssImports, icssExports };
  10903. };
  10904. extractICSS_1 = extractICSS;
  10905. return extractICSS_1;
  10906. }
  10907. var createICSSRules_1;
  10908. var hasRequiredCreateICSSRules;
  10909. function requireCreateICSSRules () {
  10910. if (hasRequiredCreateICSSRules) return createICSSRules_1;
  10911. hasRequiredCreateICSSRules = 1;
  10912. const createImports = (imports, postcss, mode = "rule") => {
  10913. return Object.keys(imports).map((path) => {
  10914. const aliases = imports[path];
  10915. const declarations = Object.keys(aliases).map((key) =>
  10916. postcss.decl({
  10917. prop: key,
  10918. value: aliases[key],
  10919. raws: { before: "\n " },
  10920. })
  10921. );
  10922. const hasDeclarations = declarations.length > 0;
  10923. const rule =
  10924. mode === "rule"
  10925. ? postcss.rule({
  10926. selector: `:import('${path}')`,
  10927. raws: { after: hasDeclarations ? "\n" : "" },
  10928. })
  10929. : postcss.atRule({
  10930. name: "icss-import",
  10931. params: `'${path}'`,
  10932. raws: { after: hasDeclarations ? "\n" : "" },
  10933. });
  10934. if (hasDeclarations) {
  10935. rule.append(declarations);
  10936. }
  10937. return rule;
  10938. });
  10939. };
  10940. const createExports = (exports, postcss, mode = "rule") => {
  10941. const declarations = Object.keys(exports).map((key) =>
  10942. postcss.decl({
  10943. prop: key,
  10944. value: exports[key],
  10945. raws: { before: "\n " },
  10946. })
  10947. );
  10948. if (declarations.length === 0) {
  10949. return [];
  10950. }
  10951. const rule =
  10952. mode === "rule"
  10953. ? postcss.rule({
  10954. selector: `:export`,
  10955. raws: { after: "\n" },
  10956. })
  10957. : postcss.atRule({
  10958. name: "icss-export",
  10959. raws: { after: "\n" },
  10960. });
  10961. rule.append(declarations);
  10962. return [rule];
  10963. };
  10964. const createICSSRules = (imports, exports, postcss, mode) => [
  10965. ...createImports(imports, postcss, mode),
  10966. ...createExports(exports, postcss, mode),
  10967. ];
  10968. createICSSRules_1 = createICSSRules;
  10969. return createICSSRules_1;
  10970. }
  10971. var src$4;
  10972. var hasRequiredSrc$4;
  10973. function requireSrc$4 () {
  10974. if (hasRequiredSrc$4) return src$4;
  10975. hasRequiredSrc$4 = 1;
  10976. const replaceValueSymbols = /*@__PURE__*/ requireReplaceValueSymbols();
  10977. const replaceSymbols = /*@__PURE__*/ requireReplaceSymbols();
  10978. const extractICSS = /*@__PURE__*/ requireExtractICSS();
  10979. const createICSSRules = /*@__PURE__*/ requireCreateICSSRules();
  10980. src$4 = {
  10981. replaceValueSymbols,
  10982. replaceSymbols,
  10983. extractICSS,
  10984. createICSSRules,
  10985. };
  10986. return src$4;
  10987. }
  10988. var hasRequiredParser$1;
  10989. function requireParser$1 () {
  10990. if (hasRequiredParser$1) return Parser;
  10991. hasRequiredParser$1 = 1;
  10992. Object.defineProperty(Parser, "__esModule", {
  10993. value: true
  10994. });
  10995. Parser.default = void 0;
  10996. var _icssUtils = /*@__PURE__*/ requireSrc$4();
  10997. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  10998. const importRegexp = /^:import\((.+)\)$/;
  10999. let Parser$1 = class Parser {
  11000. constructor(pathFetcher, trace) {
  11001. this.pathFetcher = pathFetcher;
  11002. this.plugin = this.plugin.bind(this);
  11003. this.exportTokens = {};
  11004. this.translations = {};
  11005. this.trace = trace;
  11006. }
  11007. plugin() {
  11008. const parser = this;
  11009. return {
  11010. postcssPlugin: "css-modules-parser",
  11011. async OnceExit(css) {
  11012. await Promise.all(parser.fetchAllImports(css));
  11013. parser.linkImportedSymbols(css);
  11014. return parser.extractExports(css);
  11015. }
  11016. };
  11017. }
  11018. fetchAllImports(css) {
  11019. let imports = [];
  11020. css.each(node => {
  11021. if (node.type == "rule" && node.selector.match(importRegexp)) {
  11022. imports.push(this.fetchImport(node, css.source.input.from, imports.length));
  11023. }
  11024. });
  11025. return imports;
  11026. }
  11027. linkImportedSymbols(css) {
  11028. (0, _icssUtils.replaceSymbols)(css, this.translations);
  11029. }
  11030. extractExports(css) {
  11031. css.each(node => {
  11032. if (node.type == "rule" && node.selector == ":export") this.handleExport(node);
  11033. });
  11034. }
  11035. handleExport(exportNode) {
  11036. exportNode.each(decl => {
  11037. if (decl.type == "decl") {
  11038. Object.keys(this.translations).forEach(translation => {
  11039. decl.value = decl.value.replace(translation, this.translations[translation]);
  11040. });
  11041. this.exportTokens[decl.prop] = decl.value;
  11042. }
  11043. });
  11044. exportNode.remove();
  11045. }
  11046. async fetchImport(importNode, relativeTo, depNr) {
  11047. const file = importNode.selector.match(importRegexp)[1];
  11048. const depTrace = this.trace + String.fromCharCode(depNr);
  11049. const exports = await this.pathFetcher(file, relativeTo, depTrace);
  11050. try {
  11051. importNode.each(decl => {
  11052. if (decl.type == "decl") {
  11053. this.translations[decl.prop] = exports[decl.value];
  11054. }
  11055. });
  11056. importNode.remove();
  11057. } catch (err) {
  11058. console.log(err);
  11059. }
  11060. }
  11061. };
  11062. Parser.default = Parser$1;
  11063. return Parser;
  11064. }
  11065. var saveJSON = {};
  11066. var hasRequiredSaveJSON;
  11067. function requireSaveJSON () {
  11068. if (hasRequiredSaveJSON) return saveJSON;
  11069. hasRequiredSaveJSON = 1;
  11070. Object.defineProperty(saveJSON, "__esModule", {
  11071. value: true
  11072. });
  11073. saveJSON.default = saveJSON$1;
  11074. var _fs = /*@__PURE__*/ requireFs();
  11075. function saveJSON$1(cssFile, json) {
  11076. return new Promise((resolve, reject) => {
  11077. const {
  11078. writeFile
  11079. } = (0, _fs.getFileSystem)();
  11080. writeFile(`${cssFile}.json`, JSON.stringify(json), e => e ? reject(e) : resolve(json));
  11081. });
  11082. }
  11083. return saveJSON;
  11084. }
  11085. var localsConvention = {};
  11086. /**
  11087. * lodash (Custom Build) <https://lodash.com/>
  11088. * Build: `lodash modularize exports="npm" -o ./`
  11089. * Copyright jQuery Foundation and other contributors <https://jquery.org/>
  11090. * Released under MIT license <https://lodash.com/license>
  11091. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  11092. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  11093. */
  11094. var lodash_camelcase;
  11095. var hasRequiredLodash_camelcase;
  11096. function requireLodash_camelcase () {
  11097. if (hasRequiredLodash_camelcase) return lodash_camelcase;
  11098. hasRequiredLodash_camelcase = 1;
  11099. /** `Object#toString` result references. */
  11100. var symbolTag = '[object Symbol]';
  11101. /** Used to match words composed of alphanumeric characters. */
  11102. var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
  11103. /** Used to match Latin Unicode letters (excluding mathematical operators). */
  11104. var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
  11105. /** Used to compose unicode character classes. */
  11106. var rsAstralRange = '\\ud800-\\udfff',
  11107. rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23',
  11108. rsComboSymbolsRange = '\\u20d0-\\u20f0',
  11109. rsDingbatRange = '\\u2700-\\u27bf',
  11110. rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
  11111. rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
  11112. rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
  11113. rsPunctuationRange = '\\u2000-\\u206f',
  11114. 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',
  11115. rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
  11116. rsVarRange = '\\ufe0e\\ufe0f',
  11117. rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
  11118. /** Used to compose unicode capture groups. */
  11119. var rsApos = "['\u2019]",
  11120. rsAstral = '[' + rsAstralRange + ']',
  11121. rsBreak = '[' + rsBreakRange + ']',
  11122. rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']',
  11123. rsDigits = '\\d+',
  11124. rsDingbat = '[' + rsDingbatRange + ']',
  11125. rsLower = '[' + rsLowerRange + ']',
  11126. rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
  11127. rsFitz = '\\ud83c[\\udffb-\\udfff]',
  11128. rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
  11129. rsNonAstral = '[^' + rsAstralRange + ']',
  11130. rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
  11131. rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
  11132. rsUpper = '[' + rsUpperRange + ']',
  11133. rsZWJ = '\\u200d';
  11134. /** Used to compose unicode regexes. */
  11135. var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')',
  11136. rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')',
  11137. rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
  11138. rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
  11139. reOptMod = rsModifier + '?',
  11140. rsOptVar = '[' + rsVarRange + ']?',
  11141. rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
  11142. rsSeq = rsOptVar + reOptMod + rsOptJoin,
  11143. rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
  11144. rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
  11145. /** Used to match apostrophes. */
  11146. var reApos = RegExp(rsApos, 'g');
  11147. /**
  11148. * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
  11149. * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
  11150. */
  11151. var reComboMark = RegExp(rsCombo, 'g');
  11152. /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
  11153. var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
  11154. /** Used to match complex or compound words. */
  11155. var reUnicodeWord = RegExp([
  11156. rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
  11157. rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')',
  11158. rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr,
  11159. rsUpper + '+' + rsOptUpperContr,
  11160. rsDigits,
  11161. rsEmoji
  11162. ].join('|'), 'g');
  11163. /** 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/). */
  11164. var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']');
  11165. /** Used to detect strings that need a more robust regexp to match words. */
  11166. 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 ]/;
  11167. /** Used to map Latin Unicode letters to basic Latin letters. */
  11168. var deburredLetters = {
  11169. // Latin-1 Supplement block.
  11170. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
  11171. '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
  11172. '\xc7': 'C', '\xe7': 'c',
  11173. '\xd0': 'D', '\xf0': 'd',
  11174. '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
  11175. '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
  11176. '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
  11177. '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
  11178. '\xd1': 'N', '\xf1': 'n',
  11179. '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
  11180. '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
  11181. '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
  11182. '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
  11183. '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
  11184. '\xc6': 'Ae', '\xe6': 'ae',
  11185. '\xde': 'Th', '\xfe': 'th',
  11186. '\xdf': 'ss',
  11187. // Latin Extended-A block.
  11188. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
  11189. '\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
  11190. '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
  11191. '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
  11192. '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
  11193. '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
  11194. '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
  11195. '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
  11196. '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
  11197. '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
  11198. '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
  11199. '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
  11200. '\u0134': 'J', '\u0135': 'j',
  11201. '\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
  11202. '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
  11203. '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
  11204. '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
  11205. '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
  11206. '\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
  11207. '\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
  11208. '\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
  11209. '\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
  11210. '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
  11211. '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
  11212. '\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
  11213. '\u0163': 't', '\u0165': 't', '\u0167': 't',
  11214. '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
  11215. '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
  11216. '\u0174': 'W', '\u0175': 'w',
  11217. '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
  11218. '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
  11219. '\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
  11220. '\u0132': 'IJ', '\u0133': 'ij',
  11221. '\u0152': 'Oe', '\u0153': 'oe',
  11222. '\u0149': "'n", '\u017f': 'ss'
  11223. };
  11224. /** Detect free variable `global` from Node.js. */
  11225. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
  11226. /** Detect free variable `self`. */
  11227. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  11228. /** Used as a reference to the global object. */
  11229. var root = freeGlobal || freeSelf || Function('return this')();
  11230. /**
  11231. * A specialized version of `_.reduce` for arrays without support for
  11232. * iteratee shorthands.
  11233. *
  11234. * @private
  11235. * @param {Array} [array] The array to iterate over.
  11236. * @param {Function} iteratee The function invoked per iteration.
  11237. * @param {*} [accumulator] The initial value.
  11238. * @param {boolean} [initAccum] Specify using the first element of `array` as
  11239. * the initial value.
  11240. * @returns {*} Returns the accumulated value.
  11241. */
  11242. function arrayReduce(array, iteratee, accumulator, initAccum) {
  11243. var index = -1,
  11244. length = array ? array.length : 0;
  11245. while (++index < length) {
  11246. accumulator = iteratee(accumulator, array[index], index, array);
  11247. }
  11248. return accumulator;
  11249. }
  11250. /**
  11251. * Converts an ASCII `string` to an array.
  11252. *
  11253. * @private
  11254. * @param {string} string The string to convert.
  11255. * @returns {Array} Returns the converted array.
  11256. */
  11257. function asciiToArray(string) {
  11258. return string.split('');
  11259. }
  11260. /**
  11261. * Splits an ASCII `string` into an array of its words.
  11262. *
  11263. * @private
  11264. * @param {string} The string to inspect.
  11265. * @returns {Array} Returns the words of `string`.
  11266. */
  11267. function asciiWords(string) {
  11268. return string.match(reAsciiWord) || [];
  11269. }
  11270. /**
  11271. * The base implementation of `_.propertyOf` without support for deep paths.
  11272. *
  11273. * @private
  11274. * @param {Object} object The object to query.
  11275. * @returns {Function} Returns the new accessor function.
  11276. */
  11277. function basePropertyOf(object) {
  11278. return function(key) {
  11279. return object == null ? undefined : object[key];
  11280. };
  11281. }
  11282. /**
  11283. * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
  11284. * letters to basic Latin letters.
  11285. *
  11286. * @private
  11287. * @param {string} letter The matched letter to deburr.
  11288. * @returns {string} Returns the deburred letter.
  11289. */
  11290. var deburrLetter = basePropertyOf(deburredLetters);
  11291. /**
  11292. * Checks if `string` contains Unicode symbols.
  11293. *
  11294. * @private
  11295. * @param {string} string The string to inspect.
  11296. * @returns {boolean} Returns `true` if a symbol is found, else `false`.
  11297. */
  11298. function hasUnicode(string) {
  11299. return reHasUnicode.test(string);
  11300. }
  11301. /**
  11302. * Checks if `string` contains a word composed of Unicode symbols.
  11303. *
  11304. * @private
  11305. * @param {string} string The string to inspect.
  11306. * @returns {boolean} Returns `true` if a word is found, else `false`.
  11307. */
  11308. function hasUnicodeWord(string) {
  11309. return reHasUnicodeWord.test(string);
  11310. }
  11311. /**
  11312. * Converts `string` to an array.
  11313. *
  11314. * @private
  11315. * @param {string} string The string to convert.
  11316. * @returns {Array} Returns the converted array.
  11317. */
  11318. function stringToArray(string) {
  11319. return hasUnicode(string)
  11320. ? unicodeToArray(string)
  11321. : asciiToArray(string);
  11322. }
  11323. /**
  11324. * Converts a Unicode `string` to an array.
  11325. *
  11326. * @private
  11327. * @param {string} string The string to convert.
  11328. * @returns {Array} Returns the converted array.
  11329. */
  11330. function unicodeToArray(string) {
  11331. return string.match(reUnicode) || [];
  11332. }
  11333. /**
  11334. * Splits a Unicode `string` into an array of its words.
  11335. *
  11336. * @private
  11337. * @param {string} The string to inspect.
  11338. * @returns {Array} Returns the words of `string`.
  11339. */
  11340. function unicodeWords(string) {
  11341. return string.match(reUnicodeWord) || [];
  11342. }
  11343. /** Used for built-in method references. */
  11344. var objectProto = Object.prototype;
  11345. /**
  11346. * Used to resolve the
  11347. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  11348. * of values.
  11349. */
  11350. var objectToString = objectProto.toString;
  11351. /** Built-in value references. */
  11352. var Symbol = root.Symbol;
  11353. /** Used to convert symbols to primitives and strings. */
  11354. var symbolProto = Symbol ? Symbol.prototype : undefined,
  11355. symbolToString = symbolProto ? symbolProto.toString : undefined;
  11356. /**
  11357. * The base implementation of `_.slice` without an iteratee call guard.
  11358. *
  11359. * @private
  11360. * @param {Array} array The array to slice.
  11361. * @param {number} [start=0] The start position.
  11362. * @param {number} [end=array.length] The end position.
  11363. * @returns {Array} Returns the slice of `array`.
  11364. */
  11365. function baseSlice(array, start, end) {
  11366. var index = -1,
  11367. length = array.length;
  11368. if (start < 0) {
  11369. start = -start > length ? 0 : (length + start);
  11370. }
  11371. end = end > length ? length : end;
  11372. if (end < 0) {
  11373. end += length;
  11374. }
  11375. length = start > end ? 0 : ((end - start) >>> 0);
  11376. start >>>= 0;
  11377. var result = Array(length);
  11378. while (++index < length) {
  11379. result[index] = array[index + start];
  11380. }
  11381. return result;
  11382. }
  11383. /**
  11384. * The base implementation of `_.toString` which doesn't convert nullish
  11385. * values to empty strings.
  11386. *
  11387. * @private
  11388. * @param {*} value The value to process.
  11389. * @returns {string} Returns the string.
  11390. */
  11391. function baseToString(value) {
  11392. // Exit early for strings to avoid a performance hit in some environments.
  11393. if (typeof value == 'string') {
  11394. return value;
  11395. }
  11396. if (isSymbol(value)) {
  11397. return symbolToString ? symbolToString.call(value) : '';
  11398. }
  11399. var result = (value + '');
  11400. return (result == '0' && (1 / value) == -Infinity) ? '-0' : result;
  11401. }
  11402. /**
  11403. * Casts `array` to a slice if it's needed.
  11404. *
  11405. * @private
  11406. * @param {Array} array The array to inspect.
  11407. * @param {number} start The start position.
  11408. * @param {number} [end=array.length] The end position.
  11409. * @returns {Array} Returns the cast slice.
  11410. */
  11411. function castSlice(array, start, end) {
  11412. var length = array.length;
  11413. end = end === undefined ? length : end;
  11414. return (!start && end >= length) ? array : baseSlice(array, start, end);
  11415. }
  11416. /**
  11417. * Creates a function like `_.lowerFirst`.
  11418. *
  11419. * @private
  11420. * @param {string} methodName The name of the `String` case method to use.
  11421. * @returns {Function} Returns the new case function.
  11422. */
  11423. function createCaseFirst(methodName) {
  11424. return function(string) {
  11425. string = toString(string);
  11426. var strSymbols = hasUnicode(string)
  11427. ? stringToArray(string)
  11428. : undefined;
  11429. var chr = strSymbols
  11430. ? strSymbols[0]
  11431. : string.charAt(0);
  11432. var trailing = strSymbols
  11433. ? castSlice(strSymbols, 1).join('')
  11434. : string.slice(1);
  11435. return chr[methodName]() + trailing;
  11436. };
  11437. }
  11438. /**
  11439. * Creates a function like `_.camelCase`.
  11440. *
  11441. * @private
  11442. * @param {Function} callback The function to combine each word.
  11443. * @returns {Function} Returns the new compounder function.
  11444. */
  11445. function createCompounder(callback) {
  11446. return function(string) {
  11447. return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
  11448. };
  11449. }
  11450. /**
  11451. * Checks if `value` is object-like. A value is object-like if it's not `null`
  11452. * and has a `typeof` result of "object".
  11453. *
  11454. * @static
  11455. * @memberOf _
  11456. * @since 4.0.0
  11457. * @category Lang
  11458. * @param {*} value The value to check.
  11459. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  11460. * @example
  11461. *
  11462. * _.isObjectLike({});
  11463. * // => true
  11464. *
  11465. * _.isObjectLike([1, 2, 3]);
  11466. * // => true
  11467. *
  11468. * _.isObjectLike(_.noop);
  11469. * // => false
  11470. *
  11471. * _.isObjectLike(null);
  11472. * // => false
  11473. */
  11474. function isObjectLike(value) {
  11475. return !!value && typeof value == 'object';
  11476. }
  11477. /**
  11478. * Checks if `value` is classified as a `Symbol` primitive or object.
  11479. *
  11480. * @static
  11481. * @memberOf _
  11482. * @since 4.0.0
  11483. * @category Lang
  11484. * @param {*} value The value to check.
  11485. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  11486. * @example
  11487. *
  11488. * _.isSymbol(Symbol.iterator);
  11489. * // => true
  11490. *
  11491. * _.isSymbol('abc');
  11492. * // => false
  11493. */
  11494. function isSymbol(value) {
  11495. return typeof value == 'symbol' ||
  11496. (isObjectLike(value) && objectToString.call(value) == symbolTag);
  11497. }
  11498. /**
  11499. * Converts `value` to a string. An empty string is returned for `null`
  11500. * and `undefined` values. The sign of `-0` is preserved.
  11501. *
  11502. * @static
  11503. * @memberOf _
  11504. * @since 4.0.0
  11505. * @category Lang
  11506. * @param {*} value The value to process.
  11507. * @returns {string} Returns the string.
  11508. * @example
  11509. *
  11510. * _.toString(null);
  11511. * // => ''
  11512. *
  11513. * _.toString(-0);
  11514. * // => '-0'
  11515. *
  11516. * _.toString([1, 2, 3]);
  11517. * // => '1,2,3'
  11518. */
  11519. function toString(value) {
  11520. return value == null ? '' : baseToString(value);
  11521. }
  11522. /**
  11523. * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
  11524. *
  11525. * @static
  11526. * @memberOf _
  11527. * @since 3.0.0
  11528. * @category String
  11529. * @param {string} [string=''] The string to convert.
  11530. * @returns {string} Returns the camel cased string.
  11531. * @example
  11532. *
  11533. * _.camelCase('Foo Bar');
  11534. * // => 'fooBar'
  11535. *
  11536. * _.camelCase('--foo-bar--');
  11537. * // => 'fooBar'
  11538. *
  11539. * _.camelCase('__FOO_BAR__');
  11540. * // => 'fooBar'
  11541. */
  11542. var camelCase = createCompounder(function(result, word, index) {
  11543. word = word.toLowerCase();
  11544. return result + (index ? capitalize(word) : word);
  11545. });
  11546. /**
  11547. * Converts the first character of `string` to upper case and the remaining
  11548. * to lower case.
  11549. *
  11550. * @static
  11551. * @memberOf _
  11552. * @since 3.0.0
  11553. * @category String
  11554. * @param {string} [string=''] The string to capitalize.
  11555. * @returns {string} Returns the capitalized string.
  11556. * @example
  11557. *
  11558. * _.capitalize('FRED');
  11559. * // => 'Fred'
  11560. */
  11561. function capitalize(string) {
  11562. return upperFirst(toString(string).toLowerCase());
  11563. }
  11564. /**
  11565. * Deburrs `string` by converting
  11566. * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
  11567. * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
  11568. * letters to basic Latin letters and removing
  11569. * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
  11570. *
  11571. * @static
  11572. * @memberOf _
  11573. * @since 3.0.0
  11574. * @category String
  11575. * @param {string} [string=''] The string to deburr.
  11576. * @returns {string} Returns the deburred string.
  11577. * @example
  11578. *
  11579. * _.deburr('déjà vu');
  11580. * // => 'deja vu'
  11581. */
  11582. function deburr(string) {
  11583. string = toString(string);
  11584. return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
  11585. }
  11586. /**
  11587. * Converts the first character of `string` to upper case.
  11588. *
  11589. * @static
  11590. * @memberOf _
  11591. * @since 4.0.0
  11592. * @category String
  11593. * @param {string} [string=''] The string to convert.
  11594. * @returns {string} Returns the converted string.
  11595. * @example
  11596. *
  11597. * _.upperFirst('fred');
  11598. * // => 'Fred'
  11599. *
  11600. * _.upperFirst('FRED');
  11601. * // => 'FRED'
  11602. */
  11603. var upperFirst = createCaseFirst('toUpperCase');
  11604. /**
  11605. * Splits `string` into an array of its words.
  11606. *
  11607. * @static
  11608. * @memberOf _
  11609. * @since 3.0.0
  11610. * @category String
  11611. * @param {string} [string=''] The string to inspect.
  11612. * @param {RegExp|string} [pattern] The pattern to match words.
  11613. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  11614. * @returns {Array} Returns the words of `string`.
  11615. * @example
  11616. *
  11617. * _.words('fred, barney, & pebbles');
  11618. * // => ['fred', 'barney', 'pebbles']
  11619. *
  11620. * _.words('fred, barney, & pebbles', /[^, ]+/g);
  11621. * // => ['fred', 'barney', '&', 'pebbles']
  11622. */
  11623. function words(string, pattern, guard) {
  11624. string = toString(string);
  11625. pattern = pattern;
  11626. if (pattern === undefined) {
  11627. return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
  11628. }
  11629. return string.match(pattern) || [];
  11630. }
  11631. lodash_camelcase = camelCase;
  11632. return lodash_camelcase;
  11633. }
  11634. var hasRequiredLocalsConvention;
  11635. function requireLocalsConvention () {
  11636. if (hasRequiredLocalsConvention) return localsConvention;
  11637. hasRequiredLocalsConvention = 1;
  11638. Object.defineProperty(localsConvention, "__esModule", {
  11639. value: true
  11640. });
  11641. localsConvention.makeLocalsConventionReducer = makeLocalsConventionReducer;
  11642. var _lodash = _interopRequireDefault(/*@__PURE__*/ requireLodash_camelcase());
  11643. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11644. function dashesCamelCase(string) {
  11645. return string.replace(/-+(\w)/g, (_, firstLetter) => firstLetter.toUpperCase());
  11646. }
  11647. function makeLocalsConventionReducer(localsConvention, inputFile) {
  11648. const isFunc = typeof localsConvention === "function";
  11649. return (tokens, [className, value]) => {
  11650. if (isFunc) {
  11651. const convention = localsConvention(className, value, inputFile);
  11652. tokens[convention] = value;
  11653. return tokens;
  11654. }
  11655. switch (localsConvention) {
  11656. case "camelCase":
  11657. tokens[className] = value;
  11658. tokens[(0, _lodash.default)(className)] = value;
  11659. break;
  11660. case "camelCaseOnly":
  11661. tokens[(0, _lodash.default)(className)] = value;
  11662. break;
  11663. case "dashes":
  11664. tokens[className] = value;
  11665. tokens[dashesCamelCase(className)] = value;
  11666. break;
  11667. case "dashesOnly":
  11668. tokens[dashesCamelCase(className)] = value;
  11669. break;
  11670. }
  11671. return tokens;
  11672. };
  11673. }
  11674. return localsConvention;
  11675. }
  11676. var FileSystemLoader = {};
  11677. var hasRequiredFileSystemLoader;
  11678. function requireFileSystemLoader () {
  11679. if (hasRequiredFileSystemLoader) return FileSystemLoader;
  11680. hasRequiredFileSystemLoader = 1;
  11681. Object.defineProperty(FileSystemLoader, "__esModule", {
  11682. value: true
  11683. });
  11684. FileSystemLoader.default = void 0;
  11685. var _postcss = _interopRequireDefault(require$$0$1);
  11686. var _path = _interopRequireDefault(path$1);
  11687. var _Parser = _interopRequireDefault(/*@__PURE__*/ requireParser$1());
  11688. var _fs = /*@__PURE__*/ requireFs();
  11689. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11690. // Initially copied from https://github.com/css-modules/css-modules-loader-core
  11691. class Core {
  11692. constructor(plugins) {
  11693. this.plugins = plugins || Core.defaultPlugins;
  11694. }
  11695. async load(sourceString, sourcePath, trace, pathFetcher) {
  11696. const parser = new _Parser.default(pathFetcher, trace);
  11697. const plugins = this.plugins.concat([parser.plugin()]);
  11698. const result = await (0, _postcss.default)(plugins).process(sourceString, {
  11699. from: sourcePath
  11700. });
  11701. return {
  11702. injectableSource: result.css,
  11703. exportTokens: parser.exportTokens
  11704. };
  11705. }
  11706. } // Sorts dependencies in the following way:
  11707. // AAA comes before AA and A
  11708. // AB comes after AA and before A
  11709. // All Bs come after all As
  11710. // This ensures that the files are always returned in the following order:
  11711. // - In the order they were required, except
  11712. // - After all their dependencies
  11713. const traceKeySorter = (a, b) => {
  11714. if (a.length < b.length) {
  11715. return a < b.substring(0, a.length) ? -1 : 1;
  11716. }
  11717. if (a.length > b.length) {
  11718. return a.substring(0, b.length) <= b ? -1 : 1;
  11719. }
  11720. return a < b ? -1 : 1;
  11721. };
  11722. let FileSystemLoader$1 = class FileSystemLoader {
  11723. constructor(root, plugins, fileResolve) {
  11724. if (root === "/" && process.platform === "win32") {
  11725. const cwdDrive = process.cwd().slice(0, 3);
  11726. if (!/^[A-Za-z]:\\$/.test(cwdDrive)) {
  11727. throw new Error(`Failed to obtain root from "${process.cwd()}".`);
  11728. }
  11729. root = cwdDrive;
  11730. }
  11731. this.root = root;
  11732. this.fileResolve = fileResolve;
  11733. this.sources = {};
  11734. this.traces = {};
  11735. this.importNr = 0;
  11736. this.core = new Core(plugins);
  11737. this.tokensByFile = {};
  11738. this.fs = (0, _fs.getFileSystem)();
  11739. }
  11740. async fetch(_newPath, relativeTo, _trace) {
  11741. const newPath = _newPath.replace(/^["']|["']$/g, "");
  11742. const trace = _trace || String.fromCharCode(this.importNr++);
  11743. const useFileResolve = typeof this.fileResolve === "function";
  11744. const fileResolvedPath = useFileResolve ? await this.fileResolve(newPath, relativeTo) : await Promise.resolve();
  11745. if (fileResolvedPath && !_path.default.isAbsolute(fileResolvedPath)) {
  11746. throw new Error('The returned path from the "fileResolve" option must be absolute.');
  11747. }
  11748. const relativeDir = _path.default.dirname(relativeTo);
  11749. const rootRelativePath = fileResolvedPath || _path.default.resolve(relativeDir, newPath);
  11750. 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
  11751. if (!useFileResolve && newPath[0] !== "." && !_path.default.isAbsolute(newPath)) {
  11752. try {
  11753. fileRelativePath = require.resolve(newPath);
  11754. } catch (e) {// noop
  11755. }
  11756. }
  11757. const tokens = this.tokensByFile[fileRelativePath];
  11758. if (tokens) return tokens;
  11759. return new Promise((resolve, reject) => {
  11760. this.fs.readFile(fileRelativePath, "utf-8", async (err, source) => {
  11761. if (err) reject(err);
  11762. const {
  11763. injectableSource,
  11764. exportTokens
  11765. } = await this.core.load(source, rootRelativePath, trace, this.fetch.bind(this));
  11766. this.sources[fileRelativePath] = injectableSource;
  11767. this.traces[trace] = fileRelativePath;
  11768. this.tokensByFile[fileRelativePath] = exportTokens;
  11769. resolve(exportTokens);
  11770. });
  11771. });
  11772. }
  11773. get finalSource() {
  11774. const traces = this.traces;
  11775. const sources = this.sources;
  11776. let written = new Set();
  11777. return Object.keys(traces).sort(traceKeySorter).map(key => {
  11778. const filename = traces[key];
  11779. if (written.has(filename)) {
  11780. return null;
  11781. }
  11782. written.add(filename);
  11783. return sources[filename];
  11784. }).join("");
  11785. }
  11786. };
  11787. FileSystemLoader.default = FileSystemLoader$1;
  11788. return FileSystemLoader;
  11789. }
  11790. var scoping = {};
  11791. var src$3 = {exports: {}};
  11792. var topologicalSort_1;
  11793. var hasRequiredTopologicalSort;
  11794. function requireTopologicalSort () {
  11795. if (hasRequiredTopologicalSort) return topologicalSort_1;
  11796. hasRequiredTopologicalSort = 1;
  11797. const PERMANENT_MARKER = 2;
  11798. const TEMPORARY_MARKER = 1;
  11799. function createError(node, graph) {
  11800. const er = new Error("Nondeterministic import's order");
  11801. const related = graph[node];
  11802. const relatedNode = related.find(
  11803. (relatedNode) => graph[relatedNode].indexOf(node) > -1
  11804. );
  11805. er.nodes = [node, relatedNode];
  11806. return er;
  11807. }
  11808. function walkGraph(node, graph, state, result, strict) {
  11809. if (state[node] === PERMANENT_MARKER) {
  11810. return;
  11811. }
  11812. if (state[node] === TEMPORARY_MARKER) {
  11813. if (strict) {
  11814. return createError(node, graph);
  11815. }
  11816. return;
  11817. }
  11818. state[node] = TEMPORARY_MARKER;
  11819. const children = graph[node];
  11820. const length = children.length;
  11821. for (let i = 0; i < length; ++i) {
  11822. const error = walkGraph(children[i], graph, state, result, strict);
  11823. if (error instanceof Error) {
  11824. return error;
  11825. }
  11826. }
  11827. state[node] = PERMANENT_MARKER;
  11828. result.push(node);
  11829. }
  11830. function topologicalSort(graph, strict) {
  11831. const result = [];
  11832. const state = {};
  11833. const nodes = Object.keys(graph);
  11834. const length = nodes.length;
  11835. for (let i = 0; i < length; ++i) {
  11836. const er = walkGraph(nodes[i], graph, state, result, strict);
  11837. if (er instanceof Error) {
  11838. return er;
  11839. }
  11840. }
  11841. return result;
  11842. }
  11843. topologicalSort_1 = topologicalSort;
  11844. return topologicalSort_1;
  11845. }
  11846. var hasRequiredSrc$3;
  11847. function requireSrc$3 () {
  11848. if (hasRequiredSrc$3) return src$3.exports;
  11849. hasRequiredSrc$3 = 1;
  11850. const topologicalSort = /*@__PURE__*/ requireTopologicalSort();
  11851. const matchImports = /^(.+?)\s+from\s+(?:"([^"]+)"|'([^']+)'|(global))$/;
  11852. const icssImport = /^:import\((?:"([^"]+)"|'([^']+)')\)/;
  11853. const VISITED_MARKER = 1;
  11854. /**
  11855. * :import('G') {}
  11856. *
  11857. * Rule
  11858. * composes: ... from 'A'
  11859. * composes: ... from 'B'
  11860. * Rule
  11861. * composes: ... from 'A'
  11862. * composes: ... from 'A'
  11863. * composes: ... from 'C'
  11864. *
  11865. * Results in:
  11866. *
  11867. * graph: {
  11868. * G: [],
  11869. * A: [],
  11870. * B: ['A'],
  11871. * C: ['A'],
  11872. * }
  11873. */
  11874. function addImportToGraph(importId, parentId, graph, visited) {
  11875. const siblingsId = parentId + "_" + "siblings";
  11876. const visitedId = parentId + "_" + importId;
  11877. if (visited[visitedId] !== VISITED_MARKER) {
  11878. if (!Array.isArray(visited[siblingsId])) {
  11879. visited[siblingsId] = [];
  11880. }
  11881. const siblings = visited[siblingsId];
  11882. if (Array.isArray(graph[importId])) {
  11883. graph[importId] = graph[importId].concat(siblings);
  11884. } else {
  11885. graph[importId] = siblings.slice();
  11886. }
  11887. visited[visitedId] = VISITED_MARKER;
  11888. siblings.push(importId);
  11889. }
  11890. }
  11891. src$3.exports = (options = {}) => {
  11892. let importIndex = 0;
  11893. const createImportedName =
  11894. typeof options.createImportedName !== "function"
  11895. ? (importName /*, path*/) =>
  11896. `i__imported_${importName.replace(/\W/g, "_")}_${importIndex++}`
  11897. : options.createImportedName;
  11898. const failOnWrongOrder = options.failOnWrongOrder;
  11899. return {
  11900. postcssPlugin: "postcss-modules-extract-imports",
  11901. prepare() {
  11902. const graph = {};
  11903. const visited = {};
  11904. const existingImports = {};
  11905. const importDecls = {};
  11906. const imports = {};
  11907. return {
  11908. Once(root, postcss) {
  11909. // Check the existing imports order and save refs
  11910. root.walkRules((rule) => {
  11911. const matches = icssImport.exec(rule.selector);
  11912. if (matches) {
  11913. const [, /*match*/ doubleQuotePath, singleQuotePath] = matches;
  11914. const importPath = doubleQuotePath || singleQuotePath;
  11915. addImportToGraph(importPath, "root", graph, visited);
  11916. existingImports[importPath] = rule;
  11917. }
  11918. });
  11919. root.walkDecls(/^composes$/, (declaration) => {
  11920. const multiple = declaration.value.split(",");
  11921. const values = [];
  11922. multiple.forEach((value) => {
  11923. const matches = value.trim().match(matchImports);
  11924. if (!matches) {
  11925. values.push(value);
  11926. return;
  11927. }
  11928. let tmpSymbols;
  11929. let [
  11930. ,
  11931. /*match*/ symbols,
  11932. doubleQuotePath,
  11933. singleQuotePath,
  11934. global,
  11935. ] = matches;
  11936. if (global) {
  11937. // Composing globals simply means changing these classes to wrap them in global(name)
  11938. tmpSymbols = symbols.split(/\s+/).map((s) => `global(${s})`);
  11939. } else {
  11940. const importPath = doubleQuotePath || singleQuotePath;
  11941. let parent = declaration.parent;
  11942. let parentIndexes = "";
  11943. while (parent.type !== "root") {
  11944. parentIndexes =
  11945. parent.parent.index(parent) + "_" + parentIndexes;
  11946. parent = parent.parent;
  11947. }
  11948. const { selector } = declaration.parent;
  11949. const parentRule = `_${parentIndexes}${selector}`;
  11950. addImportToGraph(importPath, parentRule, graph, visited);
  11951. importDecls[importPath] = declaration;
  11952. imports[importPath] = imports[importPath] || {};
  11953. tmpSymbols = symbols.split(/\s+/).map((s) => {
  11954. if (!imports[importPath][s]) {
  11955. imports[importPath][s] = createImportedName(s, importPath);
  11956. }
  11957. return imports[importPath][s];
  11958. });
  11959. }
  11960. values.push(tmpSymbols.join(" "));
  11961. });
  11962. declaration.value = values.join(", ");
  11963. });
  11964. const importsOrder = topologicalSort(graph, failOnWrongOrder);
  11965. if (importsOrder instanceof Error) {
  11966. const importPath = importsOrder.nodes.find((importPath) =>
  11967. // eslint-disable-next-line no-prototype-builtins
  11968. importDecls.hasOwnProperty(importPath)
  11969. );
  11970. const decl = importDecls[importPath];
  11971. throw decl.error(
  11972. "Failed to resolve order of composed modules " +
  11973. importsOrder.nodes
  11974. .map((importPath) => "`" + importPath + "`")
  11975. .join(", ") +
  11976. ".",
  11977. {
  11978. plugin: "postcss-modules-extract-imports",
  11979. word: "composes",
  11980. }
  11981. );
  11982. }
  11983. let lastImportRule;
  11984. importsOrder.forEach((path) => {
  11985. const importedSymbols = imports[path];
  11986. let rule = existingImports[path];
  11987. if (!rule && importedSymbols) {
  11988. rule = postcss.rule({
  11989. selector: `:import("${path}")`,
  11990. raws: { after: "\n" },
  11991. });
  11992. if (lastImportRule) {
  11993. root.insertAfter(lastImportRule, rule);
  11994. } else {
  11995. root.prepend(rule);
  11996. }
  11997. }
  11998. lastImportRule = rule;
  11999. if (!importedSymbols) {
  12000. return;
  12001. }
  12002. Object.keys(importedSymbols).forEach((importedSymbol) => {
  12003. rule.append(
  12004. postcss.decl({
  12005. value: importedSymbol,
  12006. prop: importedSymbols[importedSymbol],
  12007. raws: { before: "\n " },
  12008. })
  12009. );
  12010. });
  12011. });
  12012. },
  12013. };
  12014. },
  12015. };
  12016. };
  12017. src$3.exports.postcss = true;
  12018. return src$3.exports;
  12019. }
  12020. var wasmHash = {exports: {}};
  12021. /*
  12022. MIT License http://www.opensource.org/licenses/mit-license.php
  12023. Author Tobias Koppers @sokra
  12024. */
  12025. var hasRequiredWasmHash;
  12026. function requireWasmHash () {
  12027. if (hasRequiredWasmHash) return wasmHash.exports;
  12028. hasRequiredWasmHash = 1;
  12029. // 65536 is the size of a wasm memory page
  12030. // 64 is the maximum chunk size for every possible wasm hash implementation
  12031. // 4 is the maximum number of bytes per char for string encoding (max is utf-8)
  12032. // ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64
  12033. const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & -4;
  12034. class WasmHash {
  12035. /**
  12036. * @param {WebAssembly.Instance} instance wasm instance
  12037. * @param {WebAssembly.Instance[]} instancesPool pool of instances
  12038. * @param {number} chunkSize size of data chunks passed to wasm
  12039. * @param {number} digestSize size of digest returned by wasm
  12040. */
  12041. constructor(instance, instancesPool, chunkSize, digestSize) {
  12042. const exports = /** @type {any} */ (instance.exports);
  12043. exports.init();
  12044. this.exports = exports;
  12045. this.mem = Buffer.from(exports.memory.buffer, 0, 65536);
  12046. this.buffered = 0;
  12047. this.instancesPool = instancesPool;
  12048. this.chunkSize = chunkSize;
  12049. this.digestSize = digestSize;
  12050. }
  12051. reset() {
  12052. this.buffered = 0;
  12053. this.exports.init();
  12054. }
  12055. /**
  12056. * @param {Buffer | string} data data
  12057. * @param {BufferEncoding=} encoding encoding
  12058. * @returns {this} itself
  12059. */
  12060. update(data, encoding) {
  12061. if (typeof data === "string") {
  12062. while (data.length > MAX_SHORT_STRING) {
  12063. this._updateWithShortString(data.slice(0, MAX_SHORT_STRING), encoding);
  12064. data = data.slice(MAX_SHORT_STRING);
  12065. }
  12066. this._updateWithShortString(data, encoding);
  12067. return this;
  12068. }
  12069. this._updateWithBuffer(data);
  12070. return this;
  12071. }
  12072. /**
  12073. * @param {string} data data
  12074. * @param {BufferEncoding=} encoding encoding
  12075. * @returns {void}
  12076. */
  12077. _updateWithShortString(data, encoding) {
  12078. const { exports, buffered, mem, chunkSize } = this;
  12079. let endPos;
  12080. if (data.length < 70) {
  12081. if (!encoding || encoding === "utf-8" || encoding === "utf8") {
  12082. endPos = buffered;
  12083. for (let i = 0; i < data.length; i++) {
  12084. const cc = data.charCodeAt(i);
  12085. if (cc < 0x80) {
  12086. mem[endPos++] = cc;
  12087. } else if (cc < 0x800) {
  12088. mem[endPos] = (cc >> 6) | 0xc0;
  12089. mem[endPos + 1] = (cc & 0x3f) | 0x80;
  12090. endPos += 2;
  12091. } else {
  12092. // bail-out for weird chars
  12093. endPos += mem.write(data.slice(i), endPos, encoding);
  12094. break;
  12095. }
  12096. }
  12097. } else if (encoding === "latin1") {
  12098. endPos = buffered;
  12099. for (let i = 0; i < data.length; i++) {
  12100. const cc = data.charCodeAt(i);
  12101. mem[endPos++] = cc;
  12102. }
  12103. } else {
  12104. endPos = buffered + mem.write(data, buffered, encoding);
  12105. }
  12106. } else {
  12107. endPos = buffered + mem.write(data, buffered, encoding);
  12108. }
  12109. if (endPos < chunkSize) {
  12110. this.buffered = endPos;
  12111. } else {
  12112. const l = endPos & ~(this.chunkSize - 1);
  12113. exports.update(l);
  12114. const newBuffered = endPos - l;
  12115. this.buffered = newBuffered;
  12116. if (newBuffered > 0) {
  12117. mem.copyWithin(0, l, endPos);
  12118. }
  12119. }
  12120. }
  12121. /**
  12122. * @param {Buffer} data data
  12123. * @returns {void}
  12124. */
  12125. _updateWithBuffer(data) {
  12126. const { exports, buffered, mem } = this;
  12127. const length = data.length;
  12128. if (buffered + length < this.chunkSize) {
  12129. data.copy(mem, buffered, 0, length);
  12130. this.buffered += length;
  12131. } else {
  12132. const l = (buffered + length) & ~(this.chunkSize - 1);
  12133. if (l > 65536) {
  12134. let i = 65536 - buffered;
  12135. data.copy(mem, buffered, 0, i);
  12136. exports.update(65536);
  12137. const stop = l - buffered - 65536;
  12138. while (i < stop) {
  12139. data.copy(mem, 0, i, i + 65536);
  12140. exports.update(65536);
  12141. i += 65536;
  12142. }
  12143. data.copy(mem, 0, i, l - buffered);
  12144. exports.update(l - buffered - i);
  12145. } else {
  12146. data.copy(mem, buffered, 0, l - buffered);
  12147. exports.update(l);
  12148. }
  12149. const newBuffered = length + buffered - l;
  12150. this.buffered = newBuffered;
  12151. if (newBuffered > 0) {
  12152. data.copy(mem, 0, length - newBuffered, length);
  12153. }
  12154. }
  12155. }
  12156. digest(type) {
  12157. const { exports, buffered, mem, digestSize } = this;
  12158. exports.final(buffered);
  12159. this.instancesPool.push(this);
  12160. const hex = mem.toString("latin1", 0, digestSize);
  12161. if (type === "hex") {
  12162. return hex;
  12163. }
  12164. if (type === "binary" || !type) {
  12165. return Buffer.from(hex, "hex");
  12166. }
  12167. return Buffer.from(hex, "hex").toString(type);
  12168. }
  12169. }
  12170. const create = (wasmModule, instancesPool, chunkSize, digestSize) => {
  12171. if (instancesPool.length > 0) {
  12172. const old = instancesPool.pop();
  12173. old.reset();
  12174. return old;
  12175. } else {
  12176. return new WasmHash(
  12177. new WebAssembly.Instance(wasmModule),
  12178. instancesPool,
  12179. chunkSize,
  12180. digestSize
  12181. );
  12182. }
  12183. };
  12184. wasmHash.exports = create;
  12185. wasmHash.exports.MAX_SHORT_STRING = MAX_SHORT_STRING;
  12186. return wasmHash.exports;
  12187. }
  12188. /*
  12189. MIT License http://www.opensource.org/licenses/mit-license.php
  12190. Author Tobias Koppers @sokra
  12191. */
  12192. var xxhash64_1;
  12193. var hasRequiredXxhash64;
  12194. function requireXxhash64 () {
  12195. if (hasRequiredXxhash64) return xxhash64_1;
  12196. hasRequiredXxhash64 = 1;
  12197. const create = /*@__PURE__*/ requireWasmHash();
  12198. //#region wasm code: xxhash64 (../../../assembly/hash/xxhash64.asm.ts) --initialMemory 1
  12199. const xxhash64 = new WebAssembly.Module(
  12200. Buffer.from(
  12201. // 1173 bytes
  12202. "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",
  12203. "base64"
  12204. )
  12205. );
  12206. //#endregion
  12207. xxhash64_1 = create.bind(null, xxhash64, [], 32, 16);
  12208. return xxhash64_1;
  12209. }
  12210. var BatchedHash_1;
  12211. var hasRequiredBatchedHash;
  12212. function requireBatchedHash () {
  12213. if (hasRequiredBatchedHash) return BatchedHash_1;
  12214. hasRequiredBatchedHash = 1;
  12215. const MAX_SHORT_STRING = /*@__PURE__*/ requireWasmHash().MAX_SHORT_STRING;
  12216. class BatchedHash {
  12217. constructor(hash) {
  12218. this.string = undefined;
  12219. this.encoding = undefined;
  12220. this.hash = hash;
  12221. }
  12222. /**
  12223. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  12224. * @param {string|Buffer} data data
  12225. * @param {string=} inputEncoding data encoding
  12226. * @returns {this} updated hash
  12227. */
  12228. update(data, inputEncoding) {
  12229. if (this.string !== undefined) {
  12230. if (
  12231. typeof data === "string" &&
  12232. inputEncoding === this.encoding &&
  12233. this.string.length + data.length < MAX_SHORT_STRING
  12234. ) {
  12235. this.string += data;
  12236. return this;
  12237. }
  12238. this.hash.update(this.string, this.encoding);
  12239. this.string = undefined;
  12240. }
  12241. if (typeof data === "string") {
  12242. if (
  12243. data.length < MAX_SHORT_STRING &&
  12244. // base64 encoding is not valid since it may contain padding chars
  12245. (!inputEncoding || !inputEncoding.startsWith("ba"))
  12246. ) {
  12247. this.string = data;
  12248. this.encoding = inputEncoding;
  12249. } else {
  12250. this.hash.update(data, inputEncoding);
  12251. }
  12252. } else {
  12253. this.hash.update(data);
  12254. }
  12255. return this;
  12256. }
  12257. /**
  12258. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  12259. * @param {string=} encoding encoding of the return value
  12260. * @returns {string|Buffer} digest
  12261. */
  12262. digest(encoding) {
  12263. if (this.string !== undefined) {
  12264. this.hash.update(this.string, this.encoding);
  12265. }
  12266. return this.hash.digest(encoding);
  12267. }
  12268. }
  12269. BatchedHash_1 = BatchedHash;
  12270. return BatchedHash_1;
  12271. }
  12272. /*
  12273. MIT License http://www.opensource.org/licenses/mit-license.php
  12274. Author Tobias Koppers @sokra
  12275. */
  12276. var md4_1;
  12277. var hasRequiredMd4;
  12278. function requireMd4 () {
  12279. if (hasRequiredMd4) return md4_1;
  12280. hasRequiredMd4 = 1;
  12281. const create = /*@__PURE__*/ requireWasmHash();
  12282. //#region wasm code: md4 (../../../assembly/hash/md4.asm.ts) --initialMemory 1
  12283. const md4 = new WebAssembly.Module(
  12284. Buffer.from(
  12285. // 2150 bytes
  12286. "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=",
  12287. "base64"
  12288. )
  12289. );
  12290. //#endregion
  12291. md4_1 = create.bind(null, md4, [], 64, 32);
  12292. return md4_1;
  12293. }
  12294. var BulkUpdateDecorator_1;
  12295. var hasRequiredBulkUpdateDecorator;
  12296. function requireBulkUpdateDecorator () {
  12297. if (hasRequiredBulkUpdateDecorator) return BulkUpdateDecorator_1;
  12298. hasRequiredBulkUpdateDecorator = 1;
  12299. const BULK_SIZE = 2000;
  12300. // We are using an object instead of a Map as this will stay static during the runtime
  12301. // so access to it can be optimized by v8
  12302. const digestCaches = {};
  12303. class BulkUpdateDecorator {
  12304. /**
  12305. * @param {Hash | function(): Hash} hashOrFactory function to create a hash
  12306. * @param {string=} hashKey key for caching
  12307. */
  12308. constructor(hashOrFactory, hashKey) {
  12309. this.hashKey = hashKey;
  12310. if (typeof hashOrFactory === "function") {
  12311. this.hashFactory = hashOrFactory;
  12312. this.hash = undefined;
  12313. } else {
  12314. this.hashFactory = undefined;
  12315. this.hash = hashOrFactory;
  12316. }
  12317. this.buffer = "";
  12318. }
  12319. /**
  12320. * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
  12321. * @param {string|Buffer} data data
  12322. * @param {string=} inputEncoding data encoding
  12323. * @returns {this} updated hash
  12324. */
  12325. update(data, inputEncoding) {
  12326. if (
  12327. inputEncoding !== undefined ||
  12328. typeof data !== "string" ||
  12329. data.length > BULK_SIZE
  12330. ) {
  12331. if (this.hash === undefined) {
  12332. this.hash = this.hashFactory();
  12333. }
  12334. if (this.buffer.length > 0) {
  12335. this.hash.update(this.buffer);
  12336. this.buffer = "";
  12337. }
  12338. this.hash.update(data, inputEncoding);
  12339. } else {
  12340. this.buffer += data;
  12341. if (this.buffer.length > BULK_SIZE) {
  12342. if (this.hash === undefined) {
  12343. this.hash = this.hashFactory();
  12344. }
  12345. this.hash.update(this.buffer);
  12346. this.buffer = "";
  12347. }
  12348. }
  12349. return this;
  12350. }
  12351. /**
  12352. * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
  12353. * @param {string=} encoding encoding of the return value
  12354. * @returns {string|Buffer} digest
  12355. */
  12356. digest(encoding) {
  12357. let digestCache;
  12358. const buffer = this.buffer;
  12359. if (this.hash === undefined) {
  12360. // short data for hash, we can use caching
  12361. const cacheKey = `${this.hashKey}-${encoding}`;
  12362. digestCache = digestCaches[cacheKey];
  12363. if (digestCache === undefined) {
  12364. digestCache = digestCaches[cacheKey] = new Map();
  12365. }
  12366. const cacheEntry = digestCache.get(buffer);
  12367. if (cacheEntry !== undefined) {
  12368. return cacheEntry;
  12369. }
  12370. this.hash = this.hashFactory();
  12371. }
  12372. if (buffer.length > 0) {
  12373. this.hash.update(buffer);
  12374. }
  12375. const digestResult = this.hash.digest(encoding);
  12376. if (digestCache !== undefined) {
  12377. digestCache.set(buffer, digestResult);
  12378. }
  12379. return digestResult;
  12380. }
  12381. }
  12382. BulkUpdateDecorator_1 = BulkUpdateDecorator;
  12383. return BulkUpdateDecorator_1;
  12384. }
  12385. var getHashDigest_1;
  12386. var hasRequiredGetHashDigest;
  12387. function requireGetHashDigest () {
  12388. if (hasRequiredGetHashDigest) return getHashDigest_1;
  12389. hasRequiredGetHashDigest = 1;
  12390. const baseEncodeTables = {
  12391. 26: "abcdefghijklmnopqrstuvwxyz",
  12392. 32: "123456789abcdefghjkmnpqrstuvwxyz", // no 0lio
  12393. 36: "0123456789abcdefghijklmnopqrstuvwxyz",
  12394. 49: "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no lIO
  12395. 52: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12396. 58: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no 0lIO
  12397. 62: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  12398. 64: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_",
  12399. };
  12400. /**
  12401. * @param {Uint32Array} uint32Array Treated as a long base-0x100000000 number, little endian
  12402. * @param {number} divisor The divisor
  12403. * @return {number} Modulo (remainder) of the division
  12404. */
  12405. function divmod32(uint32Array, divisor) {
  12406. let carry = 0;
  12407. for (let i = uint32Array.length - 1; i >= 0; i--) {
  12408. const value = carry * 0x100000000 + uint32Array[i];
  12409. carry = value % divisor;
  12410. uint32Array[i] = Math.floor(value / divisor);
  12411. }
  12412. return carry;
  12413. }
  12414. function encodeBufferToBase(buffer, base, length) {
  12415. const encodeTable = baseEncodeTables[base];
  12416. if (!encodeTable) {
  12417. throw new Error("Unknown encoding base" + base);
  12418. }
  12419. // Input bits are only enough to generate this many characters
  12420. const limit = Math.ceil((buffer.length * 8) / Math.log2(base));
  12421. length = Math.min(length, limit);
  12422. // Most of the crypto digests (if not all) has length a multiple of 4 bytes.
  12423. // Fewer numbers in the array means faster math.
  12424. const uint32Array = new Uint32Array(Math.ceil(buffer.length / 4));
  12425. // Make sure the input buffer data is copied and is not mutated by reference.
  12426. // divmod32() would corrupt the BulkUpdateDecorator cache otherwise.
  12427. buffer.copy(Buffer.from(uint32Array.buffer));
  12428. let output = "";
  12429. for (let i = 0; i < length; i++) {
  12430. output = encodeTable[divmod32(uint32Array, base)] + output;
  12431. }
  12432. return output;
  12433. }
  12434. let crypto = undefined;
  12435. let createXXHash64 = undefined;
  12436. let createMd4 = undefined;
  12437. let BatchedHash = undefined;
  12438. let BulkUpdateDecorator = undefined;
  12439. function getHashDigest(buffer, algorithm, digestType, maxLength) {
  12440. algorithm = algorithm || "xxhash64";
  12441. maxLength = maxLength || 9999;
  12442. let hash;
  12443. if (algorithm === "xxhash64") {
  12444. if (createXXHash64 === undefined) {
  12445. createXXHash64 = /*@__PURE__*/ requireXxhash64();
  12446. if (BatchedHash === undefined) {
  12447. BatchedHash = /*@__PURE__*/ requireBatchedHash();
  12448. }
  12449. }
  12450. hash = new BatchedHash(createXXHash64());
  12451. } else if (algorithm === "md4") {
  12452. if (createMd4 === undefined) {
  12453. createMd4 = /*@__PURE__*/ requireMd4();
  12454. if (BatchedHash === undefined) {
  12455. BatchedHash = /*@__PURE__*/ requireBatchedHash();
  12456. }
  12457. }
  12458. hash = new BatchedHash(createMd4());
  12459. } else if (algorithm === "native-md4") {
  12460. if (typeof crypto === "undefined") {
  12461. crypto = require("crypto");
  12462. if (BulkUpdateDecorator === undefined) {
  12463. BulkUpdateDecorator = /*@__PURE__*/ requireBulkUpdateDecorator();
  12464. }
  12465. }
  12466. hash = new BulkUpdateDecorator(() => crypto.createHash("md4"), "md4");
  12467. } else {
  12468. if (typeof crypto === "undefined") {
  12469. crypto = require("crypto");
  12470. if (BulkUpdateDecorator === undefined) {
  12471. BulkUpdateDecorator = /*@__PURE__*/ requireBulkUpdateDecorator();
  12472. }
  12473. }
  12474. hash = new BulkUpdateDecorator(
  12475. () => crypto.createHash(algorithm),
  12476. algorithm
  12477. );
  12478. }
  12479. hash.update(buffer);
  12480. if (
  12481. digestType === "base26" ||
  12482. digestType === "base32" ||
  12483. digestType === "base36" ||
  12484. digestType === "base49" ||
  12485. digestType === "base52" ||
  12486. digestType === "base58" ||
  12487. digestType === "base62" ||
  12488. digestType === "base64safe"
  12489. ) {
  12490. return encodeBufferToBase(
  12491. hash.digest(),
  12492. digestType === "base64safe" ? 64 : digestType.substr(4),
  12493. maxLength
  12494. );
  12495. }
  12496. return hash.digest(digestType || "hex").substr(0, maxLength);
  12497. }
  12498. getHashDigest_1 = getHashDigest;
  12499. return getHashDigest_1;
  12500. }
  12501. var interpolateName_1;
  12502. var hasRequiredInterpolateName;
  12503. function requireInterpolateName () {
  12504. if (hasRequiredInterpolateName) return interpolateName_1;
  12505. hasRequiredInterpolateName = 1;
  12506. const path = path$1;
  12507. const getHashDigest = /*@__PURE__*/ requireGetHashDigest();
  12508. function interpolateName(loaderContext, name, options = {}) {
  12509. let filename;
  12510. const hasQuery =
  12511. loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1;
  12512. if (typeof name === "function") {
  12513. filename = name(
  12514. loaderContext.resourcePath,
  12515. hasQuery ? loaderContext.resourceQuery : undefined
  12516. );
  12517. } else {
  12518. filename = name || "[hash].[ext]";
  12519. }
  12520. const context = options.context;
  12521. const content = options.content;
  12522. const regExp = options.regExp;
  12523. let ext = "bin";
  12524. let basename = "file";
  12525. let directory = "";
  12526. let folder = "";
  12527. let query = "";
  12528. if (loaderContext.resourcePath) {
  12529. const parsed = path.parse(loaderContext.resourcePath);
  12530. let resourcePath = loaderContext.resourcePath;
  12531. if (parsed.ext) {
  12532. ext = parsed.ext.substr(1);
  12533. }
  12534. if (parsed.dir) {
  12535. basename = parsed.name;
  12536. resourcePath = parsed.dir + path.sep;
  12537. }
  12538. if (typeof context !== "undefined") {
  12539. directory = path
  12540. .relative(context, resourcePath + "_")
  12541. .replace(/\\/g, "/")
  12542. .replace(/\.\.(\/)?/g, "_$1");
  12543. directory = directory.substr(0, directory.length - 1);
  12544. } else {
  12545. directory = resourcePath.replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
  12546. }
  12547. if (directory.length <= 1) {
  12548. directory = "";
  12549. } else {
  12550. // directory.length > 1
  12551. folder = path.basename(directory);
  12552. }
  12553. }
  12554. if (loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1) {
  12555. query = loaderContext.resourceQuery;
  12556. const hashIdx = query.indexOf("#");
  12557. if (hashIdx >= 0) {
  12558. query = query.substr(0, hashIdx);
  12559. }
  12560. }
  12561. let url = filename;
  12562. if (content) {
  12563. // Match hash template
  12564. url = url
  12565. // `hash` and `contenthash` are same in `loader-utils` context
  12566. // let's keep `hash` for backward compatibility
  12567. .replace(
  12568. /\[(?:([^[:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*(?:safe)?))?(?::(\d+))?\]/gi,
  12569. (all, hashType, digestType, maxLength) =>
  12570. getHashDigest(content, hashType, digestType, parseInt(maxLength, 10))
  12571. );
  12572. }
  12573. url = url
  12574. .replace(/\[ext\]/gi, () => ext)
  12575. .replace(/\[name\]/gi, () => basename)
  12576. .replace(/\[path\]/gi, () => directory)
  12577. .replace(/\[folder\]/gi, () => folder)
  12578. .replace(/\[query\]/gi, () => query);
  12579. if (regExp && loaderContext.resourcePath) {
  12580. const match = loaderContext.resourcePath.match(new RegExp(regExp));
  12581. match &&
  12582. match.forEach((matched, i) => {
  12583. url = url.replace(new RegExp("\\[" + i + "\\]", "ig"), matched);
  12584. });
  12585. }
  12586. if (
  12587. typeof loaderContext.options === "object" &&
  12588. typeof loaderContext.options.customInterpolateName === "function"
  12589. ) {
  12590. url = loaderContext.options.customInterpolateName.call(
  12591. loaderContext,
  12592. url,
  12593. name,
  12594. options
  12595. );
  12596. }
  12597. return url;
  12598. }
  12599. interpolateName_1 = interpolateName;
  12600. return interpolateName_1;
  12601. }
  12602. var genericNames;
  12603. var hasRequiredGenericNames;
  12604. function requireGenericNames () {
  12605. if (hasRequiredGenericNames) return genericNames;
  12606. hasRequiredGenericNames = 1;
  12607. var interpolateName = /*@__PURE__*/ requireInterpolateName();
  12608. var path = path$1;
  12609. /**
  12610. * @param {string} pattern
  12611. * @param {object} options
  12612. * @param {string} options.context
  12613. * @param {string} options.hashPrefix
  12614. * @return {function}
  12615. */
  12616. genericNames = function createGenerator(pattern, options) {
  12617. options = options || {};
  12618. var context =
  12619. options && typeof options.context === "string"
  12620. ? options.context
  12621. : process.cwd();
  12622. var hashPrefix =
  12623. options && typeof options.hashPrefix === "string" ? options.hashPrefix : "";
  12624. /**
  12625. * @param {string} localName Usually a class name
  12626. * @param {string} filepath Absolute path
  12627. * @return {string}
  12628. */
  12629. return function generate(localName, filepath) {
  12630. var name = pattern.replace(/\[local\]/gi, localName);
  12631. var loaderContext = {
  12632. resourcePath: filepath,
  12633. };
  12634. var loaderOptions = {
  12635. content:
  12636. hashPrefix +
  12637. path.relative(context, filepath).replace(/\\/g, "/") +
  12638. "\x00" +
  12639. localName,
  12640. context: context,
  12641. };
  12642. var genericName = interpolateName(loaderContext, name, loaderOptions);
  12643. return genericName
  12644. .replace(new RegExp("[^a-zA-Z0-9\\-_\u00A0-\uFFFF]", "g"), "-")
  12645. .replace(/^((-?[0-9])|--)/, "_$1");
  12646. };
  12647. };
  12648. return genericNames;
  12649. }
  12650. var src$2 = {exports: {}};
  12651. var dist = {exports: {}};
  12652. var processor = {exports: {}};
  12653. var parser = {exports: {}};
  12654. var root = {exports: {}};
  12655. var container = {exports: {}};
  12656. var node = {exports: {}};
  12657. var util = {};
  12658. var unesc = {exports: {}};
  12659. var hasRequiredUnesc;
  12660. function requireUnesc () {
  12661. if (hasRequiredUnesc) return unesc.exports;
  12662. hasRequiredUnesc = 1;
  12663. (function (module, exports) {
  12664. exports.__esModule = true;
  12665. exports["default"] = unesc;
  12666. // Many thanks for this post which made this migration much easier.
  12667. // https://mathiasbynens.be/notes/css-escapes
  12668. /**
  12669. *
  12670. * @param {string} str
  12671. * @returns {[string, number]|undefined}
  12672. */
  12673. function gobbleHex(str) {
  12674. var lower = str.toLowerCase();
  12675. var hex = '';
  12676. var spaceTerminated = false;
  12677. for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
  12678. var code = lower.charCodeAt(i);
  12679. // check to see if we are dealing with a valid hex char [a-f|0-9]
  12680. var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
  12681. // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
  12682. spaceTerminated = code === 32;
  12683. if (!valid) {
  12684. break;
  12685. }
  12686. hex += lower[i];
  12687. }
  12688. if (hex.length === 0) {
  12689. return undefined;
  12690. }
  12691. var codePoint = parseInt(hex, 16);
  12692. var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF;
  12693. // Add special case for
  12694. // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
  12695. // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
  12696. if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) {
  12697. return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)];
  12698. }
  12699. return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  12700. }
  12701. var CONTAINS_ESCAPE = /\\/;
  12702. function unesc(str) {
  12703. var needToProcess = CONTAINS_ESCAPE.test(str);
  12704. if (!needToProcess) {
  12705. return str;
  12706. }
  12707. var ret = "";
  12708. for (var i = 0; i < str.length; i++) {
  12709. if (str[i] === "\\") {
  12710. var gobbled = gobbleHex(str.slice(i + 1, i + 7));
  12711. if (gobbled !== undefined) {
  12712. ret += gobbled[0];
  12713. i += gobbled[1];
  12714. continue;
  12715. }
  12716. // Retain a pair of \\ if double escaped `\\\\`
  12717. // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
  12718. if (str[i + 1] === "\\") {
  12719. ret += "\\";
  12720. i++;
  12721. continue;
  12722. }
  12723. // if \\ is at the end of the string retain it
  12724. // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
  12725. if (str.length === i + 1) {
  12726. ret += str[i];
  12727. }
  12728. continue;
  12729. }
  12730. ret += str[i];
  12731. }
  12732. return ret;
  12733. }
  12734. module.exports = exports.default;
  12735. } (unesc, unesc.exports));
  12736. return unesc.exports;
  12737. }
  12738. var getProp = {exports: {}};
  12739. var hasRequiredGetProp;
  12740. function requireGetProp () {
  12741. if (hasRequiredGetProp) return getProp.exports;
  12742. hasRequiredGetProp = 1;
  12743. (function (module, exports) {
  12744. exports.__esModule = true;
  12745. exports["default"] = getProp;
  12746. function getProp(obj) {
  12747. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  12748. props[_key - 1] = arguments[_key];
  12749. }
  12750. while (props.length > 0) {
  12751. var prop = props.shift();
  12752. if (!obj[prop]) {
  12753. return undefined;
  12754. }
  12755. obj = obj[prop];
  12756. }
  12757. return obj;
  12758. }
  12759. module.exports = exports.default;
  12760. } (getProp, getProp.exports));
  12761. return getProp.exports;
  12762. }
  12763. var ensureObject = {exports: {}};
  12764. var hasRequiredEnsureObject;
  12765. function requireEnsureObject () {
  12766. if (hasRequiredEnsureObject) return ensureObject.exports;
  12767. hasRequiredEnsureObject = 1;
  12768. (function (module, exports) {
  12769. exports.__esModule = true;
  12770. exports["default"] = ensureObject;
  12771. function ensureObject(obj) {
  12772. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  12773. props[_key - 1] = arguments[_key];
  12774. }
  12775. while (props.length > 0) {
  12776. var prop = props.shift();
  12777. if (!obj[prop]) {
  12778. obj[prop] = {};
  12779. }
  12780. obj = obj[prop];
  12781. }
  12782. }
  12783. module.exports = exports.default;
  12784. } (ensureObject, ensureObject.exports));
  12785. return ensureObject.exports;
  12786. }
  12787. var stripComments = {exports: {}};
  12788. var hasRequiredStripComments;
  12789. function requireStripComments () {
  12790. if (hasRequiredStripComments) return stripComments.exports;
  12791. hasRequiredStripComments = 1;
  12792. (function (module, exports) {
  12793. exports.__esModule = true;
  12794. exports["default"] = stripComments;
  12795. function stripComments(str) {
  12796. var s = "";
  12797. var commentStart = str.indexOf("/*");
  12798. var lastEnd = 0;
  12799. while (commentStart >= 0) {
  12800. s = s + str.slice(lastEnd, commentStart);
  12801. var commentEnd = str.indexOf("*/", commentStart + 2);
  12802. if (commentEnd < 0) {
  12803. return s;
  12804. }
  12805. lastEnd = commentEnd + 2;
  12806. commentStart = str.indexOf("/*", lastEnd);
  12807. }
  12808. s = s + str.slice(lastEnd);
  12809. return s;
  12810. }
  12811. module.exports = exports.default;
  12812. } (stripComments, stripComments.exports));
  12813. return stripComments.exports;
  12814. }
  12815. var hasRequiredUtil;
  12816. function requireUtil () {
  12817. if (hasRequiredUtil) return util;
  12818. hasRequiredUtil = 1;
  12819. util.__esModule = true;
  12820. util.unesc = util.stripComments = util.getProp = util.ensureObject = void 0;
  12821. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc());
  12822. util.unesc = _unesc["default"];
  12823. var _getProp = _interopRequireDefault(/*@__PURE__*/ requireGetProp());
  12824. util.getProp = _getProp["default"];
  12825. var _ensureObject = _interopRequireDefault(/*@__PURE__*/ requireEnsureObject());
  12826. util.ensureObject = _ensureObject["default"];
  12827. var _stripComments = _interopRequireDefault(/*@__PURE__*/ requireStripComments());
  12828. util.stripComments = _stripComments["default"];
  12829. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  12830. return util;
  12831. }
  12832. var hasRequiredNode;
  12833. function requireNode () {
  12834. if (hasRequiredNode) return node.exports;
  12835. hasRequiredNode = 1;
  12836. (function (module, exports) {
  12837. exports.__esModule = true;
  12838. exports["default"] = void 0;
  12839. var _util = /*@__PURE__*/ requireUtil();
  12840. 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); } }
  12841. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  12842. var cloneNode = function cloneNode(obj, parent) {
  12843. if (typeof obj !== 'object' || obj === null) {
  12844. return obj;
  12845. }
  12846. var cloned = new obj.constructor();
  12847. for (var i in obj) {
  12848. if (!obj.hasOwnProperty(i)) {
  12849. continue;
  12850. }
  12851. var value = obj[i];
  12852. var type = typeof value;
  12853. if (i === 'parent' && type === 'object') {
  12854. if (parent) {
  12855. cloned[i] = parent;
  12856. }
  12857. } else if (value instanceof Array) {
  12858. cloned[i] = value.map(function (j) {
  12859. return cloneNode(j, cloned);
  12860. });
  12861. } else {
  12862. cloned[i] = cloneNode(value, cloned);
  12863. }
  12864. }
  12865. return cloned;
  12866. };
  12867. var Node = /*#__PURE__*/function () {
  12868. function Node(opts) {
  12869. if (opts === void 0) {
  12870. opts = {};
  12871. }
  12872. Object.assign(this, opts);
  12873. this.spaces = this.spaces || {};
  12874. this.spaces.before = this.spaces.before || '';
  12875. this.spaces.after = this.spaces.after || '';
  12876. }
  12877. var _proto = Node.prototype;
  12878. _proto.remove = function remove() {
  12879. if (this.parent) {
  12880. this.parent.removeChild(this);
  12881. }
  12882. this.parent = undefined;
  12883. return this;
  12884. };
  12885. _proto.replaceWith = function replaceWith() {
  12886. if (this.parent) {
  12887. for (var index in arguments) {
  12888. this.parent.insertBefore(this, arguments[index]);
  12889. }
  12890. this.remove();
  12891. }
  12892. return this;
  12893. };
  12894. _proto.next = function next() {
  12895. return this.parent.at(this.parent.index(this) + 1);
  12896. };
  12897. _proto.prev = function prev() {
  12898. return this.parent.at(this.parent.index(this) - 1);
  12899. };
  12900. _proto.clone = function clone(overrides) {
  12901. if (overrides === void 0) {
  12902. overrides = {};
  12903. }
  12904. var cloned = cloneNode(this);
  12905. for (var name in overrides) {
  12906. cloned[name] = overrides[name];
  12907. }
  12908. return cloned;
  12909. }
  12910. /**
  12911. * Some non-standard syntax doesn't follow normal escaping rules for css.
  12912. * This allows non standard syntax to be appended to an existing property
  12913. * by specifying the escaped value. By specifying the escaped value,
  12914. * illegal characters are allowed to be directly inserted into css output.
  12915. * @param {string} name the property to set
  12916. * @param {any} value the unescaped value of the property
  12917. * @param {string} valueEscaped optional. the escaped value of the property.
  12918. */;
  12919. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  12920. if (!this.raws) {
  12921. this.raws = {};
  12922. }
  12923. var originalValue = this[name];
  12924. var originalEscaped = this.raws[name];
  12925. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  12926. if (originalEscaped || valueEscaped !== value) {
  12927. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  12928. } else {
  12929. delete this.raws[name]; // delete any escaped value that was created by the setter.
  12930. }
  12931. }
  12932. /**
  12933. * Some non-standard syntax doesn't follow normal escaping rules for css.
  12934. * This allows the escaped value to be specified directly, allowing illegal
  12935. * characters to be directly inserted into css output.
  12936. * @param {string} name the property to set
  12937. * @param {any} value the unescaped value of the property
  12938. * @param {string} valueEscaped the escaped value of the property.
  12939. */;
  12940. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  12941. if (!this.raws) {
  12942. this.raws = {};
  12943. }
  12944. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  12945. this.raws[name] = valueEscaped;
  12946. }
  12947. /**
  12948. * When you want a value to passed through to CSS directly. This method
  12949. * deletes the corresponding raw value causing the stringifier to fallback
  12950. * to the unescaped value.
  12951. * @param {string} name the property to set.
  12952. * @param {any} value The value that is both escaped and unescaped.
  12953. */;
  12954. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  12955. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  12956. if (this.raws) {
  12957. delete this.raws[name];
  12958. }
  12959. }
  12960. /**
  12961. *
  12962. * @param {number} line The number (starting with 1)
  12963. * @param {number} column The column number (starting with 1)
  12964. */;
  12965. _proto.isAtPosition = function isAtPosition(line, column) {
  12966. if (this.source && this.source.start && this.source.end) {
  12967. if (this.source.start.line > line) {
  12968. return false;
  12969. }
  12970. if (this.source.end.line < line) {
  12971. return false;
  12972. }
  12973. if (this.source.start.line === line && this.source.start.column > column) {
  12974. return false;
  12975. }
  12976. if (this.source.end.line === line && this.source.end.column < column) {
  12977. return false;
  12978. }
  12979. return true;
  12980. }
  12981. return undefined;
  12982. };
  12983. _proto.stringifyProperty = function stringifyProperty(name) {
  12984. return this.raws && this.raws[name] || this[name];
  12985. };
  12986. _proto.valueToString = function valueToString() {
  12987. return String(this.stringifyProperty("value"));
  12988. };
  12989. _proto.toString = function toString() {
  12990. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  12991. };
  12992. _createClass(Node, [{
  12993. key: "rawSpaceBefore",
  12994. get: function get() {
  12995. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  12996. if (rawSpace === undefined) {
  12997. rawSpace = this.spaces && this.spaces.before;
  12998. }
  12999. return rawSpace || "";
  13000. },
  13001. set: function set(raw) {
  13002. (0, _util.ensureObject)(this, "raws", "spaces");
  13003. this.raws.spaces.before = raw;
  13004. }
  13005. }, {
  13006. key: "rawSpaceAfter",
  13007. get: function get() {
  13008. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  13009. if (rawSpace === undefined) {
  13010. rawSpace = this.spaces.after;
  13011. }
  13012. return rawSpace || "";
  13013. },
  13014. set: function set(raw) {
  13015. (0, _util.ensureObject)(this, "raws", "spaces");
  13016. this.raws.spaces.after = raw;
  13017. }
  13018. }]);
  13019. return Node;
  13020. }();
  13021. exports["default"] = Node;
  13022. module.exports = exports.default;
  13023. } (node, node.exports));
  13024. return node.exports;
  13025. }
  13026. var types$1 = {};
  13027. var hasRequiredTypes;
  13028. function requireTypes () {
  13029. if (hasRequiredTypes) return types$1;
  13030. hasRequiredTypes = 1;
  13031. types$1.__esModule = true;
  13032. 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;
  13033. var TAG = 'tag';
  13034. types$1.TAG = TAG;
  13035. var STRING = 'string';
  13036. types$1.STRING = STRING;
  13037. var SELECTOR = 'selector';
  13038. types$1.SELECTOR = SELECTOR;
  13039. var ROOT = 'root';
  13040. types$1.ROOT = ROOT;
  13041. var PSEUDO = 'pseudo';
  13042. types$1.PSEUDO = PSEUDO;
  13043. var NESTING = 'nesting';
  13044. types$1.NESTING = NESTING;
  13045. var ID = 'id';
  13046. types$1.ID = ID;
  13047. var COMMENT = 'comment';
  13048. types$1.COMMENT = COMMENT;
  13049. var COMBINATOR = 'combinator';
  13050. types$1.COMBINATOR = COMBINATOR;
  13051. var CLASS = 'class';
  13052. types$1.CLASS = CLASS;
  13053. var ATTRIBUTE = 'attribute';
  13054. types$1.ATTRIBUTE = ATTRIBUTE;
  13055. var UNIVERSAL = 'universal';
  13056. types$1.UNIVERSAL = UNIVERSAL;
  13057. return types$1;
  13058. }
  13059. var hasRequiredContainer;
  13060. function requireContainer () {
  13061. if (hasRequiredContainer) return container.exports;
  13062. hasRequiredContainer = 1;
  13063. (function (module, exports) {
  13064. exports.__esModule = true;
  13065. exports["default"] = void 0;
  13066. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13067. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes());
  13068. 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); }
  13069. 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; }
  13070. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13071. 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."); }
  13072. 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); }
  13073. 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; }
  13074. 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); } }
  13075. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13076. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13077. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13078. var Container = /*#__PURE__*/function (_Node) {
  13079. _inheritsLoose(Container, _Node);
  13080. function Container(opts) {
  13081. var _this;
  13082. _this = _Node.call(this, opts) || this;
  13083. if (!_this.nodes) {
  13084. _this.nodes = [];
  13085. }
  13086. return _this;
  13087. }
  13088. var _proto = Container.prototype;
  13089. _proto.append = function append(selector) {
  13090. selector.parent = this;
  13091. this.nodes.push(selector);
  13092. return this;
  13093. };
  13094. _proto.prepend = function prepend(selector) {
  13095. selector.parent = this;
  13096. this.nodes.unshift(selector);
  13097. return this;
  13098. };
  13099. _proto.at = function at(index) {
  13100. return this.nodes[index];
  13101. };
  13102. _proto.index = function index(child) {
  13103. if (typeof child === 'number') {
  13104. return child;
  13105. }
  13106. return this.nodes.indexOf(child);
  13107. };
  13108. _proto.removeChild = function removeChild(child) {
  13109. child = this.index(child);
  13110. this.at(child).parent = undefined;
  13111. this.nodes.splice(child, 1);
  13112. var index;
  13113. for (var id in this.indexes) {
  13114. index = this.indexes[id];
  13115. if (index >= child) {
  13116. this.indexes[id] = index - 1;
  13117. }
  13118. }
  13119. return this;
  13120. };
  13121. _proto.removeAll = function removeAll() {
  13122. for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) {
  13123. var node = _step.value;
  13124. node.parent = undefined;
  13125. }
  13126. this.nodes = [];
  13127. return this;
  13128. };
  13129. _proto.empty = function empty() {
  13130. return this.removeAll();
  13131. };
  13132. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  13133. newNode.parent = this;
  13134. var oldIndex = this.index(oldNode);
  13135. this.nodes.splice(oldIndex + 1, 0, newNode);
  13136. newNode.parent = this;
  13137. var index;
  13138. for (var id in this.indexes) {
  13139. index = this.indexes[id];
  13140. if (oldIndex <= index) {
  13141. this.indexes[id] = index + 1;
  13142. }
  13143. }
  13144. return this;
  13145. };
  13146. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  13147. newNode.parent = this;
  13148. var oldIndex = this.index(oldNode);
  13149. this.nodes.splice(oldIndex, 0, newNode);
  13150. newNode.parent = this;
  13151. var index;
  13152. for (var id in this.indexes) {
  13153. index = this.indexes[id];
  13154. if (index <= oldIndex) {
  13155. this.indexes[id] = index + 1;
  13156. }
  13157. }
  13158. return this;
  13159. };
  13160. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  13161. var found = undefined;
  13162. this.each(function (node) {
  13163. if (node.atPosition) {
  13164. var foundChild = node.atPosition(line, col);
  13165. if (foundChild) {
  13166. found = foundChild;
  13167. return false;
  13168. }
  13169. } else if (node.isAtPosition(line, col)) {
  13170. found = node;
  13171. return false;
  13172. }
  13173. });
  13174. return found;
  13175. }
  13176. /**
  13177. * Return the most specific node at the line and column number given.
  13178. * The source location is based on the original parsed location, locations aren't
  13179. * updated as selector nodes are mutated.
  13180. *
  13181. * Note that this location is relative to the location of the first character
  13182. * of the selector, and not the location of the selector in the overall document
  13183. * when used in conjunction with postcss.
  13184. *
  13185. * If not found, returns undefined.
  13186. * @param {number} line The line number of the node to find. (1-based index)
  13187. * @param {number} col The column number of the node to find. (1-based index)
  13188. */;
  13189. _proto.atPosition = function atPosition(line, col) {
  13190. if (this.isAtPosition(line, col)) {
  13191. return this._findChildAtPosition(line, col) || this;
  13192. } else {
  13193. return undefined;
  13194. }
  13195. };
  13196. _proto._inferEndPosition = function _inferEndPosition() {
  13197. if (this.last && this.last.source && this.last.source.end) {
  13198. this.source = this.source || {};
  13199. this.source.end = this.source.end || {};
  13200. Object.assign(this.source.end, this.last.source.end);
  13201. }
  13202. };
  13203. _proto.each = function each(callback) {
  13204. if (!this.lastEach) {
  13205. this.lastEach = 0;
  13206. }
  13207. if (!this.indexes) {
  13208. this.indexes = {};
  13209. }
  13210. this.lastEach++;
  13211. var id = this.lastEach;
  13212. this.indexes[id] = 0;
  13213. if (!this.length) {
  13214. return undefined;
  13215. }
  13216. var index, result;
  13217. while (this.indexes[id] < this.length) {
  13218. index = this.indexes[id];
  13219. result = callback(this.at(index), index);
  13220. if (result === false) {
  13221. break;
  13222. }
  13223. this.indexes[id] += 1;
  13224. }
  13225. delete this.indexes[id];
  13226. if (result === false) {
  13227. return false;
  13228. }
  13229. };
  13230. _proto.walk = function walk(callback) {
  13231. return this.each(function (node, i) {
  13232. var result = callback(node, i);
  13233. if (result !== false && node.length) {
  13234. result = node.walk(callback);
  13235. }
  13236. if (result === false) {
  13237. return false;
  13238. }
  13239. });
  13240. };
  13241. _proto.walkAttributes = function walkAttributes(callback) {
  13242. var _this2 = this;
  13243. return this.walk(function (selector) {
  13244. if (selector.type === types.ATTRIBUTE) {
  13245. return callback.call(_this2, selector);
  13246. }
  13247. });
  13248. };
  13249. _proto.walkClasses = function walkClasses(callback) {
  13250. var _this3 = this;
  13251. return this.walk(function (selector) {
  13252. if (selector.type === types.CLASS) {
  13253. return callback.call(_this3, selector);
  13254. }
  13255. });
  13256. };
  13257. _proto.walkCombinators = function walkCombinators(callback) {
  13258. var _this4 = this;
  13259. return this.walk(function (selector) {
  13260. if (selector.type === types.COMBINATOR) {
  13261. return callback.call(_this4, selector);
  13262. }
  13263. });
  13264. };
  13265. _proto.walkComments = function walkComments(callback) {
  13266. var _this5 = this;
  13267. return this.walk(function (selector) {
  13268. if (selector.type === types.COMMENT) {
  13269. return callback.call(_this5, selector);
  13270. }
  13271. });
  13272. };
  13273. _proto.walkIds = function walkIds(callback) {
  13274. var _this6 = this;
  13275. return this.walk(function (selector) {
  13276. if (selector.type === types.ID) {
  13277. return callback.call(_this6, selector);
  13278. }
  13279. });
  13280. };
  13281. _proto.walkNesting = function walkNesting(callback) {
  13282. var _this7 = this;
  13283. return this.walk(function (selector) {
  13284. if (selector.type === types.NESTING) {
  13285. return callback.call(_this7, selector);
  13286. }
  13287. });
  13288. };
  13289. _proto.walkPseudos = function walkPseudos(callback) {
  13290. var _this8 = this;
  13291. return this.walk(function (selector) {
  13292. if (selector.type === types.PSEUDO) {
  13293. return callback.call(_this8, selector);
  13294. }
  13295. });
  13296. };
  13297. _proto.walkTags = function walkTags(callback) {
  13298. var _this9 = this;
  13299. return this.walk(function (selector) {
  13300. if (selector.type === types.TAG) {
  13301. return callback.call(_this9, selector);
  13302. }
  13303. });
  13304. };
  13305. _proto.walkUniversals = function walkUniversals(callback) {
  13306. var _this10 = this;
  13307. return this.walk(function (selector) {
  13308. if (selector.type === types.UNIVERSAL) {
  13309. return callback.call(_this10, selector);
  13310. }
  13311. });
  13312. };
  13313. _proto.split = function split(callback) {
  13314. var _this11 = this;
  13315. var current = [];
  13316. return this.reduce(function (memo, node, index) {
  13317. var split = callback.call(_this11, node);
  13318. current.push(node);
  13319. if (split) {
  13320. memo.push(current);
  13321. current = [];
  13322. } else if (index === _this11.length - 1) {
  13323. memo.push(current);
  13324. }
  13325. return memo;
  13326. }, []);
  13327. };
  13328. _proto.map = function map(callback) {
  13329. return this.nodes.map(callback);
  13330. };
  13331. _proto.reduce = function reduce(callback, memo) {
  13332. return this.nodes.reduce(callback, memo);
  13333. };
  13334. _proto.every = function every(callback) {
  13335. return this.nodes.every(callback);
  13336. };
  13337. _proto.some = function some(callback) {
  13338. return this.nodes.some(callback);
  13339. };
  13340. _proto.filter = function filter(callback) {
  13341. return this.nodes.filter(callback);
  13342. };
  13343. _proto.sort = function sort(callback) {
  13344. return this.nodes.sort(callback);
  13345. };
  13346. _proto.toString = function toString() {
  13347. return this.map(String).join('');
  13348. };
  13349. _createClass(Container, [{
  13350. key: "first",
  13351. get: function get() {
  13352. return this.at(0);
  13353. }
  13354. }, {
  13355. key: "last",
  13356. get: function get() {
  13357. return this.at(this.length - 1);
  13358. }
  13359. }, {
  13360. key: "length",
  13361. get: function get() {
  13362. return this.nodes.length;
  13363. }
  13364. }]);
  13365. return Container;
  13366. }(_node["default"]);
  13367. exports["default"] = Container;
  13368. module.exports = exports.default;
  13369. } (container, container.exports));
  13370. return container.exports;
  13371. }
  13372. var hasRequiredRoot;
  13373. function requireRoot () {
  13374. if (hasRequiredRoot) return root.exports;
  13375. hasRequiredRoot = 1;
  13376. (function (module, exports) {
  13377. exports.__esModule = true;
  13378. exports["default"] = void 0;
  13379. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13380. var _types = /*@__PURE__*/ requireTypes();
  13381. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13382. 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); } }
  13383. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13384. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13385. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13386. var Root = /*#__PURE__*/function (_Container) {
  13387. _inheritsLoose(Root, _Container);
  13388. function Root(opts) {
  13389. var _this;
  13390. _this = _Container.call(this, opts) || this;
  13391. _this.type = _types.ROOT;
  13392. return _this;
  13393. }
  13394. var _proto = Root.prototype;
  13395. _proto.toString = function toString() {
  13396. var str = this.reduce(function (memo, selector) {
  13397. memo.push(String(selector));
  13398. return memo;
  13399. }, []).join(',');
  13400. return this.trailingComma ? str + ',' : str;
  13401. };
  13402. _proto.error = function error(message, options) {
  13403. if (this._error) {
  13404. return this._error(message, options);
  13405. } else {
  13406. return new Error(message);
  13407. }
  13408. };
  13409. _createClass(Root, [{
  13410. key: "errorGenerator",
  13411. set: function set(handler) {
  13412. this._error = handler;
  13413. }
  13414. }]);
  13415. return Root;
  13416. }(_container["default"]);
  13417. exports["default"] = Root;
  13418. module.exports = exports.default;
  13419. } (root, root.exports));
  13420. return root.exports;
  13421. }
  13422. var selector = {exports: {}};
  13423. var hasRequiredSelector;
  13424. function requireSelector () {
  13425. if (hasRequiredSelector) return selector.exports;
  13426. hasRequiredSelector = 1;
  13427. (function (module, exports) {
  13428. exports.__esModule = true;
  13429. exports["default"] = void 0;
  13430. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13431. var _types = /*@__PURE__*/ requireTypes();
  13432. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13433. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13434. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13435. var Selector = /*#__PURE__*/function (_Container) {
  13436. _inheritsLoose(Selector, _Container);
  13437. function Selector(opts) {
  13438. var _this;
  13439. _this = _Container.call(this, opts) || this;
  13440. _this.type = _types.SELECTOR;
  13441. return _this;
  13442. }
  13443. return Selector;
  13444. }(_container["default"]);
  13445. exports["default"] = Selector;
  13446. module.exports = exports.default;
  13447. } (selector, selector.exports));
  13448. return selector.exports;
  13449. }
  13450. var className = {exports: {}};
  13451. var hasRequiredClassName;
  13452. function requireClassName () {
  13453. if (hasRequiredClassName) return className.exports;
  13454. hasRequiredClassName = 1;
  13455. (function (module, exports) {
  13456. exports.__esModule = true;
  13457. exports["default"] = void 0;
  13458. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13459. var _util = /*@__PURE__*/ requireUtil();
  13460. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13461. var _types = /*@__PURE__*/ requireTypes();
  13462. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13463. 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); } }
  13464. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13465. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13466. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13467. var ClassName = /*#__PURE__*/function (_Node) {
  13468. _inheritsLoose(ClassName, _Node);
  13469. function ClassName(opts) {
  13470. var _this;
  13471. _this = _Node.call(this, opts) || this;
  13472. _this.type = _types.CLASS;
  13473. _this._constructed = true;
  13474. return _this;
  13475. }
  13476. var _proto = ClassName.prototype;
  13477. _proto.valueToString = function valueToString() {
  13478. return '.' + _Node.prototype.valueToString.call(this);
  13479. };
  13480. _createClass(ClassName, [{
  13481. key: "value",
  13482. get: function get() {
  13483. return this._value;
  13484. },
  13485. set: function set(v) {
  13486. if (this._constructed) {
  13487. var escaped = (0, _cssesc["default"])(v, {
  13488. isIdentifier: true
  13489. });
  13490. if (escaped !== v) {
  13491. (0, _util.ensureObject)(this, "raws");
  13492. this.raws.value = escaped;
  13493. } else if (this.raws) {
  13494. delete this.raws.value;
  13495. }
  13496. }
  13497. this._value = v;
  13498. }
  13499. }]);
  13500. return ClassName;
  13501. }(_node["default"]);
  13502. exports["default"] = ClassName;
  13503. module.exports = exports.default;
  13504. } (className, className.exports));
  13505. return className.exports;
  13506. }
  13507. var comment = {exports: {}};
  13508. var hasRequiredComment;
  13509. function requireComment () {
  13510. if (hasRequiredComment) return comment.exports;
  13511. hasRequiredComment = 1;
  13512. (function (module, exports) {
  13513. exports.__esModule = true;
  13514. exports["default"] = void 0;
  13515. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13516. var _types = /*@__PURE__*/ requireTypes();
  13517. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13518. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13519. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13520. var Comment = /*#__PURE__*/function (_Node) {
  13521. _inheritsLoose(Comment, _Node);
  13522. function Comment(opts) {
  13523. var _this;
  13524. _this = _Node.call(this, opts) || this;
  13525. _this.type = _types.COMMENT;
  13526. return _this;
  13527. }
  13528. return Comment;
  13529. }(_node["default"]);
  13530. exports["default"] = Comment;
  13531. module.exports = exports.default;
  13532. } (comment, comment.exports));
  13533. return comment.exports;
  13534. }
  13535. var id = {exports: {}};
  13536. var hasRequiredId;
  13537. function requireId () {
  13538. if (hasRequiredId) return id.exports;
  13539. hasRequiredId = 1;
  13540. (function (module, exports) {
  13541. exports.__esModule = true;
  13542. exports["default"] = void 0;
  13543. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13544. var _types = /*@__PURE__*/ requireTypes();
  13545. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13546. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13547. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13548. var ID = /*#__PURE__*/function (_Node) {
  13549. _inheritsLoose(ID, _Node);
  13550. function ID(opts) {
  13551. var _this;
  13552. _this = _Node.call(this, opts) || this;
  13553. _this.type = _types.ID;
  13554. return _this;
  13555. }
  13556. var _proto = ID.prototype;
  13557. _proto.valueToString = function valueToString() {
  13558. return '#' + _Node.prototype.valueToString.call(this);
  13559. };
  13560. return ID;
  13561. }(_node["default"]);
  13562. exports["default"] = ID;
  13563. module.exports = exports.default;
  13564. } (id, id.exports));
  13565. return id.exports;
  13566. }
  13567. var tag = {exports: {}};
  13568. var namespace = {exports: {}};
  13569. var hasRequiredNamespace;
  13570. function requireNamespace () {
  13571. if (hasRequiredNamespace) return namespace.exports;
  13572. hasRequiredNamespace = 1;
  13573. (function (module, exports) {
  13574. exports.__esModule = true;
  13575. exports["default"] = void 0;
  13576. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13577. var _util = /*@__PURE__*/ requireUtil();
  13578. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13579. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13580. 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); } }
  13581. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13582. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13583. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13584. var Namespace = /*#__PURE__*/function (_Node) {
  13585. _inheritsLoose(Namespace, _Node);
  13586. function Namespace() {
  13587. return _Node.apply(this, arguments) || this;
  13588. }
  13589. var _proto = Namespace.prototype;
  13590. _proto.qualifiedName = function qualifiedName(value) {
  13591. if (this.namespace) {
  13592. return this.namespaceString + "|" + value;
  13593. } else {
  13594. return value;
  13595. }
  13596. };
  13597. _proto.valueToString = function valueToString() {
  13598. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  13599. };
  13600. _createClass(Namespace, [{
  13601. key: "namespace",
  13602. get: function get() {
  13603. return this._namespace;
  13604. },
  13605. set: function set(namespace) {
  13606. if (namespace === true || namespace === "*" || namespace === "&") {
  13607. this._namespace = namespace;
  13608. if (this.raws) {
  13609. delete this.raws.namespace;
  13610. }
  13611. return;
  13612. }
  13613. var escaped = (0, _cssesc["default"])(namespace, {
  13614. isIdentifier: true
  13615. });
  13616. this._namespace = namespace;
  13617. if (escaped !== namespace) {
  13618. (0, _util.ensureObject)(this, "raws");
  13619. this.raws.namespace = escaped;
  13620. } else if (this.raws) {
  13621. delete this.raws.namespace;
  13622. }
  13623. }
  13624. }, {
  13625. key: "ns",
  13626. get: function get() {
  13627. return this._namespace;
  13628. },
  13629. set: function set(namespace) {
  13630. this.namespace = namespace;
  13631. }
  13632. }, {
  13633. key: "namespaceString",
  13634. get: function get() {
  13635. if (this.namespace) {
  13636. var ns = this.stringifyProperty("namespace");
  13637. if (ns === true) {
  13638. return '';
  13639. } else {
  13640. return ns;
  13641. }
  13642. } else {
  13643. return '';
  13644. }
  13645. }
  13646. }]);
  13647. return Namespace;
  13648. }(_node["default"]);
  13649. exports["default"] = Namespace;
  13650. module.exports = exports.default;
  13651. } (namespace, namespace.exports));
  13652. return namespace.exports;
  13653. }
  13654. var hasRequiredTag;
  13655. function requireTag () {
  13656. if (hasRequiredTag) return tag.exports;
  13657. hasRequiredTag = 1;
  13658. (function (module, exports) {
  13659. exports.__esModule = true;
  13660. exports["default"] = void 0;
  13661. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  13662. var _types = /*@__PURE__*/ requireTypes();
  13663. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13664. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13665. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13666. var Tag = /*#__PURE__*/function (_Namespace) {
  13667. _inheritsLoose(Tag, _Namespace);
  13668. function Tag(opts) {
  13669. var _this;
  13670. _this = _Namespace.call(this, opts) || this;
  13671. _this.type = _types.TAG;
  13672. return _this;
  13673. }
  13674. return Tag;
  13675. }(_namespace["default"]);
  13676. exports["default"] = Tag;
  13677. module.exports = exports.default;
  13678. } (tag, tag.exports));
  13679. return tag.exports;
  13680. }
  13681. var string = {exports: {}};
  13682. var hasRequiredString;
  13683. function requireString () {
  13684. if (hasRequiredString) return string.exports;
  13685. hasRequiredString = 1;
  13686. (function (module, exports) {
  13687. exports.__esModule = true;
  13688. exports["default"] = void 0;
  13689. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  13690. var _types = /*@__PURE__*/ requireTypes();
  13691. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13692. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13693. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13694. var String = /*#__PURE__*/function (_Node) {
  13695. _inheritsLoose(String, _Node);
  13696. function String(opts) {
  13697. var _this;
  13698. _this = _Node.call(this, opts) || this;
  13699. _this.type = _types.STRING;
  13700. return _this;
  13701. }
  13702. return String;
  13703. }(_node["default"]);
  13704. exports["default"] = String;
  13705. module.exports = exports.default;
  13706. } (string, string.exports));
  13707. return string.exports;
  13708. }
  13709. var pseudo = {exports: {}};
  13710. var hasRequiredPseudo;
  13711. function requirePseudo () {
  13712. if (hasRequiredPseudo) return pseudo.exports;
  13713. hasRequiredPseudo = 1;
  13714. (function (module, exports) {
  13715. exports.__esModule = true;
  13716. exports["default"] = void 0;
  13717. var _container = _interopRequireDefault(/*@__PURE__*/ requireContainer());
  13718. var _types = /*@__PURE__*/ requireTypes();
  13719. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13720. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13721. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13722. var Pseudo = /*#__PURE__*/function (_Container) {
  13723. _inheritsLoose(Pseudo, _Container);
  13724. function Pseudo(opts) {
  13725. var _this;
  13726. _this = _Container.call(this, opts) || this;
  13727. _this.type = _types.PSEUDO;
  13728. return _this;
  13729. }
  13730. var _proto = Pseudo.prototype;
  13731. _proto.toString = function toString() {
  13732. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  13733. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  13734. };
  13735. return Pseudo;
  13736. }(_container["default"]);
  13737. exports["default"] = Pseudo;
  13738. module.exports = exports.default;
  13739. } (pseudo, pseudo.exports));
  13740. return pseudo.exports;
  13741. }
  13742. var attribute = {};
  13743. var hasRequiredAttribute;
  13744. function requireAttribute () {
  13745. if (hasRequiredAttribute) return attribute;
  13746. hasRequiredAttribute = 1;
  13747. (function (exports) {
  13748. exports.__esModule = true;
  13749. exports["default"] = void 0;
  13750. exports.unescapeValue = unescapeValue;
  13751. var _cssesc = _interopRequireDefault(/*@__PURE__*/ requireCssesc());
  13752. var _unesc = _interopRequireDefault(/*@__PURE__*/ requireUnesc());
  13753. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  13754. var _types = /*@__PURE__*/ requireTypes();
  13755. var _CSSESC_QUOTE_OPTIONS;
  13756. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13757. 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); } }
  13758. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  13759. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  13760. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  13761. var deprecate = /*@__PURE__*/ requireNode$1();
  13762. var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  13763. var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  13764. var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  13765. var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  13766. function unescapeValue(value) {
  13767. var deprecatedUsage = false;
  13768. var quoteMark = null;
  13769. var unescaped = value;
  13770. var m = unescaped.match(WRAPPED_IN_QUOTES);
  13771. if (m) {
  13772. quoteMark = m[1];
  13773. unescaped = m[2];
  13774. }
  13775. unescaped = (0, _unesc["default"])(unescaped);
  13776. if (unescaped !== value) {
  13777. deprecatedUsage = true;
  13778. }
  13779. return {
  13780. deprecatedUsage: deprecatedUsage,
  13781. unescaped: unescaped,
  13782. quoteMark: quoteMark
  13783. };
  13784. }
  13785. function handleDeprecatedContructorOpts(opts) {
  13786. if (opts.quoteMark !== undefined) {
  13787. return opts;
  13788. }
  13789. if (opts.value === undefined) {
  13790. return opts;
  13791. }
  13792. warnOfDeprecatedConstructor();
  13793. var _unescapeValue = unescapeValue(opts.value),
  13794. quoteMark = _unescapeValue.quoteMark,
  13795. unescaped = _unescapeValue.unescaped;
  13796. if (!opts.raws) {
  13797. opts.raws = {};
  13798. }
  13799. if (opts.raws.value === undefined) {
  13800. opts.raws.value = opts.value;
  13801. }
  13802. opts.value = unescaped;
  13803. opts.quoteMark = quoteMark;
  13804. return opts;
  13805. }
  13806. var Attribute = /*#__PURE__*/function (_Namespace) {
  13807. _inheritsLoose(Attribute, _Namespace);
  13808. function Attribute(opts) {
  13809. var _this;
  13810. if (opts === void 0) {
  13811. opts = {};
  13812. }
  13813. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  13814. _this.type = _types.ATTRIBUTE;
  13815. _this.raws = _this.raws || {};
  13816. Object.defineProperty(_this.raws, 'unquoted', {
  13817. get: deprecate(function () {
  13818. return _this.value;
  13819. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  13820. set: deprecate(function () {
  13821. return _this.value;
  13822. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  13823. });
  13824. _this._constructed = true;
  13825. return _this;
  13826. }
  13827. /**
  13828. * Returns the Attribute's value quoted such that it would be legal to use
  13829. * in the value of a css file. The original value's quotation setting
  13830. * used for stringification is left unchanged. See `setValue(value, options)`
  13831. * if you want to control the quote settings of a new value for the attribute.
  13832. *
  13833. * You can also change the quotation used for the current value by setting quoteMark.
  13834. *
  13835. * Options:
  13836. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  13837. * option is not set, the original value for quoteMark will be used. If
  13838. * indeterminate, a double quote is used. The legal values are:
  13839. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  13840. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  13841. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  13842. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  13843. * over the quoteMark option value.
  13844. * * smart {boolean} - if true, will select a quote mark based on the value
  13845. * and the other options specified here. See the `smartQuoteMark()`
  13846. * method.
  13847. **/
  13848. var _proto = Attribute.prototype;
  13849. _proto.getQuotedValue = function getQuotedValue(options) {
  13850. if (options === void 0) {
  13851. options = {};
  13852. }
  13853. var quoteMark = this._determineQuoteMark(options);
  13854. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  13855. var escaped = (0, _cssesc["default"])(this._value, cssescopts);
  13856. return escaped;
  13857. };
  13858. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  13859. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  13860. }
  13861. /**
  13862. * Set the unescaped value with the specified quotation options. The value
  13863. * provided must not include any wrapping quote marks -- those quotes will
  13864. * be interpreted as part of the value and escaped accordingly.
  13865. */;
  13866. _proto.setValue = function setValue(value, options) {
  13867. if (options === void 0) {
  13868. options = {};
  13869. }
  13870. this._value = value;
  13871. this._quoteMark = this._determineQuoteMark(options);
  13872. this._syncRawValue();
  13873. }
  13874. /**
  13875. * Intelligently select a quoteMark value based on the value's contents. If
  13876. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  13877. * mark will be picked that minimizes the number of escapes.
  13878. *
  13879. * If there's no clear winner, the quote mark from these options is used,
  13880. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  13881. * true). If the quoteMark is unspecified, a double quote is used.
  13882. *
  13883. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  13884. * from the quoteValue method.
  13885. */;
  13886. _proto.smartQuoteMark = function smartQuoteMark(options) {
  13887. var v = this.value;
  13888. var numSingleQuotes = v.replace(/[^']/g, '').length;
  13889. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  13890. if (numSingleQuotes + numDoubleQuotes === 0) {
  13891. var escaped = (0, _cssesc["default"])(v, {
  13892. isIdentifier: true
  13893. });
  13894. if (escaped === v) {
  13895. return Attribute.NO_QUOTE;
  13896. } else {
  13897. var pref = this.preferredQuoteMark(options);
  13898. if (pref === Attribute.NO_QUOTE) {
  13899. // pick a quote mark that isn't none and see if it's smaller
  13900. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  13901. var opts = CSSESC_QUOTE_OPTIONS[quote];
  13902. var quoteValue = (0, _cssesc["default"])(v, opts);
  13903. if (quoteValue.length < escaped.length) {
  13904. return quote;
  13905. }
  13906. }
  13907. return pref;
  13908. }
  13909. } else if (numDoubleQuotes === numSingleQuotes) {
  13910. return this.preferredQuoteMark(options);
  13911. } else if (numDoubleQuotes < numSingleQuotes) {
  13912. return Attribute.DOUBLE_QUOTE;
  13913. } else {
  13914. return Attribute.SINGLE_QUOTE;
  13915. }
  13916. }
  13917. /**
  13918. * Selects the preferred quote mark based on the options and the current quote mark value.
  13919. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  13920. * instead.
  13921. */;
  13922. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  13923. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  13924. if (quoteMark === undefined) {
  13925. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  13926. }
  13927. if (quoteMark === undefined) {
  13928. quoteMark = Attribute.DOUBLE_QUOTE;
  13929. }
  13930. return quoteMark;
  13931. };
  13932. _proto._syncRawValue = function _syncRawValue() {
  13933. var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  13934. if (rawValue === this._value) {
  13935. if (this.raws) {
  13936. delete this.raws.value;
  13937. }
  13938. } else {
  13939. this.raws.value = rawValue;
  13940. }
  13941. };
  13942. _proto._handleEscapes = function _handleEscapes(prop, value) {
  13943. if (this._constructed) {
  13944. var escaped = (0, _cssesc["default"])(value, {
  13945. isIdentifier: true
  13946. });
  13947. if (escaped !== value) {
  13948. this.raws[prop] = escaped;
  13949. } else {
  13950. delete this.raws[prop];
  13951. }
  13952. }
  13953. };
  13954. _proto._spacesFor = function _spacesFor(name) {
  13955. var attrSpaces = {
  13956. before: '',
  13957. after: ''
  13958. };
  13959. var spaces = this.spaces[name] || {};
  13960. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  13961. return Object.assign(attrSpaces, spaces, rawSpaces);
  13962. };
  13963. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  13964. if (spaceName === void 0) {
  13965. spaceName = name;
  13966. }
  13967. if (concat === void 0) {
  13968. concat = defaultAttrConcat;
  13969. }
  13970. var attrSpaces = this._spacesFor(spaceName);
  13971. return concat(this.stringifyProperty(name), attrSpaces);
  13972. }
  13973. /**
  13974. * returns the offset of the attribute part specified relative to the
  13975. * start of the node of the output string.
  13976. *
  13977. * * "ns" - alias for "namespace"
  13978. * * "namespace" - the namespace if it exists.
  13979. * * "attribute" - the attribute name
  13980. * * "attributeNS" - the start of the attribute or its namespace
  13981. * * "operator" - the match operator of the attribute
  13982. * * "value" - The value (string or identifier)
  13983. * * "insensitive" - the case insensitivity flag;
  13984. * @param part One of the possible values inside an attribute.
  13985. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  13986. */;
  13987. _proto.offsetOf = function offsetOf(name) {
  13988. var count = 1;
  13989. var attributeSpaces = this._spacesFor("attribute");
  13990. count += attributeSpaces.before.length;
  13991. if (name === "namespace" || name === "ns") {
  13992. return this.namespace ? count : -1;
  13993. }
  13994. if (name === "attributeNS") {
  13995. return count;
  13996. }
  13997. count += this.namespaceString.length;
  13998. if (this.namespace) {
  13999. count += 1;
  14000. }
  14001. if (name === "attribute") {
  14002. return count;
  14003. }
  14004. count += this.stringifyProperty("attribute").length;
  14005. count += attributeSpaces.after.length;
  14006. var operatorSpaces = this._spacesFor("operator");
  14007. count += operatorSpaces.before.length;
  14008. var operator = this.stringifyProperty("operator");
  14009. if (name === "operator") {
  14010. return operator ? count : -1;
  14011. }
  14012. count += operator.length;
  14013. count += operatorSpaces.after.length;
  14014. var valueSpaces = this._spacesFor("value");
  14015. count += valueSpaces.before.length;
  14016. var value = this.stringifyProperty("value");
  14017. if (name === "value") {
  14018. return value ? count : -1;
  14019. }
  14020. count += value.length;
  14021. count += valueSpaces.after.length;
  14022. var insensitiveSpaces = this._spacesFor("insensitive");
  14023. count += insensitiveSpaces.before.length;
  14024. if (name === "insensitive") {
  14025. return this.insensitive ? count : -1;
  14026. }
  14027. return -1;
  14028. };
  14029. _proto.toString = function toString() {
  14030. var _this2 = this;
  14031. var selector = [this.rawSpaceBefore, '['];
  14032. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  14033. if (this.operator && (this.value || this.value === '')) {
  14034. selector.push(this._stringFor('operator'));
  14035. selector.push(this._stringFor('value'));
  14036. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  14037. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  14038. attrSpaces.before = " ";
  14039. }
  14040. return defaultAttrConcat(attrValue, attrSpaces);
  14041. }));
  14042. }
  14043. selector.push(']');
  14044. selector.push(this.rawSpaceAfter);
  14045. return selector.join('');
  14046. };
  14047. _createClass(Attribute, [{
  14048. key: "quoted",
  14049. get: function get() {
  14050. var qm = this.quoteMark;
  14051. return qm === "'" || qm === '"';
  14052. },
  14053. set: function set(value) {
  14054. warnOfDeprecatedQuotedAssignment();
  14055. }
  14056. /**
  14057. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  14058. * returns `null` if the value is not quoted.
  14059. * returns `undefined` if the quotation state is unknown (this can happen when
  14060. * the attribute is constructed without specifying a quote mark.)
  14061. */
  14062. }, {
  14063. key: "quoteMark",
  14064. get: function get() {
  14065. return this._quoteMark;
  14066. }
  14067. /**
  14068. * Set the quote mark to be used by this attribute's value.
  14069. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  14070. * value is updated accordingly.
  14071. *
  14072. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  14073. */,
  14074. set: function set(quoteMark) {
  14075. if (!this._constructed) {
  14076. this._quoteMark = quoteMark;
  14077. return;
  14078. }
  14079. if (this._quoteMark !== quoteMark) {
  14080. this._quoteMark = quoteMark;
  14081. this._syncRawValue();
  14082. }
  14083. }
  14084. }, {
  14085. key: "qualifiedAttribute",
  14086. get: function get() {
  14087. return this.qualifiedName(this.raws.attribute || this.attribute);
  14088. }
  14089. }, {
  14090. key: "insensitiveFlag",
  14091. get: function get() {
  14092. return this.insensitive ? 'i' : '';
  14093. }
  14094. }, {
  14095. key: "value",
  14096. get: function get() {
  14097. return this._value;
  14098. },
  14099. set:
  14100. /**
  14101. * Before 3.0, the value had to be set to an escaped value including any wrapped
  14102. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  14103. * is unescaped during parsing and any quote marks are removed.
  14104. *
  14105. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  14106. * a deprecation warning is raised when the new value contains any characters that would
  14107. * require escaping (including if it contains wrapped quotes).
  14108. *
  14109. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  14110. * how the new value is quoted.
  14111. */
  14112. function set(v) {
  14113. if (this._constructed) {
  14114. var _unescapeValue2 = unescapeValue(v),
  14115. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  14116. unescaped = _unescapeValue2.unescaped,
  14117. quoteMark = _unescapeValue2.quoteMark;
  14118. if (deprecatedUsage) {
  14119. warnOfDeprecatedValueAssignment();
  14120. }
  14121. if (unescaped === this._value && quoteMark === this._quoteMark) {
  14122. return;
  14123. }
  14124. this._value = unescaped;
  14125. this._quoteMark = quoteMark;
  14126. this._syncRawValue();
  14127. } else {
  14128. this._value = v;
  14129. }
  14130. }
  14131. }, {
  14132. key: "insensitive",
  14133. get: function get() {
  14134. return this._insensitive;
  14135. }
  14136. /**
  14137. * Set the case insensitive flag.
  14138. * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
  14139. * of the attribute is updated accordingly.
  14140. *
  14141. * @param {true | false} insensitive true if the attribute should match case-insensitively.
  14142. */,
  14143. set: function set(insensitive) {
  14144. if (!insensitive) {
  14145. this._insensitive = false;
  14146. // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
  14147. // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
  14148. if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
  14149. this.raws.insensitiveFlag = undefined;
  14150. }
  14151. }
  14152. this._insensitive = insensitive;
  14153. }
  14154. }, {
  14155. key: "attribute",
  14156. get: function get() {
  14157. return this._attribute;
  14158. },
  14159. set: function set(name) {
  14160. this._handleEscapes("attribute", name);
  14161. this._attribute = name;
  14162. }
  14163. }]);
  14164. return Attribute;
  14165. }(_namespace["default"]);
  14166. exports["default"] = Attribute;
  14167. Attribute.NO_QUOTE = null;
  14168. Attribute.SINGLE_QUOTE = "'";
  14169. Attribute.DOUBLE_QUOTE = '"';
  14170. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  14171. "'": {
  14172. quotes: 'single',
  14173. wrap: true
  14174. },
  14175. '"': {
  14176. quotes: 'double',
  14177. wrap: true
  14178. }
  14179. }, _CSSESC_QUOTE_OPTIONS[null] = {
  14180. isIdentifier: true
  14181. }, _CSSESC_QUOTE_OPTIONS);
  14182. function defaultAttrConcat(attrValue, attrSpaces) {
  14183. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  14184. }
  14185. } (attribute));
  14186. return attribute;
  14187. }
  14188. var universal = {exports: {}};
  14189. var hasRequiredUniversal;
  14190. function requireUniversal () {
  14191. if (hasRequiredUniversal) return universal.exports;
  14192. hasRequiredUniversal = 1;
  14193. (function (module, exports) {
  14194. exports.__esModule = true;
  14195. exports["default"] = void 0;
  14196. var _namespace = _interopRequireDefault(/*@__PURE__*/ requireNamespace());
  14197. var _types = /*@__PURE__*/ requireTypes();
  14198. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14199. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14200. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14201. var Universal = /*#__PURE__*/function (_Namespace) {
  14202. _inheritsLoose(Universal, _Namespace);
  14203. function Universal(opts) {
  14204. var _this;
  14205. _this = _Namespace.call(this, opts) || this;
  14206. _this.type = _types.UNIVERSAL;
  14207. _this.value = '*';
  14208. return _this;
  14209. }
  14210. return Universal;
  14211. }(_namespace["default"]);
  14212. exports["default"] = Universal;
  14213. module.exports = exports.default;
  14214. } (universal, universal.exports));
  14215. return universal.exports;
  14216. }
  14217. var combinator = {exports: {}};
  14218. var hasRequiredCombinator;
  14219. function requireCombinator () {
  14220. if (hasRequiredCombinator) return combinator.exports;
  14221. hasRequiredCombinator = 1;
  14222. (function (module, exports) {
  14223. exports.__esModule = true;
  14224. exports["default"] = void 0;
  14225. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  14226. var _types = /*@__PURE__*/ requireTypes();
  14227. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14228. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14229. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14230. var Combinator = /*#__PURE__*/function (_Node) {
  14231. _inheritsLoose(Combinator, _Node);
  14232. function Combinator(opts) {
  14233. var _this;
  14234. _this = _Node.call(this, opts) || this;
  14235. _this.type = _types.COMBINATOR;
  14236. return _this;
  14237. }
  14238. return Combinator;
  14239. }(_node["default"]);
  14240. exports["default"] = Combinator;
  14241. module.exports = exports.default;
  14242. } (combinator, combinator.exports));
  14243. return combinator.exports;
  14244. }
  14245. var nesting = {exports: {}};
  14246. var hasRequiredNesting;
  14247. function requireNesting () {
  14248. if (hasRequiredNesting) return nesting.exports;
  14249. hasRequiredNesting = 1;
  14250. (function (module, exports) {
  14251. exports.__esModule = true;
  14252. exports["default"] = void 0;
  14253. var _node = _interopRequireDefault(/*@__PURE__*/ requireNode());
  14254. var _types = /*@__PURE__*/ requireTypes();
  14255. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14256. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
  14257. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  14258. var Nesting = /*#__PURE__*/function (_Node) {
  14259. _inheritsLoose(Nesting, _Node);
  14260. function Nesting(opts) {
  14261. var _this;
  14262. _this = _Node.call(this, opts) || this;
  14263. _this.type = _types.NESTING;
  14264. _this.value = '&';
  14265. return _this;
  14266. }
  14267. return Nesting;
  14268. }(_node["default"]);
  14269. exports["default"] = Nesting;
  14270. module.exports = exports.default;
  14271. } (nesting, nesting.exports));
  14272. return nesting.exports;
  14273. }
  14274. var sortAscending = {exports: {}};
  14275. var hasRequiredSortAscending;
  14276. function requireSortAscending () {
  14277. if (hasRequiredSortAscending) return sortAscending.exports;
  14278. hasRequiredSortAscending = 1;
  14279. (function (module, exports) {
  14280. exports.__esModule = true;
  14281. exports["default"] = sortAscending;
  14282. function sortAscending(list) {
  14283. return list.sort(function (a, b) {
  14284. return a - b;
  14285. });
  14286. }
  14287. module.exports = exports.default;
  14288. } (sortAscending, sortAscending.exports));
  14289. return sortAscending.exports;
  14290. }
  14291. var tokenize = {};
  14292. var tokenTypes = {};
  14293. var hasRequiredTokenTypes;
  14294. function requireTokenTypes () {
  14295. if (hasRequiredTokenTypes) return tokenTypes;
  14296. hasRequiredTokenTypes = 1;
  14297. tokenTypes.__esModule = true;
  14298. 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;
  14299. var ampersand = 38; // `&`.charCodeAt(0);
  14300. tokenTypes.ampersand = ampersand;
  14301. var asterisk = 42; // `*`.charCodeAt(0);
  14302. tokenTypes.asterisk = asterisk;
  14303. var at = 64; // `@`.charCodeAt(0);
  14304. tokenTypes.at = at;
  14305. var comma = 44; // `,`.charCodeAt(0);
  14306. tokenTypes.comma = comma;
  14307. var colon = 58; // `:`.charCodeAt(0);
  14308. tokenTypes.colon = colon;
  14309. var semicolon = 59; // `;`.charCodeAt(0);
  14310. tokenTypes.semicolon = semicolon;
  14311. var openParenthesis = 40; // `(`.charCodeAt(0);
  14312. tokenTypes.openParenthesis = openParenthesis;
  14313. var closeParenthesis = 41; // `)`.charCodeAt(0);
  14314. tokenTypes.closeParenthesis = closeParenthesis;
  14315. var openSquare = 91; // `[`.charCodeAt(0);
  14316. tokenTypes.openSquare = openSquare;
  14317. var closeSquare = 93; // `]`.charCodeAt(0);
  14318. tokenTypes.closeSquare = closeSquare;
  14319. var dollar = 36; // `$`.charCodeAt(0);
  14320. tokenTypes.dollar = dollar;
  14321. var tilde = 126; // `~`.charCodeAt(0);
  14322. tokenTypes.tilde = tilde;
  14323. var caret = 94; // `^`.charCodeAt(0);
  14324. tokenTypes.caret = caret;
  14325. var plus = 43; // `+`.charCodeAt(0);
  14326. tokenTypes.plus = plus;
  14327. var equals = 61; // `=`.charCodeAt(0);
  14328. tokenTypes.equals = equals;
  14329. var pipe = 124; // `|`.charCodeAt(0);
  14330. tokenTypes.pipe = pipe;
  14331. var greaterThan = 62; // `>`.charCodeAt(0);
  14332. tokenTypes.greaterThan = greaterThan;
  14333. var space = 32; // ` `.charCodeAt(0);
  14334. tokenTypes.space = space;
  14335. var singleQuote = 39; // `'`.charCodeAt(0);
  14336. tokenTypes.singleQuote = singleQuote;
  14337. var doubleQuote = 34; // `"`.charCodeAt(0);
  14338. tokenTypes.doubleQuote = doubleQuote;
  14339. var slash = 47; // `/`.charCodeAt(0);
  14340. tokenTypes.slash = slash;
  14341. var bang = 33; // `!`.charCodeAt(0);
  14342. tokenTypes.bang = bang;
  14343. var backslash = 92; // '\\'.charCodeAt(0);
  14344. tokenTypes.backslash = backslash;
  14345. var cr = 13; // '\r'.charCodeAt(0);
  14346. tokenTypes.cr = cr;
  14347. var feed = 12; // '\f'.charCodeAt(0);
  14348. tokenTypes.feed = feed;
  14349. var newline = 10; // '\n'.charCodeAt(0);
  14350. tokenTypes.newline = newline;
  14351. var tab = 9; // '\t'.charCodeAt(0);
  14352. // Expose aliases primarily for readability.
  14353. tokenTypes.tab = tab;
  14354. var str = singleQuote;
  14355. // No good single character representation!
  14356. tokenTypes.str = str;
  14357. var comment = -1;
  14358. tokenTypes.comment = comment;
  14359. var word = -2;
  14360. tokenTypes.word = word;
  14361. var combinator = -3;
  14362. tokenTypes.combinator = combinator;
  14363. return tokenTypes;
  14364. }
  14365. var hasRequiredTokenize;
  14366. function requireTokenize () {
  14367. if (hasRequiredTokenize) return tokenize;
  14368. hasRequiredTokenize = 1;
  14369. (function (exports) {
  14370. exports.__esModule = true;
  14371. exports.FIELDS = void 0;
  14372. exports["default"] = tokenize;
  14373. var t = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes());
  14374. var _unescapable, _wordDelimiters;
  14375. 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); }
  14376. 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; }
  14377. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  14378. 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);
  14379. var hex = {};
  14380. var hexChars = "0123456789abcdefABCDEF";
  14381. for (var i = 0; i < hexChars.length; i++) {
  14382. hex[hexChars.charCodeAt(i)] = true;
  14383. }
  14384. /**
  14385. * Returns the last index of the bar css word
  14386. * @param {string} css The string in which the word begins
  14387. * @param {number} start The index into the string where word's first letter occurs
  14388. */
  14389. function consumeWord(css, start) {
  14390. var next = start;
  14391. var code;
  14392. do {
  14393. code = css.charCodeAt(next);
  14394. if (wordDelimiters[code]) {
  14395. return next - 1;
  14396. } else if (code === t.backslash) {
  14397. next = consumeEscape(css, next) + 1;
  14398. } else {
  14399. // All other characters are part of the word
  14400. next++;
  14401. }
  14402. } while (next < css.length);
  14403. return next - 1;
  14404. }
  14405. /**
  14406. * Returns the last index of the escape sequence
  14407. * @param {string} css The string in which the sequence begins
  14408. * @param {number} start The index into the string where escape character (`\`) occurs.
  14409. */
  14410. function consumeEscape(css, start) {
  14411. var next = start;
  14412. var code = css.charCodeAt(next + 1);
  14413. if (unescapable[code]) ; else if (hex[code]) {
  14414. var hexDigits = 0;
  14415. // consume up to 6 hex chars
  14416. do {
  14417. next++;
  14418. hexDigits++;
  14419. code = css.charCodeAt(next + 1);
  14420. } while (hex[code] && hexDigits < 6);
  14421. // if fewer than 6 hex chars, a trailing space ends the escape
  14422. if (hexDigits < 6 && code === t.space) {
  14423. next++;
  14424. }
  14425. } else {
  14426. // the next char is part of the current word
  14427. next++;
  14428. }
  14429. return next;
  14430. }
  14431. var FIELDS = {
  14432. TYPE: 0,
  14433. START_LINE: 1,
  14434. START_COL: 2,
  14435. END_LINE: 3,
  14436. END_COL: 4,
  14437. START_POS: 5,
  14438. END_POS: 6
  14439. };
  14440. exports.FIELDS = FIELDS;
  14441. function tokenize(input) {
  14442. var tokens = [];
  14443. var css = input.css.valueOf();
  14444. var _css = css,
  14445. length = _css.length;
  14446. var offset = -1;
  14447. var line = 1;
  14448. var start = 0;
  14449. var end = 0;
  14450. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  14451. function unclosed(what, fix) {
  14452. if (input.safe) {
  14453. // fyi: this is never set to true.
  14454. css += fix;
  14455. next = css.length - 1;
  14456. } else {
  14457. throw input.error('Unclosed ' + what, line, start - offset, start);
  14458. }
  14459. }
  14460. while (start < length) {
  14461. code = css.charCodeAt(start);
  14462. if (code === t.newline) {
  14463. offset = start;
  14464. line += 1;
  14465. }
  14466. switch (code) {
  14467. case t.space:
  14468. case t.tab:
  14469. case t.newline:
  14470. case t.cr:
  14471. case t.feed:
  14472. next = start;
  14473. do {
  14474. next += 1;
  14475. code = css.charCodeAt(next);
  14476. if (code === t.newline) {
  14477. offset = next;
  14478. line += 1;
  14479. }
  14480. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  14481. tokenType = t.space;
  14482. endLine = line;
  14483. endColumn = next - offset - 1;
  14484. end = next;
  14485. break;
  14486. case t.plus:
  14487. case t.greaterThan:
  14488. case t.tilde:
  14489. case t.pipe:
  14490. next = start;
  14491. do {
  14492. next += 1;
  14493. code = css.charCodeAt(next);
  14494. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  14495. tokenType = t.combinator;
  14496. endLine = line;
  14497. endColumn = start - offset;
  14498. end = next;
  14499. break;
  14500. // Consume these characters as single tokens.
  14501. case t.asterisk:
  14502. case t.ampersand:
  14503. case t.bang:
  14504. case t.comma:
  14505. case t.equals:
  14506. case t.dollar:
  14507. case t.caret:
  14508. case t.openSquare:
  14509. case t.closeSquare:
  14510. case t.colon:
  14511. case t.semicolon:
  14512. case t.openParenthesis:
  14513. case t.closeParenthesis:
  14514. next = start;
  14515. tokenType = code;
  14516. endLine = line;
  14517. endColumn = start - offset;
  14518. end = next + 1;
  14519. break;
  14520. case t.singleQuote:
  14521. case t.doubleQuote:
  14522. quote = code === t.singleQuote ? "'" : '"';
  14523. next = start;
  14524. do {
  14525. escaped = false;
  14526. next = css.indexOf(quote, next + 1);
  14527. if (next === -1) {
  14528. unclosed('quote', quote);
  14529. }
  14530. escapePos = next;
  14531. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  14532. escapePos -= 1;
  14533. escaped = !escaped;
  14534. }
  14535. } while (escaped);
  14536. tokenType = t.str;
  14537. endLine = line;
  14538. endColumn = start - offset;
  14539. end = next + 1;
  14540. break;
  14541. default:
  14542. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  14543. next = css.indexOf('*/', start + 2) + 1;
  14544. if (next === 0) {
  14545. unclosed('comment', '*/');
  14546. }
  14547. content = css.slice(start, next + 1);
  14548. lines = content.split('\n');
  14549. last = lines.length - 1;
  14550. if (last > 0) {
  14551. nextLine = line + last;
  14552. nextOffset = next - lines[last].length;
  14553. } else {
  14554. nextLine = line;
  14555. nextOffset = offset;
  14556. }
  14557. tokenType = t.comment;
  14558. line = nextLine;
  14559. endLine = nextLine;
  14560. endColumn = next - nextOffset;
  14561. } else if (code === t.slash) {
  14562. next = start;
  14563. tokenType = code;
  14564. endLine = line;
  14565. endColumn = start - offset;
  14566. end = next + 1;
  14567. } else {
  14568. next = consumeWord(css, start);
  14569. tokenType = t.word;
  14570. endLine = line;
  14571. endColumn = next - offset;
  14572. }
  14573. end = next + 1;
  14574. break;
  14575. }
  14576. // Ensure that the token structure remains consistent
  14577. tokens.push([tokenType,
  14578. // [0] Token type
  14579. line,
  14580. // [1] Starting line
  14581. start - offset,
  14582. // [2] Starting column
  14583. endLine,
  14584. // [3] Ending line
  14585. endColumn,
  14586. // [4] Ending column
  14587. start,
  14588. // [5] Start position / Source index
  14589. end // [6] End position
  14590. ]);
  14591. // Reset offset for the next token
  14592. if (nextOffset) {
  14593. offset = nextOffset;
  14594. nextOffset = null;
  14595. }
  14596. start = end;
  14597. }
  14598. return tokens;
  14599. }
  14600. } (tokenize));
  14601. return tokenize;
  14602. }
  14603. var hasRequiredParser;
  14604. function requireParser () {
  14605. if (hasRequiredParser) return parser.exports;
  14606. hasRequiredParser = 1;
  14607. (function (module, exports) {
  14608. exports.__esModule = true;
  14609. exports["default"] = void 0;
  14610. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot());
  14611. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector());
  14612. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName());
  14613. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment());
  14614. var _id = _interopRequireDefault(/*@__PURE__*/ requireId());
  14615. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag());
  14616. var _string = _interopRequireDefault(/*@__PURE__*/ requireString());
  14617. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo());
  14618. var _attribute = _interopRequireWildcard(/*@__PURE__*/ requireAttribute());
  14619. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal());
  14620. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator());
  14621. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting());
  14622. var _sortAscending = _interopRequireDefault(/*@__PURE__*/ requireSortAscending());
  14623. var _tokenize = _interopRequireWildcard(/*@__PURE__*/ requireTokenize());
  14624. var tokens = _interopRequireWildcard(/*@__PURE__*/ requireTokenTypes());
  14625. var types = _interopRequireWildcard(/*@__PURE__*/ requireTypes());
  14626. var _util = /*@__PURE__*/ requireUtil();
  14627. var _WHITESPACE_TOKENS, _Object$assign;
  14628. 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); }
  14629. 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; }
  14630. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  14631. 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); } }
  14632. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  14633. 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);
  14634. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  14635. function tokenStart(token) {
  14636. return {
  14637. line: token[_tokenize.FIELDS.START_LINE],
  14638. column: token[_tokenize.FIELDS.START_COL]
  14639. };
  14640. }
  14641. function tokenEnd(token) {
  14642. return {
  14643. line: token[_tokenize.FIELDS.END_LINE],
  14644. column: token[_tokenize.FIELDS.END_COL]
  14645. };
  14646. }
  14647. function getSource(startLine, startColumn, endLine, endColumn) {
  14648. return {
  14649. start: {
  14650. line: startLine,
  14651. column: startColumn
  14652. },
  14653. end: {
  14654. line: endLine,
  14655. column: endColumn
  14656. }
  14657. };
  14658. }
  14659. function getTokenSource(token) {
  14660. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  14661. }
  14662. function getTokenSourceSpan(startToken, endToken) {
  14663. if (!startToken) {
  14664. return undefined;
  14665. }
  14666. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  14667. }
  14668. function unescapeProp(node, prop) {
  14669. var value = node[prop];
  14670. if (typeof value !== "string") {
  14671. return;
  14672. }
  14673. if (value.indexOf("\\") !== -1) {
  14674. (0, _util.ensureObject)(node, 'raws');
  14675. node[prop] = (0, _util.unesc)(value);
  14676. if (node.raws[prop] === undefined) {
  14677. node.raws[prop] = value;
  14678. }
  14679. }
  14680. return node;
  14681. }
  14682. function indexesOf(array, item) {
  14683. var i = -1;
  14684. var indexes = [];
  14685. while ((i = array.indexOf(item, i + 1)) !== -1) {
  14686. indexes.push(i);
  14687. }
  14688. return indexes;
  14689. }
  14690. function uniqs() {
  14691. var list = Array.prototype.concat.apply([], arguments);
  14692. return list.filter(function (item, i) {
  14693. return i === list.indexOf(item);
  14694. });
  14695. }
  14696. var Parser = /*#__PURE__*/function () {
  14697. function Parser(rule, options) {
  14698. if (options === void 0) {
  14699. options = {};
  14700. }
  14701. this.rule = rule;
  14702. this.options = Object.assign({
  14703. lossy: false,
  14704. safe: false
  14705. }, options);
  14706. this.position = 0;
  14707. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  14708. this.tokens = (0, _tokenize["default"])({
  14709. css: this.css,
  14710. error: this._errorGenerator(),
  14711. safe: this.options.safe
  14712. });
  14713. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  14714. this.root = new _root["default"]({
  14715. source: rootSource
  14716. });
  14717. this.root.errorGenerator = this._errorGenerator();
  14718. var selector = new _selector["default"]({
  14719. source: {
  14720. start: {
  14721. line: 1,
  14722. column: 1
  14723. }
  14724. },
  14725. sourceIndex: 0
  14726. });
  14727. this.root.append(selector);
  14728. this.current = selector;
  14729. this.loop();
  14730. }
  14731. var _proto = Parser.prototype;
  14732. _proto._errorGenerator = function _errorGenerator() {
  14733. var _this = this;
  14734. return function (message, errorOptions) {
  14735. if (typeof _this.rule === 'string') {
  14736. return new Error(message);
  14737. }
  14738. return _this.rule.error(message, errorOptions);
  14739. };
  14740. };
  14741. _proto.attribute = function attribute() {
  14742. var attr = [];
  14743. var startingToken = this.currToken;
  14744. this.position++;
  14745. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  14746. attr.push(this.currToken);
  14747. this.position++;
  14748. }
  14749. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  14750. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  14751. }
  14752. var len = attr.length;
  14753. var node = {
  14754. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  14755. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  14756. };
  14757. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  14758. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  14759. }
  14760. var pos = 0;
  14761. var spaceBefore = '';
  14762. var commentBefore = '';
  14763. var lastAdded = null;
  14764. var spaceAfterMeaningfulToken = false;
  14765. while (pos < len) {
  14766. var token = attr[pos];
  14767. var content = this.content(token);
  14768. var next = attr[pos + 1];
  14769. switch (token[_tokenize.FIELDS.TYPE]) {
  14770. case tokens.space:
  14771. // if (
  14772. // len === 1 ||
  14773. // pos === 0 && this.content(next) === '|'
  14774. // ) {
  14775. // return this.expected('attribute', token[TOKEN.START_POS], content);
  14776. // }
  14777. spaceAfterMeaningfulToken = true;
  14778. if (this.options.lossy) {
  14779. break;
  14780. }
  14781. if (lastAdded) {
  14782. (0, _util.ensureObject)(node, 'spaces', lastAdded);
  14783. var prevContent = node.spaces[lastAdded].after || '';
  14784. node.spaces[lastAdded].after = prevContent + content;
  14785. var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  14786. if (existingComment) {
  14787. node.raws.spaces[lastAdded].after = existingComment + content;
  14788. }
  14789. } else {
  14790. spaceBefore = spaceBefore + content;
  14791. commentBefore = commentBefore + content;
  14792. }
  14793. break;
  14794. case tokens.asterisk:
  14795. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14796. node.operator = content;
  14797. lastAdded = 'operator';
  14798. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  14799. if (spaceBefore) {
  14800. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  14801. node.spaces.attribute.before = spaceBefore;
  14802. spaceBefore = '';
  14803. }
  14804. if (commentBefore) {
  14805. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  14806. node.raws.spaces.attribute.before = spaceBefore;
  14807. commentBefore = '';
  14808. }
  14809. node.namespace = (node.namespace || "") + content;
  14810. var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null;
  14811. if (rawValue) {
  14812. node.raws.namespace += content;
  14813. }
  14814. lastAdded = 'namespace';
  14815. }
  14816. spaceAfterMeaningfulToken = false;
  14817. break;
  14818. case tokens.dollar:
  14819. if (lastAdded === "value") {
  14820. var oldRawValue = (0, _util.getProp)(node, 'raws', 'value');
  14821. node.value += "$";
  14822. if (oldRawValue) {
  14823. node.raws.value = oldRawValue + "$";
  14824. }
  14825. break;
  14826. }
  14827. // Falls through
  14828. case tokens.caret:
  14829. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14830. node.operator = content;
  14831. lastAdded = 'operator';
  14832. }
  14833. spaceAfterMeaningfulToken = false;
  14834. break;
  14835. case tokens.combinator:
  14836. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14837. node.operator = content;
  14838. lastAdded = 'operator';
  14839. }
  14840. if (content !== '|') {
  14841. spaceAfterMeaningfulToken = false;
  14842. break;
  14843. }
  14844. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  14845. node.operator = content;
  14846. lastAdded = 'operator';
  14847. } else if (!node.namespace && !node.attribute) {
  14848. node.namespace = true;
  14849. }
  14850. spaceAfterMeaningfulToken = false;
  14851. break;
  14852. case tokens.word:
  14853. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals &&
  14854. // this look-ahead probably fails with comment nodes involved.
  14855. !node.operator && !node.namespace) {
  14856. node.namespace = content;
  14857. lastAdded = 'namespace';
  14858. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  14859. if (spaceBefore) {
  14860. (0, _util.ensureObject)(node, 'spaces', 'attribute');
  14861. node.spaces.attribute.before = spaceBefore;
  14862. spaceBefore = '';
  14863. }
  14864. if (commentBefore) {
  14865. (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute');
  14866. node.raws.spaces.attribute.before = commentBefore;
  14867. commentBefore = '';
  14868. }
  14869. node.attribute = (node.attribute || "") + content;
  14870. var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null;
  14871. if (_rawValue) {
  14872. node.raws.attribute += content;
  14873. }
  14874. lastAdded = 'attribute';
  14875. } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) {
  14876. var _unescaped = (0, _util.unesc)(content);
  14877. var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || '';
  14878. var oldValue = node.value || '';
  14879. node.value = oldValue + _unescaped;
  14880. node.quoteMark = null;
  14881. if (_unescaped !== content || _oldRawValue) {
  14882. (0, _util.ensureObject)(node, 'raws');
  14883. node.raws.value = (_oldRawValue || oldValue) + content;
  14884. }
  14885. lastAdded = 'value';
  14886. } else {
  14887. var insensitive = content === 'i' || content === "I";
  14888. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  14889. node.insensitive = insensitive;
  14890. if (!insensitive || content === "I") {
  14891. (0, _util.ensureObject)(node, 'raws');
  14892. node.raws.insensitiveFlag = content;
  14893. }
  14894. lastAdded = 'insensitive';
  14895. if (spaceBefore) {
  14896. (0, _util.ensureObject)(node, 'spaces', 'insensitive');
  14897. node.spaces.insensitive.before = spaceBefore;
  14898. spaceBefore = '';
  14899. }
  14900. if (commentBefore) {
  14901. (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  14902. node.raws.spaces.insensitive.before = commentBefore;
  14903. commentBefore = '';
  14904. }
  14905. } else if (node.value || node.value === '') {
  14906. lastAdded = 'value';
  14907. node.value += content;
  14908. if (node.raws.value) {
  14909. node.raws.value += content;
  14910. }
  14911. }
  14912. }
  14913. spaceAfterMeaningfulToken = false;
  14914. break;
  14915. case tokens.str:
  14916. if (!node.attribute || !node.operator) {
  14917. return this.error("Expected an attribute followed by an operator preceding the string.", {
  14918. index: token[_tokenize.FIELDS.START_POS]
  14919. });
  14920. }
  14921. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  14922. unescaped = _unescapeValue.unescaped,
  14923. quoteMark = _unescapeValue.quoteMark;
  14924. node.value = unescaped;
  14925. node.quoteMark = quoteMark;
  14926. lastAdded = 'value';
  14927. (0, _util.ensureObject)(node, 'raws');
  14928. node.raws.value = content;
  14929. spaceAfterMeaningfulToken = false;
  14930. break;
  14931. case tokens.equals:
  14932. if (!node.attribute) {
  14933. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  14934. }
  14935. if (node.value) {
  14936. return this.error('Unexpected "=" found; an operator was already defined.', {
  14937. index: token[_tokenize.FIELDS.START_POS]
  14938. });
  14939. }
  14940. node.operator = node.operator ? node.operator + content : content;
  14941. lastAdded = 'operator';
  14942. spaceAfterMeaningfulToken = false;
  14943. break;
  14944. case tokens.comment:
  14945. if (lastAdded) {
  14946. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  14947. var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || '';
  14948. var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  14949. (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded);
  14950. node.raws.spaces[lastAdded].after = rawLastComment + content;
  14951. } else {
  14952. var lastValue = node[lastAdded] || '';
  14953. var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue;
  14954. (0, _util.ensureObject)(node, 'raws');
  14955. node.raws[lastAdded] = rawLastValue + content;
  14956. }
  14957. } else {
  14958. commentBefore = commentBefore + content;
  14959. }
  14960. break;
  14961. default:
  14962. return this.error("Unexpected \"" + content + "\" found.", {
  14963. index: token[_tokenize.FIELDS.START_POS]
  14964. });
  14965. }
  14966. pos++;
  14967. }
  14968. unescapeProp(node, "attribute");
  14969. unescapeProp(node, "namespace");
  14970. this.newNode(new _attribute["default"](node));
  14971. this.position++;
  14972. }
  14973. /**
  14974. * return a node containing meaningless garbage up to (but not including) the specified token position.
  14975. * if the token position is negative, all remaining tokens are consumed.
  14976. *
  14977. * This returns an array containing a single string node if all whitespace,
  14978. * otherwise an array of comment nodes with space before and after.
  14979. *
  14980. * These tokens are not added to the current selector, the caller can add them or use them to amend
  14981. * a previous node's space metadata.
  14982. *
  14983. * In lossy mode, this returns only comments.
  14984. */;
  14985. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  14986. if (stopPosition < 0) {
  14987. stopPosition = this.tokens.length;
  14988. }
  14989. var startPosition = this.position;
  14990. var nodes = [];
  14991. var space = "";
  14992. var lastComment = undefined;
  14993. do {
  14994. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  14995. if (!this.options.lossy) {
  14996. space += this.content();
  14997. }
  14998. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  14999. var spaces = {};
  15000. if (space) {
  15001. spaces.before = space;
  15002. space = "";
  15003. }
  15004. lastComment = new _comment["default"]({
  15005. value: this.content(),
  15006. source: getTokenSource(this.currToken),
  15007. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  15008. spaces: spaces
  15009. });
  15010. nodes.push(lastComment);
  15011. }
  15012. } while (++this.position < stopPosition);
  15013. if (space) {
  15014. if (lastComment) {
  15015. lastComment.spaces.after = space;
  15016. } else if (!this.options.lossy) {
  15017. var firstToken = this.tokens[startPosition];
  15018. var lastToken = this.tokens[this.position - 1];
  15019. nodes.push(new _string["default"]({
  15020. value: '',
  15021. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  15022. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  15023. spaces: {
  15024. before: space,
  15025. after: ''
  15026. }
  15027. }));
  15028. }
  15029. }
  15030. return nodes;
  15031. }
  15032. /**
  15033. *
  15034. * @param {*} nodes
  15035. */;
  15036. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  15037. var _this2 = this;
  15038. if (requiredSpace === void 0) {
  15039. requiredSpace = false;
  15040. }
  15041. var space = "";
  15042. var rawSpace = "";
  15043. nodes.forEach(function (n) {
  15044. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  15045. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  15046. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  15047. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  15048. });
  15049. if (rawSpace === space) {
  15050. rawSpace = undefined;
  15051. }
  15052. var result = {
  15053. space: space,
  15054. rawSpace: rawSpace
  15055. };
  15056. return result;
  15057. };
  15058. _proto.isNamedCombinator = function isNamedCombinator(position) {
  15059. if (position === void 0) {
  15060. position = this.position;
  15061. }
  15062. 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;
  15063. };
  15064. _proto.namedCombinator = function namedCombinator() {
  15065. if (this.isNamedCombinator()) {
  15066. var nameRaw = this.content(this.tokens[this.position + 1]);
  15067. var name = (0, _util.unesc)(nameRaw).toLowerCase();
  15068. var raws = {};
  15069. if (name !== nameRaw) {
  15070. raws.value = "/" + nameRaw + "/";
  15071. }
  15072. var node = new _combinator["default"]({
  15073. value: "/" + name + "/",
  15074. 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]),
  15075. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  15076. raws: raws
  15077. });
  15078. this.position = this.position + 3;
  15079. return node;
  15080. } else {
  15081. this.unexpected();
  15082. }
  15083. };
  15084. _proto.combinator = function combinator() {
  15085. var _this3 = this;
  15086. if (this.content() === '|') {
  15087. return this.namespace();
  15088. }
  15089. // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  15090. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  15091. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15092. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  15093. if (nodes.length > 0) {
  15094. var last = this.current.last;
  15095. if (last) {
  15096. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  15097. space = _this$convertWhitespa.space,
  15098. rawSpace = _this$convertWhitespa.rawSpace;
  15099. if (rawSpace !== undefined) {
  15100. last.rawSpaceAfter += rawSpace;
  15101. }
  15102. last.spaces.after += space;
  15103. } else {
  15104. nodes.forEach(function (n) {
  15105. return _this3.newNode(n);
  15106. });
  15107. }
  15108. }
  15109. return;
  15110. }
  15111. var firstToken = this.currToken;
  15112. var spaceOrDescendantSelectorNodes = undefined;
  15113. if (nextSigTokenPos > this.position) {
  15114. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  15115. }
  15116. var node;
  15117. if (this.isNamedCombinator()) {
  15118. node = this.namedCombinator();
  15119. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  15120. node = new _combinator["default"]({
  15121. value: this.content(),
  15122. source: getTokenSource(this.currToken),
  15123. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  15124. });
  15125. this.position++;
  15126. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  15127. this.unexpected();
  15128. }
  15129. if (node) {
  15130. if (spaceOrDescendantSelectorNodes) {
  15131. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  15132. _space = _this$convertWhitespa2.space,
  15133. _rawSpace = _this$convertWhitespa2.rawSpace;
  15134. node.spaces.before = _space;
  15135. node.rawSpaceBefore = _rawSpace;
  15136. }
  15137. } else {
  15138. // descendant combinator
  15139. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  15140. _space2 = _this$convertWhitespa3.space,
  15141. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  15142. if (!_rawSpace2) {
  15143. _rawSpace2 = _space2;
  15144. }
  15145. var spaces = {};
  15146. var raws = {
  15147. spaces: {}
  15148. };
  15149. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  15150. spaces.before = _space2.slice(0, _space2.length - 1);
  15151. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  15152. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  15153. spaces.after = _space2.slice(1);
  15154. raws.spaces.after = _rawSpace2.slice(1);
  15155. } else {
  15156. raws.value = _rawSpace2;
  15157. }
  15158. node = new _combinator["default"]({
  15159. value: ' ',
  15160. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  15161. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  15162. spaces: spaces,
  15163. raws: raws
  15164. });
  15165. }
  15166. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  15167. node.spaces.after = this.optionalSpace(this.content());
  15168. this.position++;
  15169. }
  15170. return this.newNode(node);
  15171. };
  15172. _proto.comma = function comma() {
  15173. if (this.position === this.tokens.length - 1) {
  15174. this.root.trailingComma = true;
  15175. this.position++;
  15176. return;
  15177. }
  15178. this.current._inferEndPosition();
  15179. var selector = new _selector["default"]({
  15180. source: {
  15181. start: tokenStart(this.tokens[this.position + 1])
  15182. },
  15183. sourceIndex: this.tokens[this.position + 1][_tokenize.FIELDS.START_POS]
  15184. });
  15185. this.current.parent.append(selector);
  15186. this.current = selector;
  15187. this.position++;
  15188. };
  15189. _proto.comment = function comment() {
  15190. var current = this.currToken;
  15191. this.newNode(new _comment["default"]({
  15192. value: this.content(),
  15193. source: getTokenSource(current),
  15194. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15195. }));
  15196. this.position++;
  15197. };
  15198. _proto.error = function error(message, opts) {
  15199. throw this.root.error(message, opts);
  15200. };
  15201. _proto.missingBackslash = function missingBackslash() {
  15202. return this.error('Expected a backslash preceding the semicolon.', {
  15203. index: this.currToken[_tokenize.FIELDS.START_POS]
  15204. });
  15205. };
  15206. _proto.missingParenthesis = function missingParenthesis() {
  15207. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  15208. };
  15209. _proto.missingSquareBracket = function missingSquareBracket() {
  15210. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  15211. };
  15212. _proto.unexpected = function unexpected() {
  15213. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  15214. };
  15215. _proto.unexpectedPipe = function unexpectedPipe() {
  15216. return this.error("Unexpected '|'.", this.currToken[_tokenize.FIELDS.START_POS]);
  15217. };
  15218. _proto.namespace = function namespace() {
  15219. var before = this.prevToken && this.content(this.prevToken) || true;
  15220. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  15221. this.position++;
  15222. return this.word(before);
  15223. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  15224. this.position++;
  15225. return this.universal(before);
  15226. }
  15227. this.unexpectedPipe();
  15228. };
  15229. _proto.nesting = function nesting() {
  15230. if (this.nextToken) {
  15231. var nextContent = this.content(this.nextToken);
  15232. if (nextContent === "|") {
  15233. this.position++;
  15234. return;
  15235. }
  15236. }
  15237. var current = this.currToken;
  15238. this.newNode(new _nesting["default"]({
  15239. value: this.content(),
  15240. source: getTokenSource(current),
  15241. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15242. }));
  15243. this.position++;
  15244. };
  15245. _proto.parentheses = function parentheses() {
  15246. var last = this.current.last;
  15247. var unbalanced = 1;
  15248. this.position++;
  15249. if (last && last.type === types.PSEUDO) {
  15250. var selector = new _selector["default"]({
  15251. source: {
  15252. start: tokenStart(this.tokens[this.position])
  15253. },
  15254. sourceIndex: this.tokens[this.position][_tokenize.FIELDS.START_POS]
  15255. });
  15256. var cache = this.current;
  15257. last.append(selector);
  15258. this.current = selector;
  15259. while (this.position < this.tokens.length && unbalanced) {
  15260. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15261. unbalanced++;
  15262. }
  15263. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15264. unbalanced--;
  15265. }
  15266. if (unbalanced) {
  15267. this.parse();
  15268. } else {
  15269. this.current.source.end = tokenEnd(this.currToken);
  15270. this.current.parent.source.end = tokenEnd(this.currToken);
  15271. this.position++;
  15272. }
  15273. }
  15274. this.current = cache;
  15275. } else {
  15276. // I think this case should be an error. It's used to implement a basic parse of media queries
  15277. // but I don't think it's a good idea.
  15278. var parenStart = this.currToken;
  15279. var parenValue = "(";
  15280. var parenEnd;
  15281. while (this.position < this.tokens.length && unbalanced) {
  15282. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15283. unbalanced++;
  15284. }
  15285. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15286. unbalanced--;
  15287. }
  15288. parenEnd = this.currToken;
  15289. parenValue += this.parseParenthesisToken(this.currToken);
  15290. this.position++;
  15291. }
  15292. if (last) {
  15293. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  15294. } else {
  15295. this.newNode(new _string["default"]({
  15296. value: parenValue,
  15297. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  15298. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  15299. }));
  15300. }
  15301. }
  15302. if (unbalanced) {
  15303. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  15304. }
  15305. };
  15306. _proto.pseudo = function pseudo() {
  15307. var _this4 = this;
  15308. var pseudoStr = '';
  15309. var startingToken = this.currToken;
  15310. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  15311. pseudoStr += this.content();
  15312. this.position++;
  15313. }
  15314. if (!this.currToken) {
  15315. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  15316. }
  15317. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  15318. this.splitWord(false, function (first, length) {
  15319. pseudoStr += first;
  15320. _this4.newNode(new _pseudo["default"]({
  15321. value: pseudoStr,
  15322. source: getTokenSourceSpan(startingToken, _this4.currToken),
  15323. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  15324. }));
  15325. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  15326. _this4.error('Misplaced parenthesis.', {
  15327. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  15328. });
  15329. }
  15330. });
  15331. } else {
  15332. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  15333. }
  15334. };
  15335. _proto.space = function space() {
  15336. var content = this.content();
  15337. // Handle space before and after the selector
  15338. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  15339. return node.type === 'comment';
  15340. })) {
  15341. this.spaces = this.optionalSpace(content);
  15342. this.position++;
  15343. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  15344. this.current.last.spaces.after = this.optionalSpace(content);
  15345. this.position++;
  15346. } else {
  15347. this.combinator();
  15348. }
  15349. };
  15350. _proto.string = function string() {
  15351. var current = this.currToken;
  15352. this.newNode(new _string["default"]({
  15353. value: this.content(),
  15354. source: getTokenSource(current),
  15355. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15356. }));
  15357. this.position++;
  15358. };
  15359. _proto.universal = function universal(namespace) {
  15360. var nextToken = this.nextToken;
  15361. if (nextToken && this.content(nextToken) === '|') {
  15362. this.position++;
  15363. return this.namespace();
  15364. }
  15365. var current = this.currToken;
  15366. this.newNode(new _universal["default"]({
  15367. value: this.content(),
  15368. source: getTokenSource(current),
  15369. sourceIndex: current[_tokenize.FIELDS.START_POS]
  15370. }), namespace);
  15371. this.position++;
  15372. };
  15373. _proto.splitWord = function splitWord(namespace, firstCallback) {
  15374. var _this5 = this;
  15375. var nextToken = this.nextToken;
  15376. var word = this.content();
  15377. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  15378. this.position++;
  15379. var current = this.content();
  15380. word += current;
  15381. if (current.lastIndexOf('\\') === current.length - 1) {
  15382. var next = this.nextToken;
  15383. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  15384. word += this.requiredSpace(this.content(next));
  15385. this.position++;
  15386. }
  15387. }
  15388. nextToken = this.nextToken;
  15389. }
  15390. var hasClass = indexesOf(word, '.').filter(function (i) {
  15391. // Allow escaped dot within class name
  15392. var escapedDot = word[i - 1] === '\\';
  15393. // Allow decimal numbers percent in @keyframes
  15394. var isKeyframesPercent = /^\d+\.\d+%$/.test(word);
  15395. return !escapedDot && !isKeyframesPercent;
  15396. });
  15397. var hasId = indexesOf(word, '#').filter(function (i) {
  15398. return word[i - 1] !== '\\';
  15399. });
  15400. // Eliminate Sass interpolations from the list of id indexes
  15401. var interpolations = indexesOf(word, '#{');
  15402. if (interpolations.length) {
  15403. hasId = hasId.filter(function (hashIndex) {
  15404. return !~interpolations.indexOf(hashIndex);
  15405. });
  15406. }
  15407. var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
  15408. indices.forEach(function (ind, i) {
  15409. var index = indices[i + 1] || word.length;
  15410. var value = word.slice(ind, index);
  15411. if (i === 0 && firstCallback) {
  15412. return firstCallback.call(_this5, value, indices.length);
  15413. }
  15414. var node;
  15415. var current = _this5.currToken;
  15416. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  15417. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  15418. if (~hasClass.indexOf(ind)) {
  15419. var classNameOpts = {
  15420. value: value.slice(1),
  15421. source: source,
  15422. sourceIndex: sourceIndex
  15423. };
  15424. node = new _className["default"](unescapeProp(classNameOpts, "value"));
  15425. } else if (~hasId.indexOf(ind)) {
  15426. var idOpts = {
  15427. value: value.slice(1),
  15428. source: source,
  15429. sourceIndex: sourceIndex
  15430. };
  15431. node = new _id["default"](unescapeProp(idOpts, "value"));
  15432. } else {
  15433. var tagOpts = {
  15434. value: value,
  15435. source: source,
  15436. sourceIndex: sourceIndex
  15437. };
  15438. unescapeProp(tagOpts, "value");
  15439. node = new _tag["default"](tagOpts);
  15440. }
  15441. _this5.newNode(node, namespace);
  15442. // Ensure that the namespace is used only once
  15443. namespace = null;
  15444. });
  15445. this.position++;
  15446. };
  15447. _proto.word = function word(namespace) {
  15448. var nextToken = this.nextToken;
  15449. if (nextToken && this.content(nextToken) === '|') {
  15450. this.position++;
  15451. return this.namespace();
  15452. }
  15453. return this.splitWord(namespace);
  15454. };
  15455. _proto.loop = function loop() {
  15456. while (this.position < this.tokens.length) {
  15457. this.parse(true);
  15458. }
  15459. this.current._inferEndPosition();
  15460. return this.root;
  15461. };
  15462. _proto.parse = function parse(throwOnParenthesis) {
  15463. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  15464. case tokens.space:
  15465. this.space();
  15466. break;
  15467. case tokens.comment:
  15468. this.comment();
  15469. break;
  15470. case tokens.openParenthesis:
  15471. this.parentheses();
  15472. break;
  15473. case tokens.closeParenthesis:
  15474. if (throwOnParenthesis) {
  15475. this.missingParenthesis();
  15476. }
  15477. break;
  15478. case tokens.openSquare:
  15479. this.attribute();
  15480. break;
  15481. case tokens.dollar:
  15482. case tokens.caret:
  15483. case tokens.equals:
  15484. case tokens.word:
  15485. this.word();
  15486. break;
  15487. case tokens.colon:
  15488. this.pseudo();
  15489. break;
  15490. case tokens.comma:
  15491. this.comma();
  15492. break;
  15493. case tokens.asterisk:
  15494. this.universal();
  15495. break;
  15496. case tokens.ampersand:
  15497. this.nesting();
  15498. break;
  15499. case tokens.slash:
  15500. case tokens.combinator:
  15501. this.combinator();
  15502. break;
  15503. case tokens.str:
  15504. this.string();
  15505. break;
  15506. // These cases throw; no break needed.
  15507. case tokens.closeSquare:
  15508. this.missingSquareBracket();
  15509. case tokens.semicolon:
  15510. this.missingBackslash();
  15511. default:
  15512. this.unexpected();
  15513. }
  15514. }
  15515. /**
  15516. * Helpers
  15517. */;
  15518. _proto.expected = function expected(description, index, found) {
  15519. if (Array.isArray(description)) {
  15520. var last = description.pop();
  15521. description = description.join(', ') + " or " + last;
  15522. }
  15523. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  15524. if (!found) {
  15525. return this.error("Expected " + an + " " + description + ".", {
  15526. index: index
  15527. });
  15528. }
  15529. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  15530. index: index
  15531. });
  15532. };
  15533. _proto.requiredSpace = function requiredSpace(space) {
  15534. return this.options.lossy ? ' ' : space;
  15535. };
  15536. _proto.optionalSpace = function optionalSpace(space) {
  15537. return this.options.lossy ? '' : space;
  15538. };
  15539. _proto.lossySpace = function lossySpace(space, required) {
  15540. if (this.options.lossy) {
  15541. return required ? ' ' : '';
  15542. } else {
  15543. return space;
  15544. }
  15545. };
  15546. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  15547. var content = this.content(token);
  15548. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  15549. return this.requiredSpace(content);
  15550. } else {
  15551. return content;
  15552. }
  15553. };
  15554. _proto.newNode = function newNode(node, namespace) {
  15555. if (namespace) {
  15556. if (/^ +$/.test(namespace)) {
  15557. if (!this.options.lossy) {
  15558. this.spaces = (this.spaces || '') + namespace;
  15559. }
  15560. namespace = true;
  15561. }
  15562. node.namespace = namespace;
  15563. unescapeProp(node, "namespace");
  15564. }
  15565. if (this.spaces) {
  15566. node.spaces.before = this.spaces;
  15567. this.spaces = '';
  15568. }
  15569. return this.current.append(node);
  15570. };
  15571. _proto.content = function content(token) {
  15572. if (token === void 0) {
  15573. token = this.currToken;
  15574. }
  15575. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  15576. };
  15577. /**
  15578. * returns the index of the next non-whitespace, non-comment token.
  15579. * returns -1 if no meaningful token is found.
  15580. */
  15581. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  15582. if (startPosition === void 0) {
  15583. startPosition = this.position + 1;
  15584. }
  15585. var searchPosition = startPosition;
  15586. while (searchPosition < this.tokens.length) {
  15587. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  15588. searchPosition++;
  15589. continue;
  15590. } else {
  15591. return searchPosition;
  15592. }
  15593. }
  15594. return -1;
  15595. };
  15596. _createClass(Parser, [{
  15597. key: "currToken",
  15598. get: function get() {
  15599. return this.tokens[this.position];
  15600. }
  15601. }, {
  15602. key: "nextToken",
  15603. get: function get() {
  15604. return this.tokens[this.position + 1];
  15605. }
  15606. }, {
  15607. key: "prevToken",
  15608. get: function get() {
  15609. return this.tokens[this.position - 1];
  15610. }
  15611. }]);
  15612. return Parser;
  15613. }();
  15614. exports["default"] = Parser;
  15615. module.exports = exports.default;
  15616. } (parser, parser.exports));
  15617. return parser.exports;
  15618. }
  15619. var hasRequiredProcessor;
  15620. function requireProcessor () {
  15621. if (hasRequiredProcessor) return processor.exports;
  15622. hasRequiredProcessor = 1;
  15623. (function (module, exports) {
  15624. exports.__esModule = true;
  15625. exports["default"] = void 0;
  15626. var _parser = _interopRequireDefault(/*@__PURE__*/ requireParser());
  15627. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  15628. var Processor = /*#__PURE__*/function () {
  15629. function Processor(func, options) {
  15630. this.func = func || function noop() {};
  15631. this.funcRes = null;
  15632. this.options = options;
  15633. }
  15634. var _proto = Processor.prototype;
  15635. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  15636. if (options === void 0) {
  15637. options = {};
  15638. }
  15639. var merged = Object.assign({}, this.options, options);
  15640. if (merged.updateSelector === false) {
  15641. return false;
  15642. } else {
  15643. return typeof rule !== "string";
  15644. }
  15645. };
  15646. _proto._isLossy = function _isLossy(options) {
  15647. if (options === void 0) {
  15648. options = {};
  15649. }
  15650. var merged = Object.assign({}, this.options, options);
  15651. if (merged.lossless === false) {
  15652. return true;
  15653. } else {
  15654. return false;
  15655. }
  15656. };
  15657. _proto._root = function _root(rule, options) {
  15658. if (options === void 0) {
  15659. options = {};
  15660. }
  15661. var parser = new _parser["default"](rule, this._parseOptions(options));
  15662. return parser.root;
  15663. };
  15664. _proto._parseOptions = function _parseOptions(options) {
  15665. return {
  15666. lossy: this._isLossy(options)
  15667. };
  15668. };
  15669. _proto._run = function _run(rule, options) {
  15670. var _this = this;
  15671. if (options === void 0) {
  15672. options = {};
  15673. }
  15674. return new Promise(function (resolve, reject) {
  15675. try {
  15676. var root = _this._root(rule, options);
  15677. Promise.resolve(_this.func(root)).then(function (transform) {
  15678. var string = undefined;
  15679. if (_this._shouldUpdateSelector(rule, options)) {
  15680. string = root.toString();
  15681. rule.selector = string;
  15682. }
  15683. return {
  15684. transform: transform,
  15685. root: root,
  15686. string: string
  15687. };
  15688. }).then(resolve, reject);
  15689. } catch (e) {
  15690. reject(e);
  15691. return;
  15692. }
  15693. });
  15694. };
  15695. _proto._runSync = function _runSync(rule, options) {
  15696. if (options === void 0) {
  15697. options = {};
  15698. }
  15699. var root = this._root(rule, options);
  15700. var transform = this.func(root);
  15701. if (transform && typeof transform.then === "function") {
  15702. throw new Error("Selector processor returned a promise to a synchronous call.");
  15703. }
  15704. var string = undefined;
  15705. if (options.updateSelector && typeof rule !== "string") {
  15706. string = root.toString();
  15707. rule.selector = string;
  15708. }
  15709. return {
  15710. transform: transform,
  15711. root: root,
  15712. string: string
  15713. };
  15714. }
  15715. /**
  15716. * Process rule into a selector AST.
  15717. *
  15718. * @param rule {postcss.Rule | string} The css selector to be processed
  15719. * @param options The options for processing
  15720. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  15721. */;
  15722. _proto.ast = function ast(rule, options) {
  15723. return this._run(rule, options).then(function (result) {
  15724. return result.root;
  15725. });
  15726. }
  15727. /**
  15728. * Process rule into a selector AST synchronously.
  15729. *
  15730. * @param rule {postcss.Rule | string} The css selector to be processed
  15731. * @param options The options for processing
  15732. * @returns {parser.Root} The AST of the selector after processing it.
  15733. */;
  15734. _proto.astSync = function astSync(rule, options) {
  15735. return this._runSync(rule, options).root;
  15736. }
  15737. /**
  15738. * Process a selector into a transformed value asynchronously
  15739. *
  15740. * @param rule {postcss.Rule | string} The css selector to be processed
  15741. * @param options The options for processing
  15742. * @returns {Promise<any>} The value returned by the processor.
  15743. */;
  15744. _proto.transform = function transform(rule, options) {
  15745. return this._run(rule, options).then(function (result) {
  15746. return result.transform;
  15747. });
  15748. }
  15749. /**
  15750. * Process a selector into a transformed value synchronously.
  15751. *
  15752. * @param rule {postcss.Rule | string} The css selector to be processed
  15753. * @param options The options for processing
  15754. * @returns {any} The value returned by the processor.
  15755. */;
  15756. _proto.transformSync = function transformSync(rule, options) {
  15757. return this._runSync(rule, options).transform;
  15758. }
  15759. /**
  15760. * Process a selector into a new selector string asynchronously.
  15761. *
  15762. * @param rule {postcss.Rule | string} The css selector to be processed
  15763. * @param options The options for processing
  15764. * @returns {string} the selector after processing.
  15765. */;
  15766. _proto.process = function process(rule, options) {
  15767. return this._run(rule, options).then(function (result) {
  15768. return result.string || result.root.toString();
  15769. });
  15770. }
  15771. /**
  15772. * Process a selector into a new selector string synchronously.
  15773. *
  15774. * @param rule {postcss.Rule | string} The css selector to be processed
  15775. * @param options The options for processing
  15776. * @returns {string} the selector after processing.
  15777. */;
  15778. _proto.processSync = function processSync(rule, options) {
  15779. var result = this._runSync(rule, options);
  15780. return result.string || result.root.toString();
  15781. };
  15782. return Processor;
  15783. }();
  15784. exports["default"] = Processor;
  15785. module.exports = exports.default;
  15786. } (processor, processor.exports));
  15787. return processor.exports;
  15788. }
  15789. var selectors = {};
  15790. var constructors = {};
  15791. var hasRequiredConstructors;
  15792. function requireConstructors () {
  15793. if (hasRequiredConstructors) return constructors;
  15794. hasRequiredConstructors = 1;
  15795. constructors.__esModule = true;
  15796. 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;
  15797. var _attribute = _interopRequireDefault(/*@__PURE__*/ requireAttribute());
  15798. var _className = _interopRequireDefault(/*@__PURE__*/ requireClassName());
  15799. var _combinator = _interopRequireDefault(/*@__PURE__*/ requireCombinator());
  15800. var _comment = _interopRequireDefault(/*@__PURE__*/ requireComment());
  15801. var _id = _interopRequireDefault(/*@__PURE__*/ requireId());
  15802. var _nesting = _interopRequireDefault(/*@__PURE__*/ requireNesting());
  15803. var _pseudo = _interopRequireDefault(/*@__PURE__*/ requirePseudo());
  15804. var _root = _interopRequireDefault(/*@__PURE__*/ requireRoot());
  15805. var _selector = _interopRequireDefault(/*@__PURE__*/ requireSelector());
  15806. var _string = _interopRequireDefault(/*@__PURE__*/ requireString());
  15807. var _tag = _interopRequireDefault(/*@__PURE__*/ requireTag());
  15808. var _universal = _interopRequireDefault(/*@__PURE__*/ requireUniversal());
  15809. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  15810. var attribute = function attribute(opts) {
  15811. return new _attribute["default"](opts);
  15812. };
  15813. constructors.attribute = attribute;
  15814. var className = function className(opts) {
  15815. return new _className["default"](opts);
  15816. };
  15817. constructors.className = className;
  15818. var combinator = function combinator(opts) {
  15819. return new _combinator["default"](opts);
  15820. };
  15821. constructors.combinator = combinator;
  15822. var comment = function comment(opts) {
  15823. return new _comment["default"](opts);
  15824. };
  15825. constructors.comment = comment;
  15826. var id = function id(opts) {
  15827. return new _id["default"](opts);
  15828. };
  15829. constructors.id = id;
  15830. var nesting = function nesting(opts) {
  15831. return new _nesting["default"](opts);
  15832. };
  15833. constructors.nesting = nesting;
  15834. var pseudo = function pseudo(opts) {
  15835. return new _pseudo["default"](opts);
  15836. };
  15837. constructors.pseudo = pseudo;
  15838. var root = function root(opts) {
  15839. return new _root["default"](opts);
  15840. };
  15841. constructors.root = root;
  15842. var selector = function selector(opts) {
  15843. return new _selector["default"](opts);
  15844. };
  15845. constructors.selector = selector;
  15846. var string = function string(opts) {
  15847. return new _string["default"](opts);
  15848. };
  15849. constructors.string = string;
  15850. var tag = function tag(opts) {
  15851. return new _tag["default"](opts);
  15852. };
  15853. constructors.tag = tag;
  15854. var universal = function universal(opts) {
  15855. return new _universal["default"](opts);
  15856. };
  15857. constructors.universal = universal;
  15858. return constructors;
  15859. }
  15860. var guards = {};
  15861. var hasRequiredGuards;
  15862. function requireGuards () {
  15863. if (hasRequiredGuards) return guards;
  15864. hasRequiredGuards = 1;
  15865. guards.__esModule = true;
  15866. guards.isComment = guards.isCombinator = guards.isClassName = guards.isAttribute = void 0;
  15867. guards.isContainer = isContainer;
  15868. guards.isIdentifier = void 0;
  15869. guards.isNamespace = isNamespace;
  15870. guards.isNesting = void 0;
  15871. guards.isNode = isNode;
  15872. guards.isPseudo = void 0;
  15873. guards.isPseudoClass = isPseudoClass;
  15874. guards.isPseudoElement = isPseudoElement;
  15875. guards.isUniversal = guards.isTag = guards.isString = guards.isSelector = guards.isRoot = void 0;
  15876. var _types = /*@__PURE__*/ requireTypes();
  15877. var _IS_TYPE;
  15878. 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);
  15879. function isNode(node) {
  15880. return typeof node === "object" && IS_TYPE[node.type];
  15881. }
  15882. function isNodeType(type, node) {
  15883. return isNode(node) && node.type === type;
  15884. }
  15885. var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
  15886. guards.isAttribute = isAttribute;
  15887. var isClassName = isNodeType.bind(null, _types.CLASS);
  15888. guards.isClassName = isClassName;
  15889. var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
  15890. guards.isCombinator = isCombinator;
  15891. var isComment = isNodeType.bind(null, _types.COMMENT);
  15892. guards.isComment = isComment;
  15893. var isIdentifier = isNodeType.bind(null, _types.ID);
  15894. guards.isIdentifier = isIdentifier;
  15895. var isNesting = isNodeType.bind(null, _types.NESTING);
  15896. guards.isNesting = isNesting;
  15897. var isPseudo = isNodeType.bind(null, _types.PSEUDO);
  15898. guards.isPseudo = isPseudo;
  15899. var isRoot = isNodeType.bind(null, _types.ROOT);
  15900. guards.isRoot = isRoot;
  15901. var isSelector = isNodeType.bind(null, _types.SELECTOR);
  15902. guards.isSelector = isSelector;
  15903. var isString = isNodeType.bind(null, _types.STRING);
  15904. guards.isString = isString;
  15905. var isTag = isNodeType.bind(null, _types.TAG);
  15906. guards.isTag = isTag;
  15907. var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
  15908. guards.isUniversal = isUniversal;
  15909. function isPseudoElement(node) {
  15910. 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");
  15911. }
  15912. function isPseudoClass(node) {
  15913. return isPseudo(node) && !isPseudoElement(node);
  15914. }
  15915. function isContainer(node) {
  15916. return !!(isNode(node) && node.walk);
  15917. }
  15918. function isNamespace(node) {
  15919. return isAttribute(node) || isTag(node);
  15920. }
  15921. return guards;
  15922. }
  15923. var hasRequiredSelectors;
  15924. function requireSelectors () {
  15925. if (hasRequiredSelectors) return selectors;
  15926. hasRequiredSelectors = 1;
  15927. (function (exports) {
  15928. exports.__esModule = true;
  15929. var _types = /*@__PURE__*/ requireTypes();
  15930. Object.keys(_types).forEach(function (key) {
  15931. if (key === "default" || key === "__esModule") return;
  15932. if (key in exports && exports[key] === _types[key]) return;
  15933. exports[key] = _types[key];
  15934. });
  15935. var _constructors = /*@__PURE__*/ requireConstructors();
  15936. Object.keys(_constructors).forEach(function (key) {
  15937. if (key === "default" || key === "__esModule") return;
  15938. if (key in exports && exports[key] === _constructors[key]) return;
  15939. exports[key] = _constructors[key];
  15940. });
  15941. var _guards = /*@__PURE__*/ requireGuards();
  15942. Object.keys(_guards).forEach(function (key) {
  15943. if (key === "default" || key === "__esModule") return;
  15944. if (key in exports && exports[key] === _guards[key]) return;
  15945. exports[key] = _guards[key];
  15946. });
  15947. } (selectors));
  15948. return selectors;
  15949. }
  15950. var hasRequiredDist;
  15951. function requireDist () {
  15952. if (hasRequiredDist) return dist.exports;
  15953. hasRequiredDist = 1;
  15954. (function (module, exports) {
  15955. exports.__esModule = true;
  15956. exports["default"] = void 0;
  15957. var _processor = _interopRequireDefault(/*@__PURE__*/ requireProcessor());
  15958. var selectors = _interopRequireWildcard(/*@__PURE__*/ requireSelectors());
  15959. 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); }
  15960. 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; }
  15961. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  15962. var parser = function parser(processor) {
  15963. return new _processor["default"](processor);
  15964. };
  15965. Object.assign(parser, selectors);
  15966. delete parser.__esModule;
  15967. var _default = parser;
  15968. exports["default"] = _default;
  15969. module.exports = exports.default;
  15970. } (dist, dist.exports));
  15971. return dist.exports;
  15972. }
  15973. var parse;
  15974. var hasRequiredParse;
  15975. function requireParse () {
  15976. if (hasRequiredParse) return parse;
  15977. hasRequiredParse = 1;
  15978. var openParentheses = "(".charCodeAt(0);
  15979. var closeParentheses = ")".charCodeAt(0);
  15980. var singleQuote = "'".charCodeAt(0);
  15981. var doubleQuote = '"'.charCodeAt(0);
  15982. var backslash = "\\".charCodeAt(0);
  15983. var slash = "/".charCodeAt(0);
  15984. var comma = ",".charCodeAt(0);
  15985. var colon = ":".charCodeAt(0);
  15986. var star = "*".charCodeAt(0);
  15987. var uLower = "u".charCodeAt(0);
  15988. var uUpper = "U".charCodeAt(0);
  15989. var plus = "+".charCodeAt(0);
  15990. var isUnicodeRange = /^[a-f0-9?-]+$/i;
  15991. parse = function(input) {
  15992. var tokens = [];
  15993. var value = input;
  15994. var next,
  15995. quote,
  15996. prev,
  15997. token,
  15998. escape,
  15999. escapePos,
  16000. whitespacePos,
  16001. parenthesesOpenPos;
  16002. var pos = 0;
  16003. var code = value.charCodeAt(pos);
  16004. var max = value.length;
  16005. var stack = [{ nodes: tokens }];
  16006. var balanced = 0;
  16007. var parent;
  16008. var name = "";
  16009. var before = "";
  16010. var after = "";
  16011. while (pos < max) {
  16012. // Whitespaces
  16013. if (code <= 32) {
  16014. next = pos;
  16015. do {
  16016. next += 1;
  16017. code = value.charCodeAt(next);
  16018. } while (code <= 32);
  16019. token = value.slice(pos, next);
  16020. prev = tokens[tokens.length - 1];
  16021. if (code === closeParentheses && balanced) {
  16022. after = token;
  16023. } else if (prev && prev.type === "div") {
  16024. prev.after = token;
  16025. prev.sourceEndIndex += token.length;
  16026. } else if (
  16027. code === comma ||
  16028. code === colon ||
  16029. (code === slash &&
  16030. value.charCodeAt(next + 1) !== star &&
  16031. (!parent ||
  16032. (parent && parent.type === "function" && parent.value !== "calc")))
  16033. ) {
  16034. before = token;
  16035. } else {
  16036. tokens.push({
  16037. type: "space",
  16038. sourceIndex: pos,
  16039. sourceEndIndex: next,
  16040. value: token
  16041. });
  16042. }
  16043. pos = next;
  16044. // Quotes
  16045. } else if (code === singleQuote || code === doubleQuote) {
  16046. next = pos;
  16047. quote = code === singleQuote ? "'" : '"';
  16048. token = {
  16049. type: "string",
  16050. sourceIndex: pos,
  16051. quote: quote
  16052. };
  16053. do {
  16054. escape = false;
  16055. next = value.indexOf(quote, next + 1);
  16056. if (~next) {
  16057. escapePos = next;
  16058. while (value.charCodeAt(escapePos - 1) === backslash) {
  16059. escapePos -= 1;
  16060. escape = !escape;
  16061. }
  16062. } else {
  16063. value += quote;
  16064. next = value.length - 1;
  16065. token.unclosed = true;
  16066. }
  16067. } while (escape);
  16068. token.value = value.slice(pos + 1, next);
  16069. token.sourceEndIndex = token.unclosed ? next : next + 1;
  16070. tokens.push(token);
  16071. pos = next + 1;
  16072. code = value.charCodeAt(pos);
  16073. // Comments
  16074. } else if (code === slash && value.charCodeAt(pos + 1) === star) {
  16075. next = value.indexOf("*/", pos);
  16076. token = {
  16077. type: "comment",
  16078. sourceIndex: pos,
  16079. sourceEndIndex: next + 2
  16080. };
  16081. if (next === -1) {
  16082. token.unclosed = true;
  16083. next = value.length;
  16084. token.sourceEndIndex = next;
  16085. }
  16086. token.value = value.slice(pos + 2, next);
  16087. tokens.push(token);
  16088. pos = next + 2;
  16089. code = value.charCodeAt(pos);
  16090. // Operation within calc
  16091. } else if (
  16092. (code === slash || code === star) &&
  16093. parent &&
  16094. parent.type === "function" &&
  16095. parent.value === "calc"
  16096. ) {
  16097. token = value[pos];
  16098. tokens.push({
  16099. type: "word",
  16100. sourceIndex: pos - before.length,
  16101. sourceEndIndex: pos + token.length,
  16102. value: token
  16103. });
  16104. pos += 1;
  16105. code = value.charCodeAt(pos);
  16106. // Dividers
  16107. } else if (code === slash || code === comma || code === colon) {
  16108. token = value[pos];
  16109. tokens.push({
  16110. type: "div",
  16111. sourceIndex: pos - before.length,
  16112. sourceEndIndex: pos + token.length,
  16113. value: token,
  16114. before: before,
  16115. after: ""
  16116. });
  16117. before = "";
  16118. pos += 1;
  16119. code = value.charCodeAt(pos);
  16120. // Open parentheses
  16121. } else if (openParentheses === code) {
  16122. // Whitespaces after open parentheses
  16123. next = pos;
  16124. do {
  16125. next += 1;
  16126. code = value.charCodeAt(next);
  16127. } while (code <= 32);
  16128. parenthesesOpenPos = pos;
  16129. token = {
  16130. type: "function",
  16131. sourceIndex: pos - name.length,
  16132. value: name,
  16133. before: value.slice(parenthesesOpenPos + 1, next)
  16134. };
  16135. pos = next;
  16136. if (name === "url" && code !== singleQuote && code !== doubleQuote) {
  16137. next -= 1;
  16138. do {
  16139. escape = false;
  16140. next = value.indexOf(")", next + 1);
  16141. if (~next) {
  16142. escapePos = next;
  16143. while (value.charCodeAt(escapePos - 1) === backslash) {
  16144. escapePos -= 1;
  16145. escape = !escape;
  16146. }
  16147. } else {
  16148. value += ")";
  16149. next = value.length - 1;
  16150. token.unclosed = true;
  16151. }
  16152. } while (escape);
  16153. // Whitespaces before closed
  16154. whitespacePos = next;
  16155. do {
  16156. whitespacePos -= 1;
  16157. code = value.charCodeAt(whitespacePos);
  16158. } while (code <= 32);
  16159. if (parenthesesOpenPos < whitespacePos) {
  16160. if (pos !== whitespacePos + 1) {
  16161. token.nodes = [
  16162. {
  16163. type: "word",
  16164. sourceIndex: pos,
  16165. sourceEndIndex: whitespacePos + 1,
  16166. value: value.slice(pos, whitespacePos + 1)
  16167. }
  16168. ];
  16169. } else {
  16170. token.nodes = [];
  16171. }
  16172. if (token.unclosed && whitespacePos + 1 !== next) {
  16173. token.after = "";
  16174. token.nodes.push({
  16175. type: "space",
  16176. sourceIndex: whitespacePos + 1,
  16177. sourceEndIndex: next,
  16178. value: value.slice(whitespacePos + 1, next)
  16179. });
  16180. } else {
  16181. token.after = value.slice(whitespacePos + 1, next);
  16182. token.sourceEndIndex = next;
  16183. }
  16184. } else {
  16185. token.after = "";
  16186. token.nodes = [];
  16187. }
  16188. pos = next + 1;
  16189. token.sourceEndIndex = token.unclosed ? next : pos;
  16190. code = value.charCodeAt(pos);
  16191. tokens.push(token);
  16192. } else {
  16193. balanced += 1;
  16194. token.after = "";
  16195. token.sourceEndIndex = pos + 1;
  16196. tokens.push(token);
  16197. stack.push(token);
  16198. tokens = token.nodes = [];
  16199. parent = token;
  16200. }
  16201. name = "";
  16202. // Close parentheses
  16203. } else if (closeParentheses === code && balanced) {
  16204. pos += 1;
  16205. code = value.charCodeAt(pos);
  16206. parent.after = after;
  16207. parent.sourceEndIndex += after.length;
  16208. after = "";
  16209. balanced -= 1;
  16210. stack[stack.length - 1].sourceEndIndex = pos;
  16211. stack.pop();
  16212. parent = stack[balanced];
  16213. tokens = parent.nodes;
  16214. // Words
  16215. } else {
  16216. next = pos;
  16217. do {
  16218. if (code === backslash) {
  16219. next += 1;
  16220. }
  16221. next += 1;
  16222. code = value.charCodeAt(next);
  16223. } while (
  16224. next < max &&
  16225. !(
  16226. code <= 32 ||
  16227. code === singleQuote ||
  16228. code === doubleQuote ||
  16229. code === comma ||
  16230. code === colon ||
  16231. code === slash ||
  16232. code === openParentheses ||
  16233. (code === star &&
  16234. parent &&
  16235. parent.type === "function" &&
  16236. parent.value === "calc") ||
  16237. (code === slash &&
  16238. parent.type === "function" &&
  16239. parent.value === "calc") ||
  16240. (code === closeParentheses && balanced)
  16241. )
  16242. );
  16243. token = value.slice(pos, next);
  16244. if (openParentheses === code) {
  16245. name = token;
  16246. } else if (
  16247. (uLower === token.charCodeAt(0) || uUpper === token.charCodeAt(0)) &&
  16248. plus === token.charCodeAt(1) &&
  16249. isUnicodeRange.test(token.slice(2))
  16250. ) {
  16251. tokens.push({
  16252. type: "unicode-range",
  16253. sourceIndex: pos,
  16254. sourceEndIndex: next,
  16255. value: token
  16256. });
  16257. } else {
  16258. tokens.push({
  16259. type: "word",
  16260. sourceIndex: pos,
  16261. sourceEndIndex: next,
  16262. value: token
  16263. });
  16264. }
  16265. pos = next;
  16266. }
  16267. }
  16268. for (pos = stack.length - 1; pos; pos -= 1) {
  16269. stack[pos].unclosed = true;
  16270. stack[pos].sourceEndIndex = value.length;
  16271. }
  16272. return stack[0].nodes;
  16273. };
  16274. return parse;
  16275. }
  16276. var walk$1;
  16277. var hasRequiredWalk;
  16278. function requireWalk () {
  16279. if (hasRequiredWalk) return walk$1;
  16280. hasRequiredWalk = 1;
  16281. walk$1 = function walk(nodes, cb, bubble) {
  16282. var i, max, node, result;
  16283. for (i = 0, max = nodes.length; i < max; i += 1) {
  16284. node = nodes[i];
  16285. if (!bubble) {
  16286. result = cb(node, i, nodes);
  16287. }
  16288. if (
  16289. result !== false &&
  16290. node.type === "function" &&
  16291. Array.isArray(node.nodes)
  16292. ) {
  16293. walk(node.nodes, cb, bubble);
  16294. }
  16295. if (bubble) {
  16296. cb(node, i, nodes);
  16297. }
  16298. }
  16299. };
  16300. return walk$1;
  16301. }
  16302. var stringify_1;
  16303. var hasRequiredStringify;
  16304. function requireStringify () {
  16305. if (hasRequiredStringify) return stringify_1;
  16306. hasRequiredStringify = 1;
  16307. function stringifyNode(node, custom) {
  16308. var type = node.type;
  16309. var value = node.value;
  16310. var buf;
  16311. var customResult;
  16312. if (custom && (customResult = custom(node)) !== undefined) {
  16313. return customResult;
  16314. } else if (type === "word" || type === "space") {
  16315. return value;
  16316. } else if (type === "string") {
  16317. buf = node.quote || "";
  16318. return buf + value + (node.unclosed ? "" : buf);
  16319. } else if (type === "comment") {
  16320. return "/*" + value + (node.unclosed ? "" : "*/");
  16321. } else if (type === "div") {
  16322. return (node.before || "") + value + (node.after || "");
  16323. } else if (Array.isArray(node.nodes)) {
  16324. buf = stringify(node.nodes, custom);
  16325. if (type !== "function") {
  16326. return buf;
  16327. }
  16328. return (
  16329. value +
  16330. "(" +
  16331. (node.before || "") +
  16332. buf +
  16333. (node.after || "") +
  16334. (node.unclosed ? "" : ")")
  16335. );
  16336. }
  16337. return value;
  16338. }
  16339. function stringify(nodes, custom) {
  16340. var result, i;
  16341. if (Array.isArray(nodes)) {
  16342. result = "";
  16343. for (i = nodes.length - 1; ~i; i -= 1) {
  16344. result = stringifyNode(nodes[i], custom) + result;
  16345. }
  16346. return result;
  16347. }
  16348. return stringifyNode(nodes, custom);
  16349. }
  16350. stringify_1 = stringify;
  16351. return stringify_1;
  16352. }
  16353. var unit;
  16354. var hasRequiredUnit;
  16355. function requireUnit () {
  16356. if (hasRequiredUnit) return unit;
  16357. hasRequiredUnit = 1;
  16358. var minus = "-".charCodeAt(0);
  16359. var plus = "+".charCodeAt(0);
  16360. var dot = ".".charCodeAt(0);
  16361. var exp = "e".charCodeAt(0);
  16362. var EXP = "E".charCodeAt(0);
  16363. // Check if three code points would start a number
  16364. // https://www.w3.org/TR/css-syntax-3/#starts-with-a-number
  16365. function likeNumber(value) {
  16366. var code = value.charCodeAt(0);
  16367. var nextCode;
  16368. if (code === plus || code === minus) {
  16369. nextCode = value.charCodeAt(1);
  16370. if (nextCode >= 48 && nextCode <= 57) {
  16371. return true;
  16372. }
  16373. var nextNextCode = value.charCodeAt(2);
  16374. if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) {
  16375. return true;
  16376. }
  16377. return false;
  16378. }
  16379. if (code === dot) {
  16380. nextCode = value.charCodeAt(1);
  16381. if (nextCode >= 48 && nextCode <= 57) {
  16382. return true;
  16383. }
  16384. return false;
  16385. }
  16386. if (code >= 48 && code <= 57) {
  16387. return true;
  16388. }
  16389. return false;
  16390. }
  16391. // Consume a number
  16392. // https://www.w3.org/TR/css-syntax-3/#consume-number
  16393. unit = function(value) {
  16394. var pos = 0;
  16395. var length = value.length;
  16396. var code;
  16397. var nextCode;
  16398. var nextNextCode;
  16399. if (length === 0 || !likeNumber(value)) {
  16400. return false;
  16401. }
  16402. code = value.charCodeAt(pos);
  16403. if (code === plus || code === minus) {
  16404. pos++;
  16405. }
  16406. while (pos < length) {
  16407. code = value.charCodeAt(pos);
  16408. if (code < 48 || code > 57) {
  16409. break;
  16410. }
  16411. pos += 1;
  16412. }
  16413. code = value.charCodeAt(pos);
  16414. nextCode = value.charCodeAt(pos + 1);
  16415. if (code === dot && nextCode >= 48 && nextCode <= 57) {
  16416. pos += 2;
  16417. while (pos < length) {
  16418. code = value.charCodeAt(pos);
  16419. if (code < 48 || code > 57) {
  16420. break;
  16421. }
  16422. pos += 1;
  16423. }
  16424. }
  16425. code = value.charCodeAt(pos);
  16426. nextCode = value.charCodeAt(pos + 1);
  16427. nextNextCode = value.charCodeAt(pos + 2);
  16428. if (
  16429. (code === exp || code === EXP) &&
  16430. ((nextCode >= 48 && nextCode <= 57) ||
  16431. ((nextCode === plus || nextCode === minus) &&
  16432. nextNextCode >= 48 &&
  16433. nextNextCode <= 57))
  16434. ) {
  16435. pos += nextCode === plus || nextCode === minus ? 3 : 2;
  16436. while (pos < length) {
  16437. code = value.charCodeAt(pos);
  16438. if (code < 48 || code > 57) {
  16439. break;
  16440. }
  16441. pos += 1;
  16442. }
  16443. }
  16444. return {
  16445. number: value.slice(0, pos),
  16446. unit: value.slice(pos)
  16447. };
  16448. };
  16449. return unit;
  16450. }
  16451. var lib;
  16452. var hasRequiredLib;
  16453. function requireLib () {
  16454. if (hasRequiredLib) return lib;
  16455. hasRequiredLib = 1;
  16456. var parse = /*@__PURE__*/ requireParse();
  16457. var walk = /*@__PURE__*/ requireWalk();
  16458. var stringify = /*@__PURE__*/ requireStringify();
  16459. function ValueParser(value) {
  16460. if (this instanceof ValueParser) {
  16461. this.nodes = parse(value);
  16462. return this;
  16463. }
  16464. return new ValueParser(value);
  16465. }
  16466. ValueParser.prototype.toString = function() {
  16467. return Array.isArray(this.nodes) ? stringify(this.nodes) : "";
  16468. };
  16469. ValueParser.prototype.walk = function(cb, bubble) {
  16470. walk(this.nodes, cb, bubble);
  16471. return this;
  16472. };
  16473. ValueParser.unit = /*@__PURE__*/ requireUnit();
  16474. ValueParser.walk = walk;
  16475. ValueParser.stringify = stringify;
  16476. lib = ValueParser;
  16477. return lib;
  16478. }
  16479. var hasRequiredSrc$2;
  16480. function requireSrc$2 () {
  16481. if (hasRequiredSrc$2) return src$2.exports;
  16482. hasRequiredSrc$2 = 1;
  16483. const selectorParser = /*@__PURE__*/ requireDist();
  16484. const valueParser = /*@__PURE__*/ requireLib();
  16485. const { extractICSS } = /*@__PURE__*/ requireSrc$4();
  16486. const isSpacing = (node) => node.type === "combinator" && node.value === " ";
  16487. function normalizeNodeArray(nodes) {
  16488. const array = [];
  16489. nodes.forEach((x) => {
  16490. if (Array.isArray(x)) {
  16491. normalizeNodeArray(x).forEach((item) => {
  16492. array.push(item);
  16493. });
  16494. } else if (x) {
  16495. array.push(x);
  16496. }
  16497. });
  16498. if (array.length > 0 && isSpacing(array[array.length - 1])) {
  16499. array.pop();
  16500. }
  16501. return array;
  16502. }
  16503. function localizeNode(rule, mode, localAliasMap) {
  16504. const transform = (node, context) => {
  16505. if (context.ignoreNextSpacing && !isSpacing(node)) {
  16506. throw new Error("Missing whitespace after " + context.ignoreNextSpacing);
  16507. }
  16508. if (context.enforceNoSpacing && isSpacing(node)) {
  16509. throw new Error("Missing whitespace before " + context.enforceNoSpacing);
  16510. }
  16511. let newNodes;
  16512. switch (node.type) {
  16513. case "root": {
  16514. let resultingGlobal;
  16515. context.hasPureGlobals = false;
  16516. newNodes = node.nodes.map((n) => {
  16517. const nContext = {
  16518. global: context.global,
  16519. lastWasSpacing: true,
  16520. hasLocals: false,
  16521. explicit: false,
  16522. };
  16523. n = transform(n, nContext);
  16524. if (typeof resultingGlobal === "undefined") {
  16525. resultingGlobal = nContext.global;
  16526. } else if (resultingGlobal !== nContext.global) {
  16527. throw new Error(
  16528. 'Inconsistent rule global/local result in rule "' +
  16529. node +
  16530. '" (multiple selectors must result in the same mode for the rule)'
  16531. );
  16532. }
  16533. if (!nContext.hasLocals) {
  16534. context.hasPureGlobals = true;
  16535. }
  16536. return n;
  16537. });
  16538. context.global = resultingGlobal;
  16539. node.nodes = normalizeNodeArray(newNodes);
  16540. break;
  16541. }
  16542. case "selector": {
  16543. newNodes = node.map((childNode) => transform(childNode, context));
  16544. node = node.clone();
  16545. node.nodes = normalizeNodeArray(newNodes);
  16546. break;
  16547. }
  16548. case "combinator": {
  16549. if (isSpacing(node)) {
  16550. if (context.ignoreNextSpacing) {
  16551. context.ignoreNextSpacing = false;
  16552. context.lastWasSpacing = false;
  16553. context.enforceNoSpacing = false;
  16554. return null;
  16555. }
  16556. context.lastWasSpacing = true;
  16557. return node;
  16558. }
  16559. break;
  16560. }
  16561. case "pseudo": {
  16562. let childContext;
  16563. const isNested = !!node.length;
  16564. const isScoped = node.value === ":local" || node.value === ":global";
  16565. const isImportExport =
  16566. node.value === ":import" || node.value === ":export";
  16567. if (isImportExport) {
  16568. context.hasLocals = true;
  16569. // :local(.foo)
  16570. } else if (isNested) {
  16571. if (isScoped) {
  16572. if (node.nodes.length === 0) {
  16573. throw new Error(`${node.value}() can't be empty`);
  16574. }
  16575. if (context.inside) {
  16576. throw new Error(
  16577. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  16578. );
  16579. }
  16580. childContext = {
  16581. global: node.value === ":global",
  16582. inside: node.value,
  16583. hasLocals: false,
  16584. explicit: true,
  16585. };
  16586. newNodes = node
  16587. .map((childNode) => transform(childNode, childContext))
  16588. .reduce((acc, next) => acc.concat(next.nodes), []);
  16589. if (newNodes.length) {
  16590. const { before, after } = node.spaces;
  16591. const first = newNodes[0];
  16592. const last = newNodes[newNodes.length - 1];
  16593. first.spaces = { before, after: first.spaces.after };
  16594. last.spaces = { before: last.spaces.before, after };
  16595. }
  16596. node = newNodes;
  16597. break;
  16598. } else {
  16599. childContext = {
  16600. global: context.global,
  16601. inside: context.inside,
  16602. lastWasSpacing: true,
  16603. hasLocals: false,
  16604. explicit: context.explicit,
  16605. };
  16606. newNodes = node.map((childNode) => {
  16607. const newContext = {
  16608. ...childContext,
  16609. enforceNoSpacing: false,
  16610. };
  16611. const result = transform(childNode, newContext);
  16612. childContext.global = newContext.global;
  16613. childContext.hasLocals = newContext.hasLocals;
  16614. return result;
  16615. });
  16616. node = node.clone();
  16617. node.nodes = normalizeNodeArray(newNodes);
  16618. if (childContext.hasLocals) {
  16619. context.hasLocals = true;
  16620. }
  16621. }
  16622. break;
  16623. //:local .foo .bar
  16624. } else if (isScoped) {
  16625. if (context.inside) {
  16626. throw new Error(
  16627. `A ${node.value} is not allowed inside of a ${context.inside}(...)`
  16628. );
  16629. }
  16630. const addBackSpacing = !!node.spaces.before;
  16631. context.ignoreNextSpacing = context.lastWasSpacing
  16632. ? node.value
  16633. : false;
  16634. context.enforceNoSpacing = context.lastWasSpacing
  16635. ? false
  16636. : node.value;
  16637. context.global = node.value === ":global";
  16638. context.explicit = true;
  16639. // because this node has spacing that is lost when we remove it
  16640. // we make up for it by adding an extra combinator in since adding
  16641. // spacing on the parent selector doesn't work
  16642. return addBackSpacing
  16643. ? selectorParser.combinator({ value: " " })
  16644. : null;
  16645. }
  16646. break;
  16647. }
  16648. case "id":
  16649. case "class": {
  16650. if (!node.value) {
  16651. throw new Error("Invalid class or id selector syntax");
  16652. }
  16653. if (context.global) {
  16654. break;
  16655. }
  16656. const isImportedValue = localAliasMap.has(node.value);
  16657. const isImportedWithExplicitScope = isImportedValue && context.explicit;
  16658. if (!isImportedValue || isImportedWithExplicitScope) {
  16659. const innerNode = node.clone();
  16660. innerNode.spaces = { before: "", after: "" };
  16661. node = selectorParser.pseudo({
  16662. value: ":local",
  16663. nodes: [innerNode],
  16664. spaces: node.spaces,
  16665. });
  16666. context.hasLocals = true;
  16667. }
  16668. break;
  16669. }
  16670. case "nesting": {
  16671. if (node.value === "&") {
  16672. context.hasLocals = true;
  16673. }
  16674. }
  16675. }
  16676. context.lastWasSpacing = false;
  16677. context.ignoreNextSpacing = false;
  16678. context.enforceNoSpacing = false;
  16679. return node;
  16680. };
  16681. const rootContext = {
  16682. global: mode === "global",
  16683. hasPureGlobals: false,
  16684. };
  16685. rootContext.selector = selectorParser((root) => {
  16686. transform(root, rootContext);
  16687. }).processSync(rule, { updateSelector: false, lossless: true });
  16688. return rootContext;
  16689. }
  16690. function localizeDeclNode(node, context) {
  16691. switch (node.type) {
  16692. case "word":
  16693. if (context.localizeNextItem) {
  16694. if (!context.localAliasMap.has(node.value)) {
  16695. node.value = ":local(" + node.value + ")";
  16696. context.localizeNextItem = false;
  16697. }
  16698. }
  16699. break;
  16700. case "function":
  16701. if (
  16702. context.options &&
  16703. context.options.rewriteUrl &&
  16704. node.value.toLowerCase() === "url"
  16705. ) {
  16706. node.nodes.map((nestedNode) => {
  16707. if (nestedNode.type !== "string" && nestedNode.type !== "word") {
  16708. return;
  16709. }
  16710. let newUrl = context.options.rewriteUrl(
  16711. context.global,
  16712. nestedNode.value
  16713. );
  16714. switch (nestedNode.type) {
  16715. case "string":
  16716. if (nestedNode.quote === "'") {
  16717. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/'/g, "\\'");
  16718. }
  16719. if (nestedNode.quote === '"') {
  16720. newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/"/g, '\\"');
  16721. }
  16722. break;
  16723. case "word":
  16724. newUrl = newUrl.replace(/("|'|\)|\\)/g, "\\$1");
  16725. break;
  16726. }
  16727. nestedNode.value = newUrl;
  16728. });
  16729. }
  16730. break;
  16731. }
  16732. return node;
  16733. }
  16734. // `none` is special value, other is global values
  16735. const specialKeywords = [
  16736. "none",
  16737. "inherit",
  16738. "initial",
  16739. "revert",
  16740. "revert-layer",
  16741. "unset",
  16742. ];
  16743. function localizeDeclarationValues(localize, declaration, context) {
  16744. const valueNodes = valueParser(declaration.value);
  16745. valueNodes.walk((node, index, nodes) => {
  16746. if (
  16747. node.type === "function" &&
  16748. (node.value.toLowerCase() === "var" || node.value.toLowerCase() === "env")
  16749. ) {
  16750. return false;
  16751. }
  16752. if (
  16753. node.type === "word" &&
  16754. specialKeywords.includes(node.value.toLowerCase())
  16755. ) {
  16756. return;
  16757. }
  16758. const subContext = {
  16759. options: context.options,
  16760. global: context.global,
  16761. localizeNextItem: localize && !context.global,
  16762. localAliasMap: context.localAliasMap,
  16763. };
  16764. nodes[index] = localizeDeclNode(node, subContext);
  16765. });
  16766. declaration.value = valueNodes.toString();
  16767. }
  16768. function localizeDeclaration(declaration, context) {
  16769. const isAnimation = /animation$/i.test(declaration.prop);
  16770. if (isAnimation) {
  16771. // letter
  16772. // An uppercase letter or a lowercase letter.
  16773. //
  16774. // ident-start code point
  16775. // A letter, a non-ASCII code point, or U+005F LOW LINE (_).
  16776. //
  16777. // ident code point
  16778. // An ident-start code point, a digit, or U+002D HYPHEN-MINUS (-).
  16779. // We don't validate `hex digits`, because we don't need it, it is work of linters.
  16780. const validIdent =
  16781. /^-?([a-z\u0080-\uFFFF_]|(\\[^\r\n\f])|-(?![0-9]))((\\[^\r\n\f])|[a-z\u0080-\uFFFF_0-9-])*$/i;
  16782. /*
  16783. The spec defines some keywords that you can use to describe properties such as the timing
  16784. function. These are still valid animation names, so as long as there is a property that accepts
  16785. a keyword, it is given priority. Only when all the properties that can take a keyword are
  16786. exhausted can the animation name be set to the keyword. I.e.
  16787. animation: infinite infinite;
  16788. The animation will repeat an infinite number of times from the first argument, and will have an
  16789. animation name of infinite from the second.
  16790. */
  16791. const animationKeywords = {
  16792. // animation-direction
  16793. $normal: 1,
  16794. $reverse: 1,
  16795. $alternate: 1,
  16796. "$alternate-reverse": 1,
  16797. // animation-fill-mode
  16798. $forwards: 1,
  16799. $backwards: 1,
  16800. $both: 1,
  16801. // animation-iteration-count
  16802. $infinite: 1,
  16803. // animation-play-state
  16804. $paused: 1,
  16805. $running: 1,
  16806. // animation-timing-function
  16807. $ease: 1,
  16808. "$ease-in": 1,
  16809. "$ease-out": 1,
  16810. "$ease-in-out": 1,
  16811. $linear: 1,
  16812. "$step-end": 1,
  16813. "$step-start": 1,
  16814. // Special
  16815. $none: Infinity, // No matter how many times you write none, it will never be an animation name
  16816. // Global values
  16817. $initial: Infinity,
  16818. $inherit: Infinity,
  16819. $unset: Infinity,
  16820. $revert: Infinity,
  16821. "$revert-layer": Infinity,
  16822. };
  16823. let parsedAnimationKeywords = {};
  16824. const valueNodes = valueParser(declaration.value).walk((node) => {
  16825. // If div-token appeared (represents as comma ','), a possibility of an animation-keywords should be reflesh.
  16826. if (node.type === "div") {
  16827. parsedAnimationKeywords = {};
  16828. return;
  16829. }
  16830. // Do not handle nested functions
  16831. else if (node.type === "function") {
  16832. return false;
  16833. }
  16834. // Ignore all except word
  16835. else if (node.type !== "word") {
  16836. return;
  16837. }
  16838. const value = node.type === "word" ? node.value.toLowerCase() : null;
  16839. let shouldParseAnimationName = false;
  16840. if (value && validIdent.test(value)) {
  16841. if ("$" + value in animationKeywords) {
  16842. parsedAnimationKeywords["$" + value] =
  16843. "$" + value in parsedAnimationKeywords
  16844. ? parsedAnimationKeywords["$" + value] + 1
  16845. : 0;
  16846. shouldParseAnimationName =
  16847. parsedAnimationKeywords["$" + value] >=
  16848. animationKeywords["$" + value];
  16849. } else {
  16850. shouldParseAnimationName = true;
  16851. }
  16852. }
  16853. const subContext = {
  16854. options: context.options,
  16855. global: context.global,
  16856. localizeNextItem: shouldParseAnimationName && !context.global,
  16857. localAliasMap: context.localAliasMap,
  16858. };
  16859. return localizeDeclNode(node, subContext);
  16860. });
  16861. declaration.value = valueNodes.toString();
  16862. return;
  16863. }
  16864. const isAnimationName = /animation(-name)?$/i.test(declaration.prop);
  16865. if (isAnimationName) {
  16866. return localizeDeclarationValues(true, declaration, context);
  16867. }
  16868. const hasUrl = /url\(/i.test(declaration.value);
  16869. if (hasUrl) {
  16870. return localizeDeclarationValues(false, declaration, context);
  16871. }
  16872. }
  16873. src$2.exports = (options = {}) => {
  16874. if (
  16875. options &&
  16876. options.mode &&
  16877. options.mode !== "global" &&
  16878. options.mode !== "local" &&
  16879. options.mode !== "pure"
  16880. ) {
  16881. throw new Error(
  16882. 'options.mode must be either "global", "local" or "pure" (default "local")'
  16883. );
  16884. }
  16885. const pureMode = options && options.mode === "pure";
  16886. const globalMode = options && options.mode === "global";
  16887. return {
  16888. postcssPlugin: "postcss-modules-local-by-default",
  16889. prepare() {
  16890. const localAliasMap = new Map();
  16891. return {
  16892. Once(root) {
  16893. const { icssImports } = extractICSS(root, false);
  16894. Object.keys(icssImports).forEach((key) => {
  16895. Object.keys(icssImports[key]).forEach((prop) => {
  16896. localAliasMap.set(prop, icssImports[key][prop]);
  16897. });
  16898. });
  16899. root.walkAtRules((atRule) => {
  16900. if (/keyframes$/i.test(atRule.name)) {
  16901. const globalMatch = /^\s*:global\s*\((.+)\)\s*$/.exec(
  16902. atRule.params
  16903. );
  16904. const localMatch = /^\s*:local\s*\((.+)\)\s*$/.exec(
  16905. atRule.params
  16906. );
  16907. let globalKeyframes = globalMode;
  16908. if (globalMatch) {
  16909. if (pureMode) {
  16910. throw atRule.error(
  16911. "@keyframes :global(...) is not allowed in pure mode"
  16912. );
  16913. }
  16914. atRule.params = globalMatch[1];
  16915. globalKeyframes = true;
  16916. } else if (localMatch) {
  16917. atRule.params = localMatch[0];
  16918. globalKeyframes = false;
  16919. } else if (
  16920. atRule.params &&
  16921. !globalMode &&
  16922. !localAliasMap.has(atRule.params)
  16923. ) {
  16924. atRule.params = ":local(" + atRule.params + ")";
  16925. }
  16926. atRule.walkDecls((declaration) => {
  16927. localizeDeclaration(declaration, {
  16928. localAliasMap,
  16929. options: options,
  16930. global: globalKeyframes,
  16931. });
  16932. });
  16933. } else if (/scope$/i.test(atRule.name)) {
  16934. if (atRule.params) {
  16935. atRule.params = atRule.params
  16936. .split("to")
  16937. .map((item) => {
  16938. const selector = item.trim().slice(1, -1).trim();
  16939. const context = localizeNode(
  16940. selector,
  16941. options.mode,
  16942. localAliasMap
  16943. );
  16944. context.options = options;
  16945. context.localAliasMap = localAliasMap;
  16946. if (pureMode && context.hasPureGlobals) {
  16947. throw atRule.error(
  16948. 'Selector in at-rule"' +
  16949. selector +
  16950. '" is not pure ' +
  16951. "(pure selectors must contain at least one local class or id)"
  16952. );
  16953. }
  16954. return `(${context.selector})`;
  16955. })
  16956. .join(" to ");
  16957. }
  16958. atRule.nodes.forEach((declaration) => {
  16959. if (declaration.type === "decl") {
  16960. localizeDeclaration(declaration, {
  16961. localAliasMap,
  16962. options: options,
  16963. global: globalMode,
  16964. });
  16965. }
  16966. });
  16967. } else if (atRule.nodes) {
  16968. atRule.nodes.forEach((declaration) => {
  16969. if (declaration.type === "decl") {
  16970. localizeDeclaration(declaration, {
  16971. localAliasMap,
  16972. options: options,
  16973. global: globalMode,
  16974. });
  16975. }
  16976. });
  16977. }
  16978. });
  16979. root.walkRules((rule) => {
  16980. if (
  16981. rule.parent &&
  16982. rule.parent.type === "atrule" &&
  16983. /keyframes$/i.test(rule.parent.name)
  16984. ) {
  16985. // ignore keyframe rules
  16986. return;
  16987. }
  16988. const context = localizeNode(rule, options.mode, localAliasMap);
  16989. context.options = options;
  16990. context.localAliasMap = localAliasMap;
  16991. if (pureMode && context.hasPureGlobals) {
  16992. throw rule.error(
  16993. 'Selector "' +
  16994. rule.selector +
  16995. '" is not pure ' +
  16996. "(pure selectors must contain at least one local class or id)"
  16997. );
  16998. }
  16999. rule.selector = context.selector;
  17000. // Less-syntax mixins parse as rules with no nodes
  17001. if (rule.nodes) {
  17002. rule.nodes.forEach((declaration) =>
  17003. localizeDeclaration(declaration, context)
  17004. );
  17005. }
  17006. });
  17007. },
  17008. };
  17009. },
  17010. };
  17011. };
  17012. src$2.exports.postcss = true;
  17013. return src$2.exports;
  17014. }
  17015. var src$1;
  17016. var hasRequiredSrc$1;
  17017. function requireSrc$1 () {
  17018. if (hasRequiredSrc$1) return src$1;
  17019. hasRequiredSrc$1 = 1;
  17020. const selectorParser = /*@__PURE__*/ requireDist();
  17021. const hasOwnProperty = Object.prototype.hasOwnProperty;
  17022. function isNestedRule(rule) {
  17023. if (!rule.parent || rule.parent.type === "root") {
  17024. return false;
  17025. }
  17026. if (rule.parent.type === "rule") {
  17027. return true;
  17028. }
  17029. return isNestedRule(rule.parent);
  17030. }
  17031. function getSingleLocalNamesForComposes(root, rule) {
  17032. if (isNestedRule(rule)) {
  17033. throw new Error(`composition is not allowed in nested rule \n\n${rule}`);
  17034. }
  17035. return root.nodes.map((node) => {
  17036. if (node.type !== "selector" || node.nodes.length !== 1) {
  17037. throw new Error(
  17038. `composition is only allowed when selector is single :local class name not in "${root}"`
  17039. );
  17040. }
  17041. node = node.nodes[0];
  17042. if (
  17043. node.type !== "pseudo" ||
  17044. node.value !== ":local" ||
  17045. node.nodes.length !== 1
  17046. ) {
  17047. throw new Error(
  17048. 'composition is only allowed when selector is single :local class name not in "' +
  17049. root +
  17050. '", "' +
  17051. node +
  17052. '" is weird'
  17053. );
  17054. }
  17055. node = node.first;
  17056. if (node.type !== "selector" || node.length !== 1) {
  17057. throw new Error(
  17058. 'composition is only allowed when selector is single :local class name not in "' +
  17059. root +
  17060. '", "' +
  17061. node +
  17062. '" is weird'
  17063. );
  17064. }
  17065. node = node.first;
  17066. if (node.type !== "class") {
  17067. // 'id' is not possible, because you can't compose ids
  17068. throw new Error(
  17069. 'composition is only allowed when selector is single :local class name not in "' +
  17070. root +
  17071. '", "' +
  17072. node +
  17073. '" is weird'
  17074. );
  17075. }
  17076. return node.value;
  17077. });
  17078. }
  17079. const whitespace = "[\\x20\\t\\r\\n\\f]";
  17080. const unescapeRegExp = new RegExp(
  17081. "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)",
  17082. "ig"
  17083. );
  17084. function unescape(str) {
  17085. return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => {
  17086. const high = "0x" + escaped - 0x10000;
  17087. // NaN means non-codepoint
  17088. // Workaround erroneous numeric interpretation of +"0x"
  17089. return high !== high || escapedWhitespace
  17090. ? escaped
  17091. : high < 0
  17092. ? // BMP codepoint
  17093. String.fromCharCode(high + 0x10000)
  17094. : // Supplemental Plane codepoint (surrogate pair)
  17095. String.fromCharCode((high >> 10) | 0xd800, (high & 0x3ff) | 0xdc00);
  17096. });
  17097. }
  17098. const plugin = (options = {}) => {
  17099. const generateScopedName =
  17100. (options && options.generateScopedName) || plugin.generateScopedName;
  17101. const generateExportEntry =
  17102. (options && options.generateExportEntry) || plugin.generateExportEntry;
  17103. const exportGlobals = options && options.exportGlobals;
  17104. return {
  17105. postcssPlugin: "postcss-modules-scope",
  17106. Once(root, { rule }) {
  17107. const exports = Object.create(null);
  17108. function exportScopedName(name, rawName, node) {
  17109. const scopedName = generateScopedName(
  17110. rawName ? rawName : name,
  17111. root.source.input.from,
  17112. root.source.input.css,
  17113. node
  17114. );
  17115. const exportEntry = generateExportEntry(
  17116. rawName ? rawName : name,
  17117. scopedName,
  17118. root.source.input.from,
  17119. root.source.input.css,
  17120. node
  17121. );
  17122. const { key, value } = exportEntry;
  17123. exports[key] = exports[key] || [];
  17124. if (exports[key].indexOf(value) < 0) {
  17125. exports[key].push(value);
  17126. }
  17127. return scopedName;
  17128. }
  17129. function localizeNode(node) {
  17130. switch (node.type) {
  17131. case "selector":
  17132. node.nodes = node.map((item) => localizeNode(item));
  17133. return node;
  17134. case "class":
  17135. return selectorParser.className({
  17136. value: exportScopedName(
  17137. node.value,
  17138. node.raws && node.raws.value ? node.raws.value : null,
  17139. node
  17140. ),
  17141. });
  17142. case "id": {
  17143. return selectorParser.id({
  17144. value: exportScopedName(
  17145. node.value,
  17146. node.raws && node.raws.value ? node.raws.value : null,
  17147. node
  17148. ),
  17149. });
  17150. }
  17151. case "attribute": {
  17152. if (node.attribute === "class" && node.operator === "=") {
  17153. return selectorParser.attribute({
  17154. attribute: node.attribute,
  17155. operator: node.operator,
  17156. quoteMark: "'",
  17157. value: exportScopedName(node.value, null, null),
  17158. });
  17159. }
  17160. }
  17161. }
  17162. throw new Error(
  17163. `${node.type} ("${node}") is not allowed in a :local block`
  17164. );
  17165. }
  17166. function traverseNode(node) {
  17167. switch (node.type) {
  17168. case "pseudo":
  17169. if (node.value === ":local") {
  17170. if (node.nodes.length !== 1) {
  17171. throw new Error('Unexpected comma (",") in :local block');
  17172. }
  17173. const selector = localizeNode(node.first);
  17174. // move the spaces that were around the pseudo selector to the first
  17175. // non-container node
  17176. selector.first.spaces = node.spaces;
  17177. const nextNode = node.next();
  17178. if (
  17179. nextNode &&
  17180. nextNode.type === "combinator" &&
  17181. nextNode.value === " " &&
  17182. /\\[A-F0-9]{1,6}$/.test(selector.last.value)
  17183. ) {
  17184. selector.last.spaces.after = " ";
  17185. }
  17186. node.replaceWith(selector);
  17187. return;
  17188. }
  17189. /* falls through */
  17190. case "root":
  17191. case "selector": {
  17192. node.each((item) => traverseNode(item));
  17193. break;
  17194. }
  17195. case "id":
  17196. case "class":
  17197. if (exportGlobals) {
  17198. exports[node.value] = [node.value];
  17199. }
  17200. break;
  17201. }
  17202. return node;
  17203. }
  17204. // Find any :import and remember imported names
  17205. const importedNames = {};
  17206. root.walkRules(/^:import\(.+\)$/, (rule) => {
  17207. rule.walkDecls((decl) => {
  17208. importedNames[decl.prop] = true;
  17209. });
  17210. });
  17211. // Find any :local selectors
  17212. root.walkRules((rule) => {
  17213. let parsedSelector = selectorParser().astSync(rule);
  17214. rule.selector = traverseNode(parsedSelector.clone()).toString();
  17215. rule.walkDecls(/^(composes|compose-with)$/i, (decl) => {
  17216. const localNames = getSingleLocalNamesForComposes(
  17217. parsedSelector,
  17218. decl.parent
  17219. );
  17220. const multiple = decl.value.split(",");
  17221. multiple.forEach((value) => {
  17222. const classes = value.trim().split(/\s+/);
  17223. classes.forEach((className) => {
  17224. const global = /^global\(([^)]+)\)$/.exec(className);
  17225. if (global) {
  17226. localNames.forEach((exportedName) => {
  17227. exports[exportedName].push(global[1]);
  17228. });
  17229. } else if (hasOwnProperty.call(importedNames, className)) {
  17230. localNames.forEach((exportedName) => {
  17231. exports[exportedName].push(className);
  17232. });
  17233. } else if (hasOwnProperty.call(exports, className)) {
  17234. localNames.forEach((exportedName) => {
  17235. exports[className].forEach((item) => {
  17236. exports[exportedName].push(item);
  17237. });
  17238. });
  17239. } else {
  17240. throw decl.error(
  17241. `referenced class name "${className}" in ${decl.prop} not found`
  17242. );
  17243. }
  17244. });
  17245. });
  17246. decl.remove();
  17247. });
  17248. // Find any :local values
  17249. rule.walkDecls((decl) => {
  17250. if (!/:local\s*\((.+?)\)/.test(decl.value)) {
  17251. return;
  17252. }
  17253. let tokens = decl.value.split(/(,|'[^']*'|"[^"]*")/);
  17254. tokens = tokens.map((token, idx) => {
  17255. if (idx === 0 || tokens[idx - 1] === ",") {
  17256. let result = token;
  17257. const localMatch = /:local\s*\((.+?)\)/.exec(token);
  17258. if (localMatch) {
  17259. const input = localMatch.input;
  17260. const matchPattern = localMatch[0];
  17261. const matchVal = localMatch[1];
  17262. const newVal = exportScopedName(matchVal);
  17263. result = input.replace(matchPattern, newVal);
  17264. } else {
  17265. return token;
  17266. }
  17267. return result;
  17268. } else {
  17269. return token;
  17270. }
  17271. });
  17272. decl.value = tokens.join("");
  17273. });
  17274. });
  17275. // Find any :local keyframes
  17276. root.walkAtRules(/keyframes$/i, (atRule) => {
  17277. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(atRule.params);
  17278. if (!localMatch) {
  17279. return;
  17280. }
  17281. atRule.params = exportScopedName(localMatch[1]);
  17282. });
  17283. root.walkAtRules(/scope$/i, (atRule) => {
  17284. if (atRule.params) {
  17285. atRule.params = atRule.params
  17286. .split("to")
  17287. .map((item) => {
  17288. const selector = item.trim().slice(1, -1).trim();
  17289. const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(selector);
  17290. if (!localMatch) {
  17291. return `(${selector})`;
  17292. }
  17293. let parsedSelector = selectorParser().astSync(selector);
  17294. return `(${traverseNode(parsedSelector).toString()})`;
  17295. })
  17296. .join(" to ");
  17297. }
  17298. });
  17299. // If we found any :locals, insert an :export rule
  17300. const exportedNames = Object.keys(exports);
  17301. if (exportedNames.length > 0) {
  17302. const exportRule = rule({ selector: ":export" });
  17303. exportedNames.forEach((exportedName) =>
  17304. exportRule.append({
  17305. prop: exportedName,
  17306. value: exports[exportedName].join(" "),
  17307. raws: { before: "\n " },
  17308. })
  17309. );
  17310. root.append(exportRule);
  17311. }
  17312. },
  17313. };
  17314. };
  17315. plugin.postcss = true;
  17316. plugin.generateScopedName = function (name, path) {
  17317. const sanitisedPath = path
  17318. .replace(/\.[^./\\]+$/, "")
  17319. .replace(/[\W_]+/g, "_")
  17320. .replace(/^_|_$/g, "");
  17321. return `_${sanitisedPath}__${name}`.trim();
  17322. };
  17323. plugin.generateExportEntry = function (name, scopedName) {
  17324. return {
  17325. key: unescape(name),
  17326. value: unescape(scopedName),
  17327. };
  17328. };
  17329. src$1 = plugin;
  17330. return src$1;
  17331. }
  17332. var stringHash;
  17333. var hasRequiredStringHash;
  17334. function requireStringHash () {
  17335. if (hasRequiredStringHash) return stringHash;
  17336. hasRequiredStringHash = 1;
  17337. function hash(str) {
  17338. var hash = 5381,
  17339. i = str.length;
  17340. while(i) {
  17341. hash = (hash * 33) ^ str.charCodeAt(--i);
  17342. }
  17343. /* JavaScript does bitwise operations (like XOR, above) on 32-bit signed
  17344. * integers. Since we want the results to be always positive, convert the
  17345. * signed int to an unsigned by doing an unsigned bitshift. */
  17346. return hash >>> 0;
  17347. }
  17348. stringHash = hash;
  17349. return stringHash;
  17350. }
  17351. var src = {exports: {}};
  17352. var hasRequiredSrc;
  17353. function requireSrc () {
  17354. if (hasRequiredSrc) return src.exports;
  17355. hasRequiredSrc = 1;
  17356. const ICSSUtils = /*@__PURE__*/ requireSrc$4();
  17357. const matchImports = /^(.+?|\([\s\S]+?\))\s+from\s+("[^"]*"|'[^']*'|[\w-]+)$/;
  17358. const matchValueDefinition = /(?:\s+|^)([\w-]+):?(.*?)$/;
  17359. const matchImport = /^([\w-]+)(?:\s+as\s+([\w-]+))?/;
  17360. src.exports = (options) => {
  17361. let importIndex = 0;
  17362. const createImportedName =
  17363. (options && options.createImportedName) ||
  17364. ((importName /*, path*/) =>
  17365. `i__const_${importName.replace(/\W/g, "_")}_${importIndex++}`);
  17366. return {
  17367. postcssPlugin: "postcss-modules-values",
  17368. prepare(result) {
  17369. const importAliases = [];
  17370. const definitions = {};
  17371. return {
  17372. Once(root, postcss) {
  17373. root.walkAtRules(/value/i, (atRule) => {
  17374. const matches = atRule.params.match(matchImports);
  17375. if (matches) {
  17376. let [, /*match*/ aliases, path] = matches;
  17377. // We can use constants for path names
  17378. if (definitions[path]) {
  17379. path = definitions[path];
  17380. }
  17381. const imports = aliases
  17382. .replace(/^\(\s*([\s\S]+)\s*\)$/, "$1")
  17383. .split(/\s*,\s*/)
  17384. .map((alias) => {
  17385. const tokens = matchImport.exec(alias);
  17386. if (tokens) {
  17387. const [, /*match*/ theirName, myName = theirName] = tokens;
  17388. const importedName = createImportedName(myName);
  17389. definitions[myName] = importedName;
  17390. return { theirName, importedName };
  17391. } else {
  17392. throw new Error(`@import statement "${alias}" is invalid!`);
  17393. }
  17394. });
  17395. importAliases.push({ path, imports });
  17396. atRule.remove();
  17397. return;
  17398. }
  17399. if (atRule.params.indexOf("@value") !== -1) {
  17400. result.warn("Invalid value definition: " + atRule.params);
  17401. }
  17402. let [, key, value] = `${atRule.params}${atRule.raws.between}`.match(
  17403. matchValueDefinition
  17404. );
  17405. const normalizedValue = value.replace(/\/\*((?!\*\/).*?)\*\//g, "");
  17406. if (normalizedValue.length === 0) {
  17407. result.warn("Invalid value definition: " + atRule.params);
  17408. atRule.remove();
  17409. return;
  17410. }
  17411. let isOnlySpace = /^\s+$/.test(normalizedValue);
  17412. if (!isOnlySpace) {
  17413. value = value.trim();
  17414. }
  17415. // Add to the definitions, knowing that values can refer to each other
  17416. definitions[key] = ICSSUtils.replaceValueSymbols(
  17417. value,
  17418. definitions
  17419. );
  17420. atRule.remove();
  17421. });
  17422. /* If we have no definitions, don't continue */
  17423. if (!Object.keys(definitions).length) {
  17424. return;
  17425. }
  17426. /* Perform replacements */
  17427. ICSSUtils.replaceSymbols(root, definitions);
  17428. /* 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 */
  17429. const exportDeclarations = Object.keys(definitions).map((key) =>
  17430. postcss.decl({
  17431. value: definitions[key],
  17432. prop: key,
  17433. raws: { before: "\n " },
  17434. })
  17435. );
  17436. /* Add export rules if any */
  17437. if (exportDeclarations.length > 0) {
  17438. const exportRule = postcss.rule({
  17439. selector: ":export",
  17440. raws: { after: "\n" },
  17441. });
  17442. exportRule.append(exportDeclarations);
  17443. root.prepend(exportRule);
  17444. }
  17445. /* Add import rules */
  17446. importAliases.reverse().forEach(({ path, imports }) => {
  17447. const importRule = postcss.rule({
  17448. selector: `:import(${path})`,
  17449. raws: { after: "\n" },
  17450. });
  17451. imports.forEach(({ theirName, importedName }) => {
  17452. importRule.append({
  17453. value: theirName,
  17454. prop: importedName,
  17455. raws: { before: "\n " },
  17456. });
  17457. });
  17458. root.prepend(importRule);
  17459. });
  17460. },
  17461. };
  17462. },
  17463. };
  17464. };
  17465. src.exports.postcss = true;
  17466. return src.exports;
  17467. }
  17468. var hasRequiredScoping;
  17469. function requireScoping () {
  17470. if (hasRequiredScoping) return scoping;
  17471. hasRequiredScoping = 1;
  17472. Object.defineProperty(scoping, "__esModule", {
  17473. value: true
  17474. });
  17475. scoping.behaviours = void 0;
  17476. scoping.getDefaultPlugins = getDefaultPlugins;
  17477. scoping.getDefaultScopeBehaviour = getDefaultScopeBehaviour;
  17478. scoping.getScopedNameGenerator = getScopedNameGenerator;
  17479. var _postcssModulesExtractImports = _interopRequireDefault(/*@__PURE__*/ requireSrc$3());
  17480. var _genericNames = _interopRequireDefault(/*@__PURE__*/ requireGenericNames());
  17481. var _postcssModulesLocalByDefault = _interopRequireDefault(/*@__PURE__*/ requireSrc$2());
  17482. var _postcssModulesScope = _interopRequireDefault(/*@__PURE__*/ requireSrc$1());
  17483. var _stringHash = _interopRequireDefault(/*@__PURE__*/ requireStringHash());
  17484. var _postcssModulesValues = _interopRequireDefault(/*@__PURE__*/ requireSrc());
  17485. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  17486. const behaviours = {
  17487. LOCAL: "local",
  17488. GLOBAL: "global"
  17489. };
  17490. scoping.behaviours = behaviours;
  17491. function getDefaultPlugins({
  17492. behaviour,
  17493. generateScopedName,
  17494. exportGlobals
  17495. }) {
  17496. const scope = (0, _postcssModulesScope.default)({
  17497. generateScopedName,
  17498. exportGlobals
  17499. });
  17500. const plugins = {
  17501. [behaviours.LOCAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  17502. mode: "local"
  17503. }), _postcssModulesExtractImports.default, scope],
  17504. [behaviours.GLOBAL]: [_postcssModulesValues.default, (0, _postcssModulesLocalByDefault.default)({
  17505. mode: "global"
  17506. }), _postcssModulesExtractImports.default, scope]
  17507. };
  17508. return plugins[behaviour];
  17509. }
  17510. function isValidBehaviour(behaviour) {
  17511. return Object.keys(behaviours).map(key => behaviours[key]).indexOf(behaviour) > -1;
  17512. }
  17513. function getDefaultScopeBehaviour(scopeBehaviour) {
  17514. return scopeBehaviour && isValidBehaviour(scopeBehaviour) ? scopeBehaviour : behaviours.LOCAL;
  17515. }
  17516. function generateScopedNameDefault(name, filename, css) {
  17517. const i = css.indexOf(`.${name}`);
  17518. const lineNumber = css.substr(0, i).split(/[\r\n]/).length;
  17519. const hash = (0, _stringHash.default)(css).toString(36).substr(0, 5);
  17520. return `_${name}_${hash}_${lineNumber}`;
  17521. }
  17522. function getScopedNameGenerator(generateScopedName, hashPrefix) {
  17523. const scopedNameGenerator = generateScopedName || generateScopedNameDefault;
  17524. if (typeof scopedNameGenerator === "function") {
  17525. return scopedNameGenerator;
  17526. }
  17527. return (0, _genericNames.default)(scopedNameGenerator, {
  17528. context: process.cwd(),
  17529. hashPrefix: hashPrefix
  17530. });
  17531. }
  17532. return scoping;
  17533. }
  17534. var hasRequiredPluginFactory;
  17535. function requirePluginFactory () {
  17536. if (hasRequiredPluginFactory) return pluginFactory;
  17537. hasRequiredPluginFactory = 1;
  17538. Object.defineProperty(pluginFactory, "__esModule", {
  17539. value: true
  17540. });
  17541. pluginFactory.makePlugin = makePlugin;
  17542. var _postcss = _interopRequireDefault(require$$0$1);
  17543. var _unquote = _interopRequireDefault(/*@__PURE__*/ requireUnquote());
  17544. var _Parser = _interopRequireDefault(/*@__PURE__*/ requireParser$1());
  17545. var _saveJSON = _interopRequireDefault(/*@__PURE__*/ requireSaveJSON());
  17546. var _localsConvention = /*@__PURE__*/ requireLocalsConvention();
  17547. var _FileSystemLoader = _interopRequireDefault(/*@__PURE__*/ requireFileSystemLoader());
  17548. var _scoping = /*@__PURE__*/ requireScoping();
  17549. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  17550. const PLUGIN_NAME = "postcss-modules";
  17551. function isGlobalModule(globalModules, inputFile) {
  17552. return globalModules.some(regex => inputFile.match(regex));
  17553. }
  17554. function getDefaultPluginsList(opts, inputFile) {
  17555. const globalModulesList = opts.globalModulePaths || null;
  17556. const exportGlobals = opts.exportGlobals || false;
  17557. const defaultBehaviour = (0, _scoping.getDefaultScopeBehaviour)(opts.scopeBehaviour);
  17558. const generateScopedName = (0, _scoping.getScopedNameGenerator)(opts.generateScopedName, opts.hashPrefix);
  17559. if (globalModulesList && isGlobalModule(globalModulesList, inputFile)) {
  17560. return (0, _scoping.getDefaultPlugins)({
  17561. behaviour: _scoping.behaviours.GLOBAL,
  17562. generateScopedName,
  17563. exportGlobals
  17564. });
  17565. }
  17566. return (0, _scoping.getDefaultPlugins)({
  17567. behaviour: defaultBehaviour,
  17568. generateScopedName,
  17569. exportGlobals
  17570. });
  17571. }
  17572. function getLoader(opts, plugins) {
  17573. const root = typeof opts.root === "undefined" ? "/" : opts.root;
  17574. return typeof opts.Loader === "function" ? new opts.Loader(root, plugins, opts.resolve) : new _FileSystemLoader.default(root, plugins, opts.resolve);
  17575. }
  17576. function isOurPlugin(plugin) {
  17577. return plugin.postcssPlugin === PLUGIN_NAME;
  17578. }
  17579. function makePlugin(opts) {
  17580. return {
  17581. postcssPlugin: PLUGIN_NAME,
  17582. async OnceExit(css, {
  17583. result
  17584. }) {
  17585. const getJSON = opts.getJSON || _saveJSON.default;
  17586. const inputFile = css.source.input.file;
  17587. const pluginList = getDefaultPluginsList(opts, inputFile);
  17588. const resultPluginIndex = result.processor.plugins.findIndex(plugin => isOurPlugin(plugin));
  17589. if (resultPluginIndex === -1) {
  17590. throw new Error("Plugin missing from options.");
  17591. }
  17592. const earlierPlugins = result.processor.plugins.slice(0, resultPluginIndex);
  17593. const loaderPlugins = [...earlierPlugins, ...pluginList];
  17594. const loader = getLoader(opts, loaderPlugins);
  17595. const fetcher = async (file, relativeTo, depTrace) => {
  17596. const unquoteFile = (0, _unquote.default)(file);
  17597. return loader.fetch.call(loader, unquoteFile, relativeTo, depTrace);
  17598. };
  17599. const parser = new _Parser.default(fetcher);
  17600. await (0, _postcss.default)([...pluginList, parser.plugin()]).process(css, {
  17601. from: inputFile
  17602. });
  17603. const out = loader.finalSource;
  17604. if (out) css.prepend(out);
  17605. if (opts.localsConvention) {
  17606. const reducer = (0, _localsConvention.makeLocalsConventionReducer)(opts.localsConvention, inputFile);
  17607. parser.exportTokens = Object.entries(parser.exportTokens).reduce(reducer, {});
  17608. }
  17609. result.messages.push({
  17610. type: "export",
  17611. plugin: "postcss-modules",
  17612. exportTokens: parser.exportTokens
  17613. }); // getJSON may return a promise
  17614. return getJSON(css.source.input.file, parser.exportTokens, result.opts.to);
  17615. }
  17616. };
  17617. }
  17618. return pluginFactory;
  17619. }
  17620. var hasRequiredBuild;
  17621. function requireBuild () {
  17622. if (hasRequiredBuild) return build.exports;
  17623. hasRequiredBuild = 1;
  17624. var _fs = require$$0;
  17625. var _fs2 = /*@__PURE__*/ requireFs();
  17626. var _pluginFactory = /*@__PURE__*/ requirePluginFactory();
  17627. (0, _fs2.setFileSystem)({
  17628. readFile: _fs.readFile,
  17629. writeFile: _fs.writeFile
  17630. });
  17631. build.exports = (opts = {}) => (0, _pluginFactory.makePlugin)(opts);
  17632. build.exports.postcss = true;
  17633. return build.exports;
  17634. }
  17635. var buildExports = /*@__PURE__*/ requireBuild();
  17636. var postcssModules = /*@__PURE__*/getDefaultExportFromCjs(buildExports);
  17637. function compileStyle(options) {
  17638. return doCompileStyle({
  17639. ...options,
  17640. isAsync: false
  17641. });
  17642. }
  17643. function compileStyleAsync(options) {
  17644. return doCompileStyle({
  17645. ...options,
  17646. isAsync: true
  17647. });
  17648. }
  17649. function doCompileStyle(options) {
  17650. const {
  17651. filename,
  17652. id,
  17653. scoped = false,
  17654. trim = true,
  17655. isProd = false,
  17656. modules = false,
  17657. modulesOptions = {},
  17658. preprocessLang,
  17659. postcssOptions,
  17660. postcssPlugins
  17661. } = options;
  17662. const preprocessor = preprocessLang && processors[preprocessLang];
  17663. const preProcessedSource = preprocessor && preprocess(options, preprocessor);
  17664. const map = preProcessedSource ? preProcessedSource.map : options.inMap || options.map;
  17665. const source = preProcessedSource ? preProcessedSource.code : options.source;
  17666. const shortId = id.replace(/^data-v-/, "");
  17667. const longId = `data-v-${shortId}`;
  17668. const plugins = (postcssPlugins || []).slice();
  17669. plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
  17670. if (trim) {
  17671. plugins.push(trimPlugin());
  17672. }
  17673. if (scoped) {
  17674. plugins.push(scopedPlugin(longId));
  17675. }
  17676. let cssModules;
  17677. if (modules) {
  17678. if (!options.isAsync) {
  17679. throw new Error(
  17680. "[@vue/compiler-sfc] `modules` option can only be used with compileStyleAsync()."
  17681. );
  17682. }
  17683. plugins.push(
  17684. postcssModules({
  17685. ...modulesOptions,
  17686. getJSON: (_cssFileName, json) => {
  17687. cssModules = json;
  17688. }
  17689. })
  17690. );
  17691. }
  17692. const postCSSOptions = {
  17693. ...postcssOptions,
  17694. to: filename,
  17695. from: filename
  17696. };
  17697. if (map) {
  17698. postCSSOptions.map = {
  17699. inline: false,
  17700. annotation: false,
  17701. prev: map
  17702. };
  17703. }
  17704. let result;
  17705. let code;
  17706. let outMap;
  17707. const dependencies = new Set(
  17708. preProcessedSource ? preProcessedSource.dependencies : []
  17709. );
  17710. dependencies.delete(filename);
  17711. const errors = [];
  17712. if (preProcessedSource && preProcessedSource.errors.length) {
  17713. errors.push(...preProcessedSource.errors);
  17714. }
  17715. const recordPlainCssDependencies = (messages) => {
  17716. messages.forEach((msg) => {
  17717. if (msg.type === "dependency") {
  17718. dependencies.add(msg.file);
  17719. }
  17720. });
  17721. return dependencies;
  17722. };
  17723. try {
  17724. result = require$$0$1(plugins).process(source, postCSSOptions);
  17725. if (options.isAsync) {
  17726. return result.then((result2) => ({
  17727. code: result2.css || "",
  17728. map: result2.map && result2.map.toJSON(),
  17729. errors,
  17730. modules: cssModules,
  17731. rawResult: result2,
  17732. dependencies: recordPlainCssDependencies(result2.messages)
  17733. })).catch((error) => ({
  17734. code: "",
  17735. map: void 0,
  17736. errors: [...errors, error],
  17737. rawResult: void 0,
  17738. dependencies
  17739. }));
  17740. }
  17741. recordPlainCssDependencies(result.messages);
  17742. code = result.css;
  17743. outMap = result.map;
  17744. } catch (e) {
  17745. errors.push(e);
  17746. }
  17747. return {
  17748. code: code || ``,
  17749. map: outMap && outMap.toJSON(),
  17750. errors,
  17751. rawResult: result,
  17752. dependencies
  17753. };
  17754. }
  17755. function preprocess(options, preprocessor) {
  17756. return preprocessor(
  17757. options.source,
  17758. options.inMap || options.map,
  17759. {
  17760. filename: options.filename,
  17761. ...options.preprocessOptions
  17762. },
  17763. options.preprocessCustomRequire
  17764. );
  17765. }
  17766. const UNKNOWN_TYPE = "Unknown";
  17767. function resolveObjectKey(node, computed) {
  17768. switch (node.type) {
  17769. case "StringLiteral":
  17770. case "NumericLiteral":
  17771. return String(node.value);
  17772. case "Identifier":
  17773. if (!computed) return node.name;
  17774. }
  17775. return void 0;
  17776. }
  17777. function concatStrings(strs) {
  17778. return strs.filter((s) => !!s).join(", ");
  17779. }
  17780. function isLiteralNode(node) {
  17781. return node.type.endsWith("Literal");
  17782. }
  17783. function isCallOf(node, test) {
  17784. return !!(node && test && node.type === "CallExpression" && node.callee.type === "Identifier" && (typeof test === "string" ? node.callee.name === test : test(node.callee.name)));
  17785. }
  17786. function toRuntimeTypeString(types) {
  17787. return types.length > 1 ? `[${types.join(", ")}]` : types[0];
  17788. }
  17789. function getImportedName(specifier) {
  17790. if (specifier.type === "ImportSpecifier")
  17791. return specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
  17792. else if (specifier.type === "ImportNamespaceSpecifier") return "*";
  17793. return "default";
  17794. }
  17795. function getId(node) {
  17796. return node.type === "Identifier" ? node.name : node.type === "StringLiteral" ? node.value : null;
  17797. }
  17798. const identity = (str) => str;
  17799. const fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
  17800. const toLowerCase = (str) => str.toLowerCase();
  17801. function toFileNameLowerCase(x) {
  17802. return fileNameLowerCaseRegExp.test(x) ? x.replace(fileNameLowerCaseRegExp, toLowerCase) : x;
  17803. }
  17804. function createGetCanonicalFileName(useCaseSensitiveFileNames) {
  17805. return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
  17806. }
  17807. const normalize = (path$1.posix || path$1).normalize;
  17808. const windowsSlashRE = /\\/g;
  17809. function normalizePath(p) {
  17810. return normalize(p.replace(windowsSlashRE, "/"));
  17811. }
  17812. const joinPaths = (path$1.posix || path$1).join;
  17813. const propNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~\-]/;
  17814. function getEscapedPropName(key) {
  17815. return propNameEscapeSymbolsRE.test(key) ? JSON.stringify(key) : key;
  17816. }
  17817. function analyzeScriptBindings(ast) {
  17818. for (const node of ast) {
  17819. if (node.type === "ExportDefaultDeclaration" && node.declaration.type === "ObjectExpression") {
  17820. return analyzeBindingsFromOptions(node.declaration);
  17821. }
  17822. }
  17823. return {};
  17824. }
  17825. function analyzeBindingsFromOptions(node) {
  17826. const bindings = {};
  17827. Object.defineProperty(bindings, "__isScriptSetup", {
  17828. enumerable: false,
  17829. value: false
  17830. });
  17831. for (const property of node.properties) {
  17832. if (property.type === "ObjectProperty" && !property.computed && property.key.type === "Identifier") {
  17833. if (property.key.name === "props") {
  17834. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  17835. bindings[key] = "props";
  17836. }
  17837. } else if (property.key.name === "inject") {
  17838. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  17839. bindings[key] = "options";
  17840. }
  17841. } else if (property.value.type === "ObjectExpression" && (property.key.name === "computed" || property.key.name === "methods")) {
  17842. for (const key of getObjectExpressionKeys(property.value)) {
  17843. bindings[key] = "options";
  17844. }
  17845. }
  17846. } else if (property.type === "ObjectMethod" && property.key.type === "Identifier" && (property.key.name === "setup" || property.key.name === "data")) {
  17847. for (const bodyItem of property.body.body) {
  17848. if (bodyItem.type === "ReturnStatement" && bodyItem.argument && bodyItem.argument.type === "ObjectExpression") {
  17849. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  17850. bindings[key] = property.key.name === "setup" ? "setup-maybe-ref" : "data";
  17851. }
  17852. }
  17853. }
  17854. }
  17855. }
  17856. return bindings;
  17857. }
  17858. function getObjectExpressionKeys(node) {
  17859. const keys = [];
  17860. for (const prop of node.properties) {
  17861. if (prop.type === "SpreadElement") continue;
  17862. const key = resolveObjectKey(prop.key, prop.computed);
  17863. if (key) keys.push(String(key));
  17864. }
  17865. return keys;
  17866. }
  17867. function getArrayExpressionKeys(node) {
  17868. const keys = [];
  17869. for (const element of node.elements) {
  17870. if (element && element.type === "StringLiteral") {
  17871. keys.push(element.value);
  17872. }
  17873. }
  17874. return keys;
  17875. }
  17876. function getObjectOrArrayExpressionKeys(value) {
  17877. if (value.type === "ArrayExpression") {
  17878. return getArrayExpressionKeys(value);
  17879. }
  17880. if (value.type === "ObjectExpression") {
  17881. return getObjectExpressionKeys(value);
  17882. }
  17883. return [];
  17884. }
  17885. var _a, _b;
  17886. class ScriptCompileContext {
  17887. constructor(descriptor, options) {
  17888. this.descriptor = descriptor;
  17889. this.options = options;
  17890. this.isCE = false;
  17891. this.source = this.descriptor.source;
  17892. this.filename = this.descriptor.filename;
  17893. this.s = new MagicString(this.source);
  17894. this.startOffset = (_a = this.descriptor.scriptSetup) == null ? void 0 : _a.loc.start.offset;
  17895. this.endOffset = (_b = this.descriptor.scriptSetup) == null ? void 0 : _b.loc.end.offset;
  17896. this.userImports = /* @__PURE__ */ Object.create(null);
  17897. // macros presence check
  17898. this.hasDefinePropsCall = false;
  17899. this.hasDefineEmitCall = false;
  17900. this.hasDefineExposeCall = false;
  17901. this.hasDefaultExportName = false;
  17902. this.hasDefaultExportRender = false;
  17903. this.hasDefineOptionsCall = false;
  17904. this.hasDefineSlotsCall = false;
  17905. this.hasDefineModelCall = false;
  17906. this.propsDestructuredBindings = /* @__PURE__ */ Object.create(null);
  17907. // defineModel
  17908. this.modelDecls = /* @__PURE__ */ Object.create(null);
  17909. // codegen
  17910. this.bindingMetadata = {};
  17911. this.helperImports = /* @__PURE__ */ new Set();
  17912. const { script, scriptSetup } = descriptor;
  17913. const scriptLang = script && script.lang;
  17914. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  17915. this.isJS = scriptLang === "js" || scriptLang === "jsx" || scriptSetupLang === "js" || scriptSetupLang === "jsx";
  17916. this.isTS = scriptLang === "ts" || scriptLang === "tsx" || scriptSetupLang === "ts" || scriptSetupLang === "tsx";
  17917. const customElement = options.customElement;
  17918. const filename = this.descriptor.filename;
  17919. if (customElement) {
  17920. this.isCE = typeof customElement === "boolean" ? customElement : customElement(filename);
  17921. }
  17922. const plugins = resolveParserPlugins(
  17923. scriptLang || scriptSetupLang,
  17924. options.babelParserPlugins
  17925. );
  17926. function parse(input, offset) {
  17927. try {
  17928. return parser$2.parse(input, {
  17929. plugins,
  17930. sourceType: "module"
  17931. }).program;
  17932. } catch (e) {
  17933. e.message = `[vue/compiler-sfc] ${e.message}
  17934. ${descriptor.filename}
  17935. ${shared.generateCodeFrame(
  17936. descriptor.source,
  17937. e.pos + offset,
  17938. e.pos + offset + 1
  17939. )}`;
  17940. throw e;
  17941. }
  17942. }
  17943. this.scriptAst = descriptor.script && parse(descriptor.script.content, descriptor.script.loc.start.offset);
  17944. this.scriptSetupAst = descriptor.scriptSetup && parse(descriptor.scriptSetup.content, this.startOffset);
  17945. }
  17946. helper(key) {
  17947. this.helperImports.add(key);
  17948. return `_${key}`;
  17949. }
  17950. getString(node, scriptSetup = true) {
  17951. const block = scriptSetup ? this.descriptor.scriptSetup : this.descriptor.script;
  17952. return block.content.slice(node.start, node.end);
  17953. }
  17954. warn(msg, node, scope) {
  17955. warn(generateError(msg, node, this, scope));
  17956. }
  17957. error(msg, node, scope) {
  17958. throw new Error(
  17959. `[@vue/compiler-sfc] ${generateError(msg, node, this, scope)}`
  17960. );
  17961. }
  17962. }
  17963. function generateError(msg, node, ctx, scope) {
  17964. const offset = scope ? scope.offset : ctx.startOffset;
  17965. return `${msg}
  17966. ${(scope || ctx.descriptor).filename}
  17967. ${shared.generateCodeFrame(
  17968. (scope || ctx.descriptor).source,
  17969. node.start + offset,
  17970. node.end + offset
  17971. )}`;
  17972. }
  17973. function resolveParserPlugins(lang, userPlugins, dts = false) {
  17974. const plugins = [];
  17975. if (!userPlugins || !userPlugins.some(
  17976. (p) => p === "importAssertions" || p === "importAttributes" || shared.isArray(p) && p[0] === "importAttributes"
  17977. )) {
  17978. plugins.push("importAttributes");
  17979. }
  17980. if (lang === "jsx" || lang === "tsx" || lang === "mtsx") {
  17981. plugins.push("jsx");
  17982. } else if (userPlugins) {
  17983. userPlugins = userPlugins.filter((p) => p !== "jsx");
  17984. }
  17985. if (lang === "ts" || lang === "mts" || lang === "tsx" || lang === "mtsx") {
  17986. plugins.push(["typescript", { dts }], "explicitResourceManagement");
  17987. if (!userPlugins || !userPlugins.includes("decorators")) {
  17988. plugins.push("decorators-legacy");
  17989. }
  17990. }
  17991. if (userPlugins) {
  17992. plugins.push(...userPlugins);
  17993. }
  17994. return plugins;
  17995. }
  17996. function rewriteDefault(input, as, parserPlugins) {
  17997. const ast = parser$2.parse(input, {
  17998. sourceType: "module",
  17999. plugins: resolveParserPlugins("js", parserPlugins)
  18000. }).program.body;
  18001. const s = new MagicString(input);
  18002. rewriteDefaultAST(ast, s, as);
  18003. return s.toString();
  18004. }
  18005. function rewriteDefaultAST(ast, s, as) {
  18006. if (!hasDefaultExport(ast)) {
  18007. s.append(`
  18008. const ${as} = {}`);
  18009. return;
  18010. }
  18011. ast.forEach((node) => {
  18012. if (node.type === "ExportDefaultDeclaration") {
  18013. if (node.declaration.type === "ClassDeclaration" && node.declaration.id) {
  18014. const start = node.declaration.decorators && node.declaration.decorators.length > 0 ? node.declaration.decorators[node.declaration.decorators.length - 1].end : node.start;
  18015. s.overwrite(start, node.declaration.id.start, ` class `);
  18016. s.append(`
  18017. const ${as} = ${node.declaration.id.name}`);
  18018. } else {
  18019. s.overwrite(node.start, node.declaration.start, `const ${as} = `);
  18020. }
  18021. } else if (node.type === "ExportNamedDeclaration") {
  18022. for (const specifier of node.specifiers) {
  18023. if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier" && specifier.exported.name === "default") {
  18024. if (node.source) {
  18025. if (specifier.local.name === "default") {
  18026. s.prepend(
  18027. `import { default as __VUE_DEFAULT__ } from '${node.source.value}'
  18028. `
  18029. );
  18030. const end2 = specifierEnd(s, specifier.local.end, node.end);
  18031. s.remove(specifier.start, end2);
  18032. s.append(`
  18033. const ${as} = __VUE_DEFAULT__`);
  18034. continue;
  18035. } else {
  18036. s.prepend(
  18037. `import { ${s.slice(
  18038. specifier.local.start,
  18039. specifier.local.end
  18040. )} as __VUE_DEFAULT__ } from '${node.source.value}'
  18041. `
  18042. );
  18043. const end2 = specifierEnd(s, specifier.exported.end, node.end);
  18044. s.remove(specifier.start, end2);
  18045. s.append(`
  18046. const ${as} = __VUE_DEFAULT__`);
  18047. continue;
  18048. }
  18049. }
  18050. const end = specifierEnd(s, specifier.end, node.end);
  18051. s.remove(specifier.start, end);
  18052. s.append(`
  18053. const ${as} = ${specifier.local.name}`);
  18054. }
  18055. }
  18056. }
  18057. });
  18058. }
  18059. function hasDefaultExport(ast) {
  18060. for (const stmt of ast) {
  18061. if (stmt.type === "ExportDefaultDeclaration") {
  18062. return true;
  18063. } else if (stmt.type === "ExportNamedDeclaration" && stmt.specifiers.some(
  18064. (spec) => spec.exported.name === "default"
  18065. )) {
  18066. return true;
  18067. }
  18068. }
  18069. return false;
  18070. }
  18071. function specifierEnd(s, end, nodeEnd) {
  18072. let hasCommas = false;
  18073. let oldEnd = end;
  18074. while (end < nodeEnd) {
  18075. if (/\s/.test(s.slice(end, end + 1))) {
  18076. end++;
  18077. } else if (s.slice(end, end + 1) === ",") {
  18078. end++;
  18079. hasCommas = true;
  18080. break;
  18081. } else if (s.slice(end, end + 1) === "}") {
  18082. break;
  18083. }
  18084. }
  18085. return hasCommas ? end : oldEnd;
  18086. }
  18087. const normalScriptDefaultVar = `__default__`;
  18088. function processNormalScript(ctx, scopeId) {
  18089. var _a;
  18090. const script = ctx.descriptor.script;
  18091. if (script.lang && !ctx.isJS && !ctx.isTS) {
  18092. return script;
  18093. }
  18094. try {
  18095. let content = script.content;
  18096. let map = script.map;
  18097. const scriptAst = ctx.scriptAst;
  18098. const bindings = analyzeScriptBindings(scriptAst.body);
  18099. const { cssVars } = ctx.descriptor;
  18100. const { genDefaultAs, isProd } = ctx.options;
  18101. if (cssVars.length || genDefaultAs) {
  18102. const defaultVar = genDefaultAs || normalScriptDefaultVar;
  18103. const s = new MagicString(content);
  18104. rewriteDefaultAST(scriptAst.body, s, defaultVar);
  18105. content = s.toString();
  18106. if (cssVars.length && !((_a = ctx.options.templateOptions) == null ? void 0 : _a.ssr)) {
  18107. content += genNormalScriptCssVarsCode(
  18108. cssVars,
  18109. bindings,
  18110. scopeId,
  18111. !!isProd,
  18112. defaultVar
  18113. );
  18114. }
  18115. if (!genDefaultAs) {
  18116. content += `
  18117. export default ${defaultVar}`;
  18118. }
  18119. }
  18120. return {
  18121. ...script,
  18122. content,
  18123. map,
  18124. bindings,
  18125. scriptAst: scriptAst.body
  18126. };
  18127. } catch (e) {
  18128. return script;
  18129. }
  18130. }
  18131. const balanced = (a, b, str) => {
  18132. const ma = a instanceof RegExp ? maybeMatch(a, str) : a;
  18133. const mb = b instanceof RegExp ? maybeMatch(b, str) : b;
  18134. const r = ma !== null && mb != null && range(ma, mb, str);
  18135. return (r && {
  18136. start: r[0],
  18137. end: r[1],
  18138. pre: str.slice(0, r[0]),
  18139. body: str.slice(r[0] + ma.length, r[1]),
  18140. post: str.slice(r[1] + mb.length),
  18141. });
  18142. };
  18143. const maybeMatch = (reg, str) => {
  18144. const m = str.match(reg);
  18145. return m ? m[0] : null;
  18146. };
  18147. const range = (a, b, str) => {
  18148. let begs, beg, left, right = undefined, result;
  18149. let ai = str.indexOf(a);
  18150. let bi = str.indexOf(b, ai + 1);
  18151. let i = ai;
  18152. if (ai >= 0 && bi > 0) {
  18153. if (a === b) {
  18154. return [ai, bi];
  18155. }
  18156. begs = [];
  18157. left = str.length;
  18158. while (i >= 0 && !result) {
  18159. if (i === ai) {
  18160. begs.push(i);
  18161. ai = str.indexOf(a, i + 1);
  18162. }
  18163. else if (begs.length === 1) {
  18164. const r = begs.pop();
  18165. if (r !== undefined)
  18166. result = [r, bi];
  18167. }
  18168. else {
  18169. beg = begs.pop();
  18170. if (beg !== undefined && beg < left) {
  18171. left = beg;
  18172. right = bi;
  18173. }
  18174. bi = str.indexOf(b, i + 1);
  18175. }
  18176. i = ai < bi && ai >= 0 ? ai : bi;
  18177. }
  18178. if (begs.length && right !== undefined) {
  18179. result = [left, right];
  18180. }
  18181. }
  18182. return result;
  18183. };
  18184. const escSlash = '\0SLASH' + Math.random() + '\0';
  18185. const escOpen = '\0OPEN' + Math.random() + '\0';
  18186. const escClose = '\0CLOSE' + Math.random() + '\0';
  18187. const escComma = '\0COMMA' + Math.random() + '\0';
  18188. const escPeriod = '\0PERIOD' + Math.random() + '\0';
  18189. const escSlashPattern = new RegExp(escSlash, 'g');
  18190. const escOpenPattern = new RegExp(escOpen, 'g');
  18191. const escClosePattern = new RegExp(escClose, 'g');
  18192. const escCommaPattern = new RegExp(escComma, 'g');
  18193. const escPeriodPattern = new RegExp(escPeriod, 'g');
  18194. const slashPattern = /\\\\/g;
  18195. const openPattern = /\\{/g;
  18196. const closePattern = /\\}/g;
  18197. const commaPattern = /\\,/g;
  18198. const periodPattern = /\\./g;
  18199. function numeric(str) {
  18200. return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0);
  18201. }
  18202. function escapeBraces(str) {
  18203. return str
  18204. .replace(slashPattern, escSlash)
  18205. .replace(openPattern, escOpen)
  18206. .replace(closePattern, escClose)
  18207. .replace(commaPattern, escComma)
  18208. .replace(periodPattern, escPeriod);
  18209. }
  18210. function unescapeBraces(str) {
  18211. return str
  18212. .replace(escSlashPattern, '\\')
  18213. .replace(escOpenPattern, '{')
  18214. .replace(escClosePattern, '}')
  18215. .replace(escCommaPattern, ',')
  18216. .replace(escPeriodPattern, '.');
  18217. }
  18218. /**
  18219. * Basically just str.split(","), but handling cases
  18220. * where we have nested braced sections, which should be
  18221. * treated as individual members, like {a,{b,c},d}
  18222. */
  18223. function parseCommaParts(str) {
  18224. if (!str) {
  18225. return [''];
  18226. }
  18227. const parts = [];
  18228. const m = balanced('{', '}', str);
  18229. if (!m) {
  18230. return str.split(',');
  18231. }
  18232. const { pre, body, post } = m;
  18233. const p = pre.split(',');
  18234. p[p.length - 1] += '{' + body + '}';
  18235. const postParts = parseCommaParts(post);
  18236. if (post.length) {
  18237. p[p.length - 1] += postParts.shift();
  18238. p.push.apply(p, postParts);
  18239. }
  18240. parts.push.apply(parts, p);
  18241. return parts;
  18242. }
  18243. function expand(str) {
  18244. if (!str) {
  18245. return [];
  18246. }
  18247. // I don't know why Bash 4.3 does this, but it does.
  18248. // Anything starting with {} will have the first two bytes preserved
  18249. // but *only* at the top level, so {},a}b will not expand to anything,
  18250. // but a{},b}c will be expanded to [a}c,abc].
  18251. // One could argue that this is a bug in Bash, but since the goal of
  18252. // this module is to match Bash's rules, we escape a leading {}
  18253. if (str.slice(0, 2) === '{}') {
  18254. str = '\\{\\}' + str.slice(2);
  18255. }
  18256. return expand_(escapeBraces(str), true).map(unescapeBraces);
  18257. }
  18258. function embrace(str) {
  18259. return '{' + str + '}';
  18260. }
  18261. function isPadded(el) {
  18262. return /^-?0\d/.test(el);
  18263. }
  18264. function lte(i, y) {
  18265. return i <= y;
  18266. }
  18267. function gte(i, y) {
  18268. return i >= y;
  18269. }
  18270. function expand_(str, isTop) {
  18271. /** @type {string[]} */
  18272. const expansions = [];
  18273. const m = balanced('{', '}', str);
  18274. if (!m)
  18275. return [str];
  18276. // no need to expand pre, since it is guaranteed to be free of brace-sets
  18277. const pre = m.pre;
  18278. const post = m.post.length ? expand_(m.post, false) : [''];
  18279. if (/\$$/.test(m.pre)) {
  18280. for (let k = 0; k < post.length; k++) {
  18281. const expansion = pre + '{' + m.body + '}' + post[k];
  18282. expansions.push(expansion);
  18283. }
  18284. }
  18285. else {
  18286. const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  18287. const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  18288. const isSequence = isNumericSequence || isAlphaSequence;
  18289. const isOptions = m.body.indexOf(',') >= 0;
  18290. if (!isSequence && !isOptions) {
  18291. // {a},b}
  18292. if (m.post.match(/,(?!,).*\}/)) {
  18293. str = m.pre + '{' + m.body + escClose + m.post;
  18294. return expand_(str);
  18295. }
  18296. return [str];
  18297. }
  18298. let n;
  18299. if (isSequence) {
  18300. n = m.body.split(/\.\./);
  18301. }
  18302. else {
  18303. n = parseCommaParts(m.body);
  18304. if (n.length === 1 && n[0] !== undefined) {
  18305. // x{{a,b}}y ==> x{a}y x{b}y
  18306. n = expand_(n[0], false).map(embrace);
  18307. //XXX is this necessary? Can't seem to hit it in tests.
  18308. /* c8 ignore start */
  18309. if (n.length === 1) {
  18310. return post.map(p => m.pre + n[0] + p);
  18311. }
  18312. /* c8 ignore stop */
  18313. }
  18314. }
  18315. // at this point, n is the parts, and we know it's not a comma set
  18316. // with a single entry.
  18317. let N;
  18318. if (isSequence && n[0] !== undefined && n[1] !== undefined) {
  18319. const x = numeric(n[0]);
  18320. const y = numeric(n[1]);
  18321. const width = Math.max(n[0].length, n[1].length);
  18322. let incr = n.length === 3 && n[2] !== undefined ? Math.abs(numeric(n[2])) : 1;
  18323. let test = lte;
  18324. const reverse = y < x;
  18325. if (reverse) {
  18326. incr *= -1;
  18327. test = gte;
  18328. }
  18329. const pad = n.some(isPadded);
  18330. N = [];
  18331. for (let i = x; test(i, y); i += incr) {
  18332. let c;
  18333. if (isAlphaSequence) {
  18334. c = String.fromCharCode(i);
  18335. if (c === '\\') {
  18336. c = '';
  18337. }
  18338. }
  18339. else {
  18340. c = String(i);
  18341. if (pad) {
  18342. const need = width - c.length;
  18343. if (need > 0) {
  18344. const z = new Array(need + 1).join('0');
  18345. if (i < 0) {
  18346. c = '-' + z + c.slice(1);
  18347. }
  18348. else {
  18349. c = z + c;
  18350. }
  18351. }
  18352. }
  18353. }
  18354. N.push(c);
  18355. }
  18356. }
  18357. else {
  18358. N = [];
  18359. for (let j = 0; j < n.length; j++) {
  18360. N.push.apply(N, expand_(n[j], false));
  18361. }
  18362. }
  18363. for (let j = 0; j < N.length; j++) {
  18364. for (let k = 0; k < post.length; k++) {
  18365. const expansion = pre + N[j] + post[k];
  18366. if (!isTop || isSequence || expansion) {
  18367. expansions.push(expansion);
  18368. }
  18369. }
  18370. }
  18371. }
  18372. return expansions;
  18373. }
  18374. const MAX_PATTERN_LENGTH = 1024 * 64;
  18375. const assertValidPattern = (pattern) => {
  18376. if (typeof pattern !== 'string') {
  18377. throw new TypeError('invalid pattern');
  18378. }
  18379. if (pattern.length > MAX_PATTERN_LENGTH) {
  18380. throw new TypeError('pattern is too long');
  18381. }
  18382. };
  18383. // translate the various posix character classes into unicode properties
  18384. // this works across all unicode locales
  18385. // { <posix class>: [<translation>, /u flag required, negated]
  18386. const posixClasses = {
  18387. '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
  18388. '[:alpha:]': ['\\p{L}\\p{Nl}', true],
  18389. '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
  18390. '[:blank:]': ['\\p{Zs}\\t', true],
  18391. '[:cntrl:]': ['\\p{Cc}', true],
  18392. '[:digit:]': ['\\p{Nd}', true],
  18393. '[:graph:]': ['\\p{Z}\\p{C}', true, true],
  18394. '[:lower:]': ['\\p{Ll}', true],
  18395. '[:print:]': ['\\p{C}', true],
  18396. '[:punct:]': ['\\p{P}', true],
  18397. '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
  18398. '[:upper:]': ['\\p{Lu}', true],
  18399. '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
  18400. '[:xdigit:]': ['A-Fa-f0-9', false],
  18401. };
  18402. // only need to escape a few things inside of brace expressions
  18403. // escapes: [ \ ] -
  18404. const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
  18405. // escape all regexp magic characters
  18406. const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  18407. // everything has already been escaped, we just have to join
  18408. const rangesToString = (ranges) => ranges.join('');
  18409. // takes a glob string at a posix brace expression, and returns
  18410. // an equivalent regular expression source, and boolean indicating
  18411. // whether the /u flag needs to be applied, and the number of chars
  18412. // consumed to parse the character class.
  18413. // This also removes out of order ranges, and returns ($.) if the
  18414. // entire class just no good.
  18415. const parseClass = (glob, position) => {
  18416. const pos = position;
  18417. /* c8 ignore start */
  18418. if (glob.charAt(pos) !== '[') {
  18419. throw new Error('not in a brace expression');
  18420. }
  18421. /* c8 ignore stop */
  18422. const ranges = [];
  18423. const negs = [];
  18424. let i = pos + 1;
  18425. let sawStart = false;
  18426. let uflag = false;
  18427. let escaping = false;
  18428. let negate = false;
  18429. let endPos = pos;
  18430. let rangeStart = '';
  18431. WHILE: while (i < glob.length) {
  18432. const c = glob.charAt(i);
  18433. if ((c === '!' || c === '^') && i === pos + 1) {
  18434. negate = true;
  18435. i++;
  18436. continue;
  18437. }
  18438. if (c === ']' && sawStart && !escaping) {
  18439. endPos = i + 1;
  18440. break;
  18441. }
  18442. sawStart = true;
  18443. if (c === '\\') {
  18444. if (!escaping) {
  18445. escaping = true;
  18446. i++;
  18447. continue;
  18448. }
  18449. // escaped \ char, fall through and treat like normal char
  18450. }
  18451. if (c === '[' && !escaping) {
  18452. // either a posix class, a collation equivalent, or just a [
  18453. for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
  18454. if (glob.startsWith(cls, i)) {
  18455. // invalid, [a-[] is fine, but not [a-[:alpha]]
  18456. if (rangeStart) {
  18457. return ['$.', false, glob.length - pos, true];
  18458. }
  18459. i += cls.length;
  18460. if (neg)
  18461. negs.push(unip);
  18462. else
  18463. ranges.push(unip);
  18464. uflag = uflag || u;
  18465. continue WHILE;
  18466. }
  18467. }
  18468. }
  18469. // now it's just a normal character, effectively
  18470. escaping = false;
  18471. if (rangeStart) {
  18472. // throw this range away if it's not valid, but others
  18473. // can still match.
  18474. if (c > rangeStart) {
  18475. ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
  18476. }
  18477. else if (c === rangeStart) {
  18478. ranges.push(braceEscape(c));
  18479. }
  18480. rangeStart = '';
  18481. i++;
  18482. continue;
  18483. }
  18484. // now might be the start of a range.
  18485. // can be either c-d or c-] or c<more...>] or c] at this point
  18486. if (glob.startsWith('-]', i + 1)) {
  18487. ranges.push(braceEscape(c + '-'));
  18488. i += 2;
  18489. continue;
  18490. }
  18491. if (glob.startsWith('-', i + 1)) {
  18492. rangeStart = c;
  18493. i += 2;
  18494. continue;
  18495. }
  18496. // not the start of a range, just a single character
  18497. ranges.push(braceEscape(c));
  18498. i++;
  18499. }
  18500. if (endPos < i) {
  18501. // didn't see the end of the class, not a valid class,
  18502. // but might still be valid as a literal match.
  18503. return ['', false, 0, false];
  18504. }
  18505. // if we got no ranges and no negates, then we have a range that
  18506. // cannot possibly match anything, and that poisons the whole glob
  18507. if (!ranges.length && !negs.length) {
  18508. return ['$.', false, glob.length - pos, true];
  18509. }
  18510. // if we got one positive range, and it's a single character, then that's
  18511. // not actually a magic pattern, it's just that one literal character.
  18512. // we should not treat that as "magic", we should just return the literal
  18513. // character. [_] is a perfectly valid way to escape glob magic chars.
  18514. if (negs.length === 0 &&
  18515. ranges.length === 1 &&
  18516. /^\\?.$/.test(ranges[0]) &&
  18517. !negate) {
  18518. const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
  18519. return [regexpEscape(r), false, endPos - pos, false];
  18520. }
  18521. const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
  18522. const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
  18523. const comb = ranges.length && negs.length
  18524. ? '(' + sranges + '|' + snegs + ')'
  18525. : ranges.length
  18526. ? sranges
  18527. : snegs;
  18528. return [comb, uflag, endPos - pos, true];
  18529. };
  18530. /**
  18531. * Un-escape a string that has been escaped with {@link escape}.
  18532. *
  18533. * If the {@link windowsPathsNoEscape} option is used, then square-brace
  18534. * escapes are removed, but not backslash escapes. For example, it will turn
  18535. * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
  18536. * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
  18537. *
  18538. * When `windowsPathsNoEscape` is not set, then both brace escapes and
  18539. * backslash escapes are removed.
  18540. *
  18541. * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
  18542. * or unescaped.
  18543. */
  18544. const unescape = (s, { windowsPathsNoEscape = false, } = {}) => {
  18545. return windowsPathsNoEscape
  18546. ? s.replace(/\[([^\/\\])\]/g, '$1')
  18547. : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
  18548. };
  18549. // parse a single path portion
  18550. const types = new Set(['!', '?', '+', '*', '@']);
  18551. const isExtglobType = (c) => types.has(c);
  18552. // Patterns that get prepended to bind to the start of either the
  18553. // entire string, or just a single path portion, to prevent dots
  18554. // and/or traversal patterns, when needed.
  18555. // Exts don't need the ^ or / bit, because the root binds that already.
  18556. const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
  18557. const startNoDot = '(?!\\.)';
  18558. // characters that indicate a start of pattern needs the "no dots" bit,
  18559. // because a dot *might* be matched. ( is not in the list, because in
  18560. // the case of a child extglob, it will handle the prevention itself.
  18561. const addPatternStart = new Set(['[', '.']);
  18562. // cases where traversal is A-OK, no dot prevention needed
  18563. const justDots = new Set(['..', '.']);
  18564. const reSpecials = new Set('().*{}+?[]^$\\!');
  18565. const regExpEscape$1 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  18566. // any single thing other than /
  18567. const qmark$1 = '[^/]';
  18568. // * => any number of characters
  18569. const star$1 = qmark$1 + '*?';
  18570. // use + when we need to ensure that *something* matches, because the * is
  18571. // the only thing in the path portion.
  18572. const starNoEmpty = qmark$1 + '+?';
  18573. // remove the \ chars that we added if we end up doing a nonmagic compare
  18574. // const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
  18575. class AST {
  18576. type;
  18577. #root;
  18578. #hasMagic;
  18579. #uflag = false;
  18580. #parts = [];
  18581. #parent;
  18582. #parentIndex;
  18583. #negs;
  18584. #filledNegs = false;
  18585. #options;
  18586. #toString;
  18587. // set to true if it's an extglob with no children
  18588. // (which really means one child of '')
  18589. #emptyExt = false;
  18590. constructor(type, parent, options = {}) {
  18591. this.type = type;
  18592. // extglobs are inherently magical
  18593. if (type)
  18594. this.#hasMagic = true;
  18595. this.#parent = parent;
  18596. this.#root = this.#parent ? this.#parent.#root : this;
  18597. this.#options = this.#root === this ? options : this.#root.#options;
  18598. this.#negs = this.#root === this ? [] : this.#root.#negs;
  18599. if (type === '!' && !this.#root.#filledNegs)
  18600. this.#negs.push(this);
  18601. this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
  18602. }
  18603. get hasMagic() {
  18604. /* c8 ignore start */
  18605. if (this.#hasMagic !== undefined)
  18606. return this.#hasMagic;
  18607. /* c8 ignore stop */
  18608. for (const p of this.#parts) {
  18609. if (typeof p === 'string')
  18610. continue;
  18611. if (p.type || p.hasMagic)
  18612. return (this.#hasMagic = true);
  18613. }
  18614. // note: will be undefined until we generate the regexp src and find out
  18615. return this.#hasMagic;
  18616. }
  18617. // reconstructs the pattern
  18618. toString() {
  18619. if (this.#toString !== undefined)
  18620. return this.#toString;
  18621. if (!this.type) {
  18622. return (this.#toString = this.#parts.map(p => String(p)).join(''));
  18623. }
  18624. else {
  18625. return (this.#toString =
  18626. this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
  18627. }
  18628. }
  18629. #fillNegs() {
  18630. /* c8 ignore start */
  18631. if (this !== this.#root)
  18632. throw new Error('should only call on root');
  18633. if (this.#filledNegs)
  18634. return this;
  18635. /* c8 ignore stop */
  18636. // call toString() once to fill this out
  18637. this.toString();
  18638. this.#filledNegs = true;
  18639. let n;
  18640. while ((n = this.#negs.pop())) {
  18641. if (n.type !== '!')
  18642. continue;
  18643. // walk up the tree, appending everthing that comes AFTER parentIndex
  18644. let p = n;
  18645. let pp = p.#parent;
  18646. while (pp) {
  18647. for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
  18648. for (const part of n.#parts) {
  18649. /* c8 ignore start */
  18650. if (typeof part === 'string') {
  18651. throw new Error('string part in extglob AST??');
  18652. }
  18653. /* c8 ignore stop */
  18654. part.copyIn(pp.#parts[i]);
  18655. }
  18656. }
  18657. p = pp;
  18658. pp = p.#parent;
  18659. }
  18660. }
  18661. return this;
  18662. }
  18663. push(...parts) {
  18664. for (const p of parts) {
  18665. if (p === '')
  18666. continue;
  18667. /* c8 ignore start */
  18668. if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {
  18669. throw new Error('invalid part: ' + p);
  18670. }
  18671. /* c8 ignore stop */
  18672. this.#parts.push(p);
  18673. }
  18674. }
  18675. toJSON() {
  18676. const ret = this.type === null
  18677. ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))
  18678. : [this.type, ...this.#parts.map(p => p.toJSON())];
  18679. if (this.isStart() && !this.type)
  18680. ret.unshift([]);
  18681. if (this.isEnd() &&
  18682. (this === this.#root ||
  18683. (this.#root.#filledNegs && this.#parent?.type === '!'))) {
  18684. ret.push({});
  18685. }
  18686. return ret;
  18687. }
  18688. isStart() {
  18689. if (this.#root === this)
  18690. return true;
  18691. // if (this.type) return !!this.#parent?.isStart()
  18692. if (!this.#parent?.isStart())
  18693. return false;
  18694. if (this.#parentIndex === 0)
  18695. return true;
  18696. // if everything AHEAD of this is a negation, then it's still the "start"
  18697. const p = this.#parent;
  18698. for (let i = 0; i < this.#parentIndex; i++) {
  18699. const pp = p.#parts[i];
  18700. if (!(pp instanceof AST && pp.type === '!')) {
  18701. return false;
  18702. }
  18703. }
  18704. return true;
  18705. }
  18706. isEnd() {
  18707. if (this.#root === this)
  18708. return true;
  18709. if (this.#parent?.type === '!')
  18710. return true;
  18711. if (!this.#parent?.isEnd())
  18712. return false;
  18713. if (!this.type)
  18714. return this.#parent?.isEnd();
  18715. // if not root, it'll always have a parent
  18716. /* c8 ignore start */
  18717. const pl = this.#parent ? this.#parent.#parts.length : 0;
  18718. /* c8 ignore stop */
  18719. return this.#parentIndex === pl - 1;
  18720. }
  18721. copyIn(part) {
  18722. if (typeof part === 'string')
  18723. this.push(part);
  18724. else
  18725. this.push(part.clone(this));
  18726. }
  18727. clone(parent) {
  18728. const c = new AST(this.type, parent);
  18729. for (const p of this.#parts) {
  18730. c.copyIn(p);
  18731. }
  18732. return c;
  18733. }
  18734. static #parseAST(str, ast, pos, opt) {
  18735. let escaping = false;
  18736. let inBrace = false;
  18737. let braceStart = -1;
  18738. let braceNeg = false;
  18739. if (ast.type === null) {
  18740. // outside of a extglob, append until we find a start
  18741. let i = pos;
  18742. let acc = '';
  18743. while (i < str.length) {
  18744. const c = str.charAt(i++);
  18745. // still accumulate escapes at this point, but we do ignore
  18746. // starts that are escaped
  18747. if (escaping || c === '\\') {
  18748. escaping = !escaping;
  18749. acc += c;
  18750. continue;
  18751. }
  18752. if (inBrace) {
  18753. if (i === braceStart + 1) {
  18754. if (c === '^' || c === '!') {
  18755. braceNeg = true;
  18756. }
  18757. }
  18758. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  18759. inBrace = false;
  18760. }
  18761. acc += c;
  18762. continue;
  18763. }
  18764. else if (c === '[') {
  18765. inBrace = true;
  18766. braceStart = i;
  18767. braceNeg = false;
  18768. acc += c;
  18769. continue;
  18770. }
  18771. if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {
  18772. ast.push(acc);
  18773. acc = '';
  18774. const ext = new AST(c, ast);
  18775. i = AST.#parseAST(str, ext, i, opt);
  18776. ast.push(ext);
  18777. continue;
  18778. }
  18779. acc += c;
  18780. }
  18781. ast.push(acc);
  18782. return i;
  18783. }
  18784. // some kind of extglob, pos is at the (
  18785. // find the next | or )
  18786. let i = pos + 1;
  18787. let part = new AST(null, ast);
  18788. const parts = [];
  18789. let acc = '';
  18790. while (i < str.length) {
  18791. const c = str.charAt(i++);
  18792. // still accumulate escapes at this point, but we do ignore
  18793. // starts that are escaped
  18794. if (escaping || c === '\\') {
  18795. escaping = !escaping;
  18796. acc += c;
  18797. continue;
  18798. }
  18799. if (inBrace) {
  18800. if (i === braceStart + 1) {
  18801. if (c === '^' || c === '!') {
  18802. braceNeg = true;
  18803. }
  18804. }
  18805. else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
  18806. inBrace = false;
  18807. }
  18808. acc += c;
  18809. continue;
  18810. }
  18811. else if (c === '[') {
  18812. inBrace = true;
  18813. braceStart = i;
  18814. braceNeg = false;
  18815. acc += c;
  18816. continue;
  18817. }
  18818. if (isExtglobType(c) && str.charAt(i) === '(') {
  18819. part.push(acc);
  18820. acc = '';
  18821. const ext = new AST(c, part);
  18822. part.push(ext);
  18823. i = AST.#parseAST(str, ext, i, opt);
  18824. continue;
  18825. }
  18826. if (c === '|') {
  18827. part.push(acc);
  18828. acc = '';
  18829. parts.push(part);
  18830. part = new AST(null, ast);
  18831. continue;
  18832. }
  18833. if (c === ')') {
  18834. if (acc === '' && ast.#parts.length === 0) {
  18835. ast.#emptyExt = true;
  18836. }
  18837. part.push(acc);
  18838. acc = '';
  18839. ast.push(...parts, part);
  18840. return i;
  18841. }
  18842. acc += c;
  18843. }
  18844. // unfinished extglob
  18845. // if we got here, it was a malformed extglob! not an extglob, but
  18846. // maybe something else in there.
  18847. ast.type = null;
  18848. ast.#hasMagic = undefined;
  18849. ast.#parts = [str.substring(pos - 1)];
  18850. return i;
  18851. }
  18852. static fromGlob(pattern, options = {}) {
  18853. const ast = new AST(null, undefined, options);
  18854. AST.#parseAST(pattern, ast, 0, options);
  18855. return ast;
  18856. }
  18857. // returns the regular expression if there's magic, or the unescaped
  18858. // string if not.
  18859. toMMPattern() {
  18860. // should only be called on root
  18861. /* c8 ignore start */
  18862. if (this !== this.#root)
  18863. return this.#root.toMMPattern();
  18864. /* c8 ignore stop */
  18865. const glob = this.toString();
  18866. const [re, body, hasMagic, uflag] = this.toRegExpSource();
  18867. // if we're in nocase mode, and not nocaseMagicOnly, then we do
  18868. // still need a regular expression if we have to case-insensitively
  18869. // match capital/lowercase characters.
  18870. const anyMagic = hasMagic ||
  18871. this.#hasMagic ||
  18872. (this.#options.nocase &&
  18873. !this.#options.nocaseMagicOnly &&
  18874. glob.toUpperCase() !== glob.toLowerCase());
  18875. if (!anyMagic) {
  18876. return body;
  18877. }
  18878. const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
  18879. return Object.assign(new RegExp(`^${re}$`, flags), {
  18880. _src: re,
  18881. _glob: glob,
  18882. });
  18883. }
  18884. get options() {
  18885. return this.#options;
  18886. }
  18887. // returns the string match, the regexp source, whether there's magic
  18888. // in the regexp (so a regular expression is required) and whether or
  18889. // not the uflag is needed for the regular expression (for posix classes)
  18890. // TODO: instead of injecting the start/end at this point, just return
  18891. // the BODY of the regexp, along with the start/end portions suitable
  18892. // for binding the start/end in either a joined full-path makeRe context
  18893. // (where we bind to (^|/), or a standalone matchPart context (where
  18894. // we bind to ^, and not /). Otherwise slashes get duped!
  18895. //
  18896. // In part-matching mode, the start is:
  18897. // - if not isStart: nothing
  18898. // - if traversal possible, but not allowed: ^(?!\.\.?$)
  18899. // - if dots allowed or not possible: ^
  18900. // - if dots possible and not allowed: ^(?!\.)
  18901. // end is:
  18902. // - if not isEnd(): nothing
  18903. // - else: $
  18904. //
  18905. // In full-path matching mode, we put the slash at the START of the
  18906. // pattern, so start is:
  18907. // - if first pattern: same as part-matching mode
  18908. // - if not isStart(): nothing
  18909. // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
  18910. // - if dots allowed or not possible: /
  18911. // - if dots possible and not allowed: /(?!\.)
  18912. // end is:
  18913. // - if last pattern, same as part-matching mode
  18914. // - else nothing
  18915. //
  18916. // Always put the (?:$|/) on negated tails, though, because that has to be
  18917. // there to bind the end of the negated pattern portion, and it's easier to
  18918. // just stick it in now rather than try to inject it later in the middle of
  18919. // the pattern.
  18920. //
  18921. // We can just always return the same end, and leave it up to the caller
  18922. // to know whether it's going to be used joined or in parts.
  18923. // And, if the start is adjusted slightly, can do the same there:
  18924. // - if not isStart: nothing
  18925. // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
  18926. // - if dots allowed or not possible: (?:/|^)
  18927. // - if dots possible and not allowed: (?:/|^)(?!\.)
  18928. //
  18929. // But it's better to have a simpler binding without a conditional, for
  18930. // performance, so probably better to return both start options.
  18931. //
  18932. // Then the caller just ignores the end if it's not the first pattern,
  18933. // and the start always gets applied.
  18934. //
  18935. // But that's always going to be $ if it's the ending pattern, or nothing,
  18936. // so the caller can just attach $ at the end of the pattern when building.
  18937. //
  18938. // So the todo is:
  18939. // - better detect what kind of start is needed
  18940. // - return both flavors of starting pattern
  18941. // - attach $ at the end of the pattern when creating the actual RegExp
  18942. //
  18943. // Ah, but wait, no, that all only applies to the root when the first pattern
  18944. // is not an extglob. If the first pattern IS an extglob, then we need all
  18945. // that dot prevention biz to live in the extglob portions, because eg
  18946. // +(*|.x*) can match .xy but not .yx.
  18947. //
  18948. // So, return the two flavors if it's #root and the first child is not an
  18949. // AST, otherwise leave it to the child AST to handle it, and there,
  18950. // use the (?:^|/) style of start binding.
  18951. //
  18952. // Even simplified further:
  18953. // - Since the start for a join is eg /(?!\.) and the start for a part
  18954. // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
  18955. // or start or whatever) and prepend ^ or / at the Regexp construction.
  18956. toRegExpSource(allowDot) {
  18957. const dot = allowDot ?? !!this.#options.dot;
  18958. if (this.#root === this)
  18959. this.#fillNegs();
  18960. if (!this.type) {
  18961. const noEmpty = this.isStart() && this.isEnd();
  18962. const src = this.#parts
  18963. .map(p => {
  18964. const [re, _, hasMagic, uflag] = typeof p === 'string'
  18965. ? AST.#parseGlob(p, this.#hasMagic, noEmpty)
  18966. : p.toRegExpSource(allowDot);
  18967. this.#hasMagic = this.#hasMagic || hasMagic;
  18968. this.#uflag = this.#uflag || uflag;
  18969. return re;
  18970. })
  18971. .join('');
  18972. let start = '';
  18973. if (this.isStart()) {
  18974. if (typeof this.#parts[0] === 'string') {
  18975. // this is the string that will match the start of the pattern,
  18976. // so we need to protect against dots and such.
  18977. // '.' and '..' cannot match unless the pattern is that exactly,
  18978. // even if it starts with . or dot:true is set.
  18979. const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
  18980. if (!dotTravAllowed) {
  18981. const aps = addPatternStart;
  18982. // check if we have a possibility of matching . or ..,
  18983. // and prevent that.
  18984. const needNoTrav =
  18985. // dots are allowed, and the pattern starts with [ or .
  18986. (dot && aps.has(src.charAt(0))) ||
  18987. // the pattern starts with \., and then [ or .
  18988. (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
  18989. // the pattern starts with \.\., and then [ or .
  18990. (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
  18991. // no need to prevent dots if it can't match a dot, or if a
  18992. // sub-pattern will be preventing it anyway.
  18993. const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
  18994. start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';
  18995. }
  18996. }
  18997. }
  18998. // append the "end of path portion" pattern to negation tails
  18999. let end = '';
  19000. if (this.isEnd() &&
  19001. this.#root.#filledNegs &&
  19002. this.#parent?.type === '!') {
  19003. end = '(?:$|\\/)';
  19004. }
  19005. const final = start + src + end;
  19006. return [
  19007. final,
  19008. unescape(src),
  19009. (this.#hasMagic = !!this.#hasMagic),
  19010. this.#uflag,
  19011. ];
  19012. }
  19013. // We need to calculate the body *twice* if it's a repeat pattern
  19014. // at the start, once in nodot mode, then again in dot mode, so a
  19015. // pattern like *(?) can match 'x.y'
  19016. const repeated = this.type === '*' || this.type === '+';
  19017. // some kind of extglob
  19018. const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
  19019. let body = this.#partsToRegExp(dot);
  19020. if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
  19021. // invalid extglob, has to at least be *something* present, if it's
  19022. // the entire path portion.
  19023. const s = this.toString();
  19024. this.#parts = [s];
  19025. this.type = null;
  19026. this.#hasMagic = undefined;
  19027. return [s, unescape(this.toString()), false, false];
  19028. }
  19029. // XXX abstract out this map method
  19030. let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot
  19031. ? ''
  19032. : this.#partsToRegExp(true);
  19033. if (bodyDotAllowed === body) {
  19034. bodyDotAllowed = '';
  19035. }
  19036. if (bodyDotAllowed) {
  19037. body = `(?:${body})(?:${bodyDotAllowed})*?`;
  19038. }
  19039. // an empty !() is exactly equivalent to a starNoEmpty
  19040. let final = '';
  19041. if (this.type === '!' && this.#emptyExt) {
  19042. final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
  19043. }
  19044. else {
  19045. const close = this.type === '!'
  19046. ? // !() must match something,but !(x) can match ''
  19047. '))' +
  19048. (this.isStart() && !dot && !allowDot ? startNoDot : '') +
  19049. star$1 +
  19050. ')'
  19051. : this.type === '@'
  19052. ? ')'
  19053. : this.type === '?'
  19054. ? ')?'
  19055. : this.type === '+' && bodyDotAllowed
  19056. ? ')'
  19057. : this.type === '*' && bodyDotAllowed
  19058. ? `)?`
  19059. : `)${this.type}`;
  19060. final = start + body + close;
  19061. }
  19062. return [
  19063. final,
  19064. unescape(body),
  19065. (this.#hasMagic = !!this.#hasMagic),
  19066. this.#uflag,
  19067. ];
  19068. }
  19069. #partsToRegExp(dot) {
  19070. return this.#parts
  19071. .map(p => {
  19072. // extglob ASTs should only contain parent ASTs
  19073. /* c8 ignore start */
  19074. if (typeof p === 'string') {
  19075. throw new Error('string type in extglob ast??');
  19076. }
  19077. /* c8 ignore stop */
  19078. // can ignore hasMagic, because extglobs are already always magic
  19079. const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
  19080. this.#uflag = this.#uflag || uflag;
  19081. return re;
  19082. })
  19083. .filter(p => !(this.isStart() && this.isEnd()) || !!p)
  19084. .join('|');
  19085. }
  19086. static #parseGlob(glob, hasMagic, noEmpty = false) {
  19087. let escaping = false;
  19088. let re = '';
  19089. let uflag = false;
  19090. for (let i = 0; i < glob.length; i++) {
  19091. const c = glob.charAt(i);
  19092. if (escaping) {
  19093. escaping = false;
  19094. re += (reSpecials.has(c) ? '\\' : '') + c;
  19095. continue;
  19096. }
  19097. if (c === '\\') {
  19098. if (i === glob.length - 1) {
  19099. re += '\\\\';
  19100. }
  19101. else {
  19102. escaping = true;
  19103. }
  19104. continue;
  19105. }
  19106. if (c === '[') {
  19107. const [src, needUflag, consumed, magic] = parseClass(glob, i);
  19108. if (consumed) {
  19109. re += src;
  19110. uflag = uflag || needUflag;
  19111. i += consumed - 1;
  19112. hasMagic = hasMagic || magic;
  19113. continue;
  19114. }
  19115. }
  19116. if (c === '*') {
  19117. if (noEmpty && glob === '*')
  19118. re += starNoEmpty;
  19119. else
  19120. re += star$1;
  19121. hasMagic = true;
  19122. continue;
  19123. }
  19124. if (c === '?') {
  19125. re += qmark$1;
  19126. hasMagic = true;
  19127. continue;
  19128. }
  19129. re += regExpEscape$1(c);
  19130. }
  19131. return [re, unescape(glob), !!hasMagic, uflag];
  19132. }
  19133. }
  19134. /**
  19135. * Escape all magic characters in a glob pattern.
  19136. *
  19137. * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}
  19138. * option is used, then characters are escaped by wrapping in `[]`, because
  19139. * a magic character wrapped in a character class can only be satisfied by
  19140. * that exact character. In this mode, `\` is _not_ escaped, because it is
  19141. * not interpreted as a magic character, but instead as a path separator.
  19142. */
  19143. const escape = (s, { windowsPathsNoEscape = false, } = {}) => {
  19144. // don't need to escape +@! because we escape the parens
  19145. // that make those magic, and escaping ! as [!] isn't valid,
  19146. // because [!]] is a valid glob class meaning not ']'.
  19147. return windowsPathsNoEscape
  19148. ? s.replace(/[?*()[\]]/g, '[$&]')
  19149. : s.replace(/[?*()[\]\\]/g, '\\$&');
  19150. };
  19151. const minimatch = (p, pattern, options = {}) => {
  19152. assertValidPattern(pattern);
  19153. // shortcut: comments match nothing.
  19154. if (!options.nocomment && pattern.charAt(0) === '#') {
  19155. return false;
  19156. }
  19157. return new Minimatch(pattern, options).match(p);
  19158. };
  19159. // Optimized checking for the most common glob patterns.
  19160. const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
  19161. const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
  19162. const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
  19163. const starDotExtTestNocase = (ext) => {
  19164. ext = ext.toLowerCase();
  19165. return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
  19166. };
  19167. const starDotExtTestNocaseDot = (ext) => {
  19168. ext = ext.toLowerCase();
  19169. return (f) => f.toLowerCase().endsWith(ext);
  19170. };
  19171. const starDotStarRE = /^\*+\.\*+$/;
  19172. const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
  19173. const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
  19174. const dotStarRE = /^\.\*+$/;
  19175. const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
  19176. const starRE = /^\*+$/;
  19177. const starTest = (f) => f.length !== 0 && !f.startsWith('.');
  19178. const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
  19179. const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
  19180. const qmarksTestNocase = ([$0, ext = '']) => {
  19181. const noext = qmarksTestNoExt([$0]);
  19182. if (!ext)
  19183. return noext;
  19184. ext = ext.toLowerCase();
  19185. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  19186. };
  19187. const qmarksTestNocaseDot = ([$0, ext = '']) => {
  19188. const noext = qmarksTestNoExtDot([$0]);
  19189. if (!ext)
  19190. return noext;
  19191. ext = ext.toLowerCase();
  19192. return (f) => noext(f) && f.toLowerCase().endsWith(ext);
  19193. };
  19194. const qmarksTestDot = ([$0, ext = '']) => {
  19195. const noext = qmarksTestNoExtDot([$0]);
  19196. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  19197. };
  19198. const qmarksTest = ([$0, ext = '']) => {
  19199. const noext = qmarksTestNoExt([$0]);
  19200. return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
  19201. };
  19202. const qmarksTestNoExt = ([$0]) => {
  19203. const len = $0.length;
  19204. return (f) => f.length === len && !f.startsWith('.');
  19205. };
  19206. const qmarksTestNoExtDot = ([$0]) => {
  19207. const len = $0.length;
  19208. return (f) => f.length === len && f !== '.' && f !== '..';
  19209. };
  19210. /* c8 ignore start */
  19211. const defaultPlatform = (typeof process === 'object' && process
  19212. ? (typeof process.env === 'object' &&
  19213. process.env &&
  19214. process.env.__MINIMATCH_TESTING_PLATFORM__) ||
  19215. process.platform
  19216. : 'posix');
  19217. const path = {
  19218. win32: { sep: '\\' },
  19219. posix: { sep: '/' },
  19220. };
  19221. /* c8 ignore stop */
  19222. const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
  19223. minimatch.sep = sep;
  19224. const GLOBSTAR = Symbol('globstar **');
  19225. minimatch.GLOBSTAR = GLOBSTAR;
  19226. // any single thing other than /
  19227. // don't need to escape / when using new RegExp()
  19228. const qmark = '[^/]';
  19229. // * => any number of characters
  19230. const star = qmark + '*?';
  19231. // ** when dots are allowed. Anything goes, except .. and .
  19232. // not (^ or / followed by one or two dots followed by $ or /),
  19233. // followed by anything, any number of times.
  19234. const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
  19235. // not a ^ or / followed by a dot,
  19236. // followed by anything, any number of times.
  19237. const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
  19238. const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
  19239. minimatch.filter = filter;
  19240. const ext = (a, b = {}) => Object.assign({}, a, b);
  19241. const defaults = (def) => {
  19242. if (!def || typeof def !== 'object' || !Object.keys(def).length) {
  19243. return minimatch;
  19244. }
  19245. const orig = minimatch;
  19246. const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
  19247. return Object.assign(m, {
  19248. Minimatch: class Minimatch extends orig.Minimatch {
  19249. constructor(pattern, options = {}) {
  19250. super(pattern, ext(def, options));
  19251. }
  19252. static defaults(options) {
  19253. return orig.defaults(ext(def, options)).Minimatch;
  19254. }
  19255. },
  19256. AST: class AST extends orig.AST {
  19257. /* c8 ignore start */
  19258. constructor(type, parent, options = {}) {
  19259. super(type, parent, ext(def, options));
  19260. }
  19261. /* c8 ignore stop */
  19262. static fromGlob(pattern, options = {}) {
  19263. return orig.AST.fromGlob(pattern, ext(def, options));
  19264. }
  19265. },
  19266. unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
  19267. escape: (s, options = {}) => orig.escape(s, ext(def, options)),
  19268. filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
  19269. defaults: (options) => orig.defaults(ext(def, options)),
  19270. makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
  19271. braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
  19272. match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
  19273. sep: orig.sep,
  19274. GLOBSTAR: GLOBSTAR,
  19275. });
  19276. };
  19277. minimatch.defaults = defaults;
  19278. // Brace expansion:
  19279. // a{b,c}d -> abd acd
  19280. // a{b,}c -> abc ac
  19281. // a{0..3}d -> a0d a1d a2d a3d
  19282. // a{b,c{d,e}f}g -> abg acdfg acefg
  19283. // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
  19284. //
  19285. // Invalid sets are not expanded.
  19286. // a{2..}b -> a{2..}b
  19287. // a{b}c -> a{b}c
  19288. const braceExpand = (pattern, options = {}) => {
  19289. assertValidPattern(pattern);
  19290. // Thanks to Yeting Li <https://github.com/yetingli> for
  19291. // improving this regexp to avoid a ReDOS vulnerability.
  19292. if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
  19293. // shortcut. no need to expand.
  19294. return [pattern];
  19295. }
  19296. return expand(pattern);
  19297. };
  19298. minimatch.braceExpand = braceExpand;
  19299. // parse a component of the expanded set.
  19300. // At this point, no pattern may contain "/" in it
  19301. // so we're going to return a 2d array, where each entry is the full
  19302. // pattern, split on '/', and then turned into a regular expression.
  19303. // A regexp is made at the end which joins each array with an
  19304. // escaped /, and another full one which joins each regexp with |.
  19305. //
  19306. // Following the lead of Bash 4.1, note that "**" only has special meaning
  19307. // when it is the *only* thing in a path portion. Otherwise, any series
  19308. // of * is equivalent to a single *. Globstar behavior is enabled by
  19309. // default, and can be disabled by setting options.noglobstar.
  19310. const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
  19311. minimatch.makeRe = makeRe;
  19312. const match = (list, pattern, options = {}) => {
  19313. const mm = new Minimatch(pattern, options);
  19314. list = list.filter(f => mm.match(f));
  19315. if (mm.options.nonull && !list.length) {
  19316. list.push(pattern);
  19317. }
  19318. return list;
  19319. };
  19320. minimatch.match = match;
  19321. // replace stuff like \* with *
  19322. const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
  19323. const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  19324. class Minimatch {
  19325. options;
  19326. set;
  19327. pattern;
  19328. windowsPathsNoEscape;
  19329. nonegate;
  19330. negate;
  19331. comment;
  19332. empty;
  19333. preserveMultipleSlashes;
  19334. partial;
  19335. globSet;
  19336. globParts;
  19337. nocase;
  19338. isWindows;
  19339. platform;
  19340. windowsNoMagicRoot;
  19341. regexp;
  19342. constructor(pattern, options = {}) {
  19343. assertValidPattern(pattern);
  19344. options = options || {};
  19345. this.options = options;
  19346. this.pattern = pattern;
  19347. this.platform = options.platform || defaultPlatform;
  19348. this.isWindows = this.platform === 'win32';
  19349. this.windowsPathsNoEscape =
  19350. !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
  19351. if (this.windowsPathsNoEscape) {
  19352. this.pattern = this.pattern.replace(/\\/g, '/');
  19353. }
  19354. this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
  19355. this.regexp = null;
  19356. this.negate = false;
  19357. this.nonegate = !!options.nonegate;
  19358. this.comment = false;
  19359. this.empty = false;
  19360. this.partial = !!options.partial;
  19361. this.nocase = !!this.options.nocase;
  19362. this.windowsNoMagicRoot =
  19363. options.windowsNoMagicRoot !== undefined
  19364. ? options.windowsNoMagicRoot
  19365. : !!(this.isWindows && this.nocase);
  19366. this.globSet = [];
  19367. this.globParts = [];
  19368. this.set = [];
  19369. // make the set of regexps etc.
  19370. this.make();
  19371. }
  19372. hasMagic() {
  19373. if (this.options.magicalBraces && this.set.length > 1) {
  19374. return true;
  19375. }
  19376. for (const pattern of this.set) {
  19377. for (const part of pattern) {
  19378. if (typeof part !== 'string')
  19379. return true;
  19380. }
  19381. }
  19382. return false;
  19383. }
  19384. debug(..._) { }
  19385. make() {
  19386. const pattern = this.pattern;
  19387. const options = this.options;
  19388. // empty patterns and comments match nothing.
  19389. if (!options.nocomment && pattern.charAt(0) === '#') {
  19390. this.comment = true;
  19391. return;
  19392. }
  19393. if (!pattern) {
  19394. this.empty = true;
  19395. return;
  19396. }
  19397. // step 1: figure out negation, etc.
  19398. this.parseNegate();
  19399. // step 2: expand braces
  19400. this.globSet = [...new Set(this.braceExpand())];
  19401. if (options.debug) {
  19402. this.debug = (...args) => console.error(...args);
  19403. }
  19404. this.debug(this.pattern, this.globSet);
  19405. // step 3: now we have a set, so turn each one into a series of
  19406. // path-portion matching patterns.
  19407. // These will be regexps, except in the case of "**", which is
  19408. // set to the GLOBSTAR object for globstar behavior,
  19409. // and will not contain any / characters
  19410. //
  19411. // First, we preprocess to make the glob pattern sets a bit simpler
  19412. // and deduped. There are some perf-killing patterns that can cause
  19413. // problems with a glob walk, but we can simplify them down a bit.
  19414. const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
  19415. this.globParts = this.preprocess(rawGlobParts);
  19416. this.debug(this.pattern, this.globParts);
  19417. // glob --> regexps
  19418. let set = this.globParts.map((s, _, __) => {
  19419. if (this.isWindows && this.windowsNoMagicRoot) {
  19420. // check if it's a drive or unc path.
  19421. const isUNC = s[0] === '' &&
  19422. s[1] === '' &&
  19423. (s[2] === '?' || !globMagic.test(s[2])) &&
  19424. !globMagic.test(s[3]);
  19425. const isDrive = /^[a-z]:/i.test(s[0]);
  19426. if (isUNC) {
  19427. return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))];
  19428. }
  19429. else if (isDrive) {
  19430. return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
  19431. }
  19432. }
  19433. return s.map(ss => this.parse(ss));
  19434. });
  19435. this.debug(this.pattern, set);
  19436. // filter out everything that didn't compile properly.
  19437. this.set = set.filter(s => s.indexOf(false) === -1);
  19438. // do not treat the ? in UNC paths as magic
  19439. if (this.isWindows) {
  19440. for (let i = 0; i < this.set.length; i++) {
  19441. const p = this.set[i];
  19442. if (p[0] === '' &&
  19443. p[1] === '' &&
  19444. this.globParts[i][2] === '?' &&
  19445. typeof p[3] === 'string' &&
  19446. /^[a-z]:$/i.test(p[3])) {
  19447. p[2] = '?';
  19448. }
  19449. }
  19450. }
  19451. this.debug(this.pattern, this.set);
  19452. }
  19453. // various transforms to equivalent pattern sets that are
  19454. // faster to process in a filesystem walk. The goal is to
  19455. // eliminate what we can, and push all ** patterns as far
  19456. // to the right as possible, even if it increases the number
  19457. // of patterns that we have to process.
  19458. preprocess(globParts) {
  19459. // if we're not in globstar mode, then turn all ** into *
  19460. if (this.options.noglobstar) {
  19461. for (let i = 0; i < globParts.length; i++) {
  19462. for (let j = 0; j < globParts[i].length; j++) {
  19463. if (globParts[i][j] === '**') {
  19464. globParts[i][j] = '*';
  19465. }
  19466. }
  19467. }
  19468. }
  19469. const { optimizationLevel = 1 } = this.options;
  19470. if (optimizationLevel >= 2) {
  19471. // aggressive optimization for the purpose of fs walking
  19472. globParts = this.firstPhasePreProcess(globParts);
  19473. globParts = this.secondPhasePreProcess(globParts);
  19474. }
  19475. else if (optimizationLevel >= 1) {
  19476. // just basic optimizations to remove some .. parts
  19477. globParts = this.levelOneOptimize(globParts);
  19478. }
  19479. else {
  19480. // just collapse multiple ** portions into one
  19481. globParts = this.adjascentGlobstarOptimize(globParts);
  19482. }
  19483. return globParts;
  19484. }
  19485. // just get rid of adjascent ** portions
  19486. adjascentGlobstarOptimize(globParts) {
  19487. return globParts.map(parts => {
  19488. let gs = -1;
  19489. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  19490. let i = gs;
  19491. while (parts[i + 1] === '**') {
  19492. i++;
  19493. }
  19494. if (i !== gs) {
  19495. parts.splice(gs, i - gs);
  19496. }
  19497. }
  19498. return parts;
  19499. });
  19500. }
  19501. // get rid of adjascent ** and resolve .. portions
  19502. levelOneOptimize(globParts) {
  19503. return globParts.map(parts => {
  19504. parts = parts.reduce((set, part) => {
  19505. const prev = set[set.length - 1];
  19506. if (part === '**' && prev === '**') {
  19507. return set;
  19508. }
  19509. if (part === '..') {
  19510. if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
  19511. set.pop();
  19512. return set;
  19513. }
  19514. }
  19515. set.push(part);
  19516. return set;
  19517. }, []);
  19518. return parts.length === 0 ? [''] : parts;
  19519. });
  19520. }
  19521. levelTwoFileOptimize(parts) {
  19522. if (!Array.isArray(parts)) {
  19523. parts = this.slashSplit(parts);
  19524. }
  19525. let didSomething = false;
  19526. do {
  19527. didSomething = false;
  19528. // <pre>/<e>/<rest> -> <pre>/<rest>
  19529. if (!this.preserveMultipleSlashes) {
  19530. for (let i = 1; i < parts.length - 1; i++) {
  19531. const p = parts[i];
  19532. // don't squeeze out UNC patterns
  19533. if (i === 1 && p === '' && parts[0] === '')
  19534. continue;
  19535. if (p === '.' || p === '') {
  19536. didSomething = true;
  19537. parts.splice(i, 1);
  19538. i--;
  19539. }
  19540. }
  19541. if (parts[0] === '.' &&
  19542. parts.length === 2 &&
  19543. (parts[1] === '.' || parts[1] === '')) {
  19544. didSomething = true;
  19545. parts.pop();
  19546. }
  19547. }
  19548. // <pre>/<p>/../<rest> -> <pre>/<rest>
  19549. let dd = 0;
  19550. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  19551. const p = parts[dd - 1];
  19552. if (p && p !== '.' && p !== '..' && p !== '**') {
  19553. didSomething = true;
  19554. parts.splice(dd - 1, 2);
  19555. dd -= 2;
  19556. }
  19557. }
  19558. } while (didSomething);
  19559. return parts.length === 0 ? [''] : parts;
  19560. }
  19561. // First phase: single-pattern processing
  19562. // <pre> is 1 or more portions
  19563. // <rest> is 1 or more portions
  19564. // <p> is any portion other than ., .., '', or **
  19565. // <e> is . or ''
  19566. //
  19567. // **/.. is *brutal* for filesystem walking performance, because
  19568. // it effectively resets the recursive walk each time it occurs,
  19569. // and ** cannot be reduced out by a .. pattern part like a regexp
  19570. // or most strings (other than .., ., and '') can be.
  19571. //
  19572. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  19573. // <pre>/<e>/<rest> -> <pre>/<rest>
  19574. // <pre>/<p>/../<rest> -> <pre>/<rest>
  19575. // **/**/<rest> -> **/<rest>
  19576. //
  19577. // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
  19578. // this WOULD be allowed if ** did follow symlinks, or * didn't
  19579. firstPhasePreProcess(globParts) {
  19580. let didSomething = false;
  19581. do {
  19582. didSomething = false;
  19583. // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
  19584. for (let parts of globParts) {
  19585. let gs = -1;
  19586. while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
  19587. let gss = gs;
  19588. while (parts[gss + 1] === '**') {
  19589. // <pre>/**/**/<rest> -> <pre>/**/<rest>
  19590. gss++;
  19591. }
  19592. // eg, if gs is 2 and gss is 4, that means we have 3 **
  19593. // parts, and can remove 2 of them.
  19594. if (gss > gs) {
  19595. parts.splice(gs + 1, gss - gs);
  19596. }
  19597. let next = parts[gs + 1];
  19598. const p = parts[gs + 2];
  19599. const p2 = parts[gs + 3];
  19600. if (next !== '..')
  19601. continue;
  19602. if (!p ||
  19603. p === '.' ||
  19604. p === '..' ||
  19605. !p2 ||
  19606. p2 === '.' ||
  19607. p2 === '..') {
  19608. continue;
  19609. }
  19610. didSomething = true;
  19611. // edit parts in place, and push the new one
  19612. parts.splice(gs, 1);
  19613. const other = parts.slice(0);
  19614. other[gs] = '**';
  19615. globParts.push(other);
  19616. gs--;
  19617. }
  19618. // <pre>/<e>/<rest> -> <pre>/<rest>
  19619. if (!this.preserveMultipleSlashes) {
  19620. for (let i = 1; i < parts.length - 1; i++) {
  19621. const p = parts[i];
  19622. // don't squeeze out UNC patterns
  19623. if (i === 1 && p === '' && parts[0] === '')
  19624. continue;
  19625. if (p === '.' || p === '') {
  19626. didSomething = true;
  19627. parts.splice(i, 1);
  19628. i--;
  19629. }
  19630. }
  19631. if (parts[0] === '.' &&
  19632. parts.length === 2 &&
  19633. (parts[1] === '.' || parts[1] === '')) {
  19634. didSomething = true;
  19635. parts.pop();
  19636. }
  19637. }
  19638. // <pre>/<p>/../<rest> -> <pre>/<rest>
  19639. let dd = 0;
  19640. while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
  19641. const p = parts[dd - 1];
  19642. if (p && p !== '.' && p !== '..' && p !== '**') {
  19643. didSomething = true;
  19644. const needDot = dd === 1 && parts[dd + 1] === '**';
  19645. const splin = needDot ? ['.'] : [];
  19646. parts.splice(dd - 1, 2, ...splin);
  19647. if (parts.length === 0)
  19648. parts.push('');
  19649. dd -= 2;
  19650. }
  19651. }
  19652. }
  19653. } while (didSomething);
  19654. return globParts;
  19655. }
  19656. // second phase: multi-pattern dedupes
  19657. // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
  19658. // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
  19659. // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
  19660. //
  19661. // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
  19662. // ^-- not valid because ** doens't follow symlinks
  19663. secondPhasePreProcess(globParts) {
  19664. for (let i = 0; i < globParts.length - 1; i++) {
  19665. for (let j = i + 1; j < globParts.length; j++) {
  19666. const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
  19667. if (matched) {
  19668. globParts[i] = [];
  19669. globParts[j] = matched;
  19670. break;
  19671. }
  19672. }
  19673. }
  19674. return globParts.filter(gs => gs.length);
  19675. }
  19676. partsMatch(a, b, emptyGSMatch = false) {
  19677. let ai = 0;
  19678. let bi = 0;
  19679. let result = [];
  19680. let which = '';
  19681. while (ai < a.length && bi < b.length) {
  19682. if (a[ai] === b[bi]) {
  19683. result.push(which === 'b' ? b[bi] : a[ai]);
  19684. ai++;
  19685. bi++;
  19686. }
  19687. else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
  19688. result.push(a[ai]);
  19689. ai++;
  19690. }
  19691. else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
  19692. result.push(b[bi]);
  19693. bi++;
  19694. }
  19695. else if (a[ai] === '*' &&
  19696. b[bi] &&
  19697. (this.options.dot || !b[bi].startsWith('.')) &&
  19698. b[bi] !== '**') {
  19699. if (which === 'b')
  19700. return false;
  19701. which = 'a';
  19702. result.push(a[ai]);
  19703. ai++;
  19704. bi++;
  19705. }
  19706. else if (b[bi] === '*' &&
  19707. a[ai] &&
  19708. (this.options.dot || !a[ai].startsWith('.')) &&
  19709. a[ai] !== '**') {
  19710. if (which === 'a')
  19711. return false;
  19712. which = 'b';
  19713. result.push(b[bi]);
  19714. ai++;
  19715. bi++;
  19716. }
  19717. else {
  19718. return false;
  19719. }
  19720. }
  19721. // if we fall out of the loop, it means they two are identical
  19722. // as long as their lengths match
  19723. return a.length === b.length && result;
  19724. }
  19725. parseNegate() {
  19726. if (this.nonegate)
  19727. return;
  19728. const pattern = this.pattern;
  19729. let negate = false;
  19730. let negateOffset = 0;
  19731. for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
  19732. negate = !negate;
  19733. negateOffset++;
  19734. }
  19735. if (negateOffset)
  19736. this.pattern = pattern.slice(negateOffset);
  19737. this.negate = negate;
  19738. }
  19739. // set partial to true to test if, for example,
  19740. // "/a/b" matches the start of "/*/b/*/d"
  19741. // Partial means, if you run out of file before you run
  19742. // out of pattern, then that's fine, as long as all
  19743. // the parts match.
  19744. matchOne(file, pattern, partial = false) {
  19745. const options = this.options;
  19746. // UNC paths like //?/X:/... can match X:/... and vice versa
  19747. // Drive letters in absolute drive or unc paths are always compared
  19748. // case-insensitively.
  19749. if (this.isWindows) {
  19750. const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
  19751. const fileUNC = !fileDrive &&
  19752. file[0] === '' &&
  19753. file[1] === '' &&
  19754. file[2] === '?' &&
  19755. /^[a-z]:$/i.test(file[3]);
  19756. const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
  19757. const patternUNC = !patternDrive &&
  19758. pattern[0] === '' &&
  19759. pattern[1] === '' &&
  19760. pattern[2] === '?' &&
  19761. typeof pattern[3] === 'string' &&
  19762. /^[a-z]:$/i.test(pattern[3]);
  19763. const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
  19764. const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
  19765. if (typeof fdi === 'number' && typeof pdi === 'number') {
  19766. const [fd, pd] = [file[fdi], pattern[pdi]];
  19767. if (fd.toLowerCase() === pd.toLowerCase()) {
  19768. pattern[pdi] = fd;
  19769. if (pdi > fdi) {
  19770. pattern = pattern.slice(pdi);
  19771. }
  19772. else if (fdi > pdi) {
  19773. file = file.slice(fdi);
  19774. }
  19775. }
  19776. }
  19777. }
  19778. // resolve and reduce . and .. portions in the file as well.
  19779. // dont' need to do the second phase, because it's only one string[]
  19780. const { optimizationLevel = 1 } = this.options;
  19781. if (optimizationLevel >= 2) {
  19782. file = this.levelTwoFileOptimize(file);
  19783. }
  19784. this.debug('matchOne', this, { file, pattern });
  19785. this.debug('matchOne', file.length, pattern.length);
  19786. for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
  19787. this.debug('matchOne loop');
  19788. var p = pattern[pi];
  19789. var f = file[fi];
  19790. this.debug(pattern, p, f);
  19791. // should be impossible.
  19792. // some invalid regexp stuff in the set.
  19793. /* c8 ignore start */
  19794. if (p === false) {
  19795. return false;
  19796. }
  19797. /* c8 ignore stop */
  19798. if (p === GLOBSTAR) {
  19799. this.debug('GLOBSTAR', [pattern, p, f]);
  19800. // "**"
  19801. // a/**/b/**/c would match the following:
  19802. // a/b/x/y/z/c
  19803. // a/x/y/z/b/c
  19804. // a/b/x/b/x/c
  19805. // a/b/c
  19806. // To do this, take the rest of the pattern after
  19807. // the **, and see if it would match the file remainder.
  19808. // If so, return success.
  19809. // If not, the ** "swallows" a segment, and try again.
  19810. // This is recursively awful.
  19811. //
  19812. // a/**/b/**/c matching a/b/x/y/z/c
  19813. // - a matches a
  19814. // - doublestar
  19815. // - matchOne(b/x/y/z/c, b/**/c)
  19816. // - b matches b
  19817. // - doublestar
  19818. // - matchOne(x/y/z/c, c) -> no
  19819. // - matchOne(y/z/c, c) -> no
  19820. // - matchOne(z/c, c) -> no
  19821. // - matchOne(c, c) yes, hit
  19822. var fr = fi;
  19823. var pr = pi + 1;
  19824. if (pr === pl) {
  19825. this.debug('** at the end');
  19826. // a ** at the end will just swallow the rest.
  19827. // We have found a match.
  19828. // however, it will not swallow /.x, unless
  19829. // options.dot is set.
  19830. // . and .. are *never* matched by **, for explosively
  19831. // exponential reasons.
  19832. for (; fi < fl; fi++) {
  19833. if (file[fi] === '.' ||
  19834. file[fi] === '..' ||
  19835. (!options.dot && file[fi].charAt(0) === '.'))
  19836. return false;
  19837. }
  19838. return true;
  19839. }
  19840. // ok, let's see if we can swallow whatever we can.
  19841. while (fr < fl) {
  19842. var swallowee = file[fr];
  19843. this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
  19844. // XXX remove this slice. Just pass the start index.
  19845. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
  19846. this.debug('globstar found match!', fr, fl, swallowee);
  19847. // found a match.
  19848. return true;
  19849. }
  19850. else {
  19851. // can't swallow "." or ".." ever.
  19852. // can only swallow ".foo" when explicitly asked.
  19853. if (swallowee === '.' ||
  19854. swallowee === '..' ||
  19855. (!options.dot && swallowee.charAt(0) === '.')) {
  19856. this.debug('dot detected!', file, fr, pattern, pr);
  19857. break;
  19858. }
  19859. // ** swallows a segment, and continue.
  19860. this.debug('globstar swallow a segment, and continue');
  19861. fr++;
  19862. }
  19863. }
  19864. // no match was found.
  19865. // However, in partial mode, we can't say this is necessarily over.
  19866. /* c8 ignore start */
  19867. if (partial) {
  19868. // ran out of file
  19869. this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
  19870. if (fr === fl) {
  19871. return true;
  19872. }
  19873. }
  19874. /* c8 ignore stop */
  19875. return false;
  19876. }
  19877. // something other than **
  19878. // non-magic patterns just have to match exactly
  19879. // patterns with magic have been turned into regexps.
  19880. let hit;
  19881. if (typeof p === 'string') {
  19882. hit = f === p;
  19883. this.debug('string match', p, f, hit);
  19884. }
  19885. else {
  19886. hit = p.test(f);
  19887. this.debug('pattern match', p, f, hit);
  19888. }
  19889. if (!hit)
  19890. return false;
  19891. }
  19892. // Note: ending in / means that we'll get a final ""
  19893. // at the end of the pattern. This can only match a
  19894. // corresponding "" at the end of the file.
  19895. // If the file ends in /, then it can only match a
  19896. // a pattern that ends in /, unless the pattern just
  19897. // doesn't have any more for it. But, a/b/ should *not*
  19898. // match "a/b/*", even though "" matches against the
  19899. // [^/]*? pattern, except in partial mode, where it might
  19900. // simply not be reached yet.
  19901. // However, a/b/ should still satisfy a/*
  19902. // now either we fell off the end of the pattern, or we're done.
  19903. if (fi === fl && pi === pl) {
  19904. // ran out of pattern and filename at the same time.
  19905. // an exact hit!
  19906. return true;
  19907. }
  19908. else if (fi === fl) {
  19909. // ran out of file, but still had pattern left.
  19910. // this is ok if we're doing the match as part of
  19911. // a glob fs traversal.
  19912. return partial;
  19913. }
  19914. else if (pi === pl) {
  19915. // ran out of pattern, still have file left.
  19916. // this is only acceptable if we're on the very last
  19917. // empty segment of a file with a trailing slash.
  19918. // a/* should match a/b/
  19919. return fi === fl - 1 && file[fi] === '';
  19920. /* c8 ignore start */
  19921. }
  19922. else {
  19923. // should be unreachable.
  19924. throw new Error('wtf?');
  19925. }
  19926. /* c8 ignore stop */
  19927. }
  19928. braceExpand() {
  19929. return braceExpand(this.pattern, this.options);
  19930. }
  19931. parse(pattern) {
  19932. assertValidPattern(pattern);
  19933. const options = this.options;
  19934. // shortcuts
  19935. if (pattern === '**')
  19936. return GLOBSTAR;
  19937. if (pattern === '')
  19938. return '';
  19939. // far and away, the most common glob pattern parts are
  19940. // *, *.*, and *.<ext> Add a fast check method for those.
  19941. let m;
  19942. let fastTest = null;
  19943. if ((m = pattern.match(starRE))) {
  19944. fastTest = options.dot ? starTestDot : starTest;
  19945. }
  19946. else if ((m = pattern.match(starDotExtRE))) {
  19947. fastTest = (options.nocase
  19948. ? options.dot
  19949. ? starDotExtTestNocaseDot
  19950. : starDotExtTestNocase
  19951. : options.dot
  19952. ? starDotExtTestDot
  19953. : starDotExtTest)(m[1]);
  19954. }
  19955. else if ((m = pattern.match(qmarksRE))) {
  19956. fastTest = (options.nocase
  19957. ? options.dot
  19958. ? qmarksTestNocaseDot
  19959. : qmarksTestNocase
  19960. : options.dot
  19961. ? qmarksTestDot
  19962. : qmarksTest)(m);
  19963. }
  19964. else if ((m = pattern.match(starDotStarRE))) {
  19965. fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
  19966. }
  19967. else if ((m = pattern.match(dotStarRE))) {
  19968. fastTest = dotStarTest;
  19969. }
  19970. const re = AST.fromGlob(pattern, this.options).toMMPattern();
  19971. if (fastTest && typeof re === 'object') {
  19972. // Avoids overriding in frozen environments
  19973. Reflect.defineProperty(re, 'test', { value: fastTest });
  19974. }
  19975. return re;
  19976. }
  19977. makeRe() {
  19978. if (this.regexp || this.regexp === false)
  19979. return this.regexp;
  19980. // at this point, this.set is a 2d array of partial
  19981. // pattern strings, or "**".
  19982. //
  19983. // It's better to use .match(). This function shouldn't
  19984. // be used, really, but it's pretty convenient sometimes,
  19985. // when you just want to work with a regex.
  19986. const set = this.set;
  19987. if (!set.length) {
  19988. this.regexp = false;
  19989. return this.regexp;
  19990. }
  19991. const options = this.options;
  19992. const twoStar = options.noglobstar
  19993. ? star
  19994. : options.dot
  19995. ? twoStarDot
  19996. : twoStarNoDot;
  19997. const flags = new Set(options.nocase ? ['i'] : []);
  19998. // regexpify non-globstar patterns
  19999. // if ** is only item, then we just do one twoStar
  20000. // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
  20001. // if ** is last, append (\/twoStar|) to previous
  20002. // if ** is in the middle, append (\/|\/twoStar\/) to previous
  20003. // then filter out GLOBSTAR symbols
  20004. let re = set
  20005. .map(pattern => {
  20006. const pp = pattern.map(p => {
  20007. if (p instanceof RegExp) {
  20008. for (const f of p.flags.split(''))
  20009. flags.add(f);
  20010. }
  20011. return typeof p === 'string'
  20012. ? regExpEscape(p)
  20013. : p === GLOBSTAR
  20014. ? GLOBSTAR
  20015. : p._src;
  20016. });
  20017. pp.forEach((p, i) => {
  20018. const next = pp[i + 1];
  20019. const prev = pp[i - 1];
  20020. if (p !== GLOBSTAR || prev === GLOBSTAR) {
  20021. return;
  20022. }
  20023. if (prev === undefined) {
  20024. if (next !== undefined && next !== GLOBSTAR) {
  20025. pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
  20026. }
  20027. else {
  20028. pp[i] = twoStar;
  20029. }
  20030. }
  20031. else if (next === undefined) {
  20032. pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
  20033. }
  20034. else if (next !== GLOBSTAR) {
  20035. pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
  20036. pp[i + 1] = GLOBSTAR;
  20037. }
  20038. });
  20039. return pp.filter(p => p !== GLOBSTAR).join('/');
  20040. })
  20041. .join('|');
  20042. // need to wrap in parens if we had more than one thing with |,
  20043. // otherwise only the first will be anchored to ^ and the last to $
  20044. const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
  20045. // must match entire pattern
  20046. // ending in a * or ** will make it less strict.
  20047. re = '^' + open + re + close + '$';
  20048. // can match anything, as long as it's not this.
  20049. if (this.negate)
  20050. re = '^(?!' + re + ').+$';
  20051. try {
  20052. this.regexp = new RegExp(re, [...flags].join(''));
  20053. /* c8 ignore start */
  20054. }
  20055. catch (ex) {
  20056. // should be impossible
  20057. this.regexp = false;
  20058. }
  20059. /* c8 ignore stop */
  20060. return this.regexp;
  20061. }
  20062. slashSplit(p) {
  20063. // if p starts with // on windows, we preserve that
  20064. // so that UNC paths aren't broken. Otherwise, any number of
  20065. // / characters are coalesced into one, unless
  20066. // preserveMultipleSlashes is set to true.
  20067. if (this.preserveMultipleSlashes) {
  20068. return p.split('/');
  20069. }
  20070. else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
  20071. // add an extra '' for the one we lose
  20072. return ['', ...p.split(/\/+/)];
  20073. }
  20074. else {
  20075. return p.split(/\/+/);
  20076. }
  20077. }
  20078. match(f, partial = this.partial) {
  20079. this.debug('match', f, this.pattern);
  20080. // short-circuit in the case of busted things.
  20081. // comments, etc.
  20082. if (this.comment) {
  20083. return false;
  20084. }
  20085. if (this.empty) {
  20086. return f === '';
  20087. }
  20088. if (f === '/' && partial) {
  20089. return true;
  20090. }
  20091. const options = this.options;
  20092. // windows: need to use /, not \
  20093. if (this.isWindows) {
  20094. f = f.split('\\').join('/');
  20095. }
  20096. // treat the test path as a set of pathparts.
  20097. const ff = this.slashSplit(f);
  20098. this.debug(this.pattern, 'split', ff);
  20099. // just ONE of the pattern sets in this.set needs to match
  20100. // in order for it to be valid. If negating, then just one
  20101. // match means that we have failed.
  20102. // Either way, return on the first hit.
  20103. const set = this.set;
  20104. this.debug(this.pattern, 'set', set);
  20105. // Find the basename of the path by looking for the last non-empty segment
  20106. let filename = ff[ff.length - 1];
  20107. if (!filename) {
  20108. for (let i = ff.length - 2; !filename && i >= 0; i--) {
  20109. filename = ff[i];
  20110. }
  20111. }
  20112. for (let i = 0; i < set.length; i++) {
  20113. const pattern = set[i];
  20114. let file = ff;
  20115. if (options.matchBase && pattern.length === 1) {
  20116. file = [filename];
  20117. }
  20118. const hit = this.matchOne(file, pattern, partial);
  20119. if (hit) {
  20120. if (options.flipNegate) {
  20121. return true;
  20122. }
  20123. return !this.negate;
  20124. }
  20125. }
  20126. // didn't get any hits. this is success if it's a negative
  20127. // pattern, failure otherwise.
  20128. if (options.flipNegate) {
  20129. return false;
  20130. }
  20131. return this.negate;
  20132. }
  20133. static defaults(def) {
  20134. return minimatch.defaults(def).Minimatch;
  20135. }
  20136. }
  20137. /* c8 ignore stop */
  20138. minimatch.AST = AST;
  20139. minimatch.Minimatch = Minimatch;
  20140. minimatch.escape = escape;
  20141. minimatch.unescape = unescape;
  20142. class TypeScope {
  20143. constructor(filename, source, offset = 0, imports = /* @__PURE__ */ Object.create(null), types = /* @__PURE__ */ Object.create(null), declares = /* @__PURE__ */ Object.create(null)) {
  20144. this.filename = filename;
  20145. this.source = source;
  20146. this.offset = offset;
  20147. this.imports = imports;
  20148. this.types = types;
  20149. this.declares = declares;
  20150. this.isGenericScope = false;
  20151. this.resolvedImportSources = /* @__PURE__ */ Object.create(null);
  20152. this.exportedTypes = /* @__PURE__ */ Object.create(null);
  20153. this.exportedDeclares = /* @__PURE__ */ Object.create(null);
  20154. }
  20155. }
  20156. function resolveTypeElements(ctx, node, scope, typeParameters) {
  20157. const canCache = !typeParameters;
  20158. if (canCache && node._resolvedElements) {
  20159. return node._resolvedElements;
  20160. }
  20161. const resolved = innerResolveTypeElements(
  20162. ctx,
  20163. node,
  20164. node._ownerScope || scope || ctxToScope(ctx),
  20165. typeParameters
  20166. );
  20167. return canCache ? node._resolvedElements = resolved : resolved;
  20168. }
  20169. function innerResolveTypeElements(ctx, node, scope, typeParameters) {
  20170. var _a, _b;
  20171. if (node.leadingComments && node.leadingComments.some((c) => c.value.includes("@vue-ignore"))) {
  20172. return { props: {} };
  20173. }
  20174. switch (node.type) {
  20175. case "TSTypeLiteral":
  20176. return typeElementsToMap(ctx, node.members, scope, typeParameters);
  20177. case "TSInterfaceDeclaration":
  20178. return resolveInterfaceMembers(ctx, node, scope, typeParameters);
  20179. case "TSTypeAliasDeclaration":
  20180. case "TSTypeAnnotation":
  20181. case "TSParenthesizedType":
  20182. return resolveTypeElements(
  20183. ctx,
  20184. node.typeAnnotation,
  20185. scope,
  20186. typeParameters
  20187. );
  20188. case "TSFunctionType": {
  20189. return { props: {}, calls: [node] };
  20190. }
  20191. case "TSUnionType":
  20192. case "TSIntersectionType":
  20193. return mergeElements(
  20194. node.types.map((t) => resolveTypeElements(ctx, t, scope, typeParameters)),
  20195. node.type
  20196. );
  20197. case "TSMappedType":
  20198. return resolveMappedType(ctx, node, scope, typeParameters);
  20199. case "TSIndexedAccessType": {
  20200. const types = resolveIndexType(ctx, node, scope);
  20201. return mergeElements(
  20202. types.map((t) => resolveTypeElements(ctx, t, t._ownerScope)),
  20203. "TSUnionType"
  20204. );
  20205. }
  20206. case "TSExpressionWithTypeArguments":
  20207. // referenced by interface extends
  20208. case "TSTypeReference": {
  20209. const typeName = getReferenceName(node);
  20210. if ((typeName === "ExtractPropTypes" || typeName === "ExtractPublicPropTypes") && node.typeParameters && ((_a = scope.imports[typeName]) == null ? void 0 : _a.source) === "vue") {
  20211. return resolveExtractPropTypes(
  20212. resolveTypeElements(
  20213. ctx,
  20214. node.typeParameters.params[0],
  20215. scope,
  20216. typeParameters
  20217. ),
  20218. scope
  20219. );
  20220. }
  20221. const resolved = resolveTypeReference(ctx, node, scope);
  20222. if (resolved) {
  20223. let typeParams;
  20224. if ((resolved.type === "TSTypeAliasDeclaration" || resolved.type === "TSInterfaceDeclaration") && resolved.typeParameters && node.typeParameters) {
  20225. typeParams = /* @__PURE__ */ Object.create(null);
  20226. resolved.typeParameters.params.forEach((p, i) => {
  20227. let param = typeParameters && typeParameters[p.name];
  20228. if (!param) param = node.typeParameters.params[i];
  20229. typeParams[p.name] = param;
  20230. });
  20231. }
  20232. return resolveTypeElements(
  20233. ctx,
  20234. resolved,
  20235. resolved._ownerScope,
  20236. typeParams
  20237. );
  20238. } else {
  20239. if (typeof typeName === "string") {
  20240. if (typeParameters && typeParameters[typeName]) {
  20241. return resolveTypeElements(
  20242. ctx,
  20243. typeParameters[typeName],
  20244. scope,
  20245. typeParameters
  20246. );
  20247. }
  20248. if (
  20249. // @ts-expect-error
  20250. SupportedBuiltinsSet.has(typeName)
  20251. ) {
  20252. return resolveBuiltin(
  20253. ctx,
  20254. node,
  20255. typeName,
  20256. scope,
  20257. typeParameters
  20258. );
  20259. } else if (typeName === "ReturnType" && node.typeParameters) {
  20260. const ret = resolveReturnType(
  20261. ctx,
  20262. node.typeParameters.params[0],
  20263. scope
  20264. );
  20265. if (ret) {
  20266. return resolveTypeElements(ctx, ret, scope);
  20267. }
  20268. }
  20269. }
  20270. return ctx.error(
  20271. `Unresolvable type reference or unsupported built-in utility type`,
  20272. node,
  20273. scope
  20274. );
  20275. }
  20276. }
  20277. case "TSImportType": {
  20278. if (getId(node.argument) === "vue" && ((_b = node.qualifier) == null ? void 0 : _b.type) === "Identifier" && node.qualifier.name === "ExtractPropTypes" && node.typeParameters) {
  20279. return resolveExtractPropTypes(
  20280. resolveTypeElements(ctx, node.typeParameters.params[0], scope),
  20281. scope
  20282. );
  20283. }
  20284. const sourceScope = importSourceToScope(
  20285. ctx,
  20286. node.argument,
  20287. scope,
  20288. node.argument.value
  20289. );
  20290. const resolved = resolveTypeReference(ctx, node, sourceScope);
  20291. if (resolved) {
  20292. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  20293. }
  20294. break;
  20295. }
  20296. case "TSTypeQuery":
  20297. {
  20298. const resolved = resolveTypeReference(ctx, node, scope);
  20299. if (resolved) {
  20300. return resolveTypeElements(ctx, resolved, resolved._ownerScope);
  20301. }
  20302. }
  20303. break;
  20304. }
  20305. return ctx.error(`Unresolvable type: ${node.type}`, node, scope);
  20306. }
  20307. function typeElementsToMap(ctx, elements, scope = ctxToScope(ctx), typeParameters) {
  20308. const res = { props: {} };
  20309. for (const e of elements) {
  20310. if (e.type === "TSPropertySignature" || e.type === "TSMethodSignature") {
  20311. if (typeParameters) {
  20312. scope = createChildScope(scope);
  20313. scope.isGenericScope = true;
  20314. Object.assign(scope.types, typeParameters);
  20315. }
  20316. e._ownerScope = scope;
  20317. const name = getId(e.key);
  20318. if (name && !e.computed) {
  20319. res.props[name] = e;
  20320. } else if (e.key.type === "TemplateLiteral") {
  20321. for (const key of resolveTemplateKeys(ctx, e.key, scope)) {
  20322. res.props[key] = e;
  20323. }
  20324. } else {
  20325. ctx.error(
  20326. `Unsupported computed key in type referenced by a macro`,
  20327. e.key,
  20328. scope
  20329. );
  20330. }
  20331. } else if (e.type === "TSCallSignatureDeclaration") {
  20332. (res.calls || (res.calls = [])).push(e);
  20333. }
  20334. }
  20335. return res;
  20336. }
  20337. function mergeElements(maps, type) {
  20338. if (maps.length === 1) return maps[0];
  20339. const res = { props: {} };
  20340. const { props: baseProps } = res;
  20341. for (const { props, calls } of maps) {
  20342. for (const key in props) {
  20343. if (!shared.hasOwn(baseProps, key)) {
  20344. baseProps[key] = props[key];
  20345. } else {
  20346. baseProps[key] = createProperty(
  20347. baseProps[key].key,
  20348. {
  20349. type,
  20350. // @ts-expect-error
  20351. types: [baseProps[key], props[key]]
  20352. },
  20353. baseProps[key]._ownerScope,
  20354. baseProps[key].optional || props[key].optional
  20355. );
  20356. }
  20357. }
  20358. if (calls) {
  20359. (res.calls || (res.calls = [])).push(...calls);
  20360. }
  20361. }
  20362. return res;
  20363. }
  20364. function createProperty(key, typeAnnotation, scope, optional) {
  20365. return {
  20366. type: "TSPropertySignature",
  20367. key,
  20368. kind: "get",
  20369. optional,
  20370. typeAnnotation: {
  20371. type: "TSTypeAnnotation",
  20372. typeAnnotation
  20373. },
  20374. _ownerScope: scope
  20375. };
  20376. }
  20377. function resolveInterfaceMembers(ctx, node, scope, typeParameters) {
  20378. const base = typeElementsToMap(
  20379. ctx,
  20380. node.body.body,
  20381. node._ownerScope,
  20382. typeParameters
  20383. );
  20384. if (node.extends) {
  20385. for (const ext of node.extends) {
  20386. try {
  20387. const { props, calls } = resolveTypeElements(ctx, ext, scope);
  20388. for (const key in props) {
  20389. if (!shared.hasOwn(base.props, key)) {
  20390. base.props[key] = props[key];
  20391. }
  20392. }
  20393. if (calls) {
  20394. ;
  20395. (base.calls || (base.calls = [])).push(...calls);
  20396. }
  20397. } catch (e) {
  20398. ctx.error(
  20399. `Failed to resolve extends base type.
  20400. If this previously worked in 3.2, you can instruct the compiler to ignore this extend by adding /* @vue-ignore */ before it, for example:
  20401. interface Props extends /* @vue-ignore */ Base {}
  20402. Note: both in 3.2 or with the ignore, the properties in the base type are treated as fallthrough attrs at runtime.`,
  20403. ext,
  20404. scope
  20405. );
  20406. }
  20407. }
  20408. }
  20409. return base;
  20410. }
  20411. function resolveMappedType(ctx, node, scope, typeParameters) {
  20412. const res = { props: {} };
  20413. let keys;
  20414. if (node.nameType) {
  20415. const { name, constraint } = node.typeParameter;
  20416. scope = createChildScope(scope);
  20417. Object.assign(scope.types, { ...typeParameters, [name]: constraint });
  20418. keys = resolveStringType(ctx, node.nameType, scope);
  20419. } else {
  20420. keys = resolveStringType(ctx, node.typeParameter.constraint, scope);
  20421. }
  20422. for (const key of keys) {
  20423. res.props[key] = createProperty(
  20424. {
  20425. type: "Identifier",
  20426. name: key
  20427. },
  20428. node.typeAnnotation,
  20429. scope,
  20430. !!node.optional
  20431. );
  20432. }
  20433. return res;
  20434. }
  20435. function resolveIndexType(ctx, node, scope) {
  20436. var _a, _b;
  20437. if (node.indexType.type === "TSNumberKeyword") {
  20438. return resolveArrayElementType(ctx, node.objectType, scope);
  20439. }
  20440. const { indexType, objectType } = node;
  20441. const types = [];
  20442. let keys;
  20443. let resolved;
  20444. if (indexType.type === "TSStringKeyword") {
  20445. resolved = resolveTypeElements(ctx, objectType, scope);
  20446. keys = Object.keys(resolved.props);
  20447. } else {
  20448. keys = resolveStringType(ctx, indexType, scope);
  20449. resolved = resolveTypeElements(ctx, objectType, scope);
  20450. }
  20451. for (const key of keys) {
  20452. const targetType = (_b = (_a = resolved.props[key]) == null ? void 0 : _a.typeAnnotation) == null ? void 0 : _b.typeAnnotation;
  20453. if (targetType) {
  20454. targetType._ownerScope = resolved.props[key]._ownerScope;
  20455. types.push(targetType);
  20456. }
  20457. }
  20458. return types;
  20459. }
  20460. function resolveArrayElementType(ctx, node, scope) {
  20461. if (node.type === "TSArrayType") {
  20462. return [node.elementType];
  20463. }
  20464. if (node.type === "TSTupleType") {
  20465. return node.elementTypes.map(
  20466. (t) => t.type === "TSNamedTupleMember" ? t.elementType : t
  20467. );
  20468. }
  20469. if (node.type === "TSTypeReference") {
  20470. if (getReferenceName(node) === "Array" && node.typeParameters) {
  20471. return node.typeParameters.params;
  20472. } else {
  20473. const resolved = resolveTypeReference(ctx, node, scope);
  20474. if (resolved) {
  20475. return resolveArrayElementType(ctx, resolved, scope);
  20476. }
  20477. }
  20478. }
  20479. return ctx.error(
  20480. "Failed to resolve element type from target type",
  20481. node,
  20482. scope
  20483. );
  20484. }
  20485. function resolveStringType(ctx, node, scope, typeParameters) {
  20486. switch (node.type) {
  20487. case "StringLiteral":
  20488. return [node.value];
  20489. case "TSLiteralType":
  20490. return resolveStringType(ctx, node.literal, scope, typeParameters);
  20491. case "TSUnionType":
  20492. return node.types.map((t) => resolveStringType(ctx, t, scope, typeParameters)).flat();
  20493. case "TemplateLiteral": {
  20494. return resolveTemplateKeys(ctx, node, scope);
  20495. }
  20496. case "TSTypeReference": {
  20497. const resolved = resolveTypeReference(ctx, node, scope);
  20498. if (resolved) {
  20499. return resolveStringType(ctx, resolved, scope, typeParameters);
  20500. }
  20501. if (node.typeName.type === "Identifier") {
  20502. const name = node.typeName.name;
  20503. if (typeParameters && typeParameters[name]) {
  20504. return resolveStringType(
  20505. ctx,
  20506. typeParameters[name],
  20507. scope,
  20508. typeParameters
  20509. );
  20510. }
  20511. const getParam = (index = 0) => resolveStringType(
  20512. ctx,
  20513. node.typeParameters.params[index],
  20514. scope,
  20515. typeParameters
  20516. );
  20517. switch (name) {
  20518. case "Extract":
  20519. return getParam(1);
  20520. case "Exclude": {
  20521. const excluded = getParam(1);
  20522. return getParam().filter((s) => !excluded.includes(s));
  20523. }
  20524. case "Uppercase":
  20525. return getParam().map((s) => s.toUpperCase());
  20526. case "Lowercase":
  20527. return getParam().map((s) => s.toLowerCase());
  20528. case "Capitalize":
  20529. return getParam().map(shared.capitalize);
  20530. case "Uncapitalize":
  20531. return getParam().map((s) => s[0].toLowerCase() + s.slice(1));
  20532. default:
  20533. ctx.error(
  20534. "Unsupported type when resolving index type",
  20535. node.typeName,
  20536. scope
  20537. );
  20538. }
  20539. }
  20540. }
  20541. }
  20542. return ctx.error("Failed to resolve index type into finite keys", node, scope);
  20543. }
  20544. function resolveTemplateKeys(ctx, node, scope) {
  20545. if (!node.expressions.length) {
  20546. return [node.quasis[0].value.raw];
  20547. }
  20548. const res = [];
  20549. const e = node.expressions[0];
  20550. const q = node.quasis[0];
  20551. const leading = q ? q.value.raw : ``;
  20552. const resolved = resolveStringType(ctx, e, scope);
  20553. const restResolved = resolveTemplateKeys(
  20554. ctx,
  20555. {
  20556. ...node,
  20557. expressions: node.expressions.slice(1),
  20558. quasis: q ? node.quasis.slice(1) : node.quasis
  20559. },
  20560. scope
  20561. );
  20562. for (const r of resolved) {
  20563. for (const rr of restResolved) {
  20564. res.push(leading + r + rr);
  20565. }
  20566. }
  20567. return res;
  20568. }
  20569. const SupportedBuiltinsSet = /* @__PURE__ */ new Set([
  20570. "Partial",
  20571. "Required",
  20572. "Readonly",
  20573. "Pick",
  20574. "Omit"
  20575. ]);
  20576. function resolveBuiltin(ctx, node, name, scope, typeParameters) {
  20577. const t = resolveTypeElements(
  20578. ctx,
  20579. node.typeParameters.params[0],
  20580. scope,
  20581. typeParameters
  20582. );
  20583. switch (name) {
  20584. case "Partial": {
  20585. const res2 = { props: {}, calls: t.calls };
  20586. Object.keys(t.props).forEach((key) => {
  20587. res2.props[key] = { ...t.props[key], optional: true };
  20588. });
  20589. return res2;
  20590. }
  20591. case "Required": {
  20592. const res2 = { props: {}, calls: t.calls };
  20593. Object.keys(t.props).forEach((key) => {
  20594. res2.props[key] = { ...t.props[key], optional: false };
  20595. });
  20596. return res2;
  20597. }
  20598. case "Readonly":
  20599. return t;
  20600. case "Pick": {
  20601. const picked = resolveStringType(
  20602. ctx,
  20603. node.typeParameters.params[1],
  20604. scope,
  20605. typeParameters
  20606. );
  20607. const res2 = { props: {}, calls: t.calls };
  20608. for (const key of picked) {
  20609. res2.props[key] = t.props[key];
  20610. }
  20611. return res2;
  20612. }
  20613. case "Omit":
  20614. const omitted = resolveStringType(
  20615. ctx,
  20616. node.typeParameters.params[1],
  20617. scope,
  20618. typeParameters
  20619. );
  20620. const res = { props: {}, calls: t.calls };
  20621. for (const key in t.props) {
  20622. if (!omitted.includes(key)) {
  20623. res.props[key] = t.props[key];
  20624. }
  20625. }
  20626. return res;
  20627. }
  20628. }
  20629. function resolveTypeReference(ctx, node, scope, name, onlyExported = false) {
  20630. const canCache = !(scope == null ? void 0 : scope.isGenericScope);
  20631. if (canCache && node._resolvedReference) {
  20632. return node._resolvedReference;
  20633. }
  20634. const resolved = innerResolveTypeReference(
  20635. ctx,
  20636. scope || ctxToScope(ctx),
  20637. name || getReferenceName(node),
  20638. node,
  20639. onlyExported
  20640. );
  20641. return canCache ? node._resolvedReference = resolved : resolved;
  20642. }
  20643. function innerResolveTypeReference(ctx, scope, name, node, onlyExported) {
  20644. if (typeof name === "string") {
  20645. if (scope.imports[name]) {
  20646. return resolveTypeFromImport(ctx, node, name, scope);
  20647. } else {
  20648. const lookupSource = node.type === "TSTypeQuery" ? onlyExported ? scope.exportedDeclares : scope.declares : onlyExported ? scope.exportedTypes : scope.types;
  20649. if (lookupSource[name]) {
  20650. return lookupSource[name];
  20651. } else {
  20652. const globalScopes = resolveGlobalScope(ctx);
  20653. if (globalScopes) {
  20654. for (const s of globalScopes) {
  20655. const src = node.type === "TSTypeQuery" ? s.declares : s.types;
  20656. if (src[name]) {
  20657. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(s.filename);
  20658. return src[name];
  20659. }
  20660. }
  20661. }
  20662. }
  20663. }
  20664. } else {
  20665. let ns = innerResolveTypeReference(ctx, scope, name[0], node, onlyExported);
  20666. if (ns) {
  20667. if (ns.type !== "TSModuleDeclaration") {
  20668. ns = ns._ns;
  20669. }
  20670. if (ns) {
  20671. const childScope = moduleDeclToScope(ctx, ns, ns._ownerScope || scope);
  20672. return innerResolveTypeReference(
  20673. ctx,
  20674. childScope,
  20675. name.length > 2 ? name.slice(1) : name[name.length - 1],
  20676. node,
  20677. !ns.declare
  20678. );
  20679. }
  20680. }
  20681. }
  20682. }
  20683. function getReferenceName(node) {
  20684. const ref = node.type === "TSTypeReference" ? node.typeName : node.type === "TSExpressionWithTypeArguments" ? node.expression : node.type === "TSImportType" ? node.qualifier : node.exprName;
  20685. if ((ref == null ? void 0 : ref.type) === "Identifier") {
  20686. return ref.name;
  20687. } else if ((ref == null ? void 0 : ref.type) === "TSQualifiedName") {
  20688. return qualifiedNameToPath(ref);
  20689. } else {
  20690. return "default";
  20691. }
  20692. }
  20693. function qualifiedNameToPath(node) {
  20694. if (node.type === "Identifier") {
  20695. return [node.name];
  20696. } else {
  20697. return [...qualifiedNameToPath(node.left), node.right.name];
  20698. }
  20699. }
  20700. function resolveGlobalScope(ctx) {
  20701. if (ctx.options.globalTypeFiles) {
  20702. const fs = resolveFS(ctx);
  20703. if (!fs) {
  20704. throw new Error("[vue/compiler-sfc] globalTypeFiles requires fs access.");
  20705. }
  20706. return ctx.options.globalTypeFiles.map(
  20707. (file) => fileToScope(ctx, normalizePath(file), true)
  20708. );
  20709. }
  20710. }
  20711. let ts;
  20712. let loadTS;
  20713. function registerTS(_loadTS) {
  20714. loadTS = () => {
  20715. try {
  20716. return _loadTS();
  20717. } catch (err) {
  20718. if (typeof err.message === "string" && err.message.includes("Cannot find module")) {
  20719. throw new Error(
  20720. 'Failed to load TypeScript, which is required for resolving imported types. Please make sure "typescript" is installed as a project dependency.'
  20721. );
  20722. } else {
  20723. throw new Error(
  20724. "Failed to load TypeScript for resolving imported types."
  20725. );
  20726. }
  20727. }
  20728. };
  20729. }
  20730. function resolveFS(ctx) {
  20731. if (ctx.fs) {
  20732. return ctx.fs;
  20733. }
  20734. if (!ts && loadTS) {
  20735. ts = loadTS();
  20736. }
  20737. const fs = ctx.options.fs || (ts == null ? void 0 : ts.sys);
  20738. if (!fs) {
  20739. return;
  20740. }
  20741. return ctx.fs = {
  20742. fileExists(file) {
  20743. if (file.endsWith(".vue.ts") && !file.endsWith(".d.vue.ts")) {
  20744. file = file.replace(/\.ts$/, "");
  20745. }
  20746. return fs.fileExists(file);
  20747. },
  20748. readFile(file) {
  20749. if (file.endsWith(".vue.ts") && !file.endsWith(".d.vue.ts")) {
  20750. file = file.replace(/\.ts$/, "");
  20751. }
  20752. return fs.readFile(file);
  20753. },
  20754. realpath: fs.realpath
  20755. };
  20756. }
  20757. function resolveTypeFromImport(ctx, node, name, scope) {
  20758. const { source, imported } = scope.imports[name];
  20759. const sourceScope = importSourceToScope(ctx, node, scope, source);
  20760. return resolveTypeReference(ctx, node, sourceScope, imported, true);
  20761. }
  20762. function importSourceToScope(ctx, node, scope, source) {
  20763. let fs;
  20764. try {
  20765. fs = resolveFS(ctx);
  20766. } catch (err) {
  20767. return ctx.error(err.message, node, scope);
  20768. }
  20769. if (!fs) {
  20770. return ctx.error(
  20771. `No fs option provided to \`compileScript\` in non-Node environment. File system access is required for resolving imported types.`,
  20772. node,
  20773. scope
  20774. );
  20775. }
  20776. let resolved = scope.resolvedImportSources[source];
  20777. if (!resolved) {
  20778. if (source.startsWith("..")) {
  20779. const osSpecificJoinFn = process__namespace.platform === "win32" ? path$1.join : joinPaths;
  20780. const filename = osSpecificJoinFn(path$1.dirname(scope.filename), source);
  20781. resolved = resolveExt(filename, fs);
  20782. } else if (source[0] === ".") {
  20783. const filename = joinPaths(path$1.dirname(scope.filename), source);
  20784. resolved = resolveExt(filename, fs);
  20785. } else {
  20786. if (!ts) {
  20787. if (loadTS) ts = loadTS();
  20788. if (!ts) {
  20789. return ctx.error(
  20790. `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.`,
  20791. node,
  20792. scope
  20793. );
  20794. }
  20795. }
  20796. resolved = resolveWithTS(scope.filename, source, ts, fs);
  20797. }
  20798. if (resolved) {
  20799. resolved = scope.resolvedImportSources[source] = normalizePath(resolved);
  20800. }
  20801. }
  20802. if (resolved) {
  20803. (ctx.deps || (ctx.deps = /* @__PURE__ */ new Set())).add(resolved);
  20804. return fileToScope(ctx, resolved);
  20805. } else {
  20806. return ctx.error(
  20807. `Failed to resolve import source ${JSON.stringify(source)}.`,
  20808. node,
  20809. scope
  20810. );
  20811. }
  20812. }
  20813. function resolveExt(filename, fs) {
  20814. filename = filename.replace(/\.js$/, "");
  20815. const tryResolve = (filename2) => {
  20816. if (fs.fileExists(filename2)) return filename2;
  20817. };
  20818. return tryResolve(filename) || tryResolve(filename + `.ts`) || tryResolve(filename + `.tsx`) || tryResolve(filename + `.d.ts`) || tryResolve(joinPaths(filename, `index.ts`)) || tryResolve(joinPaths(filename, `index.tsx`)) || tryResolve(joinPaths(filename, `index.d.ts`));
  20819. }
  20820. const tsConfigCache = createCache();
  20821. const tsConfigRefMap = /* @__PURE__ */ new Map();
  20822. function resolveWithTS(containingFile, source, ts2, fs) {
  20823. var _a, _b;
  20824. const configPath = ts2.findConfigFile(containingFile, fs.fileExists);
  20825. let tsCompilerOptions;
  20826. let tsResolveCache;
  20827. if (configPath) {
  20828. let configs;
  20829. const normalizedConfigPath = normalizePath(configPath);
  20830. const cached = tsConfigCache.get(normalizedConfigPath);
  20831. if (!cached) {
  20832. configs = loadTSConfig(configPath, ts2, fs).map((config) => ({ config }));
  20833. tsConfigCache.set(normalizedConfigPath, configs);
  20834. } else {
  20835. configs = cached;
  20836. }
  20837. let matchedConfig;
  20838. if (configs.length === 1) {
  20839. matchedConfig = configs[0];
  20840. } else {
  20841. for (const c of configs) {
  20842. const base = normalizePath(
  20843. c.config.options.pathsBasePath || path$1.dirname(c.config.options.configFilePath)
  20844. );
  20845. const included = (_a = c.config.raw) == null ? void 0 : _a.include;
  20846. const excluded = (_b = c.config.raw) == null ? void 0 : _b.exclude;
  20847. if (!included && (!base || containingFile.startsWith(base)) || (included == null ? void 0 : included.some((p) => minimatch(containingFile, joinPaths(base, p))))) {
  20848. if (excluded && excluded.some((p) => minimatch(containingFile, joinPaths(base, p)))) {
  20849. continue;
  20850. }
  20851. matchedConfig = c;
  20852. break;
  20853. }
  20854. }
  20855. if (!matchedConfig) {
  20856. matchedConfig = configs[configs.length - 1];
  20857. }
  20858. }
  20859. tsCompilerOptions = matchedConfig.config.options;
  20860. tsResolveCache = matchedConfig.cache || (matchedConfig.cache = ts2.createModuleResolutionCache(
  20861. process__namespace.cwd(),
  20862. createGetCanonicalFileName(ts2.sys.useCaseSensitiveFileNames),
  20863. tsCompilerOptions
  20864. ));
  20865. } else {
  20866. tsCompilerOptions = {};
  20867. }
  20868. const res = ts2.resolveModuleName(
  20869. source,
  20870. containingFile,
  20871. tsCompilerOptions,
  20872. fs,
  20873. tsResolveCache
  20874. );
  20875. if (res.resolvedModule) {
  20876. let filename = res.resolvedModule.resolvedFileName;
  20877. if (filename.endsWith(".vue.ts") && !filename.endsWith(".d.vue.ts")) {
  20878. filename = filename.replace(/\.ts$/, "");
  20879. }
  20880. return fs.realpath ? fs.realpath(filename) : filename;
  20881. }
  20882. }
  20883. function loadTSConfig(configPath, ts2, fs, visited = /* @__PURE__ */ new Set()) {
  20884. const parseConfigHost = ts2.sys;
  20885. const config = ts2.parseJsonConfigFileContent(
  20886. ts2.readConfigFile(configPath, fs.readFile).config,
  20887. parseConfigHost,
  20888. path$1.dirname(configPath),
  20889. void 0,
  20890. configPath
  20891. );
  20892. const res = [config];
  20893. visited.add(configPath);
  20894. if (config.projectReferences) {
  20895. for (const ref of config.projectReferences) {
  20896. const refPath = ts2.resolveProjectReferencePath(ref);
  20897. if (visited.has(refPath) || !fs.fileExists(refPath)) {
  20898. continue;
  20899. }
  20900. tsConfigRefMap.set(refPath, configPath);
  20901. res.unshift(...loadTSConfig(refPath, ts2, fs, visited));
  20902. }
  20903. }
  20904. return res;
  20905. }
  20906. const fileToScopeCache = createCache();
  20907. function invalidateTypeCache(filename) {
  20908. filename = normalizePath(filename);
  20909. fileToScopeCache.delete(filename);
  20910. tsConfigCache.delete(filename);
  20911. const affectedConfig = tsConfigRefMap.get(filename);
  20912. if (affectedConfig) tsConfigCache.delete(affectedConfig);
  20913. }
  20914. function fileToScope(ctx, filename, asGlobal = false) {
  20915. const cached = fileToScopeCache.get(filename);
  20916. if (cached) {
  20917. return cached;
  20918. }
  20919. const fs = resolveFS(ctx);
  20920. const source = fs.readFile(filename) || "";
  20921. const body = parseFile(filename, source, fs, ctx.options.babelParserPlugins);
  20922. const scope = new TypeScope(filename, source, 0, recordImports(body));
  20923. recordTypes(ctx, body, scope, asGlobal);
  20924. fileToScopeCache.set(filename, scope);
  20925. return scope;
  20926. }
  20927. function parseFile(filename, content, fs, parserPlugins) {
  20928. const ext = path$1.extname(filename);
  20929. if (ext === ".ts" || ext === ".mts" || ext === ".tsx" || ext === ".mtsx") {
  20930. return parser$2.parse(content, {
  20931. plugins: resolveParserPlugins(
  20932. ext.slice(1),
  20933. parserPlugins,
  20934. /\.d\.m?ts$/.test(filename)
  20935. ),
  20936. sourceType: "module"
  20937. }).program.body;
  20938. }
  20939. const isUnknownTypeSource = !/\.[cm]?[tj]sx?$/.test(filename);
  20940. const arbitraryTypeSource = `${filename.slice(0, -ext.length)}.d${ext}.ts`;
  20941. const hasArbitraryTypeDeclaration = isUnknownTypeSource && fs.fileExists(arbitraryTypeSource);
  20942. if (hasArbitraryTypeDeclaration) {
  20943. return parser$2.parse(fs.readFile(arbitraryTypeSource), {
  20944. plugins: resolveParserPlugins("ts", parserPlugins, true),
  20945. sourceType: "module"
  20946. }).program.body;
  20947. }
  20948. if (ext === ".vue") {
  20949. const {
  20950. descriptor: { script, scriptSetup }
  20951. } = parse$1(content);
  20952. if (!script && !scriptSetup) {
  20953. return [];
  20954. }
  20955. const scriptOffset = script ? script.loc.start.offset : Infinity;
  20956. const scriptSetupOffset = scriptSetup ? scriptSetup.loc.start.offset : Infinity;
  20957. const firstBlock = scriptOffset < scriptSetupOffset ? script : scriptSetup;
  20958. const secondBlock = scriptOffset < scriptSetupOffset ? scriptSetup : script;
  20959. let scriptContent = " ".repeat(Math.min(scriptOffset, scriptSetupOffset)) + firstBlock.content;
  20960. if (secondBlock) {
  20961. scriptContent += " ".repeat(secondBlock.loc.start.offset - script.loc.end.offset) + secondBlock.content;
  20962. }
  20963. const lang = (script == null ? void 0 : script.lang) || (scriptSetup == null ? void 0 : scriptSetup.lang);
  20964. return parser$2.parse(scriptContent, {
  20965. plugins: resolveParserPlugins(lang, parserPlugins),
  20966. sourceType: "module"
  20967. }).program.body;
  20968. }
  20969. return [];
  20970. }
  20971. function ctxToScope(ctx) {
  20972. if (ctx.scope) {
  20973. return ctx.scope;
  20974. }
  20975. const body = "ast" in ctx ? ctx.ast : ctx.scriptAst ? [...ctx.scriptAst.body, ...ctx.scriptSetupAst.body] : ctx.scriptSetupAst.body;
  20976. const scope = new TypeScope(
  20977. ctx.filename,
  20978. ctx.source,
  20979. "startOffset" in ctx ? ctx.startOffset : 0,
  20980. "userImports" in ctx ? Object.create(ctx.userImports) : recordImports(body)
  20981. );
  20982. recordTypes(ctx, body, scope);
  20983. return ctx.scope = scope;
  20984. }
  20985. function moduleDeclToScope(ctx, node, parentScope) {
  20986. if (node._resolvedChildScope) {
  20987. return node._resolvedChildScope;
  20988. }
  20989. const scope = createChildScope(parentScope);
  20990. if (node.body.type === "TSModuleDeclaration") {
  20991. const decl = node.body;
  20992. decl._ownerScope = scope;
  20993. const id = getId(decl.id);
  20994. scope.types[id] = scope.exportedTypes[id] = decl;
  20995. } else {
  20996. recordTypes(ctx, node.body.body, scope);
  20997. }
  20998. return node._resolvedChildScope = scope;
  20999. }
  21000. function createChildScope(parentScope) {
  21001. return new TypeScope(
  21002. parentScope.filename,
  21003. parentScope.source,
  21004. parentScope.offset,
  21005. Object.create(parentScope.imports),
  21006. Object.create(parentScope.types),
  21007. Object.create(parentScope.declares)
  21008. );
  21009. }
  21010. const importExportRE = /^Import|^Export/;
  21011. function recordTypes(ctx, body, scope, asGlobal = false) {
  21012. const { types, declares, exportedTypes, exportedDeclares, imports } = scope;
  21013. const isAmbient = asGlobal ? !body.some((s) => importExportRE.test(s.type)) : false;
  21014. for (const stmt of body) {
  21015. if (asGlobal) {
  21016. if (isAmbient) {
  21017. if (stmt.declare) {
  21018. recordType(stmt, types, declares);
  21019. }
  21020. } else if (stmt.type === "TSModuleDeclaration" && stmt.global) {
  21021. for (const s of stmt.body.body) {
  21022. recordType(s, types, declares);
  21023. }
  21024. }
  21025. } else {
  21026. recordType(stmt, types, declares);
  21027. }
  21028. }
  21029. if (!asGlobal) {
  21030. for (const stmt of body) {
  21031. if (stmt.type === "ExportNamedDeclaration") {
  21032. if (stmt.declaration) {
  21033. recordType(stmt.declaration, types, declares);
  21034. recordType(stmt.declaration, exportedTypes, exportedDeclares);
  21035. } else {
  21036. for (const spec of stmt.specifiers) {
  21037. if (spec.type === "ExportSpecifier") {
  21038. const local = spec.local.name;
  21039. const exported = getId(spec.exported);
  21040. if (stmt.source) {
  21041. imports[exported] = {
  21042. source: stmt.source.value,
  21043. imported: local
  21044. };
  21045. exportedTypes[exported] = {
  21046. type: "TSTypeReference",
  21047. typeName: {
  21048. type: "Identifier",
  21049. name: local
  21050. },
  21051. _ownerScope: scope
  21052. };
  21053. } else if (types[local]) {
  21054. exportedTypes[exported] = types[local];
  21055. }
  21056. }
  21057. }
  21058. }
  21059. } else if (stmt.type === "ExportAllDeclaration") {
  21060. const sourceScope = importSourceToScope(
  21061. ctx,
  21062. stmt.source,
  21063. scope,
  21064. stmt.source.value
  21065. );
  21066. Object.assign(scope.exportedTypes, sourceScope.exportedTypes);
  21067. } else if (stmt.type === "ExportDefaultDeclaration" && stmt.declaration) {
  21068. if (stmt.declaration.type !== "Identifier") {
  21069. recordType(stmt.declaration, types, declares, "default");
  21070. recordType(
  21071. stmt.declaration,
  21072. exportedTypes,
  21073. exportedDeclares,
  21074. "default"
  21075. );
  21076. } else if (types[stmt.declaration.name]) {
  21077. exportedTypes["default"] = types[stmt.declaration.name];
  21078. }
  21079. }
  21080. }
  21081. }
  21082. for (const key of Object.keys(types)) {
  21083. const node = types[key];
  21084. node._ownerScope = scope;
  21085. if (node._ns) node._ns._ownerScope = scope;
  21086. }
  21087. for (const key of Object.keys(declares)) {
  21088. declares[key]._ownerScope = scope;
  21089. }
  21090. }
  21091. function recordType(node, types, declares, overwriteId) {
  21092. switch (node.type) {
  21093. case "TSInterfaceDeclaration":
  21094. case "TSEnumDeclaration":
  21095. case "TSModuleDeclaration": {
  21096. const id = overwriteId || getId(node.id);
  21097. let existing = types[id];
  21098. if (existing) {
  21099. if (node.type === "TSModuleDeclaration") {
  21100. if (existing.type === "TSModuleDeclaration") {
  21101. mergeNamespaces(existing, node);
  21102. } else {
  21103. attachNamespace(existing, node);
  21104. }
  21105. break;
  21106. }
  21107. if (existing.type === "TSModuleDeclaration") {
  21108. types[id] = node;
  21109. attachNamespace(node, existing);
  21110. break;
  21111. }
  21112. if (existing.type !== node.type) {
  21113. break;
  21114. }
  21115. if (node.type === "TSInterfaceDeclaration") {
  21116. existing.body.body.push(...node.body.body);
  21117. } else {
  21118. existing.members.push(...node.members);
  21119. }
  21120. } else {
  21121. types[id] = node;
  21122. }
  21123. break;
  21124. }
  21125. case "ClassDeclaration":
  21126. if (overwriteId || node.id) types[overwriteId || getId(node.id)] = node;
  21127. break;
  21128. case "TSTypeAliasDeclaration":
  21129. types[node.id.name] = node.typeParameters ? node : node.typeAnnotation;
  21130. break;
  21131. case "TSDeclareFunction":
  21132. if (node.id) declares[node.id.name] = node;
  21133. break;
  21134. case "VariableDeclaration": {
  21135. if (node.declare) {
  21136. for (const decl of node.declarations) {
  21137. if (decl.id.type === "Identifier" && decl.id.typeAnnotation) {
  21138. declares[decl.id.name] = decl.id.typeAnnotation.typeAnnotation;
  21139. }
  21140. }
  21141. }
  21142. break;
  21143. }
  21144. }
  21145. }
  21146. function mergeNamespaces(to, from) {
  21147. const toBody = to.body;
  21148. const fromBody = from.body;
  21149. if (toBody.type === "TSModuleDeclaration") {
  21150. if (fromBody.type === "TSModuleDeclaration") {
  21151. mergeNamespaces(toBody, fromBody);
  21152. } else {
  21153. fromBody.body.push({
  21154. type: "ExportNamedDeclaration",
  21155. declaration: toBody,
  21156. exportKind: "type",
  21157. specifiers: []
  21158. });
  21159. }
  21160. } else if (fromBody.type === "TSModuleDeclaration") {
  21161. toBody.body.push({
  21162. type: "ExportNamedDeclaration",
  21163. declaration: fromBody,
  21164. exportKind: "type",
  21165. specifiers: []
  21166. });
  21167. } else {
  21168. toBody.body.push(...fromBody.body);
  21169. }
  21170. }
  21171. function attachNamespace(to, ns) {
  21172. if (!to._ns) {
  21173. to._ns = ns;
  21174. } else {
  21175. mergeNamespaces(to._ns, ns);
  21176. }
  21177. }
  21178. function recordImports(body) {
  21179. const imports = /* @__PURE__ */ Object.create(null);
  21180. for (const s of body) {
  21181. recordImport(s, imports);
  21182. }
  21183. return imports;
  21184. }
  21185. function recordImport(node, imports) {
  21186. if (node.type !== "ImportDeclaration") {
  21187. return;
  21188. }
  21189. for (const s of node.specifiers) {
  21190. imports[s.local.name] = {
  21191. imported: getImportedName(s),
  21192. source: node.source.value
  21193. };
  21194. }
  21195. }
  21196. function inferRuntimeType(ctx, node, scope = node._ownerScope || ctxToScope(ctx), isKeyOf = false) {
  21197. try {
  21198. switch (node.type) {
  21199. case "TSStringKeyword":
  21200. return ["String"];
  21201. case "TSNumberKeyword":
  21202. return ["Number"];
  21203. case "TSBooleanKeyword":
  21204. return ["Boolean"];
  21205. case "TSObjectKeyword":
  21206. return ["Object"];
  21207. case "TSNullKeyword":
  21208. return ["null"];
  21209. case "TSTypeLiteral":
  21210. case "TSInterfaceDeclaration": {
  21211. const types = /* @__PURE__ */ new Set();
  21212. const members = node.type === "TSTypeLiteral" ? node.members : node.body.body;
  21213. for (const m of members) {
  21214. if (isKeyOf) {
  21215. if (m.type === "TSPropertySignature" && m.key.type === "NumericLiteral") {
  21216. types.add("Number");
  21217. } else if (m.type === "TSIndexSignature") {
  21218. const annotation = m.parameters[0].typeAnnotation;
  21219. if (annotation && annotation.type !== "Noop") {
  21220. const type = inferRuntimeType(
  21221. ctx,
  21222. annotation.typeAnnotation,
  21223. scope
  21224. )[0];
  21225. if (type === UNKNOWN_TYPE) return [UNKNOWN_TYPE];
  21226. types.add(type);
  21227. }
  21228. } else {
  21229. types.add("String");
  21230. }
  21231. } else if (m.type === "TSCallSignatureDeclaration" || m.type === "TSConstructSignatureDeclaration") {
  21232. types.add("Function");
  21233. } else {
  21234. types.add("Object");
  21235. }
  21236. }
  21237. return types.size ? Array.from(types) : [isKeyOf ? UNKNOWN_TYPE : "Object"];
  21238. }
  21239. case "TSPropertySignature":
  21240. if (node.typeAnnotation) {
  21241. return inferRuntimeType(
  21242. ctx,
  21243. node.typeAnnotation.typeAnnotation,
  21244. scope
  21245. );
  21246. }
  21247. break;
  21248. case "TSMethodSignature":
  21249. case "TSFunctionType":
  21250. return ["Function"];
  21251. case "TSArrayType":
  21252. case "TSTupleType":
  21253. return ["Array"];
  21254. case "TSLiteralType":
  21255. switch (node.literal.type) {
  21256. case "StringLiteral":
  21257. return ["String"];
  21258. case "BooleanLiteral":
  21259. return ["Boolean"];
  21260. case "NumericLiteral":
  21261. case "BigIntLiteral":
  21262. return ["Number"];
  21263. default:
  21264. return [UNKNOWN_TYPE];
  21265. }
  21266. case "TSTypeReference": {
  21267. const resolved = resolveTypeReference(ctx, node, scope);
  21268. if (resolved) {
  21269. if (resolved.type === "TSTypeAliasDeclaration" && resolved.typeAnnotation.type === "TSFunctionType") {
  21270. return ["Function"];
  21271. }
  21272. return inferRuntimeType(ctx, resolved, resolved._ownerScope, isKeyOf);
  21273. }
  21274. if (node.typeName.type === "Identifier") {
  21275. if (isKeyOf) {
  21276. switch (node.typeName.name) {
  21277. case "String":
  21278. case "Array":
  21279. case "ArrayLike":
  21280. case "Parameters":
  21281. case "ConstructorParameters":
  21282. case "ReadonlyArray":
  21283. return ["String", "Number"];
  21284. // TS built-in utility types
  21285. case "Record":
  21286. case "Partial":
  21287. case "Required":
  21288. case "Readonly":
  21289. if (node.typeParameters && node.typeParameters.params[0]) {
  21290. return inferRuntimeType(
  21291. ctx,
  21292. node.typeParameters.params[0],
  21293. scope,
  21294. true
  21295. );
  21296. }
  21297. break;
  21298. case "Pick":
  21299. case "Extract":
  21300. if (node.typeParameters && node.typeParameters.params[1]) {
  21301. return inferRuntimeType(
  21302. ctx,
  21303. node.typeParameters.params[1],
  21304. scope
  21305. );
  21306. }
  21307. break;
  21308. case "Function":
  21309. case "Object":
  21310. case "Set":
  21311. case "Map":
  21312. case "WeakSet":
  21313. case "WeakMap":
  21314. case "Date":
  21315. case "Promise":
  21316. case "Error":
  21317. case "Uppercase":
  21318. case "Lowercase":
  21319. case "Capitalize":
  21320. case "Uncapitalize":
  21321. case "ReadonlyMap":
  21322. case "ReadonlySet":
  21323. return ["String"];
  21324. }
  21325. } else {
  21326. switch (node.typeName.name) {
  21327. case "Array":
  21328. case "Function":
  21329. case "Object":
  21330. case "Set":
  21331. case "Map":
  21332. case "WeakSet":
  21333. case "WeakMap":
  21334. case "Date":
  21335. case "Promise":
  21336. case "Error":
  21337. return [node.typeName.name];
  21338. // TS built-in utility types
  21339. // https://www.typescriptlang.org/docs/handbook/utility-types.html
  21340. case "Partial":
  21341. case "Required":
  21342. case "Readonly":
  21343. case "Record":
  21344. case "Pick":
  21345. case "Omit":
  21346. case "InstanceType":
  21347. return ["Object"];
  21348. case "Uppercase":
  21349. case "Lowercase":
  21350. case "Capitalize":
  21351. case "Uncapitalize":
  21352. return ["String"];
  21353. case "Parameters":
  21354. case "ConstructorParameters":
  21355. case "ReadonlyArray":
  21356. return ["Array"];
  21357. case "ReadonlyMap":
  21358. return ["Map"];
  21359. case "ReadonlySet":
  21360. return ["Set"];
  21361. case "NonNullable":
  21362. if (node.typeParameters && node.typeParameters.params[0]) {
  21363. return inferRuntimeType(
  21364. ctx,
  21365. node.typeParameters.params[0],
  21366. scope
  21367. ).filter((t) => t !== "null");
  21368. }
  21369. break;
  21370. case "Extract":
  21371. if (node.typeParameters && node.typeParameters.params[1]) {
  21372. return inferRuntimeType(
  21373. ctx,
  21374. node.typeParameters.params[1],
  21375. scope
  21376. );
  21377. }
  21378. break;
  21379. case "Exclude":
  21380. case "OmitThisParameter":
  21381. if (node.typeParameters && node.typeParameters.params[0]) {
  21382. return inferRuntimeType(
  21383. ctx,
  21384. node.typeParameters.params[0],
  21385. scope
  21386. );
  21387. }
  21388. break;
  21389. }
  21390. }
  21391. }
  21392. break;
  21393. }
  21394. case "TSParenthesizedType":
  21395. return inferRuntimeType(ctx, node.typeAnnotation, scope);
  21396. case "TSUnionType":
  21397. return flattenTypes(ctx, node.types, scope, isKeyOf);
  21398. case "TSIntersectionType": {
  21399. return flattenTypes(ctx, node.types, scope, isKeyOf).filter(
  21400. (t) => t !== UNKNOWN_TYPE
  21401. );
  21402. }
  21403. case "TSEnumDeclaration":
  21404. return inferEnumType(node);
  21405. case "TSSymbolKeyword":
  21406. return ["Symbol"];
  21407. case "TSIndexedAccessType": {
  21408. const types = resolveIndexType(ctx, node, scope);
  21409. return flattenTypes(ctx, types, scope, isKeyOf);
  21410. }
  21411. case "ClassDeclaration":
  21412. return ["Object"];
  21413. case "TSImportType": {
  21414. const sourceScope = importSourceToScope(
  21415. ctx,
  21416. node.argument,
  21417. scope,
  21418. node.argument.value
  21419. );
  21420. const resolved = resolveTypeReference(ctx, node, sourceScope);
  21421. if (resolved) {
  21422. return inferRuntimeType(ctx, resolved, resolved._ownerScope);
  21423. }
  21424. break;
  21425. }
  21426. case "TSTypeQuery": {
  21427. const id = node.exprName;
  21428. if (id.type === "Identifier") {
  21429. const matched = scope.declares[id.name];
  21430. if (matched) {
  21431. return inferRuntimeType(ctx, matched, matched._ownerScope, isKeyOf);
  21432. }
  21433. }
  21434. break;
  21435. }
  21436. // e.g. readonly
  21437. case "TSTypeOperator": {
  21438. return inferRuntimeType(
  21439. ctx,
  21440. node.typeAnnotation,
  21441. scope,
  21442. node.operator === "keyof"
  21443. );
  21444. }
  21445. case "TSAnyKeyword": {
  21446. if (isKeyOf) {
  21447. return ["String", "Number", "Symbol"];
  21448. }
  21449. break;
  21450. }
  21451. }
  21452. } catch (e) {
  21453. }
  21454. return [UNKNOWN_TYPE];
  21455. }
  21456. function flattenTypes(ctx, types, scope, isKeyOf = false) {
  21457. if (types.length === 1) {
  21458. return inferRuntimeType(ctx, types[0], scope, isKeyOf);
  21459. }
  21460. return [
  21461. ...new Set(
  21462. [].concat(
  21463. ...types.map((t) => inferRuntimeType(ctx, t, scope, isKeyOf))
  21464. )
  21465. )
  21466. ];
  21467. }
  21468. function inferEnumType(node) {
  21469. const types = /* @__PURE__ */ new Set();
  21470. for (const m of node.members) {
  21471. if (m.initializer) {
  21472. switch (m.initializer.type) {
  21473. case "StringLiteral":
  21474. types.add("String");
  21475. break;
  21476. case "NumericLiteral":
  21477. types.add("Number");
  21478. break;
  21479. }
  21480. }
  21481. }
  21482. return types.size ? [...types] : ["Number"];
  21483. }
  21484. function resolveExtractPropTypes({ props }, scope) {
  21485. const res = { props: {} };
  21486. for (const key in props) {
  21487. const raw = props[key];
  21488. res.props[key] = reverseInferType(
  21489. raw.key,
  21490. raw.typeAnnotation.typeAnnotation,
  21491. scope
  21492. );
  21493. }
  21494. return res;
  21495. }
  21496. function reverseInferType(key, node, scope, optional = true, checkObjectSyntax = true) {
  21497. if (checkObjectSyntax && node.type === "TSTypeLiteral") {
  21498. const typeType = findStaticPropertyType(node, "type");
  21499. if (typeType) {
  21500. const requiredType = findStaticPropertyType(node, "required");
  21501. const optional2 = requiredType && requiredType.type === "TSLiteralType" && requiredType.literal.type === "BooleanLiteral" ? !requiredType.literal.value : true;
  21502. return reverseInferType(key, typeType, scope, optional2, false);
  21503. }
  21504. } else if (node.type === "TSTypeReference" && node.typeName.type === "Identifier") {
  21505. if (node.typeName.name.endsWith("Constructor")) {
  21506. return createProperty(
  21507. key,
  21508. ctorToType(node.typeName.name),
  21509. scope,
  21510. optional
  21511. );
  21512. } else if (node.typeName.name === "PropType" && node.typeParameters) {
  21513. return createProperty(key, node.typeParameters.params[0], scope, optional);
  21514. }
  21515. }
  21516. if ((node.type === "TSTypeReference" || node.type === "TSImportType") && node.typeParameters) {
  21517. for (const t of node.typeParameters.params) {
  21518. const inferred = reverseInferType(key, t, scope, optional);
  21519. if (inferred) return inferred;
  21520. }
  21521. }
  21522. return createProperty(key, { type: `TSNullKeyword` }, scope, optional);
  21523. }
  21524. function ctorToType(ctorType) {
  21525. const ctor = ctorType.slice(0, -11);
  21526. switch (ctor) {
  21527. case "String":
  21528. case "Number":
  21529. case "Boolean":
  21530. return { type: `TS${ctor}Keyword` };
  21531. case "Array":
  21532. case "Function":
  21533. case "Object":
  21534. case "Set":
  21535. case "Map":
  21536. case "WeakSet":
  21537. case "WeakMap":
  21538. case "Date":
  21539. case "Promise":
  21540. return {
  21541. type: "TSTypeReference",
  21542. typeName: { type: "Identifier", name: ctor }
  21543. };
  21544. }
  21545. return { type: `TSNullKeyword` };
  21546. }
  21547. function findStaticPropertyType(node, key) {
  21548. const prop = node.members.find(
  21549. (m) => m.type === "TSPropertySignature" && !m.computed && getId(m.key) === key && m.typeAnnotation
  21550. );
  21551. return prop && prop.typeAnnotation.typeAnnotation;
  21552. }
  21553. function resolveReturnType(ctx, arg, scope) {
  21554. var _a;
  21555. let resolved = arg;
  21556. if (arg.type === "TSTypeReference" || arg.type === "TSTypeQuery" || arg.type === "TSImportType") {
  21557. resolved = resolveTypeReference(ctx, arg, scope);
  21558. }
  21559. if (!resolved) return;
  21560. if (resolved.type === "TSFunctionType") {
  21561. return (_a = resolved.typeAnnotation) == null ? void 0 : _a.typeAnnotation;
  21562. }
  21563. if (resolved.type === "TSDeclareFunction") {
  21564. return resolved.returnType;
  21565. }
  21566. }
  21567. function resolveUnionType(ctx, node, scope) {
  21568. if (node.type === "TSTypeReference") {
  21569. const resolved = resolveTypeReference(ctx, node, scope);
  21570. if (resolved) node = resolved;
  21571. }
  21572. let types;
  21573. if (node.type === "TSUnionType") {
  21574. types = node.types.flatMap((node2) => resolveUnionType(ctx, node2, scope));
  21575. } else {
  21576. types = [node];
  21577. }
  21578. return types;
  21579. }
  21580. const DEFINE_MODEL = "defineModel";
  21581. function processDefineModel(ctx, node, declId) {
  21582. if (!isCallOf(node, DEFINE_MODEL)) {
  21583. return false;
  21584. }
  21585. ctx.hasDefineModelCall = true;
  21586. const type = node.typeParameters && node.typeParameters.params[0] || void 0;
  21587. let modelName;
  21588. let options;
  21589. const arg0 = node.arguments[0] && CompilerDOM.unwrapTSNode(node.arguments[0]);
  21590. const hasName = arg0 && arg0.type === "StringLiteral";
  21591. if (hasName) {
  21592. modelName = arg0.value;
  21593. options = node.arguments[1];
  21594. } else {
  21595. modelName = "modelValue";
  21596. options = arg0;
  21597. }
  21598. if (ctx.modelDecls[modelName]) {
  21599. ctx.error(`duplicate model name ${JSON.stringify(modelName)}`, node);
  21600. }
  21601. let optionsString = options && ctx.getString(options);
  21602. let optionsRemoved = !options;
  21603. const runtimeOptionNodes = [];
  21604. if (options && options.type === "ObjectExpression" && !options.properties.some((p) => p.type === "SpreadElement" || p.computed)) {
  21605. let removed = 0;
  21606. for (let i = options.properties.length - 1; i >= 0; i--) {
  21607. const p = options.properties[i];
  21608. const next = options.properties[i + 1];
  21609. const start = p.start;
  21610. const end = next ? next.start : options.end - 1;
  21611. 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"))) {
  21612. optionsString = optionsString.slice(0, start - options.start) + optionsString.slice(end - options.start);
  21613. } else {
  21614. removed++;
  21615. ctx.s.remove(ctx.startOffset + start, ctx.startOffset + end);
  21616. runtimeOptionNodes.push(p);
  21617. }
  21618. }
  21619. if (removed === options.properties.length) {
  21620. optionsRemoved = true;
  21621. ctx.s.remove(
  21622. ctx.startOffset + (hasName ? arg0.end : options.start),
  21623. ctx.startOffset + options.end
  21624. );
  21625. }
  21626. }
  21627. ctx.modelDecls[modelName] = {
  21628. type,
  21629. options: optionsString,
  21630. runtimeOptionNodes,
  21631. identifier: declId && declId.type === "Identifier" ? declId.name : void 0
  21632. };
  21633. ctx.bindingMetadata[modelName] = "props";
  21634. ctx.s.overwrite(
  21635. ctx.startOffset + node.callee.start,
  21636. ctx.startOffset + node.callee.end,
  21637. ctx.helper("useModel")
  21638. );
  21639. ctx.s.appendLeft(
  21640. ctx.startOffset + (node.arguments.length ? node.arguments[0].start : node.end - 1),
  21641. `__props, ` + (hasName ? `` : `${JSON.stringify(modelName)}${optionsRemoved ? `` : `, `}`)
  21642. );
  21643. return true;
  21644. }
  21645. function genModelProps(ctx) {
  21646. if (!ctx.hasDefineModelCall) return;
  21647. const isProd = !!ctx.options.isProd;
  21648. let modelPropsDecl = "";
  21649. for (const [name, { type, options: runtimeOptions }] of Object.entries(
  21650. ctx.modelDecls
  21651. )) {
  21652. let skipCheck = false;
  21653. let codegenOptions = ``;
  21654. let runtimeTypes = type && inferRuntimeType(ctx, type);
  21655. if (runtimeTypes) {
  21656. const hasBoolean = runtimeTypes.includes("Boolean");
  21657. const hasFunction = runtimeTypes.includes("Function");
  21658. const hasUnknownType = runtimeTypes.includes(UNKNOWN_TYPE);
  21659. if (hasUnknownType) {
  21660. if (hasBoolean || hasFunction) {
  21661. runtimeTypes = runtimeTypes.filter((t) => t !== UNKNOWN_TYPE);
  21662. skipCheck = true;
  21663. } else {
  21664. runtimeTypes = ["null"];
  21665. }
  21666. }
  21667. if (!isProd) {
  21668. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}` + (skipCheck ? ", skipCheck: true" : "");
  21669. } else if (hasBoolean || runtimeOptions && hasFunction) {
  21670. codegenOptions = `type: ${toRuntimeTypeString(runtimeTypes)}`;
  21671. } else ;
  21672. }
  21673. let decl;
  21674. if (codegenOptions && runtimeOptions) {
  21675. decl = ctx.isTS ? `{ ${codegenOptions}, ...${runtimeOptions} }` : `Object.assign({ ${codegenOptions} }, ${runtimeOptions})`;
  21676. } else if (codegenOptions) {
  21677. decl = `{ ${codegenOptions} }`;
  21678. } else if (runtimeOptions) {
  21679. decl = runtimeOptions;
  21680. } else {
  21681. decl = `{}`;
  21682. }
  21683. modelPropsDecl += `
  21684. ${JSON.stringify(name)}: ${decl},`;
  21685. const modifierPropName = JSON.stringify(
  21686. name === "modelValue" ? `modelModifiers` : `${name}Modifiers`
  21687. );
  21688. modelPropsDecl += `
  21689. ${modifierPropName}: {},`;
  21690. }
  21691. return `{${modelPropsDecl}
  21692. }`;
  21693. }
  21694. const DEFINE_PROPS = "defineProps";
  21695. const WITH_DEFAULTS = "withDefaults";
  21696. function processDefineProps(ctx, node, declId, isWithDefaults = false) {
  21697. if (!isCallOf(node, DEFINE_PROPS)) {
  21698. return processWithDefaults(ctx, node, declId);
  21699. }
  21700. if (ctx.hasDefinePropsCall) {
  21701. ctx.error(`duplicate ${DEFINE_PROPS}() call`, node);
  21702. }
  21703. ctx.hasDefinePropsCall = true;
  21704. ctx.propsRuntimeDecl = node.arguments[0];
  21705. if (ctx.propsRuntimeDecl) {
  21706. for (const key of getObjectOrArrayExpressionKeys(ctx.propsRuntimeDecl)) {
  21707. if (!(key in ctx.bindingMetadata)) {
  21708. ctx.bindingMetadata[key] = "props";
  21709. }
  21710. }
  21711. }
  21712. if (node.typeParameters) {
  21713. if (ctx.propsRuntimeDecl) {
  21714. ctx.error(
  21715. `${DEFINE_PROPS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  21716. node
  21717. );
  21718. }
  21719. ctx.propsTypeDecl = node.typeParameters.params[0];
  21720. }
  21721. if (!isWithDefaults && declId && declId.type === "ObjectPattern") {
  21722. processPropsDestructure(ctx, declId);
  21723. }
  21724. ctx.propsCall = node;
  21725. ctx.propsDecl = declId;
  21726. return true;
  21727. }
  21728. function processWithDefaults(ctx, node, declId) {
  21729. if (!isCallOf(node, WITH_DEFAULTS)) {
  21730. return false;
  21731. }
  21732. if (!processDefineProps(
  21733. ctx,
  21734. node.arguments[0],
  21735. declId,
  21736. true
  21737. )) {
  21738. ctx.error(
  21739. `${WITH_DEFAULTS}' first argument must be a ${DEFINE_PROPS} call.`,
  21740. node.arguments[0] || node
  21741. );
  21742. }
  21743. if (ctx.propsRuntimeDecl) {
  21744. ctx.error(
  21745. `${WITH_DEFAULTS} can only be used with type-based ${DEFINE_PROPS} declaration.`,
  21746. node
  21747. );
  21748. }
  21749. if (declId && declId.type === "ObjectPattern") {
  21750. ctx.warn(
  21751. `${WITH_DEFAULTS}() is unnecessary when using destructure with ${DEFINE_PROPS}().
  21752. Reactive destructure will be disabled when using withDefaults().
  21753. Prefer using destructure default values, e.g. const { foo = 1 } = defineProps(...). `,
  21754. node.callee
  21755. );
  21756. }
  21757. ctx.propsRuntimeDefaults = node.arguments[1];
  21758. if (!ctx.propsRuntimeDefaults) {
  21759. ctx.error(`The 2nd argument of ${WITH_DEFAULTS} is required.`, node);
  21760. }
  21761. ctx.propsCall = node;
  21762. return true;
  21763. }
  21764. function genRuntimeProps(ctx) {
  21765. let propsDecls;
  21766. if (ctx.propsRuntimeDecl) {
  21767. propsDecls = ctx.getString(ctx.propsRuntimeDecl).trim();
  21768. if (ctx.propsDestructureDecl) {
  21769. const defaults = [];
  21770. for (const key in ctx.propsDestructuredBindings) {
  21771. const d = genDestructuredDefaultValue(ctx, key);
  21772. const finalKey = getEscapedPropName(key);
  21773. if (d)
  21774. defaults.push(
  21775. `${finalKey}: ${d.valueString}${d.needSkipFactory ? `, __skip_${finalKey}: true` : ``}`
  21776. );
  21777. }
  21778. if (defaults.length) {
  21779. propsDecls = `/*@__PURE__*/${ctx.helper(
  21780. `mergeDefaults`
  21781. )}(${propsDecls}, {
  21782. ${defaults.join(",\n ")}
  21783. })`;
  21784. }
  21785. }
  21786. } else if (ctx.propsTypeDecl) {
  21787. propsDecls = extractRuntimeProps(ctx);
  21788. }
  21789. const modelsDecls = genModelProps(ctx);
  21790. if (propsDecls && modelsDecls) {
  21791. return `/*@__PURE__*/${ctx.helper(
  21792. "mergeModels"
  21793. )}(${propsDecls}, ${modelsDecls})`;
  21794. } else {
  21795. return modelsDecls || propsDecls;
  21796. }
  21797. }
  21798. function extractRuntimeProps(ctx) {
  21799. const props = resolveRuntimePropsFromType(ctx, ctx.propsTypeDecl);
  21800. if (!props.length) {
  21801. return;
  21802. }
  21803. const propStrings = [];
  21804. const hasStaticDefaults = hasStaticWithDefaults(ctx);
  21805. for (const prop of props) {
  21806. propStrings.push(genRuntimePropFromType(ctx, prop, hasStaticDefaults));
  21807. if ("bindingMetadata" in ctx && !(prop.key in ctx.bindingMetadata)) {
  21808. ctx.bindingMetadata[prop.key] = "props";
  21809. }
  21810. }
  21811. let propsDecls = `{
  21812. ${propStrings.join(",\n ")}
  21813. }`;
  21814. if (ctx.propsRuntimeDefaults && !hasStaticDefaults) {
  21815. propsDecls = `/*@__PURE__*/${ctx.helper(
  21816. "mergeDefaults"
  21817. )}(${propsDecls}, ${ctx.getString(ctx.propsRuntimeDefaults)})`;
  21818. }
  21819. return propsDecls;
  21820. }
  21821. function resolveRuntimePropsFromType(ctx, node) {
  21822. const props = [];
  21823. const elements = resolveTypeElements(ctx, node);
  21824. for (const key in elements.props) {
  21825. const e = elements.props[key];
  21826. let type = inferRuntimeType(ctx, e);
  21827. let skipCheck = false;
  21828. if (type.includes(UNKNOWN_TYPE)) {
  21829. if (type.includes("Boolean") || type.includes("Function")) {
  21830. type = type.filter((t) => t !== UNKNOWN_TYPE);
  21831. skipCheck = true;
  21832. } else {
  21833. type = ["null"];
  21834. }
  21835. }
  21836. props.push({
  21837. key,
  21838. required: !e.optional,
  21839. type: type || [`null`],
  21840. skipCheck
  21841. });
  21842. }
  21843. return props;
  21844. }
  21845. function genRuntimePropFromType(ctx, { key, required, type, skipCheck }, hasStaticDefaults) {
  21846. let defaultString;
  21847. const destructured = genDestructuredDefaultValue(ctx, key, type);
  21848. if (destructured) {
  21849. defaultString = `default: ${destructured.valueString}${destructured.needSkipFactory ? `, skipFactory: true` : ``}`;
  21850. } else if (hasStaticDefaults) {
  21851. const prop = ctx.propsRuntimeDefaults.properties.find(
  21852. (node) => {
  21853. if (node.type === "SpreadElement") return false;
  21854. return resolveObjectKey(node.key, node.computed) === key;
  21855. }
  21856. );
  21857. if (prop) {
  21858. if (prop.type === "ObjectProperty") {
  21859. defaultString = `default: ${ctx.getString(prop.value)}`;
  21860. } else {
  21861. defaultString = `${prop.async ? "async " : ""}${prop.kind !== "method" ? `${prop.kind} ` : ""}default() ${ctx.getString(prop.body)}`;
  21862. }
  21863. }
  21864. }
  21865. const finalKey = getEscapedPropName(key);
  21866. if (!ctx.options.isProd) {
  21867. return `${finalKey}: { ${concatStrings([
  21868. `type: ${toRuntimeTypeString(type)}`,
  21869. `required: ${required}`,
  21870. skipCheck && "skipCheck: true",
  21871. defaultString
  21872. ])} }`;
  21873. } else if (type.some(
  21874. (el) => el === "Boolean" || (!hasStaticDefaults || defaultString) && el === "Function"
  21875. )) {
  21876. return `${finalKey}: { ${concatStrings([
  21877. `type: ${toRuntimeTypeString(type)}`,
  21878. defaultString
  21879. ])} }`;
  21880. } else {
  21881. if (ctx.isCE) {
  21882. if (defaultString) {
  21883. return `${finalKey}: ${`{ ${defaultString}, type: ${toRuntimeTypeString(
  21884. type
  21885. )} }`}`;
  21886. } else {
  21887. return `${finalKey}: {type: ${toRuntimeTypeString(type)}}`;
  21888. }
  21889. }
  21890. return `${finalKey}: ${defaultString ? `{ ${defaultString} }` : `{}`}`;
  21891. }
  21892. }
  21893. function hasStaticWithDefaults(ctx) {
  21894. return !!(ctx.propsRuntimeDefaults && ctx.propsRuntimeDefaults.type === "ObjectExpression" && ctx.propsRuntimeDefaults.properties.every(
  21895. (node) => node.type !== "SpreadElement" && (!node.computed || node.key.type.endsWith("Literal"))
  21896. ));
  21897. }
  21898. function genDestructuredDefaultValue(ctx, key, inferredType) {
  21899. const destructured = ctx.propsDestructuredBindings[key];
  21900. const defaultVal = destructured && destructured.default;
  21901. if (defaultVal) {
  21902. const value = ctx.getString(defaultVal);
  21903. const unwrapped = CompilerDOM.unwrapTSNode(defaultVal);
  21904. if (inferredType && inferredType.length && !inferredType.includes("null")) {
  21905. const valueType = inferValueType(unwrapped);
  21906. if (valueType && !inferredType.includes(valueType)) {
  21907. ctx.error(
  21908. `Default value of prop "${key}" does not match declared type.`,
  21909. unwrapped
  21910. );
  21911. }
  21912. }
  21913. const needSkipFactory = !inferredType && (CompilerDOM.isFunctionType(unwrapped) || unwrapped.type === "Identifier");
  21914. const needFactoryWrap = !needSkipFactory && !isLiteralNode(unwrapped) && !(inferredType == null ? void 0 : inferredType.includes("Function"));
  21915. return {
  21916. valueString: needFactoryWrap ? `() => (${value})` : value,
  21917. needSkipFactory
  21918. };
  21919. }
  21920. }
  21921. function inferValueType(node) {
  21922. switch (node.type) {
  21923. case "StringLiteral":
  21924. return "String";
  21925. case "NumericLiteral":
  21926. return "Number";
  21927. case "BooleanLiteral":
  21928. return "Boolean";
  21929. case "ObjectExpression":
  21930. return "Object";
  21931. case "ArrayExpression":
  21932. return "Array";
  21933. case "FunctionExpression":
  21934. case "ArrowFunctionExpression":
  21935. return "Function";
  21936. }
  21937. }
  21938. function processPropsDestructure(ctx, declId) {
  21939. if (ctx.options.propsDestructure === "error") {
  21940. ctx.error(`Props destructure is explicitly prohibited via config.`, declId);
  21941. } else if (ctx.options.propsDestructure === false) {
  21942. return;
  21943. }
  21944. ctx.propsDestructureDecl = declId;
  21945. const registerBinding = (key, local, defaultValue) => {
  21946. ctx.propsDestructuredBindings[key] = { local, default: defaultValue };
  21947. if (local !== key) {
  21948. ctx.bindingMetadata[local] = "props-aliased";
  21949. (ctx.bindingMetadata.__propsAliases || (ctx.bindingMetadata.__propsAliases = {}))[local] = key;
  21950. }
  21951. };
  21952. for (const prop of declId.properties) {
  21953. if (prop.type === "ObjectProperty") {
  21954. const propKey = resolveObjectKey(prop.key, prop.computed);
  21955. if (!propKey) {
  21956. ctx.error(
  21957. `${DEFINE_PROPS}() destructure cannot use computed key.`,
  21958. prop.key
  21959. );
  21960. }
  21961. if (prop.value.type === "AssignmentPattern") {
  21962. const { left, right } = prop.value;
  21963. if (left.type !== "Identifier") {
  21964. ctx.error(
  21965. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  21966. left
  21967. );
  21968. }
  21969. registerBinding(propKey, left.name, right);
  21970. } else if (prop.value.type === "Identifier") {
  21971. registerBinding(propKey, prop.value.name);
  21972. } else {
  21973. ctx.error(
  21974. `${DEFINE_PROPS}() destructure does not support nested patterns.`,
  21975. prop.value
  21976. );
  21977. }
  21978. } else {
  21979. ctx.propsDestructureRestId = prop.argument.name;
  21980. ctx.bindingMetadata[ctx.propsDestructureRestId] = "setup-reactive-const";
  21981. }
  21982. }
  21983. }
  21984. function transformDestructuredProps(ctx, vueImportAliases) {
  21985. if (ctx.options.propsDestructure === false) {
  21986. return;
  21987. }
  21988. const rootScope = /* @__PURE__ */ Object.create(null);
  21989. const scopeStack = [rootScope];
  21990. let currentScope = rootScope;
  21991. const excludedIds = /* @__PURE__ */ new WeakSet();
  21992. const parentStack = [];
  21993. const propsLocalToPublicMap = /* @__PURE__ */ Object.create(null);
  21994. for (const key in ctx.propsDestructuredBindings) {
  21995. const { local } = ctx.propsDestructuredBindings[key];
  21996. rootScope[local] = true;
  21997. propsLocalToPublicMap[local] = key;
  21998. }
  21999. function pushScope() {
  22000. scopeStack.push(currentScope = Object.create(currentScope));
  22001. }
  22002. function popScope() {
  22003. scopeStack.pop();
  22004. currentScope = scopeStack[scopeStack.length - 1] || null;
  22005. }
  22006. function registerLocalBinding(id) {
  22007. excludedIds.add(id);
  22008. if (currentScope) {
  22009. currentScope[id.name] = false;
  22010. } else {
  22011. ctx.error(
  22012. "registerBinding called without active scope, something is wrong.",
  22013. id
  22014. );
  22015. }
  22016. }
  22017. function walkScope(node, isRoot = false) {
  22018. for (const stmt of node.body) {
  22019. if (stmt.type === "VariableDeclaration") {
  22020. walkVariableDeclaration(stmt, isRoot);
  22021. } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
  22022. if (stmt.declare || !stmt.id) continue;
  22023. registerLocalBinding(stmt.id);
  22024. } else if ((stmt.type === "ForOfStatement" || stmt.type === "ForInStatement") && stmt.left.type === "VariableDeclaration") {
  22025. walkVariableDeclaration(stmt.left);
  22026. } else if (stmt.type === "ExportNamedDeclaration" && stmt.declaration && stmt.declaration.type === "VariableDeclaration") {
  22027. walkVariableDeclaration(stmt.declaration, isRoot);
  22028. } else if (stmt.type === "LabeledStatement" && stmt.body.type === "VariableDeclaration") {
  22029. walkVariableDeclaration(stmt.body, isRoot);
  22030. }
  22031. }
  22032. }
  22033. function walkVariableDeclaration(stmt, isRoot = false) {
  22034. if (stmt.declare) {
  22035. return;
  22036. }
  22037. for (const decl of stmt.declarations) {
  22038. const isDefineProps = isRoot && decl.init && isCallOf(CompilerDOM.unwrapTSNode(decl.init), "defineProps");
  22039. for (const id of CompilerDOM.extractIdentifiers(decl.id)) {
  22040. if (isDefineProps) {
  22041. excludedIds.add(id);
  22042. } else {
  22043. registerLocalBinding(id);
  22044. }
  22045. }
  22046. }
  22047. }
  22048. function rewriteId(id, parent, parentStack2) {
  22049. if (parent.type === "AssignmentExpression" && id === parent.left || parent.type === "UpdateExpression") {
  22050. ctx.error(`Cannot assign to destructured props as they are readonly.`, id);
  22051. }
  22052. if (CompilerDOM.isStaticProperty(parent) && parent.shorthand) {
  22053. if (!parent.inPattern || CompilerDOM.isInDestructureAssignment(parent, parentStack2)) {
  22054. ctx.s.appendLeft(
  22055. id.end + ctx.startOffset,
  22056. `: ${shared.genPropsAccessExp(propsLocalToPublicMap[id.name])}`
  22057. );
  22058. }
  22059. } else {
  22060. ctx.s.overwrite(
  22061. id.start + ctx.startOffset,
  22062. id.end + ctx.startOffset,
  22063. shared.genPropsAccessExp(propsLocalToPublicMap[id.name])
  22064. );
  22065. }
  22066. }
  22067. function checkUsage(node, method, alias = method) {
  22068. if (isCallOf(node, alias)) {
  22069. const arg = CompilerDOM.unwrapTSNode(node.arguments[0]);
  22070. if (arg.type === "Identifier" && currentScope[arg.name]) {
  22071. ctx.error(
  22072. `"${arg.name}" is a destructured prop and should not be passed directly to ${method}(). Pass a getter () => ${arg.name} instead.`,
  22073. arg
  22074. );
  22075. }
  22076. }
  22077. }
  22078. const ast = ctx.scriptSetupAst;
  22079. walkScope(ast, true);
  22080. estreeWalker.walk(ast, {
  22081. enter(node, parent) {
  22082. parent && parentStack.push(parent);
  22083. if (parent && parent.type.startsWith("TS") && !CompilerDOM.TS_NODE_TYPES.includes(parent.type)) {
  22084. return this.skip();
  22085. }
  22086. checkUsage(node, "watch", vueImportAliases.watch);
  22087. checkUsage(node, "toRef", vueImportAliases.toRef);
  22088. if (CompilerDOM.isFunctionType(node)) {
  22089. pushScope();
  22090. CompilerDOM.walkFunctionParams(node, registerLocalBinding);
  22091. if (node.body.type === "BlockStatement") {
  22092. walkScope(node.body);
  22093. }
  22094. return;
  22095. }
  22096. if (node.type === "CatchClause") {
  22097. pushScope();
  22098. if (node.param && node.param.type === "Identifier") {
  22099. registerLocalBinding(node.param);
  22100. }
  22101. walkScope(node.body);
  22102. return;
  22103. }
  22104. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent)) {
  22105. pushScope();
  22106. walkScope(node);
  22107. return;
  22108. }
  22109. if (node.type === "Identifier") {
  22110. if (CompilerDOM.isReferencedIdentifier(node, parent, parentStack) && !excludedIds.has(node)) {
  22111. if (currentScope[node.name]) {
  22112. rewriteId(node, parent, parentStack);
  22113. }
  22114. }
  22115. }
  22116. },
  22117. leave(node, parent) {
  22118. parent && parentStack.pop();
  22119. if (node.type === "BlockStatement" && !CompilerDOM.isFunctionType(parent) || CompilerDOM.isFunctionType(node) || node.type === "CatchClause") {
  22120. popScope();
  22121. }
  22122. }
  22123. });
  22124. }
  22125. const DEFINE_EMITS = "defineEmits";
  22126. function processDefineEmits(ctx, node, declId) {
  22127. if (!isCallOf(node, DEFINE_EMITS)) {
  22128. return false;
  22129. }
  22130. if (ctx.hasDefineEmitCall) {
  22131. ctx.error(`duplicate ${DEFINE_EMITS}() call`, node);
  22132. }
  22133. ctx.hasDefineEmitCall = true;
  22134. ctx.emitsRuntimeDecl = node.arguments[0];
  22135. if (node.typeParameters) {
  22136. if (ctx.emitsRuntimeDecl) {
  22137. ctx.error(
  22138. `${DEFINE_EMITS}() cannot accept both type and non-type arguments at the same time. Use one or the other.`,
  22139. node
  22140. );
  22141. }
  22142. ctx.emitsTypeDecl = node.typeParameters.params[0];
  22143. }
  22144. ctx.emitDecl = declId;
  22145. return true;
  22146. }
  22147. function genRuntimeEmits(ctx) {
  22148. let emitsDecl = "";
  22149. if (ctx.emitsRuntimeDecl) {
  22150. emitsDecl = ctx.getString(ctx.emitsRuntimeDecl).trim();
  22151. } else if (ctx.emitsTypeDecl) {
  22152. const typeDeclaredEmits = extractRuntimeEmits(ctx);
  22153. emitsDecl = typeDeclaredEmits.size ? `[${Array.from(typeDeclaredEmits).map((k) => JSON.stringify(k)).join(", ")}]` : ``;
  22154. }
  22155. if (ctx.hasDefineModelCall) {
  22156. let modelEmitsDecl = `[${Object.keys(ctx.modelDecls).map((n) => JSON.stringify(`update:${n}`)).join(", ")}]`;
  22157. emitsDecl = emitsDecl ? `/*@__PURE__*/${ctx.helper(
  22158. "mergeModels"
  22159. )}(${emitsDecl}, ${modelEmitsDecl})` : modelEmitsDecl;
  22160. }
  22161. return emitsDecl;
  22162. }
  22163. function extractRuntimeEmits(ctx) {
  22164. const emits = /* @__PURE__ */ new Set();
  22165. const node = ctx.emitsTypeDecl;
  22166. if (node.type === "TSFunctionType") {
  22167. extractEventNames(ctx, node.parameters[0], emits);
  22168. return emits;
  22169. }
  22170. const { props, calls } = resolveTypeElements(ctx, node);
  22171. let hasProperty = false;
  22172. for (const key in props) {
  22173. emits.add(key);
  22174. hasProperty = true;
  22175. }
  22176. if (calls) {
  22177. if (hasProperty) {
  22178. ctx.error(
  22179. `defineEmits() type cannot mixed call signature and property syntax.`,
  22180. node
  22181. );
  22182. }
  22183. for (const call of calls) {
  22184. extractEventNames(ctx, call.parameters[0], emits);
  22185. }
  22186. }
  22187. return emits;
  22188. }
  22189. function extractEventNames(ctx, eventName, emits) {
  22190. if (eventName.type === "Identifier" && eventName.typeAnnotation && eventName.typeAnnotation.type === "TSTypeAnnotation") {
  22191. const types = resolveUnionType(ctx, eventName.typeAnnotation.typeAnnotation);
  22192. for (const type of types) {
  22193. if (type.type === "TSLiteralType") {
  22194. if (type.literal.type !== "UnaryExpression" && type.literal.type !== "TemplateLiteral") {
  22195. emits.add(String(type.literal.value));
  22196. }
  22197. }
  22198. }
  22199. }
  22200. }
  22201. const DEFINE_EXPOSE = "defineExpose";
  22202. function processDefineExpose(ctx, node) {
  22203. if (isCallOf(node, DEFINE_EXPOSE)) {
  22204. if (ctx.hasDefineExposeCall) {
  22205. ctx.error(`duplicate ${DEFINE_EXPOSE}() call`, node);
  22206. }
  22207. ctx.hasDefineExposeCall = true;
  22208. return true;
  22209. }
  22210. return false;
  22211. }
  22212. const DEFINE_SLOTS = "defineSlots";
  22213. function processDefineSlots(ctx, node, declId) {
  22214. if (!isCallOf(node, DEFINE_SLOTS)) {
  22215. return false;
  22216. }
  22217. if (ctx.hasDefineSlotsCall) {
  22218. ctx.error(`duplicate ${DEFINE_SLOTS}() call`, node);
  22219. }
  22220. ctx.hasDefineSlotsCall = true;
  22221. if (node.arguments.length > 0) {
  22222. ctx.error(`${DEFINE_SLOTS}() cannot accept arguments`, node);
  22223. }
  22224. if (declId) {
  22225. ctx.s.overwrite(
  22226. ctx.startOffset + node.start,
  22227. ctx.startOffset + node.end,
  22228. `${ctx.helper("useSlots")}()`
  22229. );
  22230. }
  22231. return true;
  22232. }
  22233. const DEFINE_OPTIONS = "defineOptions";
  22234. function processDefineOptions(ctx, node) {
  22235. if (!isCallOf(node, DEFINE_OPTIONS)) {
  22236. return false;
  22237. }
  22238. if (ctx.hasDefineOptionsCall) {
  22239. ctx.error(`duplicate ${DEFINE_OPTIONS}() call`, node);
  22240. }
  22241. if (node.typeParameters) {
  22242. ctx.error(`${DEFINE_OPTIONS}() cannot accept type arguments`, node);
  22243. }
  22244. if (!node.arguments[0]) return true;
  22245. ctx.hasDefineOptionsCall = true;
  22246. ctx.optionsRuntimeDecl = CompilerDOM.unwrapTSNode(node.arguments[0]);
  22247. let propsOption = void 0;
  22248. let emitsOption = void 0;
  22249. let exposeOption = void 0;
  22250. let slotsOption = void 0;
  22251. if (ctx.optionsRuntimeDecl.type === "ObjectExpression") {
  22252. for (const prop of ctx.optionsRuntimeDecl.properties) {
  22253. if ((prop.type === "ObjectProperty" || prop.type === "ObjectMethod") && prop.key.type === "Identifier") {
  22254. switch (prop.key.name) {
  22255. case "props":
  22256. propsOption = prop;
  22257. break;
  22258. case "emits":
  22259. emitsOption = prop;
  22260. break;
  22261. case "expose":
  22262. exposeOption = prop;
  22263. break;
  22264. case "slots":
  22265. slotsOption = prop;
  22266. break;
  22267. }
  22268. }
  22269. }
  22270. }
  22271. if (propsOption) {
  22272. ctx.error(
  22273. `${DEFINE_OPTIONS}() cannot be used to declare props. Use ${DEFINE_PROPS}() instead.`,
  22274. propsOption
  22275. );
  22276. }
  22277. if (emitsOption) {
  22278. ctx.error(
  22279. `${DEFINE_OPTIONS}() cannot be used to declare emits. Use ${DEFINE_EMITS}() instead.`,
  22280. emitsOption
  22281. );
  22282. }
  22283. if (exposeOption) {
  22284. ctx.error(
  22285. `${DEFINE_OPTIONS}() cannot be used to declare expose. Use ${DEFINE_EXPOSE}() instead.`,
  22286. exposeOption
  22287. );
  22288. }
  22289. if (slotsOption) {
  22290. ctx.error(
  22291. `${DEFINE_OPTIONS}() cannot be used to declare slots. Use ${DEFINE_SLOTS}() instead.`,
  22292. slotsOption
  22293. );
  22294. }
  22295. return true;
  22296. }
  22297. function processAwait(ctx, node, needSemi, isStatement) {
  22298. const argumentStart = node.argument.extra && node.argument.extra.parenthesized ? node.argument.extra.parenStart : node.argument.start;
  22299. const startOffset = ctx.startOffset;
  22300. const argumentStr = ctx.descriptor.source.slice(
  22301. argumentStart + startOffset,
  22302. node.argument.end + startOffset
  22303. );
  22304. const containsNestedAwait = /\bawait\b/.test(argumentStr);
  22305. ctx.s.overwrite(
  22306. node.start + startOffset,
  22307. argumentStart + startOffset,
  22308. `${needSemi ? `;` : ``}(
  22309. ([__temp,__restore] = ${ctx.helper(
  22310. `withAsyncContext`
  22311. )}(${containsNestedAwait ? `async ` : ``}() => `
  22312. );
  22313. ctx.s.appendLeft(
  22314. node.end + startOffset,
  22315. `)),
  22316. ${isStatement ? `` : `__temp = `}await __temp,
  22317. __restore()${isStatement ? `` : `,
  22318. __temp`}
  22319. )`
  22320. );
  22321. }
  22322. const MACROS = [
  22323. DEFINE_PROPS,
  22324. DEFINE_EMITS,
  22325. DEFINE_EXPOSE,
  22326. DEFINE_OPTIONS,
  22327. DEFINE_SLOTS,
  22328. DEFINE_MODEL,
  22329. WITH_DEFAULTS
  22330. ];
  22331. function compileScript(sfc, options) {
  22332. var _a, _b, _c;
  22333. if (!options.id) {
  22334. warnOnce(
  22335. `compileScript now requires passing the \`id\` option.
  22336. Upgrade your vite or vue-loader version for compatibility with the latest experimental proposals.`
  22337. );
  22338. }
  22339. const ctx = new ScriptCompileContext(sfc, options);
  22340. const { script, scriptSetup, source, filename } = sfc;
  22341. const hoistStatic = options.hoistStatic !== false && !script;
  22342. const scopeId = options.id ? options.id.replace(/^data-v-/, "") : "";
  22343. const scriptLang = script && script.lang;
  22344. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  22345. if (!scriptSetup) {
  22346. if (!script) {
  22347. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
  22348. }
  22349. return processNormalScript(ctx, scopeId);
  22350. }
  22351. if (script && scriptLang !== scriptSetupLang) {
  22352. throw new Error(
  22353. `[@vue/compiler-sfc] <script> and <script setup> must have the same language type.`
  22354. );
  22355. }
  22356. if (scriptSetupLang && !ctx.isJS && !ctx.isTS) {
  22357. return scriptSetup;
  22358. }
  22359. const scriptBindings = /* @__PURE__ */ Object.create(null);
  22360. const setupBindings = /* @__PURE__ */ Object.create(null);
  22361. let defaultExport;
  22362. let hasAwait = false;
  22363. let hasInlinedSsrRenderFn = false;
  22364. const startOffset = ctx.startOffset;
  22365. const endOffset = ctx.endOffset;
  22366. const scriptStartOffset = script && script.loc.start.offset;
  22367. const scriptEndOffset = script && script.loc.end.offset;
  22368. function hoistNode(node) {
  22369. const start = node.start + startOffset;
  22370. let end = node.end + startOffset;
  22371. if (node.trailingComments && node.trailingComments.length > 0) {
  22372. const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
  22373. end = lastCommentNode.end + startOffset;
  22374. }
  22375. while (end <= source.length) {
  22376. if (!/\s/.test(source.charAt(end))) {
  22377. break;
  22378. }
  22379. end++;
  22380. }
  22381. ctx.s.move(start, end, 0);
  22382. }
  22383. function registerUserImport(source2, local, imported, isType, isFromSetup, needTemplateUsageCheck) {
  22384. let isUsedInTemplate = needTemplateUsageCheck;
  22385. if (needTemplateUsageCheck && ctx.isTS && sfc.template && !sfc.template.src && !sfc.template.lang) {
  22386. isUsedInTemplate = isImportUsed(local, sfc);
  22387. }
  22388. ctx.userImports[local] = {
  22389. isType,
  22390. imported,
  22391. local,
  22392. source: source2,
  22393. isFromSetup,
  22394. isUsedInTemplate
  22395. };
  22396. }
  22397. function checkInvalidScopeReference(node, method) {
  22398. if (!node) return;
  22399. CompilerDOM.walkIdentifiers(node, (id) => {
  22400. const binding = setupBindings[id.name];
  22401. if (binding && binding !== "literal-const") {
  22402. ctx.error(
  22403. `\`${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.`,
  22404. id
  22405. );
  22406. }
  22407. });
  22408. }
  22409. const scriptAst = ctx.scriptAst;
  22410. const scriptSetupAst = ctx.scriptSetupAst;
  22411. if (scriptAst) {
  22412. for (const node of scriptAst.body) {
  22413. if (node.type === "ImportDeclaration") {
  22414. for (const specifier of node.specifiers) {
  22415. const imported = getImportedName(specifier);
  22416. registerUserImport(
  22417. node.source.value,
  22418. specifier.local.name,
  22419. imported,
  22420. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  22421. false,
  22422. !options.inlineTemplate
  22423. );
  22424. }
  22425. }
  22426. }
  22427. }
  22428. for (const node of scriptSetupAst.body) {
  22429. if (node.type === "ImportDeclaration") {
  22430. hoistNode(node);
  22431. let removed = 0;
  22432. const removeSpecifier = (i) => {
  22433. const removeLeft = i > removed;
  22434. removed++;
  22435. const current = node.specifiers[i];
  22436. const next = node.specifiers[i + 1];
  22437. ctx.s.remove(
  22438. removeLeft ? node.specifiers[i - 1].end + startOffset : current.start + startOffset,
  22439. next && !removeLeft ? next.start + startOffset : current.end + startOffset
  22440. );
  22441. };
  22442. for (let i = 0; i < node.specifiers.length; i++) {
  22443. const specifier = node.specifiers[i];
  22444. const local = specifier.local.name;
  22445. const imported = getImportedName(specifier);
  22446. const source2 = node.source.value;
  22447. const existing = ctx.userImports[local];
  22448. if (source2 === "vue" && MACROS.includes(imported)) {
  22449. if (local === imported) {
  22450. warnOnce(
  22451. `\`${imported}\` is a compiler macro and no longer needs to be imported.`
  22452. );
  22453. } else {
  22454. ctx.error(
  22455. `\`${imported}\` is a compiler macro and cannot be aliased to a different name.`,
  22456. specifier
  22457. );
  22458. }
  22459. removeSpecifier(i);
  22460. } else if (existing) {
  22461. if (existing.source === source2 && existing.imported === imported) {
  22462. removeSpecifier(i);
  22463. } else {
  22464. ctx.error(
  22465. `different imports aliased to same local name.`,
  22466. specifier
  22467. );
  22468. }
  22469. } else {
  22470. registerUserImport(
  22471. source2,
  22472. local,
  22473. imported,
  22474. node.importKind === "type" || specifier.type === "ImportSpecifier" && specifier.importKind === "type",
  22475. true,
  22476. !options.inlineTemplate
  22477. );
  22478. }
  22479. }
  22480. if (node.specifiers.length && removed === node.specifiers.length) {
  22481. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  22482. }
  22483. }
  22484. }
  22485. const vueImportAliases = {};
  22486. for (const key in ctx.userImports) {
  22487. const { source: source2, imported, local } = ctx.userImports[key];
  22488. if (source2 === "vue") vueImportAliases[imported] = local;
  22489. }
  22490. if (script && scriptAst) {
  22491. for (const node of scriptAst.body) {
  22492. if (node.type === "ExportDefaultDeclaration") {
  22493. defaultExport = node;
  22494. let optionProperties;
  22495. if (defaultExport.declaration.type === "ObjectExpression") {
  22496. optionProperties = defaultExport.declaration.properties;
  22497. } else if (defaultExport.declaration.type === "CallExpression" && defaultExport.declaration.arguments[0] && defaultExport.declaration.arguments[0].type === "ObjectExpression") {
  22498. optionProperties = defaultExport.declaration.arguments[0].properties;
  22499. }
  22500. if (optionProperties) {
  22501. for (const p of optionProperties) {
  22502. if (p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name") {
  22503. ctx.hasDefaultExportName = true;
  22504. }
  22505. if ((p.type === "ObjectMethod" || p.type === "ObjectProperty") && p.key.type === "Identifier" && p.key.name === "render") {
  22506. ctx.hasDefaultExportRender = true;
  22507. }
  22508. }
  22509. }
  22510. const start = node.start + scriptStartOffset;
  22511. const end = node.declaration.start + scriptStartOffset;
  22512. ctx.s.overwrite(start, end, `const ${normalScriptDefaultVar} = `);
  22513. } else if (node.type === "ExportNamedDeclaration") {
  22514. const defaultSpecifier = node.specifiers.find(
  22515. (s) => s.exported.type === "Identifier" && s.exported.name === "default"
  22516. );
  22517. if (defaultSpecifier) {
  22518. defaultExport = node;
  22519. if (node.specifiers.length > 1) {
  22520. ctx.s.remove(
  22521. defaultSpecifier.start + scriptStartOffset,
  22522. defaultSpecifier.end + scriptStartOffset
  22523. );
  22524. } else {
  22525. ctx.s.remove(
  22526. node.start + scriptStartOffset,
  22527. node.end + scriptStartOffset
  22528. );
  22529. }
  22530. if (node.source) {
  22531. ctx.s.prepend(
  22532. `import { ${defaultSpecifier.local.name} as ${normalScriptDefaultVar} } from '${node.source.value}'
  22533. `
  22534. );
  22535. } else {
  22536. ctx.s.appendLeft(
  22537. scriptEndOffset,
  22538. `
  22539. const ${normalScriptDefaultVar} = ${defaultSpecifier.local.name}
  22540. `
  22541. );
  22542. }
  22543. }
  22544. if (node.declaration) {
  22545. walkDeclaration(
  22546. "script",
  22547. node.declaration,
  22548. scriptBindings,
  22549. vueImportAliases,
  22550. hoistStatic
  22551. );
  22552. }
  22553. } else if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  22554. walkDeclaration(
  22555. "script",
  22556. node,
  22557. scriptBindings,
  22558. vueImportAliases,
  22559. hoistStatic
  22560. );
  22561. }
  22562. }
  22563. if (scriptStartOffset > startOffset) {
  22564. if (!/\n$/.test(script.content.trim())) {
  22565. ctx.s.appendLeft(scriptEndOffset, `
  22566. `);
  22567. }
  22568. ctx.s.move(scriptStartOffset, scriptEndOffset, 0);
  22569. }
  22570. }
  22571. for (const node of scriptSetupAst.body) {
  22572. if (node.type === "ExpressionStatement") {
  22573. const expr = CompilerDOM.unwrapTSNode(node.expression);
  22574. if (processDefineProps(ctx, expr) || processDefineEmits(ctx, expr) || processDefineOptions(ctx, expr) || processDefineSlots(ctx, expr)) {
  22575. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  22576. } else if (processDefineExpose(ctx, expr)) {
  22577. const callee = expr.callee;
  22578. ctx.s.overwrite(
  22579. callee.start + startOffset,
  22580. callee.end + startOffset,
  22581. "__expose"
  22582. );
  22583. } else {
  22584. processDefineModel(ctx, expr);
  22585. }
  22586. }
  22587. if (node.type === "VariableDeclaration" && !node.declare) {
  22588. const total = node.declarations.length;
  22589. let left = total;
  22590. let lastNonRemoved;
  22591. for (let i = 0; i < total; i++) {
  22592. const decl = node.declarations[i];
  22593. const init = decl.init && CompilerDOM.unwrapTSNode(decl.init);
  22594. if (init) {
  22595. if (processDefineOptions(ctx, init)) {
  22596. ctx.error(
  22597. `${DEFINE_OPTIONS}() has no returning value, it cannot be assigned.`,
  22598. node
  22599. );
  22600. }
  22601. const isDefineProps = processDefineProps(ctx, init, decl.id);
  22602. if (ctx.propsDestructureRestId) {
  22603. setupBindings[ctx.propsDestructureRestId] = "setup-reactive-const";
  22604. }
  22605. const isDefineEmits = !isDefineProps && processDefineEmits(ctx, init, decl.id);
  22606. !isDefineEmits && (processDefineSlots(ctx, init, decl.id) || processDefineModel(ctx, init, decl.id));
  22607. if (isDefineProps && !ctx.propsDestructureRestId && ctx.propsDestructureDecl) {
  22608. if (left === 1) {
  22609. ctx.s.remove(node.start + startOffset, node.end + startOffset);
  22610. } else {
  22611. let start = decl.start + startOffset;
  22612. let end = decl.end + startOffset;
  22613. if (i === total - 1) {
  22614. start = node.declarations[lastNonRemoved].end + startOffset;
  22615. } else {
  22616. end = node.declarations[i + 1].start + startOffset;
  22617. }
  22618. ctx.s.remove(start, end);
  22619. left--;
  22620. }
  22621. } else if (isDefineEmits) {
  22622. ctx.s.overwrite(
  22623. startOffset + init.start,
  22624. startOffset + init.end,
  22625. "__emit"
  22626. );
  22627. } else {
  22628. lastNonRemoved = i;
  22629. }
  22630. }
  22631. }
  22632. }
  22633. let isAllLiteral = false;
  22634. if ((node.type === "VariableDeclaration" || node.type === "FunctionDeclaration" || node.type === "ClassDeclaration" || node.type === "TSEnumDeclaration") && !node.declare) {
  22635. isAllLiteral = walkDeclaration(
  22636. "scriptSetup",
  22637. node,
  22638. setupBindings,
  22639. vueImportAliases,
  22640. hoistStatic,
  22641. !!ctx.propsDestructureDecl
  22642. );
  22643. }
  22644. if (hoistStatic && isAllLiteral) {
  22645. hoistNode(node);
  22646. }
  22647. if (node.type === "VariableDeclaration" && !node.declare || node.type.endsWith("Statement")) {
  22648. const scope = [scriptSetupAst.body];
  22649. estreeWalker.walk(node, {
  22650. enter(child, parent) {
  22651. if (CompilerDOM.isFunctionType(child)) {
  22652. this.skip();
  22653. }
  22654. if (child.type === "BlockStatement") {
  22655. scope.push(child.body);
  22656. }
  22657. if (child.type === "AwaitExpression") {
  22658. hasAwait = true;
  22659. const currentScope = scope[scope.length - 1];
  22660. const needsSemi = currentScope.some((n, i) => {
  22661. return (scope.length === 1 || i > 0) && n.type === "ExpressionStatement" && n.start === child.start;
  22662. });
  22663. processAwait(
  22664. ctx,
  22665. child,
  22666. needsSemi,
  22667. parent.type === "ExpressionStatement"
  22668. );
  22669. }
  22670. },
  22671. exit(node2) {
  22672. if (node2.type === "BlockStatement") scope.pop();
  22673. }
  22674. });
  22675. }
  22676. if (node.type === "ExportNamedDeclaration" && node.exportKind !== "type" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration") {
  22677. ctx.error(
  22678. `<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.`,
  22679. node
  22680. );
  22681. }
  22682. if (ctx.isTS) {
  22683. if (node.type.startsWith("TS") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "VariableDeclaration" && node.declare) {
  22684. if (node.type !== "TSEnumDeclaration") {
  22685. hoistNode(node);
  22686. }
  22687. }
  22688. }
  22689. }
  22690. if (ctx.propsDestructureDecl) {
  22691. transformDestructuredProps(ctx, vueImportAliases);
  22692. }
  22693. checkInvalidScopeReference(ctx.propsRuntimeDecl, DEFINE_PROPS);
  22694. checkInvalidScopeReference(ctx.propsRuntimeDefaults, DEFINE_PROPS);
  22695. checkInvalidScopeReference(ctx.propsDestructureDecl, DEFINE_PROPS);
  22696. checkInvalidScopeReference(ctx.emitsRuntimeDecl, DEFINE_EMITS);
  22697. checkInvalidScopeReference(ctx.optionsRuntimeDecl, DEFINE_OPTIONS);
  22698. for (const { runtimeOptionNodes } of Object.values(ctx.modelDecls)) {
  22699. for (const node of runtimeOptionNodes) {
  22700. checkInvalidScopeReference(node, DEFINE_MODEL);
  22701. }
  22702. }
  22703. if (script) {
  22704. if (startOffset < scriptStartOffset) {
  22705. ctx.s.remove(0, startOffset);
  22706. ctx.s.remove(endOffset, scriptStartOffset);
  22707. ctx.s.remove(scriptEndOffset, source.length);
  22708. } else {
  22709. ctx.s.remove(0, scriptStartOffset);
  22710. ctx.s.remove(scriptEndOffset, startOffset);
  22711. ctx.s.remove(endOffset, source.length);
  22712. }
  22713. } else {
  22714. ctx.s.remove(0, startOffset);
  22715. ctx.s.remove(endOffset, source.length);
  22716. }
  22717. if (scriptAst) {
  22718. Object.assign(ctx.bindingMetadata, analyzeScriptBindings(scriptAst.body));
  22719. }
  22720. for (const [key, { isType, imported, source: source2 }] of Object.entries(
  22721. ctx.userImports
  22722. )) {
  22723. if (isType) continue;
  22724. ctx.bindingMetadata[key] = imported === "*" || imported === "default" && source2.endsWith(".vue") || source2 === "vue" ? "setup-const" : "setup-maybe-ref";
  22725. }
  22726. for (const key in scriptBindings) {
  22727. ctx.bindingMetadata[key] = scriptBindings[key];
  22728. }
  22729. for (const key in setupBindings) {
  22730. ctx.bindingMetadata[key] = setupBindings[key];
  22731. }
  22732. if (sfc.cssVars.length && // no need to do this when targeting SSR
  22733. !((_a = options.templateOptions) == null ? void 0 : _a.ssr)) {
  22734. ctx.helperImports.add(CSS_VARS_HELPER);
  22735. ctx.helperImports.add("unref");
  22736. ctx.s.prependLeft(
  22737. startOffset,
  22738. `
  22739. ${genCssVarsCode(
  22740. sfc.cssVars,
  22741. ctx.bindingMetadata,
  22742. scopeId,
  22743. !!options.isProd
  22744. )}
  22745. `
  22746. );
  22747. }
  22748. let args = `__props`;
  22749. if (ctx.propsTypeDecl) {
  22750. args += `: any`;
  22751. }
  22752. if (ctx.propsDecl) {
  22753. if (ctx.propsDestructureRestId) {
  22754. ctx.s.overwrite(
  22755. startOffset + ctx.propsCall.start,
  22756. startOffset + ctx.propsCall.end,
  22757. `${ctx.helper(`createPropsRestProxy`)}(__props, ${JSON.stringify(
  22758. Object.keys(ctx.propsDestructuredBindings)
  22759. )})`
  22760. );
  22761. ctx.s.overwrite(
  22762. startOffset + ctx.propsDestructureDecl.start,
  22763. startOffset + ctx.propsDestructureDecl.end,
  22764. ctx.propsDestructureRestId
  22765. );
  22766. } else if (!ctx.propsDestructureDecl) {
  22767. ctx.s.overwrite(
  22768. startOffset + ctx.propsCall.start,
  22769. startOffset + ctx.propsCall.end,
  22770. "__props"
  22771. );
  22772. }
  22773. }
  22774. if (hasAwait) {
  22775. const any = ctx.isTS ? `: any` : ``;
  22776. ctx.s.prependLeft(startOffset, `
  22777. let __temp${any}, __restore${any}
  22778. `);
  22779. }
  22780. const destructureElements = ctx.hasDefineExposeCall || !options.inlineTemplate ? [`expose: __expose`] : [];
  22781. if (ctx.emitDecl) {
  22782. destructureElements.push(`emit: __emit`);
  22783. }
  22784. if (destructureElements.length) {
  22785. args += `, { ${destructureElements.join(", ")} }`;
  22786. }
  22787. let templateMap;
  22788. let returned;
  22789. if (!options.inlineTemplate || !sfc.template && ctx.hasDefaultExportRender) {
  22790. const allBindings = {
  22791. ...scriptBindings,
  22792. ...setupBindings
  22793. };
  22794. for (const key in ctx.userImports) {
  22795. if (!ctx.userImports[key].isType && ctx.userImports[key].isUsedInTemplate) {
  22796. allBindings[key] = true;
  22797. }
  22798. }
  22799. returned = `{ `;
  22800. for (const key in allBindings) {
  22801. if (allBindings[key] === true && ctx.userImports[key].source !== "vue" && !ctx.userImports[key].source.endsWith(".vue")) {
  22802. returned += `get ${key}() { return ${key} }, `;
  22803. } else if (ctx.bindingMetadata[key] === "setup-let") {
  22804. const setArg = key === "v" ? `_v` : `v`;
  22805. returned += `get ${key}() { return ${key} }, set ${key}(${setArg}) { ${key} = ${setArg} }, `;
  22806. } else {
  22807. returned += `${key}, `;
  22808. }
  22809. }
  22810. returned = returned.replace(/, $/, "") + ` }`;
  22811. } else {
  22812. if (sfc.template && !sfc.template.src) {
  22813. if (options.templateOptions && options.templateOptions.ssr) {
  22814. hasInlinedSsrRenderFn = true;
  22815. }
  22816. const { code, ast, preamble, tips, errors, map: map2 } = compileTemplate({
  22817. filename,
  22818. ast: sfc.template.ast,
  22819. source: sfc.template.content,
  22820. inMap: sfc.template.map,
  22821. ...options.templateOptions,
  22822. id: scopeId,
  22823. scoped: sfc.styles.some((s) => s.scoped),
  22824. isProd: options.isProd,
  22825. ssrCssVars: sfc.cssVars,
  22826. compilerOptions: {
  22827. ...options.templateOptions && options.templateOptions.compilerOptions,
  22828. inline: true,
  22829. isTS: ctx.isTS,
  22830. bindingMetadata: ctx.bindingMetadata
  22831. }
  22832. });
  22833. templateMap = map2;
  22834. if (tips.length) {
  22835. tips.forEach(warnOnce);
  22836. }
  22837. const err = errors[0];
  22838. if (typeof err === "string") {
  22839. throw new Error(err);
  22840. } else if (err) {
  22841. if (err.loc) {
  22842. err.message += `
  22843. ` + sfc.filename + "\n" + shared.generateCodeFrame(
  22844. source,
  22845. err.loc.start.offset,
  22846. err.loc.end.offset
  22847. ) + `
  22848. `;
  22849. }
  22850. throw err;
  22851. }
  22852. if (preamble) {
  22853. ctx.s.prepend(preamble);
  22854. }
  22855. if (ast && ast.helpers.has(CompilerDOM.UNREF)) {
  22856. ctx.helperImports.delete("unref");
  22857. }
  22858. returned = code;
  22859. } else {
  22860. returned = `() => {}`;
  22861. }
  22862. }
  22863. if (!options.inlineTemplate && true) {
  22864. ctx.s.appendRight(
  22865. endOffset,
  22866. `
  22867. const __returned__ = ${returned}
  22868. Object.defineProperty(__returned__, '__isScriptSetup', { enumerable: false, value: true })
  22869. return __returned__
  22870. }
  22871. `
  22872. );
  22873. } else {
  22874. ctx.s.appendRight(endOffset, `
  22875. return ${returned}
  22876. }
  22877. `);
  22878. }
  22879. const genDefaultAs = options.genDefaultAs ? `const ${options.genDefaultAs} =` : `export default`;
  22880. let runtimeOptions = ``;
  22881. if (!ctx.hasDefaultExportName && filename && filename !== DEFAULT_FILENAME) {
  22882. const match = filename.match(/([^/\\]+)\.\w+$/);
  22883. if (match) {
  22884. runtimeOptions += `
  22885. __name: '${match[1]}',`;
  22886. }
  22887. }
  22888. if (hasInlinedSsrRenderFn) {
  22889. runtimeOptions += `
  22890. __ssrInlineRender: true,`;
  22891. }
  22892. const propsDecl = genRuntimeProps(ctx);
  22893. if (propsDecl) runtimeOptions += `
  22894. props: ${propsDecl},`;
  22895. const emitsDecl = genRuntimeEmits(ctx);
  22896. if (emitsDecl) runtimeOptions += `
  22897. emits: ${emitsDecl},`;
  22898. let definedOptions = "";
  22899. if (ctx.optionsRuntimeDecl) {
  22900. definedOptions = scriptSetup.content.slice(ctx.optionsRuntimeDecl.start, ctx.optionsRuntimeDecl.end).trim();
  22901. }
  22902. const exposeCall = ctx.hasDefineExposeCall || options.inlineTemplate ? `` : ` __expose();
  22903. `;
  22904. if (ctx.isTS) {
  22905. const def = (defaultExport ? `
  22906. ...${normalScriptDefaultVar},` : ``) + (definedOptions ? `
  22907. ...${definedOptions},` : "");
  22908. ctx.s.prependLeft(
  22909. startOffset,
  22910. `
  22911. ${genDefaultAs} /*@__PURE__*/${ctx.helper(
  22912. `defineComponent`
  22913. )}({${def}${runtimeOptions}
  22914. ${hasAwait ? `async ` : ``}setup(${args}) {
  22915. ${exposeCall}`
  22916. );
  22917. ctx.s.appendRight(endOffset, `})`);
  22918. } else {
  22919. if (defaultExport || definedOptions) {
  22920. ctx.s.prependLeft(
  22921. startOffset,
  22922. `
  22923. ${genDefaultAs} /*@__PURE__*/Object.assign(${defaultExport ? `${normalScriptDefaultVar}, ` : ""}${definedOptions ? `${definedOptions}, ` : ""}{${runtimeOptions}
  22924. ${hasAwait ? `async ` : ``}setup(${args}) {
  22925. ${exposeCall}`
  22926. );
  22927. ctx.s.appendRight(endOffset, `})`);
  22928. } else {
  22929. ctx.s.prependLeft(
  22930. startOffset,
  22931. `
  22932. ${genDefaultAs} {${runtimeOptions}
  22933. ${hasAwait ? `async ` : ``}setup(${args}) {
  22934. ${exposeCall}`
  22935. );
  22936. ctx.s.appendRight(endOffset, `}`);
  22937. }
  22938. }
  22939. if (ctx.helperImports.size > 0) {
  22940. const runtimeModuleName = (_c = (_b = options.templateOptions) == null ? void 0 : _b.compilerOptions) == null ? void 0 : _c.runtimeModuleName;
  22941. const importSrc = runtimeModuleName ? JSON.stringify(runtimeModuleName) : `'vue'`;
  22942. ctx.s.prepend(
  22943. `import { ${[...ctx.helperImports].map((h) => `${h} as _${h}`).join(", ")} } from ${importSrc}
  22944. `
  22945. );
  22946. }
  22947. const content = ctx.s.toString();
  22948. let map = options.sourceMap !== false ? ctx.s.generateMap({
  22949. source: filename,
  22950. hires: true,
  22951. includeContent: true
  22952. }) : void 0;
  22953. if (templateMap && map) {
  22954. const offset = content.indexOf(returned);
  22955. const templateLineOffset = content.slice(0, offset).split(/\r?\n/).length - 1;
  22956. map = mergeSourceMaps(map, templateMap, templateLineOffset);
  22957. }
  22958. return {
  22959. ...scriptSetup,
  22960. bindings: ctx.bindingMetadata,
  22961. imports: ctx.userImports,
  22962. content,
  22963. map,
  22964. scriptAst: scriptAst == null ? void 0 : scriptAst.body,
  22965. scriptSetupAst: scriptSetupAst == null ? void 0 : scriptSetupAst.body,
  22966. deps: ctx.deps ? [...ctx.deps] : void 0
  22967. };
  22968. }
  22969. function registerBinding(bindings, node, type) {
  22970. bindings[node.name] = type;
  22971. }
  22972. function walkDeclaration(from, node, bindings, userImportAliases, hoistStatic, isPropsDestructureEnabled = false) {
  22973. let isAllLiteral = false;
  22974. if (node.type === "VariableDeclaration") {
  22975. const isConst = node.kind === "const";
  22976. isAllLiteral = isConst && node.declarations.every(
  22977. (decl) => decl.id.type === "Identifier" && isStaticNode(decl.init)
  22978. );
  22979. for (const { id, init: _init } of node.declarations) {
  22980. const init = _init && CompilerDOM.unwrapTSNode(_init);
  22981. const isConstMacroCall = isConst && isCallOf(
  22982. init,
  22983. (c) => c === DEFINE_PROPS || c === DEFINE_EMITS || c === WITH_DEFAULTS || c === DEFINE_SLOTS
  22984. );
  22985. if (id.type === "Identifier") {
  22986. let bindingType;
  22987. const userReactiveBinding = userImportAliases["reactive"];
  22988. if ((hoistStatic || from === "script") && (isAllLiteral || isConst && isStaticNode(init))) {
  22989. bindingType = "literal-const";
  22990. } else if (isCallOf(init, userReactiveBinding)) {
  22991. bindingType = isConst ? "setup-reactive-const" : "setup-let";
  22992. } else if (
  22993. // if a declaration is a const literal, we can mark it so that
  22994. // the generated render fn code doesn't need to unref() it
  22995. isConstMacroCall || isConst && canNeverBeRef(init, userReactiveBinding)
  22996. ) {
  22997. bindingType = isCallOf(init, DEFINE_PROPS) ? "setup-reactive-const" : "setup-const";
  22998. } else if (isConst) {
  22999. if (isCallOf(
  23000. init,
  23001. (m) => m === userImportAliases["ref"] || m === userImportAliases["computed"] || m === userImportAliases["shallowRef"] || m === userImportAliases["customRef"] || m === userImportAliases["toRef"] || m === userImportAliases["useTemplateRef"] || m === DEFINE_MODEL
  23002. )) {
  23003. bindingType = "setup-ref";
  23004. } else {
  23005. bindingType = "setup-maybe-ref";
  23006. }
  23007. } else {
  23008. bindingType = "setup-let";
  23009. }
  23010. registerBinding(bindings, id, bindingType);
  23011. } else {
  23012. if (isCallOf(init, DEFINE_PROPS) && isPropsDestructureEnabled) {
  23013. continue;
  23014. }
  23015. if (id.type === "ObjectPattern") {
  23016. walkObjectPattern(id, bindings, isConst, isConstMacroCall);
  23017. } else if (id.type === "ArrayPattern") {
  23018. walkArrayPattern(id, bindings, isConst, isConstMacroCall);
  23019. }
  23020. }
  23021. }
  23022. } else if (node.type === "TSEnumDeclaration") {
  23023. isAllLiteral = node.members.every(
  23024. (member) => !member.initializer || isStaticNode(member.initializer)
  23025. );
  23026. bindings[node.id.name] = isAllLiteral ? "literal-const" : "setup-const";
  23027. } else if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
  23028. bindings[node.id.name] = "setup-const";
  23029. }
  23030. return isAllLiteral;
  23031. }
  23032. function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
  23033. for (const p of node.properties) {
  23034. if (p.type === "ObjectProperty") {
  23035. if (p.key.type === "Identifier" && p.key === p.value) {
  23036. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  23037. registerBinding(bindings, p.key, type);
  23038. } else {
  23039. walkPattern(p.value, bindings, isConst, isDefineCall);
  23040. }
  23041. } else {
  23042. const type = isConst ? "setup-const" : "setup-let";
  23043. registerBinding(bindings, p.argument, type);
  23044. }
  23045. }
  23046. }
  23047. function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
  23048. for (const e of node.elements) {
  23049. e && walkPattern(e, bindings, isConst, isDefineCall);
  23050. }
  23051. }
  23052. function walkPattern(node, bindings, isConst, isDefineCall = false) {
  23053. if (node.type === "Identifier") {
  23054. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  23055. registerBinding(bindings, node, type);
  23056. } else if (node.type === "RestElement") {
  23057. const type = isConst ? "setup-const" : "setup-let";
  23058. registerBinding(bindings, node.argument, type);
  23059. } else if (node.type === "ObjectPattern") {
  23060. walkObjectPattern(node, bindings, isConst);
  23061. } else if (node.type === "ArrayPattern") {
  23062. walkArrayPattern(node, bindings, isConst);
  23063. } else if (node.type === "AssignmentPattern") {
  23064. if (node.left.type === "Identifier") {
  23065. const type = isDefineCall ? "setup-const" : isConst ? "setup-maybe-ref" : "setup-let";
  23066. registerBinding(bindings, node.left, type);
  23067. } else {
  23068. walkPattern(node.left, bindings, isConst);
  23069. }
  23070. }
  23071. }
  23072. function canNeverBeRef(node, userReactiveImport) {
  23073. if (isCallOf(node, userReactiveImport)) {
  23074. return true;
  23075. }
  23076. switch (node.type) {
  23077. case "UnaryExpression":
  23078. case "BinaryExpression":
  23079. case "ArrayExpression":
  23080. case "ObjectExpression":
  23081. case "FunctionExpression":
  23082. case "ArrowFunctionExpression":
  23083. case "UpdateExpression":
  23084. case "ClassExpression":
  23085. case "TaggedTemplateExpression":
  23086. return true;
  23087. case "SequenceExpression":
  23088. return canNeverBeRef(
  23089. node.expressions[node.expressions.length - 1],
  23090. userReactiveImport
  23091. );
  23092. default:
  23093. if (isLiteralNode(node)) {
  23094. return true;
  23095. }
  23096. return false;
  23097. }
  23098. }
  23099. function isStaticNode(node) {
  23100. node = CompilerDOM.unwrapTSNode(node);
  23101. switch (node.type) {
  23102. case "UnaryExpression":
  23103. return isStaticNode(node.argument);
  23104. case "LogicalExpression":
  23105. // 1 > 2
  23106. case "BinaryExpression":
  23107. return isStaticNode(node.left) && isStaticNode(node.right);
  23108. case "ConditionalExpression": {
  23109. return isStaticNode(node.test) && isStaticNode(node.consequent) && isStaticNode(node.alternate);
  23110. }
  23111. case "SequenceExpression":
  23112. // (1, 2)
  23113. case "TemplateLiteral":
  23114. return node.expressions.every((expr) => isStaticNode(expr));
  23115. case "ParenthesizedExpression":
  23116. return isStaticNode(node.expression);
  23117. case "StringLiteral":
  23118. case "NumericLiteral":
  23119. case "BooleanLiteral":
  23120. case "NullLiteral":
  23121. case "BigIntLiteral":
  23122. return true;
  23123. }
  23124. return false;
  23125. }
  23126. function mergeSourceMaps(scriptMap, templateMap, templateLineOffset) {
  23127. const generator = new sourceMapJs.SourceMapGenerator();
  23128. const addMapping = (map, lineOffset = 0) => {
  23129. const consumer = new sourceMapJs.SourceMapConsumer(map);
  23130. consumer.sources.forEach((sourceFile) => {
  23131. generator._sources.add(sourceFile);
  23132. const sourceContent = consumer.sourceContentFor(sourceFile);
  23133. if (sourceContent != null) {
  23134. generator.setSourceContent(sourceFile, sourceContent);
  23135. }
  23136. });
  23137. consumer.eachMapping((m) => {
  23138. if (m.originalLine == null) return;
  23139. generator.addMapping({
  23140. generated: {
  23141. line: m.generatedLine + lineOffset,
  23142. column: m.generatedColumn
  23143. },
  23144. original: {
  23145. line: m.originalLine,
  23146. column: m.originalColumn
  23147. },
  23148. source: m.source,
  23149. name: m.name
  23150. });
  23151. });
  23152. };
  23153. addMapping(scriptMap);
  23154. addMapping(templateMap, templateLineOffset);
  23155. generator._sourceRoot = scriptMap.sourceRoot;
  23156. generator._file = scriptMap.file;
  23157. return generator.toJSON();
  23158. }
  23159. const version = "3.5.18";
  23160. const parseCache = parseCache$1;
  23161. const errorMessages = {
  23162. ...CompilerDOM.errorMessages,
  23163. ...CompilerDOM.DOMErrorMessages
  23164. };
  23165. const walk = estreeWalker.walk;
  23166. const shouldTransformRef = () => false;
  23167. exports.extractIdentifiers = compilerCore.extractIdentifiers;
  23168. exports.generateCodeFrame = compilerCore.generateCodeFrame;
  23169. exports.isInDestructureAssignment = compilerCore.isInDestructureAssignment;
  23170. exports.isStaticProperty = compilerCore.isStaticProperty;
  23171. exports.walkIdentifiers = compilerCore.walkIdentifiers;
  23172. exports.MagicString = MagicString;
  23173. exports.babelParse = parser$2.parse;
  23174. exports.compileScript = compileScript;
  23175. exports.compileStyle = compileStyle;
  23176. exports.compileStyleAsync = compileStyleAsync;
  23177. exports.compileTemplate = compileTemplate;
  23178. exports.errorMessages = errorMessages;
  23179. exports.extractRuntimeEmits = extractRuntimeEmits;
  23180. exports.extractRuntimeProps = extractRuntimeProps;
  23181. exports.inferRuntimeType = inferRuntimeType;
  23182. exports.invalidateTypeCache = invalidateTypeCache;
  23183. exports.parse = parse$1;
  23184. exports.parseCache = parseCache;
  23185. exports.registerTS = registerTS;
  23186. exports.resolveTypeElements = resolveTypeElements;
  23187. exports.rewriteDefault = rewriteDefault;
  23188. exports.rewriteDefaultAST = rewriteDefaultAST;
  23189. exports.shouldTransformRef = shouldTransformRef;
  23190. exports.version = version;
  23191. exports.walk = walk;